home *** CD-ROM | disk | FTP | other *** search
/ Magazyn Amiga 14 / MA_Cover_14.iso / source / c / pegase_src / coderc.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  1999-10-22  |  90.0 KB  |  3,202 lines

  1. /*
  2. **
  3. ** CoderC.cpp
  4. **
  5. ** $VER: CoderC.cpp 1.0 (05.06.99)
  6. **
  7. ** $Revision: 1.5 $
  8. ** $State: Exp $
  9. ** $Date: 1998/08/16 19:03:39 $
  10. **
  11. ** $Log: CoderC.cpp $
  12. ** Revision 1.5  1998/08/16 19:03:39  kakace
  13. ** Version Beta3+
  14. **
  15. ** Revision 1.4  1998/08/02 15:17:05  kakace
  16. ** Fonctionnement OK (Layer 1/2 + Stereo/JStereo)
  17. **
  18. ** Revision 1.3  1998/08/02 02:13:45  kakace
  19. ** Modes stereo Ok (?)
  20. **
  21. */
  22.  
  23.  
  24. //----------------------------------------------------------------------------------------------------
  25.  
  26. /// Includes
  27.  
  28. #ifndef  _INCLUDE_STDLIB_H
  29. #include <stdlib.h>
  30. #endif
  31.  
  32. #ifndef  _INCLUDE_MATH_H
  33. #include <math.h>
  34. #endif
  35.  
  36. #ifndef  _INCLUDE_IOSTREAM_H
  37. #include <iostream.h>
  38. #endif
  39.  
  40. #ifndef  CLIB_DOS_PROTOS_H
  41. #include <clib/dos_protos.h>
  42. #endif
  43.  
  44. #ifndef  _PEGASECOND_HPP
  45. #include "PegaseCond.hpp"
  46. #endif
  47.  
  48. #ifndef  _FILEINFOS_CLASS_HPP
  49. #include "FileInfosC.hpp"
  50. #endif
  51.  
  52. #ifndef  _INPUTSTREAM_CLASS_HPP
  53. #include "InputStreamC.hpp"
  54. #endif
  55.  
  56. #ifndef  _COMMON_HPP
  57. #include "common.hpp"
  58. #endif
  59.  
  60. #ifndef  _MEMORY_HPP
  61. #include "Memory.hpp"
  62. #endif
  63.  
  64. #ifndef  _CODER_CLASS_HPP
  65. #include "CoderC.hpp"
  66. #endif
  67.  
  68. #ifndef  _PSYCHO_CLASS_HPP
  69. #include "PsychoC.hpp"
  70. #endif
  71.  
  72. #ifndef  _ENCODERCONFIG_CLASS_HPP
  73. #include "EncoderConfigC.hpp"
  74. #endif
  75.  
  76. ///
  77.  
  78.  
  79. //----------------------------------------------------------------------------------------------------
  80. //====================================== Classe EncoderConfigC =======================================
  81. //----------------------------------------------------------------------------------------------------
  82.  
  83. /// EncoderConfigC::COPY CONSTRUCTOR
  84. /****** Class EncoderConfigC/COPY CONSTRUCTOR *******************************
  85. *
  86. *   NAME
  87. *   EncoderConfigC::EncoderConfigC -- Constructeur de recopie
  88. *
  89. *   SYNOPSIS
  90. *   EncoderConfigC::EncoderConfigC(roConfig)
  91. *
  92. *   EncoderConfigC::EncoderConfigC(const EncoderConfigC &);
  93. *
  94. *   FUNCTION
  95. *   Recopie les réglages de l'encodeur.
  96. *
  97. *   INPUTS
  98. *   roConfig - Réglages à recopier.
  99. *
  100. *   NOTES
  101. *   Cette fonctionnalité est utilisée pour initialiser les réglages locaux
  102. *   de l'encodeur pour chaque fichier, en partant des réglages par défaut.
  103. *
  104. *****************************************************************************
  105. *
  106. */
  107.  
  108.  
  109. EncoderConfigC::EncoderConfigC(const EncoderConfigC &roConfig)
  110. {
  111.     const EncoderConfigC *const poConfig = &roConfig;
  112.  
  113.     // Recopier les réglages par défaut.
  114.  
  115.     ecfg_iLayer       = poConfig->ecfg_iLayer;
  116.     ecfg_wSampling    = poConfig->ecfg_wSampling;
  117.     ecfg_wBitrate     = poConfig->ecfg_wBitrate;
  118.     ecfg_sFlags       = poConfig->ecfg_sFlags;
  119.     ecfg_sModes       = poConfig->ecfg_sModes;
  120.     ecfg_wTargetType  = poConfig->ecfg_wTargetType;
  121.     ecfg_iIntelFormat = poConfig->ecfg_iIntelFormat;
  122.     ecfg_CDDAFmt      = poConfig->ecfg_CDDAFmt;
  123.  
  124.     SetOutputName(poConfig->GetOutputName());
  125. }
  126. ///
  127. /// EncoderConfigC::SetBitRate()
  128. /****** Class EncoderConfigC/SetBitRate ****************************************
  129. *
  130. *   NAME
  131. *   EncoderConfigC::SetBitRate -- Définir le taux de sortie de l'encodeur.
  132. *
  133. *   SYNOPSIS
  134. *   EncoderConfigC::SetBitRate(wBitRate)
  135. *
  136. *   void EncoderConfigC::SetBitRate(UWORD);
  137. *
  138. *   FUNCTION
  139. *   Mémorise le taux de sortie de l'encodeur, ainsi que l'index correspondant.
  140. *   Si le taux de sortie demandé n'existe pas dans la table, la fonction sélec-
  141. *   tionne la valeur inférieure la plus proche.
  142. *   Si le taux de sortie demandé est inférieur à la plus petite valeur de la
  143. *   table, la fonction sélectionne la valeur par défaut (128 kbits/s)/
  144. *
  145. *   INPUTS
  146. *   wBitRate - Taux de sortie souhaité (kbits/s)
  147. *
  148. *****************************************************************************
  149. *
  150. */
  151.  
  152.  
  153. void EncoderConfigC::SetBitRate(UWORD wBitRate)
  154. {
  155.     static UWORD a_wBitrate[3][14] =
  156.     {
  157.           {32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448}, // Layer I
  158.           {32, 48, 56,  64,  80,  96, 112, 128, 160, 192, 224, 256, 320, 384}, // Layer II
  159.           {32, 40, 48,  56,  64,  80,  96, 112, 128, 160, 192, 224, 256, 320}  // Layer III
  160.     };
  161.  
  162.     int iBrate = 0;
  163.     int ibr;
  164.     int iLayer = ecfg_iLayer;
  165.     ecfg_wBitrate = 0;
  166.  
  167.     // Utiliser le taux de sortie légal immédiatement inférieur à la valeur indiquée.
  168.  
  169.     while (wBitRate >= (ibr = a_wBitrate[iLayer][iBrate]) && iBrate < 14)
  170.     {
  171.         if (wBitRate == ibr)
  172.         {
  173.             ecfg_wBitrate = a_wBitrate[iLayer][iBrate];
  174.             ecfg_sModes.bitrate = iBrate;
  175.             break;
  176.         }
  177.         ++iBrate;
  178.     }
  179.  
  180.     // Si le taux de sortie choisi n'a pas été trouvé, sélectionner la valeur inférieure
  181.     // la plus proche, ou la valeur par défaut.
  182.  
  183.     if (ecfg_wBitrate == 0)
  184.     {
  185.         if (iBrate > 0 && iBrate < 14)          // Prendre la valeur inférieure.
  186.         {
  187.             ecfg_sModes.bitrate = --iBrate;
  188.             ecfg_wBitrate       = a_wBitrate[iLayer][iBrate];
  189.         }
  190.         else                                    // Prendre la valeur par défaut.
  191.         {
  192.             ecfg_wBitrate = 160;
  193.  
  194.             if      (iLayer == LAYER_I)     ecfg_sModes.bitrate = 4;
  195.             else if (iLayer == LAYER_II)    ecfg_sModes.bitrate = 8;
  196.             else                            ecfg_sModes.bitrate = 9;
  197.         }
  198.     }
  199. }
  200. ///
  201. /// EncoderConfigC::SetSampleFreq()
  202. /****** Class EncoderConfigC/SetSampleFreq *************************************
  203. *
  204. *   NAME
  205. *   EncoderConfigC::SetSampleFreq -- Définir la fréquence d'échantillonage.
  206. *
  207. *   SYNOPSIS
  208. *   success = EncoderConfigC::SetSampleFreq(wSampleFreq)
  209. *
  210. *   bool EncoderConfigC::SetSampleFreq(UWORD);
  211. *
  212. *   FUNCTION
  213. *   Mémorise la fréquence d'échantillonage choisie par l'utilisateur ou
  214. *   spécifiée par le fichier audio à encoder.
  215. *   La tolérance pour cette fréquence d'échantillonage est de +/- 4% par
  216. *   rapport aux valeurs autorisées (32 KHz, 44.1 KHz et 48 KHz). Toutes les
  217. *   fréquences hors de ces limites sont rejetées.
  218. *
  219. *   INPUTS
  220. *   wSampleFreq - Fréquence d'échantillonage à utiliser par défaut (Hz)
  221. *
  222. *   RESULT
  223. *   success - FALSE si la fréquence est incorrecte.
  224. *
  225. *****************************************************************************
  226. *
  227. */
  228.  
  229.  
  230. int EncoderConfigC::SetSampleFreq(UWORD wSampleFreq)
  231. {
  232.     if      (wSampleFreq >= 30720 && wSampleFreq <= 33280)
  233.     {
  234.             ecfg_wSampling = 32000;
  235.             ecfg_sModes.sampfreq = F_32000;
  236.     }
  237.     else if (wSampleFreq >= 42336 && wSampleFreq <= 45864)
  238.     {
  239.             ecfg_wSampling = 44100;
  240.             ecfg_sModes.sampfreq = F_44100;
  241.     }
  242.     else if (wSampleFreq >= 46080 && wSampleFreq <= 49920)
  243.     {
  244.             ecfg_wSampling = 48000;
  245.             ecfg_sModes.sampfreq = F_48000;
  246.     }
  247.     else
  248.     {
  249.             ecfg_wSampling = 0;
  250.             ecfg_sModes.sampfreq = F_ILLEGAL;
  251.             return FALSE;
  252.     }
  253.  
  254.     return TRUE;
  255. }
  256. ///
  257.  
  258. //----------------------------------------------------------------------------------------------------
  259. //========================================== Classe CoderC ===========================================
  260. //----------------------------------------------------------------------------------------------------
  261. //
  262. //  CoderC est la classe de base, dérivée en classes spécialisées pour chaque Layer.
  263. //  Les fonctions supportées par cette classe sont des fonctions générales, communes à chaque type
  264. //  de layer (chaque classe spécialisée ayant la possibilité de re-définir en partie ces fonctions).
  265.  
  266. // Constructeur et destructeur.
  267.  
  268. /// CoderC::CoderC()
  269. CoderC::CoderC(FileInfosC &roFileInfos, ULONG iReserved) : EncoderConfigC(roFileInfos), enc_roFileInfos(roFileInfos)
  270. {
  271.     int iInitError;
  272.  
  273.     SetErrorCodes(ESTAT_NOTREADY, ERR_NOT_INITIALIZED);     // Indiquer que l'encodeur n'est pas encore prêt.
  274.     enc_pInputHandle   = NULL;
  275.  
  276.     SetOutputName(roFileInfos.GetOutputName());             // Récupérer le nom du fichier encodé.
  277.  
  278.     // Ouvrir le canal d'entrée (InputStream)
  279.  
  280.     if ( (enc_pInputHandle = CreateAudioC(roFileInfos)) )
  281.     {
  282.         ULONG SpecialOffset = (GetEncodingMode() == MONO) ? iReserved : iReserved * 2;
  283.         enc_pInputHandle->SetRollGap(SpecialOffset);
  284.  
  285.         if (enc_pInputHandle->OpenStream() == IOERR_NONE && enc_pInputHandle->AllocStreamBuffer() == IOERR_NONE)
  286.         {
  287.             iInitError  = !(enc_pdAnaFilter = (T_AnaFilter *) AllocAlignedBuffer(sizeof(T_AnaFilter)));
  288.             iInitError |= !(enc_sOutputStreamDatas.pOutputBuffer = AllocAlignedBuffer(OUTPUT_BUFFSIZE));
  289.  
  290.             if (!iInitError)
  291.             {
  292.                 SetErrorCodes(ESTAT_READY, ERR_NONE);
  293.  
  294.                 enc_bStereo  = (GetEncodingMode() == MONO) ? 1 : 2;
  295.                 enc_bSBLimit = SBLIMIT;
  296.  
  297.                 enc_iMinNeededBits = (sizeof(BSHeader) * 8) + (IsCRC() ? 16 : 0);
  298.                 enc_sOutputStreamDatas.iOB_BitIndex  = 0;
  299.                 enc_sOutputStreamDatas.iOB_TotalBits = enc_sOutputStreamDatas.iOB_BitsFree = OUTPUT_BUFFSIZE * 8;
  300.                 enc_bpOB_FileLock  = NULL;
  301.  
  302.                 InitAnaFilter();
  303.                 InitWrite();            // Initialiser le fichier destination.
  304.  
  305.                 // Initialiser le tableau "multiple" inverse (pour EncodeSamples()).
  306.  
  307.                 REAL s = 1.25992104989487;          // = sqrt³(2)
  308.                 REAL old;
  309.                 enc_adMultiples[0] = old = 0.5;
  310.  
  311.                 for (int i = 1; i < 63; i++)
  312.                 {
  313.                     old = enc_adMultiples[i] = old * s;
  314.                 }
  315.                 enc_adMultiples[63] = 1e20;
  316.  
  317.                 // Initialiser le bloc d'entête pour le fichier encodé.
  318.  
  319.                 enc_BSHeader.sBSHeader.bsh_SyncWord  = 0xFFF;
  320.                 enc_BSHeader.sBSHeader.bsh_Version   = 1;        // MPEG-1
  321.                 enc_BSHeader.sBSHeader.bsh_CRC       = !IsCRC();
  322.                 enc_BSHeader.sBSHeader.bsh_Bitrate   = GetBitrateIndex() + 1;
  323.                 enc_BSHeader.sBSHeader.bsh_SmplFreq  = GetSmplFrqIndex();
  324.                 enc_BSHeader.sBSHeader.bsh_Padding   = 0;
  325.                 enc_BSHeader.sBSHeader.bsh_Extension = 0;
  326.                 enc_BSHeader.sBSHeader.bsh_Mode      = GetEncodingMode();
  327.                 enc_BSHeader.sBSHeader.bsh_ModeExt   = 0;
  328.                 enc_BSHeader.sBSHeader.bsh_Copyright = IsCopyrighted();
  329.                 enc_BSHeader.sBSHeader.bsh_Original  = IsOriginal();
  330.                 enc_BSHeader.sBSHeader.bsh_Emphasis  = GetDeemphasis();
  331.             }
  332.             else SetErrorCodes(ESTAT_NOMEMORY, ERR_INTERNAL_BUFFERS);
  333.         }
  334.         else SetErrorCodes(ESTAT_NOTREADY, ERR_ISTREAM_FAILURE);
  335.     }
  336. }
  337. ///
  338. /// CoderC::~CoderC() (virtual)
  339. CoderC::~CoderC()
  340. {
  341.     void *pOutBuffer = enc_sOutputStreamDatas.pOutputBuffer;
  342.  
  343.     if (enc_pdAnaFilter) FreeAlignedBuffer(enc_pdAnaFilter);
  344.     if (pOutBuffer)
  345.     {
  346.         CleanupWrite();
  347.         FreeAlignedBuffer(pOutBuffer);
  348.     }
  349.  
  350.     if (enc_poPsychoC)  delete enc_poPsychoC;
  351.  
  352.     // Fermer le fichier à encoder.
  353.  
  354.     if (enc_pInputHandle)
  355.     {
  356.         enc_pInputHandle->FreeStreamBuffer();
  357.         enc_pInputHandle->CloseStream();
  358.         delete enc_pInputHandle;                      // Fermer le flux d'entrée.
  359.     }
  360. }
  361. ///
  362.  
  363.  
  364. //----------------------------------------------------------------------------------------------------
  365. //=========================== Parties communes à tous les types de Layers ============================
  366. //----------------------------------------------------------------------------------------------------
  367.  
  368. // Fonctions privées.
  369.  
  370. /// CoderC::InitAnaFilter()
  371. /****** Class CoderC/InitAnaFilter ******************************************
  372. *
  373. *   NAME
  374. *   CoderC::InitAnaFilter -- Initialiser la table AnaFilter
  375. *
  376. *   SYNOPSIS
  377. *   CoderC::InitAnaFilter()
  378. *
  379. *   void CoderC::InitAnaFilter();
  380. *
  381. *   FUNCTION
  382. *   Initialise la table AnaFilter().
  383. *
  384. *   NOTES
  385. *   Cette table est calculée en utilisant les formules de trigonométrie
  386. *   classiques plutôt qu'en faisant appel de multiples fois à cos().
  387. *
  388. *****************************************************************************
  389. *
  390. */
  391.  
  392.  
  393. void CoderC::InitAnaFilter()
  394. {
  395.     REAL sin_alpha, cos_alpha;
  396.     REAL sin_delta, cos_delta;
  397.     REAL t;
  398.  
  399.     t = PI / 64.0;
  400.     sin_delta = sin(t);
  401.     cos_delta = cos(t);
  402.  
  403.     sin_alpha = cos_alpha = sqrt(0.5);
  404.  
  405.     for (int i = 0; i < 128 ; i++)
  406.     {
  407.         t = cos_alpha * 1e9;
  408.         (*enc_pdAnaFilter)[i] = 1e-9 * ( (t >= 0) ? floor(t + 0.5) : ceil(t - 0.5) );
  409.  
  410.         // Calculer les valeurs angulaires suivantes.
  411.  
  412.         t = cos_alpha;
  413.         cos_alpha = t * cos_delta + sin_alpha * sin_delta;
  414.         sin_alpha = sin_alpha * cos_delta - t * sin_delta;
  415.     }
  416. }
  417. ///
  418. /// CoderC::GetIndex()   (double : ASM)
  419. /****** Class CoderC/GetIndex ***********************************************
  420. *
  421. *   NAME
  422. *   CoderC::GetIndex -- Retourne un index du tableau multiple[]
  423. *
  424. *   SYNOPSIS
  425. *   Index = CoderC::GetIndex(real)
  426. *
  427. *   int CoderC::GetIndex(double);
  428. *   int CoderC::GetIndex(float);
  429. *
  430. *   FUNCTION
  431. *   Sépare la mantisse et l'exposant d'un nombre flottant, puis retourne
  432. *   l'index du tableau multiple[] contenant la valeur immédiatement
  433. *   supérieure.
  434. *   Les deux variantes de la fonction permettent d'employer indifféremment
  435. *   des "double" ou des "float".
  436. *
  437. *   INPUTS
  438. *   real - Nombre flottant à traiter.
  439. *   e    - Valeur de l'exposant.
  440. *
  441. *   RESULT
  442. *   Mantisse - Valeur de la mantisse.
  443. *
  444. *   BUGS
  445. *   La valeur retournée pour la mantisse ne prend pas en compte la totalité
  446. *   des chiffres significatifs (6 chiffres en FLOAT, 9 chiffres en DOUBLE).
  447. *
  448. *   SEE ALSO
  449. *   CoderC::ScaleFactor()
  450. *
  451. *****************************************************************************
  452. *
  453. * Le tableau "multiple[]" original est composé des 63 premiers termes d'une suite
  454. * géométrique :
  455. * U0 = 2, r = SQR³(1/2), U63 = 1e-20;
  456. *
  457. *  n   : Un                =>    exp        mantisse
  458. * [00] : 2.00000000000000  => + 0x400   0x0000000000000
  459. * [01] : 1.58740105196820  => + 0x3FF   0x965FEA53D6E3D
  460. * [02] : 1.25992104989487  => + 0x3FF   0x428A2F98D728B
  461. * [03] : 1.00000000000000  => + 0x3FF   0x0000000000000
  462. * [04] : 0.79370052598410  => + 0x3FE   0x965FEA53D6E3D
  463. * ...
  464. */
  465.  
  466.  
  467. inline int CoderC::GetIndex(double real)
  468. {
  469.     // Format d'un "double" :
  470.     // seeeeeee eeeemmmm mmmmmmmm mmmmmmmm mmmmmmmm mmmmmmmm mmmmmmmm mmmmmmmm
  471.     // Bias of biased exponent = 1023
  472.  
  473.     union lfloat {double f;
  474.                   short  s[4];
  475.                  } u;
  476.  
  477.     const int NEW_EXP = 0x3FF0 + (30 * 16);                // On n'utilise que 30 bits de la mantisse.
  478.     int e, m;
  479.  
  480.     u.f = real;
  481.     e = ( 1024 - ((u.s[0] & 0x7FF0) >> 4) ) * 3;            // Extraire l'exposant.
  482.     u.s[0] = (u.s[0] & 0x000F) | NEW_EXP;                   // Modifier l'exposant.
  483.     m = (int) u.f;                                          // Convertir la mantisse (flottante) en entier.
  484.  
  485.     if      (m >= 1704458901)  e -= 3;
  486.     else if (m >= 1352829926)  e -= 2;
  487.     else if (m >= 1073741824)  e -= 1;
  488.  
  489.     if (e < 0)               e = 0;
  490.     if (e > SCALE_RANGE - 2) e = SCALE_RANGE - 2;
  491.  
  492.     return (e);
  493. }
  494.  
  495.  
  496. inline int CoderC::GetIndex(float real)
  497. {
  498.     // Format d'un "float" :
  499.     // seeeeeee emmmmmmm mmmmmmmm mmmmmmmm
  500.     // Bias of biased exponent = 127
  501.  
  502.     union sfloat {float f;
  503.                   long  l;
  504.                  } u;
  505.  
  506.     int e, m;
  507.  
  508.     u.f = real;
  509.     e = ( 128 - ((u.l & 0x7F800000) >> 23) ) * 3;           // Extraire l'exposant.
  510.     m = u.l & 0x007FFFFF;
  511.  
  512.     if      (m >= 4927477)  e -= 3;
  513.     else if (m >= 2180376)  e -= 2;
  514.     else if (m >= 0)        e -= 1;
  515.  
  516.     if (e < 0)               e = 0;
  517.     if (e > SCALE_RANGE - 2) e = SCALE_RANGE - 2;
  518.  
  519.     return (e);
  520. }
  521. ///
  522. /// CoderC::InitWrite()
  523. /****** Class CoderC/InitWrite **********************************************
  524. *
  525. *   NAME
  526. *   CoderC::InitWrite -- Initialiser le fichier de destination
  527. *
  528. *   SYNOPSIS
  529. *   CoderC::InitWrite()
  530. *
  531. *   void CoderC::InitWrite();
  532. *
  533. *   FUNCTION
  534. *   Initialise le fichier destination en l'effaçant s'il existe déjà.
  535. *
  536. *   NOTES
  537. *   Il est nécessaire d'effacer ce fichier avant de commencer l'encodage, du
  538. *   fait que la fonction WriteBuffer() ajoute les données au fur et à mesure
  539. *   dans le fichier de sortie.
  540. *
  541. *   BUGS
  542. *
  543. *****************************************************************************
  544. *
  545. */
  546.  
  547.  
  548. void CoderC::InitWrite()
  549. {
  550.     BPTR bpFileHandle;
  551.  
  552.     // Effacer le fichier, tout en le re-créant avec une taille de ZERO.
  553.  
  554.     if ( (bpFileHandle = ::Open(GetOutputName(), MODE_NEWFILE)) )
  555.     {
  556.         // Création OK. Fermer le fichier (il doit maintenant avoir une taille de ZERO)
  557.  
  558.         if (::Close(bpFileHandle) != DOSFALSE)
  559.         {
  560.             if ( (enc_bpOB_FileLock = ::Lock(GetOutputName(), SHARED_LOCK)) )
  561.             {
  562.                 return;     // On a le Lock, donc poursuivre.
  563.                             // Ce "lock" permettra de réouvrir ce fichier chaque fois qu'il
  564.                             // faudra vider le tampon de sortie, et interdit en même temps
  565.                             // la destruction du fichier tant que l'encodage n'est pas
  566.                             // terminé.
  567.             }
  568.         }
  569.     }
  570.     SetErrorCodes(ESTAT_IOERROR, ERR_OPEN_OSTREAM);
  571. }
  572. ///
  573. /// CoderC::CleanupWrite()
  574. /****** Class CoderC/CleanupWrite *******************************************
  575. *
  576. *   NAME
  577. *   CoderC::CleanupWrite -- Fermer définitivement le fichier destination.
  578. *
  579. *   SYNOPSIS
  580. *   CoderC::CleanupWrite()
  581. *
  582. *   void CoderC::CleanupWrite();
  583. *
  584. *   FUNCTION
  585. *   Vide le tampon et ferme définitivement le fichier destination en libérant
  586. *   le 'Lock' sur ce fichier.
  587. *
  588. *   NOTES
  589. *
  590. *   BUGS
  591. *
  592. *****************************************************************************
  593. *
  594. */
  595.  
  596.  
  597. void CoderC::CleanupWrite()
  598. {
  599.     WriteBuffer();
  600.  
  601.     if (enc_bpOB_FileLock != 0)
  602.     {
  603.         ::UnLock(enc_bpOB_FileLock);
  604.         enc_bpOB_FileLock = 0;
  605.     }
  606. }
  607. ///
  608. /// CoderC::WriteBuffer()
  609. /****** Class CoderC/WriteBuffer ********************************************
  610. *
  611. *   NAME
  612. *   CoderC::WriteBuffer -- Créer/compléter le fichier encodé.
  613. *
  614. *   SYNOPSIS
  615. *   CoderC::WriteBuffer()
  616. *
  617. *   void CoderC::WriteBuffer();
  618. *
  619. *   FUNCTION
  620. *   Ajoute le tampon de sortie au fichier encodé. Lors du premier appel, le
  621. *   fichier est crée ou remplacé s'il existe déjà. Les appels suivants
  622. *   ajoutent les données du tampon en fin de fichier.
  623. *
  624. *   NOTES
  625. *   Le fichier est immédiatement refermé après avoir inscrit les nouvelles
  626. *   données.
  627. *
  628. *   Lors du premier accès, le fichier est ouvert normalement, puis un 'Lock'
  629. *   est obtenu sur ce fichier. Lorsque le fichier est refermé après avoir
  630. *   inscrit les données, le 'Lock' est maintenu protégeant ainsi le fichier.
  631. *   Lors des appels suivants, c'est ce 'Lock' qui est utilisé pour ouvrir
  632. *   le fichier.
  633. *
  634. *   BUGS
  635. *   Le mode READWRITE présentait l'avantage de créer un fichier vide s'il
  636. *   n'existait pas, mais cette méthode semble poser des problèmes à AFS.
  637. *   La méthode actuelle consiste donc à initialiser le fichier grâce au mode
  638. *   NEWFILE, puis à obtenir directement un SHARED_LOCK après avoir fermé ce
  639. *   fichier vide.
  640. *
  641. *****************************************************************************
  642. *
  643. */
  644.  
  645. // La fonction Seek() ne fonctionne pas correctement avec le FileSystem v36/37.
  646. // Voir les Autodocs pour le détail.
  647.  
  648. LONG NewSeek(BPTR file, LONG position, LONG offset);
  649. // Fonction définie dans InputStream.cpp
  650.  
  651.  
  652. void CoderC::WriteBuffer()
  653. {
  654.     BPTR  file_handle;
  655.     ULONG num_bytes     = ((enc_sOutputStreamDatas.iOB_BitIndex + 7) >> 3);
  656.     e_EncErrCodes error = ERR_NONE;
  657.  
  658.     // Avorter s'il y a eu une erreur, ou si le tampon est vide.
  659.  
  660.     if (enc_iEncoderStatus != ESTAT_READY || num_bytes == 0)  return;
  661.  
  662.     // Ouvrir le fichier à partir du Lock obtenu à l'initialisation de l'encodeur.
  663.  
  664.     if (  (file_handle = ::OpenFromLock(enc_bpOB_FileLock))
  665.        && (enc_bpOB_FileLock = ::DupLockFromFH(file_handle)) )
  666.     {
  667.         if (NewSeek(file_handle, 0, OFFSET_END) >= 0)       // Se positionner en fin de fichier.
  668.         {
  669.             BYTE *buffer = (BYTE *) enc_sOutputStreamDatas.pOutputBuffer;
  670.  
  671.             // Boucler sur l'écriture dans le fichier tant qu'il reste
  672.             // des données dans le tampon.
  673.  
  674.             while (num_bytes != 0)
  675.             {
  676.                 LONG bytes_read = ::Write(file_handle, buffer, num_bytes);
  677.  
  678.                 if (bytes_read == -1)
  679.                 {
  680.                     error = ERR_WRITE_OSTREAM;              // Erreur d'écriture.
  681.                     break;
  682.                 }
  683.  
  684.                 num_bytes -= bytes_read;
  685.                 buffer    += bytes_read;
  686.             }
  687.         }
  688.         else error = ERR_SEEK_OSTREAM;                      // Erreur de positionnement.
  689.  
  690.         if (::Close(file_handle) == DOSFALSE)
  691.             error = ERR_CLOSE_OSTREAM;                      // Erreur de fermeture du fichier.
  692.     }
  693.     else error = ERR_OPEN_OSTREAM;                          // Erreur d'ouverture du fichier.
  694.  
  695.     // S'il y a eu une erreur, placer les indicateurs globaux.
  696.  
  697.     if (error != ERR_NONE)  SetErrorCodes(ESTAT_IOERROR, error);
  698. }
  699. ///
  700.  
  701. // Fonctions virtuelles.
  702.  
  703. /// CoderC::GetAudio()
  704. /****** Class CoderC/GetAudio ***********************************************
  705. *
  706. *   NAME
  707. *   CoderC::GetAudio -- Préparer la passe suivante de l'encodeur.
  708. *
  709. *   SYNOPSIS
  710. *   Result = CoderC::GetAudio()
  711. *
  712. *   bool CoderC::GetAudio();
  713. *
  714. *   FUNCTION
  715. *   Obtient l'adresse de la page suivante. Les échantillons au format Intel
  716. *   sont convertis au format Motorola.
  717. *
  718. *   RESULT
  719. *   Result - FALSE s'il y a eu une erreur pendant la lecture du tampon d'
  720. *            entrée.
  721. *
  722. *****************************************************************************
  723. *
  724. */
  725.  
  726.  
  727. int CoderC::GetAudio()
  728. {
  729.     if ( (enc_pSamples = enc_pInputHandle->ReadSamples(enc_wFrameSize)) )
  730.     {
  731.         // Réordonner les échantillons si nécessaire (conversion Intel => Motorola).
  732.         // (On converti la totalité du tampon de lecture).
  733.  
  734.         if (ecfg_iIntelFormat)     // Format Intel ?
  735.         {
  736.             char *p = (char *) enc_pSamples;
  737.             ULONG FrameSize = enc_wFrameSize;
  738.             char  temp;
  739.  
  740.             for (int i = 0; i < FrameSize; i++)
  741.             {
  742.                 temp = *p;
  743.                 *p++ = *(p+1);
  744.                 *p++ = temp;
  745.             }
  746.         }
  747.  
  748.         // Ajouter un slot si nécessaire.
  749.  
  750.         if (enc_wSPF_Reminder)
  751.         {
  752.             if (enc_wSlotFree >= ecfg_wSampling)
  753.             {
  754.                 // Le dernier slot utilisé peut contenir les données.
  755.                 enc_wSlotFree -= ecfg_wSampling;
  756.                 enc_iAvgDataBits = 0;
  757.                 enc_BSHeader.sBSHeader.bsh_Padding = 0;
  758.             }
  759.             else
  760.             {
  761.                 // Slot partiel (non entièrement rempli).
  762.                 enc_wSlotFree += enc_wSPF_Reminder;             // Calculer la place restante dans ce slot.
  763.                 enc_iAvgDataBits = enc_bBitsPerSlot;
  764.                 enc_BSHeader.sBSHeader.bsh_Padding = 1;
  765.             }
  766.         }
  767.  
  768.         enc_iAvgDataBits += enc_wSlotsPerFrame << enc_bBitsPerSlotN;
  769.         ++enc_iFrameNumber;
  770.  
  771.         return TRUE;
  772.     }
  773.  
  774.     return FALSE;
  775. }
  776. ///
  777.  
  778. // Fonctions protégées.
  779.  
  780. ///CoderC::InitSlotsPerFrame()
  781. /****** Class CoderC/InitSlotsPerFrame **************************************
  782. *
  783. *   NAME
  784. *   CoderC::InitSlotsPerFrame --
  785. *
  786. *   SYNOPSIS
  787. *   CoderC::InitSlotsPerFrame(wSamplesPerFrame, wNumBitsN)
  788. *
  789. *   void CoderC::InitSlotsPerFrame(UWORD, UWORD);
  790. *
  791. *   FUNCTION
  792. *
  793. *   INPUTS
  794. *   wSamplesPerFrame - Nombre d'échantillons par "page".
  795. *   wNumBitsN        - Nombre de bits (Log2) par slot.
  796. *
  797. *   NOTES
  798. *   L'encodeur original (Musicin) effectue ces calculs en flottant, ce qui
  799. *   peut induire des erreurs d'arrondis par rapport aux calculs sur des
  800. *   entiers comme c'est fait ici.
  801. *   La différence de taille entre un fichier encodé avec Pegase et un fichier
  802. *   encodé avec Musicin vient très probablement de là.
  803. *
  804. *****************************************************************************
  805. *
  806. */
  807.  
  808.  
  809. void CoderC::InitSlotsPerFrame(UWORD wSamplesPerFrame, UWORD wNumBitsN)
  810. {
  811.     enc_wSamplesPerFrame = wSamplesPerFrame;
  812.     enc_bBitsPerSlot     = 1 << wNumBitsN;
  813.     enc_bBitsPerSlotN    = wNumBitsN;
  814.     enc_wFrameSize       = enc_roFileInfos.GetNumChannels() * wSamplesPerFrame;
  815.  
  816.     div_t t = div( (enc_wSamplesPerFrame >> enc_bBitsPerSlotN) * 1000 * ecfg_wBitrate, ecfg_wSampling);
  817.     enc_wSlotsPerFrame = t.quot;
  818.     enc_wSPF_Reminder  = enc_wSlotFree = ecfg_wSampling - t.rem;
  819.  
  820.     enc_iAvgDataBits = enc_wSlotsPerFrame << enc_bBitsPerSlotN;
  821. }
  822. ///
  823. ///CoderC::SubBandCoding_Stereo()  (ASM)
  824. /****** Class CoderC/SubBandCoding_Stereo ***********************************
  825. *
  826. *   NAME
  827. *   CoderC::SubBandCoding_Stereo -- Prétraitement des échantillons.
  828. *
  829. *   SYNOPSIS
  830. *   CoderC::SubBandCoding_Stereo(pdSample)
  831. *
  832. *   void CoderC::SubBandCoding_Stereo(T_SubBandSmplStereo *);
  833. *   void CoderC::SubBandCoding_Stereo(T_SubBandSmplMono *);
  834. *
  835. *   FUNCTION
  836. *   Filtre la bande courante.
  837. *
  838. *   INPUTS
  839. *   - pdSample = Pointeur vers le tableau a initialiser.
  840. *
  841. *   NOTES
  842. *   Cette fonction est constituée de plusieurs sous-ensembles des sources
  843. *   originaux (boucles, window_subband et filter_subband). L'intégration de
  844. *   ces blocs dans une seule et unique fonction permet de supprimer les
  845. *   différents appels de fonction, et autorise une meilleure gestion des
  846. *   ressources.
  847. *
  848. *   L'implémentation actuelle de l'algorithme est basée sur une optimisation
  849. *   des accès mémoire. Elle n'est pas forcément la plus efficace lorsque l'
  850. *   encodeur est utilisée sur une machine dépourvue de cache (68020).
  851. *
  852. *****************************************************************************
  853. *
  854. *   22.06.98 :
  855. *       · Modification du source entraînant une meilleure génération de code
  856. *         du StormC.
  857. *
  858. *   10.09.98 :
  859. *       · Nouvel algorithme plus performant. Les données sont systématiquement
  860. *         utilisées dans tous les calculs dès la première lecture. De cette façon,
  861. *         on ne modifie plus sans cesse le cache (tableaux y[]), et donc on
  862. *         élimine un bon nombre de "flushes".
  863. *
  864. *   Combinaison des fonctions "window_subband" et "filter_subband" des Layers 1 et 2.
  865. *
  866. *   PROFILER :
  867. *       Date        Fichier             Durée       Layer II (double)       Layer II (float)
  868. *       ------------------------------------------------------------------------------------
  869. *       09.05.98    Europe2.1           00:02           00:03.02                 00:02.82
  870. *       12.05.98    07_AudioNormal      03:27           04:47
  871. *       30.05.98    07_AudioNormal      03:27           04:17
  872. *       14.06.98    07_AudioNormal      03:27           04:04
  873. *       10.09.98    07_AudioNormal      03:27           03:13
  874. */
  875.  
  876. #if _USE_ASM_FCT_ == 1
  877.  
  878. extern "C"{
  879. void SubBandCoding_Stereo(REAL pdSample[2][12][32], WORD **pActualPtr, REAL *pAnaFilter);
  880. }
  881.  
  882. inline void CoderC::SubBandCoding_Stereo(CoderC::T_SubBandSmplStereo *pdSample)
  883. {
  884.     ::SubBandCoding_Stereo(*pdSample, &enc_pSB_ActualPtr, &(*enc_pdAnaFilter)[0]);
  885. }
  886.  
  887. #else
  888.  
  889. void CoderC::SubBandCoding_Stereo(CoderC::T_SubBandSmplStereo *pdSample)
  890. {
  891.     extern const T_ANAWINDOW a_dAnaWindow[];
  892.  
  893.     ULONG j, n, m;
  894.     T_ANAWINDOW *py;
  895.     T_ANAWINDOW y[SBLIMIT*2];
  896.     T_ANAWINDOW  ysumL, ysumR;
  897.  
  898.     for (j = 0; j < SCALE_BLOCK; j++)
  899.     {
  900.         //-------------------------------------------------------------------
  901.         //========== Collationnement et application des paramètres ==========
  902.         //-------------------------------------------------------------------
  903.  
  904.         // Première partie : Calculer yx[0]
  905.  
  906.         const T_ANAWINDOW *pAnaWindow = &a_dAnaWindow[0];
  907.  
  908.         {
  909.             T_ANAWINDOW wincoeff;
  910.             WORD *p1, *p2;
  911.  
  912.             p2 = enc_pSB_ActualPtr;
  913.             p1 = &p2[31 * 2];
  914.             p2 = &p2[479 * 2];
  915.  
  916.             ysumL = ysumR = 0;
  917.  
  918.             for (n = 3; n > 0; --n)
  919.             {
  920.                 wincoeff = *pAnaWindow++;
  921.                 ysumL += wincoeff * ((LONG) *p2    - (LONG) *p1);
  922.                 ysumR += wincoeff * ((LONG)  p2[1] - (LONG)  p1[1]);
  923.                 p1 += 32 * 2; p2 += -(32 * 2);
  924.  
  925.                 wincoeff = *pAnaWindow++;
  926.                 ysumL += wincoeff * ((LONG) *p2    + (LONG) *p1);
  927.                 ysumR += wincoeff * ((LONG)  p2[1] + (LONG)  p1[1]);
  928.                 p1 += 32 * 2; p2 += -(32 * 2);
  929.             }
  930.             wincoeff = *pAnaWindow++;
  931.             ysumL += wincoeff * ((LONG) *p2    - (LONG) *p1);
  932.             ysumR += wincoeff * ((LONG)  p2[1] - (LONG)  p1[1]);
  933.  
  934.             wincoeff = *pAnaWindow++;
  935.             y[0]  = ysumL + wincoeff * p1[32 * 2];
  936.             y[32] = ysumR + wincoeff * p1[32 * 2 + 1];
  937.         }
  938.  
  939.         // Deuxième partie : Calculer yx[1;15] et yx[17;31]
  940.  
  941.         {
  942.             T_ANAWINDOW wincoeff;
  943.             T_ANAWINDOW ysumL2, ysumR2;
  944.             WORD *p1, *p2;
  945.  
  946.             ULONG stp  = 30 * 2;
  947.             ULONG next = (64 - 30) * 2;
  948.  
  949.             n = 0;
  950.  
  951.             while (n < 15)
  952.             {
  953.                 p2 = enc_pSB_ActualPtr;
  954.  
  955.                 p1 = &p2[n+n];
  956.                 p2 = &p2[478 * 2 - (n+n)];
  957.  
  958.                 ysumL = ysumL2 = ysumR = ysumR2 = 0;
  959.  
  960.                 for (m = 4; m > 0; --m)
  961.                 {
  962.                     wincoeff = *pAnaWindow++;
  963.                     ysumL2 += wincoeff * p1[0];             // b4
  964.                     ysumR2 += wincoeff * p1[1];
  965.                     ysumL  += wincoeff * p2[32 * 2];        // a1
  966.                     ysumR  += wincoeff * p2[32 * 2 + 1];
  967.  
  968.                     wincoeff = *pAnaWindow++;
  969.                     ysumL2 += wincoeff * p2[0];             // b1
  970.                     ysumR2 += wincoeff * p2[1];
  971.                     ysumL  -= wincoeff * p1[32 * 2];        // a4
  972.                     ysumR  -= wincoeff * p1[32 * 2 + 1];
  973.  
  974.                     p1 = &p1[stp]; p2 = &p2[-stp];
  975.  
  976.                     wincoeff = *pAnaWindow++;
  977.                     ysumL2 -= wincoeff * p1[0];             // b3
  978.                     ysumR2 -= wincoeff * p1[1];
  979.                     ysumL  += wincoeff * p2[32 * 2];        // a2
  980.                     ysumR  += wincoeff * p2[32 * 2 + 1];
  981.  
  982.                     wincoeff = *pAnaWindow++;
  983.                     ysumL2 -= wincoeff * p2[0];             // b2
  984.                     ysumR2 -= wincoeff * p2[1];
  985.                     ysumL  -= wincoeff * p1[32 * 2];        // a3
  986.                     ysumR  -= wincoeff * p1[32 * 2 + 1];
  987.  
  988.                     p1 = &p1[next]; p2 = &p2[-next];
  989.                 }
  990.  
  991.                 stp  -= 4; next += 4;
  992.  
  993.                 ++n; py = &y[n];
  994.  
  995.                 py[0]  = ysumL;  py[32]  = ysumR;
  996.                 py[15] = ysumL2; py[47] = ysumR2;           // On continue à partir de y[16]
  997.             }
  998.         }
  999.  
  1000.         // Dernière partie : Calculer yx[16]
  1001.  
  1002.         {
  1003.             T_ANAWINDOW wincoeff;
  1004.             WORD *pL = &enc_pSB_ActualPtr[47 * 2];
  1005.  
  1006.             ysumL = ysumR = 0;
  1007.  
  1008.             for (n = 4; n > 0; --n)
  1009.             {
  1010.                 wincoeff = *pAnaWindow++;
  1011.                 ysumL -= wincoeff * *pL;
  1012.                 ysumR -= wincoeff *  pL[1];
  1013.  
  1014.                 wincoeff = *pAnaWindow++;
  1015.                 ysumL += wincoeff * pL[256 * 2];
  1016.                 ysumR += wincoeff * pL[256 * 2 + 1];
  1017.  
  1018.                 pL += (64 * 2);
  1019.             }
  1020.             // ysumL et ysumR contiennent les valeurs yR[16] et yL[16]
  1021.         }
  1022.  
  1023.         enc_pSB_ActualPtr += (32 * 2);                      // Pointer la sous-bande suivante.
  1024.  
  1025.         //---------------------------------------------
  1026.         //========== Application des filtres ==========
  1027.         //---------------------------------------------
  1028.  
  1029.         {
  1030.             double *SampleL1 = &(*pdSample)[0][j][0];
  1031.             double *pSB_SampleL1 = SampleL1;
  1032.             double *pSB_SampleL2;
  1033.             const  REAL *pFilter = &(*enc_pdAnaFilter)[0];
  1034.  
  1035.             #define K (32*12)       // Offset pour le second canal.
  1036.  
  1037.             ULONG max = 4, lstep = 16, lpos = 8;
  1038.             ULONG i, fidx, fidx2, fstep, i32;
  1039.  
  1040.             pSB_SampleL1[0]   = y[0]  * *pFilter;
  1041.             pSB_SampleL1[K]   = y[32] * *pFilter;
  1042.             pSB_SampleL1[1]   = ysumL - pSB_SampleL1[0];
  1043.             pSB_SampleL1[K+1] = ysumR - pSB_SampleL1[K];
  1044.             pSB_SampleL1[0] = pSB_SampleL1[0] + ysumL;
  1045.             pSB_SampleL1[K] = pSB_SampleL1[K] + ysumR;
  1046.  
  1047.             while (max <= 32) {
  1048.                 i32 = 0;
  1049.                 pSB_SampleL1 = SampleL1;
  1050.                 pSB_SampleL2 = &pSB_SampleL1[max];
  1051.  
  1052.                 for (i = lpos; i < 32; i += lstep) {
  1053.                     fstep = i;
  1054.                     fidx  = fstep - i32;
  1055.                     i32 += 32;
  1056.                     fidx2 = fstep + i32;
  1057.  
  1058.                     ysumL = ysumR = 0;
  1059.                     fstep += fstep;
  1060.                     py = &y[lpos];
  1061.  
  1062.                     while (py < &y[16]) {
  1063.                         double f1 = pFilter[fidx & 127];
  1064.                         double f2 = pFilter[fidx2 & 127];
  1065.                         ysumL += py[0]  * f1 + py[15] * f2;
  1066.                         ysumR += py[32] * f1 + py[47] * f2;
  1067.                         fidx += fstep; fidx2 += fstep; py += lstep;
  1068.                     }
  1069.                     *--pSB_SampleL2 = pSB_SampleL1[0] - ysumL;
  1070.                     pSB_SampleL2[K] = pSB_SampleL1[K] - ysumR;
  1071.                     pSB_SampleL1[K] = pSB_SampleL1[K] + ysumR;
  1072.                     *pSB_SampleL1++ = *pSB_SampleL1 + ysumL;
  1073.                 }
  1074.                 lstep -= lpos;
  1075.                 lpos >>= 1;
  1076.                 max += max;
  1077.             }
  1078.         }
  1079.     }
  1080. }
  1081.  
  1082. #endif  // _USE_ASM_FCT_
  1083. ///
  1084. /// CoderC::SubBandCoding_Mono()  (ASM)
  1085.  
  1086. #if _USE_ASM_FCT_ == 1
  1087.  
  1088. extern "C"{
  1089. void SubBandCoding_Mono(REAL pdSample[12][32], WORD **pActualPtr, REAL *pAnaFilter);
  1090. }
  1091.  
  1092. inline void CoderC::SubBandCoding_Mono(CoderC::T_SubBandSmplMono *pdSample)
  1093. {
  1094.     ::SubBandCoding_Mono(*pdSample, &enc_pSB_ActualPtr, &(*enc_pdAnaFilter)[0]);
  1095. }
  1096.  
  1097. #else
  1098.  
  1099. void CoderC::SubBandCoding_Mono(CoderC::T_SubBandSmplMono *pdSample)
  1100. {
  1101.     extern const T_ANAWINDOW a_dAnaWindow[];
  1102.  
  1103.     ULONG j, m, n;
  1104.     T_ANAWINDOW  y[SBLIMIT], *py;
  1105.     T_ANAWINDOW  ysum;
  1106.  
  1107.     for (j = 0; j < SCALE_BLOCK; j++)
  1108.     {
  1109.         //-------------------------------------------------------------------
  1110.         //========== Collationnement et application des paramètres ==========
  1111.         //-------------------------------------------------------------------
  1112.  
  1113.         // Première partie : Calculer yx[0]
  1114.  
  1115.         const T_ANAWINDOW *pAnaWindow = &a_dAnaWindow[0];
  1116.  
  1117.         {
  1118.             WORD *p1, *p2;
  1119.  
  1120.             p2 = enc_pSB_ActualPtr;
  1121.             p1 = &p2[31];
  1122.             p2 = &p2[479];
  1123.  
  1124.             ysum = 0;
  1125.  
  1126.             for (n = 3; n > 0; --n)
  1127.             {
  1128.                 ysum += *pAnaWindow++ * ((LONG) *p2 - (LONG) *p1);
  1129.                 p1 += 32; p2 += -32;
  1130.  
  1131.                 ysum += *pAnaWindow++ * ((LONG) *p2 + (LONG) *p1);
  1132.                 p1 += 32; p2 += -32;
  1133.             }
  1134.             ysum += *pAnaWindow++ * ((LONG) *p2 - (LONG) *p1);
  1135.  
  1136.             y[0] = ysum + *pAnaWindow++ * p1[32];
  1137.         }
  1138.  
  1139.         // Deuxième partie : Calculer yx[1;15] et yx[17;31]
  1140.  
  1141.         {
  1142.             T_ANAWINDOW ysum2, wincoeff;
  1143.  
  1144.             WORD  *p1, *p2;
  1145.             ULONG stp  = 30;
  1146.             ULONG next = 64 - 30;
  1147.  
  1148.             n = 0;
  1149.  
  1150.             while (n < 15)
  1151.             {
  1152.                 p2 = enc_pSB_ActualPtr;
  1153.  
  1154.                 p1 = &p2[n];
  1155.                 p2 = &p2[478 - n];
  1156.  
  1157.                 ysum = ysum2 = 0;
  1158.  
  1159.                 for (m = 4; m > 0; --m)
  1160.                 {
  1161.                     wincoeff = *pAnaWindow++;
  1162.                     ysum2 += wincoeff * p1[0];          // b4
  1163.                     ysum  += wincoeff * p2[32];         // a1
  1164.  
  1165.                     wincoeff = *pAnaWindow++;
  1166.                     ysum2 += wincoeff * p2[0];          // b1
  1167.                     ysum  -= wincoeff * p1[32];         // a4
  1168.  
  1169.                     p1 = &p1[stp]; p2 = &p2[-stp];
  1170.  
  1171.                     wincoeff = *pAnaWindow++;
  1172.                     ysum2 -= wincoeff * p1[0];          // b3
  1173.                     ysum  += wincoeff * p2[32];         // a2
  1174.  
  1175.                     wincoeff = *pAnaWindow++;
  1176.                     ysum2 -= wincoeff * p2[0];          // b2
  1177.                     ysum  -= wincoeff * p1[32];         // a3
  1178.  
  1179.                     p1 = &p1[next]; p2 = &p2[-next];
  1180.                 }
  1181.  
  1182.                 stp  -= 2; next += 2;
  1183.  
  1184.                 ++n; py = &y[n];
  1185.  
  1186.                 py[0] = ysum; py[15] = ysum2;           // On continue à partir de y[16]
  1187.             }
  1188.         }
  1189.  
  1190.         // Dernière partie : Calculer yx[16]
  1191.  
  1192.         {
  1193.             WORD *p = &enc_pSB_ActualPtr[47];
  1194.  
  1195.             ysum = 0;
  1196.  
  1197.             for (n = 4; n > 0; --n)
  1198.             {
  1199.                 ysum -= *pAnaWindow++ * p[0];
  1200.                 ysum += *pAnaWindow++ * p[256];
  1201.  
  1202.                 p += 64;
  1203.             }
  1204.             // ysum contient la valeur y[16]
  1205.         }
  1206.  
  1207.         enc_pSB_ActualPtr += 32;                // Pointer la sous-bande suivante.
  1208.  
  1209.         //---------------------------------------------
  1210.         //========== Application des filtres ==========
  1211.         //---------------------------------------------
  1212.  
  1213.         {
  1214.             double *Sample = &(*pdSample)[j][0];
  1215.             double *pSB_Sample1 = Sample;
  1216.             double *pSB_Sample2;
  1217.  
  1218.             const REAL *pFilter = &(*enc_pdAnaFilter)[0];
  1219.  
  1220.             ULONG max = 4, lstep = 16, lpos = 8;
  1221.             ULONG i, fidx, fidx2, fstep, i32;
  1222.  
  1223.             pSB_Sample1[0] = y[0] * pFilter[0];
  1224.             pSB_Sample1[1] = ysum - pSB_Sample1[0];
  1225.             pSB_Sample1[0] = pSB_Sample1[0] + ysum;
  1226.  
  1227.             while (max <= 32) {
  1228.                 i32 = 0;
  1229.                 pSB_Sample1 = Sample;
  1230.                 pSB_Sample2 = &pSB_Sample1[max];
  1231.  
  1232.                 for (i = lpos; i < 32; i += lstep) {
  1233.                     fstep = i;
  1234.                     fidx  = fstep - i32;
  1235.                     i32 += 32;
  1236.                     fidx2 = fstep + i32;
  1237.  
  1238.                     ysum = 0;
  1239.                     fstep += fstep;
  1240.                     py = &y[lpos];
  1241.  
  1242.                     while (py < &y[16]) {
  1243.                         ysum += py[0] * pFilter[fidx & 127] + py[15] * pFilter[fidx2 & 127];
  1244.                         fidx += fstep; fidx2 += fstep; py += lstep;
  1245.                     }
  1246.                     *--pSB_Sample2 = *pSB_Sample1 - ysum;
  1247.                     *pSB_Sample1++ = *pSB_Sample1 + ysum;
  1248.                 }
  1249.                 lstep -= lpos;
  1250.                 lpos >>= 1;
  1251.                 max += max;
  1252.             }
  1253.         }
  1254.     }
  1255. }
  1256.  
  1257. #endif  // _USE_ASM_FCT_
  1258. ///
  1259. /// CoderC::ScaleFactor()
  1260. /****** Class CoderC/ScaleFactor ********************************************
  1261. *
  1262. *   NAME
  1263. *   CoderC::ScaleFactor -- Rechercher le facteur d'échelle.
  1264. *
  1265. *   SYNOPSIS
  1266. *   CoderC::ScaleFactor(pScalar, pSample)
  1267. *   CoderC::ScaleFactorCalc(pbScalar, pdSample)
  1268. *
  1269. *   void CoderC::ScaleFactor(T_ScaleStereo *, T_SubBandSmplStereo *);
  1270. *   void CoderC::ScaleFactor(T_ScaleMono *, T_SubBandSmplMono *);
  1271. *
  1272. *   FUNCTION
  1273. *   Recherche le facteur d'échelle pour chaque sous-bande.
  1274. *
  1275. *   INPUTS
  1276. *   - pScalar : Tableau des index vers le tableau "Multiple[]"
  1277. *   - pSample : Tableau des bandes de filtres.
  1278. *
  1279. *   BUGS
  1280. *   La boucle originale ne prend pas en compte la valeur "multiple[63]", ce
  1281. *   qui semble curieux (cependant cette valeur est utilisée pour initialiser
  1282. *   le reste du tableau "scalar[]").
  1283. *   La méthode d'obtention de l'index n'est pas forcément strictement comp-
  1284. *   atible avec la méthode originale (du fait que le nombre de chiffres
  1285. *   significatifs utilisés pour la mantisse est peut-être trop faible...)
  1286. *
  1287. *   SEE ALSO
  1288. *   CoderC::GetIndex()
  1289. *
  1290. *****************************************************************************
  1291. *
  1292. */
  1293.  
  1294. // Rechercher le facteur d'échelle de chaque canal.
  1295.  
  1296. inline void CoderC::ScaleFactor(CoderC::T_ScaleStereo *pScalar, CoderC::T_SubBandSmplStereo *pSample)
  1297. {
  1298.     for (ULONG k = 0; k < enc_bStereo; k++)
  1299.     {
  1300.         ScaleFactorCalc(&(*pScalar)[k][0], (T_SubBandSmplMono *) &(*pSample)[k][0][0]);
  1301.     }
  1302. }
  1303. ///
  1304. /// CoderC::ScaleFactorCalc()  (ASM)
  1305. // Rechercher le facteur d'échelle du canal.
  1306.  
  1307. #if _USE_ASM_FCT_ == 1
  1308.  
  1309. extern "C"{
  1310. void ScaleFactorCalc_double(UBYTE *pbScalar, REAL pdSample[12][32], ULONG iSBLimit);
  1311. }
  1312.  
  1313. void CoderC::ScaleFactorCalc(UBYTE *pbScalar, CoderC::T_SubBandSmplMono *pdSample)
  1314. {
  1315.     ::ScaleFactorCalc_double(pbScalar, *pdSample, enc_bSBLimit);
  1316. }
  1317.  
  1318. #else
  1319.  
  1320. void CoderC::ScaleFactorCalc(UBYTE *pbScalar, CoderC::T_SubBandSmplMono *pdSample)
  1321. {
  1322.     LONG  i, j;
  1323.     REAL  ds, d, *pSamples;
  1324.  
  1325.     for (i = 0; i < enc_bSBLimit; i++)
  1326.     {
  1327.         pSamples = &(*pdSample)[0][i];
  1328.         ds = fabs(*pSamples);
  1329.  
  1330.         // Rechercher la valeur maximale dans chaque bande.
  1331.  
  1332.         for (j = 1; j < SCALE_BLOCK; j++)
  1333.         {
  1334.             pSamples += SBLIMIT;                // Passer à la bande suivante.
  1335.             d = fabs(*pSamples);
  1336.             if (ds < d) ds = d;
  1337.         }
  1338.  
  1339.         *pbScalar++ = GetIndex(ds);
  1340.     }
  1341. }
  1342.  
  1343. #endif
  1344. ///
  1345. /// CoderC::MixChannels()
  1346. /****** Class CoderC/MixChannels ********************************************
  1347. *
  1348. *   NAME
  1349. *   CoderC::MixChannels -- Mixe les canaux stéréo en un canal mono.
  1350. *
  1351. *   SYNOPSIS
  1352. *   CoderC::MixChannels()
  1353. *
  1354. *   void CoderC::MixChannels();
  1355. *
  1356. *   FUNCTION
  1357. *   Mélange les deux canaux stéréo en un canal mono (JOINTSTEREO)
  1358. *
  1359. *   NOTES
  1360. *   Le mixage s'effectue APRES le calcul des filtres. Il serait plus inter-
  1361. *   ressant (et plus rapide) de mixer les canaux stéréo AVANT de calculer
  1362. *   les filtres...
  1363. *
  1364. *   BUGS
  1365. *
  1366. *****************************************************************************
  1367. *
  1368. */
  1369.  
  1370.  
  1371. void CoderC::MixChannels(CoderC::T_SubBandSmplStereo *pSample, CoderC::T_SubBandSmplMono *pJSample)
  1372. {
  1373.     ULONG sb, smp, offset;
  1374.     REAL  *pSample0, *pSample1, *pJS;
  1375.     REAL  dOneHalf = 0.5;
  1376.  
  1377.     offset = SBLIMIT - enc_bSBLimit;        // Layer I : offset = 0
  1378.  
  1379.     // Initialiser les pointeurs temporaires.
  1380.  
  1381.     pJS      = &(*pJSample)[0][0];
  1382.     pSample0 = &(*pSample)[0][0][0];
  1383.     pSample1 = &(*pSample)[1][0][0];
  1384.  
  1385.     for (smp = 0; smp < SCALE_BLOCK; smp++)
  1386.     {
  1387.         for (sb = 0; sb < enc_bSBLimit; sb++)
  1388.         {
  1389.             *pJS++ = dOneHalf * (*pSample0++ + *pSample1++);
  1390.         }
  1391.         pJS      += offset;             // Adresser la "page" suivante.
  1392.         pSample0 += offset;             // (Le Layer II n'utilise pas toutes les pages)
  1393.         pSample1 += offset;
  1394.     }
  1395. }
  1396. ///
  1397. /// CoderC::MainBitAllocation()
  1398. /****** Class CoderC/MainBitAllocation **************************************
  1399. *
  1400. *   NAME
  1401. *   CoderC::MainBitAllocation -- Traiter l'encodage en Joint-Stéréo.
  1402. *
  1403. *   SYNOPSIS
  1404. *   CoderC::MainBitAllocation()
  1405. *
  1406. *   void CoderC::MainBitAllocation();
  1407. *
  1408. *   FUNCTION
  1409. *   Détermine quel mode Joint-Stéréo (parmis les 4) utiliser pour l'encodage.
  1410. *   S'il y a assez de bits pour encoder en stéréo pure, l'encodeur utilise ce
  1411. *   mode plutôt que le Joint-Stéréo.
  1412. *
  1413. *   NOTES
  1414. *
  1415. *   BUGS
  1416. *
  1417. *****************************************************************************
  1418. *
  1419. */
  1420.  
  1421.  
  1422. void CoderC::MainBitAllocation()
  1423. {
  1424.     enc_BSHeader.sBSHeader.bsh_Mode    = STEREO;
  1425.     enc_BSHeader.sBSHeader.bsh_ModeExt = 0;
  1426.     enc_bJSBound = enc_bSBLimit;
  1427.  
  1428.     if (BitsForNoNoise() > enc_iAvgDataBits)
  1429.     {
  1430.         ULONG mode_ext = 4;
  1431.         enc_BSHeader.sBSHeader.bsh_Mode = JOINTSTEREO;
  1432.  
  1433.         do
  1434.         {
  1435.             SetJSBound(--mode_ext);
  1436.         } while (BitsForNoNoise() > enc_iAvgDataBits && mode_ext > 0);
  1437.  
  1438.         enc_BSHeader.sBSHeader.bsh_ModeExt = mode_ext;
  1439.     }
  1440. }
  1441. ///
  1442. /// CoderC::UpdateCRC()  (ASM)
  1443. /****** Class CoderC/UpdateCRC **********************************************
  1444. *
  1445. *   NAME
  1446. *   CoderC::UpdateCRC -- Calcule la somme de contrôle.
  1447. *
  1448. *   SYNOPSIS
  1449. *   CoderC::UpdateCRC(iData, iLength)
  1450. *
  1451. *   void CoderC::UpdateCRC(ULONG, ULONG);
  1452. *
  1453. *   FUNCTION
  1454. *   Ajuste la somme de contrôle.
  1455. *
  1456. *   INPUTS
  1457. *   iData   - Donnée à prendre en charge.
  1458. *   iLength - Nombre de bits de cette donnée.
  1459. *
  1460. *   NOTES
  1461. *
  1462. *   BUGS
  1463. *
  1464. *****************************************************************************
  1465. *
  1466. */
  1467.  
  1468.  
  1469. #if _USE_ASM_FCT_ == 1 || _CPUMODEL_ == 68020
  1470.  
  1471. extern "C"{
  1472. UWORD UpdateCRC(register __d0 ULONG iData, register __d1 UWORD wLength, register __d2 UWORD wCRC);
  1473. }
  1474.  
  1475. inline void CoderC::UpdateCRC(ULONG iData, ULONG iLength)
  1476. {
  1477.     enc_wCRC = ::UpdateCRC(iData, iLength, enc_wCRC);
  1478. }
  1479.  
  1480. #else
  1481.  
  1482. void CoderC::UpdateCRC(ULONG iData, ULONG iLength)
  1483. {
  1484.     ULONG iMasking = 1 << iLength;
  1485.     ULONG iCarry;
  1486.  
  1487.     while (iMasking >>= 1)
  1488.     {
  1489.         iCarry = enc_wCRC & 0x8000;
  1490.         enc_wCRC *= 2;
  1491.         if (!iCarry ^ !(iData & iMasking)) enc_wCRC ^= 0x8005;
  1492.     }
  1493. }
  1494. #endif
  1495. ///
  1496. /// CoderC::CRC_Calc()
  1497. /****** Class CoderC/CRC_Calc ***********************************************
  1498. *
  1499. *   NAME
  1500. *   CoderC::CRC_Calc -- Calcule le CRC du bloc d'entête.
  1501. *
  1502. *   SYNOPSIS
  1503. *   CoderC::CRC_Calc()
  1504. *
  1505. *   void CoderC::CRC_Calc();
  1506. *
  1507. *   FUNCTION
  1508. *   Initialise la somme de contrôle avec les informations du bloc d'entête.
  1509. *
  1510. *   BUGS
  1511. *
  1512. *****************************************************************************
  1513. *
  1514. */
  1515.  
  1516.  
  1517. void CoderC::CRC_Calc()
  1518. {
  1519.     enc_wCRC = 0xFFFF;
  1520.  
  1521.     UpdateCRC(GetBitrateIndex() + 1, 4);
  1522.     UpdateCRC(GetSmplFrqIndex(), 2);
  1523.     UpdateCRC(enc_BSHeader.sBSHeader.bsh_Padding, 1);
  1524.     UpdateCRC(enc_BSHeader.sBSHeader.bsh_Extension, 1);
  1525.     UpdateCRC(enc_BSHeader.sBSHeader.bsh_Mode, 2);
  1526.     UpdateCRC(enc_BSHeader.sBSHeader.bsh_ModeExt, 2);
  1527.     UpdateCRC((ULONG) IsCopyrighted(), 1);
  1528.     UpdateCRC((ULONG) IsOriginal(), 1);
  1529.     UpdateCRC(GetDeemphasis(), 2);
  1530. }
  1531. ///
  1532. /// CoderC::PutBits()  (ASM)
  1533. /****** Class CoderC/PutBits ************************************************
  1534. *
  1535. *   NAME
  1536. *   CoderC::PutBits -- Placer un groupe de bits dans le tampon de sortie.
  1537. *
  1538. *   SYNOPSIS
  1539. *   CoderC::PutBits(iSource, iLength)
  1540. *
  1541. *   void CoderC::PutBits(ULONG, ULONG);
  1542. *
  1543. *   FUNCTION
  1544. *   Envoie le groupe de bits passé en argument vers le tampon de sortie.
  1545. *
  1546. *   INPUTS
  1547. *   iSource - Valeur à inscrire dans le tampon.
  1548. *   iLength - Nombre de bits significatifs.
  1549. *
  1550. *   BUGS
  1551. *   La fonction "SetBitField()" n'existe qu'en assembleur.
  1552. *
  1553. *****************************************************************************
  1554. *
  1555. */
  1556.  
  1557. #ifndef USE_QUICK_PUTBITS
  1558. #if _USE_ASM_FCT_ == 1 || _CPUMODEL_ == 68020
  1559. inline void CoderC::PutBits(ULONG iSource, ULONG iLength)
  1560. {
  1561.     PutBitsASM(&enc_sOutputStreamDatas, iSource, iLength);
  1562. }
  1563.  
  1564. #else
  1565.  
  1566. void CoderC::PutBits(ULONG source, ULONG length)
  1567. {
  1568.     UWORD *output     = (UWORD *) enc_sOutputStreamDatas.pOutputBuffer;
  1569.     ULONG bit_index   = enc_sOutputStreamDatas.iOB_BitIndex;
  1570.     LONG  bits_free   = enc_sOutputStreamDatas.iOB_BitsFree;
  1571.     ULONG offset      = bit_index >> 4;
  1572.     LONG  remaining_bits;
  1573.     ULONG bit_field;
  1574.  
  1575.     remaining_bits = 32 - (bit_index & 15) - length;        // E [1;31]
  1576.     bit_field      = (output[offset] * 65536) | (source << remaining_bits);
  1577.  
  1578.     output[offset] = bit_field >> 16;
  1579.     bits_free     -= length;
  1580.  
  1581.     // Si le tampon est plein, l'écrire sur disque.
  1582.  
  1583.     if (bits_free <= 0)
  1584.     {
  1585.         bits_free = enc_sOutputStreamDatas.iOB_TotalBits;
  1586.         enc_sOutputStreamDatas.iOB_BitIndex = bits_free;
  1587.  
  1588.         WriteBuffer();
  1589.  
  1590.         output[0] = bit_field;
  1591.  
  1592.         bit_index  = 16 - remaining_bits;
  1593.         bits_free -= bit_index;
  1594.     }
  1595.     else
  1596.     {
  1597.         output[offset + 1] = bit_field;
  1598.         bit_index += length;
  1599.     }
  1600.  
  1601.     enc_sOutputStreamDatas.iOB_BitIndex = bit_index;
  1602.     enc_sOutputStreamDatas.iOB_BitsFree = bits_free;
  1603. }
  1604. #endif
  1605. #endif  // USE_QUICK_PUTBITS
  1606. ///
  1607. /// CoderC::FillFrame()
  1608. void CoderC::FillFrame()
  1609. {
  1610.     while (enc_iAvgDataBits >= 16)
  1611.     {
  1612.         PutBits(0, 16);
  1613.         enc_iAvgDataBits -= 16;
  1614.     }
  1615.  
  1616.     if (enc_iAvgDataBits)
  1617.     {
  1618.         PutBits(0, enc_iAvgDataBits);
  1619.     }
  1620.  
  1621. #ifdef USE_QUICK_PUTBITS
  1622. #if _USE_ASM_FCT_ == 1 || _CPUMODEL_ == 68020
  1623.     PutBitsASM2(&enc_sOutputStreamDatas, &bit_buffer[0], BitBuffPtr);
  1624. #else
  1625.     register UWORD *output     = (UWORD *) enc_sOutputStreamDatas.pOutputBuffer;
  1626.     register UWORD *bitpos     = &bit_buffer[0];
  1627.  
  1628.     ULONG bit_index = enc_sOutputStreamDatas.iOB_BitIndex;
  1629.     LONG  bits_free = enc_sOutputStreamDatas.iOB_BitsFree;
  1630.     ULONG offset;
  1631.     LONG  remaining_bits;
  1632.     ULONG bit_field;
  1633.  
  1634.     while (bitpos < BitBuffPtr)
  1635.     {
  1636.         ULONG length = *bitpos++;
  1637.         offset = bit_index >> 4;
  1638.         remaining_bits = 32 - (bit_index & 15) - length;     // E [1;31]
  1639.         bit_field      = (output[offset] * 65536) | (*bitpos++ << remaining_bits);
  1640.  
  1641.         output[offset] = bit_field >> 16;
  1642.         bit_index += length;
  1643.         bits_free -= length;
  1644.  
  1645.         // Si le tampon est plein, l'écrire sur disque.
  1646.  
  1647.         if (bits_free <= 0)
  1648.         {
  1649.             bits_free = enc_sOutputStreamDatas.iOB_TotalBits;
  1650.             enc_sOutputStreamDatas.iOB_BitIndex = bits_free;
  1651.  
  1652.             WriteBuffer();
  1653.  
  1654.             output[0] = bit_field;
  1655.  
  1656.             bit_index  = 16 - remaining_bits;
  1657.             bits_free -= bit_index;
  1658.         }
  1659.         else
  1660.         {
  1661.             output[offset + 1] = bit_field;
  1662.         }
  1663.     }
  1664.     enc_sOutputStreamDatas.iOB_BitIndex = bit_index;
  1665.     enc_sOutputStreamDatas.iOB_BitsFree = bits_free;
  1666. #endif
  1667. #endif
  1668. }
  1669. ///
  1670.  
  1671. //----------------------------------------------------------------------------------------------------
  1672. //========================================= Classe CoderL1C ==========================================
  1673. //----------------------------------------------------------------------------------------------------
  1674.  
  1675. // Constructeur et destructeur.
  1676.  
  1677. /// CoderL1C::CoderL1C()
  1678. CoderL1C::CoderL1C(FileInfosC &roFileInfos) : CoderC(roFileInfos, 576 + 64)
  1679. {
  1680.     if (enc_iEncoderStatus == ESTAT_READY)
  1681.     {
  1682.         int iInitError;
  1683.  
  1684.         // Initialiser l'encodeur.
  1685.  
  1686.         InitSlotsPerFrame(FRAME_SIZE, 5);
  1687.  
  1688.         iInitError = !(enc_poPsychoC = new Psycho_L1C(*this));
  1689.  
  1690.         iInitError |= !(enc_pdSB_Samples = (T_SubBandSmplStereo *) AllocAlignedBuffer(sizeof(T_SubBandSmplStereo)));
  1691.         iInitError |= !(enc_pdJ_Samples =  (T_SubBandSmplMono *) AllocAlignedBuffer(sizeof(T_SubBandSmplMono)));
  1692.  
  1693.         // A l'initialisation de l'encodeur, la variable "mode_ext" est soit
  1694.         // non définie, soit nulle. Voir les sources d'origine pour plus ample
  1695.         // information.
  1696.  
  1697.         enc_BSHeader.sBSHeader.bsh_Layer = 3;
  1698.  
  1699.         if (GetEncodingMode() == JOINTSTEREO) SetJSBound(0);
  1700.         else                                  enc_bJSBound = enc_bSBLimit;
  1701.  
  1702.         if (iInitError != FALSE || enc_poPsychoC->CheckPsychoStatus() != FALSE)
  1703.         {
  1704.             SetErrorCodes(ESTAT_NOMEMORY, ERR_INTERNAL_BUFFERS);
  1705.         }
  1706.         else if (!enc_poPsychoC->InitPsychoAnalyzer(SBLIMIT))
  1707.         {
  1708.             SetErrorCodes(ESTAT_NOTSUPPORTED, ERR_BAD_FREQUENCY);
  1709.         }
  1710.     }
  1711. }
  1712. ///
  1713. /// CoderL1C::~CoderL1C()
  1714.  
  1715. CoderL1C::~CoderL1C()
  1716. {
  1717.     if (enc_pdSB_Samples)   FreeAlignedBuffer(enc_pdSB_Samples);
  1718.     if (enc_pdJ_Samples)    FreeAlignedBuffer(enc_pdJ_Samples);
  1719. }
  1720. ///
  1721.  
  1722. // Fonctions virtuelles.
  1723.  
  1724. /// CoderL1C::GetAudio()
  1725. /****** Class CoderL1C/GetAudio *********************************************
  1726. *
  1727. *   NAME
  1728. *   CoderL1C::GetAudio -- Préparer l'analyse de la page suivante.
  1729. *
  1730. *   SYNOPSIS
  1731. *   Result = CoderL1C::GetAudio()
  1732. *
  1733. *   bool CoderL1C::GetAudio();
  1734. *
  1735. *   FUNCTION
  1736. *   Prépare l'analyse de la page suivante.
  1737. *
  1738. *   RESULT
  1739. *   Result - FALSE en cas d'erreur.
  1740. *
  1741. *   NOTES
  1742. *   Du fait que la fonction SubBandCoding() exploite les échantillons direc-
  1743. *   tement dans le tampon de lecture, le pointeur d'accès doit être adapté en
  1744. *   conséquence.
  1745. *   Même chose en ce qui concerne l'analyseur psycho-acoustique.
  1746. *
  1747. *   BUGS
  1748. *
  1749. *   SEE ALSO
  1750. *   CoderC::SubBandCoding_Stereo(), CoderC::SubBandCoding_Mono()
  1751. *
  1752. *****************************************************************************
  1753. *
  1754. */
  1755.  
  1756.  
  1757. int CoderL1C::GetAudio()
  1758. {
  1759.     int success;
  1760.     ULONG iOffset1 = 576 + 64;
  1761.     ULONG iOffset2 = 64 + 480;
  1762.  
  1763.     if (enc_bStereo == 2)
  1764.     {
  1765.         iOffset1 += iOffset1;
  1766.         iOffset2 += iOffset2;
  1767.     }
  1768.  
  1769.     if ( (success = CoderC::GetAudio()) )
  1770.     {
  1771.         enc_pwSampleBuffer= enc_pSamples - iOffset1;
  1772.         enc_pSB_ActualPtr = enc_pSamples - iOffset2;
  1773.     }
  1774.  
  1775.     return success;
  1776. }
  1777. ///
  1778. /// CoderL1C::BitsForNoNoise
  1779. /****** Class CoderL1C/BitsForNoNoise ***************************************
  1780. *
  1781. *   NAME
  1782. *   CoderL1C::BitsForNoNoise --
  1783. *
  1784. *   SYNOPSIS
  1785. *   NumBits = CoderL1C::BitsForNoNoise()
  1786. *
  1787. *   ULONG CoderL1C::BitsForNoNoise();
  1788. *
  1789. *   FUNCTION
  1790. *   Calcule le nombre de bits nécessaires à l'encodage des données avec les
  1791. *   réglages courants.
  1792. *
  1793. *   RESULT
  1794. *   NumBits - Nombre de bits nécessaires pour l'encodage.
  1795. *
  1796. *   NOTES
  1797. *   Cette fonction n'est appelée qu'en mode JOINT_STEREO. Par consequent,
  1798. *   il y a toujours 2 canaux à traiter.
  1799. *   La fonction a été modifiée en conséquence.
  1800. *
  1801. *   BUGS
  1802. *   A l'inverse des autres fonctions d'allocation, celle-ci n'alloue pas 16
  1803. *   bits supplémentaires lorsqu'on encode avec le CRC.
  1804. *   Ce n'est peut-être pas normal...
  1805. *
  1806. *****************************************************************************
  1807. *
  1808. */
  1809.  
  1810.  
  1811. ULONG CoderL1C::BitsForNoNoise()
  1812. {
  1813.     const ULONG REQBITS = 32 + SBLIMIT * 4;
  1814.  
  1815.     ULONG i, j, k;
  1816.     ULONG jsbound  = enc_bJSBound;
  1817.     ULONG req_bits = REQBITS + (jsbound * 4);
  1818.  
  1819.     LONG LTMin;
  1820.  
  1821.     for (i = 0; i < jsbound; i++)
  1822.     {
  1823.         for (j = 0; j < 2; j++)
  1824.         {
  1825.             for (k = 0, LTMin = enc_LTMin[j][i]; snr[k] < LTMin && k < 14; k++) ;
  1826.  
  1827.             if (k) req_bits += 6 * (k + k + 3);             // NB : (k + 1) × SCALE_BLOCK + 6 = 6 × (2k + 3)
  1828.         }
  1829.     }
  1830.  
  1831.     LONG *p1 = &enc_LTMin[0][i];
  1832.     LONG *p2 = &enc_LTMin[1][i];
  1833.  
  1834.     for ( /*i = jsbound,*/ ; i < SBLIMIT; i++)
  1835.     {
  1836.         for (k = 0, LTMin = *p1; snr[k] < LTMin && k < 14; k++) ;
  1837.         for (       LTMin = *p2; snr[k] < LTMin && k < 14; k++) ;
  1838.  
  1839.         ++p1; ++p2;
  1840.  
  1841.         if (k) req_bits += 6 * (k + k + 4);                 // NB : (k + 1) × SCALE_BLOCK + 12 = 6 × (2k + 4)
  1842.     }
  1843.  
  1844.     return req_bits;
  1845. }
  1846. ///
  1847. /// CoderL1C::OneBitAllocation()
  1848. /****** Class CoderL1C/OneBitAllocation *************************************
  1849. *
  1850. *   NAME
  1851. *   CoderL1C::OneBitAllocation --
  1852. *
  1853. *   SYNOPSIS
  1854. *   CoderL1C::OneBitAllocation()
  1855. *
  1856. *   void CoderL1C::OneBitAllocation();
  1857. *
  1858. *   FUNCTION
  1859. *   Adapte le nombre de bits nécessaire à l'encodage des données, bit à bit,
  1860. *   en augmentant progressivement la qualité jusqu'à ce que le nombre de bits
  1861. *   libres soit insuffisant.
  1862. *
  1863. *   BUGS
  1864. *
  1865. *****************************************************************************
  1866. *
  1867. */
  1868.  
  1869.  
  1870. void CoderL1C::OneBitAllocation()
  1871. {
  1872.     ULONG numbits, offset;
  1873.     LONG  min_sb, min_ch;
  1874.     UBYTE *pBitAlloc;
  1875.  
  1876.     UBYTE used[2 * SBLIMIT];
  1877.  
  1878.     LONG  MinNR[2 * SBLIMIT];
  1879.     LONG *pLTMin;
  1880.  
  1881.     enc_iAvgDataBits -= enc_iMinNeededBits + 4 * (SBLIMIT + ( (enc_bStereo == 2) ? enc_bJSBound : 0) );
  1882.  
  1883.     // Initialiser les tables intermédiaires.
  1884.  
  1885.     {
  1886.         LONG *pMNR;
  1887.         UBYTE *pUsed;
  1888.  
  1889.         pMNR      = &MinNR[0];
  1890.         pLTMin    = &enc_LTMin[0][0];
  1891.         pUsed     = &used[0];
  1892.         pBitAlloc = &enc_bBitAlloc[0][0];
  1893.  
  1894.         for (min_ch = enc_bStereo; min_ch > 0; min_ch--)
  1895.         {
  1896.             for (min_sb = SBLIMIT; min_sb > 0; min_sb--)
  1897.             {
  1898.                 *pMNR++      = - *pLTMin++;
  1899.                 *pUsed++     = 0;
  1900.                 *pBitAlloc++ = 0;
  1901.             }
  1902.         }
  1903.     }
  1904.  
  1905.     // Localiser la sous-bande ayant le SMR minimum.
  1906.  
  1907.     numbits = 0;
  1908.  
  1909.     do
  1910.     {
  1911.         min_sb = -1;
  1912.  
  1913.         {
  1914.             LONG i, k;
  1915.             LONG small  = MinNR[0] + 1;
  1916.  
  1917.             for (k = enc_bStereo - 1; k >= 0; --k)
  1918.             {
  1919.                 for (i = SBLIMIT, offset = k * SBLIMIT; i > 0; --i, ++offset)
  1920.                 {
  1921.                     if (small > MinNR[offset] && used[offset] != 2)
  1922.                     {
  1923.                         small  = MinNR[offset];
  1924.                         min_sb = SBLIMIT - i;
  1925.                         min_ch = k;
  1926.                     }
  1927.                 }
  1928.             }
  1929.         }
  1930.  
  1931.         if (min_sb >= 0)
  1932.         {
  1933.             ULONG smpl_bits;
  1934.  
  1935.             offset = (min_ch * SBLIMIT) + min_sb;
  1936.  
  1937.             pLTMin    = &enc_LTMin[0][0];
  1938.             pBitAlloc = &enc_bBitAlloc[0][0];
  1939.  
  1940.             if (used[offset])
  1941.             {
  1942.                 smpl_bits  = SCALE_BLOCK;
  1943.             }
  1944.             else
  1945.             {
  1946.                 smpl_bits  = 24 + 6;
  1947.  
  1948.                 if (min_sb >= enc_bJSBound && enc_bStereo == 2)
  1949.                 {
  1950.                     smpl_bits = 24 + 12;
  1951.                 }
  1952.             }
  1953.  
  1954.             smpl_bits += numbits;
  1955.  
  1956.             if (enc_iAvgDataBits >= smpl_bits)
  1957.             {
  1958.                 numbits = smpl_bits;
  1959.                 pBitAlloc[offset]++;
  1960.                 used[offset] = 1;
  1961.                 MinNR[offset] = snr[pBitAlloc[offset]] - pLTMin[offset];
  1962.  
  1963.                 if (pBitAlloc[offset] == 14) used[offset] = 2;
  1964.             }
  1965.             else used[offset] = 2;
  1966.  
  1967.             if (min_sb >= enc_bJSBound && enc_bStereo == 2)
  1968.             {
  1969.                 ULONG oth_ch = SBLIMIT - (min_ch * SBLIMIT) + min_sb;
  1970.  
  1971.                 pBitAlloc[oth_ch] = pBitAlloc[offset];
  1972.                 used[oth_ch]      = used[offset];
  1973.                 MinNR[oth_ch]     = snr[pBitAlloc[offset]] - pLTMin[oth_ch];
  1974.             }
  1975.         }
  1976.  
  1977.     } while (min_sb >= 0);
  1978.  
  1979.     enc_iAvgDataBits -= numbits;
  1980. }
  1981. ///
  1982. /// CoderL1C::Encode()
  1983. /****** Class CoderL1C/Encode ***********************************************
  1984. *
  1985. *   NAME
  1986. *   CoderL1C::Encode -- Fonction d'encodage principale.
  1987. *
  1988. *   SYNOPSIS
  1989. *   Success = CoderL1C::Encode()
  1990. *
  1991. *   bool CoderL1C::Encode();
  1992. *
  1993. *   FUNCTION
  1994. *   Cette fonction appelle toutes les autres fonctions nécessaires pour
  1995. *   encoder la portion actuelle du tampon d'entrée.
  1996. *
  1997. *   RESULT
  1998. *   Success - FALSE en cas d'erreur.
  1999. *
  2000. *   NOTES
  2001. *
  2002. *   BUGS
  2003. *
  2004. *****************************************************************************
  2005. *
  2006. */
  2007.  
  2008.  
  2009. int CoderL1C::Encode()
  2010. {
  2011.     enc_poPsychoC->PsychoAnal(enc_LTMin);
  2012.     EncodeSubBand();
  2013.  
  2014.     if (GetEncodingMode() == JOINTSTEREO)
  2015.     {
  2016.         MainBitAllocation();
  2017.     }
  2018.  
  2019.     OneBitAllocation();
  2020.  
  2021. #ifdef USE_QUICK_PUTBITS
  2022.     InitBitBuffer();
  2023. #endif
  2024.  
  2025.     PutBits(enc_BSHeader.iBSHeader >> 16, 16);
  2026.     PutBits(enc_BSHeader.iBSHeader & 0xFFFF, 16);
  2027.  
  2028.     if (IsCRC())
  2029.     {
  2030.         CRC_Calc();
  2031.         PutBits(enc_wCRC, 16);                      // encode_CRC()
  2032.     }
  2033.  
  2034.     EncodeScale();
  2035.     EncodeSamples();
  2036.     FillFrame();
  2037.  
  2038.     return (enc_iEncoderStatus == ESTAT_READY);
  2039. }
  2040. ///
  2041.  
  2042. // Fonctions de gestion
  2043.  
  2044. /// CoderL1C::EncodeSubBand()
  2045. void CoderL1C::EncodeSubBand()
  2046. {
  2047.     if (enc_bStereo == 2)   SubBandCoding_Stereo(enc_pdSB_Samples);
  2048.     else                    SubBandCoding_Mono( (T_SubBandSmplMono *) enc_pdSB_Samples);
  2049.  
  2050.     ScaleFactor(&enc_bScalar, enc_pdSB_Samples);
  2051.  
  2052.     if (GetEncodingMode() == JOINTSTEREO)
  2053.     {
  2054.         MixChannels(enc_pdSB_Samples, enc_pdJ_Samples);
  2055.         ScaleFactorCalc(&enc_bJScale[0], enc_pdJ_Samples);
  2056.     }
  2057. }
  2058. ///
  2059. /// CoderL1C::CRC_Calc()
  2060. /****** Class CoderL1C/CRC_Calc *********************************************
  2061. *
  2062. *   NAME
  2063. *   CoderL1C::CRC_Calc -- Ajuste la somme de contrôle.
  2064. *
  2065. *   SYNOPSIS
  2066. *   CoderL1C::CRC_Calc()
  2067. *
  2068. *   void CoderL1C::CRC_Calc();
  2069. *
  2070. *   FUNCTION
  2071. *   Initialise la somme de contrôle avec les données de l'entête et la table
  2072. *   d'allocation des bits.
  2073. *
  2074. *   BUGS
  2075. *
  2076. *****************************************************************************
  2077. *
  2078. */
  2079.  
  2080.  
  2081. void CoderL1C::CRC_Calc()
  2082. {
  2083.     int   i;
  2084.     ULONG stereo  = enc_bStereo - 1;
  2085.     ULONG jsbound = enc_bJSBound;
  2086.  
  2087.     UBYTE *pBitAlloc = &enc_bBitAlloc[0][0];
  2088.  
  2089.     CoderC::CRC_Calc();
  2090.  
  2091.     for (i = 0; i < SBLIMIT; i++)
  2092.     {
  2093.         UpdateCRC(*pBitAlloc, 4);
  2094.  
  2095.         if (stereo && (i < jsbound))
  2096.             UpdateCRC(pBitAlloc[SBLIMIT], 4);
  2097.  
  2098.          ++pBitAlloc;
  2099.     }
  2100. }
  2101. ///
  2102. /// CoderL1C::EncodeScale()
  2103. /****** Class CoderL1C/EncodeScale ******************************************
  2104. *
  2105. *   NAME
  2106. *   CoderL1C::EncodeScale -- Encoder les informations de gestion.
  2107. *
  2108. *   SYNOPSIS
  2109. *   CoderL1C::EncodeScale()
  2110. *
  2111. *   void CoderL1C::EncodeScale();
  2112. *
  2113. *   FUNCTION
  2114. *   Encode les informations de gestion et les envoie dans le tampon de sortie
  2115. *
  2116. *   NOTES
  2117. *   Cumule les fonctions "encode_bit_alloc()" et "encode_scale()"
  2118. *
  2119. *   BUGS
  2120. *
  2121. *****************************************************************************
  2122. *
  2123. */
  2124.  
  2125.  
  2126. void CoderL1C::EncodeScale()
  2127. {
  2128.     int     i;
  2129.     UBYTE   *pBitAlloc = &enc_bBitAlloc[0][0];
  2130.     UBYTE   *pScalar   = &enc_bScalar[0][0];
  2131.     ULONG   stereo  = enc_bStereo - 1;
  2132.     ULONG   jsbound = enc_bJSBound;
  2133.  
  2134.     // encode_bit_alloc()
  2135.  
  2136.     for (i = 0; i < SBLIMIT; i++)
  2137.     {
  2138.         PutBits(*pBitAlloc, 4);
  2139.  
  2140.         if (stereo && (i < jsbound))
  2141.             PutBits(pBitAlloc[SBLIMIT], 4);
  2142.  
  2143.         ++pBitAlloc;
  2144.     }
  2145.  
  2146.     pBitAlloc = &enc_bBitAlloc[0][0];
  2147.  
  2148.     // encode_scale()
  2149.  
  2150.     for (i = 0; i < SBLIMIT; i++)
  2151.     {
  2152.         if (*pBitAlloc)                   PutBits(*pScalar, 6);
  2153.         if (stereo && pBitAlloc[SBLIMIT]) PutBits(pScalar[SBLIMIT], 6);
  2154.  
  2155.         ++pBitAlloc; ++pScalar;
  2156.     }
  2157. }
  2158. ///
  2159. /// CoderL1C::EncodeSamples()
  2160. /****** Class CoderL1C/EncodeSamples ****************************************
  2161. *
  2162. *   NAME
  2163. *   CoderL1C::EncodeSamples -- Encode les échantillons.
  2164. *
  2165. *   SYNOPSIS
  2166. *   CoderL1C::EncodeSamples()
  2167. *
  2168. *   void CoderL1C::EncodeSamples();
  2169. *
  2170. *   FUNCTION
  2171. *   Encode les échantillons et les envoies dans le tampon de sortie.
  2172. *
  2173. *   NOTES
  2174. *
  2175. *   BUGS
  2176. *
  2177. *****************************************************************************
  2178. *
  2179. */
  2180.  
  2181.  
  2182. void CoderL1C::EncodeSamples()
  2183. {
  2184.     int     i, j, k, n;
  2185.     ULONG   jsbound = enc_bJSBound;
  2186.     ULONG   sign;
  2187.     double  d;
  2188.     double  one = 1.0;
  2189.  
  2190.     UBYTE *pBitAlloc;
  2191.     UBYTE *pJScale;
  2192.     UBYTE *pSScale;
  2193.  
  2194.     REAL  *pSSamples = &(*enc_pdSB_Samples)[0][0][0];
  2195.     REAL  *pJSamples = &(*enc_pdJ_Samples)[0][0];
  2196.  
  2197.     for (j = 0; j < SCALE_BLOCK; j++)
  2198.     {
  2199.         pBitAlloc = &enc_bBitAlloc[0][0];
  2200.         pJScale   = &enc_bJScale[0];
  2201.         pSScale   = &enc_bScalar[0][0];
  2202.  
  2203.         for (i = 0; i < SBLIMIT; i++)
  2204.         {
  2205.             for (k = 0; k < ( (i < jsbound) ? (enc_bStereo * SBLIMIT) : SBLIMIT); k += SBLIMIT)
  2206.             {
  2207.                 if ( (n = pBitAlloc[k]) )
  2208.                 {
  2209.                     if (i >= jsbound && enc_bStereo == 2)
  2210.                     {
  2211.                         d = *pJSamples * enc_adMultiples[*pJScale];
  2212.                     }
  2213.                     else
  2214.                     {
  2215.                         d = pSSamples[k * SCALE_BLOCK] * enc_adMultiples[pSScale[k]];
  2216.                     }
  2217.  
  2218.                     d = (d + one) * quant_a[n - 1];
  2219.                     n = 1 << n;
  2220.  
  2221.                     if (d < one)
  2222.                     {
  2223.                         sign = 0;
  2224.                     }
  2225.                     else
  2226.                     {
  2227.                         sign = n;
  2228.                         d -= one;
  2229.                     }
  2230.  
  2231.                 #ifndef USE_OLD_MATHLIB
  2232.                     n = ( (ULONG) (d * n) ) | sign;
  2233.                 #else
  2234.                     n = ( (ULONG) floor(d * n) ) | sign;
  2235.                 #endif
  2236.  
  2237.                     PutBits(n, pBitAlloc[k] + 1);
  2238.                 }
  2239.             }
  2240.             ++pBitAlloc; ++pJSamples; ++pSSamples; ++pJScale; ++pSScale;
  2241.         }
  2242.     }
  2243. }
  2244. ///
  2245.  
  2246.  
  2247. //----------------------------------------------------------------------------------------------------
  2248. //========================================= Classe CoderL2C ==========================================
  2249. //----------------------------------------------------------------------------------------------------
  2250.  
  2251. // Constructeur et destructeur.
  2252.  
  2253. /// CoderL2C::CoderL2C()
  2254. CoderL2C::CoderL2C(FileInfosC &roFileInfos) : CoderC(roFileInfos, 480)
  2255. {
  2256.     if (enc_iEncoderStatus == ESTAT_READY)
  2257.     {
  2258.         int iInitError;
  2259.  
  2260.         // Initialiser l'encodeur.
  2261.  
  2262.         InitSlotsPerFrame(BIGGEST_FRAME, 3);
  2263.  
  2264.         // Allouer les tampons.
  2265.  
  2266.         iInitError = !(enc_poPsychoC = new Psycho_L2C(*this));
  2267.  
  2268.         iInitError |= !(enc_pdSB_Samples = (T_SB_Samples *) AllocAlignedBuffer(sizeof(T_SB_Samples)));
  2269.         iInitError |= !(enc_pdJ_Samples =  (T_J_Samples *) AllocAlignedBuffer(sizeof(T_J_Samples)));
  2270.         iInitError |= !(enc_psAllocTable = (T_AllocTable *) AllocBuffer(sizeof(T_AllocTable)));
  2271.  
  2272.         // Terminer l'initialisation de l'encodeur.
  2273.  
  2274.         enc_BSHeader.sBSHeader.bsh_Layer = 2;
  2275.  
  2276.         if (!iInitError && !enc_poPsychoC->CheckPsychoStatus())
  2277.         {
  2278.             // Sélectionner le numéro de la table "Alloc_x" en fonction de la fréquence
  2279.             // d'échantillonage et du taux de sortie.
  2280.  
  2281.             UWORD   iSampleFreq = GetSampleFreq();
  2282.             UWORD   iBitRate    = GetBitRate();
  2283.             UWORD   iTable;
  2284.  
  2285.             if (enc_bStereo == 2) iBitRate >>= 1;   // Taux de sortie par canal.
  2286.  
  2287.             if ( iBitRate >= 56 && (iSampleFreq == 48000 || iBitRate <= 80) )   iTable = 0;
  2288.             else if (iSampleFreq != 48000 && iBitRate >= 96)                    iTable = 1;
  2289.             else if (iSampleFreq != 32000 && iBitRate <= 48)                    iTable = 2;
  2290.             else                                                                iTable = 3;
  2291.  
  2292.             enc_bSBLimit = InitAllocTables(enc_psAllocTable, iTable);
  2293.  
  2294.             // A l'initialisation de l'encodeur, la variable "mode_ext" est soit
  2295.             // non définie, soit nulle. Voir les sources d'origine pour plus ample
  2296.             // information.
  2297.  
  2298.             if (GetEncodingMode() == JOINTSTEREO) SetJSBound(0);
  2299.             else                                  enc_bJSBound = enc_bSBLimit;
  2300.  
  2301.             if (!enc_poPsychoC->InitPsychoAnalyzer(enc_bSBLimit))
  2302.                 SetErrorCodes(ESTAT_NOTSUPPORTED, ERR_BAD_FREQUENCY);
  2303.         }
  2304.         else SetErrorCodes(ESTAT_NOMEMORY, ERR_INTERNAL_BUFFERS);
  2305.     }
  2306. }
  2307. ///
  2308. /// CoderL2C::~CoderL2C()
  2309. CoderL2C::~CoderL2C()
  2310. {
  2311.     if (enc_pdSB_Samples)   FreeAlignedBuffer(enc_pdSB_Samples);
  2312.     if (enc_pdJ_Samples)    FreeAlignedBuffer(enc_pdJ_Samples);
  2313.     if (enc_psAllocTable)   FreeBuffer(enc_psAllocTable);
  2314. }
  2315. ///
  2316.  
  2317. // Fonctions virtuelles.
  2318.  
  2319. /// CoderL2C::GetAudio()
  2320. /****** Class CoderL2C/GetAudio *********************************************
  2321. *
  2322. *   NAME
  2323. *   CoderL2C::GetAudio -- Préparer l'analyse de la page suivante.
  2324. *
  2325. *   SYNOPSIS
  2326. *   Result = CoderL2C::GetAudio()
  2327. *
  2328. *   bool CoderL2C::GetAudio();
  2329. *
  2330. *   FUNCTION
  2331. *   Prépare l'analyse de la page suivante.
  2332. *
  2333. *   RESULT
  2334. *   Result - FALSE en cas d'erreur.
  2335. *
  2336. *   NOTES
  2337. *   Du fait que la fonction SubBandCoding() exploite les échantillons direc-
  2338. *   tement dans le tampon de lecture, le pointeur d'accès doit être adapté en
  2339. *   conséquence.
  2340. *   Même chose en ce qui concerne l'analyseur psycho-acoustique.
  2341. *
  2342. *   BUGS
  2343. *
  2344. *   SEE ALSO
  2345. *   CoderC::SubBandCoding_Stereo(), CoderC::SubBandCoding_Mono()
  2346. *
  2347. *****************************************************************************
  2348. *
  2349. */
  2350.  
  2351.  
  2352. int CoderL2C::GetAudio()
  2353. {
  2354.     int  success;
  2355.     ULONG iOffset;
  2356.  
  2357.     iOffset = (enc_bStereo == 2) ? 480 * 2 : 480;
  2358.  
  2359.     if ( (success = CoderC::GetAudio()) )
  2360.     {
  2361.         enc_pSB_ActualPtr = enc_pwSampleBuffer = enc_pSamples - iOffset;
  2362.     }
  2363.  
  2364.     return success;
  2365. }
  2366. ///
  2367. /// CoderL2C::BitsForNoNoise()
  2368. /****** Class CoderL2C/BitsForNoNoise ***************************************
  2369. *
  2370. *   NAME
  2371. *   CoderL2C::BitsForNoNoise --
  2372. *
  2373. *   SYNOPSIS
  2374. *   NumBits = CoderL2C::BitsForNoNoise()
  2375. *
  2376. *   ULONG CoderL2C::BitsForNoNoise();
  2377. *
  2378. *   FUNCTION
  2379. *   Calcule le nombre de bits nécessaires pour encoder les données avec les
  2380. *   réglages courants.
  2381. *
  2382. *   RESULT
  2383. *   NumBits - Nombre de bits nécessaires.
  2384. *
  2385. *   NOTES
  2386. *   Cette fonction n'est appelée qu'en mode JOINT_STEREO. Par consequent,
  2387. *   il y a toujours 2 canaux à traiter.
  2388. *   La fonction a été modifiée en conséquence.
  2389. *
  2390. *   BUGS
  2391. *
  2392. *****************************************************************************
  2393. *
  2394. */
  2395.  
  2396.  
  2397. ULONG CoderL2C::BitsForNoNoise()
  2398. {
  2399.     ULONG sb, ch, ba;
  2400.     ULONG jsbound = enc_bJSBound;
  2401.     ULONG req_bits;
  2402.     LONG  maxAlloc;
  2403.     s_SBAlloc  *pAlloc;
  2404.     LONG LTMin;
  2405.  
  2406.     req_bits = 0;
  2407.  
  2408.     for (sb = 0; sb < jsbound; sb++)
  2409.     {
  2410.         req_bits += (*enc_psAllocTable)[sb][0].bBits;
  2411.     }
  2412.  
  2413.     req_bits += req_bits;
  2414.  
  2415.     for ( ; sb < enc_bSBLimit; sb++)
  2416.     {
  2417.         req_bits += (*enc_psAllocTable)[sb][0].bBits;
  2418.     }
  2419.  
  2420.     req_bits += enc_iMinNeededBits;
  2421.  
  2422.     for (sb = 0; sb < jsbound; sb++)
  2423.     {
  2424.         for (ch = 0; ch < 2; ch++)
  2425.         {
  2426.             pAlloc = &(*enc_psAllocTable)[sb][0];
  2427.             maxAlloc = pAlloc->iBitMask - 2;
  2428.  
  2429.             for (ba = 0, LTMin = enc_LTMin[ch][sb]; snr[pAlloc->wQuant + (ba ? 1 : 0)] < LTMin && ba < maxAlloc; ba++, pAlloc++) ;
  2430.  
  2431.             if (ba)
  2432.             {
  2433.                 req_bits += pAlloc->iTotalBits + sfsPerScfsi[enc_bScaleFactorInfo[ch][sb]];
  2434.             }
  2435.         }
  2436.     }
  2437.  
  2438.     LONG *p1 = &enc_LTMin[0][sb];      // sb = jsbound
  2439.     LONG *p2 = &enc_LTMin[1][sb];
  2440.  
  2441.     for ( ; sb < enc_bSBLimit; sb++)
  2442.     {
  2443.         pAlloc = &(*enc_psAllocTable)[sb][0];
  2444.         maxAlloc = pAlloc->iBitMask - 2;
  2445.  
  2446.         for (ba = 0, LTMin = *p1; snr[pAlloc->wQuant + (ba ? 1 : 0)] < LTMin && ba < maxAlloc; ba++, pAlloc++) ;
  2447.         for (        LTMin = *p2; snr[pAlloc->wQuant + (ba ? 1 : 0)] < LTMin && ba < maxAlloc; ba++, pAlloc++) ;
  2448.  
  2449.         ++p1; ++p2;
  2450.  
  2451.         if (ba)
  2452.         {
  2453.             req_bits += pAlloc->iTotalBits + sfsPerScfsi[enc_bScaleFactorInfo[0][sb]] + sfsPerScfsi[enc_bScaleFactorInfo[1][sb]];
  2454.         }
  2455.     }
  2456.  
  2457.     return req_bits;
  2458. }
  2459. ///
  2460. /// CoderL2C::OneBitAllocation()
  2461. /****** Class CoderL2C/OneBitAllocation *************************************
  2462. *
  2463. *   NAME
  2464. *   CoderL2C::OneBitAllocation --
  2465. *
  2466. *   SYNOPSIS
  2467. *   CoderL2C::OneBitAllocation()
  2468. *
  2469. *   void CoderL2C::OneBitAllocation();
  2470. *
  2471. *   FUNCTION
  2472. *   Alloue un groupe de bits pour chacune des sous-bandes.
  2473. *   Le nombre de bit de chaque bande est incrémenté graduellement jusqu'à ce
  2474. *   qu'il n'y ait plus assez de bits libres.
  2475. *
  2476. *   NOTES
  2477. *
  2478. *   BUGS
  2479. *
  2480. *****************************************************************************
  2481. *
  2482. */
  2483.  
  2484.  
  2485. void CoderL2C::OneBitAllocation()
  2486. {
  2487.     ULONG numbits, offset;
  2488.     LONG  min_sb, min_ch;
  2489.  
  2490.     UBYTE used[2 * SBLIMIT];
  2491.     UBYTE *pBitAlloc;
  2492.  
  2493.     LONG MinNR[2 * SBLIMIT];
  2494.     s_SBAlloc *pAlloc;
  2495.  
  2496.     // Initialiser les tables intermédiaires.
  2497.  
  2498.     {
  2499.         LONG *pLTMin;
  2500.  
  2501.         pLTMin    = &enc_LTMin[0][0];
  2502.         pBitAlloc = &enc_bBitAlloc[0][0];
  2503.  
  2504.         for (min_ch = enc_bStereo - 1; min_ch >= 0; --min_ch)
  2505.         {
  2506.             for (min_sb = enc_bSBLimit, offset = min_ch * SBLIMIT; min_sb > 0; --min_sb, ++offset)
  2507.             {
  2508.                 MinNR[offset]     = - pLTMin[offset];
  2509.                 used[offset]      = 0;
  2510.                 pBitAlloc[offset] = 0;
  2511.             }
  2512.         }
  2513.     }
  2514.  
  2515.     // Calculer le nombre de bits nécessaire pour les tables de décodage.
  2516.  
  2517.     numbits = 0;
  2518.     pAlloc = &(*enc_psAllocTable)[0][0];
  2519.  
  2520.     for (min_sb = 0; min_sb < enc_bJSBound; ++min_sb)
  2521.     {
  2522.         // numbits += (*enc_psAllocTable)[min_sb][0].bBits;
  2523.         numbits += pAlloc->bBits;
  2524.         pAlloc  += MAX_ALLOC_COLS;
  2525.     }
  2526.  
  2527.     if (enc_bStereo == 2) numbits += numbits;
  2528.  
  2529.     for ( ; min_sb < enc_bSBLimit; ++min_sb)
  2530.     {
  2531.         // numbits += (*enc_psAllocTable)[min_sb][0].bBits;
  2532.         numbits += pAlloc->bBits;
  2533.         pAlloc  += MAX_ALLOC_COLS;
  2534.     }
  2535.  
  2536.     enc_iAvgDataBits -= numbits + enc_iMinNeededBits;
  2537.  
  2538.     // Localiser la sous-bande ayant le SMR minimum.
  2539.  
  2540.     numbits = 0;
  2541.  
  2542.     do
  2543.     {
  2544.         min_sb = -1;
  2545.  
  2546.         {
  2547.             LONG i, k;
  2548.             LONG small = 999999;
  2549.  
  2550.             for (k = enc_bStereo - 1; k >= 0; --k)
  2551.             {
  2552.                 offset = k * SBLIMIT;
  2553.  
  2554.                 for (i = enc_bSBLimit; i > 0; --i, ++offset)
  2555.                 {
  2556.                     if (small > MinNR[offset] && used[offset] != 2)
  2557.                     {
  2558.                         small  = MinNR[offset];
  2559.                         min_sb = enc_bSBLimit - i;
  2560.                         min_ch = k;
  2561.                     }
  2562.                 }
  2563.             }
  2564.         }
  2565.  
  2566.         if (min_sb >= 0)
  2567.         {
  2568.             LONG  oth_ch;
  2569.             ULONG ba, increment;
  2570.  
  2571.             LONG *pLTMin;
  2572.  
  2573.             offset = (min_ch * SBLIMIT);
  2574.             oth_ch = 32 - offset + min_sb;
  2575.             offset += min_sb;
  2576.  
  2577.             pBitAlloc = &enc_bBitAlloc[0][0];
  2578.             pAlloc    = &(*enc_psAllocTable)[min_sb][0];
  2579.             pLTMin    = &enc_LTMin[0][0];
  2580.  
  2581.             ba = pBitAlloc[offset];
  2582.             increment = pAlloc[ba + 1].iTotalBits;
  2583.  
  2584.             if (used[offset])
  2585.             {
  2586.                 increment -= pAlloc[ba].iTotalBits;
  2587.             }
  2588.             else
  2589.             {
  2590.                 UBYTE *pSCFSI = &enc_bScaleFactorInfo[0][0];
  2591.  
  2592.                 increment += sfsPerScfsi[pSCFSI[offset]];
  2593.  
  2594.                 if (min_sb >= enc_bJSBound && enc_bStereo == 2)
  2595.                 {
  2596.                     increment += sfsPerScfsi[pSCFSI[oth_ch]];
  2597.                 }
  2598.             }
  2599.  
  2600.             increment += numbits;
  2601.  
  2602.             if (enc_iAvgDataBits >= increment)
  2603.             {
  2604.                 ba = ++pBitAlloc[offset];
  2605.                 numbits = increment;
  2606.  
  2607.                 used[offset] = 1;
  2608.                 MinNR[offset] = snr[pAlloc[ba].wQuant + 1] - pLTMin[offset];
  2609.  
  2610.                 if (ba >= pAlloc[0].iBitMask) used[offset] = 2;
  2611.             }
  2612.             else used[offset] = 2;
  2613.  
  2614.             if (min_sb >= enc_bJSBound && enc_bStereo == 2)
  2615.             {
  2616.                 pBitAlloc[oth_ch] = ba;
  2617.                 used[oth_ch]      = used[offset];
  2618.                 MinNR[oth_ch]     = snr[pAlloc[ba].wQuant + 1] - pLTMin[oth_ch];
  2619.             }
  2620.         }
  2621.  
  2622.     } while (min_sb >= 0);
  2623.  
  2624.     enc_iAvgDataBits -= numbits;
  2625. }
  2626. ///
  2627. /// CoderL2C::Encode()
  2628. /****** Class CoderL2C/Encode ***********************************************
  2629. *
  2630. *   NAME
  2631. *   CoderL2C::Encode -- Fonction principale.
  2632. *
  2633. *   SYNOPSIS
  2634. *   success = CoderL2C::Encode()
  2635. *
  2636. *   bool CoderL2C::Encode();
  2637. *
  2638. *   FUNCTION
  2639. *   Cette fonction appelle toutes les fonctions nécessaires pour l'encodage
  2640. *   de la portion courante du tampon d'entrée.
  2641. *
  2642. *   RESULT
  2643. *   success - FALSE en cas d'erreur
  2644. *
  2645. *   BUGS
  2646. *
  2647. *****************************************************************************
  2648. *
  2649. */
  2650.  
  2651.  
  2652. int CoderL2C::Encode()
  2653. {
  2654.     enc_poPsychoC->PsychoAnal(enc_LTMin);
  2655.     EncodeSubBand();
  2656.  
  2657.     TransmissionPattern();
  2658.  
  2659.     if (GetEncodingMode() == JOINTSTEREO)
  2660.     {
  2661.         MainBitAllocation();
  2662.     }
  2663.  
  2664.     OneBitAllocation();
  2665.  
  2666. #ifdef USE_QUICK_PUTBITS
  2667.     InitBitBuffer();
  2668. #endif
  2669.  
  2670.     PutBits(enc_BSHeader.iBSHeader >> 16, 16);
  2671.     PutBits(enc_BSHeader.iBSHeader & 0xFFFF, 16);
  2672.  
  2673.     if (IsCRC())
  2674.     {
  2675.         CRC_Calc();
  2676.         PutBits(enc_wCRC, 16);                  // encode_CRC()
  2677.     }
  2678.  
  2679.     EncodeScale();
  2680.     EncodeSamples();
  2681.     FillFrame();
  2682.  
  2683.     return (enc_iEncoderStatus == ESTAT_READY);
  2684. }
  2685. ///
  2686.  
  2687. // Fonctions de gestion.
  2688.  
  2689. /// CoderL2C::EncodeSubBand()
  2690. void CoderL2C::EncodeSubBand()
  2691. {
  2692.     int iFrame;
  2693.  
  2694.     for (iFrame = 0; iFrame < 3; iFrame++)
  2695.     {
  2696.         T_SubBandSmplStereo *pSB_Samples = (T_SubBandSmplStereo *) &(*enc_pdSB_Samples)[iFrame][0][0][0];
  2697.         T_SubBandSmplMono   *pJ_Samples  = (T_SubBandSmplMono *)   &(*enc_pdJ_Samples)[iFrame][0][0];
  2698.  
  2699.         if (enc_bStereo == 2)   SubBandCoding_Stereo(pSB_Samples);
  2700.         else                    SubBandCoding_Mono( (T_SubBandSmplMono *) pSB_Samples);
  2701.  
  2702.         ScaleFactor( (T_ScaleStereo *) &enc_bScalar[iFrame][0][0], pSB_Samples);
  2703.  
  2704.         if (GetEncodingMode() == JOINTSTEREO)
  2705.         {
  2706.             MixChannels(pSB_Samples, pJ_Samples);
  2707.             ScaleFactorCalc(&enc_bJScale[iFrame][0], pJ_Samples);
  2708.         }
  2709.     }
  2710. }
  2711. ///
  2712. /// CoderL2C::InitAllocTables()
  2713. //----------------------------------------------------------------------------------------------------
  2714. //================================ Reconstruction des tables ALLOC_X =================================
  2715. //----------------------------------------------------------------------------------------------------
  2716. //
  2717. // TECHNIQUE :
  2718. //
  2719. //    Chacune des 4 tables contient 'L' lignes, 'L' étant donné par le tableau t_alloc_entries[].
  2720. //  Pour chacune de ces lignes, la table t_alloc_tables[][] donne l'index de la table de référence
  2721. //  à utiliser (t_ref_index[][]). Cette table de réference, associé au numéro de colonne, donne
  2722. //  l'index de la ligne d'information à entrer dans la table "alloc_x".
  2723. //
  2724. // => y = t_alloc_tables[x][line]
  2725. // => L = t_ref_index[y][col]
  2726. // => alloc_x[line][col] = t_ref_lines[L]
  2727.  
  2728. UBYTE CoderL2C::InitAllocTables(CoderL2C::T_AllocTable *paTable, UBYTE iTable)
  2729. {
  2730.     static const UBYTE a_bAllocEntries[] = {27, 30, 8, 12};
  2731.  
  2732.     // "Lignes" d'information utilisées.
  2733.                                                    // steps bits group quant
  2734.     static const struct s_InitTbl a_sRefLines[] = {  {    0,   2,    0,    0},    //  0
  2735.                                                      {    0,   3,    0,    0},    //  1
  2736.                                                      {    0,   4,    0,    0},    //  2
  2737.                                                      {    3,   5,    1,    0},    //  3
  2738.                                                      {    5,   7,    1,    1},    //  4
  2739.                                                      {    7,   3,    3,    2},    //  5
  2740.                                                      {    9,  10,    1,    3},    //  6
  2741.                                                      {   15,   4,    3,    4},    //  7
  2742.                                                      {   31,   5,    3,    5},    //  8
  2743.                                                      {   63,   6,    3,    6},    //  9
  2744.                                                      {  127,   7,    3,    7},    // 10
  2745.                                                      {  255,   8,    3,    8},    // 11
  2746.                                                      {  511,   9,    3,    9},    // 12
  2747.                                                      { 1023,  10,    3,   10},    // 13
  2748.                                                      { 2047,  11,    3,   11},    // 14
  2749.                                                      { 4095,  12,    3,   12},    // 15
  2750.                                                      { 8191,  13,    3,   13},    // 16
  2751.                                                      {16383,  14,    3,   14},    // 17
  2752.                                                      {32767,  15,    3,   15},    // 18
  2753.                                                      {65535,  16,    3,   16},    // 19
  2754.                                                   };
  2755.  
  2756.  
  2757.     // Index, pour chaque table de référence, des lignes à utiliser.
  2758.  
  2759.     static const UBYTE a_bRefIdx[][MAX_ALLOC_COLS] = {
  2760.                                               {2, 3, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19},   // 0
  2761.                                               {2, 3, 4, 5, 6, 7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 19},   // 1
  2762.                                               {1, 3, 4, 5, 6, 7,  8, 19, },                                 // 2
  2763.                                               {0, 3, 4, 19, },                                              // 3
  2764.                                               {2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18},    // 4
  2765.                                               {1, 3, 4, 6, 7, 8, 9, 10, },                                  // 5
  2766.                                             };
  2767.  
  2768.  
  2769.     // Index, pour chaque table, des tables de référence à utiliser.
  2770.     // Si les fonctions d'accès aux tables le permettent, il est possible de supprimer les tables
  2771.     // n° 0 et 2 en les remplaçant respectivement par les tables 1 et 3 (cela suppose que les fonctions
  2772.     // de gestion n'accèdent pas aux lignes non définies dans les tables d'origine).
  2773.  
  2774.     static const UBYTE a_bAllocTbl[][MAX_ALLOC_LINES] = {
  2775.                                                  {0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, },
  2776.                                                  {0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3},
  2777.                                                  {4, 4, 5, 5, 5, 5, 5, 5, },
  2778.                                                  {4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, },
  2779.                                                };
  2780.  
  2781.  
  2782.     UBYTE  bNumEntries = a_bAllocEntries[iTable];
  2783.     UBYTE  bLine, bSubTable, bCol, bEntry;
  2784.     struct s_SBAlloc *pTable;
  2785.  
  2786.     for (bLine = 0; bLine < bNumEntries; bLine++)
  2787.     {
  2788.         bSubTable = a_bAllocTbl[iTable][bLine];
  2789.  
  2790.         for (bCol = 0; bCol < MAX_ALLOC_COLS; bCol++)
  2791.         {
  2792.             bEntry = a_bRefIdx[bSubTable][bCol];
  2793.             pTable = & (*paTable)[bLine][bCol];
  2794.  
  2795.             // Initialiser la table.
  2796.             pTable->wSteps     = a_sRefLines[bEntry].wSteps;
  2797.             pTable->bBits      = a_sRefLines[bEntry].bBits;
  2798.             pTable->bGroup     = a_sRefLines[bEntry].bGroup;
  2799.             pTable->wQuant     = a_sRefLines[bEntry].bQuant;
  2800.  
  2801.             // Calculer des valeurs déduites des tables pour optimiser quelques fonctions.
  2802.  
  2803.             int n2 = 1;
  2804.             pTable->iTotalBits = SCALE_BLOCK * (pTable->bBits * pTable->bGroup);
  2805.             pTable->iBitMask   = (1 << pTable->bBits) - 1;
  2806.  
  2807.             while (n2 < pTable->wSteps && n2 < (1 << 16))
  2808.             {
  2809.                 n2 *= 2;
  2810.             }
  2811.  
  2812.             pTable->wStepMask = n2 >> 1;
  2813.  
  2814.             // bGroup ne sert que de drapeau (EncodeSamples())
  2815.  
  2816.             pTable->bGroup = (pTable->bGroup == 3) ? 1 : 0;
  2817.         }
  2818.     }
  2819.     return (bNumEntries);
  2820. }
  2821. ///
  2822. /// CoderL2C::TransmissionPattern()
  2823. /****** Class CoderL2C/TransmissionPattern **********************************
  2824. *
  2825. *   NAME
  2826. *   CoderL2C::TransmissionPattern -- Déterminer les sous-bandes utiles.
  2827. *
  2828. *   SYNOPSIS
  2829. *   CoderL2C::TransmissionPattern()
  2830. *
  2831. *   void CoderL2C::TransmissionPattern();
  2832. *
  2833. *   FUNCTION
  2834. *   Pour une sous-bande donnée, détermine s'il faut envoyer 1, 2 ou les 3
  2835. *   valeurs ScaleFactor[], puis initialise le tableau de sélection en accord
  2836. *   avec cette analyse.
  2837. *
  2838. *   BUGS
  2839. *
  2840. *****************************************************************************
  2841. *
  2842. *  13.09.98 : Modification des patterns [3][0], [4][0] et [4][4].
  2843. */
  2844.  
  2845. void CoderL2C::TransmissionPattern()
  2846. {
  2847.     int i, k;
  2848.     int class0, class1;
  2849.     UBYTE *scalar0, *scalar1, *scalar2;
  2850.     UBYTE *scfsi;
  2851.  
  2852.     // bits 0-2 : Masque. Un bit à 1 indique qu'il faut utiliser le facteur d'echelle.
  2853.     // bits 3-4 : Code scsfi.
  2854.  
  2855.     const int CODE0 = 0;    // Utiliser les trois facteurs d'echelle.
  2856.     const int CODE1 = 1;    // Utiliser deux fois le premier, puis le dernier.
  2857.     const int CODE2 = 2;    // Utiliser trois fois le même facteur d'echelle.
  2858.     const int CODE3 = 3;    // Utiliser le premier, puis deux fois le dernier.
  2859.  
  2860.     const int SC_1 =  4;
  2861.     const int SC_2 =  8;
  2862.     const int SC_3 = 16;
  2863.  
  2864.     const int SC_122 = CODE3 | SC_1 | SC_2;
  2865.     const int SC_133 = CODE3 | SC_1 | SC_3;
  2866.     const int SC_113 = CODE1 | SC_1 | SC_3;
  2867.     const int SC_223 = CODE1 | SC_2 | SC_3;
  2868.     const int SC_123 = CODE0 | SC_1 | SC_2 | SC_3;
  2869.     const int SC_111 = CODE2 | SC_1;
  2870.     const int SC_222 = CODE2 | SC_2;
  2871.     const int SC_333 = CODE2 | SC_3;
  2872.     const int SC_xxx = CODE2;           // Code spécial.
  2873.  
  2874.                             //  2 >> 3   2 > 3  2 == 3   2 < 3  2 << 3
  2875.     static UBYTE pattern[25] = {SC_123, SC_122, SC_122, SC_133, SC_123,     // 1 >> 2
  2876.                                 SC_113, SC_111, SC_111, SC_xxx, SC_113,     // 1 > 2
  2877.                                 SC_113, SC_111, SC_111, SC_333, SC_113,     // 1 == 2
  2878.                                 SC_223, SC_222, SC_222, SC_333, SC_223,     // 1 < 2
  2879.                                 SC_123, SC_122, SC_122, SC_133, SC_123};    // 1 << 2
  2880.  
  2881.     for (k = 0; k < enc_bStereo; k++)
  2882.     {
  2883.         scalar0 = &enc_bScalar[0][k][0];
  2884.         scalar1 = scalar0 + SBLIMIT * 2;
  2885.         scalar2 = scalar0 + SBLIMIT * 4;
  2886.  
  2887.         scfsi = &enc_bScaleFactorInfo[k][0];
  2888.  
  2889.         for (i = 0; i < enc_bSBLimit; i++)
  2890.         {
  2891.             class0 = *scalar0 - *scalar1;
  2892.             class1 = *scalar1 - *scalar2;
  2893.  
  2894.             if      (class0 <= -3)  class0 = 0 * 5;
  2895.             else if (class0 < 0)    class0 = 1 * 5;
  2896.             else if (class0 == 0)   class0 = 2 * 5;
  2897.             else if (class0 < 3)    class0 = 3 * 5;
  2898.             else                    class0 = 4 * 5;
  2899.  
  2900.             if (class1 > -3)
  2901.             {
  2902.                 if      (class1 < 0)    class0 += 1;
  2903.                 else if (class1 == 0)   class0 += 2;
  2904.                 else if (class1 < 3)    class0 += 3;
  2905.                 else                    class0 += 4;
  2906.             }
  2907.  
  2908.             class1   = pattern[class0];
  2909.             *scfsi++ = class0 = class1 & 3;
  2910.  
  2911.             // Mettre à jour les facteurs d'echelle (utilisés pour l'encodage des échantillons).
  2912.  
  2913.             if      (class0 == 1)       // 2x le premier, puis le dernier.
  2914.             {
  2915.                 if (class1 == SC_113)   *scalar1 = *scalar0;    // SC_113
  2916.                 else                    *scalar0 = *scalar1;    // SC_223
  2917.             }
  2918.             else if (class0 == 2)       // 3x le premier.
  2919.             {
  2920.                 if      (class1 == SC_111)      *scalar2 = *scalar1 = *scalar0;
  2921.                 else if (class1 == SC_222)      *scalar0 = *scalar2 = *scalar1;
  2922.                 else if (class1 == SC_333)      *scalar0 = *scalar1 = *scalar2;
  2923.                 else if (*scalar0 > *scalar2)   *scalar1 = *scalar0 = *scalar2;
  2924.                 else                            *scalar1 = *scalar2 = *scalar0;
  2925.             }
  2926.             else if (class0 == 3)       // 1x le premier, puis 2x le dernier.
  2927.             {
  2928.                 if (class1 == SC_122)   *scalar2 = *scalar1;    // SC_122
  2929.                 else                    *scalar1 = *scalar2;    // SC_133
  2930.             }
  2931.  
  2932.             ++scalar0; ++scalar1; ++scalar2;
  2933.         }
  2934.     }
  2935. }
  2936. ///
  2937. /// CoderL2C::CRC_Calc()
  2938. /****** Class CoderL2C/CRC_Calc *********************************************
  2939. *
  2940. *   NAME
  2941. *   CoderL2C::CRC_Calc -- Initialise la somme de contrôle.
  2942. *
  2943. *   SYNOPSIS
  2944. *   CoderL2C::CRC_Calc()
  2945. *
  2946. *   void CoderL2C::CRC_Calc();
  2947. *
  2948. *   FUNCTION
  2949. *   Initialise la somme de contrôle avec le bloc d'entête et les données de
  2950. *   gestion.
  2951. *
  2952. *   BUGS
  2953. *
  2954. *****************************************************************************
  2955. *
  2956. */
  2957.  
  2958.  
  2959. void CoderL2C::CRC_Calc()
  2960. {
  2961.     int   i;
  2962.     ULONG sblimit = enc_bSBLimit;
  2963.     ULONG jsbound = enc_bJSBound;
  2964.     ULONG stereo  = enc_bStereo - 1;
  2965.  
  2966.     UBYTE *pBitAlloc = &enc_bBitAlloc[0][0];
  2967.     UBYTE *pSCFSI    = &enc_bScaleFactorInfo[0][0];
  2968.  
  2969.     CoderC::CRC_Calc();
  2970.  
  2971.     for (i = 0; i < sblimit; i++)
  2972.     {
  2973.         ULONG bits = (*enc_psAllocTable)[i][0].bBits;
  2974.  
  2975.         UpdateCRC(*pBitAlloc, bits);
  2976.  
  2977.         if (stereo && (i < jsbound))
  2978.             UpdateCRC(pBitAlloc[SBLIMIT], bits);
  2979.  
  2980.         ++pBitAlloc;
  2981.     }
  2982.  
  2983.     pBitAlloc = &enc_bBitAlloc[0][0];
  2984.  
  2985.     for (i = 0; i < sblimit; i++)
  2986.     {
  2987.         if (*pBitAlloc)                     UpdateCRC(*pSCFSI, 2);
  2988.         if (stereo && pBitAlloc[SBLIMIT])   UpdateCRC(pSCFSI[SBLIMIT], 2);
  2989.         ++pSCFSI; ++pBitAlloc;
  2990.     }
  2991. }
  2992. ///
  2993. /// CoderL2C::EncodeScale()
  2994. /****** Class CoderL2C/EncodeScale ******************************************
  2995. *
  2996. *   NAME
  2997. *   CoderL2C::EncodeScale -- Encoder les données de gestion.
  2998. *
  2999. *   SYNOPSIS
  3000. *   CoderL2C::EncodeScale()
  3001. *
  3002. *   void CoderL2C::EncodeScale();
  3003. *
  3004. *   FUNCTION
  3005. *   Encode les données de gestion et les envoies dans le tampon de sortie.
  3006. *   NOTES
  3007. *   Cumule les fonctions "encode_bit_alloc()" et "encode_scale()"
  3008. *
  3009. *   BUGS
  3010. *
  3011. *****************************************************************************
  3012. *
  3013. */
  3014.  
  3015.  
  3016. void CoderL2C::EncodeScale()
  3017. {
  3018.     int     i, k;
  3019.     ULONG   stereo  = (enc_bStereo - 1) * SBLIMIT;
  3020.     ULONG   sblimit = enc_bSBLimit;
  3021.     ULONG   jsbound = enc_bJSBound;
  3022.  
  3023.     UBYTE *pBitAlloc = &enc_bBitAlloc[0][0];
  3024.  
  3025.     // encode_bit_alloc()
  3026.  
  3027.     {
  3028.         s_SBAlloc *pAlloc = &(*enc_psAllocTable)[0][0];
  3029.  
  3030.         for (i = 0; i < sblimit; i++)
  3031.         {
  3032.             k = pAlloc->bBits;
  3033.  
  3034.             PutBits(*pBitAlloc, k);
  3035.  
  3036.             if (stereo && (i < jsbound))
  3037.                 PutBits(pBitAlloc[SBLIMIT], k);
  3038.  
  3039.             ++pBitAlloc; pAlloc += MAX_ALLOC_COLS;
  3040.         }
  3041.     }
  3042.  
  3043.     // encode_scale()
  3044.  
  3045.     {
  3046.         UBYTE *pSCFSI    = &enc_bScaleFactorInfo[0][0];
  3047.         UBYTE *pScalar   = &enc_bScalar[0][0][0];
  3048.  
  3049.         pBitAlloc = &enc_bBitAlloc[0][0];
  3050.  
  3051.         for (i = 0; i < sblimit; i++)
  3052.         {
  3053.             for (k = 0; k <= stereo; k += SBLIMIT)
  3054.             {
  3055.                 if (pBitAlloc[k])  PutBits(pSCFSI[k], 2);
  3056.             }
  3057.             ++pBitAlloc; ++pSCFSI;
  3058.         }
  3059.  
  3060.         pSCFSI    = &enc_bScaleFactorInfo[0][0];
  3061.         pBitAlloc = &enc_bBitAlloc[0][0];
  3062.  
  3063.         for (i = 0; i < sblimit; i++)
  3064.         {
  3065.             for (k = 0; k <= stereo; k += SBLIMIT)
  3066.             {
  3067.                 if (pBitAlloc[k])
  3068.                 {
  3069.                     PutBits(pScalar[k], 6);
  3070.  
  3071.                     if (pSCFSI[k] == 0)
  3072.                     {
  3073.                         PutBits(pScalar[k + SBLIMIT * 2], 6);
  3074.                     }
  3075.  
  3076.                     if (pSCFSI[k] != 2)
  3077.                     {
  3078.                         PutBits(pScalar[k + SBLIMIT * 4], 6);
  3079.                     }
  3080.                 }
  3081.             }
  3082.             ++pSCFSI; ++pBitAlloc; ++pScalar;
  3083.         }
  3084.     }
  3085. }
  3086. ///
  3087. /// CoderL2C::EncodeSamples()
  3088. /****** Class CoderL2C/EncodeSamples ****************************************
  3089. *
  3090. *   NAME
  3091. *   CoderL2C::EncodeSamples -- Encoder les échantillons.
  3092. *
  3093. *   SYNOPSIS
  3094. *   CoderL2C::EncodeSamples()
  3095. *
  3096. *   void CoderL2C::EncodeSamples();
  3097. *
  3098. *   FUNCTION
  3099. *   Encode les échantillons et les envoies dans le tampon de sortie.
  3100. *
  3101. *   NOTES
  3102. *   Cumule les fonctions "subband_quantization()" et "sample_encoding()"
  3103. *
  3104. *   BUGS
  3105. *
  3106. *****************************************************************************
  3107. *
  3108. */
  3109.  
  3110.  
  3111. void CoderL2C::EncodeSamples()
  3112. {
  3113.     int    f, i, j, k, n, n2, j2;
  3114.     ULONG  jsbound = enc_bJSBound;
  3115.     ULONG  sign;
  3116.     double d;
  3117.     const float one = 1.0;
  3118.  
  3119.     UWORD  sbband[3][2*32];
  3120.  
  3121.     UBYTE     *pBitAlloc;
  3122.     UBYTE     *pJScale;
  3123.     UBYTE     *pSScale;
  3124.     REAL      *pSSamples;
  3125.     REAL      *pJSamples;
  3126.     s_SBAlloc *pAlloc;
  3127.  
  3128.     for (f = 0; f < 3; f++)
  3129.     {
  3130.         for (j = 0, j2 = 0; j < SCALE_BLOCK; j++, j2++)
  3131.         {
  3132.             pSSamples = &(*enc_pdSB_Samples)[f][0][j][0];
  3133.             pJSamples = &(*enc_pdJ_Samples)[f][j][0];
  3134.  
  3135.             pBitAlloc = &enc_bBitAlloc[0][0];
  3136.             pJScale   = &enc_bJScale[f][0];
  3137.             pSScale   = &enc_bScalar[f][0][0];
  3138.  
  3139.             if (j2 == 3) j2 = 0;
  3140.  
  3141.             for (i = 0; i < enc_bSBLimit; i++)
  3142.             {
  3143.                 //pAlloc = &(*enc_psAllocTable)[i][0];
  3144.  
  3145.                 for (k = 0; k < ( (i < jsbound) ? (enc_bStereo * SBLIMIT) : SBLIMIT); k += SBLIMIT)
  3146.                 {
  3147.                     if ( (n = pBitAlloc[k]) )
  3148.                     {
  3149.                         pAlloc = &(*enc_psAllocTable)[i][n];
  3150.                         if (i >= jsbound && enc_bStereo == 2) {
  3151.                             d = *pJSamples * enc_adMultiples[*pJScale];
  3152.                         }
  3153.                         else {
  3154.                             d = pSSamples[k * SCALE_BLOCK] * enc_adMultiples[pSScale[k]];
  3155.                         }
  3156.  
  3157.                         d  = (d + one) * quant_a[pAlloc->wQuant] - one;
  3158.                         n2 = pAlloc->wStepMask;
  3159.  
  3160.                         if (d < 0) {
  3161.                             sign = 0;
  3162.                             d += one;
  3163.                         }
  3164.                         else {
  3165.                             sign = n2;
  3166.                         }
  3167.  
  3168.                         {
  3169.                             UWORD *pSBBand = &sbband[0][k + i];
  3170.  
  3171.                     #ifndef USE_OLD_MATHLIB
  3172.                             pSBBand[j2*64] = ((ULONG) (d * n2)) | sign;
  3173.                     #else
  3174.                             pSBBand[j2*64] = ( (ULONG) floor(d * n2) ) | sign;
  3175.                     #endif
  3176.                             if (j2 == 2) {
  3177.                                 if (pAlloc->bGroup) {         //  == 3)
  3178.                                     n = pAlloc->bBits;
  3179.                                     for (int x = 0; x < 3 * 64; x += 64)
  3180.                                         PutBits(pSBBand[x], n);
  3181.                                 }
  3182.                                 else {
  3183.                                     int y = pAlloc->wSteps;
  3184.                                     int x = pSBBand[0 * 64] + y * (pSBBand[1 * 64] + y * pSBBand[2 * 64]);
  3185.  
  3186.                                     PutBits(x, pAlloc->bBits);
  3187.                                 }
  3188.                             }
  3189.                         }
  3190.                     }
  3191.                 }
  3192.                 ++pBitAlloc; ++pJSamples; ++pSSamples; ++pJScale; ++pSScale;
  3193.             }
  3194.         }
  3195.     }
  3196. }
  3197. ///
  3198.  
  3199. //----------------------------------------------------------------------------------------------------
  3200.  
  3201.  
  3202.