SPSParser.c 74.8 KB
Newer Older
xiongziliang committed
1
#include <stdio.h>
xzl committed
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#include <stdlib.h>
#include <string.h>
#include <stdint.h> /* for uint32_t, etc */
#include "SPSParser.h"

/********************************************
*define here
********************************************/
#define SPS_PPS_DEBUG
//#undef  SPS_PPS_DEBUG


#define MAX_LEN 32
#define EXTENDED_SAR       255
#define FF_ARRAY_ELEMS(a) (sizeof(a) / sizeof((a)[0]))
#define MAX_SPS_COUNT    			32
#define MAX_LOG2_MAX_FRAME_NUM    	(12 + 4)
#define MIN_LOG2_MAX_FRAME_NUM    	4
#define H264_MAX_PICTURE_COUNT 		36
#define CODEC_FLAG2_IGNORE_CROP   0x00010000 ///< Discard cropping information from SPS.
xiongziliang committed
22
#ifndef INT_MAX
xzl committed
23
#define INT_MAX						65535
xiongziliang committed
24
#endif //INT_MAX
xzl committed
25

zqsong committed
26 27 28 29 30 31 32
#ifndef FFMIN
#define FFMIN(a,b) ((a) > (b) ? (b) : (a))
#endif
#ifndef FFMAX
#define FFMAX(a,b) ((a) > (b) ? (a) : (b))
#endif

xzl committed
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
/* report level */
#define RPT_ERR (1) // error, system error
#define RPT_WRN (2) // warning, maybe wrong, maybe OK
#define RPT_INF (3) // important information
#define RPT_DBG (4) // debug information

static int rpt_lvl = RPT_WRN; /* report level: ERR, WRN, INF, DBG */

/* report micro */
#define RPT(lvl, ...) \
    do { \
        if(lvl <= rpt_lvl) { \
            switch(lvl) { \
                case RPT_ERR: \
                    fprintf(stderr, "\"%s\" line %d [err]: ", __FILE__, __LINE__); \
                    break; \
                case RPT_WRN: \
                    fprintf(stderr, "\"%s\" line %d [wrn]: ", __FILE__, __LINE__); \
                    break; \
                case RPT_INF: \
                    fprintf(stderr, "\"%s\" line %d [inf]: ", __FILE__, __LINE__); \
                    break; \
                case RPT_DBG: \
                    fprintf(stderr, "\"%s\" line %d [dbg]: ", __FILE__, __LINE__); \
                    break; \
                default: \
                    fprintf(stderr, "\"%s\" line %d [???]: ", __FILE__, __LINE__); \
                    break; \
                } \
                fprintf(stderr, __VA_ARGS__); \
                fprintf(stderr, "\n"); \
        } \
    } while(0)

static const uint8_t sg_aau8DefaultScaling4[2][16] = {
    {  6, 13, 20, 28, 13, 20, 28, 32,
      20, 28, 32, 37, 28, 32, 37, 42 },
    { 10, 14, 20, 24, 14, 20, 24, 27,
      20, 24, 27, 30, 24, 27, 30, 34 }
};

static const uint8_t sg_aau8DefaultScaling8[2][64] = {
    {  6, 10, 13, 16, 18, 23, 25, 27,
      10, 11, 16, 18, 23, 25, 27, 29,
      13, 16, 18, 23, 25, 27, 29, 31,
      16, 18, 23, 25, 27, 29, 31, 33,
      18, 23, 25, 27, 29, 31, 33, 36,
      23, 25, 27, 29, 31, 33, 36, 38,
      25, 27, 29, 31, 33, 36, 38, 40,
      27, 29, 31, 33, 36, 38, 40, 42 },
    {  9, 13, 15, 17, 19, 21, 22, 24,
      13, 13, 17, 19, 21, 22, 24, 25,
      15, 17, 19, 21, 22, 24, 25, 27,
      17, 19, 21, 22, 24, 25, 27, 28,
      19, 21, 22, 24, 25, 27, 28, 30,
      21, 22, 24, 25, 27, 28, 30, 32,
      22, 24, 25, 27, 28, 30, 32, 33,
      24, 25, 27, 28, 30, 32, 33, 35 }
};

static const T_AVRational sg_atFfH264PixelSspect[17] = {
    {   0,  1 },
    {   1,  1 },
    {  12, 11 },
    {  10, 11 },
    {  16, 11 },
    {  40, 33 },
    {  24, 11 },
    {  20, 11 },
    {  32, 11 },
    {  80, 33 },
    {  18, 11 },
    {  15, 11 },
    {  64, 33 },
    { 160, 99 },
    {   4,  3 },
    {   3,  2 },
    {   2,  1 },
};

static const uint8_t sg_au8ZigzagScan[16+1] = {
    0 + 0 * 4, 1 + 0 * 4, 0 + 1 * 4, 0 + 2 * 4,
    1 + 1 * 4, 2 + 0 * 4, 3 + 0 * 4, 2 + 1 * 4,
    1 + 2 * 4, 0 + 3 * 4, 1 + 3 * 4, 2 + 2 * 4,
    3 + 1 * 4, 3 + 2 * 4, 2 + 3 * 4, 3 + 3 * 4,
};

const uint8_t g_au8FfZigzagDirect[64] = {
    0,   1,  8, 16,  9,  2,  3, 10,
    17, 24, 32, 25, 18, 11,  4,  5,
    12, 19, 26, 33, 40, 48, 41, 34,
    27, 20, 13,  6,  7, 14, 21, 28,
    35, 42, 49, 56, 57, 50, 43, 36,
    29, 22, 15, 23, 30, 37, 44, 51,
    58, 59, 52, 45, 38, 31, 39, 46,
    53, 60, 61, 54, 47, 55, 62, 63
};


132
static const uint8_t sg_au8HevcSubWidthC[] = {
zqsong committed
133 134 135
    1, 2, 2, 1
};

136
static const uint8_t sg_au8HevcSubHeightC[] = {
zqsong committed
137 138 139
    1, 2, 1, 1
};

140
static const uint8_t sg_au8DefaultScalingListIntra[] = {
zqsong committed
141 142 143 144 145 146 147 148 149 150
    16, 16, 16, 16, 17, 18, 21, 24,
    16, 16, 16, 16, 17, 19, 22, 25,
    16, 16, 17, 18, 20, 22, 25, 29,
    16, 16, 18, 21, 24, 27, 31, 36,
    17, 17, 20, 24, 30, 35, 41, 47,
    18, 19, 22, 27, 35, 44, 54, 65,
    21, 22, 25, 31, 41, 54, 70, 88,
    24, 25, 29, 36, 47, 65, 88, 115
};

151
static const uint8_t sg_au8DefaultScalingListInter[] = {
zqsong committed
152 153 154 155 156 157 158 159 160 161 162
    16, 16, 16, 16, 17, 18, 20, 24,
    16, 16, 16, 17, 18, 20, 24, 25,
    16, 16, 17, 18, 20, 24, 25, 28,
    16, 17, 18, 20, 24, 25, 28, 33,
    17, 18, 20, 24, 25, 28, 33, 41,
    18, 20, 24, 25, 28, 33, 41, 54,
    20, 24, 25, 28, 33, 41, 54, 71,
    24, 25, 28, 33, 41, 54, 71, 91
};


163
const uint8_t g_au8HevcDiagScan4x4X[16] = {
zqsong committed
164 165 166 167 168 169
    0, 0, 1, 0,
    1, 2, 0, 1,
    2, 3, 1, 2,
    3, 2, 3, 3,
};

170
const uint8_t g_au8HevcDiagScan4x4Y[16] = {
zqsong committed
171 172 173 174 175 176
    0, 1, 0, 2,
    1, 0, 3, 2,
    1, 0, 3, 2,
    1, 3, 2, 3,
};

177
const uint8_t g_au8HevcDiagScan8x8X[64] = {
zqsong committed
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
    0, 0, 1, 0,
    1, 2, 0, 1,
    2, 3, 0, 1,
    2, 3, 4, 0,
    1, 2, 3, 4,
    5, 0, 1, 2,
    3, 4, 5, 6,
    0, 1, 2, 3,
    4, 5, 6, 7,
    1, 2, 3, 4,
    5, 6, 7, 2,
    3, 4, 5, 6,
    7, 3, 4, 5,
    6, 7, 4, 5,
    6, 7, 5, 6,
    7, 6, 7, 7,
};

196
const uint8_t g_au8HevcDiagScan8x8Y[64] = {
zqsong committed
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
    0, 1, 0, 2,
    1, 0, 3, 2,
    1, 0, 4, 3,
    2, 1, 0, 5,
    4, 3, 2, 1,
    0, 6, 5, 4,
    3, 2, 1, 0,
    7, 6, 5, 4,
    3, 2, 1, 0,
    7, 6, 5, 4,
    3, 2, 1, 7,
    6, 5, 4, 3,
    2, 7, 6, 5,
    4, 3, 7, 6,
    5, 4, 7, 6,
    5, 7, 6, 7,
};

215
static const T_AVRational sg_atVuiSar[] = {
zqsong committed
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
    {  0,   1 },
    {  1,   1 },
    { 12,  11 },
    { 10,  11 },
    { 16,  11 },
    { 40,  33 },
    { 24,  11 },
    { 20,  11 },
    { 32,  11 },
    { 80,  33 },
    { 18,  11 },
    { 15,  11 },
    { 64,  33 },
    { 160, 99 },
    {  4,   3 },
    {  3,   2 },
    {  2,   1 },
};
xzl committed
234 235 236

static inline int getBitsLeft(void *pvHandle)
{
237 238 239 240 241 242 243
    int iResLen = 0;
    T_GetBitContext *ptPtr = (T_GetBitContext *)pvHandle;
    if(ptPtr->iBufSize <= 0 || ptPtr->iTotalBit <= 0)
    {
        RPT(RPT_WRN, "buffer size is zero");
        return 0;
    }
xzl committed
244 245


246
    iResLen = ptPtr->iTotalBit - ptPtr->iBitPos;
xzl committed
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
    return iResLen;
}


/********************************************
*functions
********************************************/
/**
 *  @brief Function getOneBit()   ¶Á1¸öbit
 *  @param[in]     h     T_GetBitContext structrue
 *  @retval        0: success, -1 : failure
 *  @pre
 *  @post
 */
static int getOneBit(void *pvHandle)
{
    T_GetBitContext *ptPtr = (T_GetBitContext *)pvHandle;
    int iRet = 0;
    uint8_t *pu8CurChar = NULL;
    uint8_t u8Shift;
267
    int iResoLen = 0;
xzl committed
268 269 270 271 272 273 274

    if(NULL == ptPtr)
    {
        RPT(RPT_ERR, "NULL pointer");
        iRet = -1;
        goto exit;
    }
275 276 277
    iResoLen = getBitsLeft(ptPtr);
    if(iResoLen < 1)
    {
xzl committed
278 279
        iRet = -1;
        goto exit;
280
    }
xzl committed
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309

    pu8CurChar = ptPtr->pu8Buf + (ptPtr->iBitPos >> 3);
    u8Shift = 7 - (ptPtr->iCurBitPos);
    ptPtr->iBitPos++;
    ptPtr->iCurBitPos = ptPtr->iBitPos & 0x7;
    iRet = ((*pu8CurChar) >> u8Shift) & 0x01;

exit:
    return iRet;
}


/**
 *  @brief Function getBits()  ¶Án¸öbits£¬n²»Äܳ¬¹ý32
 *  @param[in]     h     T_GetBitContext structrue
 *  @param[in]     n     how many bits you want?
 *  @retval        0: success, -1 : failure
 *  @pre
 *  @post
 */
static int getBits(void *pvHandle, int iN)
{
    T_GetBitContext *ptPtr = (T_GetBitContext *)pvHandle;
    uint8_t au8Temp[5] = {0};
    uint8_t *pu8CurChar = NULL;
    uint8_t u8Nbyte;
    uint8_t u8Shift;
    uint32_t u32Result = 0;
    int iRet = 0;
310
    int iResoLen = 0;
xzl committed
311 312 313 314 315 316 317 318 319 320 321 322 323

    if(NULL == ptPtr)
    {
        RPT(RPT_ERR, "NULL pointer");
        iRet = -1;
        goto exit;
    }

    if(iN > MAX_LEN)
    {
        iN = MAX_LEN;
    }

324 325 326
    iResoLen = getBitsLeft(ptPtr);
    if(iResoLen < iN)
    {
xzl committed
327 328
        iRet = -1;
        goto exit;
329
    }
xzl committed
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364


    if((ptPtr->iBitPos + iN) > ptPtr->iTotalBit)
    {
        iN = ptPtr->iTotalBit- ptPtr->iBitPos;
    }

    pu8CurChar = ptPtr->pu8Buf+ (ptPtr->iBitPos>>3);
    u8Nbyte = (ptPtr->iCurBitPos + iN + 7) >> 3;
    u8Shift = (8 - (ptPtr->iCurBitPos + iN))& 0x07;

    if(iN == MAX_LEN)
    {
        RPT(RPT_DBG, "12(ptPtr->iBitPos(:%d) + iN(:%d)) > ptPtr->iTotalBit(:%d)!!! ",\
                ptPtr->iBitPos, iN, ptPtr->iTotalBit);
        RPT(RPT_DBG, "0x%x 0x%x 0x%x 0x%x", (*pu8CurChar), *(pu8CurChar+1),*(pu8CurChar+2),*(pu8CurChar+3));
    }

    memcpy(&au8Temp[5-u8Nbyte], pu8CurChar, u8Nbyte);
    iRet = (uint32_t)au8Temp[0] << 24;
    iRet = iRet << 8;
    iRet = ((uint32_t)au8Temp[1]<<24)|((uint32_t)au8Temp[2] << 16)\
                        |((uint32_t)au8Temp[3] << 8)|au8Temp[4];

    iRet = (iRet >> u8Shift) & (((uint64_t)1<<iN) - 1);

    u32Result = iRet;
    ptPtr->iBitPos += iN;
    ptPtr->iCurBitPos = ptPtr->iBitPos & 0x7;

exit:
    return u32Result;
}


zqsong committed
365 366 367 368 369 370 371 372 373 374 375 376
/**
 * Show 1-25 bits.
 */
static inline unsigned int showBits(void *pvHandle, int iN)
{
    T_GetBitContext *ptPtr = (T_GetBitContext *)pvHandle;
    uint8_t au8Temp[5] = {0};
    uint8_t *pu8CurChar = NULL;
    uint8_t u8Nbyte;
    uint8_t u8Shift;
    uint32_t u32Result = 0;
    int iRet = 0;
377
    int iResoLen = 0;
zqsong committed
378 379 380 381 382 383 384 385 386 387 388 389 390

    if(NULL == ptPtr)
    {
        RPT(RPT_ERR, "NULL pointer");
        iRet = -1;
        goto exit;
    }

    if(iN > MAX_LEN)
    {
        iN = MAX_LEN;
    }

391 392 393
    iResoLen = getBitsLeft(ptPtr);
    if(iResoLen < iN)
    {
zqsong committed
394 395
        iRet = -1;
        goto exit;
396
    }
zqsong committed
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437


    if((ptPtr->iBitPos + iN) > ptPtr->iTotalBit)
    {
        iN = ptPtr->iTotalBit- ptPtr->iBitPos;
    }

    pu8CurChar = ptPtr->pu8Buf+ (ptPtr->iBitPos>>3);
    u8Nbyte = (ptPtr->iCurBitPos + iN + 7) >> 3;
    u8Shift = (8 - (ptPtr->iCurBitPos + iN))& 0x07;

    if(iN == MAX_LEN)
    {
        RPT(RPT_DBG, "12(ptPtr->iBitPos(:%d) + iN(:%d)) > ptPtr->iTotalBit(:%d)!!! ",\
                ptPtr->iBitPos, iN, ptPtr->iTotalBit);
        RPT(RPT_DBG, "0x%x 0x%x 0x%x 0x%x", (*pu8CurChar), *(pu8CurChar+1),*(pu8CurChar+2),*(pu8CurChar+3));
    }

    memcpy(&au8Temp[5-u8Nbyte], pu8CurChar, u8Nbyte);
    iRet = (uint32_t)au8Temp[0] << 24;
    iRet = iRet << 8;
    iRet = ((uint32_t)au8Temp[1]<<24)|((uint32_t)au8Temp[2] << 16)\
                        |((uint32_t)au8Temp[3] << 8)|au8Temp[4];

    iRet = (iRet >> u8Shift) & (((uint64_t)1<<iN) - 1);

    u32Result = iRet;
//    ptPtr->iBitPos += iN;
//    ptPtr->iCurBitPos = ptPtr->iBitPos & 0x7;

exit:
    return u32Result;
}



/**
 * Show 0-32 bits.
 */
static inline unsigned int showBitsLong(void *pvHandle, int iN)
{
438
    T_GetBitContext *ptPtr = (T_GetBitContext *)pvHandle;
zqsong committed
439 440 441

    if (iN <= 32) {
        return showBits(ptPtr, iN);
442 443
    }
    return 0;
zqsong committed
444 445 446
}


xzl committed
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613

/**
 *  @brief Function parseCodenum() Ö¸Êý¸çÂײ¼±àÂë½âÎö£¬²Î¿¼h264±ê×¼µÚ9½Ú
 *  @param[in]     buf
 *  @retval        u32CodeNum
 *  @pre
 *  @post
 */
static int parseCodenum(void *pvBuf)
{
    uint8_t u8LeadingZeroBits = -1;
    uint8_t u8B;
    uint32_t u32CodeNum = 0;

    for(u8B=0; !u8B; u8LeadingZeroBits++)
    {
        u8B = getOneBit(pvBuf);
    }

    u32CodeNum = ((uint32_t)1 << u8LeadingZeroBits) - 1 + getBits(pvBuf, u8LeadingZeroBits);

    return u32CodeNum;
}

/**
 *  @brief Function parseUe() Ö¸Êý¸çÂײ¼±àÂë½âÎö ue(),²Î¿¼h264±ê×¼µÚ9½Ú
 *  @param[in]     buf       sps_pps parse buf
 *  @retval        u32CodeNum
 *  @pre
 *  @post
 */
static int parseUe(void *pvBuf)
{
    return parseCodenum(pvBuf);
}


/**
 *  @brief Function parseSe() Ö¸Êý¸çÂײ¼±àÂë½âÎö se(), ²Î¿¼h264±ê×¼µÚ9½Ú
 *  @param[in]     buf       sps_pps parse buf
 *  @retval        u32CodeNum
 *  @pre
 *  @post
 */
static int parseSe(void *pvBuf)
{
    int iRet = 0;
    int u32CodeNum;

    u32CodeNum = parseCodenum(pvBuf);
    iRet = (u32CodeNum + 1) >> 1;
    iRet = (u32CodeNum & 0x01)? iRet : -iRet;

    return iRet;
}


/**
 *  @brief Function getBitContextFree()  ÉêÇëµÄget_bit_context½á¹¹ÄÚ´æÊÍ·Å
 *  @param[in]     buf       T_GetBitContext buf
 *  @retval        none
 *  @pre
 *  @post
 */
static void getBitContextFree(void *pvBuf)
{
    T_GetBitContext *ptPtr = (T_GetBitContext *)pvBuf;

    if(ptPtr)
    {
        if(ptPtr->pu8Buf)
        {
            free(ptPtr->pu8Buf);
        }

        free(ptPtr);
    }
}




/**
 *  @brief Function deEmulationPrevention()  ½â¾ºÕù´úÂë
 *  @param[in]     buf       T_GetBitContext buf
 *  @retval        none
 *  @pre
 *  @post
 *  @note:
 *      µ÷ÊÔʱ×ÜÊÇ·¢ÏÖvui.time_scaleÖµÌرðÆæ¹Ö£¬×ÜÊÇ16777216£¬ºóÀ´²éѯԭÒòÈçÏÂ:
 *      http://www.cnblogs.com/eustoma/archive/2012/02/13/2415764.html
 *      H.264±àÂëʱ£¬ÔÚÿ¸öNALÇ°Ìí¼ÓÆðʼÂë 0x000001£¬½âÂëÆ÷ÔÚÂëÁ÷Öмì²âµ½ÆðʼÂ룬µ±Ç°NAL½áÊø¡£
 *      ΪÁË·ÀÖ¹NALÄÚ²¿³öÏÖ0x000001µÄÊý¾Ý£¬h.264ÓÖÌá³ö'·ÀÖ¹¾ºÕù emulation prevention"»úÖÆ£¬
 *      ÔÚ±àÂëÍêÒ»¸öNALʱ£¬Èç¹û¼ì²â³öÓÐÁ¬ÐøÁ½¸ö0x00×Ö½Ú£¬¾ÍÔÚºóÃæ²åÈëÒ»¸ö0x03¡£
 *      µ±½âÂëÆ÷ÔÚNALÄÚ²¿¼ì²âµ½0x000003µÄÊý¾Ý£¬¾Í°Ñ0x03Å×Æú£¬»Ö¸´Ô­Ê¼Êý¾Ý¡£
 *      0x000000  >>>>>>  0x00000300
 *      0x000001  >>>>>>  0x00000301
 *      0x000002  >>>>>>  0x00000302
 *      0x000003  >>>>>>  0x00000303
 */
static void *deEmulationPrevention(void *pvBuf)
{
    T_GetBitContext *ptPtr = NULL;
    T_GetBitContext *ptBufPtr = (T_GetBitContext *)pvBuf;
    int i = 0, j = 0;
    uint8_t *pu8TmpPtr = NULL;
    int tmp_buf_size = 0;
    int iVal = 0;

    if(NULL == ptBufPtr)
    {
        RPT(RPT_ERR, "NULL ptPtr");
        goto exit;
    }

    ptPtr = (T_GetBitContext *)malloc(sizeof(T_GetBitContext));
    if(NULL == ptPtr)
    {
        RPT(RPT_ERR, "NULL ptPtr");
        goto exit;
    }

    memcpy(ptPtr, ptBufPtr, sizeof(T_GetBitContext));

    ptPtr->pu8Buf = (uint8_t *)malloc(ptPtr->iBufSize);
    if(NULL == ptPtr->pu8Buf)
    {
        RPT(RPT_ERR, "NULL ptPtr");
        goto exit;
    }

    memcpy(ptPtr->pu8Buf, ptBufPtr->pu8Buf, ptBufPtr->iBufSize);

    pu8TmpPtr = ptPtr->pu8Buf;
    tmp_buf_size = ptPtr->iBufSize;
    for(i=0; i<(tmp_buf_size-2); i++)
    {
        /*¼ì²â0x000003*/
        iVal = (pu8TmpPtr[i]^0x00) + (pu8TmpPtr[i+1]^0x00) + (pu8TmpPtr[i+2]^0x03);
        if(iVal == 0)
        {
            /*ÌÞ³ý0x03*/
            for(j=i+2; j<tmp_buf_size-1; j++)
            {
                pu8TmpPtr[j] = pu8TmpPtr[j+1];
            }

            /*ÏàÓ¦µÄbufsizeÒª¼õС*/
            ptPtr->iBufSize--;
        }
    }

    /*ÖØмÆËãtotal_bit*/
    ptPtr->iTotalBit = ptPtr->iBufSize << 3;

    return (void *)ptPtr;

exit:
    getBitContextFree(ptPtr);
    return NULL;
}

static void decodeScalingList(void *pvBuf, uint8_t *pu8Factors, int iSize,
                                const uint8_t *pu8JvtList,
                                const uint8_t *pu8FallbackList)
{
    int i;
614 615
    int iLast = 8;
    int iNext = 8;
xzl committed
616 617 618 619 620 621
    const uint8_t *pu8Scan = iSize == 16 ? sg_au8ZigzagScan : g_au8FfZigzagDirect;

    if (!getOneBit(pvBuf)) /* matrix not written, we use the predicted one */
        memcpy(pu8Factors, pu8FallbackList, iSize * sizeof(uint8_t));
    else
        for (i = 0; i < iSize; i++)
622
        {
xzl committed
623 624 625 626 627 628
            if (iNext)
            {

                iNext = (iLast + parseSe(pvBuf)) & 0xff;
            }
            if (!i && !iNext)
629 630
            {
                /* matrix not written, we use the preset one */
xzl committed
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
                memcpy(pu8Factors, pu8JvtList, iSize * sizeof(uint8_t));
                break;
            }
            iLast = pu8Factors[pu8Scan[i]] = iNext ? iNext : iLast;
        }
}


 int decodeScalingMatrices(void *pvBuf, T_SPS *ptSps,
                                    T_PPS *ptPps, int iIsSps,
                                    uint8_t(*pau8ScalingMatrix4)[16],
                                    uint8_t(*pau8ScalingMatrix8)[64])
{
    int iFallbackSps = !iIsSps && ptSps->iScalingMatrixPresent;
    const uint8_t *pau8Fallback[4] = {
        iFallbackSps ? ptSps->aau8ScalingMatrix4[0] : sg_aau8DefaultScaling4[0],
        iFallbackSps ? ptSps->aau8ScalingMatrix4[3] : sg_aau8DefaultScaling4[1],
        iFallbackSps ? ptSps->aau8ScalingMatrix8[0] : sg_aau8DefaultScaling8[0],
        iFallbackSps ? ptSps->aau8ScalingMatrix8[3] : sg_aau8DefaultScaling8[1]
    };
    if (getOneBit(pvBuf)) {
        ptSps->iScalingMatrixPresent |= iIsSps;
        decodeScalingList(pvBuf, pau8ScalingMatrix4[0], 16, sg_aau8DefaultScaling4[0], pau8Fallback[0]);        // Intra, Y
        decodeScalingList(pvBuf, pau8ScalingMatrix4[1], 16, sg_aau8DefaultScaling4[0], pau8ScalingMatrix4[0]); // Intra, Cr
655
        decodeScalingList(pvBuf, pau8ScalingMatrix4[2], 16, sg_aau8DefaultScaling4[0], pau8ScalingMatrix4[1]); // Intra, Cb
xzl committed
656

657
        decodeScalingList(pvBuf, pau8ScalingMatrix4[3], 16, sg_aau8DefaultScaling4[1], pau8Fallback[1]);        // Inter, Y
xzl committed
658

659
        decodeScalingList(pvBuf, pau8ScalingMatrix4[4], 16, sg_aau8DefaultScaling4[1], pau8ScalingMatrix4[3]); // Inter, Cr
xzl committed
660

661
        decodeScalingList(pvBuf, pau8ScalingMatrix4[5], 16, sg_aau8DefaultScaling4[1], pau8ScalingMatrix4[4]); // Inter, Cb
xzl committed
662 663 664


        if (iIsSps || ptPps->iTransform8x8Mode)
665
        {
xzl committed
666 667 668 669
            decodeScalingList(pvBuf, pau8ScalingMatrix8[0], 64, sg_aau8DefaultScaling8[0], pau8Fallback[2]); // Intra, Y
            decodeScalingList(pvBuf, pau8ScalingMatrix8[3], 64, sg_aau8DefaultScaling8[1], pau8Fallback[3]); // Inter, Y
            if (ptSps->iChromaFormatIdc == 3) {
                decodeScalingList(pvBuf, pau8ScalingMatrix8[1], 64, sg_aau8DefaultScaling8[0], pau8ScalingMatrix8[0]); // Intra, Cr
670 671 672 673
                decodeScalingList(pvBuf, pau8ScalingMatrix8[4], 64, sg_aau8DefaultScaling8[1], pau8ScalingMatrix8[3]); // Inter, Cr
                decodeScalingList(pvBuf, pau8ScalingMatrix8[2], 64, sg_aau8DefaultScaling8[0], pau8ScalingMatrix8[1]); // Intra, Cb
                decodeScalingList(pvBuf, pau8ScalingMatrix8[5], 64, sg_aau8DefaultScaling8[1], pau8ScalingMatrix8[4]); // Inter, Cb
            }
xzl committed
674 675
        }
    }
676
    return 0;
xzl committed
677 678 679 680 681
}

static  int decodeHrdPAarameters(void *pvBuf, T_SPS *ptSps)
{
    int iCpbCount = 0;
682
    int i;
xzl committed
683 684 685
    iCpbCount = parseUe(pvBuf);

    if (iCpbCount > 32U)
686 687 688
    {
        RPT(RPT_ERR,"iCpbCount %d invalid\n", iCpbCount);
        return -1;
xzl committed
689 690 691 692 693 694

    }

    getBits(pvBuf, 4); /* bit_rate_scale */
    getBits(pvBuf, 4); /* cpb_size_scale */
    for (i = 0; i < iCpbCount; i++)
695 696 697
    {
        parseUe(pvBuf);
        parseUe(pvBuf);
xzl committed
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
        //get_ue_golomb_long(&h->gb); /* bit_rate_value_minus1 */
        //get_ue_golomb_long(&h->gb); /* cpb_size_value_minus1 */
        getOneBit(pvBuf);          /* cbr_flag */
    }
    ptSps->iInitialCpbRemovalDelayLength = getBits(pvBuf, 5) + 1;
    ptSps->iCpbRemovalDelayLength         = getBits(pvBuf, 5) + 1;
    ptSps->iDpbOutputDelayLength          = getBits(pvBuf, 5) + 1;
    ptSps->iTimeOffsetLength               = getBits(pvBuf, 5);
    ptSps->iCpbCnt                          = iCpbCount;
    return 0;
}


static inline int decodeVuiParameters(void *pvBuf, T_SPS *ptSps)
{
    int iAspectRatioInfoPresentFlag;
    unsigned int uiAspectRatioIdc;
715
    int iChromaSampleLocation;
xzl committed
716 717 718 719 720 721 722 723 724 725 726 727

    iAspectRatioInfoPresentFlag = getOneBit(pvBuf);

    if (iAspectRatioInfoPresentFlag) {
        uiAspectRatioIdc = getBits(pvBuf, 8);
        if (uiAspectRatioIdc == EXTENDED_SAR) {
            ptSps->tSar.num = getBits(pvBuf, 16);
            ptSps->tSar.den = getBits(pvBuf, 16);
        } else if (uiAspectRatioIdc < FF_ARRAY_ELEMS(sg_atFfH264PixelSspect)) {
            ptSps->tSar = sg_atFfH264PixelSspect[uiAspectRatioIdc];
        } else
        {
728
            RPT(RPT_ERR,"illegal aspect ratio\n");
xzl committed
729 730 731 732 733 734 735 736
            return -1;
        }
    } else
    {
        ptSps->tSar.num =
        ptSps->tSar.den = 0;
    }

737 738
    if (getOneBit(pvBuf))      /* iOverscanInfoPresentFlag */
        getOneBit(pvBuf);      /* iOverscanAppropriateFlag */
xzl committed
739 740 741 742

    ptSps->iVideoSignalTypePresentFlag = getOneBit(pvBuf);
    if (ptSps->iVideoSignalTypePresentFlag) {
        getBits(pvBuf, 3);                 /* video_format */
743
        ptSps->iFullRange = getOneBit(pvBuf); /* iVideoFullRangeFlag */
xzl committed
744 745 746

        ptSps->iColourDescriptionPresentFlag = getOneBit(pvBuf);
        if (ptSps->iColourDescriptionPresentFlag) {
747
            ptSps->tColorPrimaries = getBits(pvBuf, 8); /* u8ColourPrimaries */
xzl committed
748 749 750 751 752 753 754 755 756 757 758 759 760
            ptSps->tColorTrc       = getBits(pvBuf, 8); /* transfer_characteristics */
            ptSps->tColorspace      = getBits(pvBuf, 8); /* matrix_coefficients */
            if (ptSps->tColorPrimaries >= AVCOL_PRI_NB)
                ptSps->tColorPrimaries = AVCOL_PRI_UNSPECIFIED;
            if (ptSps->tColorTrc >= AVCOL_TRC_NB)
                ptSps->tColorTrc = AVCOL_TRC_UNSPECIFIED;
            if (ptSps->tColorspace >= AVCOL_SPC_NB)
                ptSps->tColorspace = AVCOL_SPC_UNSPECIFIED;
        }
    }

    /* chroma_location_info_present_flag */
    if (getOneBit(pvBuf))
761
    {
xzl committed
762 763 764 765
        /* chroma_sample_location_type_top_field */
        iChromaSampleLocation = parseUe(pvBuf);
        parseUe(pvBuf);  /* chroma_sample_location_type_bottom_field */
    }
766 767 768 769
    if(getBitsLeft(pvBuf) < 10)
    {
        return 0;
    }
xzl committed
770 771 772 773 774 775 776 777


    ptSps->iTimingInfoPresentFlag = getOneBit(pvBuf);
    if (ptSps->iTimingInfoPresentFlag) {
        unsigned u32NumUnitsInTick = getBits(pvBuf, 32);
        unsigned u32TimeScale        = getBits(pvBuf, 32);
        if (!u32NumUnitsInTick || !u32TimeScale) {

778
            RPT(RPT_ERR,"u32TimeScale/u32NumUnitsInTick invalid or unsupported (%u/%u)\n",u32TimeScale, u32NumUnitsInTick);
xzl committed
779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
            ptSps->iTimingInfoPresentFlag = 0;
        } else {
            ptSps->u32NumUnitsInTick = u32NumUnitsInTick;
            ptSps->u32TimeScale = u32TimeScale;
        }
        ptSps->iFixedFrameRateFlag = getOneBit(pvBuf);
    }

    ptSps->iNalHrdParametersPresentFlag = getOneBit(pvBuf);
    if (ptSps->iNalHrdParametersPresentFlag)
        if (decodeHrdPAarameters(pvBuf, ptSps) < 0)
            return -1;
    ptSps->iVclHrdParametersPresentFlag = getOneBit(pvBuf);
    if (ptSps->iVclHrdParametersPresentFlag)
        if (decodeHrdPAarameters(pvBuf, ptSps) < 0)
            return -1;
    if (ptSps->iNalHrdParametersPresentFlag ||
        ptSps->iVclHrdParametersPresentFlag)
        getOneBit(pvBuf);     /* low_delay_hrd_flag */
    ptSps->iPicStructPresentFlag = getOneBit(pvBuf);

800 801
    if(getBitsLeft(pvBuf) == 0)
        return 0;
xzl committed
802 803
    ptSps->iBitstreamRestrictionFlag = getOneBit(pvBuf);
    if (ptSps->iBitstreamRestrictionFlag) {
804
        getOneBit(pvBuf);     	 /* motion_vectors_over_pic_boundaries_flag */
805
        parseUe(pvBuf);
xzl committed
806 807 808 809 810 811 812 813 814
        //get_ue_golomb(&h->gb); /* max_bytes_per_pic_denom */
        parseUe(pvBuf);
        //get_ue_golomb(&h->gb); /* max_bits_per_mb_denom */
        parseUe(pvBuf);
        //get_ue_golomb(&h->gb); /* log2_max_mv_length_horizontal */
        parseUe(pvBuf);
        //get_ue_golomb(&h->gb); /* log2_max_mv_length_vertical */
        ptSps->iNumReorderFrames = parseUe(pvBuf);

815
        parseUe(pvBuf);
xzl committed
816 817 818
        //get_ue_golomb(&h->gb); /*max_dec_frame_buffering*/

        if (getBitsLeft(pvBuf) < 0)
819
        {
xzl committed
820 821 822 823 824 825 826
            ptSps->iNumReorderFrames         = 0;
            ptSps->iBitstreamRestrictionFlag = 0;
        }

        if (ptSps->iNumReorderFrames > 16U
            /* max_dec_frame_buffering || max_dec_frame_buffering > 16 */)
        {
827
            RPT(RPT_DBG, "Clipping illegal iNumReorderFrames %d\n",
xzl committed
828 829 830 831 832 833 834 835 836 837 838 839 840
                   ptSps->iNumReorderFrames);
            ptSps->iNumReorderFrames = 16;
            return -1;
        }
    }

    return 0;
}


int h264DecSeqParameterSet(void *pvBufSrc, T_SPS *ptSps)
{
    int iLevelIdc;
841
    int iConstraintSetFlags = 0;
xzl committed
842 843
    unsigned int uiSpsId;
    int i;
844
    int iLog2MaxFrameNumMinus4;
xzl committed
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912

    int iRet = 0;
    int iProfileIdc = 0;
    void *pvBuf = NULL;



    if(NULL == pvBufSrc || NULL == ptSps)
    {
        RPT(RPT_ERR,"ERR null pointer\n");
        iRet = -1;
        goto exit;
    }

    memset((void *)ptSps, 0, sizeof(T_SPS));

    pvBuf = deEmulationPrevention(pvBufSrc);
    if(NULL == pvBuf)
    {
        RPT(RPT_ERR,"ERR null pointer\n");
        iRet = -1;
        goto exit;
    }

    iProfileIdc           = getBits(pvBuf, 8);
    iConstraintSetFlags |= getOneBit(pvBuf) << 0;   // constraint_set0_flag
    iConstraintSetFlags |= getOneBit(pvBuf) << 1;   // constraint_set1_flag
    iConstraintSetFlags |= getOneBit(pvBuf) << 2;   // constraint_set2_flag
    iConstraintSetFlags |= getOneBit(pvBuf) << 3;   // constraint_set3_flag
    iConstraintSetFlags |= getOneBit(pvBuf) << 4;   // constraint_set4_flag
    iConstraintSetFlags |= getOneBit(pvBuf) << 5;   // constraint_set5_flag
    getBits(pvBuf, 2);                            // reserved_zero_2bits
    iLevelIdc = getBits(pvBuf, 8);
    uiSpsId    = parseUe(pvBuf);

    if (uiSpsId >= MAX_SPS_COUNT) {
        RPT(RPT_ERR, "uiSpsId %u out of range\n", uiSpsId);
        iRet = -1;
        goto exit;

    }


    ptSps->uiSpsId               = uiSpsId;
    ptSps->iTimeOffsetLength   = 24;
    ptSps->iProfileIdc          = iProfileIdc;
    ptSps->iConstraintSetFlags = iConstraintSetFlags;
    ptSps->iLevelIdc            = iLevelIdc;
    ptSps->iFullRange           = -1;

    memset(ptSps->aau8ScalingMatrix4, 16, sizeof(ptSps->aau8ScalingMatrix4));
    memset(ptSps->aau8ScalingMatrix8, 16, sizeof(ptSps->aau8ScalingMatrix8));
    ptSps->iScalingMatrixPresent = 0;
    ptSps->tColorspace = 2; //AVCOL_SPC_UNSPECIFIED

    if (ptSps->iProfileIdc == 100 ||  // High profile
        ptSps->iProfileIdc == 110 ||  // High10 profile
        ptSps->iProfileIdc == 122 ||  // High422 profile
        ptSps->iProfileIdc == 244 ||  // High444 Predictive profile
        ptSps->iProfileIdc ==  44 ||  // Cavlc444 profile
        ptSps->iProfileIdc ==  83 ||  // Scalable Constrained High profile (SVC)
        ptSps->iProfileIdc ==  86 ||  // Scalable High Intra profile (SVC)
        ptSps->iProfileIdc == 118 ||  // Stereo High profile (MVC)
        ptSps->iProfileIdc == 128 ||  // Multiview High profile (MVC)
        ptSps->iProfileIdc == 138 ||  // Multiview Depth High profile (MVCD)
        ptSps->iProfileIdc == 144) {  // old High444 profile
        ptSps->iChromaFormatIdc = parseUe(pvBuf);
        if (ptSps->iChromaFormatIdc > 3U)
913
        {
xzl committed
914
            RPT(RPT_ERR, "iChromaFormatIdc %u",ptSps->iChromaFormatIdc);
915 916
            iRet = -1;
            goto exit;
xzl committed
917
        }
918 919
        else if (ptSps->iChromaFormatIdc == 3)
        {
xzl committed
920 921
            ptSps->iResidualColorTransformFlag = getOneBit(pvBuf);
            if (ptSps->iResidualColorTransformFlag)
922 923 924 925
            {
                RPT(RPT_ERR, "separate color planes are not supported\n");
                iRet = -1;
                goto exit;
xzl committed
926 927 928 929 930 931

            }
        }
        ptSps->iBitDepthLuma   = parseUe(pvBuf) + 8;
        ptSps->iBitDepthChroma = parseUe(pvBuf) + 8;
        if (ptSps->iBitDepthChroma != ptSps->iBitDepthLuma)
932 933 934 935
        {
            RPT(RPT_ERR, "Different chroma and luma bit depth");
            iRet = -1;
            goto exit;
xzl committed
936 937 938 939 940

        }
        if (ptSps->iBitDepthLuma   < 8 || ptSps->iBitDepthLuma   > 14 ||
            ptSps->iBitDepthChroma < 8 || ptSps->iBitDepthChroma > 14)
        {
941 942 943
            RPT(RPT_ERR, "illegal bit depth value (%d, %d)\n",ptSps->iBitDepthLuma, ptSps->iBitDepthChroma);
            iRet = -1;
            goto exit;
xzl committed
944 945 946 947 948
        }
        ptSps->iTransformBypass = getOneBit(pvBuf);
        decodeScalingMatrices(pvBuf, ptSps, NULL, 1,
                                ptSps->aau8ScalingMatrix4, ptSps->aau8ScalingMatrix8);
    }
949 950
    else
    {
xzl committed
951 952 953 954 955 956 957 958 959 960 961

        ptSps->iChromaFormatIdc = 1;
        ptSps->iBitDepthLuma    = 8;
        ptSps->iBitDepthChroma  = 8;
    }

    iLog2MaxFrameNumMinus4 = parseUe(pvBuf);

    if (iLog2MaxFrameNumMinus4 < MIN_LOG2_MAX_FRAME_NUM - 4 ||
        iLog2MaxFrameNumMinus4 > MAX_LOG2_MAX_FRAME_NUM - 4)
    {
962 963 964
        RPT(RPT_ERR, "iLog2MaxFrameNumMinus4 out of range (0-12): %d\n", iLog2MaxFrameNumMinus4);
        iRet = -1;
        goto exit;
xzl committed
965 966 967 968 969 970 971

    }
    ptSps->iLog2MaxFrameNum = iLog2MaxFrameNumMinus4 + 4;

    ptSps->iPocType = parseUe(pvBuf);

    if (ptSps->iPocType == 0)
972 973
    {
        // FIXME #define
xzl committed
974 975
        unsigned t = parseUe(pvBuf);
        if (t>12)
976 977 978 979
        {
            RPT(RPT_ERR, "iLog2MaxPocLsb (%d) is out of range\n", t);
            iRet = -1;
            goto exit;
xzl committed
980 981 982 983

        }
        ptSps->iLog2MaxPocLsb = t + 4;
    }
984 985 986
    else if (ptSps->iPocType == 1)
    {
        // FIXME #define
xzl committed
987 988 989 990 991 992 993
        ptSps->iDeltaPicOrderAlwaysZeroFlag = getOneBit(pvBuf);
        ptSps->iOffsetForNonRefPic           = parseSe(pvBuf);
        ptSps->iOffsetForTopToBottomField   = parseSe(pvBuf);
        ptSps->iPocCycleLength                 = parseUe(pvBuf);

        if ((unsigned)ptSps->iPocCycleLength >= FF_ARRAY_ELEMS(ptSps->asOffsetForRefFrame))
        {
994 995 996
            RPT(RPT_ERR, "iPocCycleLength overflow %d\n", ptSps->iPocCycleLength);
            iRet = -1;
            goto exit;
xzl committed
997 998 999 1000 1001 1002

        }

        for (i = 0; i < ptSps->iPocCycleLength; i++)
            ptSps->asOffsetForRefFrame[i] = parseSe(pvBuf);
    }
1003 1004 1005 1006 1007
    else if (ptSps->iPocType != 2)
    {
        RPT(RPT_ERR, "illegal POC type %d\n", ptSps->iPocType);
        iRet = -1;
        goto exit;
xzl committed
1008 1009 1010 1011 1012 1013 1014

    }

    ptSps->iRefFrameCount = parseUe(pvBuf);
    if (ptSps->iRefFrameCount > H264_MAX_PICTURE_COUNT - 2 ||
        ptSps->iRefFrameCount > 16U)
    {
1015 1016 1017
        RPT(RPT_ERR, "too many reference frames %d\n", ptSps->iRefFrameCount);
        iRet = -1;
        goto exit;
xzl committed
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038

    }
    ptSps->iGapsInFrameNumAllowedFlag = getOneBit(pvBuf);
    ptSps->iMbWidth                       = parseUe(pvBuf) + 1;
    ptSps->iMbHeight                      = parseUe(pvBuf) + 1;


    ptSps->iFrameMbsOnlyFlag = getOneBit(pvBuf);
    if (!ptSps->iFrameMbsOnlyFlag)
        ptSps->iMbAff = getOneBit(pvBuf);
    else
        ptSps->iMbAff = 0;

    ptSps->iDirect8x8InferenceFlag = getOneBit(pvBuf);

    ptSps->iCrop = getOneBit(pvBuf);
    if (ptSps->iCrop) {
        unsigned int uiCropLeft   = parseUe(pvBuf);
        unsigned int uiCropRight  = parseUe(pvBuf);
        unsigned int uiCropTop    = parseUe(pvBuf);
        unsigned int uiCropBottom = parseUe(pvBuf);
1039 1040
        int iWidth  = 16 * ptSps->iMbWidth;
        int iHeight = 16 * ptSps->iMbHeight * (2 - ptSps->iFrameMbsOnlyFlag);
xzl committed
1041

1042 1043
        if(1)
        {
xzl committed
1044 1045 1046 1047 1048 1049 1050
            int vsub   = (ptSps->iChromaFormatIdc == 1) ? 1 : 0;
            int hsub   = (ptSps->iChromaFormatIdc == 1 ||
                          ptSps->iChromaFormatIdc == 2) ? 1 : 0;
            int step_x = 1 << hsub;
            int step_y = (2 - ptSps->iFrameMbsOnlyFlag) << vsub;

            if (uiCropLeft & (0x1F >> (ptSps->iBitDepthLuma > 8)))
1051
            {
xzl committed
1052 1053 1054 1055 1056 1057 1058
                uiCropLeft &= ~(0x1F >> (ptSps->iBitDepthLuma > 8));
            }

            if (uiCropLeft  > (unsigned)INT_MAX / 4 / step_x ||
                uiCropRight > (unsigned)INT_MAX / 4 / step_x ||
                uiCropTop   > (unsigned)INT_MAX / 4 / step_y ||
                uiCropBottom> (unsigned)INT_MAX / 4 / step_y ||
1059 1060
                (uiCropLeft + uiCropRight ) * step_x >= iWidth ||
                (uiCropTop  + uiCropBottom) * step_y >= iHeight
xzl committed
1061 1062
            )
            {
1063 1064 1065
                RPT(RPT_ERR, "crop values invalid %d %d %d %d / %d %d\n", uiCropLeft, uiCropRight, uiCropTop, uiCropBottom, iWidth, iHeight);
                iRet = -1;
                goto exit;
xzl committed
1066 1067 1068 1069 1070 1071 1072 1073
            }

            ptSps->uiCropLeft   = uiCropLeft   * step_x;
            ptSps->uiCropRight  = uiCropRight  * step_x;
            ptSps->uiCropTop    = uiCropTop    * step_y;
            ptSps->uiCropBottom = uiCropBottom * step_y;
        }
    }
1074 1075
    else
    {
xzl committed
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
        ptSps->uiCropLeft   =
        ptSps->uiCropRight  =
        ptSps->uiCropTop    =
        ptSps->uiCropBottom =
        ptSps->iCrop        = 0;
    }

    ptSps->iVuiParametersPresentFlag = getOneBit(pvBuf);
    if (ptSps->iVuiParametersPresentFlag) {
        int ret = decodeVuiParameters(pvBuf, ptSps);
        if (ret < 0)
            goto exit;
    }

    if (getBitsLeft(pvBuf) < 0)
1091 1092 1093
    {
        RPT(RPT_ERR, "Overread %s by %d bits\n", ptSps->iVuiParametersPresentFlag ? "VUI" : "SPS", -getBitsLeft(pvBuf));
        iRet = -1;
xzl committed
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
    }

    if (!ptSps->tSar.den)
        ptSps->tSar.den = 1;

    ptSps->iNew = 1;

exit:
#ifdef SPS_PPS_DEBUG

    if (1)
1105
    {
xzl committed
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
        static const char csp[4][5] = { "Gray", "420", "422", "444" };
        RPT(RPT_DBG,
               "ptSps:%u profile:%d/%d poc:%d ref:%d %dx%d %s %s crop:%u/%u/%u/%u %s %s %d/%d b%d reo:%d\n",
               uiSpsId, ptSps->iProfileIdc, ptSps->iLevelIdc,
               ptSps->iPocType,
               ptSps->iRefFrameCount,
               ptSps->iMbWidth, ptSps->iMbHeight,
               ptSps->iFrameMbsOnlyFlag ? "FRM" : (ptSps->iMbAff ? "MB-AFF" : "PIC-AFF"),
               ptSps->iDirect8x8InferenceFlag ? "8B8" : "",
               ptSps->uiCropLeft, ptSps->uiCropRight,
               ptSps->uiCropTop, ptSps->uiCropBottom,
               ptSps->iVuiParametersPresentFlag ? "VUI" : "",
               csp[ptSps->iChromaFormatIdc],
               ptSps->iTimingInfoPresentFlag ? ptSps->u32NumUnitsInTick : 0,
               ptSps->iTimingInfoPresentFlag ? ptSps->u32TimeScale : 0,
               ptSps->iBitDepthLuma,
               ptSps->iBitstreamRestrictionFlag ? ptSps->iNumReorderFrames : -1
               );
    }

#endif
    getBitContextFree(pvBuf);

    return iRet;
}

zqsong committed
1132

1133
static int decodeProfileTierLevel(T_GetBitContext *pvBuf, T_PTLCommon *tPtl)
zqsong committed
1134 1135 1136 1137 1138 1139
{
    int i;

    if (getBitsLeft(pvBuf) < 2+1+5 + 32 + 4 + 16 + 16 + 12)
        return -1;

1140 1141 1142 1143
    tPtl->u8ProfileSpace = getBits(pvBuf, 2);
    tPtl->u8TierFlag     = getOneBit(pvBuf);
    tPtl->u8ProfileIdc   = getBits(pvBuf, 5);
    if (tPtl->u8ProfileIdc == T_PROFILE_HEVC_MAIN)
zqsong committed
1144
        RPT(RPT_DBG, "Main profile bitstream\n");
1145
    else if (tPtl->u8ProfileIdc == T_PROFILE_HEVC_MAIN_10)
zqsong committed
1146
        RPT(RPT_DBG, "Main 10 profile bitstream\n");
1147
    else if (tPtl->u8ProfileIdc == T_PROFILE_HEVC_MAIN_STILL_PICTURE)
zqsong committed
1148
        RPT(RPT_DBG, "Main Still Picture profile bitstream\n");
1149
    else if (tPtl->u8ProfileIdc == T_PROFILE_HEVC_REXT)
zqsong committed
1150 1151
        RPT(RPT_DBG, "Range Extension profile bitstream\n");
    else
1152
        RPT(RPT_WRN, "Unknown HEVC profile: %d\n", tPtl->u8ProfileIdc);
zqsong committed
1153 1154

    for (i = 0; i < 32; i++) {
1155
        tPtl->au8ProfileCompatibilityFlag[i] = getOneBit(pvBuf);
zqsong committed
1156

1157 1158
        if (tPtl->u8ProfileIdc == 0 && i > 0 && tPtl->au8ProfileCompatibilityFlag[i])
            tPtl->u8ProfileIdc = i;
zqsong committed
1159
    }
1160 1161 1162 1163
    tPtl->u8ProgressiveSourceFlag    = getOneBit(pvBuf);
    tPtl->u8InterlacedSourceFlag     = getOneBit(pvBuf);
    tPtl->u8NonPackedConstraintFlag  = getOneBit(pvBuf);
    tPtl->u8FrameOnlyConstraintFlag  = getOneBit(pvBuf);
zqsong committed
1164 1165 1166 1167 1168 1169 1170

    getBits(pvBuf, 16); // XXX_reserved_zero_44bits[0..15]
    getBits(pvBuf, 16); // XXX_reserved_zero_44bits[16..31]
    getBits(pvBuf, 12); // XXX_reserved_zero_44bits[32..43]

    return 0;
}
1171
                                      
zqsong committed
1172

1173
static int parsePtl(T_GetBitContext *pvBuf, T_PTL *tPtl, int max_num_sub_layers)
zqsong committed
1174 1175
{
    int i;
1176
    if (decodeProfileTierLevel(pvBuf, &tPtl->tGeneralPtl) < 0 ||
zqsong committed
1177 1178 1179 1180 1181
        getBitsLeft(pvBuf) < 8 + (8*2 * (max_num_sub_layers - 1 > 0))) {
        RPT(RPT_ERR, "PTL information too short\n");
        return -1;
    }

1182
    tPtl->tGeneralPtl.u8LevelIdc = getBits(pvBuf, 8);
zqsong committed
1183 1184

    for (i = 0; i < max_num_sub_layers - 1; i++) {
1185 1186
        tPtl->au8SubLayerProfilePresentFlag[i] = getOneBit(pvBuf);
        tPtl->au8SubLayerLevelPresentFlag[i]   = getOneBit(pvBuf);
zqsong committed
1187 1188 1189 1190 1191 1192
    }

    if (max_num_sub_layers - 1> 0)
        for (i = max_num_sub_layers - 1; i < 8; i++)
            getBits(pvBuf, 2); // reserved_zero_2bits[i]
    for (i = 0; i < max_num_sub_layers - 1; i++) {
1193 1194
        if (tPtl->au8SubLayerProfilePresentFlag[i] &&
            decodeProfileTierLevel(pvBuf, &tPtl->atSubLayerPtl[i]) < 0) {
zqsong committed
1195 1196 1197 1198
            RPT(RPT_ERR,
                   "PTL information for sublayer %i too short\n", i);
            return -1;
        }
1199
        if (tPtl->au8SubLayerLevelPresentFlag[i]) {
zqsong committed
1200 1201 1202 1203 1204
            if (getBitsLeft(pvBuf) < 8) {
                RPT(RPT_ERR,
                       "Not enough data for sublayer %i level_idc\n", i);
                return -1;
            } else
1205
                tPtl->atSubLayerPtl[i].u8LevelIdc = getBits(pvBuf, 8);
zqsong committed
1206 1207 1208 1209 1210
        }
    }

    return 0;
}
1211
                      
zqsong committed
1212 1213 1214 1215 1216 1217 1218

static void setDefaultScalingListData(T_ScalingList *sl)
{
    int matrixId;

    for (matrixId = 0; matrixId < 6; matrixId++) {
        // 4x4 default is 16
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
        memset(sl->aaau8Sl[0][matrixId], 16, 16);
        sl->aau8SlDc[0][matrixId] = 16; // default for 16x16
        sl->aau8SlDc[1][matrixId] = 16; // default for 32x32
    }
    memcpy(sl->aaau8Sl[1][0], sg_au8DefaultScalingListIntra, 64);
    memcpy(sl->aaau8Sl[1][1], sg_au8DefaultScalingListIntra, 64);
    memcpy(sl->aaau8Sl[1][2], sg_au8DefaultScalingListIntra, 64);
    memcpy(sl->aaau8Sl[1][3], sg_au8DefaultScalingListInter, 64);
    memcpy(sl->aaau8Sl[1][4], sg_au8DefaultScalingListInter, 64);
    memcpy(sl->aaau8Sl[1][5], sg_au8DefaultScalingListInter, 64);
    memcpy(sl->aaau8Sl[2][0], sg_au8DefaultScalingListIntra, 64);
    memcpy(sl->aaau8Sl[2][1], sg_au8DefaultScalingListIntra, 64);
    memcpy(sl->aaau8Sl[2][2], sg_au8DefaultScalingListIntra, 64);
    memcpy(sl->aaau8Sl[2][3], sg_au8DefaultScalingListInter, 64);
    memcpy(sl->aaau8Sl[2][4], sg_au8DefaultScalingListInter, 64);
    memcpy(sl->aaau8Sl[2][5], sg_au8DefaultScalingListInter, 64);
    memcpy(sl->aaau8Sl[3][0], sg_au8DefaultScalingListIntra, 64);
    memcpy(sl->aaau8Sl[3][1], sg_au8DefaultScalingListIntra, 64);
    memcpy(sl->aaau8Sl[3][2], sg_au8DefaultScalingListIntra, 64);
    memcpy(sl->aaau8Sl[3][3], sg_au8DefaultScalingListInter, 64);
    memcpy(sl->aaau8Sl[3][4], sg_au8DefaultScalingListInter, 64);
    memcpy(sl->aaau8Sl[3][5], sg_au8DefaultScalingListInter, 64);
zqsong committed
1241 1242
}

1243
static int scalingListData(T_GetBitContext *pvBuf, T_ScalingList *sl, T_HEVCSPS *ptSps)
zqsong committed
1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
{
    uint8_t scaling_list_pred_mode_flag;
    int32_t scaling_list_dc_coef[2][6];
    int size_id, matrix_id, pos;
    int i;

    for (size_id = 0; size_id < 4; size_id++)
        for (matrix_id = 0; matrix_id < 6; matrix_id += ((size_id == 3) ? 3 : 1)) {
            scaling_list_pred_mode_flag = getOneBit(pvBuf);
            if (!scaling_list_pred_mode_flag) {
                unsigned int delta = parseUe(pvBuf);
                /* Only need to handle non-zero delta. Zero means default,
                 * which should already be in the arrays. */
                if (delta) {
                    // Copy from previous array.
                    delta *= (size_id == 3) ? 3 : 1;
                    if (matrix_id < delta) {
                        RPT(RPT_ERR,
                               "Invalid delta in scaling list data: %d.\n", delta);
                        return -1;
                    }

1266 1267
                    memcpy(sl->aaau8Sl[size_id][matrix_id],
                           sl->aaau8Sl[size_id][matrix_id - delta],
zqsong committed
1268 1269
                           size_id > 0 ? 64 : 16);
                    if (size_id > 1)
1270
                        sl->aau8SlDc[size_id - 2][matrix_id] = sl->aau8SlDc[size_id - 2][matrix_id - delta];
zqsong committed
1271 1272 1273 1274 1275 1276 1277 1278 1279 1280
                }
            } else {
                int next_coef, coef_num;
                int32_t scaling_list_delta_coef;

                next_coef = 8;
                coef_num  = FFMIN(64, 1 << (4 + (size_id << 1)));
                if (size_id > 1) {
                    scaling_list_dc_coef[size_id - 2][matrix_id] = parseSe(pvBuf) + 8;
                    next_coef = scaling_list_dc_coef[size_id - 2][matrix_id];
1281
                    sl->aau8SlDc[size_id - 2][matrix_id] = next_coef;
zqsong committed
1282 1283 1284
                }
                for (i = 0; i < coef_num; i++) {
                    if (size_id == 0)
1285 1286
                        pos = 4 * g_au8HevcDiagScan4x4Y[i] +
                                  g_au8HevcDiagScan4x4X[i];
zqsong committed
1287
                    else
1288 1289
                        pos = 8 * g_au8HevcDiagScan8x8Y[i] +
                                  g_au8HevcDiagScan8x8X[i];
zqsong committed
1290 1291 1292

                    scaling_list_delta_coef = parseSe(pvBuf);
                    next_coef = (next_coef + 256U + scaling_list_delta_coef) % 256;
1293
                    sl->aaau8Sl[size_id][matrix_id][pos] = next_coef;
zqsong committed
1294 1295 1296 1297
                }
            }
        }

1298
    if (ptSps->iChromaFormatIdc == 3) {
zqsong committed
1299
        for (i = 0; i < 64; i++) {
1300 1301 1302 1303
            sl->aaau8Sl[3][1][i] = sl->aaau8Sl[2][1][i];
            sl->aaau8Sl[3][2][i] = sl->aaau8Sl[2][2][i];
            sl->aaau8Sl[3][4][i] = sl->aaau8Sl[2][4][i];
            sl->aaau8Sl[3][5][i] = sl->aaau8Sl[2][5][i];
zqsong committed
1304
        }
1305 1306 1307 1308
        sl->aau8SlDc[1][1] = sl->aau8SlDc[0][1];
        sl->aau8SlDc[1][2] = sl->aau8SlDc[0][2];
        sl->aau8SlDc[1][4] = sl->aau8SlDc[0][4];
        sl->aau8SlDc[1][5] = sl->aau8SlDc[0][5];
zqsong committed
1309 1310 1311 1312 1313 1314 1315
    }


    return 0;
}

int hevcDecodeShortTermRps(T_GetBitContext *pvBuf,
1316
                                  T_ShortTermRPS *rps, const T_HEVCSPS *ptSps, int is_slice_header)
zqsong committed
1317 1318
{
    uint8_t rps_predict = 0;
1319
    int au32DeltaPoc;
zqsong committed
1320 1321 1322 1323 1324
    int k0 = 0;
    int k1 = 0;
    int k  = 0;
    int i;

1325
    if (rps != ptSps->atStRps && ptSps->uiNbStRps)
zqsong committed
1326 1327 1328
        rps_predict = getOneBit(pvBuf);

    if (rps_predict) {
1329 1330 1331 1332
        const T_ShortTermRPS *ptRpsRidx;
        int iDeltaRps;
        unsigned int uiAbsDeltaRps;
        uint8_t u8UseDeltaFlag = 0;
1333
        uint8_t u8DeltaRpsSign = 0;
zqsong committed
1334 1335

        if (is_slice_header) {
1336 1337
            unsigned int uiDeltaIdx = parseUe(pvBuf) + 1;
            if (u8DeltaRpsSign > ptSps->uiNbStRps) {
zqsong committed
1338 1339
                RPT(RPT_ERR,
                       "Invalid value of delta_idx in slice header RPS: %d > %d.\n",
1340
                       u8DeltaRpsSign, ptSps->uiNbStRps);
zqsong committed
1341 1342
                return -1;
            }
1343 1344
            ptRpsRidx = &ptSps->atStRps[ptSps->uiNbStRps - u8DeltaRpsSign];
            rps->iRpsIdxNumDeltaPocs = ptRpsRidx->iNumDeltaPocs;
zqsong committed
1345
        } else
1346
            ptRpsRidx = &ptSps->atStRps[rps - ptSps->atStRps - 1];
zqsong committed
1347

1348 1349 1350
        u8DeltaRpsSign = getOneBit(pvBuf);
        uiAbsDeltaRps  = parseUe(pvBuf) + 1;
        if (uiAbsDeltaRps < 1 || uiAbsDeltaRps > 32768) {
zqsong committed
1351
            RPT(RPT_ERR,
1352 1353
                   "Invalid value of uiAbsDeltaRps: %d\n",
                   uiAbsDeltaRps);
zqsong committed
1354 1355
            return -1;
        }
1356 1357 1358
        iDeltaRps      = (1 - (u8DeltaRpsSign << 1)) * uiAbsDeltaRps;
        for (i = 0; i <= ptRpsRidx->iNumDeltaPocs; i++) {
            int used = rps->au8Used[k] = getOneBit(pvBuf);
zqsong committed
1359 1360

            if (!used)
1361
                u8UseDeltaFlag = getOneBit(pvBuf);
zqsong committed
1362

1363 1364 1365
            if (used || u8UseDeltaFlag) {
                if (i < ptRpsRidx->iNumDeltaPocs)
                    au32DeltaPoc = iDeltaRps + ptRpsRidx->au32DeltaPoc[i];
zqsong committed
1366
                else
1367 1368 1369
                    au32DeltaPoc = iDeltaRps;
                rps->au32DeltaPoc[k] = au32DeltaPoc;
                if (au32DeltaPoc < 0)
zqsong committed
1370 1371 1372 1373 1374 1375 1376
                    k0++;
                else
                    k1++;
                k++;
            }
        }

1377
        if (k >= FF_ARRAY_ELEMS(rps->au8Used)) {
zqsong committed
1378
            RPT(RPT_ERR,
1379
                   "Invalid iNumDeltaPocs: %d\n", k);
zqsong committed
1380 1381 1382
            return -1;
        }

1383 1384
        rps->iNumDeltaPocs    = k;
        rps->uiNumNegativePics = k0;
zqsong committed
1385
        // sort in increasing order (smallest first)
1386
        if (rps->iNumDeltaPocs != 0) {
zqsong committed
1387
            int used, tmp;
1388 1389 1390
            for (i = 1; i < rps->iNumDeltaPocs; i++) {
                au32DeltaPoc = rps->au32DeltaPoc[i];
                used      = rps->au8Used[i];
zqsong committed
1391
                for (k = i - 1; k >= 0; k--) {
1392 1393 1394 1395 1396 1397
                    tmp = rps->au32DeltaPoc[k];
                    if (au32DeltaPoc < tmp) {
                        rps->au32DeltaPoc[k + 1] = tmp;
                        rps->au8Used[k + 1]      = rps->au8Used[k];
                        rps->au32DeltaPoc[k]     = au32DeltaPoc;
                        rps->au8Used[k]          = used;
zqsong committed
1398 1399 1400 1401
                    }
                }
            }
        }
1402
        if ((rps->uiNumNegativePics >> 1) != 0) {
zqsong committed
1403
            int used;
1404
            k = rps->uiNumNegativePics - 1;
zqsong committed
1405
            // flip the negative values to largest first
1406 1407 1408 1409 1410 1411 1412
            for (i = 0; i < rps->uiNumNegativePics >> 1; i++) {
                au32DeltaPoc         = rps->au32DeltaPoc[i];
                used              = rps->au8Used[i];
                rps->au32DeltaPoc[i] = rps->au32DeltaPoc[k];
                rps->au8Used[i]      = rps->au8Used[k];
                rps->au32DeltaPoc[k] = au32DeltaPoc;
                rps->au8Used[k]      = used;
zqsong committed
1413 1414 1415 1416
                k--;
            }
        }
    } else {
1417 1418 1419
        unsigned int uiPrev, uiNbPositivePics;
        rps->uiNumNegativePics = parseUe(pvBuf);
        uiNbPositivePics       = parseUe(pvBuf);
zqsong committed
1420

1421 1422
        if (rps->uiNumNegativePics >= HEVC_MAX_REFS ||
            uiNbPositivePics >= HEVC_MAX_REFS) {
zqsong committed
1423 1424 1425 1426
            RPT(RPT_ERR, "Too many refs in a short term RPS.\n");
            return -1;
        }

1427 1428 1429 1430 1431 1432
        rps->iNumDeltaPocs = rps->uiNumNegativePics + uiNbPositivePics;
        if (rps->iNumDeltaPocs) {
            uiPrev = 0;
            for (i = 0; i < rps->uiNumNegativePics; i++) {
                au32DeltaPoc = parseUe(pvBuf) + 1;
                if (au32DeltaPoc < 1 || au32DeltaPoc > 32768) {
zqsong committed
1433
                    RPT(RPT_ERR,
1434 1435
                        "Invalid value of au32DeltaPoc: %d\n",
                        au32DeltaPoc);
zqsong committed
1436 1437
                    return -1;
                }
1438 1439 1440
                uiPrev -= au32DeltaPoc;
                rps->au32DeltaPoc[i] = uiPrev;
                rps->au8Used[i]      = getOneBit(pvBuf);
zqsong committed
1441
            }
1442 1443 1444 1445
            uiPrev = 0;
            for (i = 0; i < uiNbPositivePics; i++) {
                au32DeltaPoc = parseUe(pvBuf) + 1;
                if (au32DeltaPoc < 1 || au32DeltaPoc > 32768) {
zqsong committed
1446
                    RPT(RPT_ERR,
1447 1448
                        "Invalid value of au32DeltaPoc: %d\n",
                        au32DeltaPoc);
zqsong committed
1449 1450
                    return -1;
                }
1451 1452 1453
                uiPrev += au32DeltaPoc;
                rps->au32DeltaPoc[rps->uiNumNegativePics + i] = uiPrev;
                rps->au8Used[rps->uiNumNegativePics + i]      = getOneBit(pvBuf);
zqsong committed
1454 1455 1456 1457 1458 1459 1460
            }
        }
    }
    return 0;
}

static void decodeSublayerHrd(T_GetBitContext *pvBuf, unsigned int nb_cpb,
1461
                                int iSubpicParamsPresent)
zqsong committed
1462 1463 1464 1465 1466 1467 1468
{
    int i;

    for (i = 0; i < nb_cpb; i++) {
        parseUe(pvBuf); // bit_rate_value_minus1
        parseUe(pvBuf); // cpb_size_value_minus1

1469
        if (iSubpicParamsPresent) {
zqsong committed
1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
            parseUe(pvBuf); // cpb_size_du_value_minus1
            parseUe(pvBuf); // bit_rate_du_value_minus1
        }
        getOneBit(pvBuf); // cbr_flag
    }
}

static int decodeHrd(T_GetBitContext *pvBuf, int common_inf_present,
                       int max_sublayers)
{
1480 1481
    int iNalParamsPresent = 0, iVclParamsPresent = 0;
    int iSubpicParamsPresent = 0;
zqsong committed
1482 1483 1484
    int i;

    if (common_inf_present) {
1485 1486
        iNalParamsPresent = getOneBit(pvBuf);
        iVclParamsPresent = getOneBit(pvBuf);
zqsong committed
1487

1488 1489
        if (iNalParamsPresent || iVclParamsPresent) {
            iSubpicParamsPresent = getOneBit(pvBuf);
zqsong committed
1490

1491
            if (iSubpicParamsPresent) {
zqsong committed
1492 1493 1494 1495 1496 1497 1498 1499 1500
                getBits(pvBuf, 8); // tick_divisor_minus2
                getBits(pvBuf, 5); // du_cpb_removal_delay_increment_length_minus1
                getBits(pvBuf, 1); // sub_pic_cpb_params_in_pic_timing_sei_flag
                getBits(pvBuf, 5); // dpb_output_delay_du_length_minus1
            }

            getBits(pvBuf, 4); // bit_rate_scale
            getBits(pvBuf, 4); // cpb_size_scale

1501
            if (iSubpicParamsPresent)
zqsong committed
1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512
                getBits(pvBuf, 4);  // cpb_size_du_scale

            getBits(pvBuf, 5); // initial_cpb_removal_delay_length_minus1
            getBits(pvBuf, 5); // au_cpb_removal_delay_length_minus1
            getBits(pvBuf, 5); // dpb_output_delay_length_minus1
        }
    }

    for (i = 0; i < max_sublayers; i++) {
        int low_delay = 0;
        unsigned int nb_cpb = 1;
1513
        int iFixedRate = getOneBit(pvBuf);
zqsong committed
1514

1515 1516
        if (!iFixedRate)
            iFixedRate = getOneBit(pvBuf);
zqsong committed
1517

1518
        if (iFixedRate)
zqsong committed
1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530
            parseUe(pvBuf);  // elemental_duration_in_tc_minus1
        else
            low_delay = getOneBit(pvBuf);

        if (!low_delay) {
            nb_cpb = parseUe(pvBuf) + 1;
            if (nb_cpb < 1 || nb_cpb > 32) {
                RPT(RPT_ERR, "nb_cpb %d invalid\n", nb_cpb);
                return -1;
            }
        }

1531 1532 1533 1534
        if (iNalParamsPresent)
            decodeSublayerHrd(pvBuf, nb_cpb, iSubpicParamsPresent);
        if (iVclParamsPresent)
            decodeSublayerHrd(pvBuf, nb_cpb, iSubpicParamsPresent);
zqsong committed
1535 1536 1537 1538
    }
    return 0;
}

1539
                       
zqsong committed
1540

1541
static void decodeVui(T_GetBitContext *pvBuf, T_HEVCSPS *ptSps)
zqsong committed
1542
{
1543 1544
    T_VUI tBackupVui, *tVui = &ptSps->tVui;
    T_GetBitContext tBackup;
zqsong committed
1545 1546 1547 1548 1549 1550 1551
    int sar_present, alt = 0;

    RPT(RPT_DBG, "Decoding VUI\n");

    sar_present = getOneBit(pvBuf);
    if (sar_present) {
        uint8_t sar_idx = getBits(pvBuf, 8);
1552 1553
        if (sar_idx < FF_ARRAY_ELEMS(sg_atVuiSar))
            tVui->tSar = sg_atVuiSar[sar_idx];
zqsong committed
1554
        else if (sar_idx == 255) {
1555 1556
            tVui->tSar.num = getBits(pvBuf, 16);
            tVui->tSar.den = getBits(pvBuf, 16);
zqsong committed
1557 1558 1559 1560 1561
        } else
            RPT(RPT_WRN,
                   "Unknown SAR index: %u.\n", sar_idx);
    }

1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576
    tVui->iOverscanInfoPresentFlag = getOneBit(pvBuf);
    if (tVui->iOverscanInfoPresentFlag)
        tVui->iOverscanAppropriateFlag = getOneBit(pvBuf);

    tVui->iVideoSignalTypePresentFlag = getOneBit(pvBuf);
    if (tVui->iVideoSignalTypePresentFlag) {
        tVui->iVideoFormat                    = getBits(pvBuf, 3);
        tVui->iVideoFullRangeFlag           = getOneBit(pvBuf);
        tVui->iColourDescriptionPresentFlag = getOneBit(pvBuf);
//        if (tVui->iVideoFullRangeFlag && ptSps->pix_fmt == AV_PIX_FMT_YUV420P)
//            ptSps->pix_fmt = AV_PIX_FMT_YUVJ420P;
        if (tVui->iColourDescriptionPresentFlag) {
            tVui->u8ColourPrimaries        = getBits(pvBuf, 8);
            tVui->u8TransferCharacteristic = getBits(pvBuf, 8);
            tVui->u8MatrixCoeffs           = getBits(pvBuf, 8);
zqsong committed
1577 1578 1579
        }
    }

1580 1581 1582 1583
    tVui->iChromaLocInfoPresentFlag = getOneBit(pvBuf);
    if (tVui->iChromaLocInfoPresentFlag) {
        tVui->iChromaSampleLocTypeTopField    = parseUe(pvBuf);
        tVui->iChromaSampleLocTypeBottomField = parseUe(pvBuf);
zqsong committed
1584 1585
    }

1586 1587 1588
    tVui->iNeutraChromaIndicationFlag = getOneBit(pvBuf);
    tVui->iFieldSeqFlag               = getOneBit(pvBuf);
    tVui->iFrameFieldInfoPresentFlag  = getOneBit(pvBuf);
zqsong committed
1589 1590

    // Backup context in case an alternate header is detected
1591 1592
    memcpy(&tBackup, pvBuf, sizeof(tBackup));
    memcpy(&tBackupVui, tVui, sizeof(tBackupVui));
zqsong committed
1593
    if (getBitsLeft(pvBuf) >= 68 && showBitsLong(pvBuf, 21) == 0x100000) {
1594
        tVui->iDefaultDisplayWindowFlag = 0;
zqsong committed
1595 1596
        RPT(RPT_WRN, "Invalid default display window\n");
    } else
1597
        tVui->iDefaultDisplayWindowFlag = getOneBit(pvBuf);
zqsong committed
1598

1599 1600 1601 1602 1603 1604 1605
    if (tVui->iDefaultDisplayWindowFlag) {
        int vert_mult  = sg_au8HevcSubHeightC[ptSps->iChromaFormatIdc];
        int horiz_mult = sg_au8HevcSubWidthC[ptSps->iChromaFormatIdc];
        tVui->tDefDispWin.uiLeftOffset   = parseUe(pvBuf) * horiz_mult;
        tVui->tDefDispWin.uiRightOffset  = parseUe(pvBuf) * horiz_mult;
        tVui->tDefDispWin.uiTopOffset    = parseUe(pvBuf) *  vert_mult;
        tVui->tDefDispWin.uiBottomOffset = parseUe(pvBuf) *  vert_mult;    
zqsong committed
1606 1607 1608
    }

timing_info:
1609
    tVui->iVuiTimingInfoPresentFlag = getOneBit(pvBuf);
zqsong committed
1610

1611
    if (tVui->iVuiTimingInfoPresentFlag) {
zqsong committed
1612 1613
        if( getBitsLeft(pvBuf) < 66 && !alt) {
            // The alternate syntax seem to have timing info located
1614
            // at where tDefDispWin is normally located
zqsong committed
1615 1616
            RPT(RPT_WRN,
                   "Strange VUI timing information, retrying...\n");
1617 1618
            memcpy(tVui, &tBackupVui, sizeof(tBackupVui));
            memcpy(pvBuf, &tBackup, sizeof(tBackup));
zqsong committed
1619 1620 1621
            alt = 1;
            goto timing_info;
        }
1622 1623
        tVui->u32VuiNumUnitsInTick               = getBits(pvBuf, 32);
        tVui->u32VuiTimeScale                      = getBits(pvBuf, 32);
zqsong committed
1624 1625
        if (alt) {
            RPT(RPT_INF, "Retry got %u/%u fps\n",
1626
                   tVui->u32VuiTimeScale, tVui->u32VuiNumUnitsInTick);
zqsong committed
1627
        }
1628 1629 1630 1631 1632 1633
        tVui->iVuiPocProportionalToTimingFlag = getOneBit(pvBuf);
        if (tVui->iVuiPocProportionalToTimingFlag)
            tVui->iVuiNumTicksPocDiffOneMinus1 = parseUe(pvBuf);
        tVui->iVuiHrdParametersPresentFlag = getOneBit(pvBuf);
        if (tVui->iVuiHrdParametersPresentFlag)
            decodeHrd(pvBuf, 1, ptSps->iMaxSubLayers);
zqsong committed
1634 1635
    }

1636 1637
    tVui->iBitstreamRestrictionFlag = getOneBit(pvBuf);
    if (tVui->iBitstreamRestrictionFlag) {
zqsong committed
1638 1639 1640 1641
        if (getBitsLeft(pvBuf) < 8 && !alt) {
            RPT(RPT_WRN,
                   "Strange VUI bitstream restriction information, retrying"
                   " from timing information...\n");
1642 1643
            memcpy(tVui, &tBackupVui, sizeof(tBackupVui));
            memcpy(pvBuf, &tBackup, sizeof(tBackup));
zqsong committed
1644 1645 1646
            alt = 1;
            goto timing_info;
        }
1647 1648 1649 1650 1651 1652 1653 1654
        tVui->iTilesFixedStructureFlag              = getOneBit(pvBuf);
        tVui->iMotionVectorsOverPicBoundariesFlag   = getOneBit(pvBuf);
        tVui->iRestrictedRefPicListsFlag            = getOneBit(pvBuf);
        tVui->iMinSpatialSegmentationIdc            = parseUe(pvBuf);
        tVui->iMaxBytesPerPicDenom                 = parseUe(pvBuf);
        tVui->iMaxBitsPerMinCuDenom               = parseUe(pvBuf);
        tVui->iLog2MaxMvLengthHorizontal           = parseUe(pvBuf);
        tVui->iLog2MaxMvLengthVertical             = parseUe(pvBuf);
zqsong committed
1655 1656 1657
    }

    if (getBitsLeft(pvBuf) < 1 && !alt) {
1658
        // XXX: Alternate syntax when iSpsRangeExtensionFlag != 0?
zqsong committed
1659 1660
        RPT(RPT_WRN,
               "Overread in VUI, retrying from timing information...\n");
1661 1662
        memcpy(tVui, &tBackupVui, sizeof(tBackupVui));
        memcpy(pvBuf, &tBackup, sizeof(tBackup));
zqsong committed
1663 1664 1665 1666 1667
        alt = 1;
        goto timing_info;
    }
}

1668 1669 1670 1671
static  unsigned avModUintp2c(unsigned a, unsigned p)
{
    return a & ((1 << p) - 1);
}
zqsong committed
1672 1673


1674
int h265DecSeqParameterSet( void *pvBufSrc, T_HEVCSPS *ptSps )
zqsong committed
1675 1676
{
    T_HEVCWindow *ow;
1677 1678
    int iLog2DiffMaxMinTransformBlockSize;
    int iBitDepthChroma, iStart, iVuiPresent, iSublayerOrderingInfo;
zqsong committed
1679 1680 1681 1682
    int i;
    int iRet = 0;

    void *pvBuf = NULL;
1683
    if(NULL == pvBufSrc || NULL == ptSps)
zqsong committed
1684 1685 1686 1687 1688 1689
    {
        RPT(RPT_ERR,"ERR null pointer\n");
        iRet = -1;
        goto exit;
    }

1690
    memset((void *)ptSps, 0, sizeof(T_HEVCSPS));
zqsong committed
1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701

    pvBuf = deEmulationPrevention(pvBufSrc);
    if(NULL == pvBuf)
    {
        RPT(RPT_ERR,"ERR null pointer\n");
        iRet = -1;
        goto exit;
    }

    // Coded parameters

1702 1703 1704
    ptSps->uiVpsId = getBits(pvBuf, 4);
    if (ptSps->uiVpsId >= HEVC_MAX_VPS_COUNT) {
        RPT(RPT_ERR, "VPS id out of range: %d\n", ptSps->uiVpsId);
1705 1706
        iRet = -1;
        goto exit;
zqsong committed
1707 1708
    }

1709 1710
    ptSps->iMaxSubLayers = getBits(pvBuf, 3) + 1;
    if (ptSps->iMaxSubLayers > HEVC_MAX_SUB_LAYERS) {
zqsong committed
1711
        RPT(RPT_ERR, "sps_max_sub_layers out of range: %d\n",
1712
               ptSps->iMaxSubLayers);
1713 1714
        iRet = -1;
        goto exit;
zqsong committed
1715 1716
    }

1717 1718
    ptSps->u8temporalIdNestingFlag = getBits(pvBuf, 1);
    if ((iRet = parsePtl(pvBuf, &ptSps->tPtl, ptSps->iMaxSubLayers)) < 0)
zqsong committed
1719 1720 1721 1722 1723
        goto exit;

    int sps_id = parseUe(pvBuf);
    if (sps_id >= HEVC_MAX_SPS_COUNT) {
        RPT(RPT_ERR, "SPS id out of range: %d\n", sps_id);
1724 1725
        iRet = -1;
        goto exit;
zqsong committed
1726 1727
    }

1728 1729 1730
    ptSps->iChromaFormatIdc = parseUe(pvBuf);
    if (ptSps->iChromaFormatIdc > 3U) {
        RPT(RPT_ERR, "iChromaFormatIdc %d is invalid\n", ptSps->iChromaFormatIdc);
1731 1732
        iRet = -1;
        goto exit;
zqsong committed
1733 1734
    }

1735 1736
    if (ptSps->iChromaFormatIdc == 3)
        ptSps->u8SeparateColourPlaneFlag = getOneBit(pvBuf);
zqsong committed
1737

1738 1739
    if (ptSps->u8SeparateColourPlaneFlag)
        ptSps->iChromaFormatIdc = 0;
zqsong committed
1740

1741 1742
    ptSps->iWidth  = parseUe(pvBuf);
    ptSps->iHeight = parseUe(pvBuf);
zqsong committed
1743 1744

    if (getOneBit(pvBuf)) { // pic_conformance_flag
1745 1746 1747 1748 1749 1750
        int vert_mult  = sg_au8HevcSubHeightC[ptSps->iChromaFormatIdc];
        int horiz_mult = sg_au8HevcSubWidthC[ptSps->iChromaFormatIdc];
        ptSps->tPicConfWin.uiLeftOffset   = parseUe(pvBuf) * horiz_mult;
        ptSps->tPicConfWin.uiRightOffset  = parseUe(pvBuf) * horiz_mult;
        ptSps->tPicConfWin.uiTopOffset    = parseUe(pvBuf) *  vert_mult;
        ptSps->tPicConfWin.uiBottomOffset = parseUe(pvBuf) *  vert_mult;
zqsong committed
1751

1752
        ptSps->tOutputWindow = ptSps->tPicConfWin;
zqsong committed
1753 1754
    }

1755 1756
    ptSps->iBitDepth   = parseUe(pvBuf) + 8;
    iBitDepthChroma = parseUe(pvBuf) + 8;
1757
    
1758
    if (ptSps->iChromaFormatIdc && iBitDepthChroma != ptSps->iBitDepth) {
zqsong committed
1759 1760 1761
        RPT(RPT_ERR,
               "Luma bit depth (%d) is different from chroma bit depth (%d), "
               "this is unsupported.\n",
1762
               ptSps->iBitDepth, iBitDepthChroma);
1763 1764
        iRet = -1;
        goto exit;
zqsong committed
1765
    }
1766
    ptSps->iBitDepthChroma = iBitDepthChroma;
zqsong committed
1767

1768 1769
    ptSps->uiLog2MaxPocLsb = parseUe(pvBuf) + 4;
    if (ptSps->uiLog2MaxPocLsb > 16) {
zqsong committed
1770
        RPT(RPT_ERR, "log2_max_pic_order_cnt_lsb_minus4 out range: %d\n",
1771
               ptSps->uiLog2MaxPocLsb - 4);
1772 1773
        iRet = -1;
        goto exit;
zqsong committed
1774 1775
    }

1776 1777 1778 1779 1780 1781 1782
    iSublayerOrderingInfo = getOneBit(pvBuf);
    iStart = iSublayerOrderingInfo ? 0 : ptSps->iMaxSubLayers - 1;
    for (i = iStart; i < ptSps->iMaxSubLayers; i++) {
        ptSps->stTemporalLayer[i].iMaxDecPicBuffering = parseUe(pvBuf) + 1;
        ptSps->stTemporalLayer[i].iNumReorderPics      = parseUe(pvBuf);
        ptSps->stTemporalLayer[i].iMaxLatencyIncrease  = parseUe(pvBuf) - 1;
        if (ptSps->stTemporalLayer[i].iMaxDecPicBuffering > (unsigned)HEVC_MAX_DPB_SIZE) {
zqsong committed
1783
            RPT(RPT_ERR, "sps_max_dec_pic_buffering_minus1 out of range: %d\n",
1784
                   ptSps->stTemporalLayer[i].iMaxDecPicBuffering - 1U);
1785 1786
            iRet = -1;
            goto exit;
zqsong committed
1787
        }
1788
        if (ptSps->stTemporalLayer[i].iNumReorderPics > ptSps->stTemporalLayer[i].iMaxDecPicBuffering - 1) {
zqsong committed
1789
            RPT(RPT_WRN, "sps_max_num_reorder_pics out of range: %d\n",
1790 1791
                   ptSps->stTemporalLayer[i].iNumReorderPics);
            if (ptSps->stTemporalLayer[i].iNumReorderPics > HEVC_MAX_DPB_SIZE - 1) {
1792 1793
                iRet = -1;
                goto exit;
zqsong committed
1794
            }
1795
            ptSps->stTemporalLayer[i].iMaxDecPicBuffering = ptSps->stTemporalLayer[i].iNumReorderPics + 1;
zqsong committed
1796 1797 1798
        }
    }

1799 1800 1801 1802 1803
    if (!iSublayerOrderingInfo) {
        for (i = 0; i < iStart; i++) {
            ptSps->stTemporalLayer[i].iMaxDecPicBuffering  = ptSps->stTemporalLayer[iStart].iMaxDecPicBuffering;
            ptSps->stTemporalLayer[i].iNumReorderPics      = ptSps->stTemporalLayer[iStart].iNumReorderPics;
            ptSps->stTemporalLayer[i].iMaxLatencyIncrease  = ptSps->stTemporalLayer[iStart].iMaxLatencyIncrease;
zqsong committed
1804 1805 1806
        }
    }

1807 1808 1809 1810 1811 1812
    ptSps->uiLog2MinCbSize                    = parseUe(pvBuf) + 3;
    ptSps->uiLog2DiffMaxMinCodingBlockSize    = parseUe(pvBuf);
    ptSps->uiLog2MinTbSize                    = parseUe(pvBuf) + 2;
    iLog2DiffMaxMinTransformBlockSize   	  = parseUe(pvBuf);
    ptSps->uiLog2MaxTrafoSize                 = iLog2DiffMaxMinTransformBlockSize +
                                               ptSps->uiLog2MinTbSize;
zqsong committed
1813

1814 1815
    if (ptSps->uiLog2MinCbSize < 3 || ptSps->uiLog2MinCbSize > 30) {
        RPT(RPT_ERR, "Invalid value %d for uiLog2MinCbSize", ptSps->uiLog2MinCbSize);
1816 1817
        iRet = -1;
        goto exit;
zqsong committed
1818 1819
    }

1820 1821
    if (ptSps->uiLog2DiffMaxMinCodingBlockSize > 30) {
        RPT(RPT_ERR, "Invalid value %d for uiLog2DiffMaxMinCodingBlockSize", ptSps->uiLog2DiffMaxMinCodingBlockSize);
1822 1823
        iRet = -1;
        goto exit;
zqsong committed
1824 1825
    }

1826 1827
    if (ptSps->uiLog2MinTbSize >= ptSps->uiLog2MinCbSize || ptSps->uiLog2MinTbSize < 2) {
        RPT(RPT_ERR, "Invalid value for uiLog2MinTbSize");
1828 1829
        iRet = -1;
        goto exit;
zqsong committed
1830 1831
    }

1832 1833
    if (iLog2DiffMaxMinTransformBlockSize < 0 || iLog2DiffMaxMinTransformBlockSize > 30) {
        RPT(RPT_ERR, "Invalid value %d for iLog2DiffMaxMinTransformBlockSize", iLog2DiffMaxMinTransformBlockSize);
1834 1835
        iRet = -1;
        goto exit;
zqsong committed
1836 1837
    }

1838 1839
    ptSps->iMaxTransformHierarchyDepthInter = parseUe(pvBuf);
    ptSps->iMaxTransformHierarchyDepthIntra = parseUe(pvBuf);
zqsong committed
1840

1841
    ptSps->u8ScalingListEnableFlag = getOneBit(pvBuf);
1842
    
1843 1844
    if (ptSps->u8ScalingListEnableFlag) {
        setDefaultScalingListData(&ptSps->tScalingList);
zqsong committed
1845 1846

        if (getOneBit(pvBuf)) {
1847
            iRet = scalingListData(pvBuf, &ptSps->tScalingList, ptSps);
zqsong committed
1848 1849 1850 1851 1852
            if (iRet < 0)
                goto exit;
        }
    }

1853 1854
    ptSps->u8AmpEnabledFlag = getOneBit(pvBuf);
    ptSps->u8SaoEnabled      = getOneBit(pvBuf);
zqsong committed
1855

1856
    ptSps->iPcmEnabledFlag = getOneBit(pvBuf);
1857
    
1858 1859 1860 1861 1862
    if (ptSps->iPcmEnabledFlag) {
        ptSps->pcm.u8BitDepth   = getBits(pvBuf, 4) + 1;
        ptSps->pcm.u8BitDepthChroma = getBits(pvBuf, 4) + 1;
        ptSps->pcm.uiLog2MinPcmCbSize = parseUe(pvBuf) + 3;
        ptSps->pcm.uiLog2MaxPcmCbSize = ptSps->pcm.uiLog2MinPcmCbSize +
zqsong committed
1863
                                        parseUe(pvBuf);
1864
        if (FFMAX(ptSps->pcm.u8BitDepth, ptSps->pcm.u8BitDepthChroma) > ptSps->iBitDepth) {
zqsong committed
1865 1866
            RPT(RPT_ERR,
                   "PCM bit depth (%d, %d) is greater than normal bit depth (%d)\n",
1867
                   ptSps->pcm.u8BitDepth, ptSps->pcm.u8BitDepthChroma, ptSps->iBitDepth);
1868 1869
            iRet = -1;
            goto exit;
zqsong committed
1870 1871
        }

1872
        ptSps->pcm.u8LoopFilterDisableFlag = getOneBit(pvBuf);
zqsong committed
1873 1874
    }

1875 1876
    ptSps->uiNbStRps = parseUe(pvBuf);
    if (ptSps->uiNbStRps > HEVC_MAX_SHORT_TERM_REF_PIC_SETS) {
zqsong committed
1877
        RPT(RPT_ERR, "Too many short term RPS: %d.\n",
1878
               ptSps->uiNbStRps);
1879 1880
        iRet = -1;
        goto exit;
zqsong committed
1881
    }
1882 1883 1884
    for (i = 0; i < ptSps->uiNbStRps; i++) {
        if ((iRet = hevcDecodeShortTermRps(pvBuf, &ptSps->atStRps[i],
                                                 ptSps, 0)) < 0)
zqsong committed
1885 1886 1887
            goto exit;
    }

1888 1889 1890 1891
    ptSps->u8LongTermRefPicsPresentFlag = getOneBit(pvBuf);
    if (ptSps->u8LongTermRefPicsPresentFlag) {
        ptSps->u8NumLongTermRefPicsSps = parseUe(pvBuf);
        if (ptSps->u8NumLongTermRefPicsSps > HEVC_MAX_LONG_TERM_REF_PICS) {
zqsong committed
1892
            RPT(RPT_ERR, "Too many long term ref pics: %d.\n",
1893
                   ptSps->u8NumLongTermRefPicsSps);
1894 1895
            iRet = -1;
            goto exit;
zqsong committed
1896
        }
1897 1898 1899
        for (i = 0; i < ptSps->u8NumLongTermRefPicsSps; i++) {
            ptSps->au16LtRefPicPocLsbSps[i]       = getBits(pvBuf, ptSps->uiLog2MaxPocLsb);
            ptSps->au8UsedByCurrPicLtSpsFlag[i] = getOneBit(pvBuf);
zqsong committed
1900 1901 1902
        }
    }

1903 1904 1905 1906 1907 1908 1909
    ptSps->u8SpsTemporalMvpEnabledFlag          = getOneBit(pvBuf);
    ptSps->u8SpsStrongIntraMmoothingEnableFlag = getOneBit(pvBuf);
    ptSps->tVui.tSar = (T_AVRational){0, 1};
    ptSps->iVuiPresent = getOneBit(pvBuf);
    if (ptSps->iVuiPresent)
        decodeVui(pvBuf, ptSps);

zqsong committed
1910 1911

    if (getOneBit(pvBuf)) { // sps_extension_flag
1912
        int iSpsRangeExtensionFlag = getOneBit(pvBuf);
zqsong committed
1913
        getBits(pvBuf, 7); //sps_extension_7bits = getBits(pvBuf, 7);
1914 1915 1916
        if (iSpsRangeExtensionFlag) {
            int iExtendedPrecisionProcessingFlag;
            int iCabacBypassAlignmentEnabledFlag;
zqsong committed
1917

1918 1919 1920
            ptSps->iTransformSkipRotationEnabledFlag = getOneBit(pvBuf);
            ptSps->iTransformSkipContextEnabledFlag  = getOneBit(pvBuf);
            ptSps->iImplicitRdpcmEnabledFlag = getOneBit(pvBuf);
zqsong committed
1921

1922
            ptSps->iExplicitRdpcmEnabledFlag = getOneBit(pvBuf);
zqsong committed
1923

1924 1925
            iExtendedPrecisionProcessingFlag = getOneBit(pvBuf);
            if (iExtendedPrecisionProcessingFlag)
zqsong committed
1926
                RPT(RPT_WRN,
1927
                   "iExtendedPrecisionProcessingFlag not yet implemented\n");
zqsong committed
1928

1929 1930 1931
            ptSps->iIntraSmoothingDisabledFlag       = getOneBit(pvBuf);
            ptSps->iHighPrecisionOffsetsEnabledFlag = getOneBit(pvBuf);
            if (ptSps->iHighPrecisionOffsetsEnabledFlag)
zqsong committed
1932
                RPT(RPT_WRN,
1933
                   "iHighPrecisionOffsetsEnabledFlag not yet implemented\n");
zqsong committed
1934

1935
            ptSps->iPersistentRiceAdaptationEnabledFlag = getOneBit(pvBuf);
zqsong committed
1936

1937 1938
            iCabacBypassAlignmentEnabledFlag  = getOneBit(pvBuf);
            if (iCabacBypassAlignmentEnabledFlag)
zqsong committed
1939
                RPT(RPT_WRN,
1940
                   "iCabacBypassAlignmentEnabledFlag not yet implemented\n");
zqsong committed
1941 1942 1943
        }
    }

1944 1945 1946 1947 1948
    ow = &ptSps->tOutputWindow;
    if (ow->uiLeftOffset >= INT_MAX - ow->uiRightOffset     ||
        ow->uiTopOffset  >= INT_MAX - ow->uiBottomOffset    ||
        ow->uiLeftOffset + ow->uiRightOffset  >= ptSps->iWidth ||
        ow->uiTopOffset  + ow->uiBottomOffset >= ptSps->iHeight) {
zqsong committed
1949
        RPT(RPT_WRN, "Invalid cropping offsets: %u/%u/%u/%u\n",
1950
               ow->uiLeftOffset, ow->uiRightOffset, ow->uiTopOffset, ow->uiBottomOffset);
zqsong committed
1951 1952 1953
        RPT(RPT_WRN,
               "Displaying the whole video surface.\n");
        memset(ow, 0, sizeof(*ow));
1954
        memset(&ptSps->tPicConfWin, 0, sizeof(ptSps->tPicConfWin));
zqsong committed
1955 1956 1957
    }

    // Inferred parameters
1958 1959 1960
    ptSps->uiLog2CtbSize = ptSps->uiLog2MinCbSize +
                         ptSps->uiLog2DiffMaxMinCodingBlockSize;
    ptSps->uiLog2MinPuSize = ptSps->uiLog2MinCbSize - 1;
zqsong committed
1961

1962 1963
    if (ptSps->uiLog2CtbSize > HEVC_MAX_LOG2_CTB_SIZE) {
        RPT(RPT_ERR, "CTB size out of range: 2^%d\n", ptSps->uiLog2CtbSize);
zqsong committed
1964
        iRet = -1;
1965
        goto exit;
zqsong committed
1966
    }
1967
    if (ptSps->uiLog2CtbSize < 4) {
zqsong committed
1968
        RPT(RPT_ERR,
1969 1970
               "uiLog2CtbSize %d differs from the bounds of any known profile\n",
               ptSps->uiLog2CtbSize);
zqsong committed
1971
        iRet = -1;
1972
        goto exit;
zqsong committed
1973 1974
    }

1975 1976 1977
    ptSps->iCtbWidth  = (ptSps->iWidth  + (1 << ptSps->uiLog2CtbSize) - 1) >> ptSps->uiLog2CtbSize;
    ptSps->iCtbHeight = (ptSps->iHeight + (1 << ptSps->uiLog2CtbSize) - 1) >> ptSps->uiLog2CtbSize;
    ptSps->iCtbSize   = ptSps->iCtbWidth * ptSps->iCtbHeight;
zqsong committed
1978

1979 1980 1981 1982 1983 1984 1985
    ptSps->iMinCbWidth  = ptSps->iWidth  >> ptSps->uiLog2MinCbSize;
    ptSps->iMinCbHeight = ptSps->iHeight >> ptSps->uiLog2MinCbSize;
    ptSps->iMinTbWidth  = ptSps->iWidth  >> ptSps->uiLog2MinTbSize;
    ptSps->iMinTbHeight = ptSps->iHeight >> ptSps->uiLog2MinTbSize;
    ptSps->iMinPuWidth  = ptSps->iWidth  >> ptSps->uiLog2MinPuSize;
    ptSps->iMinPuHeight = ptSps->iHeight >> ptSps->uiLog2MinPuSize;
    ptSps->iTbMask       = (1 << (ptSps->uiLog2CtbSize - ptSps->uiLog2MinTbSize)) - 1;
zqsong committed
1986

1987
    ptSps->iQpBdOffset = 6 * (ptSps->iBitDepth - 8);
zqsong committed
1988

1989 1990
    if (avModUintp2c(ptSps->iWidth, ptSps->uiLog2MinCbSize) ||
        avModUintp2c(ptSps->iHeight, ptSps->uiLog2MinCbSize)) {
zqsong committed
1991 1992
        RPT(RPT_ERR, "Invalid coded frame dimensions.\n");
        iRet = -1;
1993
        goto exit;
zqsong committed
1994 1995
    }

1996 1997 1998
    if (ptSps->iMaxTransformHierarchyDepthInter > ptSps->uiLog2CtbSize - ptSps->uiLog2MinTbSize) {
        RPT(RPT_ERR, "iMaxTransformHierarchyDepthInter out of range: %d\n",
               ptSps->iMaxTransformHierarchyDepthInter);
zqsong committed
1999
        iRet = -1;
2000
        goto exit;
zqsong committed
2001
    }
2002 2003 2004
    if (ptSps->iMaxTransformHierarchyDepthIntra > ptSps->uiLog2CtbSize - ptSps->uiLog2MinTbSize) {
        RPT(RPT_ERR, "iMaxTransformHierarchyDepthIntra out of range: %d\n",
               ptSps->iMaxTransformHierarchyDepthIntra);
zqsong committed
2005
        iRet = -1;
2006
        goto exit;
zqsong committed
2007
    }
2008
    if (ptSps->uiLog2MaxTrafoSize > FFMIN(ptSps->uiLog2CtbSize, 5)) {
zqsong committed
2009 2010
        RPT(RPT_ERR,
               "max transform block size out of range: %d\n",
2011
               ptSps->uiLog2MaxTrafoSize);
zqsong committed
2012
        iRet = -1;
2013
        goto exit;
zqsong committed
2014 2015 2016 2017 2018 2019
    }

    if (getBitsLeft(pvBuf) < 0) {
        RPT(RPT_ERR,
               "Overread SPS by %d bits\n", -getBitsLeft(pvBuf));
        iRet = -1;
2020
        goto exit;
zqsong committed
2021 2022
    }

2023
    
zqsong committed
2024 2025
exit:

2026 2027
    getBitContextFree(pvBuf);
    return iRet;
zqsong committed
2028 2029 2030

}

2031 2032 2033

int h265DecVideoParameterSet( void *pvBufSrc, T_HEVCVPS *ptVps )
{
2034
    int iRet = 0;
2035 2036
    int i,j;
    int uiVpsId = 0;
2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157
    
    void *pvBuf = NULL;
    if(NULL == pvBufSrc || NULL == ptVps)
    {
        RPT(RPT_ERR,"ERR null pointer\n");
        iRet = -1;
        goto exit;
    }

    memset((void *)ptVps, 0, sizeof(T_HEVCVPS));

    pvBuf = deEmulationPrevention(pvBufSrc);
    if(NULL == pvBuf)
    {
        RPT(RPT_ERR,"ERR null pointer\n");
        iRet = -1;
        goto exit;
    }

    RPT(RPT_DBG, "Decoding VPS\n");

    uiVpsId = getBits(pvBuf, 4);
    if (uiVpsId >= HEVC_MAX_VPS_COUNT) {
        RPT(RPT_ERR, "VPS id out of range: %d\n", uiVpsId);
        iRet = -1;
        goto exit;
    }

    if (getBits(pvBuf, 2) != 3) { // vps_reserved_three_2bits
        RPT(RPT_ERR, "vps_reserved_three_2bits is not three\n");
        iRet = -1;
        goto exit;
    }

    ptVps->iVpsMaxLayers 			  = getBits(pvBuf, 6) + 1;
    ptVps->iVpsMaxSubLayers 		  = getBits(pvBuf, 3) + 1;
    ptVps->u8VpsTemporalIdNestingFlag = getOneBit(pvBuf);

    if (getBits(pvBuf, 16) != 0xffff) { // vps_reserved_ffff_16bits
        RPT(RPT_ERR, "vps_reserved_ffff_16bits is not 0xffff\n");
        iRet = -1;
        goto exit;
    }

    if (ptVps->iVpsMaxSubLayers > HEVC_MAX_SUB_LAYERS) {
        RPT(RPT_ERR, "iVpsMaxSubLayers out of range: %d\n",
               ptVps->iVpsMaxSubLayers);
        iRet = -1;
        goto exit;
    }

    if (parsePtl(pvBuf, &ptVps->tPtl, ptVps->iVpsMaxSubLayers) < 0){
        iRet = -1;
        goto exit;
    }

    ptVps->iVpsSubLayerOrderingInfoPresentFlag = getOneBit(pvBuf);

    i = ptVps->iVpsSubLayerOrderingInfoPresentFlag ? 0 : ptVps->iVpsMaxSubLayers - 1;
    for (; i < ptVps->iVpsMaxSubLayers; i++) {
        ptVps->uiVpsMaxDecPicBuffering[i] = parseUe(pvBuf) + 1;
        ptVps->auiVpsNumReorderPics[i]	  = parseUe(pvBuf);
        ptVps->auiVpsMaxLatencyIncrease[i]  = parseUe(pvBuf) - 1;

        if (ptVps->uiVpsMaxDecPicBuffering[i] > HEVC_MAX_DPB_SIZE || !ptVps->uiVpsMaxDecPicBuffering[i]) {
            RPT(RPT_ERR, "vps_max_dec_pic_buffering_minus1 out of range: %d\n",
                   ptVps->uiVpsMaxDecPicBuffering[i] - 1);
            iRet = -1;
            goto exit;
        }
        if (ptVps->auiVpsNumReorderPics[i] > ptVps->uiVpsMaxDecPicBuffering[i] - 1) {
            RPT(RPT_WRN, "vps_max_num_reorder_pics out of range: %d\n",
                   ptVps->auiVpsNumReorderPics[i]);
        }
    }

    ptVps->iVpsMaxLayerId	= getBits(pvBuf, 6);
    ptVps->iVpsNumLayerSets = parseUe(pvBuf) + 1;
    if (ptVps->iVpsNumLayerSets < 1 || ptVps->iVpsNumLayerSets > 1024 ||
        (ptVps->iVpsNumLayerSets - 1LL) * (ptVps->iVpsMaxLayerId + 1LL) > getBitsLeft(pvBuf)) {
        RPT(RPT_ERR, "too many layer_id_included_flags\n");
        iRet = -1;
        goto exit;
    }

    for (i = 1; i < ptVps->iVpsNumLayerSets; i++)
        for (j = 0; j <= ptVps->iVpsMaxLayerId; j++)
            getBits(pvBuf, 1);  // layer_id_included_flag[i][j]

    ptVps->u8VpsTimingInfoPresentFlag = getOneBit(pvBuf);
    if (ptVps->u8VpsTimingInfoPresentFlag) {
        ptVps->u32VpsNumUnitsInTick				 = getBits(pvBuf, 32);
        ptVps->u32VpsTimeScale 					 = getBits(pvBuf, 32);
        ptVps->u8VpsPocProportionalToTimingFlag = getOneBit(pvBuf);
        if (ptVps->u8VpsPocProportionalToTimingFlag)
            ptVps->iVpsNumTicksPocDiffOne = parseUe(pvBuf) + 1;
        ptVps->iVpsNumHrdParameters = parseUe(pvBuf);
        if (ptVps->iVpsNumHrdParameters > (unsigned)ptVps->iVpsNumLayerSets) {
            RPT(RPT_ERR,
                   "iVpsNumHrdParameters %d is invalid\n", ptVps->iVpsNumHrdParameters);
            iRet = -1;
            goto exit;
        }
        for (i = 0; i < ptVps->iVpsNumHrdParameters; i++) {
            int common_inf_present = 1;

            parseUe(pvBuf); // hrd_layer_set_idx
            if (i)
                common_inf_present = getOneBit(pvBuf);
            decodeHrd(pvBuf, common_inf_present, ptVps->iVpsMaxSubLayers);
        }
    }
    getOneBit(pvBuf); /* vps_extension_flag */

    if (getBitsLeft(pvBuf) < 0) {
        RPT(RPT_ERR,
               "Overread VPS by %d bits\n", -getBitsLeft(pvBuf));
        
        iRet = -1;
        goto exit;
    }
2158 2159 2160 2161


exit:

2162 2163
    getBitContextFree(pvBuf);
    return iRet;
2164 2165

}
2166
    
xzl committed
2167 2168
void h264GetWidthHeight(T_SPS *ptSps, int *piWidth, int *piHeight)
{
2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179
    // ¿í¸ß¼ÆË㹫ʽ
    int iCodeWidth = 0;
    int iCodedHeight = 0;
    iCodeWidth	= 16 * ptSps->iMbWidth;
    iCodedHeight = 16 * ptSps->iMbHeight;
    *piWidth		 = iCodeWidth  - (ptSps->uiCropRight + ptSps->uiCropLeft);
    *piHeight		 = iCodedHeight - (ptSps->uiCropTop	+ ptSps->uiCropBottom);
     if (*piWidth <= 0 || *piHeight <= 0) {
         *piWidth  = iCodeWidth;
         *piHeight = iCodedHeight;
     }
xzl committed
2180

2181
    RPT(RPT_DBG, "iCodeWidth:%d, iCodedHeight:%d\n", iCodeWidth, iCodedHeight);
xzl committed
2182

2183
    RPT(RPT_DBG, "*piWidth:%d, *piHeight:%d\n", *piWidth, *piHeight);
xzl committed
2184

2185
    RPT(RPT_DBG, "ptSps->uiCropRight:%d, ptSps->uiCropLeft:%d\n", ptSps->uiCropRight, ptSps->uiCropLeft);
xzl committed
2186

2187
    RPT(RPT_DBG, "ptSps->uiCropTop:%d, ptSps->uiCropBottom:%d\n", ptSps->uiCropTop, ptSps->uiCropBottom);
xzl committed
2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215

}

int h264GetFormat(T_SPS *ptSps)
{
    return ptSps->iFrameMbsOnlyFlag;
}


void h264GeFramerate(T_SPS *ptSps, float *pfFramerate)
{
    int iFrInt = 0;
    if(ptSps->iTimingInfoPresentFlag)
    {
        if(!ptSps->iFixedFrameRateFlag)
        {
            *pfFramerate = (float)ptSps->u32TimeScale / (float)ptSps->u32NumUnitsInTick;
            //iFrInt = ptSps->vui_parameters.u32TimeScale / ptSps->vui_parameters.u32NumUnitsInTick;
        }else
        {
            *pfFramerate = (float)ptSps->u32TimeScale / (float)ptSps->u32NumUnitsInTick / 2.0;
            //iFrInt = ptSps->vui_parameters.u32TimeScale / ptSps->vui_parameters.u32NumUnitsInTick / 2;
        }
        iFrInt = ptSps->u32TimeScale / ptSps->u32NumUnitsInTick / 2;
    }
    switch(iFrInt)
    {
        case 23:// 23.98
2216
            RPT(RPT_DBG, "frame rate:23.98");
xzl committed
2217 2218
            break;
        case 24:
2219
            RPT(RPT_DBG, "frame rate:24");
xzl committed
2220 2221
            break;
        case 25:
2222
            RPT(RPT_DBG, "frame rate:25");
xzl committed
2223 2224
            break;
        case 29://29.97
2225
            RPT(RPT_DBG, "frame rate:29.97");
xzl committed
2226 2227
            break;
        case 30:
2228
            RPT(RPT_DBG, "frame rate:30");
xzl committed
2229 2230
            break;
        case 50:
2231
            RPT(RPT_DBG, "frame rate:50");
xzl committed
2232 2233
            break;
        case 59://59.94
2234
            RPT(RPT_DBG, "frame rate:59.94");
xzl committed
2235 2236
            break;
        case 60:
2237
            RPT(RPT_DBG, "frame rate:60");
xzl committed
2238 2239
            break;
        case 6:
2240
            RPT(RPT_DBG, "frame rate:6");
xzl committed
2241 2242
            break;
        case 8:
2243
            RPT(RPT_DBG, "frame rate:8");
xzl committed
2244 2245
            break;
        case 12:
2246
            RPT(RPT_DBG, "frame rate:12");
xzl committed
2247 2248
            break;
        case 15:
2249
            RPT(RPT_DBG, "frame rate:15");
xzl committed
2250 2251
            break;
        case 10:
2252
            RPT(RPT_DBG, "frame rate:10");
xzl committed
2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264
            break;

        default:
            RPT(RPT_DBG, "frame rate:0");
            break;
    }

    return;
}



zqsong committed
2265 2266 2267 2268

void h265GetWidthHeight(T_HEVCSPS *ptSps, int *piWidth, int *piHeight)
{
#if 1
2269 2270 2271 2272 2273 2274
    int iCodeWidth = 0;
    int iCodedHeight = 0;
    iCodeWidth	= ptSps->iWidth;
    iCodedHeight = ptSps->iHeight;
    *piWidth		 = ptSps->iWidth  - ptSps->tOutputWindow.uiLeftOffset - ptSps->tOutputWindow.uiRightOffset;
    *piHeight		 = ptSps->iHeight - ptSps->tOutputWindow.uiTopOffset  - ptSps->tOutputWindow.uiBottomOffset;
2275

zqsong committed
2276

2277
    RPT(RPT_DBG, "iCodeWidth:%d, iCodedHeight:%d\n", iCodeWidth, iCodedHeight);
zqsong committed
2278

2279
    RPT(RPT_DBG, "*piWidth:%d, *piHeight:%d\n", *piWidth, *piHeight);
zqsong committed
2280

2281
    RPT(RPT_DBG, "ptSps->tOutputWindow.uiRightOffset:%d, ptSps->tOutputWindow.uiLeftOffset:%d\n", ptSps->tOutputWindow.uiRightOffset, ptSps->tOutputWindow.uiLeftOffset);
zqsong committed
2282

2283
    RPT(RPT_DBG, "ptSps->tOutputWindow.uiTopOffset:%d, ptSps->tOutputWindow.uiBottomOffset:%d\n", ptSps->tOutputWindow.uiTopOffset, ptSps->tOutputWindow.uiBottomOffset);
zqsong committed
2284 2285 2286 2287 2288 2289
#endif

}



2290
void h265GeFramerate(T_HEVCVPS *ptVps, T_HEVCSPS *ptSps,float *pfFramerate)
zqsong committed
2291
{
2292
    if (ptVps && ptVps->u8VpsTimingInfoPresentFlag) {
2293 2294
        *pfFramerate = (float)(ptVps->u32VpsTimeScale) / (float)(ptVps->u32VpsNumUnitsInTick);
    
2295
    } else if (ptSps && ptSps->tVui.iVuiTimingInfoPresentFlag && ptSps->iVuiPresent) {
2296 2297 2298 2299 2300 2301
        *pfFramerate = (float)(ptSps->tVui.u32VuiTimeScale) / (float)(ptSps->tVui.u32VuiNumUnitsInTick);
    }
    else{
        //vps sps可能不包含帧率
        *pfFramerate = 0.0F;
        RPT(RPT_WRN, "frame rate:0");
2302
    }
zqsong committed
2303 2304
}