home *** CD-ROM | disk | FTP | other *** search
/ Microsoft Multimedia Jumpstart 1.1a / CD_ROM.BIN / develpmt / source / waveconv / msadpcm.c < prev    next >
C/C++ Source or Header  |  1992-08-12  |  40KB  |  1,199 lines

  1. /** msadpcm.c
  2.  *
  3.      (C) Copyright Microsoft Corp. 1991, 1992.  All rights reserved.
  4.  
  5.      You have a royalty-free right to use, modify, reproduce and 
  6.      distribute the Sample Files (and/or any modified version) in 
  7.      any way you find useful, provided that you agree that 
  8.      Microsoft has no warranty obligations or liability for any 
  9.      Sample Application Files which are modified. 
  10.      
  11.      If you did not get this from Microsoft Sources, then it may not be the
  12.      most current version.  This sample code in particular will be updated
  13.      and include more documentation.  
  14.  
  15.      Sources are:
  16.          The MM Sys File Transfer BBS: The phone number is 206 936-4082.
  17.     CompuServe: WINSDK forum, MDK section.
  18.     Anonymous FTP from ftp.uu.net vendors\microsoft\multimedia
  19. */
  20.  
  21.  
  22. #define STRICT
  23. #include <windows.h>
  24. #include <windowsx.h>
  25. #include <mmsystem.h>
  26. #include "mmreg.h"
  27. #include "msadpcm.h"
  28.  
  29.  
  30. //
  31. //  constants used by the Microsoft 4 Bit ADPCM algorithm
  32. //
  33. //  CAUTION: the code contained in this file assumes that the number of
  34. //  channels will be no greater than 2! this is for minor optimization
  35. //  purposes and would be very easy to change if >2 channels is required.
  36. //  it also assumes that the PCM data will either be 8 or 16 bit.
  37. //
  38. //  the code to look out for looks 'similar' to this:
  39. //
  40. //      PCM.BytesPerSample = (PCM.BitsPerSample >> 3) << (Channels >> 1);
  41. //
  42. #define MSADPCM_NUM_COEF        (7)
  43. #define MSADPCM_MAX_CHANNELS    (2)
  44.  
  45. #define MSADPCM_CSCALE          (8)
  46. #define MSADPCM_PSCALE          (8)
  47. #define MSADPCM_CSCALE_NUM      (1 << MSADPCM_CSCALE)
  48. #define MSADPCM_PSCALE_NUM      (1 << MSADPCM_PSCALE)
  49.  
  50. #define MSADPCM_DELTA4_MIN      (16)
  51.  
  52. #define MSADPCM_OUTPUT4_MAX     (7)
  53. #define MSADPCM_OUTPUT4_MIN     (-8)
  54.  
  55.  
  56. //
  57. //  Fixed point Delta adaption table:
  58. //
  59. //      Next Delta = Delta * gaiP4[ this output ] / MSADPCM_PSCALE
  60. //
  61. static short  gaiP4[] = { 230, 230, 230, 230, 307, 409, 512, 614,
  62.                           768, 614, 512, 409, 307, 230, 230, 230 };
  63.  
  64.  
  65. /** DWORD FAR PASCAL adpcmDecode4Bit(LPADPCMWAVEFORMAT lpwfADPCM, HPSTR hpSrc, LPPCMWAVEFORMAT lpwfPCM, HPSTR hpDst, DWORD dwSrcLen)
  66.  *
  67.  *  DESCRIPTION:
  68.  *      
  69.  *
  70.  *  ARGUMENTS:
  71.  *      (LPADPCMWAVEFORMAT lpwfADPCM, HPSTR hpSrc, LPPCMWAVEFORMAT lpwfPCM, HPSTR hpDst, DWORD dwSrcLen)
  72.  *
  73.  *  RETURN (DWORD FAR PASCAL):
  74.  *
  75.  *
  76.  *  NOTES:
  77.  *
  78.  **  */
  79.  
  80. DWORD FAR PASCAL adpcmDecode4Bit(LPADPCMWAVEFORMAT lpwfADPCM, HPSTR hpSrc, LPPCMWAVEFORMAT lpwfPCM, HPSTR hpDst, DWORD dwSrcLen)
  81. {
  82.     short   iInput;
  83.     short   iNextInput;
  84.     short   iFirstNibble;
  85.     short   iDelta;
  86.     long    lSamp;
  87.     long    lPrediction;
  88.     BYTE    bPredictors;
  89.     BYTE    bChannels;
  90.     BYTE    bBitsPerSample;
  91.     BYTE    m;
  92.     WORD    n;
  93.     WORD    wSamplesPerBlock;
  94.     WORD    wBlockHeaderBytes;
  95.     DWORD   dwTotalPos;
  96.     DWORD   dwDecoded;
  97.     short   aiSamp1[MSADPCM_MAX_CHANNELS];
  98.     short   aiSamp2[MSADPCM_MAX_CHANNELS];
  99.     short   aiCoef1[MSADPCM_MAX_CHANNELS];
  100.     short   aiCoef2[MSADPCM_MAX_CHANNELS];
  101.     short   aiDelta[MSADPCM_MAX_CHANNELS];
  102.     LPADPCMCOEFSET  lpCoefSet;
  103.  
  104.     //
  105.     //  put some commonly used info in more accessible variables and init
  106.     //  the wBlockHeaderBytes, dwDecoded and dwTotalPos vars...
  107.     //
  108.     lpCoefSet           = &lpwfADPCM->aCoef[0];
  109.     bPredictors         = (BYTE)lpwfADPCM->wNumCoef;
  110.     bChannels           = (BYTE)lpwfADPCM->wfx.nChannels;
  111.     bBitsPerSample      = (BYTE)lpwfPCM->wBitsPerSample;
  112.     wSamplesPerBlock    = lpwfADPCM->wSamplesPerBlock;
  113.     wBlockHeaderBytes   = bChannels * 7;
  114.     dwDecoded           = 0L;
  115.     dwTotalPos          = 0L;
  116.  
  117.  
  118.     //
  119.     //  step through each byte of ADPCM data and decode it to the requested
  120.     //  PCM format (8 or 16 bit).
  121.     //
  122.     while (dwTotalPos < dwSrcLen)
  123.     {
  124.         //
  125.         //  the first thing we need to do with each block of ADPCM data is
  126.         //  to read the header which consists of 7 bytes of data per channel.
  127.         //  so our first check is to make sure that we have _at least_
  128.         //  enough input data for a complete ADPCM block header--if there
  129.         //  is not enough data for the header, then exit.
  130.         //
  131.         //  the header looks like this:
  132.         //      1 byte predictor per channel
  133.         //      2 byte delta per channel
  134.         //      2 byte first sample per channel
  135.         //      2 byte second sample per channel
  136.         //
  137.         //  this gives us (7 * bChannels) bytes of header information. note
  138.         //  that as long as there is _at least_ (7 * bChannels) of header
  139.         //  info, we will grab the two samples from the header (and if no
  140.         //  data exists following the header we will exit in the decode
  141.         //  loop below).
  142.         //
  143.         dwTotalPos += wBlockHeaderBytes;
  144.         if (dwTotalPos > dwSrcLen)
  145.             goto adpcmDecode4BitExit;
  146.             
  147.         //
  148.         //  grab and validate the predictor for each channel
  149.         //
  150.         for (m = 0; m < bChannels; m++)
  151.         {
  152.             BYTE    bPredictor;
  153.  
  154.             bPredictor = (BYTE)(*hpSrc++);
  155.             if (bPredictor >=  bPredictors)
  156.             {
  157.                 //
  158.                 //  the predictor is out of range--this is considered a
  159.                 //  fatal error with the ADPCM data, so we fail by returning
  160.                 //  zero bytes decoded
  161.                 //
  162.                 dwDecoded = 0;
  163.                 goto adpcmDecode4BitExit;
  164.             }
  165.  
  166.             //
  167.             //  get the coefficients for the predictor index
  168.             //
  169.             aiCoef1[m] = lpCoefSet[bPredictor].iCoef1;
  170.             aiCoef2[m] = lpCoefSet[bPredictor].iCoef2;
  171.         }
  172.         
  173.         //
  174.         //  get the starting delta for each channel
  175.         //
  176.         for (m = 0; m < bChannels; m++)
  177.         {
  178.             aiDelta[m] = *(short huge *)hpSrc;
  179.             hpSrc++;
  180.             hpSrc++;
  181.         }
  182.  
  183.         //
  184.         //  get the sample just previous to the first encoded sample per
  185.         //  channel
  186.         //
  187.         for (m = 0; m < bChannels; m++)
  188.         {
  189.             aiSamp1[m] = *(short huge *)hpSrc;
  190.             hpSrc++;
  191.             hpSrc++;
  192.         }
  193.  
  194.         //
  195.         //  get the sample previous to aiSamp1[x] per channel
  196.         //
  197.         for (m = 0; m < bChannels; m++)
  198.         {
  199.             aiSamp2[m] = *(short huge *)hpSrc;
  200.             hpSrc++;
  201.             hpSrc++;
  202.         }
  203.  
  204.  
  205.         //
  206.         //  write out first 2 samples for each channel.
  207.         //
  208.         //  NOTE: the samples are written to the destination PCM buffer
  209.         //  in the _reverse_ order that they are in the header block:
  210.         //  remember that aiSamp2[x] is the _previous_ sample to aiSamp1[x].
  211.         //
  212.         if (bBitsPerSample == (BYTE)8)
  213.         {
  214.             for (m = 0; m < bChannels; m++)
  215.             {
  216.                 *hpDst++ = (char)((aiSamp2[m] >> 8) + 128);
  217.             }
  218.             for (m = 0; m < bChannels; m++)
  219.             {
  220.                 *hpDst++ = (char)((aiSamp1[m] >> 8) + 128);
  221.             }
  222.         }
  223.         else
  224.         {
  225.             for (m = 0; m < bChannels; m++)
  226.             {
  227.                 *(short huge *)hpDst = aiSamp2[m];
  228.                 hpDst++;
  229.                 hpDst++;
  230.             }
  231.             for (m = 0; m < bChannels; m++)
  232.             {
  233.                 *(short huge *)hpDst = aiSamp1[m];
  234.                 hpDst++;
  235.                 hpDst++;
  236.             }
  237.         }
  238.  
  239.         //
  240.         //  we have decoded the first two samples for this block, so add
  241.         //  two to our decoded count
  242.         //
  243.         dwDecoded += 2;
  244.  
  245.  
  246.         //
  247.         //  we now need to decode the 'data' section of the ADPCM block.
  248.         //  this consists of packed 4 bit nibbles.
  249.         //
  250.         //  NOTE: we start our count for the number of data bytes to decode
  251.         //  at 2 because we have already decoded the first 2 samples in
  252.         //  this block.
  253.         //
  254.         iFirstNibble = 1;
  255.         for (n = 2; n < wSamplesPerBlock; n++)
  256.         {
  257.             for (m = 0; m < bChannels; m++)
  258.             {
  259.                 if (iFirstNibble)
  260.                 {
  261.                     //
  262.                     //  we need to grab the next byte to decode--make sure
  263.                     //  that there is a byte for us to grab before continue
  264.                     //
  265.                     dwTotalPos++;
  266.                     if (dwTotalPos > dwSrcLen)
  267.                         goto adpcmDecode4BitExit;
  268.  
  269.                     //
  270.                     //  grab the next two nibbles and create sign extended
  271.                     //  integers out of them:
  272.                     //
  273.                     //      iInput is the first nibble to decode
  274.                     //      iNextInput will be the next nibble decoded
  275.                     //
  276.                     iNextInput  = (short)*hpSrc++;
  277.                     iInput      = iNextInput >> 4;
  278.                     iNextInput  = (iNextInput << 12) >> 12;
  279.  
  280.                     iFirstNibble = 0;
  281.                 }
  282.                 else
  283.                 {
  284.                     //
  285.                     //  put the next sign extended nibble into iInput and
  286.                     //  decode it--also set iFirstNibble back to 1 so we
  287.                     //  will read another byte from the source stream on
  288.                     //  the next iteration...
  289.                     //
  290.                     iInput = iNextInput;
  291.                     iFirstNibble = 1;
  292.                 }
  293.  
  294.  
  295.                 //
  296.                 //  compute the next Adaptive Scale Factor (ASF) and put
  297.                 //  this value in aiDelta for the current channel.
  298.                 //
  299.                 iDelta = aiDelta[m];
  300.                 aiDelta[m] = (short)((gaiP4[iInput & 15] * (long)iDelta) >> MSADPCM_PSCALE);
  301.                 if (aiDelta[m] < MSADPCM_DELTA4_MIN)
  302.                     aiDelta[m] = MSADPCM_DELTA4_MIN;
  303.  
  304.                 //
  305.                 //  decode iInput (the sign extended 4 bit nibble)--there are
  306.                 //  two steps to this:
  307.                 //
  308.                 //  1.  predict the next sample using the previous two
  309.                 //      samples and the predictor coefficients:
  310.                 //
  311.                 //      Prediction = (aiSamp1[channel] * aiCoef1[channel] + 
  312.                 //              aiSamp2[channel] * aiCoef2[channel]) / 256;
  313.                 //
  314.                 //  2.  reconstruct the original PCM sample using the encoded
  315.                 //      sample (iInput), the Adaptive Scale Factor (aiDelta)
  316.                 //      and the prediction value computed in step 1 above.
  317.                 //
  318.                 //      Sample = (iInput * aiDelta[channel]) + Prediction;
  319.                 //
  320.                 lPrediction = (((long)aiSamp1[m] * aiCoef1[m]) +
  321.                                 ((long)aiSamp2[m] * aiCoef2[m])) >> MSADPCM_CSCALE;
  322.                 lSamp = ((long)iInput * iDelta) + lPrediction;
  323.  
  324.                 //
  325.                 //  now we need to clamp lSamp to [-32768..32767]--this value
  326.                 //  will then be a valid 16 bit sample.
  327.                 //
  328.                 if (lSamp > 32767)
  329.                     lSamp = 32767;
  330.                 else if (lSamp < -32768)
  331.                     lSamp = -32768;
  332.         
  333.                 //
  334.                 //  lSamp contains the decoded iInput sample--now write it
  335.                 //  out to the destination buffer
  336.                 //
  337.                 if (bBitsPerSample == (BYTE)8)
  338.                 {
  339.                     *hpDst++ = (char)(((short)lSamp >> 8) + 128);
  340.                 }
  341.                 else
  342.                 {
  343.                     *(short huge *)hpDst = (short)lSamp;
  344.                     hpDst++;
  345.                     hpDst++;
  346.                 }
  347.                 
  348.                 //
  349.                 //  ripple our previous samples down making the new aiSamp1
  350.                 //  equal to the sample we just decoded
  351.                 //
  352.                 aiSamp2[m] = aiSamp1[m];
  353.                 aiSamp1[m] = (short)lSamp;
  354.             }
  355.  
  356.             //
  357.             //  we have decoded one more complete sample
  358.             //
  359.             dwDecoded++;
  360.         }
  361.     }
  362.  
  363.     //
  364.     //  we're done decoding the input data. dwDecoded contains the number
  365.     //  of complete _SAMPLES_ that were decoded. we need to return the
  366.     //  number of _BYTES_ decoded. so calculate the number of bytes per
  367.     //  sample and multiply that with dwDecoded...
  368.     //
  369. adpcmDecode4BitExit:
  370.  
  371.     return (dwDecoded * ((bBitsPerSample >> (BYTE)3) << (bChannels >> 1)));
  372. } /* adpcmDecode4Bit() */
  373.  
  374.  
  375.  
  376. /** short NEAR PASCAL adpcmEncode4Bit_FirstDelta(short iCoef1, short iCoef2, short iP5, short iP4, short iP3, short iP2, short iP1)
  377.  *
  378.  *  DESCRIPTION:
  379.  *      
  380.  *
  381.  *  ARGUMENTS:
  382.  *      (short iCoef1, short iCoef2, short iP5, short iP4, short iP3, short iP2, short iP1)
  383.  *
  384.  *  RETURN (short NEAR PASCAL):
  385.  *
  386.  *
  387.  *  NOTES:
  388.  *
  389.  **  */
  390.  
  391. short NEAR PASCAL adpcmEncode4Bit_FirstDelta(short iCoef1, short iCoef2, short iP5, short iP4, short iP3, short iP2, short iP1)
  392. {
  393.     long    lTotal;
  394.     short   iRtn;
  395.     long    lTemp;
  396.  
  397.     //
  398.     //  use average of 3 predictions
  399.     //
  400.     lTemp  = (((long)iP5 * iCoef2) + ((long)iP4 * iCoef1)) >> MSADPCM_CSCALE;
  401.     lTotal = (lTemp > iP3) ? (lTemp - iP3) : (iP3 - lTemp);
  402.  
  403.     lTemp   = (((long)iP4 * iCoef2) + ((long)iP3 * iCoef1)) >> MSADPCM_CSCALE;
  404.     lTotal += (lTemp > iP2) ? (lTemp - iP2) : (iP2 - lTemp);
  405.  
  406.     lTemp   = (((long)iP3 * iCoef2) + ((long)iP2 * iCoef1)) >> MSADPCM_CSCALE;
  407.     lTotal += (lTemp > iP1) ? (lTemp - iP1) : (iP1 - lTemp);
  408.     
  409.     //
  410.     //  optimal iDelta is 1/4 of prediction error
  411.     //
  412.     iRtn = (short)(lTotal / 12);
  413.     if (iRtn < MSADPCM_DELTA4_MIN)
  414.         iRtn = MSADPCM_DELTA4_MIN;
  415.  
  416.     return (iRtn);
  417. } /* adpcmEncode4Bit_FirstDelta() */
  418.  
  419.  
  420. /** DWORD FAR PASCAL adpcmEncode4Bit(LPPCMWAVEFORMAT lpwfPCM, HPSTR hpSrc, LPADPCMWAVEFORMAT lpwfADPCM, HPSTR hpDst, DWORD dwSrcLen)
  421.  *
  422.  *  DESCRIPTION:
  423.  *      
  424.  *
  425.  *  ARGUMENTS:
  426.  *      (LPPCMWAVEFORMAT lpwfPCM, HPSTR hpSrc, LPADPCMWAVEFORMAT lpwfADPCM, HPSTR hpDst, DWORD dwSrcLen)
  427.  *
  428.  *  RETURN (DWORD FAR PASCAL):
  429.  *
  430.  *
  431.  *  NOTES:
  432.  *
  433.  **  */
  434.  
  435. #define ENCODE_DELTA_LOOKAHEAD      5
  436.  
  437. DWORD FAR PASCAL adpcmEncode4Bit(LPPCMWAVEFORMAT lpwfPCM, HPSTR hpSrc, LPADPCMWAVEFORMAT lpwfADPCM, HPSTR hpDst, DWORD dwSrcLen)
  438. {
  439.     LPSTR   lpSamplesBuf;
  440.     LPSTR   lpSamples;
  441.  
  442.     BYTE    abBestPredictor[MSADPCM_MAX_CHANNELS];
  443.     DWORD   adwTotalError[MSADPCM_NUM_COEF][MSADPCM_MAX_CHANNELS];
  444.  
  445.     short   aiSamples[ENCODE_DELTA_LOOKAHEAD][MSADPCM_MAX_CHANNELS];
  446.     short   aiFirstDelta[MSADPCM_NUM_COEF][MSADPCM_MAX_CHANNELS];
  447.     short   aiDelta[MSADPCM_MAX_CHANNELS];
  448.     short   aiSamp1[MSADPCM_MAX_CHANNELS];
  449.     short   aiSamp2[MSADPCM_MAX_CHANNELS];
  450.  
  451.     short   iCoef1;
  452.     short   iCoef2;
  453.     short   iSamp1;
  454.     short   iSamp2;
  455.     short   iDelta;
  456.     short   iSample;
  457.     short   iOutput;
  458.  
  459.     long    lSamp;
  460.  
  461.     DWORD   dw;
  462.     DWORD   dwTotalConverted;
  463.     DWORD   dwInputPos;
  464.  
  465.     long    lError;
  466.     long    lPrediction;
  467.  
  468.     WORD    wSamplesPerBlock;
  469.     WORD    cbSample;
  470.     WORD    wBlockHeaderBytes;
  471.     WORD    wBlockSize;
  472.     WORD    wNextWrite;
  473.     WORD    wFirstNibble;
  474.     WORD    n;
  475.     BYTE    m;
  476.     BYTE    i;
  477.     BYTE    bChannels;
  478.     BYTE    bBitsPerSample;
  479.  
  480.     //
  481.     //  first copy some information into more accessible (cheaper and shorter)
  482.     //  variables--and precompute some stuff...
  483.     //
  484.     wSamplesPerBlock    = lpwfADPCM->wSamplesPerBlock;
  485.     bChannels           = (BYTE)lpwfPCM->wf.nChannels;
  486.     bBitsPerSample      = (BYTE)lpwfPCM->wBitsPerSample;
  487.     wBlockHeaderBytes   = bChannels * 7;
  488.     dwInputPos          = 0L;
  489.     dwTotalConverted    = 0L;
  490.  
  491.     //
  492.     //  calculate the number of bytes per sample in the PCM data
  493.     //
  494.     //  note: the following code works because we _know_ that we only deal
  495.     //  with 8 or 16 bits per sample PCM and 1 or 2 channels..
  496.     //
  497.     cbSample = (bBitsPerSample >> 3) << (bChannels >> 1);
  498.  
  499.     //
  500.     //  we allocate and use a small buffer (<64k) to hold an entire block of
  501.     //  samples to be encoded. the reason for this is mainly because we
  502.     //  make 8 passes over the data per block and using huge pointers all
  503.     //  of the time is expensive. so we put it in a <64k chunk and eliminate
  504.     //  the huge pointer stuff
  505.     //
  506.     lpSamplesBuf = GlobalAllocPtr(GMEM_MOVEABLE|GMEM_SHARE, wSamplesPerBlock * cbSample);
  507.     if (!lpSamplesBuf)
  508.         return (0L);
  509.  
  510.     //
  511.     //  step through each block of PCM data and encode it to 4 bit ADPCM
  512.     //
  513.     for ( ; dwInputPos < dwSrcLen; dwInputPos += (wBlockSize * cbSample))
  514.     {
  515.         //
  516.         //  determine how much data we should encode for this block--this
  517.         //  will be wSamplesPerBlock until we hit the last chunk of PCM
  518.         //  data that will not fill a complete block. so on the last block
  519.         //  we only encode that amount of data remaining...
  520.         //
  521.         dw = (dwSrcLen - dwInputPos) / cbSample;
  522.         wBlockSize = (WORD)min((DWORD)wSamplesPerBlock, dw);
  523.  
  524.         if (!wBlockSize)
  525.             break;
  526.  
  527.         //
  528.         //  copy the samples that we will be encoding into our small data
  529.         //  samples buffer (this is faster than doing huge pointer arith
  530.         //  all of the time)
  531.         //
  532.         hmemcpy(lpSamplesBuf, &hpSrc[dwInputPos], wBlockSize * cbSample);
  533.  
  534.         //
  535.         //  find the optimal predictor for each channel: to do this, we
  536.         //  must step through and encode using each coefficient set (one
  537.         //  at a time) and determine which one has the least error from
  538.         //  the original data. the one with the least error is then used
  539.         //  for the final encode (the 8th pass done below).
  540.         //
  541.         //  NOTE: keeping the encoded data of the one that has the least
  542.         //  error at all times is an obvious optimization that should be
  543.         //  done. in this way, we only need to do 7 passes instead of 8.
  544.         //
  545.         for (i = 0; i < MSADPCM_NUM_COEF; i++)
  546.         {
  547.             //
  548.             //  reset pointer to beginning of our temporary small data
  549.             //  samples buffer
  550.             //
  551.             lpSamples = lpSamplesBuf;
  552.  
  553.             //
  554.             //  copy the coefficient pair for the current coefficient set
  555.             //  we are using into more convenient/cheaper variables
  556.             //
  557.             iCoef1 = lpwfADPCM->aCoef[i].iCoef1;
  558.             iCoef2 = lpwfADPCM->aCoef[i].iCoef2;
  559.  
  560.             //
  561.             //  we need to choose the first iDelta--to do this, we need
  562.             //  to look at the first few samples. for convenience, we copy
  563.             //  the first ENCODE_DELTA_LOOKAHEAD samples (converted to 
  564.             //  16 bit samples) into a temporary buffer
  565.             //
  566.             for (n = 0; n < ENCODE_DELTA_LOOKAHEAD; n++)
  567.             {
  568.                 for (m = 0; m < bChannels; m++)
  569.                 {
  570.                     if (bBitsPerSample != 8)
  571.                     {
  572.                         iSample = *(short far *)lpSamples;
  573.                         lpSamples++;
  574.                         lpSamples++;
  575.                     }
  576.                     else
  577.                         iSample = ((short)*lpSamples++ - 128) << 8;
  578.  
  579.                     aiSamples[n][m] = iSample;
  580.                 }
  581.             }
  582.  
  583.             //
  584.             //  now choose the first iDelta and setup the first two samples
  585.             //  based on the 16 samples we copied from the source data above
  586.             //  for each channel
  587.             //
  588.             for (m = 0; m < bChannels; m++)
  589.             {
  590.                 //
  591.                 //  reset total error calculation for new block
  592.                 //
  593.                 adwTotalError[i][m] = 0L;
  594.  
  595.                 //
  596.                 //  first 2 samples will come from real data--compute
  597.                 //  starting from there
  598.                 //
  599.                 aiSamp1[m] = aiSamples[1][m];
  600.                 aiSamp2[m] = aiSamples[0][m];
  601.                         
  602.                 //
  603.                 //  calculate initial iDelta
  604.                 //
  605.                 iDelta = adpcmEncode4Bit_FirstDelta(iCoef1, iCoef2,
  606.                         aiSamples[0][m], aiSamples[1][m], aiSamples[2][m],
  607.                         aiSamples[3][m], aiSamples[4][m]);
  608.                 aiDelta[m] = aiFirstDelta[i][m] = iDelta;
  609.             }
  610.  
  611.             //
  612.             //  step over first two complete samples--we took care of them
  613.             //  above
  614.             //
  615.             lpSamples = &lpSamplesBuf[cbSample * 2];
  616.  
  617.             //
  618.             //  now encode the rest of the PCM data in this block--note
  619.             //  we start 2 samples ahead because the first two samples are
  620.             //  simply copied into the ADPCM block header...
  621.             //
  622.             for (n = 2; n < wBlockSize; n++)
  623.             {
  624.                 //
  625.                 //  each channel gets encoded independently... obviously.
  626.                 //
  627.                 for (m = 0; m < bChannels; m++)
  628.                 {
  629.                     //
  630.                     //  yes, copy into cheaper variables because we access
  631.                     //  them a lot
  632.                     //
  633.                     iSamp1 = aiSamp1[m];
  634.                     iSamp2 = aiSamp2[m];
  635.                     iDelta = aiDelta[m];
  636.  
  637.                     //
  638.                     //  calculate the prediction based on the previous two
  639.                     //  samples
  640.                     //
  641.                     lPrediction = ((long)iSamp1 * iCoef1 +
  642.                                     (long)iSamp2 * iCoef2) >> MSADPCM_CSCALE;
  643.  
  644.                     //
  645.                     //  grab the sample (for the current channel) to encode
  646.                     //  from the source and convert it to a 16 bit data if
  647.                     //  necessary
  648.                     //
  649.                     if (bBitsPerSample != 8)
  650.                     {
  651.                         iSample = *(short far *)lpSamples;
  652.                         lpSamples++;
  653.                         lpSamples++;
  654.                     }
  655.                     else
  656.                         iSample = ((short)*lpSamples++ - 128) << 8;
  657.  
  658.                     //
  659.                     //  encode it
  660.                     //
  661.                     lError = (long)iSample - lPrediction;
  662.                     iOutput = (short)(lError / iDelta);
  663.                     if (iOutput > MSADPCM_OUTPUT4_MAX)
  664.                         iOutput = MSADPCM_OUTPUT4_MAX;
  665.                     else if (iOutput < MSADPCM_OUTPUT4_MIN)
  666.                         iOutput = MSADPCM_OUTPUT4_MIN;
  667.  
  668.                     lSamp = lPrediction + ((long)iDelta * iOutput);
  669.         
  670.                     if (lSamp > 32767)
  671.                         lSamp = 32767;
  672.                     else if (lSamp < -32768)
  673.                         lSamp = -32768;
  674.         
  675.                     //
  676.                     //  compute the next iDelta
  677.                     //
  678.                     iDelta = (short)((gaiP4[iOutput & 15] * (long)iDelta) >> MSADPCM_PSCALE);
  679.                     if (iDelta < MSADPCM_DELTA4_MIN)
  680.                         iDelta = MSADPCM_DELTA4_MIN;
  681.         
  682.                     //
  683.                     //  save updated values for this channel back into the
  684.                     //  original arrays...
  685.                     //
  686.                     aiDelta[m] = iDelta;
  687.                     aiSamp2[m] = iSamp1;
  688.                     aiSamp1[m] = (short)lSamp;
  689.  
  690.                     //
  691.                     //  keep a running status on the error for the current
  692.                     //  coefficient pair for this channel
  693.                     //
  694.                     lError = lSamp - iSample;
  695.                     adwTotalError[i][m] += (lError * lError) >> 7;
  696.                 }
  697.             }
  698.         }
  699.  
  700.  
  701.         //
  702.         //  WHEW! we have now made 7 passes over the data and calculated
  703.         //  the error for each--so it's time to find the one that produced
  704.         //  the lowest error and use that predictor (this is for each
  705.         //  channel of course)
  706.         //
  707.         for (m = 0; m < bChannels; m++)
  708.         {
  709.             abBestPredictor[m] = 0;
  710.             dw = adwTotalError[0][m];
  711.             for (i = 1; i < MSADPCM_NUM_COEF; i++)
  712.             {
  713.                 if (adwTotalError[i][m] < dw)
  714.                 {
  715.                     abBestPredictor[m] = i;
  716.                     dw = adwTotalError[i][m];
  717.                 }
  718.             }
  719.         }    
  720.         
  721.  
  722.         //
  723.         //  reset pointer to beginning of our temporary samples buffer--
  724.         //  we're going to make our final pass on the data with the optimal
  725.         //  predictor that we found above
  726.         //
  727.         lpSamples = lpSamplesBuf;
  728.  
  729.  
  730.         //
  731.         //  grab first iDelta from our precomputed first deltas that we
  732.         //  calculated above
  733.         //
  734.         for (m = 0; m < bChannels; m++)
  735.         {
  736.             i = abBestPredictor[m];
  737.             aiDelta[m] = aiFirstDelta[i][m];
  738.         }
  739.  
  740.         //
  741.         //  get the first two samples from the source data (so we can write
  742.         //  them into the ADPCM block header and use them in our prediction
  743.         //  calculation when encoding the rest of the data).
  744.         //
  745.         if (bBitsPerSample != 8)
  746.         {
  747.             for (m = 0; m < bChannels; m++)
  748.             {
  749.                 aiSamp2[m] = *(short far *)lpSamples;
  750.                 lpSamples++;
  751.                 lpSamples++;
  752.             }
  753.             for (m = 0; m < bChannels; m++)
  754.             {
  755.                 aiSamp1[m] = *(short far *)lpSamples;
  756.                 lpSamples++;
  757.                 lpSamples++;
  758.             }
  759.         }
  760.         else
  761.         {
  762.             for (m = 0; m < bChannels; m++)
  763.             {
  764.                 aiSamp2[m] = ((short)*lpSamples++ - 128) << 8;
  765.             }
  766.             for (m = 0; m < bChannels; m++)
  767.             {
  768.                 aiSamp1[m] = ((short)*lpSamples++ - 128) << 8;
  769.             }
  770.         }
  771.  
  772.  
  773.         //
  774.         //  write the block header for the encoded data
  775.         //
  776.         //  the block header is composed of the following data:
  777.         //      1 byte predictor per channel
  778.         //      2 byte delta per channel
  779.         //      2 byte first sample per channel
  780.         //      2 byte second sample per channel
  781.         //
  782.         //  this gives us (7 * bChannels) bytes of header information
  783.         //
  784.         //  so first write the 1 byte predictor for each channel into the
  785.         //  destination buffer
  786.         //
  787.         for (m = 0; m < bChannels; m++)
  788.         {
  789.             *hpDst++ = abBestPredictor[m];
  790.         }
  791.  
  792.         //
  793.         //  now write the 2 byte delta per channel...
  794.         //
  795.         for (m = 0; m < bChannels; m++)
  796.         {
  797.             *(short huge *)hpDst = aiDelta[m];
  798.             hpDst++;
  799.             hpDst++;
  800.         }
  801.  
  802.         //
  803.         //  finally, write the first two samples (2 bytes each per channel)
  804.         //
  805.         for (m = 0; m < bChannels; m++)
  806.         {
  807.             *(short huge *)hpDst = aiSamp1[m];
  808.             hpDst++;
  809.             hpDst++;
  810.         }
  811.         for (m = 0; m < bChannels; m++)
  812.         {
  813.             *(short huge *)hpDst = aiSamp2[m];
  814.             hpDst++;
  815.             hpDst++;
  816.         }
  817.  
  818.         //
  819.         //  the number of bytes that we have written to the destination
  820.         //  buffer is (7 * bChannels)--so add this to our total number of
  821.         //  bytes written to the destination.. for our return value.
  822.         //
  823.         dwTotalConverted += wBlockHeaderBytes;
  824.         
  825.  
  826.         //
  827.         //  we have written the header for this block--now write the data
  828.         //  chunk (which consists of a bunch of encoded nibbles). note that
  829.         //  we start our count at 2 because we already wrote the first
  830.         //  two samples into the destination buffer as part of the header
  831.         //
  832.         wFirstNibble = 1;
  833.         for (n = 2; n < wBlockSize; n++)
  834.         {
  835.             //
  836.             //  each channel gets encoded independently... obviously.
  837.             //
  838.             for (m = 0; m < bChannels; m++)
  839.             {
  840.                 //
  841.                 //  use our chosen best predictor and grab the coefficient
  842.                 //  pair to use for this channel...
  843.                 //
  844.                 i = abBestPredictor[m];
  845.                 iCoef1 = lpwfADPCM->aCoef[i].iCoef1;
  846.                 iCoef2 = lpwfADPCM->aCoef[i].iCoef2;
  847.  
  848.                 //
  849.                 //  copy into cheaper variables because we access them a lot
  850.                 //
  851.                 iSamp1 = aiSamp1[m];
  852.                 iSamp2 = aiSamp2[m];
  853.                 iDelta = aiDelta[m];
  854.  
  855.                 //
  856.                 //  calculate the prediction based on the previous two samples
  857.                 //
  858.                 lPrediction = ((long)iSamp1 * iCoef1 +
  859.                                 (long)iSamp2 * iCoef2) >> MSADPCM_CSCALE;
  860.  
  861.                 //
  862.                 //  grab the sample to encode--convert it to 16 bit data if
  863.                 //  necessary...
  864.                 //
  865.                 if (bBitsPerSample != 8)
  866.                 {
  867.                     iSample = *(short far *)lpSamples;
  868.                     lpSamples++;
  869.                     lpSamples++;
  870.                 }
  871.                 else
  872.                     iSample = ((short)*lpSamples++ - 128) << 8;
  873.  
  874.                 //
  875.                 //  encode the sample
  876.                 //
  877.                 lError = (long)iSample - lPrediction;
  878.                 iOutput = (short)(lError / iDelta);
  879.                 if (iOutput > MSADPCM_OUTPUT4_MAX)
  880.                     iOutput = MSADPCM_OUTPUT4_MAX;
  881.                 else if (iOutput < MSADPCM_OUTPUT4_MIN)
  882.                     iOutput = MSADPCM_OUTPUT4_MIN;
  883.  
  884.                 lSamp = lPrediction + ((long)iDelta * iOutput);
  885.             
  886.                 if (lSamp > 32767)
  887.                     lSamp = 32767;
  888.                 else if (lSamp < -32768)
  889.                     lSamp = -32768;
  890.  
  891.                 //
  892.                 //  compute the next iDelta
  893.                 //
  894.                 iDelta = (short)((gaiP4[iOutput&15] * (long)iDelta) >> MSADPCM_PSCALE); 
  895.                 if (iDelta < MSADPCM_DELTA4_MIN)
  896.                     iDelta = MSADPCM_DELTA4_MIN;
  897.  
  898.                 //
  899.                 //  save updated values for this channel back into the
  900.                 //  original arrays...
  901.                 //
  902.                 aiDelta[m] = iDelta;
  903.                 aiSamp2[m] = iSamp1;
  904.                 aiSamp1[m] = (short)lSamp;
  905.  
  906.                 //
  907.                 //  we have another nibble of encoded data--either combine
  908.                 //  this with the previous nibble and write out a full 
  909.                 //  byte, or save this nibble for the next nibble to be
  910.                 //  combined into a full byte and written to the destination
  911.                 //  buffer... uhg!
  912.                 //
  913.                 if (wFirstNibble)
  914.                 {
  915.                     wNextWrite = (iOutput & 15) << 4;
  916.                     wFirstNibble = 0;
  917.                 }
  918.                 else
  919.                 {
  920.                     *hpDst++ = (BYTE)(wNextWrite | (iOutput & 15));
  921.                     dwTotalConverted += 1;
  922.                     wFirstNibble++;
  923.                 }
  924.             }
  925.         }
  926.     }
  927.  
  928.     //
  929.     //  free the memory used for our small data buffer and return the number
  930.     //  of bytes that we wrote into the destination buffer...
  931.     //
  932.     GlobalFreePtr(lpSamplesBuf);
  933.  
  934.     return (dwTotalConverted);
  935. } /* adpcmEncode4Bit() */
  936.  
  937.  
  938.  
  939. //---------------------------------------------------------------------------
  940. //
  941. //  the code below provides 'support' routines for building/verifying ADPCM
  942. //  headers, etc.
  943. //
  944. //  the coefficient pairs that should be in the wave format header for
  945. //  the Microsoft 4 Bit ADPCM algorithm. the code to copy the coefficients
  946. //  into the wave format header is shown:
  947. //
  948. //      short gaiCoef1[] = { 256,  512,  0, 192, 240,  460,  392 };
  949. //      short gaiCoef2[] = {   0, -256,  0,  64,   0, -208, -232 };
  950. //
  951. //      for (w = 0; w < MSADPCM_NUM_COEF; w++)
  952. //      {
  953. //          lpwfADPCM->aCoef[w].iCoef1 = gaiCoef1[w];
  954. //          lpwfADPCM->aCoef[w].iCoef2 = gaiCoef2[w];
  955. //      }
  956. //
  957. //---------------------------------------------------------------------------
  958.  
  959. static short gaiCoef1[] = { 256,  512,  0, 192, 240,  460,  392 };
  960. static short gaiCoef2[] = {   0, -256,  0,  64,   0, -208, -232 };
  961.  
  962.  
  963. /** BOOL FAR PASCAL adpcmIsValidFormat(LPWAVEFORMATEX lpwfx)
  964.  *
  965.  *  DESCRIPTION:
  966.  *      
  967.  *
  968.  *  ARGUMENTS:
  969.  *      (LPWAVEFORMATEX lpwfx)
  970.  *
  971.  *  RETURN (BOOL FAR PASCAL):
  972.  *
  973.  *
  974.  *  NOTES:
  975.  *
  976.  ** */
  977.  
  978. BOOL FAR PASCAL adpcmIsValidFormat(LPWAVEFORMATEX lpwfx)
  979. {
  980.     LPADPCMWAVEFORMAT   lpwfADPCM;
  981.     WORD                w;
  982.  
  983.     if (!lpwfx)
  984.         return (FALSE);
  985.  
  986.     if (lpwfx->wFormatTag != WAVE_FORMAT_ADPCM)
  987.         return (FALSE);
  988.  
  989.     if (lpwfx->wBitsPerSample != 4)
  990.         return (FALSE);
  991.  
  992.     if ((lpwfx->nChannels < 1) || (lpwfx->nChannels > MSADPCM_MAX_CHANNELS))
  993.         return (FALSE);
  994.  
  995.  
  996.     //
  997.     //  check coef's to see if it is Microsoft's standard 4 Bit ADPCM
  998.     //
  999.     lpwfADPCM = (LPADPCMWAVEFORMAT)lpwfx;
  1000.  
  1001.     if (lpwfADPCM->wNumCoef != MSADPCM_NUM_COEF)
  1002.         return (FALSE);
  1003.  
  1004.     for (w = 0; w < MSADPCM_NUM_COEF; w++)
  1005.     {
  1006.         if (lpwfADPCM->aCoef[w].iCoef1 != gaiCoef1[w])
  1007.             return (FALSE);
  1008.  
  1009.         if (lpwfADPCM->aCoef[w].iCoef2 != gaiCoef2[w])
  1010.             return (FALSE);
  1011.     }
  1012.  
  1013.     return (TRUE);
  1014. } /* adpcmIsValidFormat() */
  1015.  
  1016.  
  1017. /** BOOL FAR PASCAL pcmIsValidFormat(LPWAVEFORMATEX lpwfx)
  1018.  *
  1019.  *  DESCRIPTION:
  1020.  *      
  1021.  *
  1022.  *  ARGUMENTS:
  1023.  *      (LPWAVEFORMATEX lpwfx)
  1024.  *
  1025.  *  RETURN (BOOL FAR PASCAL):
  1026.  *
  1027.  *
  1028.  *  NOTES:
  1029.  *
  1030.  ** */
  1031.  
  1032. BOOL FAR PASCAL pcmIsValidFormat(LPWAVEFORMATEX lpwfx)
  1033. {
  1034.     if (!lpwfx)
  1035.         return (FALSE);
  1036.  
  1037.     if (lpwfx->wFormatTag != WAVE_FORMAT_PCM)
  1038.         return (FALSE);
  1039.  
  1040.     if ((lpwfx->wBitsPerSample != 8) && (lpwfx->wBitsPerSample != 16))
  1041.         return (FALSE);
  1042.  
  1043.     if ((lpwfx->nChannels < 1) || (lpwfx->nChannels > MSADPCM_MAX_CHANNELS))
  1044.         return (FALSE);
  1045.  
  1046.     return (TRUE);
  1047. } /* pcmIsValidFormat() */
  1048.  
  1049.  
  1050. /** BOOL FAR PASCAL adpcmBuildFormatHeader(LPWAVEFORMATEX lpwfxSrc, LPWAVEFORMATEX lpwfxDst)
  1051.  *
  1052.  *  DESCRIPTION:
  1053.  *      
  1054.  *
  1055.  *  ARGUMENTS:
  1056.  *      (LPWAVEFORMATEX lpwfxSrc, LPWAVEFORMATEX lpwfxDst)
  1057.  *
  1058.  *  RETURN (BOOL FAR PASCAL):
  1059.  *
  1060.  *
  1061.  *  NOTES:
  1062.  *
  1063.  ** */
  1064.  
  1065. BOOL FAR PASCAL adpcmBuildFormatHeader(LPWAVEFORMATEX lpwfxSrc, LPWAVEFORMATEX lpwfxDst)
  1066. {
  1067.     LPADPCMWAVEFORMAT   lpwfADPCM;
  1068.     WORD                wBlockAlign;
  1069.     WORD                wChannels;
  1070.     WORD                wBitsPerSample;
  1071.     WORD                wHeaderBytes;
  1072.     DWORD               dw;
  1073.     WORD                w;
  1074.  
  1075.     //
  1076.     //  if the source format is PCM, then build an ADPCM destination format
  1077.     //  header... assuming the PCM format header is valid.
  1078.     //
  1079.     if (lpwfxSrc->wFormatTag == WAVE_FORMAT_PCM)
  1080.     {
  1081.         if (!pcmIsValidFormat(lpwfxSrc))
  1082.             return (FALSE);
  1083.  
  1084.         lpwfADPCM = (LPADPCMWAVEFORMAT)lpwfxDst;
  1085.  
  1086.         //
  1087.         //  fill in destination header with appropriate ADPCM stuff based
  1088.         //  on source PCM header...
  1089.         //
  1090.         lpwfxDst->wFormatTag     = WAVE_FORMAT_ADPCM;
  1091.         lpwfxDst->nSamplesPerSec = lpwfxSrc->nSamplesPerSec;
  1092.         lpwfxDst->nChannels      = wChannels      = lpwfxSrc->nChannels;
  1093.         lpwfxDst->wBitsPerSample = wBitsPerSample = 4;
  1094.  
  1095.         //
  1096.         //  choose a block alignment that makes sense for the sample rate
  1097.         //  that the original PCM data is. basically, this needs to be
  1098.         //  some reasonable number to allow efficient streaming, etc.
  1099.         //
  1100.         //  don't let block alignment get too small...
  1101.         //
  1102.         wBlockAlign = 256 * wChannels;
  1103.         if (lpwfxSrc->nSamplesPerSec > 11025)
  1104.             wBlockAlign *= (WORD)(lpwfxSrc->nSamplesPerSec / 11000);
  1105.  
  1106.         lpwfxDst->nBlockAlign = wBlockAlign;
  1107.  
  1108.         //
  1109.         //  compute that 'samples per block' that will be in the encoded
  1110.         //  ADPCM data blocks. this is determined by subtracting out the
  1111.         //  'other info' contained in each block--a block is composed of
  1112.         //  a header followed by the encoded data.
  1113.         //
  1114.         //  the block header is composed of the following data:
  1115.         //      1 byte predictor per channel
  1116.         //      2 byte delta per channel
  1117.         //      2 byte first sample per channel
  1118.         //      2 byte second sample per channel
  1119.         //
  1120.         //  this gives us (7 * wChannels) bytes of header information that
  1121.         //  contains our first two full samples (so we add two below).
  1122.         //
  1123.         wHeaderBytes = (7 * wChannels);
  1124.  
  1125.         w = (wBlockAlign - wHeaderBytes) * 8;
  1126.         lpwfADPCM->wSamplesPerBlock = (w / (wBitsPerSample * wChannels)) + 2;
  1127.  
  1128.         //
  1129.         //  now compute the avg bytes per second (man this code bites!)
  1130.         //
  1131.         dw = (((DWORD)wBitsPerSample * wChannels * 
  1132.                         (DWORD)lpwfxDst->nSamplesPerSec) / 8);
  1133.         lpwfxDst->nAvgBytesPerSec = (WORD)(dw + wHeaderBytes + 
  1134.                         ((dw / wBlockAlign) * wHeaderBytes));
  1135.  
  1136.         //
  1137.         //  fill in the cbSize field of the extended wave format header.
  1138.         //  this number is the number of _EXTRA BYTES_ *after* the end
  1139.         //  of the WAVEFORMATEX structure that are need for the compression
  1140.         //  format.
  1141.         //
  1142.         //  for Microsoft's 4 Bit ADPCM format, this number is 32:
  1143.         //
  1144.         lpwfxDst->cbSize = sizeof(ADPCMWAVEFORMAT) - sizeof(WAVEFORMATEX) +
  1145.                             (MSADPCM_NUM_COEF * sizeof(ADPCMCOEFSET));
  1146.  
  1147.         //
  1148.         //  copy the Microsoft 4 Bit ADPCM coef's into the header
  1149.         //
  1150.         lpwfADPCM->wNumCoef = MSADPCM_NUM_COEF;
  1151.         for (w = 0; w < MSADPCM_NUM_COEF; w++)
  1152.         {
  1153.             lpwfADPCM->aCoef[w].iCoef1 = gaiCoef1[w];
  1154.             lpwfADPCM->aCoef[w].iCoef2 = gaiCoef2[w];
  1155.         }
  1156.  
  1157.         return (TRUE);
  1158.     }
  1159.  
  1160.     //
  1161.     //  if the source format is ADPCM, then build an appropriate PCM header
  1162.     //
  1163.     else if (lpwfxSrc->wFormatTag == WAVE_FORMAT_ADPCM)
  1164.     {
  1165.         if (!adpcmIsValidFormat(lpwfxSrc))
  1166.             return (FALSE);
  1167.  
  1168.         //
  1169.         //  fill in the info for our destination format...
  1170.         //
  1171.         lpwfxDst->wFormatTag     = WAVE_FORMAT_PCM;
  1172.         lpwfxDst->nSamplesPerSec = lpwfxSrc->nSamplesPerSec;
  1173.         lpwfxDst->nChannels      = wChannels = lpwfxSrc->nChannels;
  1174.  
  1175.         //
  1176.         //  NOTE: bits per sample can be 8 or 16.. most people don't have
  1177.         //  16 bit boards (yet!), so default to 8 bit decoding..
  1178.         //
  1179. #if 0
  1180.         lpwfxDst->wBitsPerSample = wBitsPerSample = 16;
  1181. #else
  1182.         lpwfxDst->wBitsPerSample = wBitsPerSample = 8;
  1183. #endif
  1184.  
  1185.         //
  1186.         //  set nAvgBytesPerSec and nBlockAlign
  1187.         //
  1188.         lpwfxDst->nBlockAlign     = (wBitsPerSample >> 3) << (wChannels >> 1);
  1189.         lpwfxDst->nAvgBytesPerSec = lpwfxDst->nSamplesPerSec * wBitsPerSample;
  1190.  
  1191.         return (TRUE);
  1192.     }
  1193.  
  1194.     return (FALSE);
  1195. } /* adpcmBuildFormatHeader() */
  1196.  
  1197.  
  1198. /** EOF: msadpcm.c **/
  1199.