home *** CD-ROM | disk | FTP | other *** search
/ Netrunner 2004 October / NETRUNNER0410.ISO / regular / dctm.lzh / DCTM / source.lzh / source / tompeg.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2003-02-08  |  200.1 KB  |  6,421 lines

  1. /*************************************************************************
  2.     tompeg.cpp
  3.  
  4.     03/02/08    Xiaohong
  5. *************************************************************************/
  6.  
  7. /**********************************************************
  8.     âwâbâ_âtâ@âCâïé╠âCâôâNâïü[âh
  9. **********************************************************/
  10. #pragma comment(lib,"vfw32.lib")
  11. #include "tompeg.h"
  12. #include "systemdata.h"
  13. #include "picturestruct.h"
  14. #include "uvtempbuffers.h"
  15. #include "sequencedata.h"
  16. #include "cDCT.h"
  17. #include "macros.h"
  18. #include <vfw.h>
  19. #include <math.h>
  20.  
  21. /**********************************************************
  22.     ì\æóæ╠é╠ÉΘî╛
  23. **********************************************************/
  24. typedef struct
  25. {
  26.     unsigned char code; /* right justified */
  27.     char len;
  28. }VLCtable;
  29.  
  30. /* for codes longer than 8 bits (excluding leading zeroes) */
  31. typedef struct
  32. {
  33.     unsigned short code; /* right justified */
  34.     char len;
  35. }sVLCtable;
  36. /*---------------------------------------------------------
  37.     Äσé╔ Rcü` è╓Éöôαé┼Ägùpé╖éΘò╧Éöé╠ì\æóæ╠
  38. ---------------------------------------------------------*/
  39. typedef struct
  40. {
  41.     int r,Xi,Xb,Xp,d0i,d0p,d0b;
  42.     double avg_act;
  43.  
  44.     int R, T, d;
  45.     double actsum;
  46.     int Np, Nb, S, Q;
  47.     int prev_mquant;
  48. }TOMPEG_RATECONTROL;
  49.  
  50. /*---------------------------------------------------------
  51.     AddFrame é╞ NextFrame é╠ù╝ò√é┼ïñÆ╩é╡é─Ägùpé╖éΘò╧Éöé╠ì\æóæ╠
  52. ---------------------------------------------------------*/
  53. typedef struct
  54. {
  55.     int sxf, syf, sxb, syb;
  56.     unsigned char *neworg[3], *newref[3];
  57. }ADDFRAME_STRUCT;
  58.  
  59. /*---------------------------------------------------------
  60.     PICTUREDATA é╠ÉΘî╛
  61. ---------------------------------------------------------*/
  62. typedef struct
  63. {
  64.     int nTempRef;
  65.     int nPictType;
  66. }PICTUREHEADER;
  67.  
  68. typedef struct
  69. {
  70.     int nForwHorFCode,nForwVertFCode;
  71.     int nBackHorFCode,nBackVertFCode;
  72.     int nDCPrecision;
  73.     int nPictStruct;
  74.     bool bFramePredDCTTab[3],bFramePredDCT;
  75.     bool bConcealTab[3];
  76.     bool bQScaleTab[3],bQScaleType;
  77.     bool bTopFirst;
  78.     bool bIntravlcTab[3],bIntravlc;
  79.     bool bAltScanTab[3],bAltScan;
  80.     bool bRepeatFirst;
  81.     bool bProgFrame;
  82. }PICTURECODINGEXTENSION;
  83.  
  84. typedef struct
  85. {
  86.     PICTUREHEADER stHeader;
  87.     PICTURECODINGEXTENSION stCodingExtension;
  88. }PICTUREDATA;
  89.  
  90. /*---------------------------------------------------------
  91.     CODINGMODELPARAMS
  92. ---------------------------------------------------------*/
  93. typedef struct
  94. {
  95.     int nFramesNumberInGroupOfPicture;    // N
  96.     int nDistanceBetweenIPFrames;        // M
  97.     int nIntraSliceRefreshIntaeval;        // P
  98.     int nTotalNumberOfFramesToEncode;    // nframes
  99.     int nTimeCodeOfFirstFrame;            // tc0
  100.     bool bFieldPicture;                    // fieldpic
  101. }CODINGMODELPARAMS;
  102.  
  103. /**********************************************************
  104.     âOâìü[âoâïÆΦÉöé╠ÉΘî╛
  105. **********************************************************/
  106. /* zig-zag scan */
  107. static const unsigned char g_ZigZagScanArray[64] =
  108. {
  109.     0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,
  110.     12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,
  111.     35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,
  112.     58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63
  113. };
  114.  
  115. /* alternate scan */
  116. static const unsigned char g_AlternateScanArray[64] = 
  117. {
  118.     0,8,16,24,1,9,2,10,17,25,32,40,48,56,57,49,
  119.     41,33,26,18,3,11,4,12,19,27,34,42,50,58,35,43,
  120.     51,59,20,28,5,13,6,14,21,29,36,44,52,60,37,45,
  121.     53,61,22,30,7,15,23,31,38,46,54,62,39,47,55,63
  122. };
  123.  
  124. /* non-linear quantization coefficient table */
  125. static const unsigned char g_NonLinerQuantizationArray[32] =
  126. {
  127.     0, 1, 2, 3, 4, 5, 6, 7,
  128.     8,10,12,14,16,18,20,22,
  129.     24,28,32,36,40,44,48,52,
  130.     56,64,72,80,88,96,104,112
  131. };
  132.  
  133. static const unsigned char g_MapNonLinearQuantizationArray[113] = 
  134. {
  135.     0,1,2,3,4,5,6,7,8,8,9,9,10,10,11,11,12,12,13,13,14,14,15,15,16,16,
  136.     16,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,22,22,
  137.     22,22,23,23,23,23,24,24,24,24,24,24,24,25,25,25,25,25,25,25,26,26,
  138.     26,26,26,26,26,26,27,27,27,27,27,27,27,27,28,28,28,28,28,28,28,29,
  139.     29,29,29,29,29,29,29,29,29,30,30,30,30,30,30,30,31,31,31,31,31
  140. };
  141.  
  142. static const VLCtable g_AddRincArray[33]=
  143. {
  144.     {0x01,1},  {0x03,3},  {0x02,3},  {0x03,4},
  145.     {0x02,4},  {0x03,5},  {0x02,5},  {0x07,7},
  146.     {0x06,7},  {0x0b,8},  {0x0a,8},  {0x09,8},
  147.     {0x08,8},  {0x07,8},  {0x06,8},  {0x17,10},
  148.     {0x16,10}, {0x15,10}, {0x14,10}, {0x13,10},
  149.     {0x12,10}, {0x23,11}, {0x22,11}, {0x21,11},
  150.     {0x20,11}, {0x1f,11}, {0x1e,11}, {0x1d,11},
  151.     {0x1c,11}, {0x1b,11}, {0x1a,11}, {0x19,11},
  152.     {0x18,11}
  153. };
  154.  
  155.  
  156. /* Table B-2, B-3, B-4 variable length codes for macroblock_type
  157.  *
  158.  * indexed by [macroblock_type]
  159.  */
  160.  
  161. static const VLCtable g_MacroblockTypeTable[3][32]=
  162. {
  163.     /* I */
  164.     {
  165.         {0,0}, {1,1}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0},
  166.         {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0},
  167.         {0,0}, {1,2}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0},
  168.         {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}
  169.     },
  170.     /* P */
  171.     {
  172.         {0,0}, {3,5}, {1,2}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0},
  173.         {1,3}, {0,0}, {1,1}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0},
  174.         {0,0}, {1,6}, {1,5}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0},
  175.         {0,0}, {0,0}, {2,5}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}
  176.     },
  177.     /* B */
  178.     {
  179.         {0,0}, {3,5}, {0,0}, {0,0}, {2,3}, {0,0}, {3,3}, {0,0},
  180.         {2,4}, {0,0}, {3,4}, {0,0}, {2,2}, {0,0}, {3,2}, {0,0},
  181.         {0,0}, {1,6}, {0,0}, {0,0}, {0,0}, {0,0}, {2,6}, {0,0},
  182.         {0,0}, {0,0}, {3,6}, {0,0}, {0,0}, {0,0}, {2,5}, {0,0}
  183.     }
  184. };
  185.  
  186.  
  187. /* Table B-5 ... B-8 variable length codes for macroblock_type in
  188.  *  scalable sequences
  189.  *
  190.  * not implemented
  191.  */
  192.  
  193. /* Table B-9, variable length codes for coded_block_pattern
  194.  *
  195.  * indexed by [coded_block_pattern]
  196.  */
  197.  
  198. static const VLCtable g_CodedBlockPatternArray[64]=
  199. {
  200.     {0x01,9}, {0x0b,5}, {0x09,5}, {0x0d,6}, 
  201.     {0x0d,4}, {0x17,7}, {0x13,7}, {0x1f,8}, 
  202.     {0x0c,4}, {0x16,7}, {0x12,7}, {0x1e,8}, 
  203.     {0x13,5}, {0x1b,8}, {0x17,8}, {0x13,8}, 
  204.     {0x0b,4}, {0x15,7}, {0x11,7}, {0x1d,8}, 
  205.     {0x11,5}, {0x19,8}, {0x15,8}, {0x11,8}, 
  206.     {0x0f,6}, {0x0f,8}, {0x0d,8}, {0x03,9}, 
  207.     {0x0f,5}, {0x0b,8}, {0x07,8}, {0x07,9}, 
  208.     {0x0a,4}, {0x14,7}, {0x10,7}, {0x1c,8}, 
  209.     {0x0e,6}, {0x0e,8}, {0x0c,8}, {0x02,9}, 
  210.     {0x10,5}, {0x18,8}, {0x14,8}, {0x10,8}, 
  211.     {0x0e,5}, {0x0a,8}, {0x06,8}, {0x06,9}, 
  212.     {0x12,5}, {0x1a,8}, {0x16,8}, {0x12,8}, 
  213.     {0x0d,5}, {0x09,8}, {0x05,8}, {0x05,9}, 
  214.     {0x0c,5}, {0x08,8}, {0x04,8}, {0x04,9},
  215.     {0x07,3}, {0x0a,5}, {0x08,5}, {0x0c,6}
  216. };
  217.  
  218.  
  219. /* Table B-10, variable length codes for motion_code
  220.  *
  221.  * indexed by [abs(motion_code)]
  222.  * sign of motion_code is treated elsewhere
  223.  */
  224.  
  225. static const VLCtable g_MotionCodeArray[17]=
  226. {
  227.     {0x01,1},  {0x01,2},  {0x01,3},  {0x01,4},
  228.     {0x03,6},  {0x05,7},  {0x04,7},  {0x03,7},
  229.     {0x0b,9},  {0x0a,9},  {0x09,9},  {0x11,10},
  230.     {0x10,10}, {0x0f,10}, {0x0e,10}, {0x0d,10},
  231.     {0x0c,10}
  232. };
  233.  
  234.  
  235. /* Table B-11, variable length codes for dmvector
  236.  *
  237.  * treated elsewhere
  238.  */
  239.  
  240. /* Table B-12, variable length codes for dct_dc_size_luminance
  241.  *
  242.  * indexed by [dct_dc_size_luminance]
  243.  */
  244.  
  245. static const sVLCtable g_DCTDcSizeLuminanceArray[12]=
  246. {
  247.     {0x0004,3}, {0x0000,2}, {0x0001,2}, {0x0005,3}, {0x0006,3}, {0x000e,4},
  248.     {0x001e,5}, {0x003e,6}, {0x007e,7}, {0x00fe,8}, {0x01fe,9}, {0x01ff,9}
  249. };
  250.  
  251.  
  252. /* Table B-13, variable length codes for dct_dc_size_chrominance
  253.  *
  254.  * indexed by [dct_dc_size_chrominance]
  255.  */
  256.  
  257. static const sVLCtable g_DCTDcSizeChrominanceArray[12]=
  258. {
  259.     {0x0000,2}, {0x0001,2}, {0x0002,2}, {0x0006,3}, {0x000e,4}, {0x001e,5},
  260.     {0x003e,6}, {0x007e,7}, {0x00fe,8}, {0x01fe,9}, {0x03fe,10},{0x03ff,10}
  261. };
  262.  
  263.  
  264. /* Table B-14, DCT coefficients table zero
  265.  *
  266.  * indexed by [run][level-1]
  267.  * split into two tables (g_DCTCodeTable1, g_DCTCodeTable2) to reduce size
  268.  * 'first DCT coefficient' condition and 'End of Block' are treated elsewhere
  269.  * codes do not include s (sign bit)
  270.  */
  271.  
  272. static VLCtable g_DCTCodeTable1[2][40]=
  273. {
  274.     /* run = 0, level = 1...40 */
  275.     {
  276.         {0x03, 2}, {0x04, 4}, {0x05, 5}, {0x06, 7},
  277.         {0x26, 8}, {0x21, 8}, {0x0a,10}, {0x1d,12},
  278.         {0x18,12}, {0x13,12}, {0x10,12}, {0x1a,13},
  279.         {0x19,13}, {0x18,13}, {0x17,13}, {0x1f,14},
  280.         {0x1e,14}, {0x1d,14}, {0x1c,14}, {0x1b,14},
  281.         {0x1a,14}, {0x19,14}, {0x18,14}, {0x17,14},
  282.         {0x16,14}, {0x15,14}, {0x14,14}, {0x13,14},
  283.         {0x12,14}, {0x11,14}, {0x10,14}, {0x18,15},
  284.         {0x17,15}, {0x16,15}, {0x15,15}, {0x14,15},
  285.         {0x13,15}, {0x12,15}, {0x11,15}, {0x10,15}
  286.     },
  287.     /* run = 1, level = 1...18 */
  288.     {
  289.         {0x03, 3}, {0x06, 6}, {0x25, 8}, {0x0c,10},
  290.         {0x1b,12}, {0x16,13}, {0x15,13}, {0x1f,15},
  291.         {0x1e,15}, {0x1d,15}, {0x1c,15}, {0x1b,15},
  292.         {0x1a,15}, {0x19,15}, {0x13,16}, {0x12,16},
  293.         {0x11,16}, {0x10,16}, {0x00, 0}, {0x00, 0},
  294.         {0x00, 0}, {0x00, 0}, {0x00, 0}, {0x00, 0},
  295.         {0x00, 0}, {0x00, 0}, {0x00, 0}, {0x00, 0},
  296.         {0x00, 0}, {0x00, 0}, {0x00, 0}, {0x00, 0},
  297.         {0x00, 0}, {0x00, 0}, {0x00, 0}, {0x00, 0},
  298.         {0x00, 0}, {0x00, 0}, {0x00, 0}, {0x00, 0}
  299.     }
  300. };
  301.  
  302. static VLCtable g_DCTCodeTable2[30][5]=
  303. {
  304.     /* run = 2...31, level = 1...5 */
  305.     {{0x05, 4}, {0x04, 7}, {0x0b,10}, {0x14,12}, {0x14,13}},
  306.     {{0x07, 5}, {0x24, 8}, {0x1c,12}, {0x13,13}, {0x00, 0}},
  307.     {{0x06, 5}, {0x0f,10}, {0x12,12}, {0x00, 0}, {0x00, 0}},
  308.     {{0x07, 6}, {0x09,10}, {0x12,13}, {0x00, 0}, {0x00, 0}},
  309.     {{0x05, 6}, {0x1e,12}, {0x14,16}, {0x00, 0}, {0x00, 0}},
  310.     {{0x04, 6}, {0x15,12}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  311.     {{0x07, 7}, {0x11,12}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  312.     {{0x05, 7}, {0x11,13}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  313.     {{0x27, 8}, {0x10,13}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  314.     {{0x23, 8}, {0x1a,16}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  315.     {{0x22, 8}, {0x19,16}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  316.     {{0x20, 8}, {0x18,16}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  317.     {{0x0e,10}, {0x17,16}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  318.     {{0x0d,10}, {0x16,16}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  319.     {{0x08,10}, {0x15,16}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  320.     {{0x1f,12}, {0x00, 0}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  321.     {{0x1a,12}, {0x00, 0}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  322.     {{0x19,12}, {0x00, 0}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  323.     {{0x17,12}, {0x00, 0}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  324.     {{0x16,12}, {0x00, 0}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  325.     {{0x1f,13}, {0x00, 0}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  326.     {{0x1e,13}, {0x00, 0}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  327.     {{0x1d,13}, {0x00, 0}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  328.     {{0x1c,13}, {0x00, 0}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  329.     {{0x1b,13}, {0x00, 0}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  330.     {{0x1f,16}, {0x00, 0}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  331.     {{0x1e,16}, {0x00, 0}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  332.     {{0x1d,16}, {0x00, 0}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  333.     {{0x1c,16}, {0x00, 0}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  334.     {{0x1b,16}, {0x00, 0}, {0x00, 0}, {0x00, 0}, {0x00, 0}}
  335. };
  336.  
  337.  
  338. /* Table B-15, DCT coefficients table one
  339.  *
  340.  * indexed by [run][level-1]
  341.  * split into two tables (g_DCTCodeTable1a, g_DCTCodeTable2a) to reduce size
  342.  * 'End of Block' is treated elsewhere
  343.  * codes do not include s (sign bit)
  344.  */
  345.  
  346. static VLCtable g_DCTCodeTable1a[2][40]=
  347. {
  348.     /* run = 0, level = 1...40 */
  349.     {
  350.         {0x02, 2}, {0x06, 3}, {0x07, 4}, {0x1c, 5},
  351.         {0x1d, 5}, {0x05, 6}, {0x04, 6}, {0x7b, 7},
  352.         {0x7c, 7}, {0x23, 8}, {0x22, 8}, {0xfa, 8},
  353.         {0xfb, 8}, {0xfe, 8}, {0xff, 8}, {0x1f,14},
  354.         {0x1e,14}, {0x1d,14}, {0x1c,14}, {0x1b,14},
  355.         {0x1a,14}, {0x19,14}, {0x18,14}, {0x17,14},
  356.         {0x16,14}, {0x15,14}, {0x14,14}, {0x13,14},
  357.         {0x12,14}, {0x11,14}, {0x10,14}, {0x18,15},
  358.         {0x17,15}, {0x16,15}, {0x15,15}, {0x14,15},
  359.         {0x13,15}, {0x12,15}, {0x11,15}, {0x10,15}
  360.     },
  361.     /* run = 1, level = 1...18 */
  362.     {
  363.         {0x02, 3}, {0x06, 5}, {0x79, 7}, {0x27, 8},
  364.         {0x20, 8}, {0x16,13}, {0x15,13}, {0x1f,15},
  365.         {0x1e,15}, {0x1d,15}, {0x1c,15}, {0x1b,15},
  366.         {0x1a,15}, {0x19,15}, {0x13,16}, {0x12,16},
  367.         {0x11,16}, {0x10,16}, {0x00, 0}, {0x00, 0},
  368.         {0x00, 0}, {0x00, 0}, {0x00, 0}, {0x00, 0},
  369.         {0x00, 0}, {0x00, 0}, {0x00, 0}, {0x00, 0},
  370.         {0x00, 0}, {0x00, 0}, {0x00, 0}, {0x00, 0},
  371.         {0x00, 0}, {0x00, 0}, {0x00, 0}, {0x00, 0},
  372.         {0x00, 0}, {0x00, 0}, {0x00, 0}, {0x00, 0}
  373.     }
  374. };
  375.  
  376. static VLCtable g_DCTCodeTable2a[30][5]=
  377. {
  378.     /* run = 2...31, level = 1...5 */
  379.     {{0x05, 5}, {0x07, 7}, {0xfc, 8}, {0x0c,10}, {0x14,13}},
  380.     {{0x07, 5}, {0x26, 8}, {0x1c,12}, {0x13,13}, {0x00, 0}},
  381.     {{0x06, 6}, {0xfd, 8}, {0x12,12}, {0x00, 0}, {0x00, 0}},
  382.     {{0x07, 6}, {0x04, 9}, {0x12,13}, {0x00, 0}, {0x00, 0}},
  383.     {{0x06, 7}, {0x1e,12}, {0x14,16}, {0x00, 0}, {0x00, 0}},
  384.     {{0x04, 7}, {0x15,12}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  385.     {{0x05, 7}, {0x11,12}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  386.     {{0x78, 7}, {0x11,13}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  387.     {{0x7a, 7}, {0x10,13}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  388.     {{0x21, 8}, {0x1a,16}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  389.     {{0x25, 8}, {0x19,16}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  390.     {{0x24, 8}, {0x18,16}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  391.     {{0x05, 9}, {0x17,16}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  392.     {{0x07, 9}, {0x16,16}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  393.     {{0x0d,10}, {0x15,16}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  394.     {{0x1f,12}, {0x00, 0}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  395.     {{0x1a,12}, {0x00, 0}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  396.     {{0x19,12}, {0x00, 0}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  397.     {{0x17,12}, {0x00, 0}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  398.     {{0x16,12}, {0x00, 0}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  399.     {{0x1f,13}, {0x00, 0}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  400.     {{0x1e,13}, {0x00, 0}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  401.     {{0x1d,13}, {0x00, 0}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  402.     {{0x1c,13}, {0x00, 0}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  403.     {{0x1b,13}, {0x00, 0}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  404.     {{0x1f,16}, {0x00, 0}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  405.     {{0x1e,16}, {0x00, 0}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  406.     {{0x1d,16}, {0x00, 0}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  407.     {{0x1c,16}, {0x00, 0}, {0x00, 0}, {0x00, 0}, {0x00, 0}},
  408.     {{0x1b,16}, {0x00, 0}, {0x00, 0}, {0x00, 0}, {0x00, 0}}
  409. };
  410. /**********************************************************
  411.     âìü[âJâïè╓Éö é╠ÉΘî╛
  412. **********************************************************/
  413. /*---------------------------------------------------------
  414.     êΩÄ₧âtâ@âCâïé╠âpâXé╠ì∞ɼ
  415. ---------------------------------------------------------*/
  416. static void MakeTmpFilePath(char* szPath,unsigned long uLength,char *szFname);
  417. /*---------------------------------------------------------
  418.     ò╧Éöé╠É▌ÆΦ
  419. ---------------------------------------------------------*/
  420. static inline TOMPGRET SetParam(void);
  421. /*---------------------------------------------------------
  422.     ò╧Éöé╠ö═ê═é╠â`âFâbâN
  423. ---------------------------------------------------------*/
  424. static inline TOMPGRET RangeCheck(void);
  425. /*---------------------------------------------------------
  426.     ârâbâgâîü[âgé╠â`âFâbâN
  427. ---------------------------------------------------------*/
  428. static inline bool ValidBitrate(const unsigned char,const unsigned int);
  429. /*=========================================================
  430.     Rate Control
  431. =========================================================*/
  432. /*---------------------------------------------------------
  433.     âVü[âPâôâXé╠Åëè·ë╗
  434. ---------------------------------------------------------*/
  435. static inline void RcInitSeq(void);
  436. static inline void RcInitGOP(const int,const int);
  437. static inline void RcInitPic(unsigned char* frame);
  438. static inline void RcUpdatePict(void);
  439. /*---------------------------------------------------------
  440.     compute initial quantization stepsize 
  441.     (at the beginning of picture)
  442. ---------------------------------------------------------*/
  443. static inline int RcStartMb(void);
  444. /*---------------------------------------------------------
  445.     Step 2: measure virtual buffer - estimated buffer discrepancy
  446. ---------------------------------------------------------*/
  447. static inline int RcCalcMQuant(const int);
  448. /*---------------------------------------------------------
  449.     compute variance of 8x8 block
  450. ---------------------------------------------------------*/
  451. static double VarSBlock(unsigned char*,const int);
  452. /*=========================================================
  453.     VBV é╠îvÄZ
  454.  
  455.     generates warnings if underflow or overflow occurs
  456. =========================================================*/
  457. /*---------------------------------------------------------
  458.     vbv_end_of_picture
  459.  
  460.     has to be called directly after writing picture_data()
  461.     needed for accurate VBV buffer overflow calculation
  462.     assumes there is no byte stuffing prior to the next start code
  463. ---------------------------------------------------------*/
  464. static void VBVEndOfPicture(void);
  465. /*---------------------------------------------------------
  466.     has to be called directly after writing the picture start code,
  467.     the    reference point for vbv_delay
  468. ---------------------------------------------------------*/
  469. static inline int CalcVBVDelay(void);
  470. /*=========================================================
  471.     âwâbâ_é╠Åæé½ì₧é▌
  472. =========================================================*/
  473. /*---------------------------------------------------------
  474.     âwâbâ_é╠Åæé½ì₧é▌
  475. ---------------------------------------------------------*/
  476. static inline void PutGroupHeader(const int,const unsigned char);
  477. /*---------------------------------------------------------
  478.     âtâîü[âÇö╘ìåé⌐éτâ^âCâÇâRü[âhé╓ò╧è╖
  479. ---------------------------------------------------------*/
  480. static inline int FrameToTimeCode(int);
  481. /*---------------------------------------------------------
  482.     output a zero terminated string as user data
  483.  
  484.     string must not emulate start codes
  485. ---------------------------------------------------------*/
  486. static inline void PutUserData(char* userdata);
  487. /*---------------------------------------------------------
  488.     generate picture header
  489. ---------------------------------------------------------*/
  490. static inline void PutPictureHeader(void);
  491. /*---------------------------------------------------------
  492.     generate picture coding extension (6.2.3.1, 6.3.11)
  493.  
  494.     composite display information (v_axis etc.) not implemented
  495. ---------------------------------------------------------*/
  496. static inline void PutPictureCodingExtension(void);
  497. /*---------------------------------------------------------
  498.     BITMAPINFOHEADER é╞ ârâbâgâfü[â^é≡Ä≤é»Äµé┴é─üCÄgùpë┬ö\é╚î`é╔ò╧ìXé╖éΘ
  499. ---------------------------------------------------------*/
  500. static inline TOMPGRET ConvRGBtoYUV(const LPBITMAPINFO,const unsigned char*,unsigned char* []);
  501.  
  502. /*=========================================================
  503.     ô«é½é╠ÉäÆΦ
  504. =========================================================*/
  505. /*---------------------------------------------------------
  506.     ô«é½é╠ÉäÆΦ
  507. ---------------------------------------------------------*/
  508. static void MotionEstimation(unsigned char* oldorg,
  509.                            unsigned char* neworg,
  510.                            unsigned char* oldref,
  511.                            unsigned char* newref,
  512.                            unsigned char* cur,
  513.                            unsigned char* curref,
  514.                            int sxf,int syf,int sxb,int syb,
  515.                            MACROBLOCKINFO* mbi,
  516.                            int secondfield,bool ipflag);
  517. /*---------------------------------------------------------
  518.     âtâîü[âÇÅπé┼é╠ô«é½ÉäÆΦ
  519. ---------------------------------------------------------*/
  520. static inline void FrameME(unsigned char* oldorg,
  521.                          unsigned char* neworg,
  522.                          unsigned char* oldref,
  523.                          unsigned char* newref,
  524.                          unsigned char* cur,
  525.                          int i,int j,int sxf,int syf,int sxb,int syb,
  526.                          MACROBLOCKINFO* mbi);
  527.  
  528. /*---------------------------------------------------------
  529.     âtâBü[âïâhÅπé┼é╠ô«é½ÉäÆΦ
  530.  
  531.     oldorg: original frame for forward prediction (P and B frames)
  532.     neworg: original frame for backward prediction (B frames only)
  533.     oldref: reconstructed frame for forward prediction (P and B frames)
  534.     newref: reconstructed frame for backward prediction (B frames only)
  535.     cur:    current original frame (the one for which the prediction is formed)
  536.     curref: current reconstructed frame (to predict second field from first)
  537.     sxf,syf: forward search window (frame coordinates)
  538.     sxb,syb: backward search window (frame coordinates)
  539.     mbi:    pointer to macroblock info structure
  540.     secondfield: indicates second field of a frame (in P fields this means
  541.                   that reference field of opposite parity is in curref instead
  542.                   of oldref)
  543.     ipflag: indicates a P type field which is the second field of a frame
  544.            in which the first field is I type (this restricts predictions
  545.            to be based only on the opposite parity (=I) field)
  546.  
  547.     results:
  548.     mbi->
  549.     mb_type: 0, MB_INTRA, MB_FORWARD, MB_BACKWARD, MB_FORWARD|MB_BACKWARD
  550.     MV[][][]: motion vectors (field format)
  551.     mv_field_sel: top/bottom field
  552.     motion_type: MC_FIELD, MC_16X8
  553.  
  554.     uses global vars: pict_type, pict_struct
  555. ---------------------------------------------------------*/
  556. static inline void FieldME(unsigned char *oldorg, unsigned char *neworg,
  557.                             unsigned char *oldref, unsigned char *newref, unsigned char *cur,
  558.                             unsigned char *curref, int i, int j, int sxf, int syf, int sxb, int syb,
  559.                             MACROBLOCKINFO *mbi, int secondfield, bool ipflag);
  560.  
  561. /*---------------------------------------------------------
  562.     frame picture motion estimation
  563.  
  564.     org: top left pel of source reference frame
  565.     ref: top left pel of reconstructed reference frame
  566.     mb:  macroblock to be matched
  567.     i,j: location of mb relative to ref (=center of search window)
  568.     sx,sy: half widths of search window
  569.     iminp,jminp,dframep: location and value of best frame prediction
  570.     imintp,jmintp,tselp: location of best field pred. for top field of mb
  571.     iminbp,jminbp,bselp: location of best field pred. for bottom field of mb
  572.     dfieldp: value of field prediction
  573. ---------------------------------------------------------*/
  574. static void FrameEstimate(unsigned char *org,
  575.                         unsigned char *ref, unsigned char *mb,
  576.                         int i, int j,
  577.                         int sx, int sy, int *iminp, int *jminp, int *imintp, int *jmintp,
  578.                         int *iminbp, int *jminbp, int *dframep, int *dfieldp,
  579.                         int *tselp, int *bselp, int imins[2][2], int jmins[2][2]);
  580. static inline void DPFrameEstimate(unsigned char *ref,
  581.                                     unsigned char *mb, int i, int j, int iminf[2][2], int jminf[2][2],
  582.                                     int *iminp, int *jminp, int *imindmvp, int *jmindmvp,
  583.                                     int *dmcp, int *vmcp);
  584. /*---------------------------------------------------------
  585.     field picture motion estimation subroutine
  586.  
  587.     toporg: address of original top reference field
  588.     topref: address of reconstructed top reference field
  589.     botorg: address of original bottom reference field
  590.     botref: address of reconstructed bottom reference field
  591.     mb:  macroblock to be matched
  592.     i,j: location of mb (=center of search window)
  593.     sx,sy: half width/height of search window
  594.  
  595.     iminp,jminp,selp,dfieldp: location and distance of best field prediction
  596.     imin8up,jmin8up,sel8up: location of best 16x8 pred. for upper half of mb
  597.     imin8lp,jmin8lp,sel8lp: location of best 16x8 pred. for lower half of mb
  598.     d8p: distance of best 16x8 prediction
  599.     iminsp,jminsp,dsp: location and distance of best same parity field
  600.                        prediction (needed for dual prime, only valid if
  601.                        ipflag==0)
  602. ---------------------------------------------------------*/
  603. static void FieldEstimate(unsigned char *toporg,
  604.                             unsigned char *topref, unsigned char *botorg, unsigned char *botref,
  605.                             unsigned char *mb, int i, int j, int sx, int sy, bool ipflag,
  606.                             int *iminp, int *jminp, int *imin8up, int *jmin8up, int *imin8lp,
  607.                             int *jmin8lp, int *dfieldp, int *d8p, int *selp, int *sel8up, int *sel8lp,
  608.                             int *iminsp, int *jminsp, int *dsp);
  609. static inline void DPFieldEstimate(unsigned char *topref,
  610.                                     unsigned char *botref, unsigned char *mb,
  611.                                     int i, int j, int imins, int jmins, int *imindmvp, int *jmindmvp,
  612.                                     int *dmcp, int *vmcp);
  613.  
  614. /*---------------------------------------------------------
  615.     full search block matching
  616.  
  617.     blk: top left pel of (16*h) block
  618.     h: height of block
  619.     lx: distance (in bytes) of vertically adjacent pels in ref,blk
  620.     org: top left pel of source reference picture
  621.     ref: top left pel of reconstructed reference picture
  622.     i0,j0: center of search window
  623.     sx,sy: half widths of search window
  624.     xmax,ymax: right/bottom limits of search area
  625.     iminp,jminp: pointers to where the result is stored
  626.                  result is given as half pel offset from ref(0,0)
  627.                  i.e. NOT relative to (i0,j0)
  628. ---------------------------------------------------------*/
  629. static int FullSearch(unsigned char *org, unsigned char *ref,
  630.                     unsigned char *blk,
  631.                     int lx, int i0, int j0, int sx, int sy, int h, int xmax, int ymax,
  632.                     int *iminp, int *jminp);
  633. /*---------------------------------------------------------
  634.     total absolute difference between two (16*h) blocks
  635.     including optional half pel interpolation of blk1 (hx,hy)
  636.     blk1,blk2: addresses of top left pels of both blocks
  637.     lx:        distance (in bytes) of vertically adjacent pels
  638.     hx,hy:     flags for horizontal and/or vertical interpolation
  639.     h:         height of block (usually 8 or 16)
  640.     distlim:   bail out if sum exceeds this value
  641. ---------------------------------------------------------*/
  642. static int Dist1(unsigned char *blk1, unsigned char *blk2,
  643.                 int lx, int hx, int hy, int h, int distlim);
  644. /*---------------------------------------------------------
  645.     total squared difference between two (16*h) blocks
  646.     including optional half pel interpolation of blk1 (hx,hy)
  647.     blk1,blk2: addresses of top left pels of both blocks
  648.     lx:        distance (in bytes) of vertically adjacent pels
  649.     hx,hy:     flags for horizontal and/or vertical interpolation
  650.     h:         height of block (usually 8 or 16)
  651. ---------------------------------------------------------*/
  652. static int Dist2(unsigned char *blk1, unsigned char *blk2,
  653.                 int lx, int hx, int hy, int h);
  654. /*---------------------------------------------------------
  655.     absolute difference error between a (16*h) block and a bidirectional
  656.     prediction
  657.  
  658.     p2: address of top left pel of block
  659.     pf,hxf,hyf: address and half pel flags of forward ref. block
  660.     pb,hxb,hyb: address and half pel flags of backward ref. block
  661.     h: height of block
  662.     lx: distance (in bytes) of vertically adjacent pels in p2,pf,pb
  663. ---------------------------------------------------------*/
  664. static int BDist1(unsigned char *pf, unsigned char *pb,
  665.                 unsigned char *p2, int lx, int hxf, int hyf, int hxb, int hyb, int h);
  666. /*---------------------------------------------------------
  667.     squared error between a (16*h) block and a bidirectional
  668.     prediction
  669.  
  670.     p2: address of top left pel of block
  671.     pf,hxf,hyf: address and half pel flags of forward ref. block
  672.     pb,hxb,hyb: address and half pel flags of backward ref. block
  673.     h: height of block
  674.     lx: distance (in bytes) of vertically adjacent pels in p2,pf,pb
  675. ---------------------------------------------------------*/
  676. static int BDist2(unsigned char *pf, unsigned char *pb,
  677.                 unsigned char *p2, int lx, int hxf, int hyf, int hxb, int hyb, int h);
  678. /*---------------------------------------------------------
  679.     variance of a (16*16) block, multiplied by 256
  680.     p:  address of top left pel of block
  681.     lx: distance (in bytes) of vertically adjacent pels
  682. ---------------------------------------------------------*/
  683. static int Variance(unsigned char *p,int lx);
  684.  
  685. /*=========================================================
  686.     predict
  687. =========================================================*/
  688. /*---------------------------------------------------------
  689.     form prediction for a complete picture (frontend for predict_mb)
  690.  
  691.     reff: reference frame for forward prediction
  692.     refb: reference frame for backward prediction
  693.     cur:  destination (current) frame
  694.     secondfield: predict second field of a frame
  695.     mbi:  macroblock info
  696. ---------------------------------------------------------*/
  697. static void Predict(unsigned char* reff[],unsigned char* refb[],unsigned char* cur[],
  698.                      int secondfield,MACROBLOCKINFO* mbi);
  699. /*---------------------------------------------------------
  700.     form prediction for one macroblock
  701.  
  702.     oldref: reference frame for forward prediction
  703.     newref: reference frame for backward prediction
  704.     cur:    destination (current) frame
  705.     lx:     frame width (identical to global var `width')
  706.     bx,by:  picture (field or frame) coordinates of macroblock to be predicted
  707.     pict_type: I, P or B
  708.     pict_struct: FRAME_PICTURE, TOP_FIELD, BOTTOM_FIELD
  709.     mb_type:     MB_FORWARD, MB_BACKWARD, MB_INTRA
  710.     motion_type: MC_FRAME, MC_FIELD, MC_16X8, MC_DMV
  711.     secondfield: predict second field of a frame
  712.     PMV[2][2][2]: motion vectors (in half pel picture coordinates)
  713.     mv_field_sel[2][2]: motion vertical field selects (for field predictions)
  714.     dmvector: differential motion vectors (for dual prime)
  715.  
  716.     Notes:
  717.     - when predicting a P type picture which is the second field of
  718.       a frame, the same parity reference field is in oldref, while the
  719.       opposite parity reference field is assumed to be in newref!
  720.     - intra macroblocks are modelled to have a constant prediction of 128
  721.       for all pels; this results in a DC DCT coefficient symmetric to 0
  722.     - vectors for field prediction in frame pictures are in half pel frame
  723.       coordinates (vertical component is twice the field value and always
  724.       even)
  725.  
  726.     already covers dual prime (not yet used)
  727. ---------------------------------------------------------*/
  728. static inline void PredictMB(
  729.                             unsigned char *oldref[], unsigned char *newref[], unsigned char *cur[],
  730.                             int lx, int bx, int by, int pict_type, int pict_struct, int mb_type,
  731.                             int motion_type, int secondfield,
  732.                             int PMV[][2][2], int mv_field_sel[][2], int dmvector[]);
  733. /*---------------------------------------------------------
  734.     predict a rectangular block (all three components)
  735.  
  736.     src:     source frame (Y,U,V)
  737.     sfield:  source field select (0: frame or top field, 1: bottom field)
  738.     dst:     destination frame (Y,U,V)
  739.     dfield:  destination field select (0: frame or top field, 1: bottom field)
  740.  
  741.     the following values are in luminance picture (frame or field) dimensions
  742.     lx:      distance of vertically adjacent pels (selects frame or field pred.)
  743.     w,h:     width and height of block (only 16x16 or 16x8 are used)
  744.     x,y:     coordinates of destination block
  745.     dx,dy:   half pel motion vector
  746.     addflag: store or add (= average) prediction
  747. ---------------------------------------------------------*/
  748. static void Pred(unsigned char *src[], int sfield,
  749.                 unsigned char *dst[], int dfield,
  750.                 int lx, int w, int h, int x, int y, int dx, int dy, int addflag);
  751. /*---------------------------------------------------------
  752.     low level prediction routine
  753.  
  754.     src:     prediction source
  755.     dst:     prediction destination
  756.     lx:      line width (for both src and dst)
  757.     x,y:     destination coordinates
  758.     dx,dy:   half pel motion vector
  759.     w,h:     size of prediction block
  760.     addflag: store or add prediction
  761. ---------------------------------------------------------*/
  762. static inline void PredComp(unsigned char *src, unsigned char *dst,
  763.                             int lx, int w, int h, int x, int y, int dx, int dy, int addflag);
  764. /*---------------------------------------------------------
  765.     calculate derived motion vectors (DMV) for dual prime prediction
  766.     dmvector[2]: differential motion vectors (-1,0,+1)
  767.     mvx,mvy: motion vector (for same parity)
  768.  
  769.     DMV[2][2]: derived motion vectors (for opposite parity)
  770.  
  771.     uses global variables pict_struct and topfirst
  772.  
  773.     Notes:
  774.      - all vectors are in field coordinates (even for frame pictures)
  775. ---------------------------------------------------------*/
  776. static void CalDMV(int DMV[][2], int *dmvector, int mvx,int mvy);
  777.  
  778. static inline void ClearBlock(unsigned char *cur[], int i0, int j0);
  779.  
  780. /*=========================================================
  781.     ò╧î`
  782. =========================================================*/
  783. /*---------------------------------------------------------
  784.     subtract prediction and transform prediction error
  785. ---------------------------------------------------------*/
  786. static void Transform(unsigned char* pred[],
  787.                        unsigned char* cur[],
  788.                        MACROBLOCKINFO* mbi,
  789.                        short blocks[][64]);
  790. /*---------------------------------------------------------
  791.     inverse transform prediction error and add prediction
  792. ---------------------------------------------------------*/
  793. static void ITransform(unsigned char* pred[],
  794.                         unsigned char* cur[],
  795.                         MACROBLOCKINFO* mbi,
  796.                         short blocks[][64]);
  797. /*---------------------------------------------------------
  798.     add prediction and prediction error, saturate to 0...255
  799. ---------------------------------------------------------*/
  800. static inline void AddPred(unsigned char* pred,unsigned char* cur,int lx,short* blk);
  801. /*---------------------------------------------------------
  802.     subtract prediction from block data
  803. ---------------------------------------------------------*/
  804. static inline void SubPred(unsigned char* pred,unsigned char* cur,int lx,short* blk);
  805. /*---------------------------------------------------------
  806.     select between frame and field DCT
  807.  
  808.     preliminary version: based on inter-field correlation
  809. ---------------------------------------------------------*/
  810. static void DCTTypeEstimation(unsigned char* pred,
  811.                              unsigned char* cur,
  812.                              MACROBLOCKINFO* mbi);
  813. /*=========================================================
  814.     PutPic
  815. =========================================================*/
  816. /*---------------------------------------------------------
  817.     quantization / variable length encoding of a complete picture
  818. ---------------------------------------------------------*/
  819. static TOMPGRET PutPicture(unsigned char* frame);
  820. /*---------------------------------------------------------
  821.     output motion vectors (6.2.5.2, 6.3.16.2)
  822.  
  823.     this routine also updates the predictions for motion vectors (PMV)
  824. ---------------------------------------------------------*/
  825. static void PutMotionVectors(int MV[2][2][2], int PMV[2][2][2],
  826.                             int mv_field_sel[2][2], int dmvector[2], int s, int motion_type,
  827.                             int hor_f_code, int vert_f_code);
  828. /*=========================================================
  829.     Put Mpeg
  830. =========================================================*/
  831. /*---------------------------------------------------------
  832.     generate variable length codes for an intra-coded block (6.2.6, 6.3.17)
  833. ---------------------------------------------------------*/
  834. static inline TOMPGRET PutIntraCodedBlock(short* blk,int cc);
  835. /*---------------------------------------------------------
  836.     generate variable length codes for a non-intra-coded block (6.2.6, 6.3.17)
  837. ---------------------------------------------------------*/
  838. static inline TOMPGRET PutNonIntraCodedBlock(short* blk);
  839. /*---------------------------------------------------------
  840.     generate variable length code for a motion vector component (7.6.3.1)
  841. ---------------------------------------------------------*/
  842. static void PutMotionVector(int dmv,int f_code);
  843. /*=========================================================
  844.     Put Variable Length Codes
  845. =========================================================*/
  846. /*---------------------------------------------------------
  847.     generate variable length code for luminance DC coefficient
  848. ---------------------------------------------------------*/
  849. static inline TOMPGRET PutLuminanceDCCoefficient(const int);
  850. /*---------------------------------------------------------
  851.     generate variable length code for chrominance DC coefficient
  852. ---------------------------------------------------------*/
  853. static inline TOMPGRET PutChrominanceDCCoefficient(const int);
  854. /*---------------------------------------------------------
  855.     generate variable length code for DC coefficient (7.2.1)
  856. ---------------------------------------------------------*/
  857. static TOMPGRET PutDC(const void*,const int);
  858. /*---------------------------------------------------------
  859.     generate variable length code for first coefficient
  860.     of a non-intra block (7.2.2.2)
  861. ---------------------------------------------------------*/
  862. static inline TOMPGRET PutACFirst(const int,const int);
  863. /*---------------------------------------------------------
  864.     generate variable length code for other DCT coefficients (7.2.2)
  865. ---------------------------------------------------------*/
  866. static TOMPGRET PutAC(const int,const int,const int);
  867. /*---------------------------------------------------------
  868.     generate variable length code for macroblock_address_increment
  869. ---------------------------------------------------------*/
  870. static inline void PutMacroblockAddressIncement(int);
  871. /*---------------------------------------------------------
  872.     generate variable length code for macroblock_type
  873. ---------------------------------------------------------*/
  874. static inline void PutMacroblockType(const int,const int);
  875. /*---------------------------------------------------------
  876.     generate variable length code for motion_code
  877. ---------------------------------------------------------*/
  878. static inline void PutMotionCode(const int);
  879. /*---------------------------------------------------------
  880.     generate variable length code for dmvector[t]
  881. ---------------------------------------------------------*/
  882. static void PutDMVector(const int);
  883. /*---------------------------------------------------------
  884.     generate variable length code for coded_block_pattern
  885.  
  886.     4:2:2, 4:4:4 not implemented
  887. ---------------------------------------------------------*/
  888. static inline void PutCodedBlockPattern(const int);
  889.  
  890. /*=========================================================
  891.     ù╩Äqë╗âeü[âuâïè╓îW
  892. =========================================================*/
  893. static inline int QuantIntra(short* src,short* dst,int dc_prec,
  894.                             unsigned char* quant_mat,unsigned short* recip_quant_mat,
  895.                             int mquant);
  896. static inline int QuantNonIntra(short* src,short* dst,
  897.                             unsigned char* quant_mat,
  898.                             unsigned short* recip_quant_mat,
  899.                             int mquant);
  900. /*---------------------------------------------------------
  901.     MPEG-1 inverse quantization
  902. ---------------------------------------------------------*/
  903. static void IQuantIntra(short* src,short* dst,int dc_prec,unsigned char* quant_mat,int mquant);
  904. static void IQuantNonIntra(short* src,short* dst,
  905.                           unsigned char* quant_mat,
  906.                           int mquant);
  907. /**********************************************************
  908.     âìü[âJâïò╧Éö é╠ÉΘî╛
  909. **********************************************************/
  910. static PICTURESTRUCT g_stPictureStruct;
  911. static PICTUREDATA g_stPictureData;
  912. static UVTEMPBUFFERS g_stUVTempBuffers;
  913. static CODINGMODELPARAMS g_stCodingModelParams;
  914. static SYSTEMDATA g_stSystemData;
  915. static SEQUENCEDATA g_stSequenceData;
  916. static cDCT g_cDCT;
  917. static TOMPEG_RATECONTROL g_stRateControl;
  918. static ADDFRAME_STRUCT g_stAddFrameStruct;
  919. static bool (*g_pProcFunction)(TOMPEG_PROCESS_PARAM,int);
  920.  
  921. static char g_szTmpVideoPath[260];
  922. static char g_szTmpAudioPath[260];
  923.  
  924. static int g_nWriteSequenceGrounp = 0;
  925. static int g_nSearchSize;
  926. static int g_nFastMotionCompensationLevel;
  927. static int g_nCurrentFrame;
  928.  
  929. /**********************************************************
  930.     SEQUENCEDATA é╠âüâôâoè╓Éöé╠ÉΘî╛
  931.  
  932.     ôαòöé┼ g_ZigZagScanArray é≡Ägùpé╡é─éóéΘòöò¬é¬éáéΘé╠é┼
  933.     ò╩é╠Ä└ìsâtâ@âCâïé╔é╖éΘé▒é╞é¬Åoùêé▄é╣é±é┼é╡é╜üièOòöÄQÅ╞îÖüIüj
  934. **********************************************************/
  935. void SEQUENCEDATA::PutSequenceHeader(SYSTEMDATA* pSystemData,const PICTURESTRUCT* pPictureStruct)
  936. {
  937.     int i;
  938.  
  939.     pSystemData->alignbits();
  940.     pSystemData->putbits(SEQ_START_CODE,32); /* sequence_header_code */
  941.     pSystemData->putbits(stHeader.nHFrameSize,12); /* horizontal_size_value */
  942.     pSystemData->putbits(stHeader.nVFrameSize,12); /* vertical_size_value */
  943.     pSystemData->putbits(stHeader.nAspectRatio,4); /* aspect_ratio_information */
  944.     pSystemData->putbits(stHeader.nFrameRateCode+1,4); /* frame_rate_code */
  945.     pSystemData->putbits((int)ceil(stHeader.fBitRate/400.0),18); /* bit_rate_value */
  946.     pSystemData->putbits(1,1); /* marker_bit */
  947.     pSystemData->putbits(stHeader.nVBVBufferSize,10); /* vbv_buffer_size_value */
  948.     pSystemData->putbits(stHeader.uConstrainedParams,1); /* constrained_parameters_flag */
  949.  
  950.     if (stHeader.bLoadIQuant)
  951.     {
  952.         pSystemData->putbits(1,1); /* load_intra_quantizer_matrix */
  953.         for (i=0; i<64; i++)  /* matrices are always downloaded in zig-zag order */
  954.             pSystemData->putbits(pPictureStruct->uIntraQArray[g_ZigZagScanArray[i]],8); /* intra_quantizer_matrix */
  955.     }
  956.     else
  957.         pSystemData->putbits(0,1);
  958.  
  959.     if (stHeader.bLoadNIQuant)
  960.     {
  961.         pSystemData->putbits(1,1); /* load_non_intra_quantizer_matrix */
  962.         for (i=0; i<64; i++)
  963.             pSystemData->putbits(pPictureStruct->uInterQArray[g_ZigZagScanArray[i]],8); /* non_intra_quantizer_matrix */
  964.     }
  965.     else
  966.         pSystemData->putbits(0,1); /* load_non_intra_quantizer_matrix */
  967.  
  968. }
  969. void SEQUENCEDATA::PutSequenceDisplayExtension(SYSTEMDATA* pSystemData)
  970. {
  971.     pSystemData->alignbits();
  972.     pSystemData->putbits(EXT_START_CODE,32); /* extension_start_code */
  973.     pSystemData->putbits(DISP_ID,4); /* extension_start_code_identifier */
  974.     pSystemData->putbits(stDisplayExtension.nVideoFormat,3); /* video_format */
  975.     pSystemData->putbits(1,1); /* colour_description */
  976.     pSystemData->putbits(stDisplayExtension.nColorPrimaries,8); /* colour_primaries */
  977.     pSystemData->putbits(stDisplayExtension.nTransferCharacteristics,8); /* transfer_characteristics */
  978.     pSystemData->putbits(stDisplayExtension.nMatrixCoefficients,8); /* matrix_coefficients */
  979.     pSystemData->putbits(stDisplayExtension.nDisplayHSize,14); /* display_horizontal_size */
  980.     pSystemData->putbits(1,1); /* marker_bit */
  981.     pSystemData->putbits(stDisplayExtension.nDisplayVSize,14); /* display_vertical_size */
  982.  
  983. }
  984. void SEQUENCEDATA::PutSequenceEndCode(SYSTEMDATA* pSystemData)
  985. {
  986.     pSystemData->alignbits();
  987.     pSystemData->putbits(SEQ_END_CODE,32);
  988. }
  989.  
  990.  
  991.  
  992. /**********************************************************
  993.     cTompeg é╠âüâôâoè╓Éöé╠ÉΘî╛
  994. **********************************************************/
  995. int WINAPI DllMain(HINSTANCE hInst, DWORD fdwReason, PVOID pvReserved)
  996. {
  997.     TOMPEG_Init();
  998.  
  999.     return TRUE;
  1000. }
  1001. /*---------------------------------------------------------
  1002.     âëâCâuâëâèé╠Åëè·ë╗
  1003. ---------------------------------------------------------*/
  1004. EXPORT void CALLBACK TOMPEG_Init(void)
  1005. {
  1006.     g_szTmpAudioPath[0] = '\0';
  1007.     g_szTmpVideoPath[0] = '\0';
  1008.  
  1009.     TOMPEG_Clear();
  1010. }
  1011. /*---------------------------------------------------------
  1012.     âüâéâèé╠ë≡ò·
  1013. ---------------------------------------------------------*/
  1014. EXPORT void CALLBACK TOMPEG_Clear(void)
  1015. {
  1016.     g_pProcFunction = NULL;
  1017.     g_nFastMotionCompensationLevel = 0;
  1018.     g_nCurrentFrame = 0;
  1019.  
  1020.     g_stUVTempBuffers.Clear();
  1021.     g_stPictureStruct.Clear();
  1022.     g_stSystemData.CloseOutFile();
  1023.  
  1024.     if(g_szTmpVideoPath[0]!='\0')
  1025.         DeleteFile(g_szTmpVideoPath);
  1026.     g_szTmpVideoPath[0] = '\0';
  1027.  
  1028.     if(g_szTmpAudioPath[0]!='\0')
  1029.         DeleteFile(g_szTmpAudioPath);
  1030.     g_szTmpAudioPath[0] = '\0';
  1031. }
  1032. /*---------------------------------------------------------
  1033.     âtâ@âCâïé≡ò█æ╢é╖éΘ
  1034. ---------------------------------------------------------*/
  1035. EXPORT TOMPGRET CALLBACK TOMPEG_SaveAs(const char* szFile)
  1036. {
  1037.     g_stSequenceData.PutSequenceEndCode(&g_stSystemData);
  1038.  
  1039.     g_stSystemData.flushbits();
  1040.     g_stSystemData.CloseOutFile();
  1041.     TOMPGRET ret;
  1042.  
  1043.     if(g_szTmpAudioPath[0] == '\0')
  1044.     {
  1045.         // âIü[âfâBâIâfü[â^é╚é╡
  1046.         if(!MoveFile(g_szTmpVideoPath,szFile))
  1047.         {
  1048.             return TR_ERR_RENAME_TMP_FILE;
  1049.         }
  1050.         g_szTmpVideoPath[0] = '\0';
  1051.     }
  1052.     else
  1053.     {
  1054.         // mplex
  1055.         if((ret = TOMPEG_ConvAudioAndVideo(g_szTmpVideoPath,g_szTmpAudioPath,szFile,g_pProcFunction))!=TR_OK)
  1056.         {
  1057.             return ret;
  1058.         }
  1059.     }
  1060.  
  1061.     TOMPEG_Clear();
  1062.  
  1063.     return TR_OK;
  1064. }
  1065. /*---------------------------------------------------------
  1066.     Äƒé╠âtâîü[âÇö╘ìåé≡ò╘é╖
  1067. ---------------------------------------------------------*/
  1068. EXPORT int CALLBACK TOMPEG_NextFrame(void)
  1069. {
  1070.     int f,j;
  1071.     int f0, n, np, nb;
  1072.  
  1073.     if(g_nCurrentFrame == 0)
  1074.     {
  1075.         RcInitSeq(); /* initialize rate control */
  1076.  
  1077.         /* sequence header, sequence extension and sequence display extension */
  1078.         g_stSequenceData.PutSequenceHeader(&g_stSystemData,&g_stPictureStruct);
  1079.  
  1080.         /* optionally output some text data (description, copyright or whatever) */
  1081.         PutUserData(VERSION_INFO);
  1082.  
  1083.     }
  1084.  
  1085.     /* f0: lowest frame number in current GOP
  1086.      *
  1087.      * first GOP contains N-(M-1) frames,
  1088.      * all other GOPs contain N frames
  1089.      */
  1090.  
  1091.     if(g_stCodingModelParams.nFramesNumberInGroupOfPicture == 0)
  1092.     {
  1093.         return TR_FRAME_NUMBER_IN_GROOUP_ERR;
  1094.     }
  1095.  
  1096.     f0 = g_stCodingModelParams.nFramesNumberInGroupOfPicture*((g_nCurrentFrame+(g_stCodingModelParams.nDistanceBetweenIPFrames-1))/g_stCodingModelParams.nFramesNumberInGroupOfPicture) - (g_stCodingModelParams.nDistanceBetweenIPFrames-1);
  1097.  
  1098.     if (f0<0)
  1099.         f0 = 0;
  1100.  
  1101.     if (g_nCurrentFrame==0 || (g_nCurrentFrame-1)%g_stCodingModelParams.nDistanceBetweenIPFrames==0)
  1102.     {
  1103.         /* I or P frame */
  1104.         for (j=0; j<3; j++)
  1105.         {
  1106.             /* shuffle reference frames */
  1107.             g_stAddFrameStruct.neworg[j] = g_stPictureStruct.stOriginalFrames.pOldFrame[j];
  1108.             g_stAddFrameStruct.newref[j] = g_stPictureStruct.stReconstructedFrames.pOldFrame[j];
  1109.             g_stPictureStruct.stOriginalFrames.pOldFrame[j] = g_stPictureStruct.stOriginalFrames.pNewFrame[j];
  1110.             g_stPictureStruct.stReconstructedFrames.pOldFrame[j] = g_stPictureStruct.stReconstructedFrames.pNewFrame[j];
  1111.             g_stPictureStruct.stOriginalFrames.pNewFrame[j] = g_stAddFrameStruct.neworg[j];
  1112.             g_stPictureStruct.stReconstructedFrames.pNewFrame[j] = g_stAddFrameStruct.newref[j];
  1113.         }
  1114.  
  1115.         /* f: frame number in display order */
  1116.         if(g_nCurrentFrame==0)
  1117.         {
  1118.             f = 0;
  1119.         }
  1120.         else
  1121.         {
  1122.             f = g_nCurrentFrame + g_stCodingModelParams.nDistanceBetweenIPFrames-1;
  1123.         }
  1124.  
  1125.         if (f >= g_stCodingModelParams.nTotalNumberOfFramesToEncode)
  1126.             f = g_stCodingModelParams.nTotalNumberOfFramesToEncode - 1;
  1127.  
  1128.         if (g_nCurrentFrame==f0) /* first displayed frame in GOP is I */
  1129.         {
  1130.             /* I frame */
  1131.             g_stPictureData.stHeader.nPictType = I_TYPE;
  1132.             g_stPictureData.stCodingExtension.nForwHorFCode = g_stPictureData.stCodingExtension.nForwVertFCode = 15;
  1133.             g_stPictureData.stCodingExtension.nBackHorFCode = g_stPictureData.stCodingExtension.nBackVertFCode = 15;
  1134.  
  1135.             /* n: number of frames in current GOP
  1136.             *
  1137.             * first GOP contains (M-1) less (B) frames
  1138.             */
  1139.             if(g_nCurrentFrame == 0)
  1140.             {
  1141.                 n = g_stCodingModelParams.nFramesNumberInGroupOfPicture-(g_stCodingModelParams.nDistanceBetweenIPFrames-1);
  1142.             }
  1143.             else
  1144.             {
  1145.                 n = g_stCodingModelParams.nFramesNumberInGroupOfPicture;
  1146.             }
  1147.  
  1148.             /* last GOP may contain less frames */
  1149.             if (n > g_stCodingModelParams.nTotalNumberOfFramesToEncode-f0)
  1150.                 n = g_stCodingModelParams.nTotalNumberOfFramesToEncode-f0;
  1151.  
  1152.             /* number of P frames */
  1153.             if (g_nCurrentFrame==0)
  1154.                 np = (n + 2*(g_stCodingModelParams.nDistanceBetweenIPFrames-1))/g_stCodingModelParams.nDistanceBetweenIPFrames - 1; /* first GOP */
  1155.             else
  1156.                 np = (n + (g_stCodingModelParams.nDistanceBetweenIPFrames-1))/g_stCodingModelParams.nDistanceBetweenIPFrames - 1;
  1157.  
  1158.             /* number of B frames */
  1159.             nb = n - np - 1;
  1160.  
  1161.             RcInitGOP(np,nb);
  1162.  
  1163.  
  1164.             /* Write sequence header to every g_nWriteSequenceGrounp-th GOP if required but skip 1st GOP  */
  1165.             if(g_nWriteSequenceGrounp) {
  1166.                 if(!((g_nCurrentFrame/g_stCodingModelParams.nFramesNumberInGroupOfPicture)%g_nWriteSequenceGrounp)&&(g_nCurrentFrame))
  1167.                     g_stSequenceData.PutSequenceHeader(&g_stSystemData,&g_stPictureStruct);
  1168.             }
  1169.             /* set closed_GOP in first GOP only */
  1170.             PutGroupHeader(f0,g_nCurrentFrame==0);
  1171.         }
  1172.         else
  1173.         {
  1174.         /* P frame */
  1175.             g_stPictureData.stHeader.nPictType = P_TYPE;
  1176.             g_stPictureData.stCodingExtension.nForwHorFCode = g_stPictureStruct.pstMotionData[0].forw_hor_f_code;
  1177.             g_stPictureData.stCodingExtension.nForwVertFCode = g_stPictureStruct.pstMotionData[0].forw_vert_f_code;
  1178.             g_stPictureData.stCodingExtension.nBackHorFCode = g_stPictureData.stCodingExtension.nBackVertFCode = 15;
  1179.             g_stAddFrameStruct.sxf = g_stPictureStruct.pstMotionData[0].sxf;
  1180.             g_stAddFrameStruct.syf = g_stPictureStruct.pstMotionData[0].syf;
  1181.         }
  1182.     }
  1183.     else
  1184.     {
  1185.         /* B frame */
  1186.         for (j=0; j<3; j++)
  1187.         {
  1188.             g_stAddFrameStruct.neworg[j] = g_stPictureStruct.stOriginalFrames.pAuxFrame[j];
  1189.             g_stAddFrameStruct.newref[j] = g_stPictureStruct.stReconstructedFrames.pAuxFrame[j];
  1190.         }
  1191.  
  1192.         /* f: frame number in display order */
  1193.         f = g_nCurrentFrame - 1;
  1194.         g_stPictureData.stHeader.nPictType = B_TYPE;
  1195.         n = (g_nCurrentFrame-2)%g_stCodingModelParams.nDistanceBetweenIPFrames + 1; /* first B: n=1, second B: n=2, ... */
  1196.         g_stPictureData.stCodingExtension.nForwHorFCode = g_stPictureStruct.pstMotionData[n].forw_hor_f_code;
  1197.         g_stPictureData.stCodingExtension.nForwVertFCode = g_stPictureStruct.pstMotionData[n].forw_vert_f_code;
  1198.         g_stPictureData.stCodingExtension.nBackHorFCode = g_stPictureStruct.pstMotionData[n].back_hor_f_code;
  1199.         g_stPictureData.stCodingExtension.nBackVertFCode = g_stPictureStruct.pstMotionData[n].back_vert_f_code;
  1200.         g_stAddFrameStruct.sxf = g_stPictureStruct.pstMotionData[n].sxf;
  1201.         g_stAddFrameStruct.syf = g_stPictureStruct.pstMotionData[n].syf;
  1202.         g_stAddFrameStruct.sxb = g_stPictureStruct.pstMotionData[n].sxb;
  1203.         g_stAddFrameStruct.syb = g_stPictureStruct.pstMotionData[n].syb;
  1204.     }
  1205.  
  1206.     g_stPictureData.stHeader.nTempRef = f - f0;
  1207.     g_stPictureData.stCodingExtension.bFramePredDCT = g_stPictureData.stCodingExtension.bFramePredDCTTab[g_stPictureData.stHeader.nPictType-1];
  1208.     g_stPictureData.stCodingExtension.bQScaleType = g_stPictureData.stCodingExtension.bQScaleTab[g_stPictureData.stHeader.nPictType-1];
  1209.     g_stPictureData.stCodingExtension.bIntravlc = g_stPictureData.stCodingExtension.bIntravlcTab[g_stPictureData.stHeader.nPictType-1];
  1210.     g_stPictureData.stCodingExtension.bAltScan = g_stPictureData.stCodingExtension.bAltScanTab[g_stPictureData.stHeader.nPictType-1];
  1211.  
  1212.     g_nCurrentFrame++;
  1213.  
  1214.     if(g_pProcFunction!=NULL)
  1215.     {
  1216.         if(!g_pProcFunction(TOMPEG_PROCESS_ENCODE_M1V,g_nCurrentFrame*100/g_stCodingModelParams.nTotalNumberOfFramesToEncode))
  1217.         {
  1218.             return -1;
  1219.         }
  1220.     }
  1221.  
  1222.     return f;
  1223. }
  1224. /*---------------------------------------------------------
  1225.     ëµæ£é≡Æ╟ë┴é╖éΘ
  1226. ---------------------------------------------------------*/
  1227. EXPORT TOMPGRET CALLBACK TOMPEG_AddFrame(const LPBITMAPINFO lpInfo,const unsigned char* pBytes)
  1228. {
  1229.     static const char ipb[5] = {' ','I','P','B','D'};
  1230.     TOMPGRET ret;
  1231.     bool ipflag;
  1232.     int j,k;
  1233.  
  1234.     if((ret = ConvRGBtoYUV(lpInfo,pBytes,g_stAddFrameStruct.neworg))!=TR_OK)
  1235.     {
  1236.         return ret;
  1237.     }
  1238.  
  1239.     if (g_stCodingModelParams.bFieldPicture)
  1240.     {
  1241.  
  1242.         if(g_stPictureData.stCodingExtension.bTopFirst)
  1243.         {
  1244.             g_stPictureData.stCodingExtension.nPictStruct = TOP_FIELD;
  1245.         }
  1246.         else
  1247.         {
  1248.             g_stPictureData.stCodingExtension.nPictStruct = BOTTOM_FIELD;
  1249.         }
  1250.  
  1251.         MotionEstimation(g_stPictureStruct.stOriginalFrames.pOldFrame[0],
  1252.                         g_stPictureStruct.stOriginalFrames.pNewFrame[0],
  1253.                         g_stPictureStruct.stReconstructedFrames.pOldFrame[0],
  1254.                         g_stPictureStruct.stReconstructedFrames.pNewFrame[0],
  1255.                         g_stAddFrameStruct.neworg[0],g_stAddFrameStruct.newref[0],
  1256.                         g_stAddFrameStruct.sxf,g_stAddFrameStruct.syf,g_stAddFrameStruct.sxb,g_stAddFrameStruct.syb,
  1257.                         g_stPictureStruct.pstMacroBlockInfo,
  1258.                         0,0);
  1259.  
  1260.         Predict(g_stPictureStruct.stReconstructedFrames.pOldFrame,
  1261.                 g_stPictureStruct.stReconstructedFrames.pNewFrame,
  1262.                 g_stPictureStruct.pPredictionFrameArray,
  1263.                 0,
  1264.                 g_stPictureStruct.pstMacroBlockInfo);
  1265.         DCTTypeEstimation(g_stPictureStruct.pPredictionFrameArray[0],
  1266.                         g_stAddFrameStruct.neworg[0],
  1267.                         g_stPictureStruct.pstMacroBlockInfo);
  1268.         Transform(g_stPictureStruct.pPredictionFrameArray,
  1269.                 g_stAddFrameStruct.neworg,
  1270.                 g_stPictureStruct.pstMacroBlockInfo,
  1271.                 g_stPictureStruct.pBlocksArray);
  1272.  
  1273.         if((ret = PutPicture(g_stAddFrameStruct.neworg[0]))!=TR_OK)
  1274.         {
  1275.             return ret;
  1276.         }
  1277.  
  1278.         for (k=0; k<g_stSequenceData.stHeader.nMacroBlocksHeight2*g_stSequenceData.stHeader.nMacroBlocksWidth; k++)
  1279.         {
  1280.             if (g_stPictureStruct.pstMacroBlockInfo[k].mb_type & MB_INTRA)
  1281.                 for (j=0; j<g_stSequenceData.stHeader.nBlockCount; j++)
  1282.                     IQuantIntra(g_stPictureStruct.pBlocksArray[k*g_stSequenceData.stHeader.nBlockCount+j],
  1283.                                 g_stPictureStruct.pBlocksArray[k*g_stSequenceData.stHeader.nBlockCount+j],
  1284.                                 g_stPictureData.stCodingExtension.nDCPrecision,
  1285.                                 g_stPictureStruct.uIntraQArray,
  1286.                                 g_stPictureStruct.pstMacroBlockInfo[k].mquant);
  1287.             else
  1288.                 for (j=0;j<g_stSequenceData.stHeader.nBlockCount;j++)
  1289.                     IQuantNonIntra(g_stPictureStruct.pBlocksArray[k*g_stSequenceData.stHeader.nBlockCount+j],
  1290.                                 g_stPictureStruct.pBlocksArray[k*g_stSequenceData.stHeader.nBlockCount+j],
  1291.                                 g_stPictureStruct.uInterQArray,
  1292.                                 g_stPictureStruct.pstMacroBlockInfo[k].mquant);
  1293.         }
  1294.  
  1295.         ITransform(g_stPictureStruct.pPredictionFrameArray,
  1296.                 g_stAddFrameStruct.newref,
  1297.                 g_stPictureStruct.pstMacroBlockInfo,
  1298.                 g_stPictureStruct.pBlocksArray);
  1299.  
  1300.  
  1301.         if(g_stPictureData.stCodingExtension.bTopFirst)
  1302.         {
  1303.             g_stPictureData.stCodingExtension.nPictStruct = BOTTOM_FIELD;
  1304.         }
  1305.         else
  1306.         {
  1307.             g_stPictureData.stCodingExtension.nPictStruct = TOP_FIELD;
  1308.         }
  1309.  
  1310.         if(g_stPictureData.stHeader.nPictType==I_TYPE)
  1311.         {
  1312.             ipflag = true;
  1313.         }
  1314.         else
  1315.         {
  1316.             ipflag = false;
  1317.         }
  1318.         if (ipflag)
  1319.         {
  1320.             /* first field = I, second field = P */
  1321.             g_stPictureData.stHeader.nPictType = P_TYPE;
  1322.             g_stPictureData.stCodingExtension.nForwHorFCode = g_stPictureStruct.pstMotionData[0].forw_hor_f_code;
  1323.             g_stPictureData.stCodingExtension.nForwVertFCode = g_stPictureStruct.pstMotionData[0].forw_vert_f_code;
  1324.             g_stPictureData.stCodingExtension.nBackHorFCode = g_stPictureData.stCodingExtension.nBackVertFCode = 15;
  1325.             g_stAddFrameStruct.sxf = g_stPictureStruct.pstMotionData[0].sxf;
  1326.             g_stAddFrameStruct.syf = g_stPictureStruct.pstMotionData[0].syf;
  1327.         }
  1328.  
  1329.         MotionEstimation(g_stPictureStruct.stOriginalFrames.pOldFrame[0],
  1330.                         g_stPictureStruct.stOriginalFrames.pNewFrame[0],
  1331.                         g_stPictureStruct.stReconstructedFrames.pOldFrame[0],
  1332.                         g_stPictureStruct.stReconstructedFrames.pNewFrame[0],
  1333.                         g_stAddFrameStruct.neworg[0],g_stAddFrameStruct.newref[0],
  1334.                         g_stAddFrameStruct.sxf,g_stAddFrameStruct.syf,g_stAddFrameStruct.sxb,g_stAddFrameStruct.syb,
  1335.                         g_stPictureStruct.pstMacroBlockInfo,
  1336.                         1,ipflag);
  1337.  
  1338.         Predict(g_stPictureStruct.stReconstructedFrames.pOldFrame,
  1339.                 g_stPictureStruct.stReconstructedFrames.pNewFrame,
  1340.                 g_stPictureStruct.pPredictionFrameArray,
  1341.                 1,
  1342.                 g_stPictureStruct.pstMacroBlockInfo);
  1343.         DCTTypeEstimation(g_stPictureStruct.pPredictionFrameArray[0],
  1344.                         g_stAddFrameStruct.neworg[0],
  1345.                         g_stPictureStruct.pstMacroBlockInfo);
  1346.         Transform(g_stPictureStruct.pPredictionFrameArray,
  1347.                 g_stAddFrameStruct.neworg,
  1348.                 g_stPictureStruct.pstMacroBlockInfo,
  1349.                 g_stPictureStruct.pBlocksArray);
  1350.  
  1351.         PutPicture(g_stAddFrameStruct.neworg[0]);
  1352.  
  1353.         for (k=0; k<g_stSequenceData.stHeader.nMacroBlocksHeight2*g_stSequenceData.stHeader.nMacroBlocksWidth; k++)
  1354.         {
  1355.             if (g_stPictureStruct.pstMacroBlockInfo[k].mb_type & MB_INTRA)
  1356.                 for (j=0; j<g_stSequenceData.stHeader.nBlockCount; j++)
  1357.                     IQuantIntra(g_stPictureStruct.pBlocksArray[k*g_stSequenceData.stHeader.nBlockCount+j],
  1358.                                 g_stPictureStruct.pBlocksArray[k*g_stSequenceData.stHeader.nBlockCount+j],
  1359.                                 g_stPictureData.stCodingExtension.nDCPrecision,
  1360.                                 g_stPictureStruct.uIntraQArray,
  1361.                                 g_stPictureStruct.pstMacroBlockInfo[k].mquant);
  1362.             else
  1363.                 for (j=0;j<g_stSequenceData.stHeader.nBlockCount;j++)
  1364.                     IQuantNonIntra(g_stPictureStruct.pBlocksArray[k*g_stSequenceData.stHeader.nBlockCount+j],
  1365.                                 g_stPictureStruct.pBlocksArray[k*g_stSequenceData.stHeader.nBlockCount+j],
  1366.                                 g_stPictureStruct.uInterQArray,
  1367.                                 g_stPictureStruct.pstMacroBlockInfo[k].mquant);
  1368.         }
  1369.  
  1370.         ITransform(g_stPictureStruct.pPredictionFrameArray,
  1371.         g_stAddFrameStruct.newref,
  1372.         g_stPictureStruct.pstMacroBlockInfo,
  1373.         g_stPictureStruct.pBlocksArray);
  1374.     }
  1375.     else
  1376.     {
  1377.         g_stPictureData.stCodingExtension.nPictStruct = FRAME_PICTURE;
  1378.  
  1379.         /* do motion_estimation
  1380.         *
  1381.         * uses source frames (...orgframe) for full pel search
  1382.         * and reconstructed frames (...refframe) for half pel search
  1383.         */
  1384.  
  1385.         MotionEstimation(g_stPictureStruct.stOriginalFrames.pOldFrame[0],
  1386.                         g_stPictureStruct.stOriginalFrames.pNewFrame[0],
  1387.                         g_stPictureStruct.stReconstructedFrames.pOldFrame[0],
  1388.                         g_stPictureStruct.stReconstructedFrames.pNewFrame[0],
  1389.                         g_stAddFrameStruct.neworg[0],g_stAddFrameStruct.newref[0],
  1390.                         g_stAddFrameStruct.sxf,g_stAddFrameStruct.syf,g_stAddFrameStruct.sxb,g_stAddFrameStruct.syb,
  1391.                         g_stPictureStruct.pstMacroBlockInfo,
  1392.                         0,0);
  1393.  
  1394.         Predict(g_stPictureStruct.stReconstructedFrames.pOldFrame,
  1395.                 g_stPictureStruct.stReconstructedFrames.pNewFrame,
  1396.                 g_stPictureStruct.pPredictionFrameArray,
  1397.                 0,
  1398.                 g_stPictureStruct.pstMacroBlockInfo);
  1399.         DCTTypeEstimation(g_stPictureStruct.pPredictionFrameArray[0],
  1400.                         g_stAddFrameStruct.neworg[0],
  1401.                         g_stPictureStruct.pstMacroBlockInfo);
  1402.         Transform(g_stPictureStruct.pPredictionFrameArray,
  1403.                 g_stAddFrameStruct.neworg,
  1404.                 g_stPictureStruct.pstMacroBlockInfo,
  1405.                 g_stPictureStruct.pBlocksArray);
  1406.  
  1407.         PutPicture(g_stAddFrameStruct.neworg[0]);
  1408.  
  1409.         for (k=0; k<g_stSequenceData.stHeader.nMacroBlocksHeight*g_stSequenceData.stHeader.nMacroBlocksWidth; k++)
  1410.         {
  1411.             if (g_stPictureStruct.pstMacroBlockInfo[k].mb_type & MB_INTRA)
  1412.                 for (j=0; j<g_stSequenceData.stHeader.nBlockCount; j++)
  1413.                     IQuantIntra(g_stPictureStruct.pBlocksArray[k*g_stSequenceData.stHeader.nBlockCount+j],
  1414.                         g_stPictureStruct.pBlocksArray[k*g_stSequenceData.stHeader.nBlockCount+j],
  1415.                         g_stPictureData.stCodingExtension.nDCPrecision,
  1416.                         g_stPictureStruct.uIntraQArray,
  1417.                         g_stPictureStruct.pstMacroBlockInfo[k].mquant);
  1418.             else
  1419.                 for (j=0;j<g_stSequenceData.stHeader.nBlockCount;j++)
  1420.                     IQuantNonIntra(g_stPictureStruct.pBlocksArray[k*g_stSequenceData.stHeader.nBlockCount+j],
  1421.                                     g_stPictureStruct.pBlocksArray[k*g_stSequenceData.stHeader.nBlockCount+j],
  1422.                                     g_stPictureStruct.uInterQArray,
  1423.                                     g_stPictureStruct.pstMacroBlockInfo[k].mquant);
  1424.         }
  1425.  
  1426.         ITransform(g_stPictureStruct.pPredictionFrameArray,
  1427.                     g_stAddFrameStruct.newref,
  1428.                     g_stPictureStruct.pstMacroBlockInfo,
  1429.                     g_stPictureStruct.pBlocksArray);
  1430.     }
  1431.  
  1432. //    sprintf(name,g_stSystemData.szTPlref,f+g_stCodingModelParams.nNumberOfFirstFrame);
  1433. //    g_stSequenceData.WriteFrame(name,newref);
  1434.  
  1435.  
  1436.     return TR_OK;
  1437. }
  1438. /*---------------------------------------------------------
  1439.     ì∞ɼèJÄn
  1440. ---------------------------------------------------------*/
  1441. EXPORT TOMPGRET CALLBACK TOMPEG_Start(const TOMPEG_VIDEO_FORMAT* pTompegFormat,
  1442.                                       const char* szTmpVideoPath,
  1443.                                       const char* szTmpAudioPath,
  1444.                                       bool(* CallBack)(TOMPEG_PROCESS_PARAM,int))
  1445. {
  1446.     const double fRateArray[8]= {24000.0/1001.0,24.0,25.0,30000.0/1001.0,30.0,50.0,60000.0/1001.0,60.0};
  1447.     TOMPGRET ret;
  1448.     int i, size;
  1449.     int block_count_tab[3] = {6,8,12};
  1450.     double tmp_rate = ((double)pTompegFormat->nRate)/((double)pTompegFormat->nScale);
  1451.     double min_err,err;
  1452.  
  1453.     //---------------- êΩÄ₧âtâ@âCâïé╠âpâXé≡ì∞ɼé╖éΘ ----------------//
  1454.     if(szTmpVideoPath != NULL)
  1455.     {
  1456.         strncpy(g_szTmpVideoPath,szTmpVideoPath,sizeof(g_szTmpVideoPath));
  1457.     }
  1458.     else
  1459.     {
  1460.         MakeTmpFilePath(g_szTmpVideoPath,sizeof(g_szTmpVideoPath),"tmp.m1v");
  1461.     }
  1462.     
  1463.     g_szTmpAudioPath[0] = '\0';
  1464.     if(pTompegFormat->stAudioFormat.pAudioStream!=NULL)
  1465.     {
  1466.         if(szTmpAudioPath != NULL)
  1467.         {
  1468.             strncpy(g_szTmpAudioPath,szTmpAudioPath,sizeof(g_szTmpAudioPath));
  1469.         }
  1470.         else
  1471.         {
  1472.             MakeTmpFilePath(g_szTmpAudioPath,sizeof(g_szTmpAudioPath),"tmp.mp2");
  1473.         }
  1474.     }
  1475.  
  1476.     //---------------- ò╧Éöé╠É▌ÆΦ ----------------------------------//
  1477.     g_pProcFunction = CallBack;
  1478.  
  1479.     g_nWriteSequenceGrounp = pTompegFormat->nWriteSequenceGrounp;
  1480.     g_stSequenceData.stHeader.nVBVBufferSize = pTompegFormat->nVBVBufferSize;
  1481.     g_stSequenceData.stDisplayExtension.nDisplayHSize = pTompegFormat->nWidth;
  1482.     g_stSequenceData.stDisplayExtension.nDisplayVSize = pTompegFormat->nHeight;
  1483.     g_stCodingModelParams.nTotalNumberOfFramesToEncode = pTompegFormat->uLength;
  1484.  
  1485.     // âtâîü[âÇâîü[âgé≡îvÄZ
  1486.     min_err = fabs(fRateArray[0] - tmp_rate);
  1487.     g_stSequenceData.stHeader.nFrameRateCode = 0;
  1488.     for(i=1;i<sizeof(fRateArray)/sizeof(fRateArray[0]);i++)
  1489.     {
  1490.         err = fabs(fRateArray[i] - tmp_rate);
  1491.         if(err<min_err)
  1492.         {
  1493.             g_stSequenceData.stHeader.nFrameRateCode = i;
  1494.         }
  1495.     }
  1496.     g_stSequenceData.stHeader.fFrameRate = fRateArray[g_stSequenceData.stHeader.nFrameRateCode];
  1497.     
  1498.     if(pTompegFormat->stAudioFormat.pAudioStream==NULL)
  1499.     {
  1500.         g_stSequenceData.stHeader.fBitRate = (double)(pTompegFormat->uSystemByteRateParam*8*1024);
  1501.     }
  1502.     else
  1503.     {
  1504.         g_stSequenceData.stHeader.fBitRate = (double)(pTompegFormat->uSystemByteRateParam*8*1024) - (double)(pTompegFormat->stAudioFormat.uAudioBitrateParam*1024) - (float)(4*8*1024);
  1505.         g_stSequenceData.stHeader.fBitRate = g_stSequenceData.stHeader.fBitRate * 0.9; // allow some room for the bitrate to overun...
  1506.         if(g_stSequenceData.stHeader.fBitRate <= 81920.0)
  1507.         {
  1508.             return TR_BITRATE_ERR;
  1509.         }
  1510.     }
  1511.  
  1512.     g_nSearchSize = pTompegFormat->nSearchSize;
  1513.     if(g_nSearchSize<0||g_nSearchSize>4)
  1514.     {
  1515.         return TR_SEARCH_SIZE_ERR;
  1516.     }
  1517.  
  1518.     if((pTompegFormat->uSystemByteRateParam < 10)
  1519.         ||(pTompegFormat->uSystemByteRateParam > 5000))
  1520.     {
  1521.         return TR_ERR_SYSTEM_BYTE_RATE_PARAM;
  1522.     }
  1523.  
  1524.     g_stSequenceData.stHeader.nHFrameSize = ((g_stSequenceData.stDisplayExtension.nDisplayHSize + 15)>>4)<<4; // make it multiple of 16
  1525.     g_stSequenceData.stHeader.nVFrameSize = ((g_stSequenceData.stDisplayExtension.nDisplayVSize + 3)>>2)<<2;
  1526.  
  1527.     g_nFastMotionCompensationLevel = pTompegFormat->nFastMotionCompensationLevel;
  1528.     if(g_nFastMotionCompensationLevel < 0 
  1529.         || g_nFastMotionCompensationLevel > 3)
  1530.     {
  1531.         return TR_FAST_MOTION_COMP_LEVEL_ERR;
  1532.     }
  1533.  
  1534.     if((ret=SetParam())!=TR_OK)
  1535.     {
  1536.         return ret;
  1537.     }
  1538.  
  1539.     //---------------- ù╩Äqë╗âeü[âuâïé╠Åëè·ë╗ ----------------------------//
  1540.     if (pTompegFormat->pQuantizerMatrix == NULL)
  1541.     {
  1542.         /* use default intra matrix */
  1543.         const unsigned char default_intra_quantizer_matrix[64] = 
  1544.         {
  1545.             8, 16, 19, 22, 26, 27, 29, 34,
  1546.             16, 16, 22, 24, 27, 29, 34, 37,
  1547.             19, 22, 26, 27, 29, 34, 34, 38,
  1548.             22, 22, 26, 27, 29, 34, 37, 40,
  1549.             22, 26, 27, 29, 32, 35, 40, 48,
  1550.             26, 27, 29, 32, 35, 40, 48, 58,
  1551.             26, 27, 29, 34, 38, 46, 56, 69,
  1552.             27, 29, 35, 38, 46, 56, 69, 83
  1553.         };
  1554.         g_stSequenceData.stHeader.bLoadIQuant = false;
  1555.         memcpy(g_stPictureStruct.uIntraQArray,default_intra_quantizer_matrix,sizeof(g_stPictureStruct.uIntraQArray));        
  1556.     }
  1557.     else
  1558.     {
  1559.         g_stSequenceData.stHeader.bLoadIQuant = true;    
  1560.         memcpy(g_stPictureStruct.uIntraQArray,pTompegFormat->pQuantizerMatrix,sizeof(g_stPictureStruct.uIntraQArray));        
  1561.     }
  1562.     for (i=0; i<64; i++)
  1563.     {
  1564.         if(g_stPictureStruct.uIntraQArray[i]==0)
  1565.         {
  1566.             g_stPictureStruct.uIntraQArray[i] = 1;
  1567.         }
  1568.         g_stPictureStruct.uRecipIntraQArray[i] = (unsigned short)((16384.0 + (double) g_stPictureStruct.uIntraQArray[i]/2.0)/g_stPictureStruct.uIntraQArray[i]);
  1569.     }
  1570.  
  1571.     if (pTompegFormat->pNonIntraMatrix == NULL)
  1572.     {
  1573.         /* use default non-intra matrix */
  1574.         g_stSequenceData.stHeader.bLoadNIQuant = false;
  1575.         for (i=0; i<64; i++)
  1576.         {
  1577.             g_stPictureStruct.uInterQArray[i] = 16;
  1578.         }
  1579.     }
  1580.     else
  1581.     {
  1582.         /* read customized non-intra matrix */
  1583.         g_stSequenceData.stHeader.bLoadNIQuant = true;
  1584.         memcpy(g_stPictureStruct.uInterQArray,pTompegFormat->pNonIntraMatrix,sizeof(g_stPictureStruct.uInterQArray));        
  1585.     }
  1586.     for (i=0; i<64; i++)
  1587.     {
  1588.         if(g_stPictureStruct.uInterQArray[i]==0)
  1589.         {
  1590.             g_stPictureStruct.uInterQArray[i] = 1;
  1591.         }
  1592.         g_stPictureStruct.uRecipInterQArray[i] = (unsigned short)((16384.0 + (double) g_stPictureStruct.uInterQArray[i]/2.0)/g_stPictureStruct.uInterQArray[i]);
  1593.     }
  1594.  
  1595.     g_stSystemData.initbits();
  1596.  
  1597.     /* round picture dimensions to nearest multiple of 16 or 32 */
  1598.     g_stSequenceData.stHeader.nMacroBlocksWidth = (g_stSequenceData.stHeader.nHFrameSize+15)/16;
  1599.     if(g_stSequenceData.stExtension.bProgressSequence)
  1600.     {
  1601.         g_stSequenceData.stHeader.nMacroBlocksHeight = (g_stSequenceData.stHeader.nVFrameSize+15)/16;
  1602.     }
  1603.     else
  1604.     {
  1605.         g_stSequenceData.stHeader.nMacroBlocksHeight = 2*((g_stSequenceData.stHeader.nVFrameSize+31)/32);
  1606.     }
  1607.     if(g_stCodingModelParams.bFieldPicture)
  1608.     {
  1609.         g_stSequenceData.stHeader.nMacroBlocksHeight2 = g_stSequenceData.stHeader.nMacroBlocksHeight>>1;
  1610.     }
  1611.     else
  1612.     {
  1613.         g_stSequenceData.stHeader.nMacroBlocksHeight2 = g_stSequenceData.stHeader.nMacroBlocksHeight;
  1614.     }
  1615.     g_stSequenceData.stHeader.nWidth = 16*g_stSequenceData.stHeader.nMacroBlocksWidth;
  1616.     g_stSequenceData.stHeader.nHeight = 16*g_stSequenceData.stHeader.nMacroBlocksHeight;
  1617.  
  1618.     if(g_stSequenceData.stExtension.nChromaFormat==CHROMA444)
  1619.     {
  1620.         g_stSequenceData.stHeader.nChromWidth = g_stSequenceData.stHeader.nWidth;
  1621.     }
  1622.     else
  1623.     {
  1624.         g_stSequenceData.stHeader.nChromWidth = g_stSequenceData.stHeader.nWidth>>1;
  1625.     }
  1626.     if(g_stSequenceData.stExtension.nChromaFormat!=CHROMA420)
  1627.     {
  1628.         g_stSequenceData.stHeader.nChromHeight =  g_stSequenceData.stHeader.nHeight;
  1629.     }
  1630.     else
  1631.     {
  1632.         g_stSequenceData.stHeader.nChromHeight =  g_stSequenceData.stHeader.nHeight>>1;
  1633.     }
  1634.  
  1635.     if(g_stCodingModelParams.bFieldPicture)
  1636.     {
  1637.         g_stSequenceData.stHeader.nHeight2 =  g_stSequenceData.stHeader.nHeight>>1;
  1638.     }
  1639.     else
  1640.     {
  1641.         g_stSequenceData.stHeader.nHeight2 =  g_stSequenceData.stHeader.nHeight;
  1642.     }
  1643.     if(g_stCodingModelParams.bFieldPicture)
  1644.     {
  1645.         g_stSequenceData.stHeader.nWidth2 = g_stSequenceData.stHeader.nWidth<<1;
  1646.     }
  1647.     else
  1648.     {
  1649.         g_stSequenceData.stHeader.nWidth2 = g_stSequenceData.stHeader.nWidth;
  1650.     }
  1651.     if(g_stCodingModelParams.bFieldPicture)
  1652.     {
  1653.         g_stSequenceData.stHeader.nChromWidth2 = g_stSequenceData.stHeader.nChromWidth<<1;
  1654.     }
  1655.     else
  1656.     {
  1657.         g_stSequenceData.stHeader.nChromWidth2 = g_stSequenceData.stHeader.nChromWidth;
  1658.     }
  1659.  
  1660.     g_stSequenceData.stHeader.nBlockCount = block_count_tab[g_stSequenceData.stExtension.nChromaFormat-1];
  1661.  
  1662.     /* clip table */
  1663.     if(!g_stPictureStruct.MakeClippingTable())
  1664.     {
  1665.         return TR_ERR_MAKE_CLIPPING_TABLE;
  1666.     }
  1667.     
  1668.  
  1669.     for (i=0; i<3; i++)
  1670.     {
  1671.         if(i == 0)
  1672.         {
  1673.             size = g_stSequenceData.stHeader.nWidth*g_stSequenceData.stHeader.nHeight;
  1674.         }
  1675.         else
  1676.         {
  1677.             size = g_stSequenceData.stHeader.nChromWidth*g_stSequenceData.stHeader.nChromHeight;
  1678.         }
  1679.  
  1680.         if(!g_stPictureStruct.AllocFrames(i,size))
  1681.         {
  1682.             return TR_ERR_ALLOC_FRAMES;
  1683.         }
  1684.     }
  1685.  
  1686.     // now allocate space U and V buffers for readpic routine
  1687.  
  1688.  
  1689.     if (!g_stPictureStruct.AllocMacloBlockInfo(g_stSequenceData.stHeader.nMacroBlocksWidth*g_stSequenceData.stHeader.nMacroBlocksHeight2))
  1690.     {
  1691.         return TR_ERR_ALLOC_BLOCK_INFO;
  1692.     }
  1693.  
  1694.     if(!g_stUVTempBuffers.Alloc(g_stSequenceData.stHeader.nWidth*g_stSequenceData.stHeader.nHeight,
  1695.         pTompegFormat->bUseImageNoiseReduction))
  1696.     {
  1697.         return TR_ERR_ALLOC_TEMP_UV_BUFFER;
  1698.     }
  1699.  
  1700.     if (!g_stPictureStruct.AllocBlockArray(g_stSequenceData.stHeader.nMacroBlocksWidth*g_stSequenceData.stHeader.nMacroBlocksHeight2*g_stSequenceData.stHeader.nBlockCount))
  1701.     {
  1702.         return TR_ERR_ALLOC_BLOCK_ARRAY;
  1703.     }
  1704.  
  1705.     if(pTompegFormat->stAudioFormat.pAudioStream!=NULL)
  1706.     {
  1707.         if((ret = TOMPEG_PCM2MP(g_szTmpAudioPath,
  1708.             &(pTompegFormat->stAudioFormat),
  1709.             g_pProcFunction))!=TR_OK)
  1710.         {
  1711.             return ret;
  1712.         }
  1713.     }
  1714.  
  1715.     /* open output file */
  1716.     if (!g_stSystemData.OpenOutFile(g_szTmpVideoPath))
  1717.         return TR_ERR_OPEN_FILE;
  1718.  
  1719.     return TR_OK;
  1720. }
  1721. /*---------------------------------------------------------
  1722.     êΩÄ₧âtâ@âCâïé╠âpâXé╠ì∞ɼ
  1723. ---------------------------------------------------------*/
  1724. static void MakeTmpFilePath(char* szPath,unsigned long uLength,char *szFname)
  1725. {
  1726.     unsigned int i;
  1727.     GetCurrentDirectory(uLength,szPath);
  1728.     for(i=1;i<uLength;i++)
  1729.     {
  1730.         if(szPath[i] == '\0')
  1731.         {
  1732.             if(szPath[i-1] != '\\')
  1733.             {
  1734.                 lstrcat(szPath,"\\");
  1735.             }
  1736.             lstrcat(szPath,szFname);
  1737.             break;
  1738.         }
  1739.     }
  1740. }
  1741. /*---------------------------------------------------------
  1742.     ò╧Éöé╠É▌ÆΦ
  1743. ---------------------------------------------------------*/
  1744. inline TOMPGRET SetParam(void)
  1745. {
  1746.     TOMPGRET ret;
  1747.     int i;
  1748.     int h,m,s,f;
  1749.  
  1750.     //char temp[256]="Encoded by AVI2MPG1 Version ";
  1751.  
  1752.     // several of the encoding parameters are implied by the source file
  1753.     // format, lets get these parameters from the .avi file.
  1754.  
  1755.     //strcpy(g_stSystemData.szTPlref, "-");
  1756.     //strcpy(g_stSystemData.szStatName, "nul:");
  1757.  
  1758.     // lets assume starts at frame 0
  1759.     //g_stCodingModelParams.nNumberOfFirstFrame = 0;
  1760.  
  1761.     g_stCodingModelParams.bFieldPicture = false; // frame pictures only for mpeg1
  1762.  
  1763.     // g_stSequenceData.stHeader.fBitRate = 1856000;  // max SIF
  1764.     g_stSequenceData.stExtension.bLowDelay = false;     
  1765.     g_stSequenceData.stExtension.bProgressSequence = true;
  1766.     g_stSequenceData.stExtension.nChromaFormat = 1; // 4:2:0
  1767.     g_stPictureData.stCodingExtension.bConcealTab[0] = false;
  1768.     g_stPictureData.stCodingExtension.bConcealTab[1] = false;
  1769.     g_stPictureData.stCodingExtension.bConcealTab[2] = false;
  1770.     g_stPictureData.stCodingExtension.bTopFirst = false;
  1771.     g_stPictureData.stCodingExtension.bProgFrame = true;
  1772.  
  1773.     h = 0;
  1774.     m = 0;
  1775.     s = 0;
  1776.     f = 0;
  1777.  
  1778.     g_stCodingModelParams.nFramesNumberInGroupOfPicture = 15;
  1779.     g_stCodingModelParams.nDistanceBetweenIPFrames = 3;
  1780.     g_stSequenceData.stHeader.nAspectRatio = 8;
  1781.     g_stSequenceData.stExtension.nProfile = 4;
  1782.     g_stSequenceData.stDisplayExtension.nVideoFormat = 1;
  1783.     g_stSequenceData.stExtension.nLevel = 10;
  1784.     g_stSequenceData.stHeader.uConstrainedParams = 1;
  1785.     
  1786.     g_stSequenceData.stDisplayExtension.nColorPrimaries = 5;
  1787.     g_stSequenceData.stDisplayExtension.nTransferCharacteristics = 5;
  1788.     g_stSequenceData.stDisplayExtension.nMatrixCoefficients = 5;
  1789.     
  1790.     g_stPictureData.stCodingExtension.nDCPrecision = 0;
  1791.  
  1792.     g_stPictureData.stCodingExtension.bFramePredDCTTab[0] = true;
  1793.     g_stPictureData.stCodingExtension.bFramePredDCTTab[1] = true;
  1794.     g_stPictureData.stCodingExtension.bFramePredDCTTab[2] = true;
  1795.  
  1796.     g_stPictureData.stCodingExtension.bQScaleTab[0] = false;
  1797.     g_stPictureData.stCodingExtension.bQScaleTab[1] = false;
  1798.     g_stPictureData.stCodingExtension.bQScaleTab[2] = false;
  1799.  
  1800.     g_stPictureData.stCodingExtension.bIntravlcTab[0] = false;
  1801.     g_stPictureData.stCodingExtension.bIntravlcTab[1] = false;
  1802.     g_stPictureData.stCodingExtension.bIntravlcTab[2] = false;
  1803.  
  1804.     g_stPictureData.stCodingExtension.bAltScanTab[0] = false;
  1805.     g_stPictureData.stCodingExtension.bAltScanTab[1] = false;
  1806.     g_stPictureData.stCodingExtension.bAltScanTab[2] = false;
  1807.     
  1808.     g_stPictureData.stCodingExtension.bRepeatFirst = false;
  1809.  
  1810.     g_stCodingModelParams.nIntraSliceRefreshIntaeval = 0;
  1811.     g_stRateControl.r = 0;
  1812.     g_stRateControl.avg_act = 0;
  1813.  
  1814.     g_stRateControl.Xi = 0;
  1815.     g_stRateControl.Xp = 0;
  1816.     g_stRateControl.Xb = 0;
  1817.     g_stRateControl.d0i = 0;
  1818.     g_stRateControl.d0p = 0;
  1819.     g_stRateControl.d0b = 0;
  1820.  
  1821.     // Check for consistency here
  1822.     if (g_nWriteSequenceGrounp<0)
  1823.     {
  1824.         return TR_WRSEQH2GOP_ERR;
  1825.     }
  1826.     if (g_stCodingModelParams.nFramesNumberInGroupOfPicture<1)
  1827.     {
  1828.         return TR_FRAME_NUMBER_IN_GROOUP_ERR;
  1829.     }
  1830.     if (g_stCodingModelParams.nDistanceBetweenIPFrames<1)
  1831.     {
  1832.         return TR_DISTANCE_BETWEEN_IP_FRAMES_ERR;
  1833.     }
  1834.     if (g_stCodingModelParams.nFramesNumberInGroupOfPicture%g_stCodingModelParams.nDistanceBetweenIPFrames != 0)
  1835.     {
  1836.         return TR_FNIG_MULTIPLE_DBIPF_ERR;
  1837.     }
  1838.  
  1839.     if (!g_stPictureStruct.AllocMotionStruct(g_stCodingModelParams.nDistanceBetweenIPFrames))
  1840.     {
  1841.         return TR_ERR_ALLOC_MOTION_STRUCT;
  1842.     }
  1843.  
  1844.     /* intra slice interval refresh period */  
  1845.     g_stCodingModelParams.nIntraSliceRefreshIntaeval = 0;
  1846.     g_stRateControl.r = 0;
  1847.     g_stRateControl.avg_act = 0;
  1848.     g_stRateControl.Xi = 0;
  1849.     g_stRateControl.Xp = 0;
  1850.     g_stRateControl.Xb = 0;
  1851.     g_stRateControl.d0i = 0;
  1852.     g_stRateControl.d0p = 0;
  1853.     g_stRateControl.d0b = 0;
  1854. /*
  1855.     if (!g_stPictureStruct.AllocMotionStruct(g_stCodingModelParams.nDistanceBetweenIPFrames))
  1856.       _error("malloc failed\n");
  1857. */
  1858.     // It's not so easy to introduce default values, so switch for the search size here
  1859.     switch (g_nSearchSize)
  1860.     {
  1861.     case 0:
  1862.         g_stPictureStruct.pstMotionData[0].forw_hor_f_code = g_stPictureStruct.pstMotionData[0].forw_vert_f_code = 2;
  1863.         g_stPictureStruct.pstMotionData[0].sxf = g_stPictureStruct.pstMotionData[0].syf = 11;
  1864.  
  1865.         g_stPictureStruct.pstMotionData[1].forw_hor_f_code = g_stPictureStruct.pstMotionData[1].forw_vert_f_code = 1;
  1866.         g_stPictureStruct.pstMotionData[1].sxf = g_stPictureStruct.pstMotionData[1].syf = 3;
  1867.  
  1868.         g_stPictureStruct.pstMotionData[1].back_hor_f_code = g_stPictureStruct.pstMotionData[1].back_vert_f_code = 1;
  1869.         g_stPictureStruct.pstMotionData[1].sxb = g_stPictureStruct.pstMotionData[1].syb = 7;
  1870.  
  1871.         g_stPictureStruct.pstMotionData[2].forw_hor_f_code = g_stPictureStruct.pstMotionData[2].forw_vert_f_code = 1;
  1872.         g_stPictureStruct.pstMotionData[2].sxf = g_stPictureStruct.pstMotionData[2].syf = 7;
  1873.  
  1874.         g_stPictureStruct.pstMotionData[2].back_hor_f_code = g_stPictureStruct.pstMotionData[2].back_vert_f_code = 1;
  1875.         g_stPictureStruct.pstMotionData[2].sxb = g_stPictureStruct.pstMotionData[2].syb = 3;
  1876.     break;
  1877.  
  1878.     case 1:
  1879.         g_stPictureStruct.pstMotionData[0].forw_hor_f_code = g_stPictureStruct.pstMotionData[0].forw_vert_f_code = 2;
  1880.         g_stPictureStruct.pstMotionData[0].sxf = g_stPictureStruct.pstMotionData[0].syf = 15;
  1881.  
  1882.         g_stPictureStruct.pstMotionData[1].forw_hor_f_code = g_stPictureStruct.pstMotionData[1].forw_vert_f_code = 1;
  1883.         g_stPictureStruct.pstMotionData[1].sxf = g_stPictureStruct.pstMotionData[1].syf = 7;
  1884.  
  1885.         g_stPictureStruct.pstMotionData[1].back_hor_f_code = g_stPictureStruct.pstMotionData[1].back_vert_f_code = 2;
  1886.         g_stPictureStruct.pstMotionData[1].sxb = g_stPictureStruct.pstMotionData[1].syb = 15;
  1887.  
  1888.         g_stPictureStruct.pstMotionData[2].forw_hor_f_code = g_stPictureStruct.pstMotionData[2].forw_vert_f_code = 2;
  1889.         g_stPictureStruct.pstMotionData[2].sxf = g_stPictureStruct.pstMotionData[2].syf = 15;
  1890.  
  1891.         g_stPictureStruct.pstMotionData[2].back_hor_f_code = g_stPictureStruct.pstMotionData[2].back_vert_f_code = 1;
  1892.         g_stPictureStruct.pstMotionData[2].sxb = g_stPictureStruct.pstMotionData[2].syb = 7;
  1893.     break;
  1894.  
  1895.     case 2:
  1896.         g_stPictureStruct.pstMotionData[0].forw_hor_f_code = g_stPictureStruct.pstMotionData[0].forw_vert_f_code = 3;
  1897.         g_stPictureStruct.pstMotionData[0].sxf = g_stPictureStruct.pstMotionData[0].syf = 31;
  1898.  
  1899.         g_stPictureStruct.pstMotionData[1].forw_hor_f_code = g_stPictureStruct.pstMotionData[1].forw_vert_f_code = 2;
  1900.         g_stPictureStruct.pstMotionData[1].sxf = g_stPictureStruct.pstMotionData[1].syf = 15;
  1901.  
  1902.         g_stPictureStruct.pstMotionData[1].back_hor_f_code = g_stPictureStruct.pstMotionData[1].back_vert_f_code = 3;
  1903.         g_stPictureStruct.pstMotionData[1].sxb = g_stPictureStruct.pstMotionData[1].syb = 31;
  1904.  
  1905.         g_stPictureStruct.pstMotionData[2].forw_hor_f_code = g_stPictureStruct.pstMotionData[2].forw_vert_f_code = 3;
  1906.         g_stPictureStruct.pstMotionData[2].sxf = g_stPictureStruct.pstMotionData[2].syf = 31;
  1907.  
  1908.         g_stPictureStruct.pstMotionData[2].back_hor_f_code = g_stPictureStruct.pstMotionData[2].back_vert_f_code = 2;
  1909.         g_stPictureStruct.pstMotionData[2].sxb = g_stPictureStruct.pstMotionData[2].syb = 15;
  1910.     break;
  1911.  
  1912.     case 3:
  1913.         g_stPictureStruct.pstMotionData[0].forw_hor_f_code = g_stPictureStruct.pstMotionData[0].forw_vert_f_code = 4;
  1914.         g_stPictureStruct.pstMotionData[0].sxf = g_stPictureStruct.pstMotionData[0].syf = 63;
  1915.  
  1916.         g_stPictureStruct.pstMotionData[1].forw_hor_f_code = g_stPictureStruct.pstMotionData[1].forw_vert_f_code = 3;
  1917.         g_stPictureStruct.pstMotionData[1].sxf = g_stPictureStruct.pstMotionData[1].syf = 31;
  1918.  
  1919.         g_stPictureStruct.pstMotionData[1].back_hor_f_code = g_stPictureStruct.pstMotionData[1].back_vert_f_code = 4;
  1920.         g_stPictureStruct.pstMotionData[1].sxb = g_stPictureStruct.pstMotionData[1].syb = 63;
  1921.  
  1922.         g_stPictureStruct.pstMotionData[2].forw_hor_f_code = g_stPictureStruct.pstMotionData[2].forw_vert_f_code = 4;
  1923.         g_stPictureStruct.pstMotionData[2].sxf = g_stPictureStruct.pstMotionData[2].syf = 63;
  1924.  
  1925.         g_stPictureStruct.pstMotionData[2].back_hor_f_code = g_stPictureStruct.pstMotionData[2].back_vert_f_code = 3;
  1926.         g_stPictureStruct.pstMotionData[2].sxb = g_stPictureStruct.pstMotionData[2].syb = 31;
  1927.     break;
  1928.  
  1929.     case 4:
  1930.         g_stPictureStruct.pstMotionData[0].forw_hor_f_code = g_stPictureStruct.pstMotionData[0].forw_vert_f_code = 4;
  1931.         g_stPictureStruct.pstMotionData[0].sxf = g_stPictureStruct.pstMotionData[0].syf = 63;
  1932.  
  1933.         g_stPictureStruct.pstMotionData[1].forw_hor_f_code = g_stPictureStruct.pstMotionData[1].forw_vert_f_code = 4;
  1934.         g_stPictureStruct.pstMotionData[1].sxf = g_stPictureStruct.pstMotionData[1].syf = 63;
  1935.  
  1936.         g_stPictureStruct.pstMotionData[1].back_hor_f_code = g_stPictureStruct.pstMotionData[1].back_vert_f_code = 4;
  1937.         g_stPictureStruct.pstMotionData[1].sxb = g_stPictureStruct.pstMotionData[1].syb = 63;
  1938.  
  1939.         g_stPictureStruct.pstMotionData[2].forw_hor_f_code = g_stPictureStruct.pstMotionData[2].forw_vert_f_code = 4;
  1940.         g_stPictureStruct.pstMotionData[2].sxf = g_stPictureStruct.pstMotionData[2].syf = 63;
  1941.  
  1942.         g_stPictureStruct.pstMotionData[2].back_hor_f_code = g_stPictureStruct.pstMotionData[2].back_vert_f_code = 4;
  1943.         g_stPictureStruct.pstMotionData[2].sxb = g_stPictureStruct.pstMotionData[2].syb = 63;
  1944.     break;
  1945.     }
  1946.  
  1947.     /* make sure MPEG specific parameters are valid */
  1948.     if((ret = RangeCheck())!=TR_OK)
  1949.     {
  1950.         return ret;
  1951.     }
  1952.  
  1953.     /* timecode -> frame number */
  1954.     g_stCodingModelParams.nTimeCodeOfFirstFrame = h;
  1955.     g_stCodingModelParams.nTimeCodeOfFirstFrame = 60*g_stCodingModelParams.nTimeCodeOfFirstFrame + m;
  1956.     g_stCodingModelParams.nTimeCodeOfFirstFrame = 60*g_stCodingModelParams.nTimeCodeOfFirstFrame + s;
  1957.     g_stCodingModelParams.nTimeCodeOfFirstFrame = (int)(g_stSequenceData.stHeader.fFrameRate+0.5)*g_stCodingModelParams.nTimeCodeOfFirstFrame + f;
  1958.  
  1959.     /* MPEG-1 */
  1960.     if (g_stSequenceData.stHeader.uConstrainedParams)
  1961.     {
  1962.         if (g_stSequenceData.stHeader.nHFrameSize>768
  1963.             || g_stSequenceData.stHeader.nVFrameSize>576
  1964.             || ((g_stSequenceData.stHeader.nHFrameSize+15)/16)*((g_stSequenceData.stHeader.nVFrameSize+15)/16)>396
  1965.             || ((g_stSequenceData.stHeader.nHFrameSize+15)/16)*((g_stSequenceData.stHeader.nVFrameSize+15)/16)*g_stSequenceData.stHeader.fFrameRate>396*25.0
  1966.             || g_stSequenceData.stHeader.fFrameRate>30.0)
  1967.             {
  1968.                 g_stSequenceData.stHeader.uConstrainedParams = 0;
  1969.             }
  1970.     }
  1971.  
  1972.     if (g_stSequenceData.stHeader.uConstrainedParams)
  1973.     {
  1974.       for (i=0; i<g_stCodingModelParams.nDistanceBetweenIPFrames; i++)
  1975.       {
  1976.         if (g_stPictureStruct.pstMotionData[i].forw_hor_f_code>4)
  1977.         {
  1978.             g_stSequenceData.stHeader.uConstrainedParams = 0;
  1979.             break;
  1980.         }
  1981.  
  1982.         if (g_stPictureStruct.pstMotionData[i].forw_vert_f_code>4)
  1983.         {
  1984.             g_stSequenceData.stHeader.uConstrainedParams = 0;
  1985.             break;
  1986.         }
  1987.  
  1988.         if (i!=0)
  1989.         {
  1990.           if (g_stPictureStruct.pstMotionData[i].back_hor_f_code>4)
  1991.           {
  1992.             g_stSequenceData.stHeader.uConstrainedParams = 0;
  1993.             break;
  1994.           }
  1995.  
  1996.           if (g_stPictureStruct.pstMotionData[i].back_vert_f_code>4)
  1997.           {
  1998.             g_stSequenceData.stHeader.uConstrainedParams = 0;
  1999.             break;
  2000.           }
  2001.         }
  2002.       }
  2003.     }
  2004.  
  2005.     /* relational checks */
  2006.  
  2007.     if (!g_stSequenceData.stExtension.bProgressSequence)
  2008.     {
  2009.         g_stSequenceData.stExtension.bProgressSequence = true;
  2010.     }
  2011.  
  2012.     if (g_stSequenceData.stExtension.nChromaFormat!=CHROMA420)
  2013.     {
  2014.         g_stSequenceData.stExtension.nChromaFormat = CHROMA420;
  2015.     }
  2016.  
  2017.     if (g_stPictureData.stCodingExtension.nDCPrecision!=0)
  2018.     {
  2019.         g_stPictureData.stCodingExtension.nDCPrecision = 0;
  2020.     }
  2021.  
  2022.     for (i=0; i<3; i++)
  2023.         if(g_stPictureData.stCodingExtension.bQScaleTab[i])
  2024.         {
  2025.             g_stPictureData.stCodingExtension.bQScaleTab[i] = 0;
  2026.         }
  2027.  
  2028.     for (i=0; i<3; i++)
  2029.         if (g_stPictureData.stCodingExtension.bIntravlcTab[i])
  2030.         {
  2031.             g_stPictureData.stCodingExtension.bIntravlcTab[i] = 0;
  2032.         }
  2033.  
  2034.     for (i=0; i<3; i++)
  2035.         if (g_stPictureData.stCodingExtension.bAltScanTab[i])
  2036.         {
  2037.             g_stPictureData.stCodingExtension.bAltScanTab[i] = 0;
  2038.         }
  2039.  
  2040.     if (g_stSequenceData.stExtension.bProgressSequence && !g_stPictureData.stCodingExtension.bProgFrame)
  2041.     {
  2042.         g_stPictureData.stCodingExtension.bProgFrame = true;
  2043.     }
  2044.  
  2045.     if (g_stPictureData.stCodingExtension.bProgFrame && g_stCodingModelParams.bFieldPicture)
  2046.     {
  2047.         g_stCodingModelParams.bFieldPicture = false;
  2048.     }
  2049.  
  2050.     if (!g_stPictureData.stCodingExtension.bProgFrame && g_stPictureData.stCodingExtension.bRepeatFirst)
  2051.     {
  2052.         g_stPictureData.stCodingExtension.bRepeatFirst = 0;
  2053.     }
  2054.  
  2055.     if (g_stPictureData.stCodingExtension.bProgFrame)
  2056.     {
  2057.         for (i=0; i<3; i++)
  2058.             if (!g_stPictureData.stCodingExtension.bFramePredDCTTab[i])
  2059.             {
  2060.                 g_stPictureData.stCodingExtension.bFramePredDCTTab[i] = 1;
  2061.             }
  2062.     }
  2063.  
  2064.     if (g_stSequenceData.stExtension.bProgressSequence 
  2065.         && !g_stPictureData.stCodingExtension.bRepeatFirst
  2066.         && g_stPictureData.stCodingExtension.bTopFirst)
  2067.     {
  2068.         g_stPictureData.stCodingExtension.bTopFirst = false;
  2069.     }
  2070.  
  2071.     /* search windows */
  2072.     for (i=0; i<g_stCodingModelParams.nDistanceBetweenIPFrames; i++)
  2073.     {
  2074.         if (g_stPictureStruct.pstMotionData[i].sxf > (4<<g_stPictureStruct.pstMotionData[i].forw_hor_f_code)-1)
  2075.         {
  2076.             g_stPictureStruct.pstMotionData[i].sxf = (4<<g_stPictureStruct.pstMotionData[i].forw_hor_f_code)-1;
  2077.         }
  2078.  
  2079.         if (g_stPictureStruct.pstMotionData[i].syf > (4<<g_stPictureStruct.pstMotionData[i].forw_vert_f_code)-1)
  2080.         {
  2081.             g_stPictureStruct.pstMotionData[i].syf = (4<<g_stPictureStruct.pstMotionData[i].forw_vert_f_code)-1;
  2082.         }
  2083.  
  2084.         if (i!=0)
  2085.         {
  2086.           if (g_stPictureStruct.pstMotionData[i].sxb > (4<<g_stPictureStruct.pstMotionData[i].back_hor_f_code)-1)
  2087.           {
  2088.                 g_stPictureStruct.pstMotionData[i].sxb = (4<<g_stPictureStruct.pstMotionData[i].back_hor_f_code)-1;
  2089.           }
  2090.  
  2091.           if (g_stPictureStruct.pstMotionData[i].syb > (4<<g_stPictureStruct.pstMotionData[i].back_vert_f_code)-1)
  2092.           {
  2093.                 g_stPictureStruct.pstMotionData[i].syb = (4<<g_stPictureStruct.pstMotionData[i].back_vert_f_code)-1;
  2094.           }
  2095.         }
  2096.     }
  2097.  
  2098.     return TR_OK;
  2099. }
  2100. /*---------------------------------------------------------
  2101.     ò╧Éöé╠ö═ê═é╠â`âFâbâN
  2102. ---------------------------------------------------------*/
  2103. inline TOMPGRET RangeCheck(void)
  2104. {
  2105.     int i;
  2106.  
  2107.     /* range and value checks */
  2108.  
  2109.     if (g_stSequenceData.stHeader.nHFrameSize<1 || g_stSequenceData.stHeader.nHFrameSize>16383)
  2110.     {
  2111.         return TR_HFRAME_SIZE_ERR;
  2112.     }
  2113.     if (g_stSequenceData.stHeader.nHFrameSize>4095)
  2114.     {
  2115.         return TR_HFRAME_SIZE_ERR;
  2116.     }
  2117.  
  2118.     if ((g_stSequenceData.stHeader.nHFrameSize&4095)==0)
  2119.     {
  2120.         return TR_HFRAME_SIZE_ERR;
  2121.     }
  2122.  
  2123.     if (g_stSequenceData.stExtension.nChromaFormat!=CHROMA444 && g_stSequenceData.stHeader.nHFrameSize%2 != 0)
  2124.     {
  2125.         return TR_CHROMA_FORMAT_ERR;
  2126.     }
  2127.  
  2128.     if (g_stSequenceData.stHeader.nVFrameSize<1 || g_stSequenceData.stHeader.nVFrameSize>16383)
  2129.     {
  2130.         return TR_VFRAME_SIZE_ERR;
  2131.     }
  2132.     if (g_stSequenceData.stHeader.nVFrameSize>4095)
  2133.     {
  2134.         return TR_VFRAME_SIZE_ERR;
  2135.     }
  2136.     if ((g_stSequenceData.stHeader.nVFrameSize&4095)==0)
  2137.     {
  2138.         return TR_VFRAME_SIZE_ERR;
  2139.     }
  2140.     if (g_stSequenceData.stExtension.nChromaFormat==CHROMA420 && g_stSequenceData.stHeader.nVFrameSize%2 != 0)
  2141.     {
  2142.         return TR_CHROMA_FORMAT_ERR;
  2143.     }
  2144.     if(g_stCodingModelParams.bFieldPicture)
  2145.     {
  2146.         if (g_stSequenceData.stHeader.nVFrameSize%2 != 0)
  2147.         {
  2148.             return TR_VFRAME_SIZE_ERR;
  2149.         }
  2150.         if (g_stSequenceData.stExtension.nChromaFormat==CHROMA420 && g_stSequenceData.stHeader.nVFrameSize%4 != 0)
  2151.         {
  2152.             return TR_CHROMA_FORMAT_ERR;
  2153.         }
  2154.     }
  2155.  
  2156.     if (g_stSequenceData.stHeader.nAspectRatio<1 || g_stSequenceData.stHeader.nAspectRatio>14)
  2157.     {
  2158.         return TR_ASPECT_RATIO_ERR;
  2159.     }
  2160.  
  2161.     if (g_stSequenceData.stHeader.nFrameRateCode<0 || g_stSequenceData.stHeader.nFrameRateCode>7)
  2162.     {
  2163.         return TR_FRAME_RATE_CODE_ERR;
  2164.     }
  2165.  
  2166.     if (g_stSequenceData.stHeader.fBitRate<=0.0)
  2167.     {
  2168.         return TR_BITRATE_ERR;
  2169.     }
  2170.     if (g_stSequenceData.stHeader.fBitRate > ((double)((1<<30)-1))*400.0)
  2171.     {
  2172.         return TR_BITRATE_ERR;
  2173.     }
  2174.     if (g_stSequenceData.stHeader.fBitRate > ((double)((1<<18)-1))*400.0)
  2175.     {
  2176.         return TR_BITRATE_ERR;
  2177.     }
  2178.  
  2179.     if (g_stSequenceData.stHeader.nVBVBufferSize<1 || g_stSequenceData.stHeader.nVBVBufferSize>0x3ffff)
  2180.     {
  2181.         return TR_VBV_BUFFER_SIZE_ERR;
  2182.     }
  2183.     if (g_stSequenceData.stHeader.nVBVBufferSize>=1024)
  2184.     {
  2185.         return TR_VBV_BUFFER_SIZE_ERR;
  2186.     }
  2187.  
  2188.     if (g_stSequenceData.stExtension.nChromaFormat<CHROMA420 || g_stSequenceData.stExtension.nChromaFormat>CHROMA444)
  2189.     {
  2190.         return TR_CHROMA_FORMAT_ERR;
  2191.     }
  2192.  
  2193.     if (g_stSequenceData.stDisplayExtension.nVideoFormat<0 || g_stSequenceData.stDisplayExtension.nVideoFormat>4)
  2194.     {
  2195.         return TR_VIDEO_FORMAT_ERR;
  2196.     }
  2197.  
  2198.     if (g_stSequenceData.stDisplayExtension.nColorPrimaries<1 || g_stSequenceData.stDisplayExtension.nColorPrimaries>7 || g_stSequenceData.stDisplayExtension.nColorPrimaries==3)
  2199.     {
  2200.         return TR_COLOR_PRIMARIES_ERR;
  2201.     }
  2202.  
  2203.     if (g_stSequenceData.stDisplayExtension.nTransferCharacteristics<1
  2204.         || g_stSequenceData.stDisplayExtension.nTransferCharacteristics>7
  2205.         || g_stSequenceData.stDisplayExtension.nTransferCharacteristics==3)
  2206.     {
  2207.         return TR_TRANSFER_CHARACTERISTICS_ERR;
  2208.     }
  2209.  
  2210.     if (g_stSequenceData.stDisplayExtension.nMatrixCoefficients<1
  2211.         || g_stSequenceData.stDisplayExtension.nMatrixCoefficients>7
  2212.         || g_stSequenceData.stDisplayExtension.nMatrixCoefficients==3)
  2213.     {
  2214.         return TR_MATRIX_COEFFICIENTS_ERR;
  2215.     }
  2216.  
  2217.     if (g_stSequenceData.stDisplayExtension.nDisplayHSize<0
  2218.         || g_stSequenceData.stDisplayExtension.nDisplayHSize>16383)
  2219.     {
  2220.         return TR_DISPLAY_HSIZE_ERR;
  2221.     }
  2222.     if (g_stSequenceData.stDisplayExtension.nDisplayVSize<0
  2223.         || g_stSequenceData.stDisplayExtension.nDisplayVSize>16383)
  2224.     {
  2225.         return TR_DISPLAY_VSIZE_ERR;
  2226.     }
  2227.  
  2228.     if (g_stPictureData.stCodingExtension.nDCPrecision<0
  2229.         || g_stPictureData.stCodingExtension.nDCPrecision>3)
  2230.     {
  2231.         return TR_INTRA_DC_PRECISION_ERR;
  2232.     }
  2233.  
  2234.     for (i=0; i<g_stCodingModelParams.nDistanceBetweenIPFrames; i++)
  2235.     {
  2236.         if (g_stPictureStruct.pstMotionData[i].forw_hor_f_code<1
  2237.             || g_stPictureStruct.pstMotionData[i].forw_hor_f_code>9)
  2238.         {
  2239.             return TR_FHCODE_ERR;
  2240.         }
  2241.         if (g_stPictureStruct.pstMotionData[i].forw_vert_f_code<1
  2242.             || g_stPictureStruct.pstMotionData[i].forw_vert_f_code>9)
  2243.         {
  2244.             return TR_FVCODE_ERR;
  2245.         }
  2246.         if (g_stPictureStruct.pstMotionData[i].forw_hor_f_code>7)
  2247.         {
  2248.             return TR_FHCODE_ERR;
  2249.         }
  2250.         if (g_stPictureStruct.pstMotionData[i].forw_vert_f_code>7)
  2251.         {
  2252.             return TR_FVCODE_ERR;
  2253.         }
  2254.         if (g_stPictureStruct.pstMotionData[i].sxf<=0)
  2255.         {
  2256.             return TR_SXF_ERR;
  2257.         }
  2258.         if (g_stPictureStruct.pstMotionData[i].syf<=0)
  2259.         {
  2260.             return TR_SYF_ERR;
  2261.         }
  2262.         if (i!=0)
  2263.         {
  2264.             if (g_stPictureStruct.pstMotionData[i].back_hor_f_code<1
  2265.                 || g_stPictureStruct.pstMotionData[i].back_hor_f_code>9)
  2266.             {
  2267.                 return TR_BHCODE_ERR;
  2268.             }
  2269.             if (g_stPictureStruct.pstMotionData[i].back_vert_f_code<1
  2270.                 || g_stPictureStruct.pstMotionData[i].back_vert_f_code>9)
  2271.             {
  2272.                 return TR_BVCODE_ERR;
  2273.             }
  2274.             if (g_stPictureStruct.pstMotionData[i].back_hor_f_code>7)
  2275.             {
  2276.                 return TR_BHCODE_ERR;
  2277.             }
  2278.             if (g_stPictureStruct.pstMotionData[i].back_vert_f_code>7)
  2279.             {
  2280.                 return TR_BVCODE_ERR;
  2281.             }
  2282.             if (g_stPictureStruct.pstMotionData[i].sxb<=0)
  2283.             {
  2284.                 return TR_SXB_ERR;
  2285.             }
  2286.             if (g_stPictureStruct.pstMotionData[i].syb<=0)
  2287.             {
  2288.                 return TR_SYB_ERR;
  2289.             }
  2290.         }
  2291.     }
  2292.  
  2293.     return TR_OK;
  2294. }
  2295.  
  2296. /*=========================================================
  2297.     Rate Control
  2298. =========================================================*/
  2299. /*---------------------------------------------------------
  2300.     âVü[âPâôâXé╠Åëè·ë╗
  2301. ---------------------------------------------------------*/
  2302. inline void RcInitSeq(void)
  2303. {
  2304.     /* reaction parameter (constant) */
  2305.     if (g_stRateControl.r == 0)
  2306.     {
  2307.         g_stRateControl.r = (int)(2.0*g_stSequenceData.stHeader.fBitRate/g_stSequenceData.stHeader.fFrameRate + 0.5);
  2308.     }
  2309.  
  2310.     /* average activity */
  2311.     if (g_stRateControl.avg_act == 0.0)
  2312.     {
  2313.         g_stRateControl.avg_act = 400.0;
  2314.     }
  2315.  
  2316.     /* remaining # of bits in GOP */
  2317.     g_stRateControl.R = 0;
  2318.  
  2319.     /* global complexity measure */
  2320.     if (g_stRateControl.Xi==0)
  2321.     {
  2322.         g_stRateControl.Xi = (int)(160.0*g_stSequenceData.stHeader.fBitRate/115.0 + 0.5);
  2323.     }
  2324.     if (g_stRateControl.Xp==0)
  2325.     {
  2326.         g_stRateControl.Xp = (int)( 60.0*g_stSequenceData.stHeader.fBitRate/115.0 + 0.5);
  2327.     }
  2328.     if (g_stRateControl.Xb==0)
  2329.     {
  2330.         g_stRateControl.Xb = (int)( 42.0*g_stSequenceData.stHeader.fBitRate/115.0 + 0.5);
  2331.     }
  2332.  
  2333.     /* virtual buffer fullness */
  2334.     if (g_stRateControl.d0i==0)
  2335.     {
  2336.         g_stRateControl.d0i = (int)(10.0*g_stRateControl.r/31.0 + 0.5);
  2337.     }
  2338.     if (g_stRateControl.d0p==0)
  2339.     {
  2340.         g_stRateControl.d0p = (int)(10.0*g_stRateControl.r/31.0 + 0.5);
  2341.     }
  2342.     if (g_stRateControl.d0b==0)
  2343.     {
  2344.         g_stRateControl.d0b = (int)(1.4*10.0*g_stRateControl.r/31.0 + 0.5);
  2345.     }
  2346. }
  2347.  
  2348. inline void RcInitGOP(const int np,const int nb)
  2349. {
  2350.     g_stRateControl.R += (int) (((double)(1 + np + nb)) * g_stSequenceData.stHeader.fBitRate / g_stSequenceData.stHeader.fFrameRate + 0.5);
  2351.     if(g_stCodingModelParams.bFieldPicture)
  2352.     {
  2353.         g_stRateControl.Np = 2*np+1;
  2354.     }
  2355.     else
  2356.     {
  2357.         g_stRateControl.Np = np;
  2358.     }
  2359.     if(g_stCodingModelParams.bFieldPicture)
  2360.     {
  2361.         g_stRateControl.Nb = 2*nb;
  2362.     }
  2363.     else
  2364.     {
  2365.         g_stRateControl.Nb = nb;
  2366.     }
  2367. }
  2368. inline void RcInitPic(unsigned char* frame)
  2369. {
  2370.     const int width = g_stSequenceData.stHeader.nWidth;
  2371.     const int width2 = g_stSequenceData.stHeader.nWidth2;
  2372.  
  2373.     double Tmin;
  2374.  
  2375.     int i,j,k;
  2376.     unsigned char *p;
  2377.     double actj,var;
  2378.  
  2379.     switch (g_stPictureData.stHeader.nPictType)
  2380.     {
  2381.     case I_TYPE:
  2382.         g_stRateControl.T = (int)(g_stRateControl.R/(1.0+g_stRateControl.Np*g_stRateControl.Xp/(g_stRateControl.Xi*1.0)+g_stRateControl.Nb*g_stRateControl.Xb/(g_stRateControl.Xi*1.4)) + 0.5);
  2383.         g_stRateControl.d = g_stRateControl.d0i;
  2384.         break;
  2385.     case P_TYPE:
  2386.         g_stRateControl.T = (int)(g_stRateControl.R/(g_stRateControl.Np+g_stRateControl.Nb*1.0*g_stRateControl.Xb/(1.4*g_stRateControl.Xp)) + 0.5);
  2387.         g_stRateControl.d = g_stRateControl.d0p;
  2388.         break;
  2389.     case B_TYPE:
  2390.         g_stRateControl.T = (int)(g_stRateControl.R/(g_stRateControl.Nb+g_stRateControl.Np*1.4*g_stRateControl.Xp/(1.0*g_stRateControl.Xb)) + 0.5);
  2391.         g_stRateControl.d = g_stRateControl.d0b;
  2392.         break;
  2393.     }
  2394.  
  2395.     Tmin = (int)(g_stSequenceData.stHeader.fBitRate/(8.0*g_stSequenceData.stHeader.fFrameRate) + 0.5);
  2396.  
  2397.     if (g_stRateControl.T<Tmin)
  2398.         g_stRateControl.T = (int)Tmin;
  2399.  
  2400.     g_stRateControl.S = g_stSystemData.bitcount();
  2401.     g_stRateControl.Q = 0;
  2402.  
  2403.  
  2404.     k = 0;
  2405.  
  2406.     for (j=0; j<g_stSequenceData.stHeader.nHeight2; j+=16)
  2407.     {
  2408.         for (i=0; i<width; i+=16)
  2409.         {
  2410.             if(g_stPictureData.stCodingExtension.nPictStruct==BOTTOM_FIELD)
  2411.             {
  2412.                 p = frame + width + i + width2*j;
  2413.             }
  2414.             else
  2415.             {
  2416.                 p = frame + i + width2*j;
  2417.             }
  2418.  
  2419.             /* take minimum spatial activity measure of luminance blocks */
  2420.  
  2421.             actj = VarSBlock(p,width2);
  2422.             var = VarSBlock(p+8,width2);
  2423.             if (var<actj)
  2424.             {
  2425.                 actj = var;
  2426.             }
  2427.             var = VarSBlock(p+8*width2,width2);
  2428.             if (var<actj)
  2429.             {
  2430.                 actj = var;
  2431.             }
  2432.             var = VarSBlock(p+8*width2+8,width2);
  2433.             if (var<actj)
  2434.             {
  2435.                 actj = var;
  2436.             }
  2437.  
  2438.             if (!g_stCodingModelParams.bFieldPicture && !g_stSequenceData.stExtension.bProgressSequence)
  2439.             {
  2440.                 /* field */
  2441.                 var = VarSBlock(p,width<<1);
  2442.                 if (var<actj) actj = var;
  2443.                 var = VarSBlock(p+8,width<<1);
  2444.                 if (var<actj) actj = var;
  2445.                 var = VarSBlock(p+width,width<<1);
  2446.                 if (var<actj) actj = var;
  2447.                 var = VarSBlock(p+width+8,width<<1);
  2448.                 if (var<actj) actj = var;
  2449.             }
  2450.  
  2451.             actj+= 1.0;
  2452.  
  2453.             g_stPictureStruct.pstMacroBlockInfo[k++].act = actj;
  2454.         }
  2455.     }
  2456.     g_stRateControl.actsum = 0.0;
  2457. }
  2458. inline void RcUpdatePict(void)
  2459. {
  2460.     const int mb_wh2 = g_stSequenceData.stHeader.nMacroBlocksWidth*g_stSequenceData.stHeader.nMacroBlocksHeight2;
  2461.     double X;
  2462.  
  2463.     g_stRateControl.S = g_stSystemData.bitcount() - g_stRateControl.S; /* total # of bits in picture */
  2464.     g_stRateControl.R-= g_stRateControl.S; /* remaining # of bits in GOP */
  2465.     X = (int)(g_stRateControl.S*((0.5*(double)g_stRateControl.Q)/(mb_wh2)) + 0.5);
  2466.     g_stRateControl.d+= g_stRateControl.S - g_stRateControl.T;
  2467.     g_stRateControl.avg_act = g_stRateControl.actsum/(mb_wh2);
  2468.  
  2469.     switch (g_stPictureData.stHeader.nPictType)
  2470.     {
  2471.     case I_TYPE:
  2472.         g_stRateControl.Xi = (int)X;
  2473.         g_stRateControl.d0i = g_stRateControl.d;
  2474.         break;
  2475.     case P_TYPE:
  2476.         g_stRateControl.Xp = (int)X;
  2477.         g_stRateControl.d0p = g_stRateControl.d;
  2478.         g_stRateControl.Np--;
  2479.         break;
  2480.     case B_TYPE:
  2481.         g_stRateControl.Xb = (int)X;
  2482.         g_stRateControl.d0b = g_stRateControl.d;
  2483.         g_stRateControl.Nb--;
  2484.         break;
  2485.     }
  2486. }
  2487.  
  2488. /*---------------------------------------------------------
  2489.     compute initial quantization stepsize 
  2490.     (at the beginning of picture)
  2491. ---------------------------------------------------------*/
  2492. inline int RcStartMb(void)
  2493. {
  2494.     int mquant;
  2495.  
  2496.     if (g_stPictureData.stCodingExtension.bQScaleType)
  2497.     {
  2498.         mquant = (int)(2.0*g_stRateControl.d*31.0/g_stRateControl.r + 0.5);
  2499.  
  2500.         /* clip mquant to legal (linear) range */
  2501.         if (mquant<1)
  2502.             mquant = 1;
  2503.  
  2504.         if (mquant>112)
  2505.             mquant = 112;
  2506.  
  2507.         /* map to legal quantization level */
  2508.         mquant = g_NonLinerQuantizationArray[g_MapNonLinearQuantizationArray[mquant]];
  2509.     }
  2510.     else
  2511.     {
  2512.         mquant = (int)(g_stRateControl.d*31.0/g_stRateControl.r + 0.5);
  2513.         mquant <<= 1;
  2514.  
  2515.         /* clip mquant to legal (linear) range */
  2516.         if (mquant<2)
  2517.             mquant = 2;
  2518.  
  2519.         if (mquant>62)
  2520.             mquant = 62;
  2521.  
  2522.         g_stRateControl.prev_mquant = mquant;
  2523.     }
  2524.  
  2525.     return mquant;
  2526. }
  2527. /*---------------------------------------------------------
  2528.     Step 2: measure virtual buffer - estimated buffer discrepancy
  2529. ---------------------------------------------------------*/
  2530. inline int RcCalcMQuant(const int j)
  2531. {
  2532.     int mquant;
  2533.     double dj, Qj, actj, N_actj;
  2534.  
  2535.     /* measure virtual buffer discrepancy from uniform distribution model */
  2536.     dj = g_stRateControl.d + (g_stSystemData.bitcount()-g_stRateControl.S)
  2537.         - j*(g_stRateControl.T/(g_stSequenceData.stHeader.nMacroBlocksWidth*g_stSequenceData.stHeader.nMacroBlocksHeight2));
  2538.  
  2539.     /* scale against dynamic range of mquant and the bits/picture count */
  2540.     Qj = dj*31.0/g_stRateControl.r;
  2541.     /*Qj = dj*(q_scale_type ? 56.0 : 31.0)/r;  */
  2542.  
  2543.     actj = g_stPictureStruct.pstMacroBlockInfo[j].act;
  2544.     g_stRateControl.actsum+= actj;
  2545.  
  2546.     /* compute normalized activity */
  2547.     N_actj = (2.0*actj+g_stRateControl.avg_act)/(actj+2.0*g_stRateControl.avg_act);
  2548.  
  2549.     if (g_stPictureData.stCodingExtension.bQScaleType)
  2550.     {
  2551.         /* modulate mquant with combined buffer and local activity measures */
  2552.         mquant = (int)(2.0*Qj*N_actj + 0.5);
  2553.  
  2554.         /* clip mquant to legal (linear) range */
  2555.         if (mquant<1)
  2556.             mquant = 1;
  2557.  
  2558.         if (mquant>112)
  2559.             mquant = 112;
  2560.  
  2561.         /* map to legal quantization level */
  2562.         mquant = g_NonLinerQuantizationArray[g_MapNonLinearQuantizationArray[mquant]];
  2563.     }
  2564.     else
  2565.     {
  2566.         /* modulate mquant with combined buffer and local activity measures */
  2567.         mquant = (int)(Qj*N_actj + 0.5);
  2568.         mquant <<= 1;
  2569.  
  2570.         /* clip mquant to legal (linear) range */
  2571.         if (mquant<2)
  2572.             mquant = 2;
  2573.  
  2574.         if (mquant>62)
  2575.             mquant = 62;
  2576.  
  2577.         /* ignore small changes in mquant */
  2578.         if (mquant>=8 && (mquant-g_stRateControl.prev_mquant)>=-4 && (mquant-g_stRateControl.prev_mquant)<=4)
  2579.             mquant = g_stRateControl.prev_mquant;
  2580.  
  2581.         g_stRateControl.prev_mquant = mquant;
  2582.     }
  2583.  
  2584.     g_stRateControl.Q+= mquant; /* for calculation of average mquant */
  2585.  
  2586.     return mquant;
  2587. }
  2588. /*---------------------------------------------------------
  2589.     compute variance of 8x8 block
  2590. ---------------------------------------------------------*/
  2591. double VarSBlock(unsigned char* p,const int lx)
  2592. {
  2593.     int i, j;
  2594.     unsigned int v, s, s2;
  2595.  
  2596.     s = s2 = 0;
  2597.     for (j=0; j<8; j++)
  2598.     {
  2599.         for (i=0; i<8; i++)
  2600.         {
  2601.             v = *p++;
  2602.             s+= v;
  2603.             s2+= v*v;
  2604.         }
  2605.         p+= lx - 8;
  2606.     }
  2607.  
  2608.     return s2/64.0 - (s/64.0)*(s/64.0);
  2609. }
  2610. /*=========================================================
  2611.     VBV é╠îvÄZ
  2612.  
  2613.     generates warnings if underflow or overflow occurs
  2614. =========================================================*/
  2615. /*---------------------------------------------------------
  2616.     has to be called directly after writing picture_data()
  2617.     needed for accurate VBV buffer overflow calculation
  2618.     assumes there is no byte stuffing prior to the next start code
  2619. ---------------------------------------------------------*/
  2620. void VBVEndOfPicture(void)
  2621. {
  2622.     static int bitcnt_EOP;
  2623.     bitcnt_EOP = g_stSystemData.bitcount();
  2624.     bitcnt_EOP = (bitcnt_EOP + 7) & ~7; /* account for bit stuffing */
  2625. }
  2626. /*---------------------------------------------------------
  2627.     has to be called directly after writing the picture start code,
  2628.     the    reference point for vbv_delay
  2629. ---------------------------------------------------------*/
  2630. inline int CalcVBVDelay(void)
  2631. {
  2632.     const double frame_rate = g_stSequenceData.stHeader.fFrameRate;
  2633.     const bool prog_seq = g_stSequenceData.stExtension.bProgressSequence;
  2634.  
  2635.     double picture_delay;
  2636.     int nVBVDelay;
  2637.     static double next_ip_delay; /* due to frame reordering delay */
  2638.     static double decoding_time = 0.0;
  2639.  
  2640.     /* number of 1/90000 s ticks until next picture is to be decoded */
  2641.     if (g_stPictureData.stHeader.nPictType == B_TYPE)
  2642.     {
  2643.         if (prog_seq)
  2644.         {
  2645.             if (!g_stPictureData.stCodingExtension.bRepeatFirst)
  2646.                 picture_delay = 90000.0/frame_rate; /* 1 frame */
  2647.             else
  2648.             {
  2649.                 if (!g_stPictureData.stCodingExtension.bTopFirst)
  2650.                     picture_delay = 90000.0*2.0/frame_rate; /* 2 frames */
  2651.                 else
  2652.                     picture_delay = 90000.0*3.0/frame_rate; /* 3 frames */
  2653.             }
  2654.         }
  2655.         else
  2656.         {
  2657.             /* interlaced */
  2658.             if (g_stCodingModelParams.bFieldPicture)
  2659.                 picture_delay = 90000.0/(2.0*frame_rate); /* 1 field */
  2660.             else
  2661.             {
  2662.                 if (!g_stPictureData.stCodingExtension.bRepeatFirst)
  2663.                     picture_delay = 90000.0*2.0/(2.0*frame_rate); /* 2 flds */
  2664.                 else
  2665.                     picture_delay = 90000.0*3.0/(2.0*frame_rate); /* 3 flds */
  2666.             }
  2667.         }
  2668.     }
  2669.     else
  2670.     {
  2671.         /* I or P picture */
  2672.         if (g_stCodingModelParams.bFieldPicture)
  2673.         {
  2674.             if(g_stPictureData.stCodingExtension.bTopFirst==(g_stPictureData.stCodingExtension.nPictStruct==TOP_FIELD))
  2675.             {
  2676.                 /* first field */
  2677.                 picture_delay = 90000.0/(2.0*frame_rate);
  2678.             }
  2679.             else
  2680.             {
  2681.                 /* second field */
  2682.                 /* take frame reordering delay into account */
  2683.                 picture_delay = next_ip_delay - 90000.0/(2.0*frame_rate);
  2684.             }
  2685.         }
  2686.         else
  2687.         {
  2688.             /* frame picture */
  2689.             /* take frame reordering delay into account*/
  2690.             picture_delay = next_ip_delay;
  2691.         }
  2692.  
  2693.         if (!g_stCodingModelParams.bFieldPicture || g_stPictureData.stCodingExtension.bTopFirst!=(g_stPictureData.stCodingExtension.nPictStruct==TOP_FIELD))
  2694.         {
  2695.             /* frame picture or second field */
  2696.             if (prog_seq)
  2697.             {
  2698.                 if (!g_stPictureData.stCodingExtension.bRepeatFirst)
  2699.                     next_ip_delay = 90000.0/frame_rate;
  2700.                 else
  2701.                 {
  2702.                     if (!g_stPictureData.stCodingExtension.bTopFirst)
  2703.                         next_ip_delay = 90000.0*2.0/frame_rate;
  2704.                     else
  2705.                         next_ip_delay = 90000.0*3.0/frame_rate;
  2706.                 }
  2707.             }
  2708.             else
  2709.             {
  2710.                 if (g_stCodingModelParams.bFieldPicture)
  2711.                     next_ip_delay = 90000.0/(2.0*frame_rate);
  2712.                 else
  2713.                 {
  2714.                     if (!g_stPictureData.stCodingExtension.bRepeatFirst)
  2715.                         next_ip_delay = 90000.0*2.0/(2.0*frame_rate);
  2716.                     else
  2717.                         next_ip_delay = 90000.0*3.0/(2.0*frame_rate);
  2718.                 }
  2719.             }
  2720.         }
  2721.     }
  2722.  
  2723.     if (decoding_time==0.0)
  2724.     {
  2725.         /* first call of calc_vbv_delay */
  2726.         /* we start with a 7/8 filled VBV buffer (12.5% back-off) */
  2727.         picture_delay = ((g_stSequenceData.stHeader.nVBVBufferSize*16384*7)/8)*90000.0/g_stSequenceData.stHeader.fBitRate;
  2728.         if (g_stCodingModelParams.bFieldPicture)
  2729.             next_ip_delay = (int)(90000.0/frame_rate+0.5);
  2730.     }
  2731.  
  2732.     /* VBV checks */
  2733.  
  2734.     /* when to decode current frame */
  2735.     decoding_time += picture_delay;
  2736.  
  2737.     /* warning: bitcount() may overflow (e.g. after 9 min. at 8 Mbit/s */
  2738.     nVBVDelay = (int)(decoding_time - g_stSystemData.bitcount()*90000.0/g_stSequenceData.stHeader.fBitRate);
  2739.  
  2740.     if (nVBVDelay<0)
  2741.     {
  2742.         nVBVDelay = 0;
  2743.     }
  2744.  
  2745.     if (nVBVDelay>65535)
  2746.     {
  2747.         nVBVDelay = 65535;
  2748.     }
  2749.  
  2750.     return nVBVDelay;
  2751. }
  2752. /*=========================================================
  2753.     âwâbâ_é╠Åæé½ì₧é▌
  2754. =========================================================*/
  2755. /*---------------------------------------------------------
  2756.     âwâbâ_é╠Åæé½ì₧é▌
  2757. ---------------------------------------------------------*/
  2758. inline void PutGroupHeader(const int frame,const unsigned char closed_gop)
  2759. {
  2760.     g_stSystemData.alignbits();
  2761.     g_stSystemData.putbits(GOP_START_CODE,32); /* group_start_code */
  2762.     g_stSystemData.putbits(FrameToTimeCode(g_stCodingModelParams.nTimeCodeOfFirstFrame+frame),25); /* time_code */
  2763.     g_stSystemData.putbits(closed_gop,1); /* closed_gop */
  2764.     g_stSystemData.putbits(0,1); /* broken_link */
  2765. }
  2766. /*---------------------------------------------------------
  2767.     âtâîü[âÇö╘ìåé⌐éτâ^âCâÇâRü[âhé╓ò╧è╖
  2768. ---------------------------------------------------------*/
  2769. inline int FrameToTimeCode(int frame)
  2770. {
  2771.     int fps, pict, sec, minute, hour, tc;
  2772.  
  2773.     fps = (int)(g_stSequenceData.stHeader.fFrameRate+0.5);
  2774.     pict = frame%fps;
  2775.     frame = (frame-pict)/fps;
  2776.     sec = frame%60;
  2777.     frame = (frame-sec)/60;
  2778.     minute = frame%60;
  2779.     frame = (frame-minute)/60;
  2780.     hour = frame%24;
  2781.     tc = (hour<<19) | (minute<<13) | (1<<12) | (sec<<6) | pict;
  2782.  
  2783.     return tc;
  2784. }
  2785. /*---------------------------------------------------------
  2786.     output a zero terminated string as user data
  2787.  
  2788.     string must not emulate start codes
  2789. ---------------------------------------------------------*/
  2790. inline void PutUserData(char* userdata)
  2791. {
  2792.     g_stSystemData.alignbits();
  2793.     g_stSystemData.putbits(USER_START_CODE,32); /* user_data_start_code */
  2794.     while (*userdata)
  2795.         g_stSystemData.putbits(*userdata++,8);
  2796. }
  2797. /*---------------------------------------------------------
  2798.     generate picture header
  2799. ---------------------------------------------------------*/
  2800. inline void PutPictureHeader(void)
  2801. {
  2802.     g_stSystemData.alignbits();
  2803.     g_stSystemData.putbits(PICTURE_START_CODE,32); /* picture_start_code */
  2804.     g_stSystemData.putbits(g_stPictureData.stHeader.nTempRef,10); /* temporal_reference */
  2805.     g_stSystemData.putbits(g_stPictureData.stHeader.nPictType,3); /* picture_coding_type */
  2806.     g_stSystemData.putbits(CalcVBVDelay(),16); /* vbv_delay */
  2807.  
  2808.     if (g_stPictureData.stHeader.nPictType==P_TYPE
  2809.         || g_stPictureData.stHeader.nPictType==B_TYPE)
  2810.     {
  2811.         g_stSystemData.putbits(0,1); /* full_pel_forward_vector */
  2812.         g_stSystemData.putbits(g_stPictureData.stCodingExtension.nForwHorFCode,3);
  2813.     }
  2814.  
  2815.     if (g_stPictureData.stHeader.nPictType==B_TYPE)
  2816.     {
  2817.         g_stSystemData.putbits(0,1); /* full_pel_backward_vector */
  2818.         g_stSystemData.putbits(g_stPictureData.stCodingExtension.nBackHorFCode,3);
  2819.     }
  2820.  
  2821.     g_stSystemData.putbits(0,1); /* extra_bit_picture */
  2822. }
  2823. /*---------------------------------------------------------
  2824.     generate picture coding extension (6.2.3.1, 6.3.11)
  2825.  
  2826.     composite display information (v_axis etc.) not implemented
  2827. ---------------------------------------------------------*/
  2828. inline void PutPictureCodingExtension(void)
  2829. {
  2830.     g_stSystemData.alignbits();
  2831.     g_stSystemData.putbits(EXT_START_CODE,32); /* extension_start_code */
  2832.     g_stSystemData.putbits(CODING_ID,4); /* extension_start_code_identifier */
  2833.     g_stSystemData.putbits(g_stPictureData.stCodingExtension.nForwHorFCode,4); /* forward_horizontal_f_code */
  2834.     g_stSystemData.putbits(g_stPictureData.stCodingExtension.nForwVertFCode,4); /* forward_vertical_f_code */
  2835.     g_stSystemData.putbits(g_stPictureData.stCodingExtension.nBackHorFCode,4); /* backward_horizontal_f_code */
  2836.     g_stSystemData.putbits(g_stPictureData.stCodingExtension.nBackVertFCode,4); /* backward_vertical_f_code */
  2837.     g_stSystemData.putbits(g_stPictureData.stCodingExtension.nDCPrecision,2); /* intra_dc_precision */
  2838.     g_stSystemData.putbits(g_stPictureData.stCodingExtension.nPictStruct,2); /* picture_structure */
  2839.     if(g_stPictureData.stCodingExtension.nPictStruct==FRAME_PICTURE)
  2840.         g_stSystemData.putbits(g_stPictureData.stCodingExtension.bTopFirst?1:0,1); /* top_field_first */
  2841.  
  2842.     else
  2843.         g_stSystemData.putbits(0,1); /* top_field_first */
  2844.     g_stSystemData.putbits(g_stPictureData.stCodingExtension.bFramePredDCT?1:0,1); /* frame_pred_frame_dct */
  2845.     g_stSystemData.putbits(0,1); /* concealment_motion_vectors  -- currently not implemented */
  2846.     g_stSystemData.putbits(g_stPictureData.stCodingExtension.bQScaleType?1:0,1); /* q_scale_type */
  2847.     g_stSystemData.putbits(g_stPictureData.stCodingExtension.bIntravlc?1:0,1); /* intra_vlc_format */
  2848.     g_stSystemData.putbits(g_stPictureData.stCodingExtension.bAltScan?1:0,1); /* g_AlternateScanArray */
  2849.     g_stSystemData.putbits(g_stPictureData.stCodingExtension.bRepeatFirst?1:0,1); /* repeat_first_field */
  2850.     g_stSystemData.putbits(g_stPictureData.stCodingExtension.bProgFrame?1:0,1); /* chroma_420_type */
  2851.     g_stSystemData.putbits(g_stPictureData.stCodingExtension.bProgFrame?1:0,1); /* progressive_frame */
  2852.     g_stSystemData.putbits(0,1); /* composite_display_flag */
  2853. }
  2854.  
  2855. /*---------------------------------------------------------
  2856.     BITMAPINFOHEADER é╞ ârâbâgâfü[â^é≡Ä≤é»Äµé┴é─üCÄgùpë┬ö\é╚î`é╔ò╧ìXé╖éΘ
  2857. ---------------------------------------------------------*/
  2858. inline TOMPGRET ConvRGBtoYUV(const LPBITMAPINFO lpInfo,const unsigned char* pBytes,unsigned char* frame[])
  2859. {
  2860.     const int width = g_stSequenceData.stHeader.nWidth;
  2861.     const int height = g_stSequenceData.stHeader.nHeight;
  2862.     const int vertical_size = g_stSequenceData.stHeader.nVFrameSize;
  2863.     const double RY = (77.0/256.0), GY = (150.0/256.0), BY = (29.0/256.0);
  2864.     const double RU = (-44.0/256.0), GU = (-87.0/256.0), BU = (131.0/256.0);
  2865.     const double RV = (131.0/256.0), GV = (-110.0/256.0), BV = (-21.0/256.0);
  2866.     const unsigned short pixsz = lpInfo->bmiHeader.biBitCount;
  2867.     const int bytewidth = (((lpInfo->bmiHeader.biWidth*lpInfo->bmiHeader.biBitCount+31)&~31)/8);
  2868.  
  2869.     static unsigned int u, dib_offset, j, hblank, vblank, hcrop, vcrop, topblank;
  2870.     static int x, y;
  2871.     static double R, G, B;
  2872.     unsigned char *lpcurpix,*lpcurscanl;
  2873.     unsigned short *lpcurpixw;
  2874.  
  2875.  
  2876.     int h, w, p;
  2877.     int lblank, rblank;
  2878.     unsigned char *lpframeY;
  2879.     const RGBQUAD *lpPal = (RGBQUAD*)(((unsigned char*)lpInfo) + lpInfo->bmiHeader.biSize);
  2880.  
  2881.     if((pixsz!=8)&&(pixsz!=16)&&(pixsz!=24)&&(pixsz!=32))
  2882.     {
  2883.         return TR_BITCOUNT_ERR;
  2884.     }
  2885.  
  2886.     // check for compression type of retrieved DIB
  2887.  
  2888.     if (lpInfo->bmiHeader.biCompression != BI_RGB) // does not support BI_BITFIELDS
  2889.     {
  2890.         return TR_BICOMPRESSION_ERR;
  2891.     }
  2892.  
  2893.     // if frame width is less than output width, then there are blank pixels in output frame on left and right
  2894.     if(width>lpInfo->bmiHeader.biWidth)
  2895.         hblank = width - lpInfo->bmiHeader.biWidth;
  2896.     else
  2897.         hblank=0;
  2898.  
  2899.     // similarily, if height is less than output, then there are blank lines at the top and bottom
  2900.     if(height>lpInfo->bmiHeader.biHeight)
  2901.         vblank = height - lpInfo->bmiHeader.biHeight;
  2902.     else
  2903.         vblank=0;
  2904.  
  2905.     // if frame width is greater than output width, we have to trim pixels
  2906.     if(width<lpInfo->bmiHeader.biWidth)
  2907.         hcrop = lpInfo->bmiHeader.biWidth - width;
  2908.     else
  2909.         hcrop=0;
  2910.  
  2911.     // if frame height is greater than output height, we have to trim pixels
  2912.     if(height<lpInfo->bmiHeader.biHeight)
  2913.         vcrop = lpInfo->bmiHeader.biHeight - height;
  2914.     else
  2915.         vcrop=0;
  2916.  
  2917.     if(vertical_size>lpInfo->bmiHeader.biHeight)
  2918.         topblank = (vertical_size - lpInfo->bmiHeader.biHeight)/2;
  2919.     else
  2920.         topblank = 0;
  2921.  
  2922.     // convert RGB DIB to YUV (4:2:0)
  2923.     lpframeY = (unsigned char *)frame[0];
  2924.  
  2925.     // take care of any blank lines on the top
  2926.     j = topblank;
  2927.     while(j > 0)
  2928.     {
  2929.         for(x = 0; x < width; x++)
  2930.         {
  2931.             *lpframeY++ = 0;
  2932.             p = x + (j - 1)*width;
  2933.             g_stUVTempBuffers.SetUVBuffer(p,128,128);
  2934.         }
  2935.         j--;
  2936.     }
  2937.  
  2938.     switch(pixsz)
  2939.     {
  2940.         case 8:
  2941.             lpcurscanl = (unsigned char *)(pBytes + ((lpInfo->bmiHeader.biHeight - 1 - (vcrop/2)) * bytewidth) + ((hcrop/2)));
  2942.             p = (hblank/2)+topblank*width;
  2943.  
  2944.             h = lpInfo->bmiHeader.biHeight - (int) vcrop;
  2945.             lblank = hblank/2;
  2946.             rblank = hblank - lblank;
  2947.  
  2948.             do
  2949.             {
  2950.                 // take care of any blank pixels on the left
  2951.                 if(lblank > 0)
  2952.                 {
  2953.                     memset(lpframeY, 0, lblank);
  2954.                     g_stUVTempBuffers.SetUVBuffer(p,128,128,lblank);
  2955.                     lpframeY += lblank;
  2956.                     p += lblank;
  2957.                 }
  2958.  
  2959.                 w = lpInfo->bmiHeader.biWidth - (int) hcrop;
  2960.                 lpcurpix = lpcurscanl;
  2961.  
  2962.                 do
  2963.                 {
  2964.                     R = (float) lpPal[*lpcurpix * 4].rgbRed;
  2965.                     G = (float) lpPal[*lpcurpix * 4].rgbGreen;
  2966.                     B = (float) lpPal[*lpcurpix * 4].rgbBlue;
  2967.                     lpcurpix++;
  2968.  
  2969.                     *lpframeY++ = (int)(RY*R + GY*G + BY*B);
  2970.                     g_stUVTempBuffers.SetUVBuffer(p,
  2971.                         (int)(RU*R + GU*G + BU*B + 128.5),
  2972.                         (int)(RV*R + GV*G + BV*B + 128.5));
  2973.                     p++;
  2974.                 } while(--w);
  2975.  
  2976.                 // take care of any blank pixels on the right
  2977.                 if(rblank > 0)
  2978.                 {
  2979.                     memset(lpframeY, 0, rblank);
  2980.                     g_stUVTempBuffers.SetUVBuffer(p,128,128,rblank);
  2981.                     lpframeY += rblank;
  2982.                     p += rblank;
  2983.                 }
  2984.  
  2985.                 lpcurscanl -= bytewidth;
  2986.             } while(--h);
  2987.             break;
  2988.  
  2989.         case 16:
  2990.             lpcurscanl = (unsigned char *)(pBytes + ((lpInfo->bmiHeader.biHeight - 1 - (vcrop/2)) * bytewidth) + ((hcrop/2) * 2));
  2991.             p = (hblank/2)+topblank*width;
  2992.  
  2993.             h = lpInfo->bmiHeader.biHeight - (int) vcrop;
  2994.             lblank = hblank/2;
  2995.             rblank = hblank - lblank;
  2996.  
  2997.             do
  2998.             {
  2999.                 // take care of any blank pixels on the left
  3000.                 if(lblank > 0)
  3001.                 {
  3002.                     memset(lpframeY, 0, lblank);
  3003.                     g_stUVTempBuffers.SetUVBuffer(p,128,128,lblank);
  3004.                     lpframeY += lblank;
  3005.                     p += lblank;
  3006.                 }
  3007.  
  3008.                 w = lpInfo->bmiHeader.biWidth - (int) hcrop;
  3009.                 lpcurpixw = (unsigned short *) lpcurscanl;
  3010.  
  3011.                 do
  3012.                 {
  3013.                     R = (float)(((*lpcurpixw >> 7) & 0xf8)|0x07);
  3014.                     G = (float)(((*lpcurpixw >> 2) & 0xf8)|0x07);
  3015.                     B = (float)(((*lpcurpixw << 3) & 0xf8)|0x07);
  3016.                     lpcurpixw++;
  3017.  
  3018.                     *lpframeY++ = (int)(RY*R + GY*G + BY*B);
  3019.                     g_stUVTempBuffers.SetUVBuffer(p,
  3020.                         (int)(RU*R + GU*G + BU*B + 128.5),
  3021.                         (int)(RV*R + GV*G + BV*B + 128.5));
  3022.                     p++;
  3023.                 } while(--w);
  3024.  
  3025.                 // take care of any blank pixels on the right
  3026.                 if(rblank > 0)
  3027.                 {
  3028.                     memset(lpframeY, 0, rblank);
  3029.                     g_stUVTempBuffers.SetUVBuffer(p,128,128,rblank);
  3030.                     lpframeY += rblank;
  3031.                     p += rblank;
  3032.                 }
  3033.  
  3034.                 lpcurscanl -= bytewidth;
  3035.             } while(--h);
  3036.             break;
  3037.  
  3038.         case 24:
  3039.             lpcurscanl = (unsigned char *)(pBytes + ((lpInfo->bmiHeader.biHeight - 1 - (vcrop/2)) * bytewidth) + ((hcrop/2) * 3));
  3040.             p = (hblank/2)+topblank*width;
  3041.  
  3042.             h = lpInfo->bmiHeader.biHeight - (int) vcrop;
  3043.             lblank = hblank/2;
  3044.             rblank = hblank - lblank;
  3045.  
  3046.             do
  3047.             {
  3048.                 // take care of any blank pixels on the left
  3049.                 if(lblank > 0)
  3050.                 {
  3051.                     memset(lpframeY, 0, lblank);
  3052.                     g_stUVTempBuffers.SetUVBuffer(p,128,128,lblank);
  3053.                     lpframeY += lblank;
  3054.                     p += lblank;
  3055.                 }
  3056.  
  3057.                 w = lpInfo->bmiHeader.biWidth - (int) hcrop;
  3058.                 lpcurpix = lpcurscanl;
  3059.  
  3060.                 do
  3061.                 {
  3062.                     B = *lpcurpix++;
  3063.                     G = *lpcurpix++;
  3064.                     R = *lpcurpix++;
  3065.  
  3066.                     *lpframeY++ = (int)(RY*R + GY*G + BY*B);
  3067.                     g_stUVTempBuffers.SetUVBuffer(p,
  3068.                         (int)(RU*R + GU*G + BU*B + 128.5),
  3069.                         (int)(RV*R + GV*G + BV*B + 128.5));
  3070.                     p++;
  3071.                 } while(--w);
  3072.  
  3073.                 // take care of any blank pixels on the right
  3074.                 if(rblank > 0)
  3075.                 {
  3076.                     memset(lpframeY, 0, rblank);
  3077.                     g_stUVTempBuffers.SetUVBuffer(p,128,128,rblank);
  3078.                     lpframeY += rblank;
  3079.                     p += rblank;
  3080.                 }
  3081.  
  3082.                 lpcurscanl -= bytewidth;
  3083.             } while(--h);
  3084.             break;
  3085.  
  3086.         case 32:
  3087.             lpcurscanl = (unsigned char *)(pBytes + ((lpInfo->bmiHeader.biHeight - 1 - (vcrop/2)) * bytewidth) + ((hcrop/2) * 4));
  3088.             p = (hblank/2)+topblank*width;
  3089.  
  3090.             h = lpInfo->bmiHeader.biHeight - (int) vcrop;
  3091.             lblank = hblank/2;
  3092.             rblank = hblank - lblank;
  3093.  
  3094.             do
  3095.             {
  3096.                 // take care of any blank pixels on the left
  3097.                 if(lblank > 0)
  3098.                 {
  3099.                     memset(lpframeY, 0, lblank);
  3100.                     g_stUVTempBuffers.SetUVBuffer(p,128,128,lblank);
  3101.                     lpframeY += lblank;
  3102.                     p += lblank;
  3103.                 }
  3104.  
  3105.                 w = lpInfo->bmiHeader.biWidth - (int) hcrop;
  3106.                 lpcurpix = lpcurscanl;
  3107.  
  3108.                 do
  3109.                 {
  3110.                     B = *lpcurpix++;
  3111.                     G = *lpcurpix++;
  3112.                     R = *lpcurpix++;
  3113.                     lpcurpix++;
  3114.  
  3115.                     *lpframeY++ = (int)(RY*R + GY*G + BY*B);
  3116.                     g_stUVTempBuffers.SetUVBuffer(p,
  3117.                         (int)(RU*R + GU*G + BU*B + 128.5),
  3118.                         (int)(RV*R + GV*G + BV*B + 128.5));
  3119.                     p++;
  3120.                 } while(--w);
  3121.  
  3122.                 // take care of any blank pixels on the right
  3123.                 if(rblank > 0)
  3124.                 {
  3125.                     memset(lpframeY, 0, rblank);
  3126.                     g_stUVTempBuffers.SetUVBuffer(p,128,128,rblank);
  3127.                     lpframeY += rblank;
  3128.                     p += rblank;
  3129.                 }
  3130.  
  3131.                 lpcurscanl -= bytewidth;
  3132.             } while(--h);
  3133.             break;
  3134.  
  3135.         default:
  3136.             return TR_BITCOUNT_ERR;
  3137.     }
  3138.  
  3139.     // and any blank lines on the bottom
  3140.     j = vblank - topblank;
  3141.     //printf("j=%u, vblank=%u, vertical_size=%u, biHeight=%u\n",j,vblank,vertical_size,lpbi->biHeight);
  3142.     while(j > 0)
  3143.     {
  3144.         for(x = 0; x < width; x++)
  3145.         {
  3146.             *lpframeY++ = 0;
  3147.             p = x + (topblank+lpInfo->bmiHeader.biHeight + j - 1)*width;
  3148.             g_stUVTempBuffers.SetUVBuffer(p,128,128);
  3149.         }
  3150.         j--;
  3151.     }
  3152.  
  3153.  
  3154.     // now do FIR chroma subsampling
  3155.     g_stUVTempBuffers.conv444to422U(&g_stPictureStruct,&g_stSequenceData);
  3156.     g_stUVTempBuffers.conv444to422V(&g_stPictureStruct,&g_stSequenceData);
  3157.     
  3158.     g_stUVTempBuffers.conv422to420U(frame[1],&g_stPictureStruct,&g_stSequenceData);
  3159.     g_stUVTempBuffers.conv422to420V(frame[2],&g_stPictureStruct,&g_stSequenceData);
  3160.  
  3161.     g_stUVTempBuffers.SoftFilter(frame,width,height);
  3162.  
  3163.     return TR_OK;
  3164. }
  3165. /*=========================================================
  3166.     ô«é½é╠ÉäÆΦ
  3167. =========================================================*/
  3168. /*---------------------------------------------------------
  3169.     ô«é½é╠ÉäÆΦ
  3170. ---------------------------------------------------------*/
  3171. void MotionEstimation(unsigned char* oldorg,
  3172.                        unsigned char* neworg,
  3173.                        unsigned char* oldref,
  3174.                        unsigned char* newref,
  3175.                        unsigned char* cur,
  3176.                        unsigned char* curref,
  3177.                        int sxf,int syf,int sxb,int syb,
  3178.                        MACROBLOCKINFO* mbi,
  3179.                        int secondfield,bool ipflag)
  3180. {
  3181.     int i, j;
  3182.     const int width = g_stSequenceData.stHeader.nWidth;
  3183.     const int height2 = g_stSequenceData.stHeader.nHeight2;
  3184.  
  3185.     /* loop through all macroblocks of the picture */
  3186.     for (j=0; j<height2; j+=16)
  3187.     {
  3188.         for (i=0; i<width; i+=16)
  3189.         {
  3190.             if (g_stPictureData.stCodingExtension.nPictStruct==FRAME_PICTURE)
  3191.                 FrameME(oldorg,neworg,oldref,newref,cur,i,j,sxf,syf,sxb,syb,mbi);
  3192.             else
  3193.                 FieldME(oldorg,neworg,oldref,newref,cur,curref,i,j,sxf,syf,sxb,syb,
  3194.                         mbi,secondfield,ipflag);
  3195.             mbi++;
  3196.         }
  3197.  
  3198.     }
  3199. }
  3200. /*---------------------------------------------------------
  3201.     âtâîü[âÇÅπé┼é╠ô«é½ÉäÆΦ
  3202. ---------------------------------------------------------*/
  3203. inline void FrameME(unsigned char* oldorg,
  3204.                      unsigned char* neworg,
  3205.                      unsigned char* oldref,
  3206.                      unsigned char* newref,
  3207.                      unsigned char* cur,
  3208.                      int i,int j,int sxf,int syf,int sxb,int syb,
  3209.                      MACROBLOCKINFO* mbi)
  3210. {
  3211.     const int width = g_stSequenceData.stHeader.nWidth;
  3212.     const int height = g_stSequenceData.stHeader.nHeight;
  3213.  
  3214.     int imin,jmin,iminf,jminf,iminr,jminr;
  3215.     int imint,jmint,iminb,jminb;
  3216.     int imintf,jmintf,iminbf,jminbf;
  3217.     int imintr,jmintr,iminbr,jminbr;
  3218.     int var,v0;
  3219.     int dmc,dmcf,dmcr,dmci,vmc,vmcf,vmcr,vmci;
  3220.     int dmcfield,dmcfieldf,dmcfieldr,dmcfieldi;
  3221.     int tsel,bsel,tself,bself,tselr,bselr;
  3222.     unsigned char *mb;
  3223.     int imins[2][2],jmins[2][2];
  3224.     int imindp,jmindp,imindmv,jmindmv,dmc_dp,vmc_dp;
  3225.  
  3226.  
  3227.     mb = cur + i + width*j;
  3228.  
  3229.     var = Variance(mb,width);
  3230.  
  3231.     if (g_stPictureData.stHeader.nPictType==I_TYPE)
  3232.         mbi->mb_type = MB_INTRA;
  3233.     else if (g_stPictureData.stHeader.nPictType==P_TYPE)
  3234.     {
  3235.         if (g_stPictureData.stCodingExtension.bFramePredDCT)
  3236.         {
  3237.             dmc = FullSearch(oldorg,oldref,mb,
  3238.                             width,i,j,sxf,syf,16,width,height,&imin,&jmin);
  3239.             vmc = Dist2(oldref+(imin>>1)+width*(jmin>>1),mb,
  3240.                         width,imin&1,jmin&1,16);
  3241.             mbi->motion_type = MC_FRAME;
  3242.         }
  3243.         else
  3244.         {
  3245.             FrameEstimate(oldorg,oldref,mb,i,j,sxf,syf,
  3246.                         &imin,&jmin,&imint,&jmint,&iminb,&jminb,
  3247.                         &dmc,&dmcfield,&tsel,&bsel,imins,jmins);
  3248.  
  3249.             if (g_stCodingModelParams.nDistanceBetweenIPFrames==1)
  3250.                 DPFrameEstimate(oldref,mb,i,j>>1,imins,jmins,
  3251.                                 &imindp,&jmindp,&imindmv,&jmindmv,&dmc_dp,&vmc_dp);
  3252.  
  3253.             /* select between dual prime, frame and field prediction */
  3254.             if (g_stCodingModelParams.nDistanceBetweenIPFrames==1 && dmc_dp<dmc && dmc_dp<dmcfield)
  3255.             {
  3256.                 mbi->motion_type = MC_DMV;
  3257.                 dmc = dmc_dp;
  3258.                 vmc = vmc_dp;
  3259.             }
  3260.             else if (dmc<=dmcfield)
  3261.             {
  3262.                 mbi->motion_type = MC_FRAME;
  3263.                 vmc = Dist2(oldref+(imin>>1)+width*(jmin>>1),mb,
  3264.                             width,imin&1,jmin&1,16);
  3265.             }
  3266.             else
  3267.             {
  3268.                 mbi->motion_type = MC_FIELD;
  3269.                 dmc = dmcfield;
  3270.                 vmc = Dist2(oldref+(tsel?width:0)+(imint>>1)+(width<<1)*(jmint>>1),
  3271.                             mb,width<<1,imint&1,jmint&1,8);
  3272.                 vmc+= Dist2(oldref+(bsel?width:0)+(iminb>>1)+(width<<1)*(jminb>>1),
  3273.                             mb+width,width<<1,iminb&1,jminb&1,8);
  3274.             }
  3275.         }
  3276.  
  3277.         /* select between intra or non-intra coding:
  3278.         *
  3279.         * selection is based on intra block variance (var) vs.
  3280.         * prediction error variance (vmc)
  3281.         *
  3282.         * blocks with small prediction error are always coded non-intra
  3283.         * even if variance is smaller (is this reasonable?)
  3284.         */
  3285.         if (vmc>var && vmc>=9*256)
  3286.             mbi->mb_type = MB_INTRA;
  3287.         else
  3288.         {
  3289.             /* select between MC / No-MC
  3290.             *
  3291.             * use No-MC if var(No-MC) <= 1.25*var(MC)
  3292.             * (i.e slightly biased towards No-MC)
  3293.             *
  3294.             * blocks with small prediction error are always coded as No-MC
  3295.             * (requires no motion vectors, allows skipping)
  3296.             */
  3297.             v0 = Dist2(oldref+i+width*j,mb,width,0,0,16);
  3298.  
  3299.             if (4*v0>5*vmc && v0>=9*256)
  3300.             {
  3301.                 /* use MC */
  3302.                 var = vmc;
  3303.                 mbi->mb_type = MB_FORWARD;
  3304.                 if (mbi->motion_type==MC_FRAME)
  3305.                 {
  3306.                     mbi->MV[0][0][0] = imin - (i<<1);
  3307.                     mbi->MV[0][0][1] = jmin - (j<<1);
  3308.                 }
  3309.                 else if (mbi->motion_type==MC_DMV)
  3310.                 {
  3311.                     /* these are FRAME vectors */
  3312.                     /* same parity vector */
  3313.                     mbi->MV[0][0][0] = imindp - (i<<1);
  3314.                     mbi->MV[0][0][1] = (jmindp<<1) - (j<<1);
  3315.  
  3316.                     /* opposite parity vector */
  3317.                     mbi->dmvector[0] = imindmv;
  3318.                     mbi->dmvector[1] = jmindmv;
  3319.                 }
  3320.                 else
  3321.                 {
  3322.                     /* these are FRAME vectors */
  3323.                     mbi->MV[0][0][0] = imint - (i<<1);
  3324.                     mbi->MV[0][0][1] = (jmint<<1) - (j<<1);
  3325.                     mbi->MV[1][0][0] = iminb - (i<<1);
  3326.                     mbi->MV[1][0][1] = (jminb<<1) - (j<<1);
  3327.                     mbi->mv_field_sel[0][0] = tsel;
  3328.                     mbi->mv_field_sel[1][0] = bsel;
  3329.                 }
  3330.             }
  3331.             else
  3332.             {
  3333.                 /* No-MC */
  3334.                 var = v0;
  3335.                 mbi->mb_type = 0;
  3336.                 mbi->motion_type = MC_FRAME;
  3337.                 mbi->MV[0][0][0] = 0;
  3338.                 mbi->MV[0][0][1] = 0;
  3339.             }
  3340.         }
  3341.     }
  3342.     else /* if (pict_type==B_TYPE) */
  3343.     {
  3344.         if (g_stPictureData.stCodingExtension.bFramePredDCT)
  3345.         {
  3346.             /* forward */
  3347.             dmcf = FullSearch(oldorg,oldref,mb,
  3348.                         width,i,j,sxf,syf,16,width,height,&iminf,&jminf);
  3349.             vmcf = Dist2(oldref+(iminf>>1)+width*(jminf>>1),mb,
  3350.                         width,iminf&1,jminf&1,16);
  3351.  
  3352.             /* backward */
  3353.             dmcr = FullSearch(neworg,newref,mb,
  3354.                         width,i,j,sxb,syb,16,width,height,&iminr,&jminr);
  3355.             vmcr = Dist2(newref+(iminr>>1)+width*(jminr>>1),mb,
  3356.                         width,iminr&1,jminr&1,16);
  3357.  
  3358.             /* interpolated (bidirectional) */
  3359.             vmci = BDist2(oldref+(iminf>>1)+width*(jminf>>1),
  3360.                         newref+(iminr>>1)+width*(jminr>>1),
  3361.                         mb,width,iminf&1,jminf&1,iminr&1,jminr&1,16);
  3362.  
  3363.             /* decisions */
  3364.  
  3365.             /* select between forward/backward/interpolated prediction:
  3366.             * use the one with smallest mean sqaured prediction error
  3367.             */
  3368.             if (vmcf<=vmcr && vmcf<=vmci)
  3369.             {
  3370.                 vmc = vmcf;
  3371.                 mbi->mb_type = MB_FORWARD;
  3372.             }
  3373.             else if (vmcr<=vmci)
  3374.             {
  3375.                 vmc = vmcr;
  3376.                 mbi->mb_type = MB_BACKWARD;
  3377.             }
  3378.             else
  3379.             {
  3380.                 vmc = vmci;
  3381.                 mbi->mb_type = MB_FORWARD|MB_BACKWARD;
  3382.             }
  3383.  
  3384.             mbi->motion_type = MC_FRAME;
  3385.         }
  3386.         else
  3387.         {
  3388.             /* forward prediction */
  3389.             FrameEstimate(oldorg,oldref,mb,i,j,sxf,syf,
  3390.                         &iminf,&jminf,&imintf,&jmintf,&iminbf,&jminbf,
  3391.                         &dmcf,&dmcfieldf,&tself,&bself,imins,jmins);
  3392.  
  3393.             /* backward prediction */
  3394.             FrameEstimate(neworg,newref,mb,i,j,sxb,syb,
  3395.                         &iminr,&jminr,&imintr,&jmintr,&iminbr,&jminbr,
  3396.                         &dmcr,&dmcfieldr,&tselr,&bselr,imins,jmins);
  3397.  
  3398.             /* calculate interpolated distance */
  3399.             /* frame */
  3400.             dmci = BDist1(oldref+(iminf>>1)+width*(jminf>>1),
  3401.                         newref+(iminr>>1)+width*(jminr>>1),
  3402.                         mb,width,iminf&1,jminf&1,iminr&1,jminr&1,16);
  3403.  
  3404.             /* top field */
  3405.             dmcfieldi = BDist1(oldref+(imintf>>1)+(tself?width:0)+(width<<1)*(jmintf>>1),
  3406.                             newref+(imintr>>1)+(tselr?width:0)+(width<<1)*(jmintr>>1),
  3407.                             mb,width<<1,imintf&1,jmintf&1,imintr&1,jmintr&1,8);
  3408.  
  3409.             /* bottom field */
  3410.             dmcfieldi+= BDist1(oldref+(iminbf>>1)+(bself?width:0)+(width<<1)*(jminbf>>1),
  3411.                             newref+(iminbr>>1)+(bselr?width:0)+(width<<1)*(jminbr>>1),
  3412.                             mb+width,width<<1,iminbf&1,jminbf&1,iminbr&1,jminbr&1,8);
  3413.  
  3414.             /* select prediction type of minimum distance from the
  3415.             * six candidates (field/frame * forward/backward/interpolated)
  3416.             */
  3417.             if (dmci<dmcfieldi && dmci<dmcf && dmci<dmcfieldf
  3418.                 && dmci<dmcr && dmci<dmcfieldr)
  3419.             {
  3420.                 /* frame, interpolated */
  3421.                 mbi->mb_type = MB_FORWARD|MB_BACKWARD;
  3422.                 mbi->motion_type = MC_FRAME;
  3423.                 vmc = BDist2(oldref+(iminf>>1)+width*(jminf>>1),
  3424.                             newref+(iminr>>1)+width*(jminr>>1),
  3425.                             mb,width,iminf&1,jminf&1,iminr&1,jminr&1,16);
  3426.             }
  3427.             else if (dmcfieldi<dmcf && dmcfieldi<dmcfieldf
  3428.                     && dmcfieldi<dmcr && dmcfieldi<dmcfieldr)
  3429.             {
  3430.                 /* field, interpolated */
  3431.                 mbi->mb_type = MB_FORWARD|MB_BACKWARD;
  3432.                 mbi->motion_type = MC_FIELD;
  3433.                 vmc = BDist2(oldref+(imintf>>1)+(tself?width:0)+(width<<1)*(jmintf>>1),
  3434.                             newref+(imintr>>1)+(tselr?width:0)+(width<<1)*(jmintr>>1),
  3435.                             mb,width<<1,imintf&1,jmintf&1,imintr&1,jmintr&1,8);
  3436.                 vmc+= BDist2(oldref+(iminbf>>1)+(bself?width:0)+(width<<1)*(jminbf>>1),
  3437.                             newref+(iminbr>>1)+(bselr?width:0)+(width<<1)*(jminbr>>1),
  3438.                             mb+width,width<<1,iminbf&1,jminbf&1,iminbr&1,jminbr&1,8);
  3439.             }
  3440.             else if (dmcf<dmcfieldf && dmcf<dmcr && dmcf<dmcfieldr)
  3441.             {
  3442.                 /* frame, forward */
  3443.                 mbi->mb_type = MB_FORWARD;
  3444.                 mbi->motion_type = MC_FRAME;
  3445.                 vmc = Dist2(oldref+(iminf>>1)+width*(jminf>>1),mb,
  3446.                             width,iminf&1,jminf&1,16);
  3447.             }
  3448.             else if (dmcfieldf<dmcr && dmcfieldf<dmcfieldr)
  3449.             {
  3450.                 /* field, forward */
  3451.                 mbi->mb_type = MB_FORWARD;
  3452.                 mbi->motion_type = MC_FIELD;
  3453.                 vmc = Dist2(oldref+(tself?width:0)+(imintf>>1)+(width<<1)*(jmintf>>1),
  3454.                             mb,width<<1,imintf&1,jmintf&1,8);
  3455.                 vmc+= Dist2(oldref+(bself?width:0)+(iminbf>>1)+(width<<1)*(jminbf>>1),
  3456.                             mb+width,width<<1,iminbf&1,jminbf&1,8);
  3457.             }
  3458.             else if (dmcr<dmcfieldr)
  3459.             {
  3460.                 /* frame, backward */
  3461.                 mbi->mb_type = MB_BACKWARD;
  3462.                 mbi->motion_type = MC_FRAME;
  3463.                 vmc = Dist2(newref+(iminr>>1)+width*(jminr>>1),mb,
  3464.                             width,iminr&1,jminr&1,16);
  3465.             }
  3466.             else
  3467.             {
  3468.                 /* field, backward */
  3469.                 mbi->mb_type = MB_BACKWARD;
  3470.                 mbi->motion_type = MC_FIELD;
  3471.                 vmc = Dist2(newref+(tselr?width:0)+(imintr>>1)+(width<<1)*(jmintr>>1),
  3472.                             mb,width<<1,imintr&1,jmintr&1,8);
  3473.                 vmc+= Dist2(newref+(bselr?width:0)+(iminbr>>1)+(width<<1)*(jminbr>>1),
  3474.                             mb+width,width<<1,iminbr&1,jminbr&1,8);
  3475.             }
  3476.         }
  3477.  
  3478.         /* select between intra or non-intra coding:
  3479.          *
  3480.          * selection is based on intra block variance (var) vs.
  3481.          * prediction error variance (vmc)
  3482.          *
  3483.          * blocks with small prediction error are always coded non-intra
  3484.          * even if variance is smaller (is this reasonable?)
  3485.          */
  3486.         if (vmc>var && vmc>=9*256)
  3487.             mbi->mb_type = MB_INTRA;
  3488.         else
  3489.         {
  3490.             var = vmc;
  3491.             if (mbi->motion_type==MC_FRAME)
  3492.             {
  3493.                 /* forward */
  3494.                 mbi->MV[0][0][0] = iminf - (i<<1);
  3495.                 mbi->MV[0][0][1] = jminf - (j<<1);
  3496.                 /* backward */
  3497.                 mbi->MV[0][1][0] = iminr - (i<<1);
  3498.                 mbi->MV[0][1][1] = jminr - (j<<1);
  3499.             }
  3500.             else
  3501.             {
  3502.                 /* these are FRAME vectors */
  3503.                 /* forward */
  3504.                 mbi->MV[0][0][0] = imintf - (i<<1);
  3505.                 mbi->MV[0][0][1] = (jmintf<<1) - (j<<1);
  3506.                 mbi->MV[1][0][0] = iminbf - (i<<1);
  3507.                 mbi->MV[1][0][1] = (jminbf<<1) - (j<<1);
  3508.                 mbi->mv_field_sel[0][0] = tself;
  3509.                 mbi->mv_field_sel[1][0] = bself;
  3510.                 /* backward */
  3511.                 mbi->MV[0][1][0] = imintr - (i<<1);
  3512.                 mbi->MV[0][1][1] = (jmintr<<1) - (j<<1);
  3513.                 mbi->MV[1][1][0] = iminbr - (i<<1);
  3514.                 mbi->MV[1][1][1] = (jminbr<<1) - (j<<1);
  3515.                 mbi->mv_field_sel[0][1] = tselr;
  3516.                 mbi->mv_field_sel[1][1] = bselr;
  3517.             }
  3518.         }
  3519.     }
  3520.  
  3521.     mbi->var = var;
  3522. }
  3523.  
  3524. /*---------------------------------------------------------
  3525.     âtâBü[âïâhÅπé┼é╠ô«é½ÉäÆΦ
  3526. ---------------------------------------------------------*/
  3527. inline void FieldME(unsigned char *oldorg, unsigned char *neworg,
  3528.                     unsigned char *oldref, unsigned char *newref, unsigned char *cur,
  3529.                     unsigned char *curref, int i, int j, int sxf, int syf, int sxb, int syb,
  3530.                     MACROBLOCKINFO *mbi, int secondfield, bool ipflag)
  3531. {
  3532.     const int width = g_stSequenceData.stHeader.nWidth;
  3533.     int w2;
  3534.     unsigned char *mb, *toporg, *topref, *botorg, *botref;
  3535.     int var,vmc,v0,dmc,dmcfieldi,dmc8i;
  3536.     int imin,jmin,imin8u,jmin8u,imin8l,jmin8l,dmcfield,dmc8,sel,sel8u,sel8l;
  3537.     int iminf,jminf,imin8uf,jmin8uf,imin8lf,jmin8lf,dmcfieldf,dmc8f,self,sel8uf,sel8lf;
  3538.     int iminr,jminr,imin8ur,jmin8ur,imin8lr,jmin8lr,dmcfieldr,dmc8r,selr,sel8ur,sel8lr;
  3539.     int imins,jmins,ds,imindmv,jmindmv,vmc_dp,dmc_dp;
  3540.  
  3541.     w2 = width<<1;
  3542.  
  3543.     mb = cur + i + w2*j;
  3544.  
  3545.     if (g_stPictureData.stCodingExtension.nPictStruct==BOTTOM_FIELD)
  3546.         mb += width;
  3547.  
  3548.     var = Variance(mb,w2);
  3549.  
  3550.     if (g_stPictureData.stHeader.nPictType==I_TYPE)
  3551.         mbi->mb_type = MB_INTRA;
  3552.     else if (g_stPictureData.stHeader.nPictType==P_TYPE)
  3553.     {
  3554.         toporg = oldorg;
  3555.         topref = oldref;
  3556.         botorg = oldorg + width;
  3557.         botref = oldref + width;
  3558.  
  3559.         if (secondfield)
  3560.         {
  3561.             /* opposite parity field is in same frame */
  3562.             if (g_stPictureData.stCodingExtension.nPictStruct==TOP_FIELD)
  3563.             {
  3564.                 /* current is top field */
  3565.                 botorg = cur + width;
  3566.                 botref = curref + width;
  3567.             }
  3568.             else
  3569.             {
  3570.                 /* current is bottom field */
  3571.                 toporg = cur;
  3572.                 topref = curref;
  3573.             }
  3574.         }
  3575.  
  3576.         FieldEstimate(toporg,topref,botorg,botref,mb,i,j,sxf,syf,ipflag,
  3577.                         &imin,&jmin,&imin8u,&jmin8u,&imin8l,&jmin8l,
  3578.                         &dmcfield,&dmc8,&sel,&sel8u,&sel8l,&imins,&jmins,&ds);
  3579.  
  3580.         if (g_stCodingModelParams.nDistanceBetweenIPFrames==1 && !ipflag)  /* generic condition which permits Dual Prime */
  3581.             DPFieldEstimate(topref,botref,mb,i,j,imins,jmins,&imindmv,&jmindmv,
  3582.                             &dmc_dp,&vmc_dp);
  3583.  
  3584.         /* select between dual prime, field and 16x8 prediction */
  3585.         if (g_stCodingModelParams.nDistanceBetweenIPFrames==1 && !ipflag && dmc_dp<dmc8 && dmc_dp<dmcfield)
  3586.         {
  3587.             /* Dual Prime prediction */
  3588.             mbi->motion_type = MC_DMV;
  3589.             dmc = dmc_dp;     /* L1 metric */
  3590.             vmc = vmc_dp;     /* we already calculated L2 error for Dual */
  3591.  
  3592.         }
  3593.         else if (dmc8<dmcfield)
  3594.         {
  3595.             /* 16x8 prediction */
  3596.             mbi->motion_type = MC_16X8;
  3597.             /* upper half block */
  3598.             vmc = Dist2((sel8u?botref:topref) + (imin8u>>1) + w2*(jmin8u>>1),
  3599.                         mb,w2,imin8u&1,jmin8u&1,8);
  3600.             /* lower half block */
  3601.             vmc+= Dist2((sel8l?botref:topref) + (imin8l>>1) + w2*(jmin8l>>1),
  3602.                         mb+8*w2,w2,imin8l&1,jmin8l&1,8);
  3603.         }
  3604.         else
  3605.         {
  3606.             /* field prediction */
  3607.             mbi->motion_type = MC_FIELD;
  3608.             vmc = Dist2((sel?botref:topref) + (imin>>1) + w2*(jmin>>1),
  3609.                         mb,w2,imin&1,jmin&1,16);
  3610.         }
  3611.  
  3612.         /* select between intra and non-intra coding */
  3613.         if (vmc>var && vmc>=9*256)
  3614.             mbi->mb_type = MB_INTRA;
  3615.         else
  3616.         {
  3617.             /* zero MV field prediction from same parity ref. field
  3618.             * (not allowed if ipflag is set)
  3619.             */
  3620.             if (!ipflag)
  3621.                 v0 = Dist2(((g_stPictureData.stCodingExtension.nPictStruct==BOTTOM_FIELD)?botref:topref) + i + w2*j,
  3622.                             mb,w2,0,0,16);
  3623.             if (ipflag || (4*v0>5*vmc && v0>=9*256))
  3624.             {
  3625.                 var = vmc;
  3626.                 mbi->mb_type = MB_FORWARD;
  3627.                 if (mbi->motion_type==MC_FIELD)
  3628.                 {
  3629.                     mbi->MV[0][0][0] = imin - (i<<1);
  3630.                     mbi->MV[0][0][1] = jmin - (j<<1);
  3631.                     mbi->mv_field_sel[0][0] = sel;
  3632.                 }
  3633.                 else if (mbi->motion_type==MC_DMV)
  3634.                 {
  3635.                     /* same parity vector */
  3636.                     mbi->MV[0][0][0] = imins - (i<<1);
  3637.                     mbi->MV[0][0][1] = jmins - (j<<1);
  3638.  
  3639.                     /* opposite parity vector */
  3640.                     mbi->dmvector[0] = imindmv;
  3641.                     mbi->dmvector[1] = jmindmv;
  3642.                 }
  3643.                 else
  3644.                 {
  3645.                     mbi->MV[0][0][0] = imin8u - (i<<1);
  3646.                     mbi->MV[0][0][1] = jmin8u - (j<<1);
  3647.                     mbi->MV[1][0][0] = imin8l - (i<<1);
  3648.                     mbi->MV[1][0][1] = jmin8l - ((j+8)<<1);
  3649.                     mbi->mv_field_sel[0][0] = sel8u;
  3650.                     mbi->mv_field_sel[1][0] = sel8l;
  3651.                 }
  3652.             }
  3653.             else
  3654.             {
  3655.                 /* No MC */
  3656.                 var = v0;
  3657.                 mbi->mb_type = 0;
  3658.                 mbi->motion_type = MC_FIELD;
  3659.                 mbi->MV[0][0][0] = 0;
  3660.                 mbi->MV[0][0][1] = 0;
  3661.                 mbi->mv_field_sel[0][0] = (g_stPictureData.stCodingExtension.nPictStruct==BOTTOM_FIELD);
  3662.             }
  3663.         }
  3664.     }
  3665.     else /* if (pict_type==B_TYPE) */
  3666.     {
  3667.         /* forward prediction */
  3668.         FieldEstimate(oldorg,oldref,oldorg+width,oldref+width,mb,
  3669.                     i,j,sxf,syf,0,
  3670.                     &iminf,&jminf,&imin8uf,&jmin8uf,&imin8lf,&jmin8lf,
  3671.                     &dmcfieldf,&dmc8f,&self,&sel8uf,&sel8lf,&imins,&jmins,&ds);
  3672.  
  3673.         /* backward prediction */
  3674.         FieldEstimate(neworg,newref,neworg+width,newref+width,mb,
  3675.                     i,j,sxb,syb,0,
  3676.                     &iminr,&jminr,&imin8ur,&jmin8ur,&imin8lr,&jmin8lr,
  3677.                     &dmcfieldr,&dmc8r,&selr,&sel8ur,&sel8lr,&imins,&jmins,&ds);
  3678.  
  3679.         /* calculate distances for bidirectional prediction */
  3680.         /* field */
  3681.         dmcfieldi = BDist1(oldref + (self?width:0) + (iminf>>1) + w2*(jminf>>1),
  3682.                         newref + (selr?width:0) + (iminr>>1) + w2*(jminr>>1),
  3683.                         mb,w2,iminf&1,jminf&1,iminr&1,jminr&1,16);
  3684.  
  3685.         /* 16x8 upper half block */
  3686.         dmc8i = BDist1(oldref + (sel8uf?width:0) + (imin8uf>>1) + w2*(jmin8uf>>1),
  3687.                     newref + (sel8ur?width:0) + (imin8ur>>1) + w2*(jmin8ur>>1),
  3688.                     mb,w2,imin8uf&1,jmin8uf&1,imin8ur&1,jmin8ur&1,8);
  3689.  
  3690.         /* 16x8 lower half block */
  3691.         dmc8i+= BDist1(oldref + (sel8lf?width:0) + (imin8lf>>1) + w2*(jmin8lf>>1),
  3692.                     newref + (sel8lr?width:0) + (imin8lr>>1) + w2*(jmin8lr>>1),
  3693.                     mb+8*w2,w2,imin8lf&1,jmin8lf&1,imin8lr&1,jmin8lr&1,8);
  3694.  
  3695.         /* select prediction type of minimum distance */
  3696.         if (dmcfieldi<dmc8i && dmcfieldi<dmcfieldf && dmcfieldi<dmc8f
  3697.             && dmcfieldi<dmcfieldr && dmcfieldi<dmc8r)
  3698.         {
  3699.             /* field, interpolated */
  3700.             mbi->mb_type = MB_FORWARD|MB_BACKWARD;
  3701.             mbi->motion_type = MC_FIELD;
  3702.             vmc = BDist2(oldref + (self?width:0) + (iminf>>1) + w2*(jminf>>1),
  3703.                         newref + (selr?width:0) + (iminr>>1) + w2*(jminr>>1),
  3704.                         mb,w2,iminf&1,jminf&1,iminr&1,jminr&1,16);
  3705.         }
  3706.         else if (dmc8i<dmcfieldf && dmc8i<dmc8f
  3707.                 && dmc8i<dmcfieldr && dmc8i<dmc8r)
  3708.         {
  3709.             /* 16x8, interpolated */
  3710.             mbi->mb_type = MB_FORWARD|MB_BACKWARD;
  3711.             mbi->motion_type = MC_16X8;
  3712.  
  3713.             /* upper half block */
  3714.             vmc = BDist2(oldref + (sel8uf?width:0) + (imin8uf>>1) + w2*(jmin8uf>>1),
  3715.                         newref + (sel8ur?width:0) + (imin8ur>>1) + w2*(jmin8ur>>1),
  3716.                         mb,w2,imin8uf&1,jmin8uf&1,imin8ur&1,jmin8ur&1,8);
  3717.  
  3718.             /* lower half block */
  3719.             vmc+= BDist2(oldref + (sel8lf?width:0) + (imin8lf>>1) + w2*(jmin8lf>>1),
  3720.                         newref + (sel8lr?width:0) + (imin8lr>>1) + w2*(jmin8lr>>1),
  3721.                         mb+8*w2,w2,imin8lf&1,jmin8lf&1,imin8lr&1,jmin8lr&1,8);
  3722.         }
  3723.         else if (dmcfieldf<dmc8f && dmcfieldf<dmcfieldr && dmcfieldf<dmc8r)
  3724.         {
  3725.             /* field, forward */
  3726.             mbi->mb_type = MB_FORWARD;
  3727.             mbi->motion_type = MC_FIELD;
  3728.             vmc = Dist2(oldref + (self?width:0) + (iminf>>1) + w2*(jminf>>1),
  3729.                         mb,w2,iminf&1,jminf&1,16);
  3730.         }
  3731.         else if (dmc8f<dmcfieldr && dmc8f<dmc8r)
  3732.         {
  3733.             /* 16x8, forward */
  3734.             mbi->mb_type = MB_FORWARD;
  3735.             mbi->motion_type = MC_16X8;
  3736.  
  3737.             /* upper half block */
  3738.             vmc = Dist2(oldref + (sel8uf?width:0) + (imin8uf>>1) + w2*(jmin8uf>>1),
  3739.             mb,w2,imin8uf&1,jmin8uf&1,8);
  3740.  
  3741.             /* lower half block */
  3742.             vmc+= Dist2(oldref + (sel8lf?width:0) + (imin8lf>>1) + w2*(jmin8lf>>1),
  3743.                         mb+8*w2,w2,imin8lf&1,jmin8lf&1,8);
  3744.         }
  3745.         else if (dmcfieldr<dmc8r)
  3746.         {
  3747.             /* field, backward */
  3748.             mbi->mb_type = MB_BACKWARD;
  3749.             mbi->motion_type = MC_FIELD;
  3750.             vmc = Dist2(newref + (selr?width:0) + (iminr>>1) + w2*(jminr>>1),
  3751.                         mb,w2,iminr&1,jminr&1,16);
  3752.         }
  3753.         else
  3754.         {
  3755.             /* 16x8, backward */
  3756.             mbi->mb_type = MB_BACKWARD;
  3757.             mbi->motion_type = MC_16X8;
  3758.  
  3759.             /* upper half block */
  3760.             vmc = Dist2(newref + (sel8ur?width:0) + (imin8ur>>1) + w2*(jmin8ur>>1),
  3761.                         mb,w2,imin8ur&1,jmin8ur&1,8);
  3762.  
  3763.             /* lower half block */
  3764.             vmc+= Dist2(newref + (sel8lr?width:0) + (imin8lr>>1) + w2*(jmin8lr>>1),
  3765.                         mb+8*w2,w2,imin8lr&1,jmin8lr&1,8);
  3766.         }
  3767.  
  3768.         /* select between intra and non-intra coding */
  3769.         if (vmc>var && vmc>=9*256)
  3770.             mbi->mb_type = MB_INTRA;
  3771.         else
  3772.         {
  3773.             var = vmc;
  3774.             if (mbi->motion_type==MC_FIELD)
  3775.             {
  3776.                 /* forward */
  3777.                 mbi->MV[0][0][0] = iminf - (i<<1);
  3778.                 mbi->MV[0][0][1] = jminf - (j<<1);
  3779.                 mbi->mv_field_sel[0][0] = self;
  3780.                 /* backward */
  3781.                 mbi->MV[0][1][0] = iminr - (i<<1);
  3782.                 mbi->MV[0][1][1] = jminr - (j<<1);
  3783.                 mbi->mv_field_sel[0][1] = selr;
  3784.             }
  3785.             else /* MC_16X8 */
  3786.             {
  3787.                 /* forward */
  3788.                 mbi->MV[0][0][0] = imin8uf - (i<<1);
  3789.                 mbi->MV[0][0][1] = jmin8uf - (j<<1);
  3790.                 mbi->mv_field_sel[0][0] = sel8uf;
  3791.                 mbi->MV[1][0][0] = imin8lf - (i<<1);
  3792.                 mbi->MV[1][0][1] = jmin8lf - ((j+8)<<1);
  3793.                 mbi->mv_field_sel[1][0] = sel8lf;
  3794.                 /* backward */
  3795.                 mbi->MV[0][1][0] = imin8ur - (i<<1);
  3796.                 mbi->MV[0][1][1] = jmin8ur - (j<<1);
  3797.                 mbi->mv_field_sel[0][1] = sel8ur;
  3798.                 mbi->MV[1][1][0] = imin8lr - (i<<1);
  3799.                 mbi->MV[1][1][1] = jmin8lr - ((j+8)<<1);
  3800.                 mbi->mv_field_sel[1][1] = sel8lr;
  3801.             }
  3802.         }
  3803.     }
  3804.  
  3805.     mbi->var = var;
  3806. }
  3807.  
  3808. /*
  3809.  * frame picture motion estimation
  3810.  *
  3811.  * org: top left pel of source reference frame
  3812.  * ref: top left pel of reconstructed reference frame
  3813.  * mb:  macroblock to be matched
  3814.  * i,j: location of mb relative to ref (=center of search window)
  3815.  * sx,sy: half widths of search window
  3816.  * iminp,jminp,dframep: location and value of best frame prediction
  3817.  * imintp,jmintp,tselp: location of best field pred. for top field of mb
  3818.  * iminbp,jminbp,bselp: location of best field pred. for bottom field of mb
  3819.  * dfieldp: value of field prediction
  3820.  */
  3821. void FrameEstimate(unsigned char *org,
  3822.                             unsigned char *ref, unsigned char *mb,
  3823.                             int i, int j,
  3824.                             int sx, int sy, int *iminp, int *jminp, int *imintp, int *jmintp,
  3825.                             int *iminbp, int *jminbp, int *dframep, int *dfieldp,
  3826.                             int *tselp, int *bselp, int imins[2][2], int jmins[2][2])
  3827. {
  3828.     const int width = g_stSequenceData.stHeader.nWidth;
  3829.     const int height = g_stSequenceData.stHeader.nHeight;
  3830.  
  3831.     int dt,db,dmint,dminb;
  3832.     int imint,iminb,jmint,jminb;
  3833.  
  3834.     /* frame prediction */
  3835.     *dframep = FullSearch(org,ref,mb,width,i,j,sx,sy,16,width,height,
  3836.                         iminp,jminp);
  3837.  
  3838.     /* predict top field from top field */
  3839.     dt = FullSearch(org,ref,mb,width<<1,i,j>>1,sx,sy>>1,8,width,height>>1,
  3840.                     &imint,&jmint);
  3841.  
  3842.     /* predict top field from bottom field */
  3843.     db = FullSearch(org+width,ref+width,mb,width<<1,i,j>>1,sx,sy>>1,8,width,height>>1,
  3844.                     &iminb,&jminb);
  3845.  
  3846.     imins[0][0] = imint;
  3847.     jmins[0][0] = jmint;
  3848.     imins[1][0] = iminb;
  3849.     jmins[1][0] = jminb;
  3850.  
  3851.     /* select prediction for top field */
  3852.     if (dt<=db)
  3853.     {
  3854.         dmint=dt; *imintp=imint; *jmintp=jmint; *tselp=0;
  3855.     }
  3856.     else
  3857.     {
  3858.         dmint=db; *imintp=iminb; *jmintp=jminb; *tselp=1;
  3859.     }
  3860.  
  3861.     /* predict bottom field from top field */
  3862.     dt = FullSearch(org,ref,mb+width,width<<1,i,j>>1,sx,sy>>1,8,width,height>>1,
  3863.                     &imint,&jmint);
  3864.  
  3865.     /* predict bottom field from bottom field */
  3866.     db = FullSearch(org+width,ref+width,mb+width,width<<1,i,j>>1,sx,sy>>1,8,width,height>>1,
  3867.                     &iminb,&jminb);
  3868.  
  3869.     imins[0][1] = imint;
  3870.     jmins[0][1] = jmint;
  3871.     imins[1][1] = iminb;
  3872.     jmins[1][1] = jminb;
  3873.  
  3874.     /* select prediction for bottom field */
  3875.     if (db<=dt)
  3876.     {
  3877.         dminb=db; *iminbp=iminb; *jminbp=jminb; *bselp=1;
  3878.     }
  3879.     else
  3880.     {
  3881.         dminb=dt; *iminbp=imint; *jminbp=jmint; *bselp=0;
  3882.     }
  3883.  
  3884.     *dfieldp=dmint+dminb;
  3885. }
  3886.  
  3887. /*---------------------------------------------------------
  3888.     field picture motion estimation subroutine
  3889.  
  3890.     toporg: address of original top reference field
  3891.     topref: address of reconstructed top reference field
  3892.     botorg: address of original bottom reference field
  3893.     botref: address of reconstructed bottom reference field
  3894.     mb:  macroblock to be matched
  3895.     i,j: location of mb (=center of search window)
  3896.     sx,sy: half width/height of search window
  3897.  
  3898.     iminp,jminp,selp,dfieldp: location and distance of best field prediction
  3899.     imin8up,jmin8up,sel8up: location of best 16x8 pred. for upper half of mb
  3900.     imin8lp,jmin8lp,sel8lp: location of best 16x8 pred. for lower half of mb
  3901.     d8p: distance of best 16x8 prediction
  3902.     iminsp,jminsp,dsp: location and distance of best same parity field
  3903.                        prediction (needed for dual prime, only valid if
  3904.                        ipflag==0)
  3905. ---------------------------------------------------------*/
  3906. void FieldEstimate(unsigned char *toporg,
  3907.                             unsigned char *topref, unsigned char *botorg, unsigned char *botref,
  3908.                             unsigned char *mb, int i, int j, int sx, int sy, bool ipflag,
  3909.                             int *iminp, int *jminp, int *imin8up, int *jmin8up, int *imin8lp,
  3910.                             int *jmin8lp, int *dfieldp, int *d8p, int *selp, int *sel8up, int *sel8lp,
  3911.                             int *iminsp, int *jminsp, int *dsp)
  3912. {
  3913.     const int width = g_stSequenceData.stHeader.nWidth;
  3914.     const int height = g_stSequenceData.stHeader.nHeight;
  3915.  
  3916.     int dt, db, imint, jmint, iminb, jminb;
  3917.     bool notop = false, nobot = false;
  3918.  
  3919.     /* if ipflag is set, predict from field of opposite parity only */
  3920.     if(ipflag && (g_stPictureData.stCodingExtension.nPictStruct==TOP_FIELD))
  3921.     {
  3922.         notop = true;
  3923.     }
  3924.     if(ipflag && (g_stPictureData.stCodingExtension.nPictStruct==BOTTOM_FIELD))
  3925.     {
  3926.         nobot = true;
  3927.     }
  3928.  
  3929.     /* field prediction */
  3930.  
  3931.     /* predict current field from top field */
  3932.     if (notop)
  3933.         dt = 65536; /* infinity */
  3934.     else
  3935.         dt = FullSearch(toporg,topref,mb,width<<1,
  3936.                         i,j,sx,sy>>1,16,width,height>>1,
  3937.                         &imint,&jmint);
  3938.  
  3939.     /* predict current field from bottom field */
  3940.     if (nobot)
  3941.         db = 65536; /* infinity */
  3942.     else
  3943.         db = FullSearch(botorg,botref,mb,width<<1,
  3944.                         i,j,sx,sy>>1,16,width,height>>1,
  3945.                         &iminb,&jminb);
  3946.  
  3947.     /* same parity prediction (only valid if ipflag==0) */
  3948.     if (g_stPictureData.stCodingExtension.nPictStruct==TOP_FIELD)
  3949.     {
  3950.         *iminsp = imint;
  3951.         *jminsp = jmint;
  3952.         *dsp = dt;
  3953.     }
  3954.     else
  3955.     {
  3956.         *iminsp = iminb;
  3957.         *jminsp = jminb;
  3958.         *dsp = db;
  3959.     }
  3960.  
  3961.     /* select field prediction */
  3962.     if (dt<=db)
  3963.     {
  3964.         *dfieldp = dt;
  3965.         *iminp = imint;
  3966.         *jminp = jmint;
  3967.         *selp = 0;
  3968.     }
  3969.     else
  3970.     {
  3971.         *dfieldp = db;
  3972.         *iminp = iminb;
  3973.         *jminp = jminb;
  3974.         *selp = 1;
  3975.     }
  3976.  
  3977.  
  3978.     /* 16x8 motion compensation */
  3979.  
  3980.     /* predict upper half field from top field */
  3981.     if (notop)
  3982.         dt = 65536;
  3983.     else
  3984.         dt = FullSearch(toporg,topref,mb,width<<1,
  3985.                         i,j,sx,sy>>1,8,width,height>>1,
  3986.                         &imint,&jmint);
  3987.  
  3988.     /* predict upper half field from bottom field */
  3989.     if (nobot)
  3990.         db = 65536;
  3991.     else
  3992.         db = FullSearch(botorg,botref,mb,width<<1,
  3993.                         i,j,sx,sy>>1,8,width,height>>1,
  3994.                         &iminb,&jminb);
  3995.  
  3996.     /* select prediction for upper half field */
  3997.     if (dt<=db)
  3998.     {
  3999.         *d8p = dt; *imin8up = imint; *jmin8up = jmint; *sel8up = 0;
  4000.     }
  4001.     else
  4002.     {
  4003.         *d8p = db; *imin8up = iminb; *jmin8up = jminb; *sel8up = 1;
  4004.     }
  4005.  
  4006.     /* predict lower half field from top field */
  4007.     if (notop)
  4008.         dt = 65536;
  4009.     else
  4010.         dt = FullSearch(toporg,topref,mb+(width<<4),width<<1,
  4011.                         i,j+8,sx,sy>>1,8,width,height>>1,
  4012.                         &imint,&jmint);
  4013.  
  4014.     /* predict lower half field from bottom field */
  4015.     if (nobot)
  4016.         db = 65536;
  4017.     else
  4018.         db = FullSearch(botorg,botref,mb+(width<<4),width<<1,
  4019.                         i,j+8,sx,sy>>1,8,width,height>>1,
  4020.                         &iminb,&jminb);
  4021.  
  4022.     /* select prediction for lower half field */
  4023.     if (dt<=db)
  4024.     {
  4025.         *d8p += dt; *imin8lp = imint; *jmin8lp = jmint; *sel8lp = 0;
  4026.     }
  4027.     else
  4028.     {
  4029.         *d8p += db; *imin8lp = iminb; *jmin8lp = jminb; *sel8lp = 1;
  4030.     }
  4031. }
  4032.  
  4033. inline void DPFrameEstimate(unsigned char *ref,
  4034.                     unsigned char *mb, int i, int j, int iminf[2][2], int jminf[2][2],
  4035.                     int *iminp, int *jminp, int *imindmvp, int *jmindmvp,
  4036.                     int *dmcp, int *vmcp)
  4037. {
  4038.     const int width = g_stSequenceData.stHeader.nWidth;
  4039.     const int height = g_stSequenceData.stHeader.nHeight;
  4040.     int pref,ppred,delta_x,delta_y;
  4041.     int is,js,it,jt,ib,jb,it0,jt0,ib0,jb0;
  4042.     int imins,jmins,imint,jmint,iminb,jminb,imindmv,jmindmv;
  4043.     int vmc,local_dist;
  4044.  
  4045.     /* Calculate Dual Prime distortions for 9 delta candidates
  4046.     * for each of the four minimum field vectors
  4047.     * Note: only for P pictures!
  4048.     */
  4049.  
  4050.     /* initialize minimum dual prime distortion to large value */
  4051.     vmc = 1 << 30;
  4052.  
  4053.     for (pref=0; pref<2; pref++)
  4054.     {
  4055.         for (ppred=0; ppred<2; ppred++)
  4056.         {
  4057.             /* convert Cartesian absolute to relative motion vector
  4058.             * values (wrt current macroblock address (i,j)
  4059.             */
  4060.             is = iminf[pref][ppred] - (i<<1);
  4061.             js = jminf[pref][ppred] - (j<<1);
  4062.  
  4063.             if (pref!=ppred)
  4064.             {
  4065.                 /* vertical field shift adjustment */
  4066.                 if (ppred==0)
  4067.                     js++;
  4068.                 else
  4069.                     js--;
  4070.  
  4071.                 /* mvxs and mvys scaling*/
  4072.                 is<<=1;
  4073.                 js<<=1;
  4074.                 if ((g_stPictureData.stCodingExtension.bTopFirst&&ppred==1)
  4075.                     || (!g_stPictureData.stCodingExtension.bTopFirst&&ppred==0))
  4076.                 {
  4077.                     /* second field: scale by 1/3 */
  4078.                     is = (is>=0) ? (is+1)/3 : -((-is+1)/3);
  4079.                     js = (js>=0) ? (js+1)/3 : -((-js+1)/3);
  4080.                 }
  4081.                 else
  4082.                     continue;
  4083.             }
  4084.  
  4085.             /* vector for prediction from field of opposite 'parity' */
  4086.             if (g_stPictureData.stCodingExtension.bTopFirst)
  4087.             {
  4088.                 /* vector for prediction of top field from bottom field */
  4089.                 it0 = ((is+(is>0))>>1);
  4090.                 jt0 = ((js+(js>0))>>1) - 1;
  4091.  
  4092.                 /* vector for prediction of bottom field from top field */
  4093.                 ib0 = ((3*is+(is>0))>>1);
  4094.                 jb0 = ((3*js+(js>0))>>1) + 1;
  4095.             }
  4096.             else
  4097.             {
  4098.                 /* vector for prediction of top field from bottom field */
  4099.                 it0 = ((3*is+(is>0))>>1);
  4100.                 jt0 = ((3*js+(js>0))>>1) - 1;
  4101.  
  4102.                 /* vector for prediction of bottom field from top field */
  4103.                 ib0 = ((is+(is>0))>>1);
  4104.                 jb0 = ((js+(js>0))>>1) + 1;
  4105.             }
  4106.  
  4107.             /* convert back to absolute half-pel field picture coordinates */
  4108.             is += i<<1;
  4109.             js += j<<1;
  4110.             it0 += i<<1;
  4111.             jt0 += j<<1;
  4112.             ib0 += i<<1;
  4113.             jb0 += j<<1;
  4114.  
  4115.             if (is >= 0 && is <= (width-16)<<1 &&
  4116.                 js >= 0 && js <= (height-16))
  4117.             {
  4118.                 for (delta_y=-1; delta_y<=1; delta_y++)
  4119.                 {
  4120.                     for (delta_x=-1; delta_x<=1; delta_x++)
  4121.                     {
  4122.                         /* opposite field coordinates */
  4123.                         it = it0 + delta_x;
  4124.                         jt = jt0 + delta_y;
  4125.                         ib = ib0 + delta_x;
  4126.                         jb = jb0 + delta_y;
  4127.  
  4128.                         if (it >= 0 && it <= (width-16)<<1 &&
  4129.                             jt >= 0 && jt <= (height-16) &&
  4130.                             ib >= 0 && ib <= (width-16)<<1 &&
  4131.                             jb >= 0 && jb <= (height-16))
  4132.                         {
  4133.                             /* compute prediction error */
  4134.                             local_dist = BDist2(
  4135.                                                 ref + (is>>1) + (width<<1)*(js>>1),
  4136.                                                 ref + width + (it>>1) + (width<<1)*(jt>>1),
  4137.                                                 mb,             /* current mb location */
  4138.                                                 width<<1,       /* adjacent line distance */
  4139.                                                 is&1, js&1, it&1, jt&1, /* half-pel flags */
  4140.                                                 8);             /* block height */
  4141.                             local_dist += BDist2(
  4142.                                                 ref + width + (is>>1) + (width<<1)*(js>>1),
  4143.                                                 ref + (ib>>1) + (width<<1)*(jb>>1),
  4144.                                                 mb + width,     /* current mb location */
  4145.                                                 width<<1,       /* adjacent line distance */
  4146.                                                 is&1, js&1, ib&1, jb&1, /* half-pel flags */
  4147.                                                 8);             /* block height */
  4148.  
  4149.                             /* update delta with least distortion vector */
  4150.                             if (local_dist < vmc)
  4151.                             {
  4152.                                 imins = is;
  4153.                                 jmins = js;
  4154.                                 imint = it;
  4155.                                 jmint = jt;
  4156.                                 iminb = ib;
  4157.                                 jminb = jb;
  4158.                                 imindmv = delta_x;
  4159.                                 jmindmv = delta_y;
  4160.                                 vmc = local_dist;
  4161.                             }
  4162.                         }
  4163.                     }  /* end delta x loop */
  4164.                 } /* end delta y loop */
  4165.             }
  4166.         }
  4167.     }
  4168.  
  4169.     /* Compute L1 error for decision purposes */
  4170.     local_dist = BDist1(
  4171.                         ref + (imins>>1) + (width<<1)*(jmins>>1),
  4172.                         ref + width + (imint>>1) + (width<<1)*(jmint>>1),
  4173.                         mb,
  4174.                         width<<1,
  4175.                         imins&1, jmins&1, imint&1, jmint&1,
  4176.                         8);
  4177.     local_dist += BDist1(
  4178.                         ref + width + (imins>>1) + (width<<1)*(jmins>>1),
  4179.                         ref + (iminb>>1) + (width<<1)*(jminb>>1),
  4180.                         mb + width,
  4181.                         width<<1,
  4182.                         imins&1, jmins&1, iminb&1, jminb&1,
  4183.                         8);
  4184.  
  4185.     *dmcp = local_dist;
  4186.     *iminp = imins;
  4187.     *jminp = jmins;
  4188.     *imindmvp = imindmv;
  4189.     *jmindmvp = jmindmv;
  4190.     *vmcp = vmc;
  4191. }
  4192.  
  4193. inline void DPFieldEstimate(unsigned char *topref,
  4194.                             unsigned char *botref, unsigned char *mb,
  4195.                             int i, int j, int imins, int jmins, int *imindmvp, int *jmindmvp,
  4196.                             int *dmcp, int *vmcp)
  4197. {
  4198.     const int width = g_stSequenceData.stHeader.nWidth;
  4199.     const int width2 = g_stSequenceData.stHeader.nWidth2;
  4200.     const int height2 = g_stSequenceData.stHeader.nHeight2;
  4201.     unsigned char *sameref, *oppref;
  4202.     int io0,jo0,io,jo,delta_x,delta_y,mvxs,mvys,mvxo0,mvyo0;
  4203.     int imino,jmino,imindmv,jmindmv,vmc_dp,local_dist;
  4204.  
  4205.     /* Calculate Dual Prime distortions for 9 delta candidates */
  4206.     /* Note: only for P pictures! */
  4207.  
  4208.     /* Assign opposite and same reference pointer */
  4209.     if (g_stPictureData.stCodingExtension.nPictStruct==TOP_FIELD)
  4210.     {
  4211.         sameref = topref;    
  4212.         oppref = botref;
  4213.     }
  4214.     else 
  4215.     {
  4216.         sameref = botref;
  4217.         oppref = topref;
  4218.     }
  4219.  
  4220.     /* convert Cartesian absolute to relative motion vector
  4221.     * values (wrt current macroblock address (i,j)
  4222.     */
  4223.     mvxs = imins - (i<<1);
  4224.     mvys = jmins - (j<<1);
  4225.  
  4226.     /* vector for prediction from field of opposite 'parity' */
  4227.     mvxo0 = (mvxs+(mvxs>0)) >> 1;  /* mvxs // 2 */
  4228.     mvyo0 = (mvys+(mvys>0)) >> 1;  /* mvys // 2 */
  4229.  
  4230.     /* vertical field shift correction */
  4231.     if (g_stPictureData.stCodingExtension.nPictStruct==TOP_FIELD)
  4232.         mvyo0--;
  4233.     else
  4234.         mvyo0++;
  4235.  
  4236.     /* convert back to absolute coordinates */
  4237.     io0 = mvxo0 + (i<<1);
  4238.     jo0 = mvyo0 + (j<<1);
  4239.  
  4240.     /* initialize minimum dual prime distortion to large value */
  4241.     vmc_dp = 1 << 30;
  4242.  
  4243.     for (delta_y = -1; delta_y <= 1; delta_y++)
  4244.     {
  4245.         for (delta_x = -1; delta_x <=1; delta_x++)
  4246.         {
  4247.             /* opposite field coordinates */
  4248.             io = io0 + delta_x;
  4249.             jo = jo0 + delta_y;
  4250.  
  4251.             if (io >= 0 && io <= (width-16)<<1 &&
  4252.                 jo >= 0 && jo <= (height2-16)<<1)
  4253.             {
  4254.                 /* compute prediction error */
  4255.                 local_dist = BDist2(
  4256.                                     sameref + (imins>>1) + width2*(jmins>>1),
  4257.                                     oppref  + (io>>1)    + width2*(jo>>1),
  4258.                                     mb,             /* current mb location */
  4259.                                     width2,         /* adjacent line distance */
  4260.                                     imins&1, jmins&1, io&1, jo&1, /* half-pel flags */
  4261.                                     16);            /* block height */
  4262.  
  4263.                 /* update delta with least distortion vector */
  4264.                 if (local_dist < vmc_dp)
  4265.                 {
  4266.                     imino = io;
  4267.                     jmino = jo;
  4268.                     imindmv = delta_x;
  4269.                     jmindmv = delta_y;
  4270.                     vmc_dp = local_dist;
  4271.                 }
  4272.             }
  4273.         }  /* end delta x loop */
  4274.     } /* end delta y loop */
  4275.  
  4276.     /* Compute L1 error for decision purposes */
  4277.     *dmcp = BDist1(
  4278.                     sameref + (imins>>1) + width2*(jmins>>1),
  4279.                     oppref  + (imino>>1) + width2*(jmino>>1),
  4280.                     mb,             /* current mb location */
  4281.                     width2,         /* adjacent line distance */
  4282.                     imins&1, jmins&1, imino&1, jmino&1, /* half-pel flags */
  4283.                     16);            /* block height */
  4284.  
  4285.     *imindmvp = imindmv;
  4286.     *jmindmvp = jmindmv;
  4287.     *vmcp = vmc_dp;
  4288. }
  4289. /*---------------------------------------------------------
  4290.     full search block matching
  4291.  
  4292.     blk: top left pel of (16*h) block
  4293.     h: height of block
  4294.     lx: distance (in bytes) of vertically adjacent pels in ref,blk
  4295.     org: top left pel of source reference picture
  4296.     ref: top left pel of reconstructed reference picture
  4297.     i0,j0: center of search window
  4298.     sx,sy: half widths of search window
  4299.     xmax,ymax: right/bottom limits of search area
  4300.     iminp,jminp: pointers to where the result is stored
  4301.                  result is given as half pel offset from ref(0,0)
  4302.                  i.e. NOT relative to (i0,j0)
  4303. ---------------------------------------------------------*/
  4304. int FullSearch(unsigned char *org, unsigned char *ref,
  4305.                         unsigned char *blk,
  4306.                         int lx, int i0, int j0, int sx, int sy, int h, int xmax, int ymax,
  4307.                         int *iminp, int *jminp)
  4308. {
  4309.     int i,j,imin,jmin,ilow,ihigh,jlow,jhigh;
  4310.     int d,dmin;
  4311.     int k,l,sxy;
  4312.  
  4313.     ilow = i0 - sx;
  4314.     ihigh = i0 + sx;
  4315.  
  4316.     if (ilow<0)
  4317.         ilow = 0;
  4318.  
  4319.     if (ihigh>xmax-16)
  4320.         ihigh = xmax-16;
  4321.  
  4322.     jlow = j0 - sy;
  4323.     jhigh = j0 + sy;
  4324.  
  4325.     if (jlow<0)
  4326.         jlow = 0;
  4327.  
  4328.     if (jhigh>ymax-h)
  4329.         jhigh = ymax-h;
  4330.  
  4331.     /* full pel search, spiraling outwards */
  4332.  
  4333.     imin = i0;
  4334.     jmin = j0;
  4335.     dmin = Dist1(org+imin+lx*jmin,blk,lx,0,0,h,65536);
  4336.  
  4337.     sxy = (sx>sy) ? sx : sy;
  4338.  
  4339.     for (l=1; l<=sxy; l++)
  4340.     {
  4341.         i = i0 - l;
  4342.         j = j0 - l;
  4343.         for (k=0; k<8*l; k++)
  4344.         {
  4345.             if (i>=ilow && i<=ihigh && j>=jlow && j<=jhigh)
  4346.             {
  4347.                 d = Dist1(org+i+lx*j,blk,lx,0,0,h,dmin);
  4348.  
  4349.                 if (d<dmin)
  4350.                 {
  4351.                     dmin = d;
  4352.                     imin = i;
  4353.                     jmin = j;
  4354.                 }
  4355.             }
  4356.  
  4357.             if      (k<2*l) i++;
  4358.             else if (k<4*l) j++;
  4359.             else if (k<6*l) i--;
  4360.             else            j--;
  4361.         }
  4362.     }
  4363.  
  4364.     /* half pel */
  4365.     dmin = 65536;
  4366.     imin <<= 1;
  4367.     jmin <<= 1;
  4368.     ilow = imin - (imin>0);
  4369.     ihigh = imin + (imin<((xmax-16)<<1));
  4370.     jlow = jmin - (jmin>0);
  4371.     jhigh = jmin + (jmin<((ymax-h)<<1));
  4372.  
  4373.     for (j=jlow; j<=jhigh; j++)
  4374.         for (i=ilow; i<=ihigh; i++)
  4375.         {
  4376.             d = Dist1(ref+(i>>1)+lx*(j>>1),blk,lx,i&1,j&1,h,dmin);
  4377.  
  4378.             if (d<dmin)
  4379.             {
  4380.                 dmin = d;
  4381.                 imin = i;
  4382.                 jmin = j;
  4383.             }
  4384.         }
  4385.  
  4386.     *iminp = imin;
  4387.     *jminp = jmin;
  4388.  
  4389.     return dmin;
  4390. }
  4391. /*---------------------------------------------------------
  4392.     total absolute difference between two (16*h) blocks
  4393.     including optional half pel interpolation of blk1 (hx,hy)
  4394.     blk1,blk2: addresses of top left pels of both blocks
  4395.     lx:        distance (in bytes) of vertically adjacent pels
  4396.     hx,hy:     flags for horizontal and/or vertical interpolation
  4397.     h:         height of block (usually 8 or 16)
  4398.     distlim:   bail out if sum exceeds this value
  4399. ---------------------------------------------------------*/
  4400. int Dist1(unsigned char *blk1, unsigned char *blk2,
  4401.                 int lx, int hx, int hy, int h, int distlim)
  4402. {
  4403.     unsigned char *p1,*p1a,*p2;
  4404.     int i,j;
  4405.     int s,v;
  4406.  
  4407.     if(g_nFastMotionCompensationLevel)
  4408.     {
  4409.         lx <<= g_nFastMotionCompensationLevel;
  4410.         h >>= g_nFastMotionCompensationLevel;
  4411.     }
  4412.  
  4413.     if (!hx && !hy)
  4414.     {
  4415.  
  4416.         s = 0;
  4417.         p1 = blk1;
  4418.         p2 = blk2;
  4419.  
  4420.         for (j=0; j<h; j++)
  4421.         {
  4422.             if ((v = p1[0]  - p2[0])<0)  v = -v; s+= v;
  4423.             if ((v = p1[1]  - p2[1])<0)  v = -v; s+= v;
  4424.             if ((v = p1[2]  - p2[2])<0)  v = -v; s+= v;
  4425.             if ((v = p1[3]  - p2[3])<0)  v = -v; s+= v;
  4426.             if ((v = p1[4]  - p2[4])<0)  v = -v; s+= v;
  4427.             if ((v = p1[5]  - p2[5])<0)  v = -v; s+= v;
  4428.             if ((v = p1[6]  - p2[6])<0)  v = -v; s+= v;
  4429.             if ((v = p1[7]  - p2[7])<0)  v = -v; s+= v;
  4430.             if ((v = p1[8]  - p2[8])<0)  v = -v; s+= v;
  4431.             if ((v = p1[9]  - p2[9])<0)  v = -v; s+= v;
  4432.             if ((v = p1[10] - p2[10])<0) v = -v; s+= v;
  4433.             if ((v = p1[11] - p2[11])<0) v = -v; s+= v;
  4434.             if ((v = p1[12] - p2[12])<0) v = -v; s+= v;
  4435.             if ((v = p1[13] - p2[13])<0) v = -v; s+= v;
  4436.             if ((v = p1[14] - p2[14])<0) v = -v; s+= v;
  4437.             if ((v = p1[15] - p2[15])<0) v = -v; s+= v;
  4438.  
  4439.             if (s >= distlim)
  4440.                 break;
  4441.  
  4442.             p1+= lx;
  4443.             p2+= lx;
  4444.         }
  4445.     }
  4446.     else if (hx && !hy)
  4447.     {
  4448.         s = 0;
  4449.         p1 = blk1;
  4450.         p2 = blk2;
  4451.  
  4452.         for (j=0; j<h; j++)
  4453.         {
  4454.             for (i=0; i<16; i++)
  4455.             {
  4456.                 v = ((unsigned int)(p1[i]+p1[i+1]+1)>>1) - p2[i];
  4457.  
  4458.                 if (v>=0)
  4459.                     s+= v;
  4460.                 else
  4461.                     s-= v;
  4462.             }
  4463.             p1+= lx;
  4464.             p2+= lx;
  4465.         }
  4466.     }
  4467.     else if (!hx && hy)
  4468.     {
  4469.         s = 0;
  4470.         p1 = blk1;
  4471.         p2 = blk2;
  4472.         p1a = p1 + lx;
  4473.         for (j=0; j<h; j++)
  4474.         {
  4475.             for (i=0; i<16; i++)
  4476.             {
  4477.                 v = ((unsigned int)(p1[i]+p1a[i]+1)>>1) - p2[i];
  4478.  
  4479.                 if (v>=0)
  4480.                     s+= v;
  4481.                 else
  4482.                     s-= v;
  4483.             }
  4484.             p1 = p1a;
  4485.             p1a+= lx;
  4486.             p2+= lx;
  4487.         }
  4488.     }
  4489.     else // if (hx && hy)
  4490.     {
  4491.         s = 0;
  4492.         p1 = blk1;
  4493.         p2 = blk2;
  4494.         p1a = p1 + lx;
  4495.         for (j=0; j<h; j++)
  4496.         {
  4497.             for (i=0; i<16; i++)
  4498.             {
  4499.                 v = ((unsigned int)(p1[i]+p1[i+1]+p1a[i]+p1a[i+1]+2)>>2) - p2[i];
  4500.  
  4501.                 if (v>=0)
  4502.                     s+= v;
  4503.                 else
  4504.                     s-= v;
  4505.             }
  4506.             p1 = p1a;
  4507.             p1a+= lx;
  4508.             p2+= lx;
  4509.         }
  4510.     }
  4511.  
  4512.     return s;
  4513. }
  4514. /*---------------------------------------------------------
  4515.     total squared difference between two (16*h) blocks
  4516.     including optional half pel interpolation of blk1 (hx,hy)
  4517.     blk1,blk2: addresses of top left pels of both blocks
  4518.     lx:        distance (in bytes) of vertically adjacent pels
  4519.     hx,hy:     flags for horizontal and/or vertical interpolation
  4520.     h:         height of block (usually 8 or 16)
  4521. ---------------------------------------------------------*/
  4522. int Dist2(unsigned char *blk1, unsigned char *blk2,
  4523.                     int lx, int hx, int hy, int h)
  4524. {
  4525.     unsigned char *p1,*p1a,*p2;
  4526.     int i,j;
  4527.     int s,v;
  4528.  
  4529.     if(g_nFastMotionCompensationLevel)
  4530.     {
  4531.         lx <<= g_nFastMotionCompensationLevel;
  4532.         h >>= g_nFastMotionCompensationLevel;
  4533.     }
  4534.  
  4535.     if (!hx && !hy)
  4536.     {
  4537.         s = 0;
  4538.         p1 = blk1;
  4539.         p2 = blk2;
  4540.         for (j=0; j<h; j++)
  4541.         {
  4542.             for (i=0; i<16; i++)
  4543.             {
  4544.                 v = p1[i] - p2[i];
  4545.                 s+= v*v;
  4546.             }
  4547.             p1+= lx;
  4548.             p2+= lx;
  4549.         }
  4550.     }
  4551.     else if (hx && !hy)
  4552.     {
  4553.         s = 0;
  4554.         p1 = blk1;
  4555.         p2 = blk2;
  4556.         for (j=0; j<h; j++)
  4557.         {
  4558.             for (i=0; i<16; i++)
  4559.             {
  4560.                 v = ((unsigned int)(p1[i]+p1[i+1]+1)>>1) - p2[i];
  4561.                 s+= v*v;
  4562.             }
  4563.             p1+= lx;
  4564.             p2+= lx;
  4565.         }
  4566.     }
  4567.     else if (!hx && hy)
  4568.     {
  4569.         s = 0;
  4570.         p1 = blk1;
  4571.         p2 = blk2;
  4572.         p1a = p1 + lx;
  4573.         for (j=0; j<h; j++)
  4574.         {
  4575.             for (i=0; i<16; i++)
  4576.             {
  4577.                 v = ((unsigned int)(p1[i]+p1a[i]+1)>>1) - p2[i];
  4578.                 s+= v*v;
  4579.             }
  4580.             p1 = p1a;
  4581.             p1a+= lx;
  4582.             p2+= lx;
  4583.         }
  4584.     }
  4585.     else // if (hx && hy)
  4586.     {
  4587.         s = 0;
  4588.         p1 = blk1;
  4589.         p2 = blk2;
  4590.         p1a = p1 + lx;
  4591.         for (j=0; j<h; j++)
  4592.         {
  4593.             for (i=0; i<16; i++)
  4594.             {
  4595.                 v = ((unsigned int)(p1[i]+p1[i+1]+p1a[i]+p1a[i+1]+2)>>2) - p2[i];
  4596.                 s+= v*v;
  4597.             }
  4598.             p1 = p1a;
  4599.             p1a+= lx;
  4600.             p2+= lx;
  4601.         }
  4602.     }
  4603.  
  4604.     return s;
  4605. }
  4606.  
  4607.  
  4608. /*---------------------------------------------------------
  4609.     absolute difference error between a (16*h) block and a bidirectional
  4610.     prediction
  4611.  
  4612.     p2: address of top left pel of block
  4613.     pf,hxf,hyf: address and half pel flags of forward ref. block
  4614.     pb,hxb,hyb: address and half pel flags of backward ref. block
  4615.     h: height of block
  4616.     lx: distance (in bytes) of vertically adjacent pels in p2,pf,pb
  4617. ---------------------------------------------------------*/
  4618. int BDist1(unsigned char *pf, unsigned char *pb,
  4619.                 unsigned char *p2, int lx, int hxf, int hyf, int hxb, int hyb, int h)
  4620. {
  4621.     unsigned char *pfa,*pfb,*pfc,*pba,*pbb,*pbc;
  4622.     int i,j;
  4623.     int s,v;
  4624.  
  4625.     if(g_nFastMotionCompensationLevel)
  4626.     {
  4627.         lx <<= g_nFastMotionCompensationLevel;
  4628.         h >>= g_nFastMotionCompensationLevel;
  4629.     }
  4630.  
  4631.     pfa = pf + hxf;
  4632.     pfb = pf + lx*hyf;
  4633.     pfc = pfb + hxf;
  4634.  
  4635.     pba = pb + hxb;
  4636.     pbb = pb + lx*hyb;
  4637.     pbc = pbb + hxb;
  4638.  
  4639.     s = 0;
  4640.     for (j=0; j<h; j++)
  4641.     {
  4642.         for (i=0; i<16; i++)
  4643.         {
  4644.             v = ((((unsigned int)(*pf++ + *pfa++ + *pfb++ + *pfc++ + 2)>>2) +
  4645.                 ((unsigned int)(*pb++ + *pba++ + *pbb++ + *pbc++ + 2)>>2) + 1)>>1)
  4646.                 - *p2++;
  4647.  
  4648.             if (v>=0)
  4649.                 s+= v;
  4650.             else
  4651.                 s-= v;
  4652.         }
  4653.  
  4654.         p2+= lx-16;
  4655.         pf+= lx-16;
  4656.         pfa+= lx-16;
  4657.         pfb+= lx-16;
  4658.         pfc+= lx-16;
  4659.         pb+= lx-16;
  4660.         pba+= lx-16;
  4661.         pbb+= lx-16;
  4662.         pbc+= lx-16;
  4663.     }
  4664.     return s;
  4665. }
  4666.  
  4667. /*---------------------------------------------------------
  4668.     squared error between a (16*h) block and a bidirectional
  4669.     prediction
  4670.  
  4671.     p2: address of top left pel of block
  4672.     pf,hxf,hyf: address and half pel flags of forward ref. block
  4673.     pb,hxb,hyb: address and half pel flags of backward ref. block
  4674.     h: height of block
  4675.     lx: distance (in bytes) of vertically adjacent pels in p2,pf,pb
  4676. ---------------------------------------------------------*/
  4677. int BDist2(unsigned char *pf, unsigned char *pb,
  4678.                     unsigned char *p2, int lx, int hxf, int hyf, int hxb, int hyb, int h)
  4679. {
  4680.     unsigned char *pfa,*pfb,*pfc,*pba,*pbb,*pbc;
  4681.     int i,j;
  4682.     int s,v;
  4683.  
  4684.     if(g_nFastMotionCompensationLevel)
  4685.     {
  4686.         lx <<= g_nFastMotionCompensationLevel;
  4687.         h >>= g_nFastMotionCompensationLevel;
  4688.     }
  4689.  
  4690.     pfa = pf + hxf;
  4691.     pfb = pf + lx*hyf;
  4692.     pfc = pfb + hxf;
  4693.  
  4694.     pba = pb + hxb;
  4695.     pbb = pb + lx*hyb;
  4696.     pbc = pbb + hxb;
  4697.  
  4698.     s = 0;
  4699.     for (j=0; j<h; j++)
  4700.     {
  4701.         for (i=0; i<16; i++)
  4702.         {
  4703.             v = ((((unsigned int)(*pf++ + *pfa++ + *pfb++ + *pfc++ + 2)>>2) +
  4704.                 ((unsigned int)(*pb++ + *pba++ + *pbb++ + *pbc++ + 2)>>2) + 1)>>1)
  4705.                 - *p2++;
  4706.  
  4707.             s+=v*v;
  4708.         }
  4709.         p2+= lx-16;
  4710.         pf+= lx-16;
  4711.         pfa+= lx-16;
  4712.         pfb+= lx-16;
  4713.         pfc+= lx-16;
  4714.         pb+= lx-16;
  4715.         pba+= lx-16;
  4716.         pbb+= lx-16;
  4717.         pbc+= lx-16;
  4718.     }
  4719.  
  4720.     return s;
  4721. }
  4722.  
  4723. /*---------------------------------------------------------
  4724.     variance of a (16*16) block, multiplied by 256
  4725.     p:  address of top left pel of block
  4726.     lx: distance (in bytes) of vertically adjacent pels
  4727. ---------------------------------------------------------*/
  4728. int Variance(unsigned char *p,int lx)
  4729. {
  4730.     unsigned int i,j;
  4731.     unsigned int v,s,s2;
  4732.  
  4733.     s = s2 = 0;
  4734.     for (j=0; j<16; j++)
  4735.     {
  4736.         for (i=0; i<16; i++)
  4737.         {
  4738.             v = *p++;
  4739.             s+= v;
  4740.             s2+= v*v;
  4741.         }
  4742.         p+= lx-16;
  4743.     }
  4744.  
  4745.     return s2 - (s*s)/256;
  4746. }
  4747.  
  4748. static int calcDist16(unsigned char *p1In, unsigned char *p2In)
  4749. {
  4750. /*
  4751.  * Returns the sum of the absolute differences between bytes
  4752.  * in two 16 bytes arrays.
  4753.  *
  4754.  */
  4755.     unsigned char *p1,*p2;
  4756.     int v;
  4757.     int s = 0;
  4758.  
  4759.   /*
  4760.    * Need local variables p1, p2 because function may be called with
  4761.    * variables in registers
  4762.    *
  4763.    */
  4764.  
  4765.     p1 = p1In;
  4766.     p2 = p2In;
  4767.  
  4768.  
  4769.     if ((v = p1[0]  - p2[0])<0)  v = -v; s+= v;
  4770.     if ((v = p1[1]  - p2[1])<0)  v = -v; s+= v;
  4771.     if ((v = p1[2]  - p2[2])<0)  v = -v; s+= v;
  4772.     if ((v = p1[3]  - p2[3])<0)  v = -v; s+= v;
  4773.     if ((v = p1[4]  - p2[4])<0)  v = -v; s+= v;
  4774.     if ((v = p1[5]  - p2[5])<0)  v = -v; s+= v;
  4775.     if ((v = p1[6]  - p2[6])<0)  v = -v; s+= v;
  4776.     if ((v = p1[7]  - p2[7])<0)  v = -v; s+= v;
  4777.     if ((v = p1[8]  - p2[8])<0)  v = -v; s+= v;
  4778.     if ((v = p1[9]  - p2[9])<0)  v = -v; s+= v;
  4779.     if ((v = p1[10] - p2[10])<0) v = -v; s+= v;
  4780.     if ((v = p1[11] - p2[11])<0) v = -v; s+= v;
  4781.     if ((v = p1[12] - p2[12])<0) v = -v; s+= v;
  4782.     if ((v = p1[13] - p2[13])<0) v = -v; s+= v;
  4783.     if ((v = p1[14] - p2[14])<0) v = -v; s+= v;
  4784.     if ((v = p1[15] - p2[15])<0) v = -v; s+= v;
  4785.  
  4786.     return s;
  4787. }
  4788. /*=========================================================
  4789.     predict
  4790. =========================================================*/
  4791. /*---------------------------------------------------------
  4792.     form prediction for a complete picture (frontend for predict_mb)
  4793.  
  4794.     reff: reference frame for forward prediction
  4795.     refb: reference frame for backward prediction
  4796.     cur:  destination (current) frame
  4797.     secondfield: predict second field of a frame
  4798.     mbi:  macroblock info
  4799. ---------------------------------------------------------*/
  4800. void Predict(unsigned char* reff[],unsigned char* refb[],unsigned char* cur[],
  4801.                     int secondfield,MACROBLOCKINFO* mbi)
  4802. {
  4803.     int i, j, k;
  4804.  
  4805.     k = 0;
  4806.  
  4807.     /* loop through all macroblocks of the picture */
  4808.     for (j=0; j<g_stSequenceData.stHeader.nHeight2; j+=16)
  4809.     {
  4810.         for (i=0; i<g_stSequenceData.stHeader.nWidth; i+=16)
  4811.         {
  4812.             PredictMB(reff,refb,cur,g_stSequenceData.stHeader.nWidth,i,j,
  4813.                         g_stPictureData.stHeader.nPictType,
  4814.                         g_stPictureData.stCodingExtension.nPictStruct,
  4815.                         mbi[k].mb_type,mbi[k].motion_type,secondfield,
  4816.                         mbi[k].MV,mbi[k].mv_field_sel,mbi[k].dmvector);
  4817.  
  4818.             k++;
  4819.         }
  4820.     }
  4821. }
  4822.  
  4823. /*---------------------------------------------------------
  4824.     form prediction for one macroblock
  4825.  
  4826.     oldref: reference frame for forward prediction
  4827.     newref: reference frame for backward prediction
  4828.     cur:    destination (current) frame
  4829.     lx:     frame width (identical to global var `width')
  4830.     bx,by:  picture (field or frame) coordinates of macroblock to be predicted
  4831.     pict_type: I, P or B
  4832.     pict_struct: FRAME_PICTURE, TOP_FIELD, BOTTOM_FIELD
  4833.     mb_type:     MB_FORWARD, MB_BACKWARD, MB_INTRA
  4834.     motion_type: MC_FRAME, MC_FIELD, MC_16X8, MC_DMV
  4835.     secondfield: predict second field of a frame
  4836.     PMV[2][2][2]: motion vectors (in half pel picture coordinates)
  4837.     mv_field_sel[2][2]: motion vertical field selects (for field predictions)
  4838.     dmvector: differential motion vectors (for dual prime)
  4839.  
  4840.     Notes:
  4841.     - when predicting a P type picture which is the second field of
  4842.       a frame, the same parity reference field is in oldref, while the
  4843.       opposite parity reference field is assumed to be in newref!
  4844.     - intra macroblocks are modelled to have a constant prediction of 128
  4845.       for all pels; this results in a DC DCT coefficient symmetric to 0
  4846.     - vectors for field prediction in frame pictures are in half pel frame
  4847.       coordinates (vertical component is twice the field value and always
  4848.       even)
  4849.     
  4850.     already covers dual prime (not yet used)
  4851. ---------------------------------------------------------*/
  4852. inline void PredictMB(unsigned char *oldref[], unsigned char *newref[], unsigned char *cur[],
  4853.                         int lx, int bx, int by, int pict_type, int pict_struct, int mb_type,
  4854.                         int motion_type, int secondfield,
  4855.                         int PMV[][2][2], int mv_field_sel[][2], int dmvector[])
  4856. {
  4857.     int addflag, currentfield;
  4858.     unsigned char **predframe;
  4859.     int DMV[2][2];
  4860.  
  4861.     if (mb_type&MB_INTRA)
  4862.     {
  4863.         ClearBlock(cur,bx,by);
  4864.         return;
  4865.     }
  4866.  
  4867.     addflag = 0; /* first prediction is stored, second is added and averaged */
  4868.  
  4869.     if ((mb_type & MB_FORWARD) || (pict_type==P_TYPE))
  4870.     {
  4871.         /* forward prediction, including zero MV in P pictures */
  4872.  
  4873.         if (pict_struct==FRAME_PICTURE)
  4874.         {
  4875.         /* frame picture */
  4876.  
  4877.             if ((motion_type==MC_FRAME) || !(mb_type & MB_FORWARD))
  4878.             {
  4879.                 /* frame-based prediction in frame picture */
  4880.                 Pred(oldref,0,cur,0,
  4881.                     lx,16,16,bx,by,PMV[0][0][0],PMV[0][0][1],0);
  4882.             }
  4883.             else if (motion_type==MC_FIELD)
  4884.             {
  4885.                 /* field-based prediction in frame picture
  4886.                 *
  4887.                 * note scaling of the vertical coordinates (by, PMV[][0][1])
  4888.                 * from frame to field!
  4889.                 */
  4890.  
  4891.                 /* top field prediction */
  4892.                 Pred(oldref,mv_field_sel[0][0],cur,0,
  4893.                     lx<<1,16,8,bx,by>>1,PMV[0][0][0],PMV[0][0][1]>>1,0);
  4894.  
  4895.                 /* bottom field prediction */
  4896.                 Pred(oldref,mv_field_sel[1][0],cur,1,
  4897.                     lx<<1,16,8,bx,by>>1,PMV[1][0][0],PMV[1][0][1]>>1,0);
  4898.             }
  4899.             else if (motion_type==MC_DMV)
  4900.             {
  4901.                 /* dual prime prediction */
  4902.  
  4903.                 /* calculate derived motion vectors */
  4904.                 CalDMV(DMV,dmvector,PMV[0][0][0],PMV[0][0][1]>>1);
  4905.  
  4906.                 /* predict top field from top field */
  4907.                 Pred(oldref,0,cur,0,
  4908.                     lx<<1,16,8,bx,by>>1,PMV[0][0][0],PMV[0][0][1]>>1,0);
  4909.  
  4910.                 /* predict bottom field from bottom field */
  4911.                 Pred(oldref,1,cur,1,
  4912.                     lx<<1,16,8,bx,by>>1,PMV[0][0][0],PMV[0][0][1]>>1,0);
  4913.  
  4914.                 /* predict and add to top field from bottom field */
  4915.                 Pred(oldref,1,cur,0,
  4916.                     lx<<1,16,8,bx,by>>1,DMV[0][0],DMV[0][1],1);
  4917.  
  4918.                 /* predict and add to bottom field from top field */
  4919.                 Pred(oldref,0,cur,1,
  4920.                     lx<<1,16,8,bx,by>>1,DMV[1][0],DMV[1][1],1);
  4921.             }
  4922.             else
  4923.             {
  4924.                 /* invalid motion_type in frame picture */
  4925.             }
  4926.         }
  4927.         else /* TOP_FIELD or BOTTOM_FIELD */
  4928.         {
  4929.             /* field picture */
  4930.  
  4931.             currentfield = (pict_struct==BOTTOM_FIELD);
  4932.  
  4933.             /* determine which frame to use for prediction */
  4934.             if ((pict_type==P_TYPE) && secondfield
  4935.                 && (currentfield!=mv_field_sel[0][0]))
  4936.                 predframe = newref; /* same frame */
  4937.             else
  4938.                 predframe = oldref; /* previous frame */
  4939.  
  4940.             if ((motion_type==MC_FIELD) || !(mb_type & MB_FORWARD))
  4941.             {
  4942.                 /* field-based prediction in field picture */
  4943.                 Pred(predframe,mv_field_sel[0][0],cur,currentfield,
  4944.                     lx<<1,16,16,bx,by,PMV[0][0][0],PMV[0][0][1],0);
  4945.             }
  4946.             else if (motion_type==MC_16X8)
  4947.             {
  4948.                 /* 16 x 8 motion compensation in field picture */
  4949.  
  4950.                 /* upper half */
  4951.                 Pred(predframe,mv_field_sel[0][0],cur,currentfield,
  4952.                     lx<<1,16,8,bx,by,PMV[0][0][0],PMV[0][0][1],0);
  4953.  
  4954.                 /* determine which frame to use for lower half prediction */
  4955.                 if ((pict_type==P_TYPE) && secondfield
  4956.                     && (currentfield!=mv_field_sel[1][0]))
  4957.                     predframe = newref; /* same frame */
  4958.                 else
  4959.                     predframe = oldref; /* previous frame */
  4960.  
  4961.                 /* lower half */
  4962.                 Pred(predframe,mv_field_sel[1][0],cur,currentfield,
  4963.                     lx<<1,16,8,bx,by+8,PMV[1][0][0],PMV[1][0][1],0);
  4964.             }
  4965.             else if (motion_type==MC_DMV)
  4966.             {
  4967.                 /* dual prime prediction */
  4968.  
  4969.                 /* determine which frame to use for prediction */
  4970.                 if (secondfield)
  4971.                     predframe = newref; /* same frame */
  4972.                 else
  4973.                     predframe = oldref; /* previous frame */
  4974.  
  4975.                 /* calculate derived motion vectors */
  4976.                 CalDMV(DMV,dmvector,PMV[0][0][0],PMV[0][0][1]);
  4977.  
  4978.                 /* predict from field of same parity */
  4979.                 Pred(oldref,currentfield,cur,currentfield,
  4980.                     lx<<1,16,16,bx,by,PMV[0][0][0],PMV[0][0][1],0);
  4981.  
  4982.                 /* predict from field of opposite parity */
  4983.                 Pred(predframe,!currentfield,cur,currentfield,
  4984.                     lx<<1,16,16,bx,by,DMV[0][0],DMV[0][1],1);
  4985.             }
  4986.             else
  4987.             {
  4988.                 /* invalid motion_type in field picture */
  4989.             }
  4990.         }
  4991.         addflag = 1; /* next prediction (if any) will be averaged with this one */
  4992.     }
  4993.  
  4994.     if (mb_type & MB_BACKWARD)
  4995.     {
  4996.         /* backward prediction */
  4997.  
  4998.         if (pict_struct==FRAME_PICTURE)
  4999.         {
  5000.         /* frame picture */
  5001.  
  5002.             if (motion_type==MC_FRAME)
  5003.             {
  5004.                 /* frame-based prediction in frame picture */
  5005.                 Pred(newref,0,cur,0,
  5006.                     lx,16,16,bx,by,PMV[0][1][0],PMV[0][1][1],addflag);
  5007.             }
  5008.             else
  5009.             {
  5010.                 /* field-based prediction in frame picture
  5011.                 *
  5012.                 * note scaling of the vertical coordinates (by, PMV[][1][1])
  5013.                 * from frame to field!
  5014.                 */
  5015.  
  5016.                 /* top field prediction */
  5017.                 Pred(newref,mv_field_sel[0][1],cur,0,
  5018.                     lx<<1,16,8,bx,by>>1,PMV[0][1][0],PMV[0][1][1]>>1,addflag);
  5019.  
  5020.                 /* bottom field prediction */
  5021.                 Pred(newref,mv_field_sel[1][1],cur,1,
  5022.                     lx<<1,16,8,bx,by>>1,PMV[1][1][0],PMV[1][1][1]>>1,addflag);
  5023.             }
  5024.         }
  5025.         else /* TOP_FIELD or BOTTOM_FIELD */
  5026.         {
  5027.             /* field picture */
  5028.  
  5029.             currentfield = (pict_struct==BOTTOM_FIELD);
  5030.  
  5031.             if (motion_type==MC_FIELD)
  5032.             {
  5033.                 /* field-based prediction in field picture */
  5034.                 Pred(newref,mv_field_sel[0][1],cur,currentfield,
  5035.                     lx<<1,16,16,bx,by,PMV[0][1][0],PMV[0][1][1],addflag);
  5036.             }
  5037.             else if (motion_type==MC_16X8)
  5038.             {
  5039.                 /* 16 x 8 motion compensation in field picture */
  5040.  
  5041.                 /* upper half */
  5042.                 Pred(newref,mv_field_sel[0][1],cur,currentfield,
  5043.                     lx<<1,16,8,bx,by,PMV[0][1][0],PMV[0][1][1],addflag);
  5044.  
  5045.                 /* lower half */
  5046.                 Pred(newref,mv_field_sel[1][1],cur,currentfield,
  5047.                     lx<<1,16,8,bx,by+8,PMV[1][1][0],PMV[1][1][1],addflag);
  5048.             }
  5049.             else
  5050.             {
  5051.                 /* invalid motion_type in field picture */
  5052.             }
  5053.         }
  5054.     }
  5055. }
  5056. /*---------------------------------------------------------
  5057.     predict a rectangular block (all three components)
  5058.  
  5059.     src:     source frame (Y,U,V)
  5060.     sfield:  source field select (0: frame or top field, 1: bottom field)
  5061.     dst:     destination frame (Y,U,V)
  5062.     dfield:  destination field select (0: frame or top field, 1: bottom field)
  5063.  
  5064.     the following values are in luminance picture (frame or field) dimensions
  5065.     lx:      distance of vertically adjacent pels (selects frame or field pred.)
  5066.     w,h:     width and height of block (only 16x16 or 16x8 are used)
  5067.     x,y:     coordinates of destination block
  5068.     dx,dy:   half pel motion vector
  5069.     addflag: store or add (= average) prediction
  5070. ---------------------------------------------------------*/
  5071. void Pred(unsigned char *src[], int sfield,
  5072.                 unsigned char *dst[], int dfield,
  5073.                 int lx, int w, int h, int x, int y, int dx, int dy, int addflag)
  5074. {
  5075.     int cc;
  5076.  
  5077.     for (cc=0; cc<3; cc++)
  5078.     {
  5079.         if (cc==1)
  5080.         {
  5081.             /* scale for color components */
  5082.             if (g_stSequenceData.stExtension.nChromaFormat==CHROMA420)
  5083.             {
  5084.                 /* vertical */
  5085.                 h >>= 1; y >>= 1; dy /= 2;
  5086.             }
  5087.             if (g_stSequenceData.stExtension.nChromaFormat!=CHROMA444)
  5088.             {
  5089.                 /* horizontal */
  5090.                 w >>= 1; x >>= 1; dx /= 2;
  5091.                 lx >>= 1;
  5092.             }
  5093.         }
  5094.         PredComp(src[cc]+(sfield?lx>>1:0),dst[cc]+(dfield?lx>>1:0),
  5095.                     lx,w,h,x,y,dx,dy,addflag);
  5096.     }
  5097. }
  5098.  
  5099. /*---------------------------------------------------------
  5100.     low level prediction routine
  5101.  
  5102.     src:     prediction source
  5103.     dst:     prediction destination
  5104.     lx:      line width (for both src and dst)
  5105.     x,y:     destination coordinates
  5106.     dx,dy:   half pel motion vector
  5107.     w,h:     size of prediction block
  5108.     addflag: store or add prediction
  5109. ---------------------------------------------------------*/
  5110. inline void PredComp(unsigned char *src, unsigned char *dst,
  5111.                             int lx, int w, int h, int x, int y, int dx, int dy, int addflag)
  5112. {
  5113.     int xint, xh, yint, yh;
  5114.     int i, j;
  5115.     unsigned char *s, *d;
  5116.  
  5117.     /* half pel scaling */
  5118.     xint = dx>>1; /* integer part */
  5119.     xh = dx & 1;  /* half pel flag */
  5120.     yint = dy>>1;
  5121.     yh = dy & 1;
  5122.  
  5123.     /* origins */
  5124.     s = src + lx*(y+yint) + (x+xint); /* motion vector */
  5125.     d = dst + lx*y + x;
  5126.  
  5127.     if (!xh && !yh)
  5128.     {
  5129.         if (addflag)
  5130.         {
  5131.             for (j=0; j<h; j++)
  5132.             {
  5133.                 for (i=0; i<w; i++)
  5134.                     d[i] = (unsigned int)(d[i]+s[i]+1)>>1;
  5135.  
  5136.                 s+= lx;
  5137.                 d+= lx;
  5138.             }
  5139.         }
  5140.         else
  5141.         {
  5142.             for (j=0; j<h; j++)
  5143.             {
  5144.                 for (i=0; i<w; i++)
  5145.                     d[i] = s[i];
  5146.  
  5147.                 s+= lx;
  5148.                 d+= lx;
  5149.             }
  5150.         }
  5151.     }
  5152.     else if (!xh && yh)
  5153.     if (addflag)
  5154.     {
  5155.         for (j=0; j<h; j++)
  5156.         {
  5157.             for (i=0; i<w; i++)
  5158.                 d[i] = (d[i] + ((unsigned int)(s[i]+s[i+lx]+1)>>1)+1)>>1;
  5159.                 
  5160.             s+= lx;
  5161.             d+= lx;
  5162.         }
  5163.     }
  5164.     else
  5165.     {
  5166.         for (j=0; j<h; j++)
  5167.         {
  5168.             for (i=0; i<w; i++)
  5169.                 d[i] = (unsigned int)(s[i]+s[i+lx]+1)>>1;
  5170.                 
  5171.             s+= lx;
  5172.             d+= lx;
  5173.         }
  5174.     }
  5175.     else if (xh && !yh)
  5176.     if (addflag)
  5177.     {
  5178.         for (j=0; j<h; j++)
  5179.         {
  5180.             for (i=0; i<w; i++)
  5181.                 d[i] = (d[i] + ((unsigned int)(s[i]+s[i+1]+1)>>1)+1)>>1;
  5182.                 
  5183.             s+= lx;
  5184.             d+= lx;
  5185.         }
  5186.     }
  5187.     else
  5188.     {
  5189.  
  5190.         for (j=0; j<h; j++)
  5191.         {
  5192.             for (i=0; i<w; i++)
  5193.                 d[i] = (unsigned int)(s[i]+s[i+1]+1)>>1;
  5194.  
  5195.             s+= lx;
  5196.             d+= lx;
  5197.         }
  5198.     }
  5199.     else /* if (xh && yh) */
  5200.     if (addflag)
  5201.     {
  5202.         for (j=0; j<h; j++)
  5203.         {
  5204.             for (i=0; i<w; i++)
  5205.                 d[i] = (d[i] + ((unsigned int)(s[i]+s[i+1]+s[i+lx]+s[i+lx+1]+2)>>2)+1)>>1;
  5206.  
  5207.             s+= lx;
  5208.             d+= lx;
  5209.         }
  5210.     }
  5211.     else
  5212.     {
  5213.         for (j=0; j<h; j++)
  5214.         {
  5215.             for (i=0; i<w; i++)
  5216.                 d[i] = (unsigned int)(s[i]+s[i+1]+s[i+lx]+s[i+lx+1]+2)>>2;
  5217.  
  5218.             s+= lx;
  5219.             d+= lx;
  5220.         }
  5221.     }
  5222. }
  5223.  
  5224. /*---------------------------------------------------------
  5225.     calculate derived motion vectors (DMV) for dual prime prediction
  5226.     dmvector[2]: differential motion vectors (-1,0,+1)
  5227.     mvx,mvy: motion vector (for same parity)
  5228.  
  5229.     DMV[2][2]: derived motion vectors (for opposite parity)
  5230.  
  5231.     uses global variables pict_struct and topfirst
  5232.  
  5233.     Notes:
  5234.      - all vectors are in field coordinates (even for frame pictures)
  5235. ---------------------------------------------------------*/
  5236. void CalDMV(int DMV[][2], int *dmvector, int mvx,int mvy)
  5237. {
  5238.     if (g_stPictureData.stCodingExtension.nPictStruct==FRAME_PICTURE)
  5239.     {
  5240.         if (g_stPictureData.stCodingExtension.bTopFirst)
  5241.         {
  5242.             /* vector for prediction of top field from bottom field */
  5243.             DMV[0][0] = ((mvx  +(mvx>0))>>1) + dmvector[0];
  5244.             DMV[0][1] = ((mvy  +(mvy>0))>>1) + dmvector[1] - 1;
  5245.  
  5246.             /* vector for prediction of bottom field from top field */
  5247.             DMV[1][0] = ((3*mvx+(mvx>0))>>1) + dmvector[0];
  5248.             DMV[1][1] = ((3*mvy+(mvy>0))>>1) + dmvector[1] + 1;
  5249.         }
  5250.         else
  5251.         {
  5252.             /* vector for prediction of top field from bottom field */
  5253.             DMV[0][0] = ((3*mvx+(mvx>0))>>1) + dmvector[0];
  5254.             DMV[0][1] = ((3*mvy+(mvy>0))>>1) + dmvector[1] - 1;
  5255.  
  5256.             /* vector for prediction of bottom field from top field */
  5257.             DMV[1][0] = ((mvx  +(mvx>0))>>1) + dmvector[0];
  5258.             DMV[1][1] = ((mvy  +(mvy>0))>>1) + dmvector[1] + 1;
  5259.         }
  5260.     }
  5261.     else
  5262.     {
  5263.         /* vector for prediction from field of opposite 'parity' */
  5264.         DMV[0][0] = ((mvx+(mvx>0))>>1) + dmvector[0];
  5265.         DMV[0][1] = ((mvy+(mvy>0))>>1) + dmvector[1];
  5266.  
  5267.         /* correct for vertical field shift */
  5268.         if (g_stPictureData.stCodingExtension.nPictStruct==TOP_FIELD)
  5269.             DMV[0][1]--;
  5270.         else
  5271.             DMV[0][1]++;
  5272.     }
  5273. }
  5274.  
  5275. inline void ClearBlock(unsigned char *cur[], int i0, int j0)
  5276. {
  5277.     const int width = g_stSequenceData.stHeader.nWidth;
  5278.     const int width2 = g_stSequenceData.stHeader.nWidth2;
  5279.     const int chroma_format = g_stSequenceData.stExtension.nChromaFormat;
  5280.     const int chrog_width = g_stSequenceData.stHeader.nChromWidth;
  5281.     const int chrog_width2 = g_stSequenceData.stHeader.nChromWidth2;
  5282.     int i, j, w, h;
  5283.     unsigned char *p;
  5284.  
  5285.     if(g_stPictureData.stCodingExtension.nPictStruct==BOTTOM_FIELD)
  5286.     {
  5287.         p = cur[0] + width  + i0 + width2*j0;
  5288.     }
  5289.     else
  5290.     {
  5291.         p = cur[0] + i0 + width2*j0;
  5292.     }
  5293.  
  5294.     for (j=0; j<16; j++)
  5295.     {
  5296.         for (i=0; i<16; i++)
  5297.             p[i] = 128;
  5298.         p+= width2;
  5299.     }
  5300.  
  5301.     w = h = 16;
  5302.  
  5303.     if (chroma_format!=CHROMA444)
  5304.     {
  5305.         i0>>=1; w>>=1;
  5306.     }
  5307.  
  5308.     if (chroma_format==CHROMA420)
  5309.     {
  5310.         j0>>=1; h>>=1;
  5311.     }
  5312.  
  5313.     if(g_stPictureData.stCodingExtension.nPictStruct==BOTTOM_FIELD)
  5314.     {
  5315.         p = cur[1] + chrog_width + i0 + chrog_width2*j0;
  5316.     }
  5317.     else
  5318.     {
  5319.         p = cur[1] + i0 + chrog_width2*j0;
  5320.     }
  5321.  
  5322.  
  5323.     for (j=0; j<h; j++)
  5324.     {
  5325.         for (i=0; i<w; i++)
  5326.             p[i] = 128;
  5327.         p+= chrog_width2;
  5328.     }
  5329.  
  5330.     if(g_stPictureData.stCodingExtension.nPictStruct==BOTTOM_FIELD)
  5331.     {
  5332.         p = cur[2] + chrog_width + i0 + chrog_width2*j0;
  5333.     }
  5334.     else
  5335.     {
  5336.         p = cur[2] + i0 + chrog_width2*j0;
  5337.     }
  5338.  
  5339.     for (j=0; j<h; j++)
  5340.     {
  5341.         for (i=0; i<w; i++)
  5342.             p[i] = 128;
  5343.         p+= chrog_width2;
  5344.     }
  5345. }
  5346. /*=========================================================
  5347.     ò╧î`
  5348. =========================================================*/
  5349. /*---------------------------------------------------------
  5350.     subtract prediction and transform prediction error
  5351. ---------------------------------------------------------*/
  5352. void Transform(unsigned char* pred[],
  5353.                unsigned char* cur[],
  5354.                MACROBLOCKINFO* mbi,
  5355.                short blocks[][64])
  5356. {
  5357.     const int width = g_stSequenceData.stHeader.nWidth;
  5358.     const int width2 = g_stSequenceData.stHeader.nWidth2;
  5359.     const int chroma_format = g_stSequenceData.stExtension.nChromaFormat;
  5360.     const int chrog_width = g_stSequenceData.stHeader.nChromWidth;
  5361.     const int chrog_width2 = g_stSequenceData.stHeader.nChromWidth2;
  5362.     const int block_count = g_stSequenceData.stHeader.nBlockCount;
  5363.  
  5364.     int i, j, i1, j1, k, n, cc, offs, lx;
  5365.  
  5366.     k = 0;
  5367.  
  5368.     for (j=0; j<g_stSequenceData.stHeader.nHeight2; j+=16)
  5369.         for (i=0; i<width; i+=16)
  5370.         {
  5371.             for (n=0; n<block_count; n++)
  5372.             {
  5373.                 cc = (n<4) ? 0 : (n&1)+1; /* color component index */
  5374.                 if (cc==0)
  5375.                 {
  5376.                     /* luminance */
  5377.                     if ((g_stPictureData.stCodingExtension.nPictStruct==FRAME_PICTURE) && mbi[k].dct_type)
  5378.                     {
  5379.                         /* field DCT */
  5380.                         offs = i + ((n&1)<<3) + width*(j+((n&2)>>1));
  5381.                         lx = width<<1;
  5382.                     }
  5383.                     else
  5384.                     {
  5385.                         /* frame DCT */
  5386.                         offs = i + ((n&1)<<3) + width2*(j+((n&2)<<2));
  5387.                         lx = width2;
  5388.                     }
  5389.  
  5390.                 if (g_stPictureData.stCodingExtension.nPictStruct==BOTTOM_FIELD)
  5391.                     offs += width;
  5392.             }
  5393.             else
  5394.             {
  5395.                 /* chrominance */
  5396.  
  5397.                 /* scale coordinates */
  5398.                 i1 = (chroma_format==CHROMA444) ? i : i>>1;
  5399.                 j1 = (chroma_format!=CHROMA420) ? j : j>>1;
  5400.  
  5401.                 if ((g_stPictureData.stCodingExtension.nPictStruct==FRAME_PICTURE) && mbi[k].dct_type
  5402.                     && (chroma_format!=CHROMA420))
  5403.                 {
  5404.                     /* field DCT */
  5405.                     offs = i1 + (n&8) + chrog_width*(j1+((n&2)>>1));
  5406.                     lx = chrog_width<<1;
  5407.                 }
  5408.                 else
  5409.                 {
  5410.                     /* frame DCT */
  5411.                     offs = i1 + (n&8) + chrog_width2*(j1+((n&2)<<2));
  5412.                     lx = chrog_width2;
  5413.                 }
  5414.  
  5415.                 if (g_stPictureData.stCodingExtension.nPictStruct==BOTTOM_FIELD)
  5416.                     offs += chrog_width;
  5417.             }
  5418.  
  5419.             SubPred(pred[cc]+offs,cur[cc]+offs,lx,blocks[k*block_count+n]);
  5420.             g_cDCT.fDCT(blocks[k*block_count+n]);
  5421.         }
  5422.  
  5423.         k++;
  5424.     }
  5425. }
  5426. /*---------------------------------------------------------
  5427.     inverse transform prediction error and add prediction
  5428. ---------------------------------------------------------*/
  5429. void ITransform(unsigned char* pred[],
  5430.                         unsigned char* cur[],
  5431.                         MACROBLOCKINFO* mbi,
  5432.                         short blocks[][64])
  5433. {
  5434.     const int width = g_stSequenceData.stHeader.nWidth;
  5435.     const int width2 = g_stSequenceData.stHeader.nWidth2;
  5436.     const int chroma_format = g_stSequenceData.stExtension.nChromaFormat;
  5437.     const int chrog_width = g_stSequenceData.stHeader.nChromWidth;
  5438.     const int chrog_width2 = g_stSequenceData.stHeader.nChromWidth2;
  5439.     const int block_count = g_stSequenceData.stHeader.nBlockCount;
  5440.     int i, j, i1, j1, k, n, cc, offs, lx;
  5441.  
  5442.     k = 0;
  5443.  
  5444.     for (j=0; j<g_stSequenceData.stHeader.nHeight2; j+=16)
  5445.         for (i=0; i<width; i+=16)
  5446.         {
  5447.             for (n=0; n<block_count; n++)
  5448.             {
  5449.                 cc = (n<4) ? 0 : (n&1)+1; /* color component index */
  5450.  
  5451.                 if (cc==0)
  5452.                 {
  5453.                     /* luminance */
  5454.                     if ((g_stPictureData.stCodingExtension.nPictStruct==FRAME_PICTURE) && mbi[k].dct_type)
  5455.                     {
  5456.                         /* field DCT */
  5457.                         offs = i + ((n&1)<<3) + width*(j+((n&2)>>1));
  5458.                         lx = width<<1;
  5459.                     }
  5460.                     else
  5461.                     {
  5462.                         /* frame DCT */
  5463.                         offs = i + ((n&1)<<3) + width2*(j+((n&2)<<2));
  5464.                         lx = width2;
  5465.                     }
  5466.  
  5467.                     if (g_stPictureData.stCodingExtension.nPictStruct==BOTTOM_FIELD)
  5468.                         offs += width;
  5469.                 }
  5470.                 else
  5471.                 {
  5472.                     /* chrominance */
  5473.  
  5474.                     /* scale coordinates */
  5475.                     i1 = (chroma_format==CHROMA444) ? i : i>>1;
  5476.                     j1 = (chroma_format!=CHROMA420) ? j : j>>1;
  5477.  
  5478.                     if ((g_stPictureData.stCodingExtension.nPictStruct==FRAME_PICTURE) && mbi[k].dct_type
  5479.                         && (chroma_format!=CHROMA420))
  5480.                     {
  5481.                         /* field DCT */
  5482.                         offs = i1 + (n&8) + chrog_width*(j1+((n&2)>>1));
  5483.                         lx = chrog_width<<1;
  5484.                     }
  5485.                     else
  5486.                     {
  5487.                         /* frame DCT */
  5488.                         offs = i1 + (n&8) + chrog_width2*(j1+((n&2)<<2));
  5489.                         lx = chrog_width2;
  5490.                     }
  5491.  
  5492.                     if (g_stPictureData.stCodingExtension.nPictStruct==BOTTOM_FIELD)
  5493.                         offs += chrog_width;
  5494.                 }
  5495.  
  5496.                 g_cDCT.iDCT(blocks[k*block_count+n]);
  5497.                 AddPred(pred[cc]+offs,cur[cc]+offs,lx,blocks[k*block_count+n]);
  5498.             }
  5499.  
  5500.             k++;
  5501.         }
  5502. }
  5503. /*---------------------------------------------------------
  5504.     add prediction and prediction error, saturate to 0...255
  5505. ---------------------------------------------------------*/
  5506. inline void AddPred(unsigned char* pred,
  5507.                              unsigned char* cur,
  5508.                              int lx,short* blk)
  5509. {
  5510.     int i, j;
  5511.  
  5512.     for (j=0; j<8; j++)
  5513.     {
  5514.         for (i=0; i<8; i++)
  5515.             cur[i] = g_stPictureStruct.pClippingTable[blk[i] + pred[i]];
  5516.  
  5517.         blk+= 8;
  5518.         cur+= lx;
  5519.         pred+= lx;
  5520.     }
  5521. }
  5522. /*---------------------------------------------------------
  5523.     subtract prediction from block data
  5524. ---------------------------------------------------------*/
  5525. inline void SubPred(unsigned char* pred,unsigned char* cur,int lx,short* blk)
  5526. {
  5527.     int i, j;
  5528.  
  5529.     for (j=0; j<8; j++)
  5530.     {
  5531.         for (i=0; i<8; i++)
  5532.             blk[i] = cur[i] - pred[i];
  5533.  
  5534.         blk+= 8;
  5535.         cur+= lx;
  5536.         pred+= lx;
  5537.     }
  5538. }
  5539.  
  5540. /*---------------------------------------------------------
  5541.     select between frame and field DCT
  5542.  
  5543.     preliminary version: based on inter-field correlation
  5544. ---------------------------------------------------------*/
  5545. void DCTTypeEstimation(unsigned char* pred,
  5546.                          unsigned char* cur,
  5547.                          MACROBLOCKINFO* mbi)
  5548. {
  5549.     const int width = g_stSequenceData.stHeader.nWidth;
  5550.     short blk0[128], blk1[128];
  5551.     int i, j, i0, j0, k, offs, s0, s1, sq0, sq1, s01;
  5552.     double d, r;
  5553.  
  5554.     k = 0;
  5555.  
  5556.     for (j0=0; j0<g_stSequenceData.stHeader.nHeight2; j0+=16)
  5557.         for (i0=0; i0<width; i0+=16)
  5558.         {
  5559.             if (g_stPictureData.stCodingExtension.bFramePredDCT || g_stPictureData.stCodingExtension.nPictStruct!=FRAME_PICTURE)
  5560.                 mbi[k].dct_type = 0;
  5561.             else
  5562.             {
  5563.                 /* interlaced frame picture */
  5564.                 /*
  5565.                 * calculate prediction error (cur-pred) for top (blk0)
  5566.                 * and bottom field (blk1)
  5567.                 */
  5568.                 for (j=0; j<8; j++)
  5569.                 {
  5570.                     offs = width*((j<<1)+j0) + i0;
  5571.                     for (i=0; i<16; i++)
  5572.                     {
  5573.                         blk0[16*j+i] = cur[offs] - pred[offs];
  5574.                         blk1[16*j+i] = cur[offs+width] - pred[offs+width];
  5575.                         offs++;
  5576.                     }
  5577.                 }
  5578.                 /* correlate fields */
  5579.                 s0=s1=sq0=sq1=s01=0;
  5580.  
  5581.                 for (i=0; i<128; i++)
  5582.                 {
  5583.                     s0+= blk0[i];
  5584.                     sq0+= blk0[i]*blk0[i];
  5585.                     s1+= blk1[i];
  5586.                     sq1+= blk1[i]*blk1[i];
  5587.                     s01+= blk0[i]*blk1[i];
  5588.                 }
  5589.  
  5590.                 d = (sq0-(s0*s0)/128.0)*(sq1-(s1*s1)/128.0);
  5591.  
  5592.                 if (d>0.0)
  5593.                 {
  5594.                     r = (s01-(s0*s1)/128.0)/sqrt(d);
  5595.                 if (r>0.5)
  5596.                     mbi[k].dct_type = 0; /* frame DCT */
  5597.                 else
  5598.                     mbi[k].dct_type = 1; /* field DCT */
  5599.             }
  5600.             else
  5601.             mbi[k].dct_type = 1; /* field DCT */
  5602.         }
  5603.         k++;
  5604.     }
  5605. }
  5606. /*=========================================================
  5607.     PutPicture
  5608. =========================================================*/
  5609. /*---------------------------------------------------------
  5610.     quantization / variable length encoding of a complete picture
  5611. ---------------------------------------------------------*/
  5612. TOMPGRET PutPicture(unsigned char* frame)
  5613. {
  5614.     TOMPGRET ret;
  5615.     int i, j, k, comp, cc;
  5616.     int mb_type;
  5617.     int PMV[2][2][2];
  5618.     int prev_mquant;
  5619.     int cbp, MBAinc;
  5620.  
  5621.     RcInitPic(frame); /* set up rate control */
  5622.  
  5623.     /* picture header and picture coding extension */
  5624.     PutPictureHeader();
  5625.  
  5626.     prev_mquant = RcStartMb(); /* initialize quantization parameter */
  5627.  
  5628.     k = 0;
  5629.  
  5630.     for (j=0; j<g_stSequenceData.stHeader.nMacroBlocksHeight2; j++)
  5631.     {
  5632.         /* macroblock row loop */
  5633.  
  5634.         for (i=0; i<g_stSequenceData.stHeader.nMacroBlocksWidth; i++)
  5635.         {
  5636.             /* macroblock loop */
  5637.             if (i==0)
  5638.             {
  5639.                 /* slice header (6.2.4) */
  5640.                 g_stSystemData.alignbits();
  5641.  
  5642.                 g_stSystemData.putbits(SLICE_MIN_START+j,32); /* slice_start_code */
  5643.  
  5644.                 /* quantiser_scale_code */
  5645.                 if(g_stPictureData.stCodingExtension.bQScaleType)
  5646.                 {
  5647.                     g_stSystemData.putbits(g_MapNonLinearQuantizationArray[prev_mquant],5);
  5648.                 }
  5649.                 else
  5650.                 {
  5651.                     g_stSystemData.putbits(prev_mquant >> 1,5);
  5652.                 }
  5653.  
  5654.                 g_stSystemData.putbits(0,1); /* extra_bit_slice */
  5655.  
  5656.                 /* reset predictors */
  5657.  
  5658.                 for(cc=0; cc<3; cc++)
  5659.                     g_stPictureStruct.nDcDctPredictionArray[cc] = 0;
  5660.  
  5661.                 PMV[0][0][0]=PMV[0][0][1]=PMV[1][0][0]=PMV[1][0][1]=0;
  5662.                 PMV[0][1][0]=PMV[0][1][1]=PMV[1][1][0]=PMV[1][1][1]=0;
  5663.  
  5664.                 MBAinc = i + 1; /* first MBAinc denotes absolute position */
  5665.             }
  5666.  
  5667.             mb_type = g_stPictureStruct.pstMacroBlockInfo[k].mb_type;
  5668.  
  5669.             /* determine mquant (rate control) */
  5670.             g_stPictureStruct.pstMacroBlockInfo[k].mquant = RcCalcMQuant(k);
  5671.  
  5672.             /* quantize macroblock */
  5673.             if (mb_type & MB_INTRA)
  5674.             {
  5675.                 for (comp=0; comp<g_stSequenceData.stHeader.nBlockCount; comp++)
  5676.                     QuantIntra(g_stPictureStruct.pBlocksArray[k*g_stSequenceData.stHeader.nBlockCount+comp],
  5677.                                 g_stPictureStruct.pBlocksArray[k*g_stSequenceData.stHeader.nBlockCount+comp],
  5678.                                 g_stPictureData.stCodingExtension.nDCPrecision,
  5679.                                 g_stPictureStruct.uIntraQArray,
  5680.                                 g_stPictureStruct.uRecipIntraQArray,
  5681.                                 g_stPictureStruct.pstMacroBlockInfo[k].mquant);
  5682.                 g_stPictureStruct.pstMacroBlockInfo[k].cbp = cbp = (1<<g_stSequenceData.stHeader.nBlockCount) - 1;
  5683.             }
  5684.             else
  5685.             {
  5686.                 cbp = 0;
  5687.                 for (comp=0;comp<g_stSequenceData.stHeader.nBlockCount;comp++)
  5688.                     cbp = (cbp<<1) | QuantNonIntra(g_stPictureStruct.pBlocksArray[k*g_stSequenceData.stHeader.nBlockCount+comp],
  5689.                                                     g_stPictureStruct.pBlocksArray[k*g_stSequenceData.stHeader.nBlockCount+comp],
  5690.                                                     g_stPictureStruct.uInterQArray,
  5691.                                                     g_stPictureStruct.uRecipInterQArray,
  5692.                                                     g_stPictureStruct.pstMacroBlockInfo[k].mquant);
  5693.  
  5694.                 g_stPictureStruct.pstMacroBlockInfo[k].cbp = cbp;
  5695.  
  5696.                 if (cbp)
  5697.                     mb_type|= MB_PATTERN;
  5698.             }
  5699.  
  5700.             /* output mquant if it has changed */
  5701.             if (cbp && prev_mquant!=g_stPictureStruct.pstMacroBlockInfo[k].mquant)
  5702.                 mb_type|= MB_QUANT;
  5703.  
  5704.             /* check if macroblock can be skipped */
  5705.             if (i!=0 && i!=g_stSequenceData.stHeader.nMacroBlocksWidth-1 && !cbp)
  5706.             {
  5707.                 /* no DCT coefficients and neither first nor last macroblock of slice */
  5708.  
  5709.                 if (g_stPictureData.stHeader.nPictType==P_TYPE && !(mb_type&MB_FORWARD))
  5710.                 {
  5711.                     /* P picture, no motion vectors -> skip */
  5712.  
  5713.                     /* reset predictors */
  5714.  
  5715.                     for(cc=0; cc<3; cc++)
  5716.                         g_stPictureStruct.nDcDctPredictionArray[cc] = 0;
  5717.  
  5718.                     PMV[0][0][0]=PMV[0][0][1]=PMV[1][0][0]=PMV[1][0][1]=0;
  5719.                     PMV[0][1][0]=PMV[0][1][1]=PMV[1][1][0]=PMV[1][1][1]=0;
  5720.  
  5721.                     g_stPictureStruct.pstMacroBlockInfo[k].mb_type = mb_type;
  5722.                     g_stPictureStruct.pstMacroBlockInfo[k].skipped = 1;
  5723.                     MBAinc++;
  5724.                     k++;
  5725.                     continue;
  5726.                 }
  5727.  
  5728.                 if (g_stPictureData.stHeader.nPictType==B_TYPE
  5729.                     && g_stPictureData.stCodingExtension.nPictStruct==FRAME_PICTURE
  5730.                     && g_stPictureStruct.pstMacroBlockInfo[k].motion_type==MC_FRAME
  5731.                     && ((g_stPictureStruct.pstMacroBlockInfo[k-1].mb_type^mb_type)&(MB_FORWARD|MB_BACKWARD))==0
  5732.                     && (!(mb_type&MB_FORWARD) ||
  5733.                     (PMV[0][0][0]==g_stPictureStruct.pstMacroBlockInfo[k].MV[0][0][0] &&
  5734.                      PMV[0][0][1]==g_stPictureStruct.pstMacroBlockInfo[k].MV[0][0][1]))
  5735.                     && (!(mb_type&MB_BACKWARD) ||
  5736.                     (PMV[0][1][0]==g_stPictureStruct.pstMacroBlockInfo[k].MV[0][1][0] &&
  5737.                      PMV[0][1][1]==g_stPictureStruct.pstMacroBlockInfo[k].MV[0][1][1])))
  5738.                 {
  5739.                     /* conditions for skipping in B frame pictures:
  5740.                     * - must be frame predicted
  5741.                     * - must be the same prediction type (forward/backward/interp.)
  5742.                     *   as previous macroblock
  5743.                     * - relevant vectors (forward/backward/both) have to be the same
  5744.                     *   as in previous macroblock
  5745.                     */
  5746.  
  5747.                     g_stPictureStruct.pstMacroBlockInfo[k].mb_type = mb_type;
  5748.                     g_stPictureStruct.pstMacroBlockInfo[k].skipped = 1;
  5749.                     MBAinc++;
  5750.                     k++;
  5751.                     continue;
  5752.                 }
  5753.  
  5754.             if (g_stPictureData.stHeader.nPictType==B_TYPE
  5755.                 && g_stPictureData.stCodingExtension.nPictStruct!=FRAME_PICTURE
  5756.                 && g_stPictureStruct.pstMacroBlockInfo[k].motion_type==MC_FIELD
  5757.                 && ((g_stPictureStruct.pstMacroBlockInfo[k-1].mb_type^mb_type)&(MB_FORWARD|MB_BACKWARD))==0
  5758.                 && (!(mb_type&MB_FORWARD) ||
  5759.                 (PMV[0][0][0]==g_stPictureStruct.pstMacroBlockInfo[k].MV[0][0][0] &&
  5760.                  PMV[0][0][1]==g_stPictureStruct.pstMacroBlockInfo[k].MV[0][0][1] &&
  5761.                  g_stPictureStruct.pstMacroBlockInfo[k].mv_field_sel[0][0]==(g_stPictureData.stCodingExtension.nPictStruct==BOTTOM_FIELD)))
  5762.                 && (!(mb_type&MB_BACKWARD) ||
  5763.                 (PMV[0][1][0]==g_stPictureStruct.pstMacroBlockInfo[k].MV[0][1][0] &&
  5764.                  PMV[0][1][1]==g_stPictureStruct.pstMacroBlockInfo[k].MV[0][1][1] &&
  5765.                  g_stPictureStruct.pstMacroBlockInfo[k].mv_field_sel[0][1]==(g_stPictureData.stCodingExtension.nPictStruct==BOTTOM_FIELD))))
  5766.                 {
  5767.                     /* conditions for skipping in B field pictures:
  5768.                     * - must be field predicted
  5769.                     * - must be the same prediction type (forward/backward/interp.)
  5770.                     *   as previous macroblock
  5771.                     * - relevant vectors (forward/backward/both) have to be the same
  5772.                     *   as in previous macroblock
  5773.                     * - relevant motion_vertical_field_selects have to be of same
  5774.                     *   parity as current field
  5775.                     */
  5776.  
  5777.                     g_stPictureStruct.pstMacroBlockInfo[k].mb_type = mb_type;
  5778.                     g_stPictureStruct.pstMacroBlockInfo[k].skipped = 1;
  5779.                     MBAinc++;
  5780.                     k++;
  5781.                     continue;
  5782.                 }
  5783.             }
  5784.  
  5785.             /* macroblock cannot be skipped */
  5786.             g_stPictureStruct.pstMacroBlockInfo[k].skipped = 0;
  5787.  
  5788.             /* there's no VLC for 'No MC, Not Coded':
  5789.             * we have to transmit (0,0) motion vectors
  5790.             */
  5791.             if (g_stPictureData.stHeader.nPictType==P_TYPE && !cbp && !(mb_type&MB_FORWARD))
  5792.                     mb_type|= MB_FORWARD;
  5793.  
  5794.             PutMacroblockAddressIncement(MBAinc); /* macroblock_address_increment */
  5795.             MBAinc = 1;
  5796.  
  5797.             PutMacroblockType(g_stPictureData.stHeader.nPictType,mb_type); /* macroblock type */
  5798.  
  5799.             if (mb_type & (MB_FORWARD|MB_BACKWARD) && !g_stPictureData.stCodingExtension.bFramePredDCT)
  5800.                     g_stSystemData.putbits(g_stPictureStruct.pstMacroBlockInfo[k].motion_type,2);
  5801.  
  5802.             if (g_stPictureData.stCodingExtension.nPictStruct==FRAME_PICTURE && cbp && !g_stPictureData.stCodingExtension.bFramePredDCT)
  5803.                     g_stSystemData.putbits(g_stPictureStruct.pstMacroBlockInfo[k].dct_type,1);
  5804.  
  5805.             if (mb_type & MB_QUANT)
  5806.             {
  5807.                 if(g_stPictureData.stCodingExtension.bQScaleType)
  5808.                 {
  5809.                     g_stSystemData.putbits(g_MapNonLinearQuantizationArray[g_stPictureStruct.pstMacroBlockInfo[k].mquant],5);
  5810.                 }
  5811.                 else
  5812.                 {
  5813.                     g_stSystemData.putbits(g_stPictureStruct.pstMacroBlockInfo[k].mquant>>1,5);
  5814.                 }
  5815.                 prev_mquant = g_stPictureStruct.pstMacroBlockInfo[k].mquant;
  5816.             }
  5817.  
  5818.             if (mb_type & MB_FORWARD)
  5819.             {
  5820.                 /* forward motion vectors, update predictors */
  5821.                 PutMotionVectors(g_stPictureStruct.pstMacroBlockInfo[k].MV,
  5822.                     PMV,
  5823.                     g_stPictureStruct.pstMacroBlockInfo[k].mv_field_sel,
  5824.                     g_stPictureStruct.pstMacroBlockInfo[k].dmvector,
  5825.                     0,
  5826.                     g_stPictureStruct.pstMacroBlockInfo[k].motion_type,
  5827.                     g_stPictureData.stCodingExtension.nForwHorFCode,
  5828.                     g_stPictureData.stCodingExtension.nForwVertFCode);
  5829.             }
  5830.  
  5831.             if (mb_type & MB_BACKWARD)
  5832.             {
  5833.                 /* backward motion vectors, update predictors */
  5834.                 PutMotionVectors(g_stPictureStruct.pstMacroBlockInfo[k].MV,
  5835.                     PMV,
  5836.                     g_stPictureStruct.pstMacroBlockInfo[k].mv_field_sel,
  5837.                     g_stPictureStruct.pstMacroBlockInfo[k].dmvector,
  5838.                     1,
  5839.                     g_stPictureStruct.pstMacroBlockInfo[k].motion_type,
  5840.                     g_stPictureData.stCodingExtension.nBackHorFCode,
  5841.                     g_stPictureData.stCodingExtension.nBackVertFCode);
  5842.             }
  5843.  
  5844.             if (mb_type & MB_PATTERN)
  5845.             {
  5846.                 PutCodedBlockPattern((cbp >> (g_stSequenceData.stHeader.nBlockCount-6)) & 63);
  5847.  
  5848.                 if (g_stSequenceData.stExtension.nChromaFormat!=CHROMA420)
  5849.                     g_stSystemData.putbits(cbp,g_stSequenceData.stHeader.nBlockCount-6);
  5850.             }
  5851.  
  5852.             for (comp=0; comp<g_stSequenceData.stHeader.nBlockCount; comp++)
  5853.             {
  5854.                 /* block loop */
  5855.                 if (cbp & (1<<(g_stSequenceData.stHeader.nBlockCount-1-comp)))
  5856.                 {
  5857.                     if (mb_type & MB_INTRA)
  5858.                     {
  5859.                         cc = (comp<4) ? 0 : (comp&1)+1;
  5860.                         if((ret = PutIntraCodedBlock(g_stPictureStruct.pBlocksArray[k*g_stSequenceData.stHeader.nBlockCount+comp],cc))!=TR_OK)
  5861.                         {
  5862.                             return ret;
  5863.                         }
  5864.                     }
  5865.                     else
  5866.                     {
  5867.                         if((ret = PutNonIntraCodedBlock(g_stPictureStruct.pBlocksArray[k*g_stSequenceData.stHeader.nBlockCount+comp]))!=TR_OK)
  5868.                         {
  5869.                             return ret;
  5870.                         }
  5871.                     }
  5872.                 }
  5873.             }
  5874.  
  5875.             /* reset predictors */
  5876.             if (!(mb_type & MB_INTRA))
  5877.                 for (cc=0; cc<3; cc++)
  5878.                     g_stPictureStruct.nDcDctPredictionArray[cc] = 0;
  5879.  
  5880.             if (mb_type & MB_INTRA || (g_stPictureData.stHeader.nPictType==P_TYPE && !(mb_type & MB_FORWARD)))
  5881.             {
  5882.                 PMV[0][0][0]=PMV[0][0][1]=PMV[1][0][0]=PMV[1][0][1]=0;
  5883.                 PMV[0][1][0]=PMV[0][1][1]=PMV[1][1][0]=PMV[1][1][1]=0;
  5884.             }
  5885.  
  5886.             g_stPictureStruct.pstMacroBlockInfo[k].mb_type = mb_type;
  5887.             k++;
  5888.         }
  5889.     }
  5890.  
  5891.     RcUpdatePict();
  5892.     VBVEndOfPicture();
  5893.  
  5894.     return TR_OK;
  5895. }
  5896. /*---------------------------------------------------------
  5897.     output motion vectors (6.2.5.2, 6.3.16.2)
  5898.  
  5899.     this routine also updates the predictions for motion vectors (PMV)
  5900. ---------------------------------------------------------*/
  5901. void PutMotionVectors(int MV[2][2][2], int PMV[2][2][2],
  5902.                             int mv_field_sel[2][2], int dmvector[2], int s, int motion_type,
  5903.                             int hor_f_code, int vert_f_code)
  5904. {
  5905.     if(g_stPictureData.stCodingExtension.nPictStruct==FRAME_PICTURE)
  5906.     {
  5907.         if(motion_type==MC_FRAME)
  5908.         {
  5909.             /* frame prediction */
  5910.             PutMotionVector(MV[0][s][0]-PMV[0][s][0],hor_f_code);
  5911.             PutMotionVector(MV[0][s][1]-PMV[0][s][1],vert_f_code);
  5912.             PMV[0][s][0]=PMV[1][s][0]=MV[0][s][0];
  5913.             PMV[0][s][1]=PMV[1][s][1]=MV[0][s][1];
  5914.         }
  5915.         else if (motion_type==MC_FIELD)
  5916.         {
  5917.             /* field prediction */
  5918.             g_stSystemData.putbits(mv_field_sel[0][s],1);
  5919.             PutMotionVector(MV[0][s][0]-PMV[0][s][0],hor_f_code);
  5920.             PutMotionVector((MV[0][s][1]>>1)-(PMV[0][s][1]>>1),vert_f_code);
  5921.             g_stSystemData.putbits(mv_field_sel[1][s],1);
  5922.             PutMotionVector(MV[1][s][0]-PMV[1][s][0],hor_f_code);
  5923.             PutMotionVector((MV[1][s][1]>>1)-(PMV[1][s][1]>>1),vert_f_code);
  5924.             PMV[0][s][0]=MV[0][s][0];
  5925.             PMV[0][s][1]=MV[0][s][1];
  5926.             PMV[1][s][0]=MV[1][s][0];
  5927.             PMV[1][s][1]=MV[1][s][1];
  5928.         }
  5929.         else
  5930.         {
  5931.             /* dual prime prediction */
  5932.             PutMotionVector(MV[0][s][0]-PMV[0][s][0],hor_f_code);
  5933.             PutDMVector(dmvector[0]);
  5934.             PutMotionVector((MV[0][s][1]>>1)-(PMV[0][s][1]>>1),vert_f_code);
  5935.             PutDMVector(dmvector[1]);
  5936.             PMV[0][s][0]=PMV[1][s][0]=MV[0][s][0];
  5937.             PMV[0][s][1]=PMV[1][s][1]=MV[0][s][1];
  5938.         }
  5939.     }
  5940.     else
  5941.     {
  5942.         /* field picture */
  5943.         if (motion_type==MC_FIELD)
  5944.         {
  5945.             /* field prediction */
  5946.             g_stSystemData.putbits(mv_field_sel[0][s],1);
  5947.             PutMotionVector(MV[0][s][0]-PMV[0][s][0],hor_f_code);
  5948.             PutMotionVector(MV[0][s][1]-PMV[0][s][1],vert_f_code);
  5949.             PMV[0][s][0]=PMV[1][s][0]=MV[0][s][0];
  5950.             PMV[0][s][1]=PMV[1][s][1]=MV[0][s][1];
  5951.         }
  5952.         else if (motion_type==MC_16X8)
  5953.         {
  5954.             /* 16x8 prediction */
  5955.             g_stSystemData.putbits(mv_field_sel[0][s],1);
  5956.             PutMotionVector(MV[0][s][0]-PMV[0][s][0],hor_f_code);
  5957.             PutMotionVector(MV[0][s][1]-PMV[0][s][1],vert_f_code);
  5958.             g_stSystemData.putbits(mv_field_sel[1][s],1);
  5959.             PutMotionVector(MV[1][s][0]-PMV[1][s][0],hor_f_code);
  5960.             PutMotionVector(MV[1][s][1]-PMV[1][s][1],vert_f_code);
  5961.             PMV[0][s][0]=MV[0][s][0];
  5962.             PMV[0][s][1]=MV[0][s][1];
  5963.             PMV[1][s][0]=MV[1][s][0];
  5964.             PMV[1][s][1]=MV[1][s][1];
  5965.         }
  5966.         else
  5967.         {
  5968.             /* dual prime prediction */
  5969.             PutMotionVector(MV[0][s][0]-PMV[0][s][0],hor_f_code);
  5970.             PutDMVector(dmvector[0]);
  5971.             PutMotionVector(MV[0][s][1]-PMV[0][s][1],vert_f_code);
  5972.             PutDMVector(dmvector[1]);
  5973.             PMV[0][s][0]=PMV[1][s][0]=MV[0][s][0];
  5974.             PMV[0][s][1]=PMV[1][s][1]=MV[0][s][1];
  5975.         }
  5976.     }
  5977. }
  5978. /*=========================================================
  5979.     Put Mpeg
  5980. =========================================================*/
  5981. /*---------------------------------------------------------
  5982.     generate variable length codes for an intra-coded block (6.2.6, 6.3.17)
  5983. ---------------------------------------------------------*/
  5984. inline TOMPGRET PutIntraCodedBlock(short* blk,int cc)
  5985. {
  5986.     TOMPGRET ret;
  5987.     int n, dct_diff, run, signed_level;
  5988.     const unsigned char* scan_array = (g_stPictureData.stCodingExtension.bAltScan?g_AlternateScanArray:g_ZigZagScanArray);
  5989.  
  5990.     /* DC coefficient (7.2.1) */
  5991.     dct_diff = blk[0] - g_stPictureStruct.nDcDctPredictionArray[cc]; /* difference to previous block */
  5992.     g_stPictureStruct.nDcDctPredictionArray[cc] = blk[0];
  5993.  
  5994.     if (cc==0)
  5995.     {
  5996.         if((ret = PutLuminanceDCCoefficient(dct_diff))!=TR_OK)
  5997.         {
  5998.             return ret;
  5999.         }
  6000.     }
  6001.     else
  6002.     {
  6003.         if((ret = PutChrominanceDCCoefficient(dct_diff))!=TR_OK)
  6004.         {
  6005.             return ret;
  6006.         }
  6007.     }
  6008.  
  6009.     /* AC coefficients (7.2.2) */
  6010.     run = 0;
  6011.     for (n=1; n<64; n++)
  6012.     {
  6013.         /* use appropriate entropy scanning pattern */
  6014.         signed_level = blk[scan_array[n]];
  6015.         if (signed_level!=0)
  6016.         {
  6017.             if((ret = PutAC(run,signed_level,g_stPictureData.stCodingExtension.bIntravlc))!=TR_OK)
  6018.             {
  6019.                 return ret;
  6020.             }
  6021.             run = 0;
  6022.         }
  6023.         else
  6024.             run++; /* count zero coefficients */
  6025.     }
  6026.  
  6027.     /* End of Block -- normative block punctuation */
  6028.     if (g_stPictureData.stCodingExtension.bIntravlc)
  6029.         g_stSystemData.putbits(6,4); /* 0110 (Table B-15) */
  6030.     else
  6031.         g_stSystemData.putbits(2,2); /* 10 (Table B-14) */
  6032.  
  6033.     return TR_OK;
  6034. }
  6035. /*---------------------------------------------------------
  6036.     generate variable length codes for a non-intra-coded block (6.2.6, 6.3.17)
  6037. ---------------------------------------------------------*/
  6038. inline TOMPGRET PutNonIntraCodedBlock(short* blk)
  6039. {
  6040.     TOMPGRET ret;
  6041.     int n, run, signed_level, first;
  6042.     const unsigned char* scan_array = 
  6043.         (g_stPictureData.stCodingExtension.bAltScan? g_AlternateScanArray:g_ZigZagScanArray);
  6044.  
  6045.     run = 0;
  6046.     first = 1;
  6047.  
  6048.     for (n=0; n<64; n++)
  6049.     {
  6050.         /* use appropriate entropy scanning pattern */
  6051.         signed_level = blk[scan_array[n]];
  6052.  
  6053.         if (signed_level!=0)
  6054.         {
  6055.             if (first)
  6056.             {
  6057.                 /* first coefficient in non-intra block */
  6058.                 if((ret = PutACFirst(run,signed_level))!=TR_OK)
  6059.                 {
  6060.                     return ret;
  6061.                 }
  6062.                 first = 0;
  6063.             }
  6064.             else
  6065.             {
  6066.                 if((ret = PutAC(run,signed_level,0))!=TR_OK)
  6067.                 {
  6068.                     return ret;
  6069.                 }
  6070.             }
  6071.  
  6072.             run = 0;
  6073.  
  6074.         }
  6075.         else
  6076.             run++; /* count zero coefficients */
  6077.     }
  6078.  
  6079.     /* End of Block -- normative block punctuation  */
  6080.     g_stSystemData.putbits(2,2);
  6081.  
  6082.     return TR_OK;
  6083. }
  6084. /*---------------------------------------------------------
  6085.     generate variable length code for a motion vector component (7.6.3.1)
  6086. ---------------------------------------------------------*/
  6087. void PutMotionVector(int dmv,int f_code)
  6088. {
  6089.     int r_size, f, vmin, vmax, dv, temp, motion_code, motion_residual;
  6090.  
  6091.     r_size = f_code - 1; /* number of fixed length code ('residual') bits */
  6092.     f = 1<<r_size;
  6093.     vmin = -16*f; /* lower range limit */
  6094.     vmax = 16*f - 1; /* upper range limit */
  6095.     dv = 32*f;
  6096.  
  6097.     /* fold vector difference into [vmin...vmax] */
  6098.     if (dmv>vmax)
  6099.         dmv-= dv;
  6100.     else if (dmv<vmin)
  6101.         dmv+= dv;
  6102.  
  6103.     /* check value */
  6104.     if (dmv<vmin || dmv>vmax)
  6105.     {
  6106.     }
  6107.  
  6108.     /* split dmv into motion_code and motion_residual */
  6109.     temp = ((dmv<0) ? -dmv : dmv) + f - 1;
  6110.     motion_code = temp>>r_size;
  6111.  
  6112.     if (dmv<0)
  6113.         motion_code = -motion_code;
  6114.  
  6115.     motion_residual = temp & (f-1);
  6116.  
  6117.     PutMotionCode(motion_code); /* variable length code */
  6118.  
  6119.     if (r_size!=0 && motion_code!=0)
  6120.         g_stSystemData.putbits(motion_residual,r_size); /* fixed length code */
  6121. }
  6122.  
  6123. /*=========================================================
  6124.     Put Variable Length Codes
  6125. =========================================================*/
  6126. /*---------------------------------------------------------
  6127.     generate variable length code for luminance DC coefficient
  6128. ---------------------------------------------------------*/
  6129. inline TOMPGRET PutLuminanceDCCoefficient(const int val)
  6130. {
  6131.     return PutDC(g_DCTDcSizeLuminanceArray,val);
  6132. }
  6133. /*---------------------------------------------------------
  6134.     generate variable length code for chrominance DC coefficient
  6135. ---------------------------------------------------------*/
  6136. inline TOMPGRET PutChrominanceDCCoefficient(const int val)
  6137. {
  6138.     return PutDC(g_DCTDcSizeChrominanceArray,val);
  6139. }
  6140. /*---------------------------------------------------------
  6141.     generate variable length code for DC coefficient (7.2.1)
  6142. ---------------------------------------------------------*/
  6143. TOMPGRET PutDC(const void* pvtab,const int val)
  6144. {
  6145.     const sVLCtable *tab = (sVLCtable*)pvtab;
  6146.     int absval, size;
  6147.  
  6148.     absval = (val<0) ? -val : val; /* abs(val) */
  6149.  
  6150.     if (absval>255)
  6151.     {
  6152.         /* should never happen */
  6153.         return TR_DC_VALUE_OUT_OF_RANGE;
  6154.     }
  6155.  
  6156.     /* compute dct_dc_size */
  6157.     size = 0;
  6158.  
  6159.     while (absval)
  6160.     {
  6161.         absval >>= 1;
  6162.         size++;
  6163.     }
  6164.  
  6165.     /* generate VLC for dct_dc_size (Table B-12 or B-13) */
  6166.     g_stSystemData.putbits(tab[size].code,tab[size].len);
  6167.  
  6168.     /* append fixed length code (dc_dct_differential) */
  6169.     if (size!=0)
  6170.     {
  6171.         if (val>=0)
  6172.             absval = val;
  6173.         else
  6174.             absval = val + (1<<size) - 1; /* val + (2 ^ size) - 1 */
  6175.         g_stSystemData.putbits(absval,size);
  6176.     }
  6177.     return TR_OK;
  6178. }
  6179. /*---------------------------------------------------------
  6180.     generate variable length code for first coefficient
  6181.     of a non-intra block (7.2.2.2)
  6182. ---------------------------------------------------------*/
  6183. inline TOMPGRET PutACFirst(const int run,const int val)
  6184. {
  6185.     if (run==0 && (val==1 || val==-1))
  6186.     {
  6187.         /* these are treated differently */
  6188.         g_stSystemData.putbits(2|(val<0?1:0),2); /* generate '1s' (s=sign), (Table B-14, line 2) */
  6189.         return TR_OK;
  6190.     }
  6191.     else
  6192.     {
  6193.         return PutAC(run,val,0); /* no difference for all others */
  6194.     }
  6195.     return TR_OK;
  6196. }
  6197. /*---------------------------------------------------------
  6198.     generate variable length code for other DCT coefficients (7.2.2)
  6199. ---------------------------------------------------------*/
  6200. TOMPGRET PutAC(const int run,const int signed_level,const int vlcformat)
  6201. {
  6202.     int level, len;
  6203.     VLCtable *ptab;
  6204.  
  6205.     level = (signed_level<0) ? -signed_level : signed_level; /* abs(signed_level) */
  6206.  
  6207.     /* make sure run and level are valid */
  6208.     if (run<0 || run>63 || level==0 || level>255)
  6209.     {
  6210.         return TR_AC_VALUE_OUT_OF_RANGE;
  6211.     }
  6212.  
  6213.     len = 0;
  6214.  
  6215.     if (run<2 && level<41)
  6216.     {
  6217.         /* vlcformat selects either of Table B-14 / B-15 */
  6218.         if (vlcformat)
  6219.             ptab = &g_DCTCodeTable1a[run][level-1];
  6220.         else
  6221.             ptab = &g_DCTCodeTable1[run][level-1];
  6222.  
  6223.         len = ptab->len;
  6224.     }
  6225.     else if (run<32 && level<6)
  6226.     {
  6227.         /* vlcformat selects either of Table B-14 / B-15 */
  6228.         if (vlcformat)
  6229.             ptab = &g_DCTCodeTable2a[run-2][level-1];
  6230.         else
  6231.             ptab = &g_DCTCodeTable2[run-2][level-1];
  6232.  
  6233.         len = ptab->len;
  6234.     }
  6235.  
  6236.     if (len!=0) /* a VLC code exists */
  6237.     {
  6238.         g_stSystemData.putbits(ptab->code,len);
  6239.         g_stSystemData.putbits(signed_level<0,1); /* sign */
  6240.     }
  6241.     else
  6242.     {
  6243.         /* no VLC for this (run, level) combination: use escape coding (7.2.2.3) */
  6244.         g_stSystemData.putbits(1l,6); /* Escape */
  6245.         g_stSystemData.putbits(run,6); /* 6 bit code for run */
  6246.         /* ISO/IEC 11172-2 uses a 8 or 16 bit code */
  6247.         if (signed_level>127)
  6248.             g_stSystemData.putbits(0,8);
  6249.         if (signed_level<-127)
  6250.             g_stSystemData.putbits(128,8);
  6251.         g_stSystemData.putbits(signed_level,8);
  6252.     }
  6253.     return TR_OK;
  6254. }
  6255.  
  6256. /*---------------------------------------------------------
  6257.     generate variable length code for macroblock_address_increment
  6258. ---------------------------------------------------------*/
  6259. inline void PutMacroblockAddressIncement(int addrinc)
  6260. {
  6261.     while (addrinc>33)
  6262.     {
  6263.         g_stSystemData.putbits(0x08,11); /* macroblock_escape */
  6264.         addrinc-= 33;
  6265.     }
  6266.  
  6267.     g_stSystemData.putbits(g_AddRincArray[addrinc-1].code,g_AddRincArray[addrinc-1].len);
  6268. }
  6269.  
  6270. /*---------------------------------------------------------
  6271.     generate variable length code for macroblock_type
  6272. ---------------------------------------------------------*/
  6273. inline void PutMacroblockType(const int pict_type,const int mb_type)
  6274. {
  6275.     g_stSystemData.putbits(g_MacroblockTypeTable[pict_type-1][mb_type].code,
  6276.             g_MacroblockTypeTable[pict_type-1][mb_type].len);
  6277. }
  6278. /*---------------------------------------------------------
  6279.     generate variable length code for motion_code
  6280. ---------------------------------------------------------*/
  6281. inline void PutMotionCode(const int motion_code)
  6282. {
  6283.     int abscode = abs(motion_code); /* abs(motion_code) */
  6284.     g_stSystemData.putbits(g_MotionCodeArray[abscode].code,g_MotionCodeArray[abscode].len);
  6285.     if (motion_code!=0)
  6286.         g_stSystemData.putbits(motion_code<0,1); /* sign, 0=positive, 1=negative */
  6287. }
  6288. /*---------------------------------------------------------
  6289.     generate variable length code for dmvector[t]
  6290. ---------------------------------------------------------*/
  6291. void PutDMVector(const int dmv)
  6292. {
  6293.     if (dmv==0)
  6294.         g_stSystemData.putbits(0,1);
  6295.     else if (dmv>0)
  6296.         g_stSystemData.putbits(2,2);
  6297.     else
  6298.         g_stSystemData.putbits(3,2);
  6299. }
  6300.  
  6301. /*---------------------------------------------------------
  6302.     generate variable length code for coded_block_pattern
  6303.  
  6304.     4:2:2, 4:4:4 not implemented
  6305. ---------------------------------------------------------*/
  6306. inline void PutCodedBlockPattern(const int cbp)
  6307. {
  6308.     g_stSystemData.putbits(g_CodedBlockPatternArray[cbp].code,g_CodedBlockPatternArray[cbp].len);
  6309. }
  6310. /*=========================================================
  6311.     ù╩Äqë╗âeü[âuâïè╓îW
  6312. =========================================================*/
  6313. inline int QuantIntra(short* src,short* dst,int dc_prec,
  6314.                             unsigned char* quant_mat,unsigned short* recip_quant_mat,
  6315.                             int mquant)
  6316. {
  6317.     int i;
  6318.     int x, y, d;
  6319.     static short mquantm3p2div4[4];
  6320.     static unsigned short recip_mquant[4];
  6321.  
  6322.     x = src[0];
  6323.     d = 8>>dc_prec; /* intra_dc_mult */
  6324.     dst[0] = (x>=0) ? (x+(d>>1))/d : -((-x+(d>>1))/d); /* round(x/d) */
  6325.  
  6326.     for (i=1; i<64; i++)
  6327.     {
  6328.         x = src[i];
  6329.         d = quant_mat[i];
  6330.         y = (32*(x>=0 ? x : -x) + (d>>1))/d; /* round(32*x/quant_mat) */
  6331.         //y = (32*(x>=0 ? x : -x))/d;
  6332.         d = (3*mquant+2)>>2;
  6333.         y = (y+d)/(2*mquant); /* (y+0.75*mquant) / (2*mquant) */
  6334.  
  6335.         /* clip to syntax limits */
  6336.         if (y > 255)
  6337.         {
  6338.             y = 255;
  6339.         }
  6340.  
  6341.         dst[i] = (x>=0) ? y : -y;
  6342.     }
  6343.  
  6344.     return 1;
  6345. }
  6346.  
  6347. inline int QuantNonIntra(short* src,short* dst,
  6348.                                 unsigned char* quant_mat,
  6349.                                 unsigned short* recip_quant_mat,
  6350.                                 int mquant)
  6351. {
  6352.     int i;
  6353.     int x, y, d;
  6354.     int nzflag;
  6355.  
  6356.     nzflag = 0;
  6357.  
  6358.     for (i=0; i<64; i++)
  6359.     {
  6360.         x = src[i];
  6361.         d = quant_mat[i];
  6362.         y = (32*(x>=0 ? x : -x) + (d>>1))/d; // round(32*x/quant_mat)
  6363.         y /= (2*mquant);
  6364.  
  6365.         // clip to syntax limits
  6366.         if (y > 255)
  6367.         {
  6368.             y = 255;
  6369.         }
  6370.  
  6371.         if ((dst[i] = (x>=0 ? y : -y)) != 0)
  6372.             nzflag=1;
  6373.     }
  6374.  
  6375.     return nzflag;
  6376. }
  6377.  
  6378. /*---------------------------------------------------------
  6379.     MPEG-1 inverse quantization
  6380. ---------------------------------------------------------*/
  6381. void IQuantIntra(short* src,short* dst,int dc_prec,unsigned char* quant_mat,int mquant)
  6382. {
  6383.     int i, val;
  6384.  
  6385.     dst[0] = src[0] << (3-dc_prec);
  6386.     for (i=1; i<64; i++)
  6387.     {
  6388.         val = (int)(src[i]*quant_mat[i]*mquant)/16;
  6389.  
  6390.         /* mismatch control */
  6391.         if ((val&1)==0 && val!=0)
  6392.             val+= (val>0) ? -1 : 1;
  6393.  
  6394.         /* saturation */
  6395.         dst[i] = (val>2047) ? 2047 : ((val<-2048) ? -2048 : val);
  6396.     }
  6397. }
  6398.  
  6399. void IQuantNonIntra(short* src,short* dst,
  6400.                       unsigned char* quant_mat,
  6401.                       int mquant)
  6402. {
  6403.     int i, val;
  6404.  
  6405.     for (i=0; i<64; i++)
  6406.     {
  6407.         val = src[i];
  6408.         if (val!=0)
  6409.         {
  6410.             val = (int)((2*val+(val>0 ? 1 : -1))*quant_mat[i]*mquant)/32;
  6411.  
  6412.             /* mismatch control */
  6413.             if ((val&1)==0 && val!=0)
  6414.                 val+= (val>0) ? -1 : 1;
  6415.         }
  6416.  
  6417.         /* saturation */
  6418.         dst[i] = (val>2047) ? 2047 : ((val<-2048) ? -2048 : val);
  6419.     }
  6420. }
  6421.