1 /*!
2  * \copy
3  *     Copyright (c)  2009-2013, Cisco Systems
4  *     All rights reserved.
5  *
6  *     Redistribution and use in source and binary forms, with or without
7  *     modification, are permitted provided that the following conditions
8  *     are met:
9  *
10  *        * Redistributions of source code must retain the above copyright
11  *          notice, this list of conditions and the following disclaimer.
12  *
13  *        * Redistributions in binary form must reproduce the above copyright
14  *          notice, this list of conditions and the following disclaimer in
15  *          the documentation and/or other materials provided with the
16  *          distribution.
17  *
18  *     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  *     "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  *     LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
21  *     FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
22  *     COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
23  *     INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
24  *     BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25  *     LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26  *     CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  *     LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
28  *     ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  *     POSSIBILITY OF SUCH DAMAGE.
30  *
31  *
32  * \file    au_parser.c
33  *
34  * \brief   Interfaces introduced in Access Unit level based parser
35  *
36  * \date    03/10/2009 Created
37  *
38  *************************************************************************************
39  */
40 #include "codec_def.h"
41 #include "au_parser.h"
42 #include "decoder.h"
43 #include "error_code.h"
44 #include "memmgr_nal_unit.h"
45 #include "decoder_core.h"
46 #include "bit_stream.h"
47 #include "memory_align.h"
48 
49 #define _PARSE_NALHRD_VCLHRD_PARAMS_ 1
50 
51 namespace WelsDec {
52 /*!
53  *************************************************************************************
54  * \brief   Start Code Prefix (0x 00 00 00 01) detection
55  *
56  * \param   pBuf        bitstream payload buffer
57  * \param   pOffset     offset between NAL rbsp and original bitsteam that
58  *                      start code prefix is seperated from.
59  * \param   iBufSize    count size of buffer
60  *
61  * \return  RBSP buffer of start code prefix exclusive
62  *
63  * \note    N/A
64  *************************************************************************************
65  */
DetectStartCodePrefix(const uint8_t * kpBuf,int32_t * pOffset,int32_t iBufSize)66 uint8_t* DetectStartCodePrefix (const uint8_t* kpBuf, int32_t* pOffset, int32_t iBufSize) {
67   uint8_t* pBits = (uint8_t*)kpBuf;
68 
69   do {
70     int32_t iIdx = 0;
71     while ((iIdx < iBufSize) && (! (*pBits))) {
72       ++ pBits;
73       ++ iIdx;
74     }
75     if (iIdx >= iBufSize)  break;
76 
77     ++ iIdx;
78     ++ pBits;
79 
80     if ((iIdx >= 3) && ((* (pBits - 1)) == 0x1)) {
81       *pOffset = (int32_t) (((uintptr_t)pBits) - ((uintptr_t)kpBuf));
82       return pBits;
83     }
84 
85     iBufSize -= iIdx;
86   }  while (1);
87 
88   return NULL;
89 }
90 
91 /*!
92  *************************************************************************************
93  * \brief   to parse nal unit
94  *
95  * \param   pCtx            decoder context
96  * \param   pNalUnitHeader  parsed result of NAL Unit Header to output
97  * \param   pSrcRbsp        bitstream buffer to input
98  * \param   iSrcRbspLen     length size of bitstream buffer payload
99  * \param   pSrcNal
100  * \param   iSrcNalLen
101  * \param   pConsumedBytes  consumed bytes during parsing
102  *
103  * \return  decoded bytes payload, might be (pSrcRbsp+1) if no escapes
104  *
105  * \note    N/A
106  *************************************************************************************
107  */
ParseNalHeader(PWelsDecoderContext pCtx,SNalUnitHeader * pNalUnitHeader,uint8_t * pSrcRbsp,int32_t iSrcRbspLen,uint8_t * pSrcNal,int32_t iSrcNalLen,int32_t * pConsumedBytes)108 uint8_t* ParseNalHeader (PWelsDecoderContext pCtx, SNalUnitHeader* pNalUnitHeader, uint8_t* pSrcRbsp,
109                          int32_t iSrcRbspLen, uint8_t* pSrcNal, int32_t iSrcNalLen, int32_t* pConsumedBytes) {
110   PNalUnit pCurNal = NULL;
111   uint8_t* pNal     = pSrcRbsp;
112   int32_t iNalSize  = iSrcRbspLen;
113   PBitStringAux pBs = NULL;
114   bool bExtensionFlag = false;
115   int32_t iErr = ERR_NONE;
116   int32_t iBitSize = 0;
117   SDataBuffer* pSavedData = &pCtx->sSavedData;
118   SLogContext* pLogCtx = & (pCtx->sLogCtx);
119   pNalUnitHeader->eNalUnitType = NAL_UNIT_UNSPEC_0;//SHOULD init it. because pCtx->sCurNalHead is common variable.
120 
121   //remove the consecutive ZERO at the end of current NAL in the reverse order.--2011.6.1
122   {
123     int32_t iIndex = iSrcRbspLen - 1;
124     uint8_t uiBsZero = 0;
125     while (iIndex >= 0) {
126       uiBsZero = pSrcRbsp[iIndex];
127       if (0 == uiBsZero) {
128         --iNalSize;
129         ++ (*pConsumedBytes);
130         --iIndex;
131       } else {
132         break;
133       }
134     }
135   }
136 
137   pNalUnitHeader->uiForbiddenZeroBit = (uint8_t) (pNal[0] >> 7); // uiForbiddenZeroBit
138   if (pNalUnitHeader->uiForbiddenZeroBit) { //2010.4.14
139     pCtx->iErrorCode |= dsBitstreamError;
140     return NULL; //uiForbiddenZeroBit should always equal to 0
141   }
142 
143   pNalUnitHeader->uiNalRefIdc   = (uint8_t) (pNal[0] >> 5);             // uiNalRefIdc
144   pNalUnitHeader->eNalUnitType  = (EWelsNalUnitType) (pNal[0] & 0x1f);  // eNalUnitType
145 
146   ++pNal;
147   --iNalSize;
148   ++ (*pConsumedBytes);
149 
150   if (! (IS_SEI_NAL (pNalUnitHeader->eNalUnitType) || IS_SPS_NAL (pNalUnitHeader->eNalUnitType)
151          || IS_AU_DELIMITER_NAL (pNalUnitHeader->eNalUnitType) || pCtx->sSpsPpsCtx.bSpsExistAheadFlag)) {
152     if (pCtx->bPrintFrameErrorTraceFlag && pCtx->sSpsPpsCtx.iSpsErrorIgnored == 0) {
153       WelsLog (pLogCtx, WELS_LOG_WARNING,
154                "parse_nal(), no exist Sequence Parameter Sets ahead of sequence when try to decode NAL(type:%d).",
155                pNalUnitHeader->eNalUnitType);
156     } else {
157       pCtx->sSpsPpsCtx.iSpsErrorIgnored++;
158     }
159     pCtx->pDecoderStatistics->iSpsNoExistNalNum++;
160     pCtx->iErrorCode = dsNoParamSets;
161     return NULL;
162   }
163   pCtx->sSpsPpsCtx.iSpsErrorIgnored = 0;
164   if (! (IS_SEI_NAL (pNalUnitHeader->eNalUnitType) || IS_PARAM_SETS_NALS (pNalUnitHeader->eNalUnitType)
165          || IS_AU_DELIMITER_NAL (pNalUnitHeader->eNalUnitType) || pCtx->sSpsPpsCtx.bPpsExistAheadFlag)) {
166     if (pCtx->bPrintFrameErrorTraceFlag && pCtx->sSpsPpsCtx.iPpsErrorIgnored == 0) {
167       WelsLog (pLogCtx, WELS_LOG_WARNING,
168                "parse_nal(), no exist Picture Parameter Sets ahead of sequence when try to decode NAL(type:%d).",
169                pNalUnitHeader->eNalUnitType);
170     } else {
171       pCtx->sSpsPpsCtx.iPpsErrorIgnored++;
172     }
173     pCtx->pDecoderStatistics->iPpsNoExistNalNum++;
174     pCtx->iErrorCode = dsNoParamSets;
175     return NULL;
176   }
177   pCtx->sSpsPpsCtx.iPpsErrorIgnored = 0;
178   if ((IS_VCL_NAL_AVC_BASE (pNalUnitHeader->eNalUnitType) && ! (pCtx->sSpsPpsCtx.bSpsExistAheadFlag
179        || pCtx->sSpsPpsCtx.bPpsExistAheadFlag)) ||
180       (IS_NEW_INTRODUCED_SVC_NAL (pNalUnitHeader->eNalUnitType) && ! (pCtx->sSpsPpsCtx.bSpsExistAheadFlag
181           || pCtx->sSpsPpsCtx.bSubspsExistAheadFlag
182           || pCtx->sSpsPpsCtx.bPpsExistAheadFlag))) {
183     if (pCtx->bPrintFrameErrorTraceFlag && pCtx->sSpsPpsCtx.iSubSpsErrorIgnored == 0) {
184       WelsLog (pLogCtx, WELS_LOG_WARNING,
185                "ParseNalHeader(), no exist Parameter Sets ahead of sequence when try to decode slice(type:%d).",
186                pNalUnitHeader->eNalUnitType);
187     } else {
188       pCtx->sSpsPpsCtx.iSubSpsErrorIgnored++;
189     }
190     pCtx->pDecoderStatistics->iSubSpsNoExistNalNum++;
191     pCtx->iErrorCode    |= dsNoParamSets;
192     return NULL;
193   }
194   pCtx->sSpsPpsCtx.iSubSpsErrorIgnored = 0;
195 
196   switch (pNalUnitHeader->eNalUnitType) {
197   case NAL_UNIT_AU_DELIMITER:
198   case NAL_UNIT_SEI:
199     if (pCtx->pAccessUnitList->uiAvailUnitsNum > 0) {
200       pCtx->pAccessUnitList->uiEndPos = pCtx->pAccessUnitList->uiAvailUnitsNum - 1;
201       pCtx->bAuReadyFlag = true;
202     }
203     break;
204 
205   case NAL_UNIT_PREFIX:
206     pCurNal = &pCtx->sSpsPpsCtx.sPrefixNal;
207     pCurNal->uiTimeStamp = pCtx->uiTimeStamp;
208 
209     if (iNalSize < NAL_UNIT_HEADER_EXT_SIZE) {
210       PAccessUnit pCurAu = pCtx->pAccessUnitList;
211       uint32_t uiAvailNalNum = pCurAu->uiAvailUnitsNum;
212 
213       if (uiAvailNalNum > 0) {
214         pCurAu->uiEndPos = uiAvailNalNum - 1;
215         if (pCtx->pParam->eEcActiveIdc == ERROR_CON_DISABLE) {
216           pCtx->bAuReadyFlag = true;
217         }
218       }
219       pCurNal->sNalData.sPrefixNal.bPrefixNalCorrectFlag = false;
220       pCtx->iErrorCode |= dsBitstreamError;
221       return NULL;
222     }
223 
224     DecodeNalHeaderExt (pCurNal, pNal);
225     if ((pCurNal->sNalHeaderExt.uiQualityId != 0) || (pCurNal->sNalHeaderExt.bUseRefBasePicFlag != 0)) {
226       WelsLog (pLogCtx, WELS_LOG_WARNING,
227                "ParseNalHeader() in Prefix Nal Unit:uiQualityId (%d) != 0, bUseRefBasePicFlag (%d) != 0, not supported!",
228                pCurNal->sNalHeaderExt.uiQualityId, pCurNal->sNalHeaderExt.bUseRefBasePicFlag);
229       PAccessUnit pCurAu = pCtx->pAccessUnitList;
230       uint32_t uiAvailNalNum = pCurAu->uiAvailUnitsNum;
231 
232       if (uiAvailNalNum > 0) {
233         pCurAu->uiEndPos = uiAvailNalNum - 1;
234         if (pCtx->pParam->eEcActiveIdc == ERROR_CON_DISABLE) {
235           pCtx->bAuReadyFlag = true;
236         }
237       }
238       pCurNal->sNalData.sPrefixNal.bPrefixNalCorrectFlag = false;
239       pCtx->iErrorCode |= dsBitstreamError;
240       return NULL;
241     }
242 
243     pNal            += NAL_UNIT_HEADER_EXT_SIZE;
244     iNalSize        -= NAL_UNIT_HEADER_EXT_SIZE;
245     *pConsumedBytes += NAL_UNIT_HEADER_EXT_SIZE;
246 
247     pCurNal->sNalHeaderExt.sNalUnitHeader.uiForbiddenZeroBit = pNalUnitHeader->uiForbiddenZeroBit;
248     pCurNal->sNalHeaderExt.sNalUnitHeader.uiNalRefIdc        = pNalUnitHeader->uiNalRefIdc;
249     pCurNal->sNalHeaderExt.sNalUnitHeader.eNalUnitType       = pNalUnitHeader->eNalUnitType;
250     if (pNalUnitHeader->uiNalRefIdc != 0) {
251       pBs = &pCtx->sBs;
252       iBitSize = (iNalSize << 3) - BsGetTrailingBits (pNal + iNalSize - 1); // convert into bit
253 
254       iErr = DecInitBits (pBs, pNal, iBitSize);
255       if (iErr) {
256         WelsLog (pLogCtx, WELS_LOG_ERROR, "NAL_UNIT_PREFIX: DecInitBits() fail due invalid access.");
257         pCtx->iErrorCode |= dsBitstreamError;
258         return NULL;
259       }
260       ParsePrefixNalUnit (pCtx, pBs);
261     }
262     pCurNal->sNalData.sPrefixNal.bPrefixNalCorrectFlag = true;
263 
264     break;
265   case NAL_UNIT_CODED_SLICE_EXT:
266     bExtensionFlag = true;
267   case NAL_UNIT_CODED_SLICE:
268   case NAL_UNIT_CODED_SLICE_IDR: {
269     PAccessUnit pCurAu = NULL;
270     uint32_t uiAvailNalNum;
271     pCurNal = MemGetNextNal (&pCtx->pAccessUnitList, pCtx->pMemAlign);
272     if (NULL == pCurNal) {
273       WelsLog (pLogCtx, WELS_LOG_ERROR, "MemGetNextNal() fail due out of memory.");
274       pCtx->iErrorCode |= dsOutOfMemory;
275       return NULL;
276     }
277     pCurNal->uiTimeStamp = pCtx->uiTimeStamp;
278     pCurNal->sNalHeaderExt.sNalUnitHeader.uiForbiddenZeroBit = pNalUnitHeader->uiForbiddenZeroBit;
279     pCurNal->sNalHeaderExt.sNalUnitHeader.uiNalRefIdc        = pNalUnitHeader->uiNalRefIdc;
280     pCurNal->sNalHeaderExt.sNalUnitHeader.eNalUnitType       = pNalUnitHeader->eNalUnitType;
281     pCurAu        = pCtx->pAccessUnitList;
282     uiAvailNalNum = pCurAu->uiAvailUnitsNum;
283 
284 
285     if (pNalUnitHeader->eNalUnitType == NAL_UNIT_CODED_SLICE_EXT) {
286       if (iNalSize < NAL_UNIT_HEADER_EXT_SIZE) {
287         ForceClearCurrentNal (pCurAu);
288 
289         if (uiAvailNalNum > 1) {
290           pCurAu->uiEndPos = uiAvailNalNum - 2;
291           if (pCtx->pParam->eEcActiveIdc == ERROR_CON_DISABLE) {
292             pCtx->bAuReadyFlag = true;
293           }
294         }
295         pCtx->iErrorCode |= dsBitstreamError;
296         return NULL;
297       }
298 
299       DecodeNalHeaderExt (pCurNal, pNal);
300       if (pCurNal->sNalHeaderExt.uiQualityId != 0 ||
301           pCurNal->sNalHeaderExt.bUseRefBasePicFlag) {
302         if (pCurNal->sNalHeaderExt.uiQualityId != 0)
303           WelsLog (pLogCtx, WELS_LOG_WARNING, "ParseNalHeader():uiQualityId (%d) != 0, MGS not supported!",
304                    pCurNal->sNalHeaderExt.uiQualityId);
305         if (pCurNal->sNalHeaderExt.bUseRefBasePicFlag != 0)
306           WelsLog (pLogCtx, WELS_LOG_WARNING, "ParseNalHeader():bUseRefBasePicFlag (%d) != 0, MGS not supported!",
307                    pCurNal->sNalHeaderExt.bUseRefBasePicFlag);
308 
309         ForceClearCurrentNal (pCurAu);
310 
311         if (uiAvailNalNum > 1) {
312           pCurAu->uiEndPos = uiAvailNalNum - 2;
313           if (pCtx->pParam->eEcActiveIdc == ERROR_CON_DISABLE) {
314             pCtx->bAuReadyFlag = true;
315           }
316         }
317         pCtx->iErrorCode |= dsBitstreamError;
318         return NULL;
319       }
320       pNal            += NAL_UNIT_HEADER_EXT_SIZE;
321       iNalSize        -= NAL_UNIT_HEADER_EXT_SIZE;
322       *pConsumedBytes += NAL_UNIT_HEADER_EXT_SIZE;
323 
324       if (pCtx->pParam->bParseOnly) {
325         pCurNal->sNalData.sVclNal.pNalPos = pSavedData->pCurPos;
326         int32_t iTrailingZeroByte = 0;
327         while (pSrcNal[iSrcNalLen - iTrailingZeroByte - 1] == 0x0) //remove final trailing 0 bytes
328           iTrailingZeroByte++;
329         int32_t iActualLen = iSrcNalLen - iTrailingZeroByte;
330         pCurNal->sNalData.sVclNal.iNalLength = iActualLen - NAL_UNIT_HEADER_EXT_SIZE;
331         //unify start code as 0x0001
332         int32_t iCurrStartByte = 4; //4 for 0x0001, 3 for 0x001
333         if (pSrcNal[0] == 0x0 && pSrcNal[1] == 0x0 && pSrcNal[2] == 0x1) { //if 0x001
334           iCurrStartByte = 3;
335           pCurNal->sNalData.sVclNal.iNalLength++;
336         }
337         if (pCurNal->sNalHeaderExt.bIdrFlag) {
338           * (pSrcNal + iCurrStartByte) &= 0xE0;
339           * (pSrcNal + iCurrStartByte) |= 0x05;
340         } else {
341           * (pSrcNal + iCurrStartByte) &= 0xE0;
342           * (pSrcNal + iCurrStartByte) |= 0x01;
343         }
344         pSavedData->pCurPos[0] = pSavedData->pCurPos[1] = pSavedData->pCurPos[2] = 0x0;
345         pSavedData->pCurPos[3] = 0x1;
346         pSavedData->pCurPos[4] = * (pSrcNal + iCurrStartByte);
347         pSavedData->pCurPos += 5;
348         int32_t iOffset = iCurrStartByte + 1 + NAL_UNIT_HEADER_EXT_SIZE;
349         memcpy (pSavedData->pCurPos, pSrcNal + iOffset, iActualLen - iOffset);
350         pSavedData->pCurPos += iActualLen - iOffset;
351       }
352     } else {
353       if (pCtx->pParam->bParseOnly) {
354         pCurNal->sNalData.sVclNal.pNalPos = pSavedData->pCurPos;
355         int32_t iTrailingZeroByte = 0;
356         while (pSrcNal[iSrcNalLen - iTrailingZeroByte - 1] == 0x0) //remove final trailing 0 bytes
357           iTrailingZeroByte++;
358         int32_t iActualLen = iSrcNalLen - iTrailingZeroByte;
359         pCurNal->sNalData.sVclNal.iNalLength = iActualLen;
360         //unify start code as 0x0001
361         int32_t iStartDeltaByte = 0; //0 for 0x0001, 1 for 0x001
362         if (pSrcNal[0] == 0x0 && pSrcNal[1] == 0x0 && pSrcNal[2] == 0x1) { //if 0x001
363           pSavedData->pCurPos[0] = 0x0;
364           iStartDeltaByte = 1;
365           pCurNal->sNalData.sVclNal.iNalLength++;
366         }
367         memcpy (pSavedData->pCurPos + iStartDeltaByte, pSrcNal, iActualLen);
368         pSavedData->pCurPos += iStartDeltaByte + iActualLen;
369       }
370       if (NAL_UNIT_PREFIX == pCtx->sSpsPpsCtx.sPrefixNal.sNalHeaderExt.sNalUnitHeader.eNalUnitType) {
371         if (pCtx->sSpsPpsCtx.sPrefixNal.sNalData.sPrefixNal.bPrefixNalCorrectFlag) {
372           PrefetchNalHeaderExtSyntax (pCtx, pCurNal, &pCtx->sSpsPpsCtx.sPrefixNal);
373         }
374       }
375 
376       pCurNal->sNalHeaderExt.bIdrFlag = (NAL_UNIT_CODED_SLICE_IDR == pNalUnitHeader->eNalUnitType) ? true :
377                                         false;   //SHOULD update this flag for AVC if no prefix NAL
378       pCurNal->sNalHeaderExt.iNoInterLayerPredFlag = 1;
379     }
380 
381     pBs = &pCurAu->pNalUnitsList[uiAvailNalNum - 1]->sNalData.sVclNal.sSliceBitsRead;
382     iBitSize = (iNalSize << 3) - BsGetTrailingBits (pNal + iNalSize - 1); // convert into bit
383     iErr = DecInitBits (pBs, pNal, iBitSize);
384     if (iErr) {
385       ForceClearCurrentNal (pCurAu);
386       if (uiAvailNalNum > 1) {
387         pCurAu->uiEndPos = uiAvailNalNum - 2;
388         if (pCtx->pParam->eEcActiveIdc == ERROR_CON_DISABLE) {
389           pCtx->bAuReadyFlag = true;
390         }
391       }
392       WelsLog (pLogCtx, WELS_LOG_ERROR, "NAL_UNIT_CODED_SLICE: DecInitBits() fail due invalid access.");
393       pCtx->iErrorCode |= dsBitstreamError;
394       return NULL;
395     }
396     iErr = ParseSliceHeaderSyntaxs (pCtx, pBs, bExtensionFlag);
397     if (iErr != ERR_NONE) {
398       if ((uiAvailNalNum == 1) && (pCurNal->sNalHeaderExt.bIdrFlag)) { //IDR parse error
399         ResetActiveSPSForEachLayer (pCtx);
400       }
401       //if current NAL occur error when parsing, should clean it from pNalUnitsList
402       //otherwise, when Next good NAL decoding, this corrupt NAL is considered as normal NAL and lead to decoder crash
403       ForceClearCurrentNal (pCurAu);
404 
405       if (uiAvailNalNum > 1) {
406         pCurAu->uiEndPos = uiAvailNalNum - 2;
407         if (pCtx->pParam->eEcActiveIdc == ERROR_CON_DISABLE) {
408           pCtx->bAuReadyFlag = true;
409         }
410       }
411       pCtx->iErrorCode |= dsBitstreamError;
412       return NULL;
413     }
414 
415     if ((uiAvailNalNum == 1)
416         && CheckNextAuNewSeq (pCtx, pCurNal, pCurNal->sNalData.sVclNal.sSliceHeaderExt.sSliceHeader.pSps)) {
417       ResetActiveSPSForEachLayer (pCtx);
418     }
419     if ((uiAvailNalNum > 1) &&
420         CheckAccessUnitBoundary (pCtx, pCurAu->pNalUnitsList[uiAvailNalNum - 1], pCurAu->pNalUnitsList[uiAvailNalNum - 2],
421                                  pCurAu->pNalUnitsList[uiAvailNalNum - 1]->sNalData.sVclNal.sSliceHeaderExt.sSliceHeader.pSps)) {
422       pCurAu->uiEndPos = uiAvailNalNum - 2;
423       pCtx->bAuReadyFlag = true;
424       pCtx->bNextNewSeqBegin = CheckNextAuNewSeq (pCtx, pCurNal, pCurNal->sNalData.sVclNal.sSliceHeaderExt.sSliceHeader.pSps);
425 
426     }
427   }
428   break;
429   default:
430     break;
431   }
432 
433   return pNal;
434 }
435 
436 
CheckAccessUnitBoundaryExt(PNalUnitHeaderExt pLastNalHdrExt,PNalUnitHeaderExt pCurNalHeaderExt,PSliceHeader pLastSliceHeader,PSliceHeader pCurSliceHeader)437 bool CheckAccessUnitBoundaryExt (PNalUnitHeaderExt pLastNalHdrExt, PNalUnitHeaderExt pCurNalHeaderExt,
438                                  PSliceHeader pLastSliceHeader, PSliceHeader pCurSliceHeader) {
439   const PSps kpSps = pCurSliceHeader->pSps;
440 
441   //Sub-clause 7.1.4.1.1 temporal_id
442   if (pLastNalHdrExt->uiTemporalId != pCurNalHeaderExt->uiTemporalId) {
443     return true;
444   }
445 
446   // Subclause 7.4.1.2.5
447   if (pLastSliceHeader->iRedundantPicCnt > pCurSliceHeader->iRedundantPicCnt)
448     return true;
449 
450   // Subclause G7.4.1.2.4
451   if (pLastNalHdrExt->uiDependencyId > pCurNalHeaderExt->uiDependencyId)
452     return true;
453   if (pLastNalHdrExt->uiQualityId > pCurNalHeaderExt->uiQualityId)
454     return true;
455 
456   // Subclause 7.4.1.2.4
457   if (pLastSliceHeader->iFrameNum != pCurSliceHeader->iFrameNum)
458     return true;
459   if (pLastSliceHeader->iPpsId != pCurSliceHeader->iPpsId)
460     return true;
461   if (pLastSliceHeader->pSps->iSpsId != pCurSliceHeader->pSps->iSpsId)
462     return true;
463   if (pLastSliceHeader->bFieldPicFlag != pCurSliceHeader->bFieldPicFlag)
464     return true;
465   if (pLastSliceHeader->bBottomFiledFlag != pCurSliceHeader->bBottomFiledFlag)
466     return true;
467   if ((pLastNalHdrExt->sNalUnitHeader.uiNalRefIdc != NRI_PRI_LOWEST) != (pCurNalHeaderExt->sNalUnitHeader.uiNalRefIdc !=
468       NRI_PRI_LOWEST))
469     return true;
470   if (pLastNalHdrExt->bIdrFlag != pCurNalHeaderExt->bIdrFlag)
471     return true;
472   if (pCurNalHeaderExt->bIdrFlag) {
473     if (pLastSliceHeader->uiIdrPicId != pCurSliceHeader->uiIdrPicId)
474       return true;
475   }
476   if (kpSps->uiPocType == 0) {
477     if (pLastSliceHeader->iPicOrderCntLsb != pCurSliceHeader->iPicOrderCntLsb)
478       return true;
479     if (pLastSliceHeader->iDeltaPicOrderCntBottom != pCurSliceHeader->iDeltaPicOrderCntBottom)
480       return true;
481   } else if (kpSps->uiPocType == 1) {
482     if (pLastSliceHeader->iDeltaPicOrderCnt[0] != pCurSliceHeader->iDeltaPicOrderCnt[0])
483       return true;
484     if (pLastSliceHeader->iDeltaPicOrderCnt[1] != pCurSliceHeader->iDeltaPicOrderCnt[1])
485       return true;
486   }
487   if (memcmp (pLastSliceHeader->pPps, pCurSliceHeader->pPps, sizeof (SPps)) != 0
488       || memcmp (pLastSliceHeader->pSps, pCurSliceHeader->pSps, sizeof (SSps)) != 0) {
489     return true;
490   }
491   return false;
492 }
493 
494 
CheckAccessUnitBoundary(PWelsDecoderContext pCtx,const PNalUnit kpCurNal,const PNalUnit kpLastNal,const PSps kpSps)495 bool CheckAccessUnitBoundary (PWelsDecoderContext pCtx, const PNalUnit kpCurNal, const PNalUnit kpLastNal,
496                               const PSps kpSps) {
497   const PNalUnitHeaderExt kpLastNalHeaderExt = &kpLastNal->sNalHeaderExt;
498   const PNalUnitHeaderExt kpCurNalHeaderExt = &kpCurNal->sNalHeaderExt;
499   const SSliceHeader* kpLastSliceHeader = &kpLastNal->sNalData.sVclNal.sSliceHeaderExt.sSliceHeader;
500   const SSliceHeader* kpCurSliceHeader = &kpCurNal->sNalData.sVclNal.sSliceHeaderExt.sSliceHeader;
501   if (pCtx->sSpsPpsCtx.pActiveLayerSps[kpCurNalHeaderExt->uiDependencyId] != NULL
502       && pCtx->sSpsPpsCtx.pActiveLayerSps[kpCurNalHeaderExt->uiDependencyId] != kpSps) {
503     return true; // the active sps changed, new sequence begins, so the current au is ready
504   }
505 
506   //Sub-clause 7.1.4.1.1 temporal_id
507   if (kpLastNalHeaderExt->uiTemporalId != kpCurNalHeaderExt->uiTemporalId) {
508     return true;
509   }
510   if (kpLastSliceHeader->iFrameNum != kpCurSliceHeader->iFrameNum)
511     return true;
512   // Subclause 7.4.1.2.5
513   if (kpLastSliceHeader->iRedundantPicCnt > kpCurSliceHeader->iRedundantPicCnt)
514     return true;
515 
516   // Subclause G7.4.1.2.4
517   if (kpLastNalHeaderExt->uiDependencyId > kpCurNalHeaderExt->uiDependencyId)
518     return true;
519   // Subclause 7.4.1.2.4
520   if (kpLastNalHeaderExt->uiDependencyId == kpCurNalHeaderExt->uiDependencyId
521       && kpLastSliceHeader->iPpsId != kpCurSliceHeader->iPpsId)
522     return true;
523   if (kpLastSliceHeader->bFieldPicFlag != kpCurSliceHeader->bFieldPicFlag)
524     return true;
525   if (kpLastSliceHeader->bBottomFiledFlag != kpCurSliceHeader->bBottomFiledFlag)
526     return true;
527   if ((kpLastNalHeaderExt->sNalUnitHeader.uiNalRefIdc != NRI_PRI_LOWEST) != (kpCurNalHeaderExt->sNalUnitHeader.uiNalRefIdc
528       != NRI_PRI_LOWEST))
529     return true;
530   if (kpLastNalHeaderExt->bIdrFlag != kpCurNalHeaderExt->bIdrFlag)
531     return true;
532   if (kpCurNalHeaderExt->bIdrFlag) {
533     if (kpLastSliceHeader->uiIdrPicId != kpCurSliceHeader->uiIdrPicId)
534       return true;
535   }
536   if (kpSps->uiPocType == 0) {
537     if (kpLastSliceHeader->iPicOrderCntLsb != kpCurSliceHeader->iPicOrderCntLsb)
538       return true;
539     if (kpLastSliceHeader->iDeltaPicOrderCntBottom != kpCurSliceHeader->iDeltaPicOrderCntBottom)
540       return true;
541   } else if (kpSps->uiPocType == 1) {
542     if (kpLastSliceHeader->iDeltaPicOrderCnt[0] != kpCurSliceHeader->iDeltaPicOrderCnt[0])
543       return true;
544     if (kpLastSliceHeader->iDeltaPicOrderCnt[1] != kpCurSliceHeader->iDeltaPicOrderCnt[1])
545       return true;
546   }
547 
548   return false;
549 }
550 
CheckNextAuNewSeq(PWelsDecoderContext pCtx,const PNalUnit kpCurNal,const PSps kpSps)551 bool CheckNextAuNewSeq (PWelsDecoderContext pCtx, const PNalUnit kpCurNal, const PSps kpSps) {
552   const PNalUnitHeaderExt kpCurNalHeaderExt = &kpCurNal->sNalHeaderExt;
553   if (pCtx->sSpsPpsCtx.pActiveLayerSps[kpCurNalHeaderExt->uiDependencyId] != NULL
554       && pCtx->sSpsPpsCtx.pActiveLayerSps[kpCurNalHeaderExt->uiDependencyId] != kpSps)
555     return true;
556   if (kpCurNalHeaderExt->bIdrFlag)
557     return true;
558 
559   return false;
560 }
561 
562 /*!
563  *************************************************************************************
564  * \brief   to parse NON VCL NAL Units
565  *
566  * \param   pCtx        decoder context
567  * \param   rbsp        rbsp buffer of NAL Unit
568  * \param   src_len     length of rbsp buffer
569  *
570  * \return  0 - successed
571  *          1 - failed
572  *
573  *************************************************************************************
574  */
ParseNonVclNal(PWelsDecoderContext pCtx,uint8_t * pRbsp,const int32_t kiSrcLen,uint8_t * pSrcNal,const int32_t kSrcNalLen)575 int32_t ParseNonVclNal (PWelsDecoderContext pCtx, uint8_t* pRbsp, const int32_t kiSrcLen, uint8_t* pSrcNal,
576                         const int32_t kSrcNalLen) {
577   PBitStringAux pBs = NULL;
578   EWelsNalUnitType eNalType     = NAL_UNIT_UNSPEC_0; // make initial value as unspecified
579   int32_t iPicWidth             = 0;
580   int32_t iPicHeight            = 0;
581   int32_t iBitSize              = 0;
582   int32_t iErr                  = ERR_NONE;
583   if (kiSrcLen <= 0)
584     return iErr;
585 
586   pBs = &pCtx->sBs; // SBitStringAux instance for non VCL NALs decoding
587   iBitSize = (kiSrcLen << 3) - BsGetTrailingBits (pRbsp + kiSrcLen - 1); // convert into bit
588   eNalType = pCtx->sCurNalHead.eNalUnitType;
589 
590   switch (eNalType) {
591   case NAL_UNIT_SPS:
592   case NAL_UNIT_SUBSET_SPS:
593     if (iBitSize > 0) {
594       iErr = DecInitBits (pBs, pRbsp, iBitSize);
595       if (ERR_NONE != iErr) {
596         if (pCtx->pParam->eEcActiveIdc == ERROR_CON_DISABLE)
597           pCtx->iErrorCode |= dsNoParamSets;
598         else
599           pCtx->iErrorCode |= dsBitstreamError;
600         return iErr;
601       }
602     }
603     iErr = ParseSps (pCtx, pBs, &iPicWidth, &iPicHeight, pSrcNal, kSrcNalLen);
604     if (ERR_NONE != iErr) { // modified for pSps/pSubsetSps invalid, 12/1/2009
605       if (pCtx->pParam->eEcActiveIdc == ERROR_CON_DISABLE)
606         pCtx->iErrorCode |= dsNoParamSets;
607       else
608         pCtx->iErrorCode |= dsBitstreamError;
609       return iErr;
610     }
611     pCtx->bHasNewSps = true;
612     break;
613 
614   case NAL_UNIT_PPS:
615     if (iBitSize > 0) {
616       iErr = DecInitBits (pBs, pRbsp, iBitSize);
617       if (ERR_NONE != iErr) {
618         if (pCtx->pParam->eEcActiveIdc == ERROR_CON_DISABLE)
619           pCtx->iErrorCode |= dsNoParamSets;
620         else
621           pCtx->iErrorCode |= dsBitstreamError;
622         return iErr;
623       }
624     }
625     iErr = ParsePps (pCtx, &pCtx->sSpsPpsCtx.sPpsBuffer[0], pBs, pSrcNal, kSrcNalLen);
626     if (ERR_NONE != iErr) { // modified for pps invalid, 12/1/2009
627       if (pCtx->pParam->eEcActiveIdc == ERROR_CON_DISABLE)
628         pCtx->iErrorCode |= dsNoParamSets;
629       else
630         pCtx->iErrorCode |= dsBitstreamError;
631       pCtx->bHasNewSps = false;
632       return iErr;
633     }
634 
635     pCtx->sSpsPpsCtx.bPpsExistAheadFlag = true;
636     ++ (pCtx->sSpsPpsCtx.iSeqId);
637     break;
638 
639   case NAL_UNIT_SEI:
640 
641     break;
642 
643   case NAL_UNIT_PREFIX:
644     break;
645   case NAL_UNIT_CODED_SLICE_DPA:
646   case NAL_UNIT_CODED_SLICE_DPB:
647   case NAL_UNIT_CODED_SLICE_DPC:
648 
649     break;
650 
651   default:
652     break;
653   }
654 
655   return iErr;
656 }
657 
ParseRefBasePicMarking(PBitStringAux pBs,PRefBasePicMarking pRefBasePicMarking)658 int32_t ParseRefBasePicMarking (PBitStringAux pBs, PRefBasePicMarking pRefBasePicMarking) {
659   uint32_t uiCode;
660   WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //adaptive_ref_base_pic_marking_mode_flag
661   const bool kbAdaptiveMarkingModeFlag = !!uiCode;
662   pRefBasePicMarking->bAdaptiveRefBasePicMarkingModeFlag = kbAdaptiveMarkingModeFlag;
663   if (kbAdaptiveMarkingModeFlag) {
664     int32_t iIdx = 0;
665     do {
666       WELS_READ_VERIFY (BsGetUe (pBs, &uiCode)); //MMCO_base
667       const uint32_t kuiMmco = uiCode;
668 
669       pRefBasePicMarking->mmco_base[iIdx].uiMmcoType = kuiMmco;
670 
671       if (kuiMmco == MMCO_END)
672         break;
673 
674       if (kuiMmco == MMCO_SHORT2UNUSED) {
675         WELS_READ_VERIFY (BsGetUe (pBs, &uiCode)); //difference_of_base_pic_nums_minus1
676         pRefBasePicMarking->mmco_base[iIdx].uiDiffOfPicNums = 1 + uiCode;
677         pRefBasePicMarking->mmco_base[iIdx].iShortFrameNum  = 0;
678       } else if (kuiMmco == MMCO_LONG2UNUSED) {
679         WELS_READ_VERIFY (BsGetUe (pBs, &uiCode)); //long_term_base_pic_num
680         pRefBasePicMarking->mmco_base[iIdx].uiLongTermPicNum = uiCode;
681       }
682       ++ iIdx;
683     } while (iIdx < MAX_MMCO_COUNT);
684   }
685   return ERR_NONE;
686 }
687 
ParsePrefixNalUnit(PWelsDecoderContext pCtx,PBitStringAux pBs)688 int32_t ParsePrefixNalUnit (PWelsDecoderContext pCtx, PBitStringAux pBs) {
689   PNalUnit pCurNal = &pCtx->sSpsPpsCtx.sPrefixNal;
690   uint32_t uiCode;
691 
692   if (pCurNal->sNalHeaderExt.sNalUnitHeader.uiNalRefIdc != 0) {
693     PNalUnitHeaderExt head_ext = &pCurNal->sNalHeaderExt;
694     PPrefixNalUnit sPrefixNal = &pCurNal->sNalData.sPrefixNal;
695     WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //store_ref_base_pic_flag
696     sPrefixNal->bStoreRefBasePicFlag = !!uiCode;
697     if ((head_ext->bUseRefBasePicFlag || sPrefixNal->bStoreRefBasePicFlag) && !head_ext->bIdrFlag) {
698       WELS_READ_VERIFY (ParseRefBasePicMarking (pBs, &sPrefixNal->sRefPicBaseMarking));
699     }
700     WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //additional_prefix_nal_unit_extension_flag
701     sPrefixNal->bPrefixNalUnitAdditionalExtFlag = !!uiCode;
702     if (sPrefixNal->bPrefixNalUnitAdditionalExtFlag) {
703       WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //additional_prefix_nal_unit_extension_data_flag
704       sPrefixNal->bPrefixNalUnitExtFlag = !!uiCode;
705     }
706   }
707   return ERR_NONE;
708 }
709 
710 #define SUBSET_SPS_SEQ_SCALED_REF_LAYER_LEFT_OFFSET_MIN -32768
711 #define SUBSET_SPS_SEQ_SCALED_REF_LAYER_LEFT_OFFSET_MAX 32767
712 #define SUBSET_SPS_SEQ_SCALED_REF_LAYER_TOP_OFFSET_MIN -32768
713 #define SUBSET_SPS_SEQ_SCALED_REF_LAYER_TOP_OFFSET_MAX 32767
714 #define SUBSET_SPS_SEQ_SCALED_REF_LAYER_RIGHT_OFFSET_MIN -32768
715 #define SUBSET_SPS_SEQ_SCALED_REF_LAYER_RIGHT_OFFSET_MAX 32767
716 #define SUBSET_SPS_SEQ_SCALED_REF_LAYER_BOTTOM_OFFSET_MIN -32768
717 #define SUBSET_SPS_SEQ_SCALED_REF_LAYER_BOTTOM_OFFSET_MAX 32767
718 
719 
720 
721 
DecodeSpsSvcExt(PWelsDecoderContext pCtx,PSubsetSps pSpsExt,PBitStringAux pBs)722 int32_t DecodeSpsSvcExt (PWelsDecoderContext pCtx, PSubsetSps pSpsExt, PBitStringAux pBs) {
723   PSpsSvcExt  pExt = NULL;
724   uint32_t uiCode;
725   int32_t iCode;
726 
727   pExt = &pSpsExt->sSpsSvcExt;
728 
729   WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //inter_layer_deblocking_filter_control_present_flag
730   pExt->bInterLayerDeblockingFilterCtrlPresentFlag = !!uiCode;
731   WELS_READ_VERIFY (BsGetBits (pBs, 2, &uiCode)); //extended_spatial_scalability_idc
732   pExt->uiExtendedSpatialScalability = uiCode;
733   if (pExt->uiExtendedSpatialScalability > 2) {
734     WelsLog (& (pCtx->sLogCtx), WELS_LOG_WARNING,
735              "DecodeSpsSvcExt():extended_spatial_scalability (%d) != 0, ESS not supported!",
736              pExt->uiExtendedSpatialScalability);
737     return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_INVALID_ESS);
738   }
739 
740   pExt->uiChromaPhaseXPlus1Flag =
741     0;  // FIXME: Incoherent with JVT X201 standard (= 1), but conformance to JSVM (= 0) implementation.
742   pExt->uiChromaPhaseYPlus1 = 1;
743 
744   WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //chroma_phase_x_plus1_flag
745   pExt->uiChromaPhaseXPlus1Flag = uiCode;
746   WELS_READ_VERIFY (BsGetBits (pBs, 2, &uiCode)); //chroma_phase_y_plus1
747   pExt->uiChromaPhaseYPlus1 = uiCode;
748 
749   pExt->uiSeqRefLayerChromaPhaseXPlus1Flag = pExt->uiChromaPhaseXPlus1Flag;
750   pExt->uiSeqRefLayerChromaPhaseYPlus1     = pExt->uiChromaPhaseYPlus1;
751   memset (&pExt->sSeqScaledRefLayer, 0, sizeof (SPosOffset));
752 
753   if (pExt->uiExtendedSpatialScalability == 1) {
754     SPosOffset* const kpPos = &pExt->sSeqScaledRefLayer;
755     WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //seq_ref_layer_chroma_phase_x_plus1_flag
756     pExt->uiSeqRefLayerChromaPhaseXPlus1Flag = uiCode;
757     WELS_READ_VERIFY (BsGetBits (pBs, 2, &uiCode)); //seq_ref_layer_chroma_phase_y_plus1
758     pExt->uiSeqRefLayerChromaPhaseYPlus1 = uiCode;
759 
760     WELS_READ_VERIFY (BsGetSe (pBs, &iCode)); //seq_scaled_ref_layer_left_offset
761     kpPos->iLeftOffset = iCode;
762     WELS_CHECK_SE_BOTH_WARNING (kpPos->iLeftOffset, SUBSET_SPS_SEQ_SCALED_REF_LAYER_LEFT_OFFSET_MIN,
763                                 SUBSET_SPS_SEQ_SCALED_REF_LAYER_LEFT_OFFSET_MAX, "seq_scaled_ref_layer_left_offset");
764     WELS_READ_VERIFY (BsGetSe (pBs, &iCode)); //seq_scaled_ref_layer_top_offset
765     kpPos->iTopOffset = iCode;
766     WELS_CHECK_SE_BOTH_WARNING (kpPos->iTopOffset, SUBSET_SPS_SEQ_SCALED_REF_LAYER_TOP_OFFSET_MIN,
767                                 SUBSET_SPS_SEQ_SCALED_REF_LAYER_TOP_OFFSET_MAX, "seq_scaled_ref_layer_top_offset");
768     WELS_READ_VERIFY (BsGetSe (pBs, &iCode)); //seq_scaled_ref_layer_right_offset
769     kpPos->iRightOffset = iCode;
770     WELS_CHECK_SE_BOTH_WARNING (kpPos->iRightOffset, SUBSET_SPS_SEQ_SCALED_REF_LAYER_RIGHT_OFFSET_MIN,
771                                 SUBSET_SPS_SEQ_SCALED_REF_LAYER_RIGHT_OFFSET_MAX, "seq_scaled_ref_layer_right_offset");
772     WELS_READ_VERIFY (BsGetSe (pBs, &iCode)); //seq_scaled_ref_layer_bottom_offset
773     kpPos->iBottomOffset = iCode;
774     WELS_CHECK_SE_BOTH_WARNING (kpPos->iBottomOffset, SUBSET_SPS_SEQ_SCALED_REF_LAYER_BOTTOM_OFFSET_MIN,
775                                 SUBSET_SPS_SEQ_SCALED_REF_LAYER_BOTTOM_OFFSET_MAX, "seq_scaled_ref_layer_bottom_offset");
776   }
777 
778   WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //seq_tcoeff_level_prediction_flag
779   pExt->bSeqTCoeffLevelPredFlag = !!uiCode;
780   pExt->bAdaptiveTCoeffLevelPredFlag = false;
781   if (pExt->bSeqTCoeffLevelPredFlag) {
782     WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //adaptive_tcoeff_level_prediction_flag
783     pExt->bAdaptiveTCoeffLevelPredFlag = !!uiCode;
784   }
785   WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //slice_header_restriction_flag
786   pExt->bSliceHeaderRestrictionFlag = !!uiCode;
787 
788 
789 
790   return ERR_NONE;
791 }
792 
GetLevelLimits(int32_t iLevelIdx,bool bConstraint3)793 const SLevelLimits* GetLevelLimits (int32_t iLevelIdx, bool bConstraint3) {
794   switch (iLevelIdx) {
795   case 9:
796     return &g_ksLevelLimits[1];
797   case 10:
798     return &g_ksLevelLimits[0];
799   case 11:
800     if (bConstraint3)
801       return &g_ksLevelLimits[1];
802     else
803       return &g_ksLevelLimits[2];
804   case 12:
805     return &g_ksLevelLimits[3];
806   case 13:
807     return &g_ksLevelLimits[4];
808   case 20:
809     return &g_ksLevelLimits[5];
810   case 21:
811     return &g_ksLevelLimits[6];
812   case 22:
813     return &g_ksLevelLimits[7];
814   case 30:
815     return &g_ksLevelLimits[8];
816   case 31:
817     return &g_ksLevelLimits[9];
818   case 32:
819     return &g_ksLevelLimits[10];
820   case 40:
821     return &g_ksLevelLimits[11];
822   case 41:
823     return &g_ksLevelLimits[12];
824   case 42:
825     return &g_ksLevelLimits[13];
826   case 50:
827     return &g_ksLevelLimits[14];
828   case 51:
829     return &g_ksLevelLimits[15];
830   case 52:
831     return &g_ksLevelLimits[16];
832   default:
833     return NULL;
834   }
835   return NULL;
836 }
837 
CheckSpsActive(PWelsDecoderContext pCtx,PSps pSps,bool bUseSubsetFlag)838 bool CheckSpsActive (PWelsDecoderContext pCtx, PSps pSps, bool bUseSubsetFlag) {
839   for (int i = 0; i < MAX_LAYER_NUM; i++) {
840     if (pCtx->sSpsPpsCtx.pActiveLayerSps[i] == pSps)
841       return true;
842   }
843   // Pre-active, will be used soon
844   if (bUseSubsetFlag) {
845     if (pSps->iMbWidth > 0 && pSps->iMbHeight > 0 && pCtx->sSpsPpsCtx.bSubspsAvailFlags[pSps->iSpsId]) {
846       if (pCtx->iTotalNumMbRec > 0) {
847         return true;
848       }
849       if (pCtx->pAccessUnitList->uiAvailUnitsNum > 0) {
850         int i = 0, iNum = (int32_t) pCtx->pAccessUnitList->uiAvailUnitsNum;
851         while (i < iNum) {
852           PNalUnit pNalUnit = pCtx->pAccessUnitList->pNalUnitsList[i];
853           if (pNalUnit->sNalData.sVclNal.bSliceHeaderExtFlag) { //ext data
854             PSps pNextUsedSps = pNalUnit->sNalData.sVclNal.sSliceHeaderExt.sSliceHeader.pSps;
855             if (pNextUsedSps->iSpsId == pSps->iSpsId)
856               return true;
857           }
858           ++i;
859         }
860       }
861     }
862   } else {
863     if (pSps->iMbWidth > 0 && pSps->iMbHeight > 0 && pCtx->sSpsPpsCtx.bSpsAvailFlags[pSps->iSpsId]) {
864       if (pCtx->iTotalNumMbRec > 0) {
865         return true;
866       }
867       if (pCtx->pAccessUnitList->uiAvailUnitsNum > 0) {
868         int i = 0, iNum = (int32_t) pCtx->pAccessUnitList->uiAvailUnitsNum;
869         while (i < iNum) {
870           PNalUnit pNalUnit = pCtx->pAccessUnitList->pNalUnitsList[i];
871           if (!pNalUnit->sNalData.sVclNal.bSliceHeaderExtFlag) { //non-ext data
872             PSps pNextUsedSps = pNalUnit->sNalData.sVclNal.sSliceHeaderExt.sSliceHeader.pSps;
873             if (pNextUsedSps->iSpsId == pSps->iSpsId)
874               return true;
875           }
876           ++i;
877         }
878       }
879     }
880   }
881   return false;
882 }
883 
884 #define  SPS_LOG2_MAX_FRAME_NUM_MINUS4_MAX 12
885 #define  SPS_LOG2_MAX_PIC_ORDER_CNT_LSB_MINUS4_MAX 12
886 #define  SPS_NUM_REF_FRAMES_IN_PIC_ORDER_CNT_CYCLE_MAX 255
887 #define  SPS_MAX_NUM_REF_FRAMES_MAX 16
888 #define  PPS_PIC_INIT_QP_QS_MIN 0
889 #define  PPS_PIC_INIT_QP_QS_MAX 51
890 #define  PPS_CHROMA_QP_INDEX_OFFSET_MIN -12
891 #define  PPS_CHROMA_QP_INDEX_OFFSET_MAX 12
892 #define  SCALING_LIST_DELTA_SCALE_MAX 127
893 #define SCALING_LIST_DELTA_SCALE_MIN -128
894 
895 /*!
896  *************************************************************************************
897  * \brief   to parse Sequence Parameter Set (SPS)
898  *
899  * \param   pCtx        Decoder context
900  * \param   pBsAux      bitstream reader auxiliary
901  * \param   pPicWidth   picture width current Sps represented
902  * \param   pPicHeight  picture height current Sps represented
903  *
904  * \return  0 - successed
905  *      1 - failed
906  *
907  * \note    Call it in case eNalUnitType is SPS.
908  *************************************************************************************
909  */
910 
ParseSps(PWelsDecoderContext pCtx,PBitStringAux pBsAux,int32_t * pPicWidth,int32_t * pPicHeight,uint8_t * pSrcNal,const int32_t kSrcNalLen)911 int32_t ParseSps (PWelsDecoderContext pCtx, PBitStringAux pBsAux, int32_t* pPicWidth, int32_t* pPicHeight,
912                   uint8_t* pSrcNal, const int32_t kSrcNalLen) {
913   PBitStringAux pBs = pBsAux;
914   SSubsetSps sTempSubsetSps;
915   PSps pSps = NULL;
916   PSubsetSps pSubsetSps = NULL;
917   SNalUnitHeader* pNalHead = &pCtx->sCurNalHead;
918   ProfileIdc uiProfileIdc;
919   uint8_t uiLevelIdc;
920   int32_t iSpsId;
921   uint32_t uiCode;
922   int32_t iCode;
923   int32_t iRet = ERR_NONE;
924   bool bConstraintSetFlags[6] = { false };
925   const bool kbUseSubsetFlag   = IS_SUBSET_SPS_NAL (pNalHead->eNalUnitType);
926 
927   WELS_READ_VERIFY (BsGetBits (pBs, 8, &uiCode)); //profile_idc
928   uiProfileIdc = uiCode;
929   if (uiProfileIdc != PRO_BASELINE && uiProfileIdc != PRO_MAIN && uiProfileIdc != PRO_SCALABLE_BASELINE
930       && uiProfileIdc != PRO_SCALABLE_HIGH
931       && uiProfileIdc != PRO_EXTENDED && uiProfileIdc != PRO_HIGH) {
932     WelsLog (& (pCtx->sLogCtx), WELS_LOG_WARNING, "SPS ID can not be supported!\n");
933     return false;
934   }
935   WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //constraint_set0_flag
936   bConstraintSetFlags[0] = !!uiCode;
937   WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //constraint_set1_flag
938   bConstraintSetFlags[1] = !!uiCode;
939   WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //constraint_set2_flag
940   bConstraintSetFlags[2] = !!uiCode;
941   WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //constraint_set3_flag
942   bConstraintSetFlags[3] = !!uiCode;
943   WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //constraint_set4_flag
944   bConstraintSetFlags[4] = !!uiCode;
945   WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //constraint_set5_flag
946   bConstraintSetFlags[5] = !!uiCode;
947   WELS_READ_VERIFY (BsGetBits (pBs, 2, &uiCode)); // reserved_zero_2bits, equal to 0
948   WELS_READ_VERIFY (BsGetBits (pBs, 8, &uiCode)); // level_idc
949   uiLevelIdc = uiCode;
950   WELS_READ_VERIFY (BsGetUe (pBs, &uiCode)); //seq_parameter_set_id
951   if (uiCode >= MAX_SPS_COUNT) { // Modified to check invalid negative iSpsId, 12/1/2009
952     WelsLog (& (pCtx->sLogCtx), WELS_LOG_WARNING, " iSpsId is out of range! \n");
953     return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_SPS_ID_OVERFLOW);
954   }
955   iSpsId = uiCode;
956   pSubsetSps = &sTempSubsetSps;
957   pSps = &sTempSubsetSps.sSps;
958   memset (pSubsetSps, 0, sizeof (SSubsetSps));
959   // Use the level 5.2 for compatibility
960   const SLevelLimits* pSMaxLevelLimits = GetLevelLimits (52, false);
961   const SLevelLimits* pSLevelLimits = GetLevelLimits (uiLevelIdc, bConstraintSetFlags[3]);
962   if (NULL == pSLevelLimits) {
963     WelsLog (& (pCtx->sLogCtx), WELS_LOG_WARNING, "ParseSps(): level_idx (%d).\n", uiLevelIdc);
964     return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_UNSUPPORTED_NON_BASELINE);
965   } else pSps->pSLevelLimits = pSLevelLimits;
966   // syntax elements in default
967   pSps->uiChromaFormatIdc = 1;
968   pSps->uiChromaArrayType = 1;
969 
970   pSps->uiProfileIdc = uiProfileIdc;
971   pSps->uiLevelIdc   = uiLevelIdc;
972   pSps->iSpsId       = iSpsId;
973 
974   if (PRO_SCALABLE_BASELINE == uiProfileIdc || PRO_SCALABLE_HIGH == uiProfileIdc ||
975       PRO_HIGH == uiProfileIdc || PRO_HIGH10 == uiProfileIdc ||
976       PRO_HIGH422 == uiProfileIdc || PRO_HIGH444 == uiProfileIdc ||
977       PRO_CAVLC444 == uiProfileIdc || 44 == uiProfileIdc) {
978 
979     WELS_READ_VERIFY (BsGetUe (pBs, &uiCode)); //chroma_format_idc
980     pSps->uiChromaFormatIdc = uiCode;
981 //    if (pSps->uiChromaFormatIdc != 1) {
982 //      WelsLog (& (pCtx->sLogCtx), WELS_LOG_WARNING, "ParseSps(): chroma_format_idc (%d) = 1 supported.",
983 //               pSps->uiChromaFormatIdc);
984 //      return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_UNSUPPORTED_NON_BASELINE);
985 //    }
986     if (pSps->uiChromaFormatIdc > 1) {
987       WelsLog (& (pCtx->sLogCtx), WELS_LOG_WARNING, "ParseSps(): chroma_format_idc (%d) <=1 supported.",
988                pSps->uiChromaFormatIdc);
989       return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_UNSUPPORTED_NON_BASELINE);
990 
991     }// To support 4:0:0; 4:2:0
992     pSps->uiChromaArrayType = pSps->uiChromaFormatIdc;
993     WELS_READ_VERIFY (BsGetUe (pBs, &uiCode)); //bit_depth_luma_minus8
994     if (uiCode != 0) {
995       WelsLog (& (pCtx->sLogCtx), WELS_LOG_WARNING, "ParseSps(): bit_depth_luma (%d) Only 8 bit supported.", 8 + uiCode);
996       return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_UNSUPPORTED_NON_BASELINE);
997     }
998     pSps->uiBitDepthLuma = 8;
999 
1000     WELS_READ_VERIFY (BsGetUe (pBs, &uiCode)); //bit_depth_chroma_minus8
1001     if (uiCode != 0) {
1002       WelsLog (& (pCtx->sLogCtx), WELS_LOG_WARNING, "ParseSps(): bit_depth_chroma (%d). Only 8 bit supported.", 8 + uiCode);
1003       return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_UNSUPPORTED_NON_BASELINE);
1004     }
1005     pSps->uiBitDepthChroma = 8;
1006 
1007     WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //qpprime_y_zero_transform_bypass_flag
1008     pSps->bQpPrimeYZeroTransfBypassFlag = !!uiCode;
1009     WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //seq_scaling_matrix_present_flag
1010     pSps->bSeqScalingMatrixPresentFlag = !!uiCode;
1011 
1012     if (pSps->bSeqScalingMatrixPresentFlag) {
1013       WELS_READ_VERIFY (ParseScalingList (pSps, pBs, 0, 0, pSps->bSeqScalingListPresentFlag, pSps->iScalingList4x4,
1014                                           pSps->iScalingList8x8));
1015     }
1016   }
1017   WELS_READ_VERIFY (BsGetUe (pBs, &uiCode)); //log2_max_frame_num_minus4
1018   WELS_CHECK_SE_UPPER_ERROR (uiCode, SPS_LOG2_MAX_FRAME_NUM_MINUS4_MAX, "log2_max_frame_num_minus4",
1019                              GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_INVALID_LOG2_MAX_FRAME_NUM_MINUS4));
1020   pSps->uiLog2MaxFrameNum = LOG2_MAX_FRAME_NUM_OFFSET + uiCode;
1021   WELS_READ_VERIFY (BsGetUe (pBs, &uiCode)); //pic_order_cnt_type
1022   pSps->uiPocType = uiCode;
1023 
1024   if (0 == pSps->uiPocType) {
1025     WELS_READ_VERIFY (BsGetUe (pBs, &uiCode)); //log2_max_pic_order_cnt_lsb_minus4
1026     // log2_max_pic_order_cnt_lsb_minus4 should be in range 0 to 12, inclusive. (sec. 7.4.3)
1027     WELS_CHECK_SE_UPPER_ERROR (uiCode, SPS_LOG2_MAX_PIC_ORDER_CNT_LSB_MINUS4_MAX, "log2_max_pic_order_cnt_lsb_minus4",
1028                                GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_INVALID_LOG2_MAX_PIC_ORDER_CNT_LSB_MINUS4));
1029     pSps->iLog2MaxPocLsb = LOG2_MAX_PIC_ORDER_CNT_LSB_OFFSET + uiCode; // log2_max_pic_order_cnt_lsb_minus4
1030 
1031   } else if (1 == pSps->uiPocType) {
1032     int32_t i;
1033     WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //delta_pic_order_always_zero_flag
1034     pSps->bDeltaPicOrderAlwaysZeroFlag = !!uiCode;
1035     WELS_READ_VERIFY (BsGetSe (pBs, &iCode)); //offset_for_non_ref_pic
1036     pSps->iOffsetForNonRefPic = iCode;
1037     WELS_READ_VERIFY (BsGetSe (pBs, &iCode)); //offset_for_top_to_bottom_field
1038     pSps->iOffsetForTopToBottomField = iCode;
1039     WELS_READ_VERIFY (BsGetUe (pBs, &uiCode)); //num_ref_frames_in_pic_order_cnt_cycle
1040     WELS_CHECK_SE_UPPER_ERROR (uiCode, SPS_NUM_REF_FRAMES_IN_PIC_ORDER_CNT_CYCLE_MAX,
1041                                "num_ref_frames_in_pic_order_cnt_cycle", GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS,
1042                                    ERR_INFO_INVALID_NUM_REF_FRAME_IN_PIC_ORDER_CNT_CYCLE));
1043     pSps->iNumRefFramesInPocCycle = uiCode;
1044     for (i = 0; i < pSps->iNumRefFramesInPocCycle; i++) {
1045       WELS_READ_VERIFY (BsGetSe (pBs, &iCode)); //offset_for_ref_frame[ i ]
1046       pSps->iOffsetForRefFrame[ i ] = iCode;
1047     }
1048   }
1049   if (pSps->uiPocType > 2) {
1050     WelsLog (& (pCtx->sLogCtx), WELS_LOG_WARNING, " illegal pic_order_cnt_type: %d ! ", pSps->uiPocType);
1051     return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_INVALID_POC_TYPE);
1052   }
1053 
1054   WELS_READ_VERIFY (BsGetUe (pBs, &uiCode)); //max_num_ref_frames
1055   pSps->iNumRefFrames = uiCode;
1056   WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //gaps_in_frame_num_value_allowed_flag
1057   pSps->bGapsInFrameNumValueAllowedFlag = !!uiCode;
1058   WELS_READ_VERIFY (BsGetUe (pBs, &uiCode)); //pic_width_in_mbs_minus1
1059   pSps->iMbWidth = PIC_WIDTH_IN_MBS_OFFSET + uiCode;
1060   if (pSps->iMbWidth > MAX_MB_SIZE || pSps->iMbWidth == 0) {
1061     WelsLog (& (pCtx->sLogCtx), WELS_LOG_ERROR, "pic_width_in_mbs(%d) invalid!", pSps->iMbWidth);
1062     return  GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_INVALID_MAX_MB_SIZE);
1063   }
1064   if (((uint64_t)pSps->iMbWidth * (uint64_t)pSps->iMbWidth) > (uint64_t) (8 * pSLevelLimits->uiMaxFS)) {
1065     if (((uint64_t)pSps->iMbWidth * (uint64_t)pSps->iMbWidth) > (uint64_t) (8 * pSMaxLevelLimits->uiMaxFS)) {
1066       WelsLog (& (pCtx->sLogCtx), WELS_LOG_ERROR, "the pic_width_in_mbs exceeds the level limits!");
1067       return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_INVALID_MAX_MB_SIZE);
1068     } else {
1069       WelsLog (& (pCtx->sLogCtx), WELS_LOG_WARNING, "the pic_width_in_mbs exceeds the level limits!");
1070     }
1071   }
1072   WELS_READ_VERIFY (BsGetUe (pBs, &uiCode)); //pic_height_in_map_units_minus1
1073   pSps->iMbHeight = PIC_HEIGHT_IN_MAP_UNITS_OFFSET + uiCode;
1074   if (pSps->iMbHeight > MAX_MB_SIZE || pSps->iMbHeight == 0) {
1075     WelsLog (& (pCtx->sLogCtx), WELS_LOG_ERROR, "pic_height_in_mbs(%d) invalid!", pSps->iMbHeight);
1076     return  GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_INVALID_MAX_MB_SIZE);
1077   }
1078   if (((uint64_t)pSps->iMbHeight * (uint64_t)pSps->iMbHeight) > (uint64_t) (8 * pSLevelLimits->uiMaxFS)) {
1079     if (((uint64_t)pSps->iMbHeight * (uint64_t)pSps->iMbHeight) > (uint64_t) (8 * pSMaxLevelLimits->uiMaxFS)) {
1080       WelsLog (& (pCtx->sLogCtx), WELS_LOG_ERROR, "the pic_height_in_mbs exceeds the level limits!");
1081       return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_INVALID_MAX_MB_SIZE);
1082     } else {
1083       WelsLog (& (pCtx->sLogCtx), WELS_LOG_WARNING, "the pic_height_in_mbs exceeds the level limits!");
1084     }
1085   }
1086   uint64_t uiTmp64 = (uint64_t)pSps->iMbWidth * (uint64_t)pSps->iMbHeight;
1087   if (uiTmp64 > (uint64_t)pSLevelLimits->uiMaxFS) {
1088     if (uiTmp64 > (uint64_t)pSMaxLevelLimits->uiMaxFS) {
1089       WelsLog (& (pCtx->sLogCtx), WELS_LOG_ERROR, "the total count of mb exceeds the level limits!");
1090       return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_INVALID_MAX_MB_SIZE);
1091     } else {
1092       WelsLog (& (pCtx->sLogCtx), WELS_LOG_WARNING, "the total count of mb exceeds the level limits!");
1093     }
1094   }
1095   pSps->uiTotalMbCount = (uint32_t)uiTmp64;
1096   WELS_CHECK_SE_UPPER_ERROR (pSps->iNumRefFrames, SPS_MAX_NUM_REF_FRAMES_MAX, "max_num_ref_frames",
1097                              GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_INVALID_MAX_NUM_REF_FRAMES));
1098   // here we check max_num_ref_frames
1099   uint32_t uiMaxDpbMbs = pSLevelLimits->uiMaxDPBMbs;
1100   uint32_t uiMaxDpbFrames = uiMaxDpbMbs / pSps->uiTotalMbCount;
1101   if (uiMaxDpbFrames > SPS_MAX_NUM_REF_FRAMES_MAX)
1102     uiMaxDpbFrames = SPS_MAX_NUM_REF_FRAMES_MAX;
1103   if ((uint32_t)pSps->iNumRefFrames > uiMaxDpbFrames) {
1104     WelsLog (& (pCtx->sLogCtx), WELS_LOG_WARNING, " max_num_ref_frames exceeds level limits!");
1105   }
1106   WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //frame_mbs_only_flag
1107   pSps->bFrameMbsOnlyFlag = !!uiCode;
1108   if (!pSps->bFrameMbsOnlyFlag) {
1109     WelsLog (& (pCtx->sLogCtx), WELS_LOG_WARNING, "ParseSps(): frame_mbs_only_flag (%d) not supported.",
1110              pSps->bFrameMbsOnlyFlag);
1111     return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_UNSUPPORTED_MBAFF);
1112   }
1113   WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //direct_8x8_inference_flag
1114   pSps->bDirect8x8InferenceFlag = !!uiCode;
1115   WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //frame_cropping_flag
1116   pSps->bFrameCroppingFlag = !!uiCode;
1117   if (pSps->bFrameCroppingFlag) {
1118     WELS_READ_VERIFY (BsGetUe (pBs, &uiCode)); //frame_crop_left_offset
1119     pSps->sFrameCrop.iLeftOffset = uiCode;
1120     WELS_READ_VERIFY (BsGetUe (pBs, &uiCode)); //frame_crop_right_offset
1121     pSps->sFrameCrop.iRightOffset = uiCode;
1122     if ((pSps->sFrameCrop.iLeftOffset + pSps->sFrameCrop.iRightOffset) > ((int32_t)pSps->iMbWidth * 16 / 2)) {
1123       WelsLog (& (pCtx->sLogCtx), WELS_LOG_ERROR, "frame_crop_left_offset + frame_crop_right_offset exceeds limits!");
1124       return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_INVALID_CROPPING_DATA);
1125     }
1126     WELS_READ_VERIFY (BsGetUe (pBs, &uiCode)); //frame_crop_top_offset
1127     pSps->sFrameCrop.iTopOffset = uiCode;
1128     WELS_READ_VERIFY (BsGetUe (pBs, &uiCode)); //frame_crop_bottom_offset
1129     pSps->sFrameCrop.iBottomOffset = uiCode;
1130     if ((pSps->sFrameCrop.iTopOffset + pSps->sFrameCrop.iBottomOffset) > ((int32_t)pSps->iMbHeight * 16 / 2)) {
1131       WelsLog (& (pCtx->sLogCtx), WELS_LOG_ERROR, "frame_crop_top_offset + frame_crop_right_offset exceeds limits!");
1132       return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_INVALID_CROPPING_DATA);
1133     }
1134   } else {
1135     pSps->sFrameCrop.iLeftOffset   = 0; // frame_crop_left_offset
1136     pSps->sFrameCrop.iRightOffset  = 0; // frame_crop_right_offset
1137     pSps->sFrameCrop.iTopOffset    = 0; // frame_crop_top_offset
1138     pSps->sFrameCrop.iBottomOffset = 0; // frame_crop_bottom_offset
1139   }
1140   WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //vui_parameters_present_flag
1141   pSps->bVuiParamPresentFlag = !!uiCode;
1142   if (pSps->bVuiParamPresentFlag) {
1143     int iRetVui = ParseVui (pCtx, pSps, pBsAux);
1144     if (iRetVui == GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_UNSUPPORTED_VUI_HRD)) {
1145       if (kbUseSubsetFlag) { //Currently do no support VUI with HRD enable in subsetSPS
1146         WelsLog (& (pCtx->sLogCtx), WELS_LOG_ERROR, "hrd parse in vui of subsetSPS is not supported!");
1147         return iRetVui;
1148       }
1149     } else {
1150       WELS_READ_VERIFY (iRetVui);
1151     }
1152   }
1153 
1154   if (pCtx->pParam->bParseOnly) {
1155     if (kSrcNalLen >= SPS_PPS_BS_SIZE - 4) { //sps bs exceeds!
1156       WelsLog (& (pCtx->sLogCtx), WELS_LOG_WARNING, "sps payload size (%d) too large for parse only (%d), not supported!",
1157                kSrcNalLen, SPS_PPS_BS_SIZE - 4);
1158       pCtx->iErrorCode |= dsBitstreamError;
1159       return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_OUT_OF_MEMORY);
1160     }
1161     if (!kbUseSubsetFlag) { //SPS
1162       SSpsBsInfo* pSpsBs = &pCtx->sSpsBsInfo [iSpsId];
1163       pSpsBs->iSpsId = iSpsId;
1164       int32_t iTrailingZeroByte = 0;
1165       while (pSrcNal[kSrcNalLen - iTrailingZeroByte - 1] == 0x0) //remove final trailing 0 bytes
1166         iTrailingZeroByte++;
1167       int32_t iActualLen = kSrcNalLen - iTrailingZeroByte;
1168       pSpsBs->uiSpsBsLen = (uint16_t) iActualLen;
1169       //unify start code as 0x0001
1170       int32_t iStartDeltaByte = 0; //0 for 0x0001, 1 for 0x001
1171       if (pSrcNal[0] == 0x0 && pSrcNal[1] == 0x0 && pSrcNal[2] == 0x1) { //if 0x001
1172         pSpsBs->pSpsBsBuf[0] = 0x0; //add 0 to form 0x0001
1173         iStartDeltaByte++;
1174         pSpsBs->uiSpsBsLen++;
1175       }
1176       memcpy (pSpsBs->pSpsBsBuf + iStartDeltaByte, pSrcNal, iActualLen);
1177     } else { //subset SPS
1178       SSpsBsInfo* pSpsBs = &pCtx->sSubsetSpsBsInfo [iSpsId];
1179       pSpsBs->iSpsId = iSpsId;
1180       pSpsBs->pSpsBsBuf [0] = pSpsBs->pSpsBsBuf [1] = pSpsBs->pSpsBsBuf [2] = 0x00;
1181       pSpsBs->pSpsBsBuf [3] = 0x01;
1182       pSpsBs->pSpsBsBuf [4] = 0x67;
1183 
1184       //re-write subset SPS to SPS
1185       SBitStringAux sSubsetSpsBs;
1186       CMemoryAlign* pMa = pCtx->pMemAlign;
1187 
1188       uint8_t* pBsBuf = static_cast<uint8_t*> (pMa->WelsMallocz (SPS_PPS_BS_SIZE + 4,
1189                         "Temp buffer for parse only usage.")); //to reserve 4 bytes for UVLC writing buffer
1190       if (NULL == pBsBuf) {
1191         WelsLog (& (pCtx->sLogCtx), WELS_LOG_ERROR, "sps buffer alloc failed for parse only!");
1192         pCtx->iErrorCode |= dsOutOfMemory;
1193         return pCtx->iErrorCode;
1194       }
1195       InitBits (&sSubsetSpsBs, pBsBuf, (int32_t) (pBs->pEndBuf - pBs->pStartBuf));
1196       BsWriteBits (&sSubsetSpsBs, 8, 77); //profile_idc, forced to Main profile
1197       BsWriteOneBit (&sSubsetSpsBs, pSps->bConstraintSet0Flag); // constraint_set0_flag
1198       BsWriteOneBit (&sSubsetSpsBs, pSps->bConstraintSet1Flag); // constraint_set1_flag
1199       BsWriteOneBit (&sSubsetSpsBs, pSps->bConstraintSet2Flag); // constraint_set2_flag
1200       BsWriteOneBit (&sSubsetSpsBs, pSps->bConstraintSet3Flag); // constraint_set3_flag
1201       BsWriteBits (&sSubsetSpsBs, 4, 0); //constraint_set4_flag, constraint_set5_flag, reserved_zero_2bits
1202       BsWriteBits (&sSubsetSpsBs, 8, pSps->uiLevelIdc); //level_idc
1203       BsWriteUE (&sSubsetSpsBs, pSps->iSpsId); //sps_id
1204       BsWriteUE (&sSubsetSpsBs, pSps->uiLog2MaxFrameNum - 4); //log2_max_frame_num_minus4
1205       BsWriteUE (&sSubsetSpsBs, pSps->uiPocType); //pic_order_cnt_type
1206       if (pSps->uiPocType == 0) {
1207         BsWriteUE (&sSubsetSpsBs, pSps->iLog2MaxPocLsb - 4); //log2_max_pic_order_cnt_lsb_minus4
1208       } else if (pSps->uiPocType == 1) {
1209         BsWriteOneBit (&sSubsetSpsBs, pSps->bDeltaPicOrderAlwaysZeroFlag); //delta_pic_order_always_zero_flag
1210         BsWriteSE (&sSubsetSpsBs, pSps->iOffsetForNonRefPic); //offset_for_no_ref_pic
1211         BsWriteSE (&sSubsetSpsBs, pSps->iOffsetForTopToBottomField); //offset_for_top_to_bottom_field
1212         BsWriteUE (&sSubsetSpsBs, pSps->iNumRefFramesInPocCycle); //num_ref_frames_in_pic_order_cnt_cycle
1213         for (int32_t i = 0; i < pSps->iNumRefFramesInPocCycle; ++i) {
1214           BsWriteSE (&sSubsetSpsBs, pSps->iOffsetForRefFrame[i]); //offset_for_ref_frame[i]
1215         }
1216       }
1217       BsWriteUE (&sSubsetSpsBs, pSps->iNumRefFrames); //max_num_ref_frames
1218       BsWriteOneBit (&sSubsetSpsBs, pSps->bGapsInFrameNumValueAllowedFlag); //gaps_in_frame_num_value_allowed_flag
1219       BsWriteUE (&sSubsetSpsBs, pSps->iMbWidth - 1); //pic_width_in_mbs_minus1
1220       BsWriteUE (&sSubsetSpsBs, pSps->iMbHeight - 1); //pic_height_in_map_units_minus1
1221       BsWriteOneBit (&sSubsetSpsBs, pSps->bFrameMbsOnlyFlag); //frame_mbs_only_flag
1222       if (!pSps->bFrameMbsOnlyFlag) {
1223         BsWriteOneBit (&sSubsetSpsBs, pSps->bMbaffFlag); //mb_adaptive_frame_field_flag
1224       }
1225       BsWriteOneBit (&sSubsetSpsBs, pSps->bDirect8x8InferenceFlag); //direct_8x8_inference_flag
1226       BsWriteOneBit (&sSubsetSpsBs, pSps->bFrameCroppingFlag); //frame_cropping_flag
1227       if (pSps->bFrameCroppingFlag) {
1228         BsWriteUE (&sSubsetSpsBs, pSps->sFrameCrop.iLeftOffset); //frame_crop_left_offset
1229         BsWriteUE (&sSubsetSpsBs, pSps->sFrameCrop.iRightOffset); //frame_crop_right_offset
1230         BsWriteUE (&sSubsetSpsBs, pSps->sFrameCrop.iTopOffset); //frame_crop_top_offset
1231         BsWriteUE (&sSubsetSpsBs, pSps->sFrameCrop.iBottomOffset); //frame_crop_bottom_offset
1232       }
1233       BsWriteOneBit (&sSubsetSpsBs, 0); //vui_parameters_present_flag
1234       BsRbspTrailingBits (&sSubsetSpsBs); //finished, rbsp trailing bit
1235       int32_t iRbspSize = (int32_t) (sSubsetSpsBs.pCurBuf - sSubsetSpsBs.pStartBuf);
1236       RBSP2EBSP (pSpsBs->pSpsBsBuf + 5, sSubsetSpsBs.pStartBuf, iRbspSize);
1237       pSpsBs->uiSpsBsLen = (uint16_t) (sSubsetSpsBs.pCurBuf - sSubsetSpsBs.pStartBuf + 5);
1238       if (pBsBuf) {
1239         pMa->WelsFree (pBsBuf, "pBsBuf for parse only usage");
1240       }
1241     }
1242   }
1243   // Check if SPS SVC extension applicated
1244   if (kbUseSubsetFlag && (PRO_SCALABLE_BASELINE == uiProfileIdc || PRO_SCALABLE_HIGH == uiProfileIdc)) {
1245     if ((iRet = DecodeSpsSvcExt (pCtx, pSubsetSps, pBs)) != ERR_NONE) {
1246       return iRet;
1247     }
1248 
1249     WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //svc_vui_parameters_present_flag
1250     pSubsetSps->bSvcVuiParamPresentFlag = !!uiCode;
1251     if (pSubsetSps->bSvcVuiParamPresentFlag) {
1252     }
1253   }
1254 
1255 
1256   if (PRO_SCALABLE_BASELINE == uiProfileIdc || PRO_SCALABLE_HIGH == uiProfileIdc)
1257     pCtx->sSpsPpsCtx.bAvcBasedFlag = false;
1258 
1259   *pPicWidth  = pSps->iMbWidth << 4;
1260   *pPicHeight = pSps->iMbHeight << 4;
1261   PSps pTmpSps = NULL;
1262   if (kbUseSubsetFlag) {
1263     pTmpSps = &pCtx->sSpsPpsCtx.sSubsetSpsBuffer[iSpsId].sSps;
1264   } else {
1265     pTmpSps = &pCtx->sSpsPpsCtx.sSpsBuffer[iSpsId];
1266   }
1267   if (CheckSpsActive (pCtx, pTmpSps, kbUseSubsetFlag)) {
1268     // we are overwriting the active sps, copy a temp buffer
1269     if (kbUseSubsetFlag) {
1270       if (memcmp (&pCtx->sSpsPpsCtx.sSubsetSpsBuffer[iSpsId], pSubsetSps, sizeof (SSubsetSps)) != 0) {
1271         if (pCtx->pAccessUnitList->uiAvailUnitsNum > 0) {
1272           memcpy (&pCtx->sSpsPpsCtx.sSubsetSpsBuffer[MAX_SPS_COUNT], pSubsetSps, sizeof (SSubsetSps));
1273           pCtx->bAuReadyFlag = true;
1274           pCtx->pAccessUnitList->uiEndPos = pCtx->pAccessUnitList->uiAvailUnitsNum - 1;
1275           pCtx->sSpsPpsCtx.iOverwriteFlags |= OVERWRITE_SUBSETSPS;
1276         } else if ((pCtx->pSps != NULL) && (pCtx->pSps->iSpsId == pSubsetSps->sSps.iSpsId)) {
1277           memcpy (&pCtx->sSpsPpsCtx.sSubsetSpsBuffer[MAX_SPS_COUNT], pSubsetSps, sizeof (SSubsetSps));
1278           pCtx->sSpsPpsCtx.iOverwriteFlags |= OVERWRITE_SUBSETSPS;
1279         } else {
1280           memcpy (&pCtx->sSpsPpsCtx.sSubsetSpsBuffer[iSpsId], pSubsetSps, sizeof (SSubsetSps));
1281         }
1282       }
1283     } else {
1284       if (memcmp (&pCtx->sSpsPpsCtx.sSpsBuffer[iSpsId], pSps, sizeof (SSps)) != 0) {
1285         if (pCtx->pAccessUnitList->uiAvailUnitsNum > 0) {
1286           memcpy (&pCtx->sSpsPpsCtx.sSpsBuffer[MAX_SPS_COUNT], pSps, sizeof (SSps));
1287           pCtx->sSpsPpsCtx.iOverwriteFlags |= OVERWRITE_SPS;
1288           pCtx->bAuReadyFlag = true;
1289           pCtx->pAccessUnitList->uiEndPos = pCtx->pAccessUnitList->uiAvailUnitsNum - 1;
1290         } else if ((pCtx->pSps != NULL) && (pCtx->pSps->iSpsId == pSps->iSpsId)) {
1291           memcpy (&pCtx->sSpsPpsCtx.sSpsBuffer[MAX_SPS_COUNT], pSps, sizeof (SSps));
1292           pCtx->sSpsPpsCtx.iOverwriteFlags |= OVERWRITE_SPS;
1293         } else {
1294           memcpy (&pCtx->sSpsPpsCtx.sSpsBuffer[iSpsId], pSps, sizeof (SSps));
1295         }
1296       }
1297     }
1298   }
1299   // Not overwrite active sps, just copy to final place
1300   else if (kbUseSubsetFlag) {
1301     memcpy (&pCtx->sSpsPpsCtx.sSubsetSpsBuffer[iSpsId], pSubsetSps, sizeof (SSubsetSps));
1302     pCtx->sSpsPpsCtx.bSubspsAvailFlags[iSpsId] = true;
1303     pCtx->sSpsPpsCtx.bSubspsExistAheadFlag = true;
1304   } else {
1305     memcpy (&pCtx->sSpsPpsCtx.sSpsBuffer[iSpsId], pSps, sizeof (SSps));
1306     pCtx->sSpsPpsCtx.bSpsAvailFlags[iSpsId] = true;
1307     pCtx->sSpsPpsCtx.bSpsExistAheadFlag = true;
1308   }
1309   return ERR_NONE;
1310 }
1311 
1312 /*!
1313  *************************************************************************************
1314  * \brief   to parse Picture Parameter Set (PPS)
1315  *
1316  * \param   pCtx        Decoder context
1317  * \param   pPpsList    pps list
1318  * \param   pBsAux      bitstream reader auxiliary
1319  *
1320  * \return  0 - successed
1321  *          1 - failed
1322  *
1323  * \note    Call it in case eNalUnitType is PPS.
1324  *************************************************************************************
1325  */
ParsePps(PWelsDecoderContext pCtx,PPps pPpsList,PBitStringAux pBsAux,uint8_t * pSrcNal,const int32_t kSrcNalLen)1326 int32_t ParsePps (PWelsDecoderContext pCtx, PPps pPpsList, PBitStringAux pBsAux, uint8_t* pSrcNal,
1327                   const int32_t kSrcNalLen) {
1328 
1329   PPps pPps = NULL;
1330   SPps sTempPps;
1331   uint32_t uiPpsId = 0;
1332   uint32_t iTmp;
1333   uint32_t uiCode;
1334   int32_t iCode;
1335 
1336   WELS_READ_VERIFY (BsGetUe (pBsAux, &uiCode)); //pic_parameter_set_id
1337   uiPpsId = uiCode;
1338   if (uiPpsId >= MAX_PPS_COUNT) {
1339     return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_PPS_ID_OVERFLOW);
1340   }
1341   pPps = &sTempPps;
1342   memset (pPps, 0, sizeof (SPps));
1343 
1344   pPps->iPpsId = uiPpsId;
1345   WELS_READ_VERIFY (BsGetUe (pBsAux, &uiCode)); //seq_parameter_set_id
1346   pPps->iSpsId = uiCode;
1347 
1348   if (pPps->iSpsId >= MAX_SPS_COUNT) {
1349     return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_SPS_ID_OVERFLOW);
1350   }
1351 
1352   WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //entropy_coding_mode_flag
1353   pPps->bEntropyCodingModeFlag = !!uiCode;
1354   WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //bottom_field_pic_order_in_frame_present_flag
1355   pPps->bPicOrderPresentFlag   = !!uiCode;
1356 
1357   WELS_READ_VERIFY (BsGetUe (pBsAux, &uiCode)); //num_slice_groups_minus1
1358   pPps->uiNumSliceGroups = NUM_SLICE_GROUPS_OFFSET + uiCode;
1359 
1360   if (pPps->uiNumSliceGroups > MAX_SLICEGROUP_IDS) {
1361     return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_INVALID_SLICEGROUP);
1362   }
1363 
1364   if (pPps->uiNumSliceGroups > 1) {
1365     WELS_READ_VERIFY (BsGetUe (pBsAux, &uiCode)); //slice_group_map_type
1366     pPps->uiSliceGroupMapType = uiCode;
1367     if (pPps->uiSliceGroupMapType > 1) {
1368       WelsLog (& (pCtx->sLogCtx), WELS_LOG_WARNING, "ParsePps(): slice_group_map_type (%d): support only 0,1.",
1369                pPps->uiSliceGroupMapType);
1370       return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_UNSUPPORTED_FMOTYPE);
1371     }
1372 
1373     switch (pPps->uiSliceGroupMapType) {
1374     case 0:
1375       for (iTmp = 0; iTmp < pPps->uiNumSliceGroups; iTmp++) {
1376         WELS_READ_VERIFY (BsGetUe (pBsAux, &uiCode)); //run_length_minus1[ iGroup ]
1377         pPps->uiRunLength[iTmp] = RUN_LENGTH_OFFSET + uiCode;
1378       }
1379       break;
1380     default:
1381       break;
1382     }
1383   }
1384 
1385   WELS_READ_VERIFY (BsGetUe (pBsAux, &uiCode)); //num_ref_idx_l0_default_active_minus1
1386   pPps->uiNumRefIdxL0Active = NUM_REF_IDX_L0_DEFAULT_ACTIVE_OFFSET + uiCode;
1387   WELS_READ_VERIFY (BsGetUe (pBsAux, &uiCode)); //num_ref_idx_l1_default_active_minus1
1388   pPps->uiNumRefIdxL1Active = NUM_REF_IDX_L1_DEFAULT_ACTIVE_OFFSET + uiCode;
1389 
1390   if (pPps->uiNumRefIdxL0Active > MAX_REF_PIC_COUNT ||
1391       pPps->uiNumRefIdxL1Active > MAX_REF_PIC_COUNT) {
1392     return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_REF_COUNT_OVERFLOW);
1393   }
1394 
1395   WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //weighted_pred_flag
1396   pPps->bWeightedPredFlag  = !!uiCode;
1397   WELS_READ_VERIFY (BsGetBits (pBsAux, 2, &uiCode)); //weighted_bipred_idc
1398   pPps->uiWeightedBipredIdc = uiCode;
1399   // weighted_bipred_idc > 0 NOT supported now, but no impact when we ignore it
1400 
1401   WELS_READ_VERIFY (BsGetSe (pBsAux, &iCode)); //pic_init_qp_minus26
1402   pPps->iPicInitQp = PIC_INIT_QP_OFFSET + iCode;
1403   WELS_CHECK_SE_BOTH_ERROR (pPps->iPicInitQp, PPS_PIC_INIT_QP_QS_MIN, PPS_PIC_INIT_QP_QS_MAX, "pic_init_qp_minus26 + 26",
1404                             GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_INVALID_PIC_INIT_QP));
1405   WELS_READ_VERIFY (BsGetSe (pBsAux, &iCode)); //pic_init_qs_minus26
1406   pPps->iPicInitQs = PIC_INIT_QS_OFFSET + iCode;
1407   WELS_CHECK_SE_BOTH_ERROR (pPps->iPicInitQs, PPS_PIC_INIT_QP_QS_MIN, PPS_PIC_INIT_QP_QS_MAX, "pic_init_qs_minus26 + 26",
1408                             GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_INVALID_PIC_INIT_QS));
1409   WELS_READ_VERIFY (BsGetSe (pBsAux, &iCode)); //chroma_qp_index_offset,cb
1410   pPps->iChromaQpIndexOffset[0]                  = iCode;
1411   WELS_CHECK_SE_BOTH_ERROR (pPps->iChromaQpIndexOffset[0], PPS_CHROMA_QP_INDEX_OFFSET_MIN, PPS_CHROMA_QP_INDEX_OFFSET_MAX,
1412                             "chroma_qp_index_offset", GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_INVALID_CHROMA_QP_INDEX_OFFSET));
1413   pPps->iChromaQpIndexOffset[1] = pPps->iChromaQpIndexOffset[0];//init cr qp offset
1414   WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //deblocking_filter_control_present_flag
1415   pPps->bDeblockingFilterControlPresentFlag   = !!uiCode;
1416   WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //constrained_intra_pred_flag
1417   pPps->bConstainedIntraPredFlag              = !!uiCode;
1418   WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //redundant_pic_cnt_present_flag
1419   pPps->bRedundantPicCntPresentFlag           = !!uiCode;
1420 
1421   if (CheckMoreRBSPData (pBsAux)) {
1422     WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //transform_8x8_mode_flag
1423     pPps->bTransform8x8ModeFlag = !!uiCode;
1424     WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //pic_scaling_matrix_present_flag
1425     pPps->bPicScalingMatrixPresentFlag = !!uiCode;
1426     if (pPps->bPicScalingMatrixPresentFlag) {
1427       if (pCtx->sSpsPpsCtx.bSpsAvailFlags[pPps->iSpsId]) {
1428         WELS_READ_VERIFY (ParseScalingList (&pCtx->sSpsPpsCtx.sSpsBuffer[pPps->iSpsId], pBsAux, 1, pPps->bTransform8x8ModeFlag,
1429                                             pPps->bPicScalingListPresentFlag, pPps->iScalingList4x4, pPps->iScalingList8x8));
1430       } else {
1431         WelsLog (& (pCtx->sLogCtx), WELS_LOG_WARNING,
1432                  "ParsePps(): sps_id (%d) does not exist for scaling_list. This PPS (%d) is marked as invalid.", pPps->iSpsId,
1433                  pPps->iPpsId);
1434         return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_INVALID_SPS_ID);
1435       }
1436     }
1437     WELS_READ_VERIFY (BsGetSe (pBsAux, &iCode)); //second_chroma_qp_index_offset
1438     pPps->iChromaQpIndexOffset[1] = iCode;
1439     WELS_CHECK_SE_BOTH_ERROR (pPps->iChromaQpIndexOffset[1], PPS_CHROMA_QP_INDEX_OFFSET_MIN,
1440                               PPS_CHROMA_QP_INDEX_OFFSET_MAX, "chroma_qp_index_offset", GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS,
1441                                   ERR_INFO_INVALID_CHROMA_QP_INDEX_OFFSET));
1442   }
1443 
1444   if (pCtx->pPps != NULL && pCtx->pPps->iPpsId == pPps->iPpsId) {
1445     if (memcmp (pCtx->pPps, pPps, sizeof (*pPps)) != 0) {
1446       memcpy (&pCtx->sSpsPpsCtx.sPpsBuffer[MAX_PPS_COUNT], pPps, sizeof (SPps));
1447       pCtx->sSpsPpsCtx.iOverwriteFlags |= OVERWRITE_PPS;
1448       if (pCtx->pAccessUnitList->uiAvailUnitsNum > 0) {
1449         pCtx->bAuReadyFlag = true;
1450         pCtx->pAccessUnitList->uiEndPos = pCtx->pAccessUnitList->uiAvailUnitsNum - 1;
1451       }
1452     }
1453   } else {
1454     memcpy (&pCtx->sSpsPpsCtx.sPpsBuffer[uiPpsId], pPps, sizeof (SPps));
1455     pCtx->sSpsPpsCtx.bPpsAvailFlags[uiPpsId] = true;
1456   }
1457   if (pCtx->pParam->bParseOnly) {
1458     if (kSrcNalLen >= SPS_PPS_BS_SIZE - 4) { //pps bs exceeds
1459       WelsLog (& (pCtx->sLogCtx), WELS_LOG_WARNING, "pps payload size (%d) too large for parse only (%d), not supported!",
1460                kSrcNalLen, SPS_PPS_BS_SIZE - 4);
1461       pCtx->iErrorCode |= dsBitstreamError;
1462       return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_OUT_OF_MEMORY);
1463     }
1464     SPpsBsInfo* pPpsBs = &pCtx->sPpsBsInfo [uiPpsId];
1465     pPpsBs->iPpsId = (int32_t) uiPpsId;
1466     int32_t iTrailingZeroByte = 0;
1467     while (pSrcNal[kSrcNalLen - iTrailingZeroByte - 1] == 0x0) //remove final trailing 0 bytes
1468       iTrailingZeroByte++;
1469     int32_t iActualLen = kSrcNalLen - iTrailingZeroByte;
1470     pPpsBs->uiPpsBsLen = (uint16_t) iActualLen;
1471     //unify start code as 0x0001
1472     int32_t iStartDeltaByte = 0; //0 for 0x0001, 1 for 0x001
1473     if (pSrcNal[0] == 0x0 && pSrcNal[1] == 0x0 && pSrcNal[2] == 0x1) { //if 0x001
1474       pPpsBs->pPpsBsBuf[0] = 0x0; //add 0 to form 0x0001
1475       iStartDeltaByte++;
1476       pPpsBs->uiPpsBsLen++;
1477     }
1478     memcpy (pPpsBs->pPpsBsBuf + iStartDeltaByte, pSrcNal, iActualLen);
1479   }
1480   return ERR_NONE;
1481 }
1482 
1483 #define VUI_MAX_CHROMA_LOG_TYPE_TOP_BOTTOM_FIELD_MAX 5
1484 #define VUI_NUM_UNITS_IN_TICK_MIN 1
1485 #define VUI_TIME_SCALE_MIN 1
1486 #define VUI_MAX_BYTES_PER_PIC_DENOM_MAX 16
1487 #define VUI_MAX_BITS_PER_MB_DENOM_MAX 16
1488 #define VUI_LOG2_MAX_MV_LENGTH_HOR_MAX 16
1489 #define VUI_LOG2_MAX_MV_LENGTH_VER_MAX 16
1490 #define VUI_MAX_DEC_FRAME_BUFFERING_MAX 16
ParseVui(PWelsDecoderContext pCtx,PSps pSps,PBitStringAux pBsAux)1491 int32_t ParseVui (PWelsDecoderContext pCtx, PSps pSps, PBitStringAux pBsAux) {
1492   uint32_t uiCode;
1493   PVui pVui = &pSps->sVui;
1494   WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //aspect_ratio_info_present_flag
1495   pVui->bAspectRatioInfoPresentFlag = !!uiCode;
1496   if (pSps->sVui.bAspectRatioInfoPresentFlag) {
1497     WELS_READ_VERIFY (BsGetBits (pBsAux, 8, &uiCode)); //aspect_ratio_idc
1498     pVui->uiAspectRatioIdc = uiCode;
1499     if (pVui->uiAspectRatioIdc < 17) {
1500       pVui->uiSarWidth  = g_ksVuiSampleAspectRatio[pVui->uiAspectRatioIdc].uiWidth;
1501       pVui->uiSarHeight = g_ksVuiSampleAspectRatio[pVui->uiAspectRatioIdc].uiHeight;
1502     } else if (pVui->uiAspectRatioIdc == EXTENDED_SAR) {
1503       WELS_READ_VERIFY (BsGetBits (pBsAux, 16, &uiCode)); //sar_width
1504       pVui->uiSarWidth = uiCode;
1505       WELS_READ_VERIFY (BsGetBits (pBsAux, 16, &uiCode)); //sar_height
1506       pVui->uiSarHeight = uiCode;
1507     }
1508   }
1509   WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //overscan_info_present_flag
1510   pVui->bOverscanInfoPresentFlag = !!uiCode;
1511   if (pVui->bOverscanInfoPresentFlag) {
1512     WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //overscan_appropriate_flag
1513     pVui->bOverscanAppropriateFlag = !!uiCode;
1514   }
1515   WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //video_signal_type_present_flag
1516   pVui->bVideoSignalTypePresentFlag = !!uiCode;
1517   if (pVui->bVideoSignalTypePresentFlag) {
1518     WELS_READ_VERIFY (BsGetBits (pBsAux, 3, &uiCode)); //video_format
1519     pVui->uiVideoFormat = uiCode;
1520     WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //video_full_range_flag
1521     pVui->bVideoFullRangeFlag = !!uiCode;
1522     WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //colour_description_present_flag
1523     pVui->bColourDescripPresentFlag = !!uiCode;
1524     if (pVui->bColourDescripPresentFlag) {
1525       WELS_READ_VERIFY (BsGetBits (pBsAux, 8, &uiCode)); //colour_primaries
1526       pVui->uiColourPrimaries = uiCode;
1527       WELS_READ_VERIFY (BsGetBits (pBsAux, 8, &uiCode)); //transfer_characteristics
1528       pVui->uiTransferCharacteristics = uiCode;
1529       WELS_READ_VERIFY (BsGetBits (pBsAux, 8, &uiCode)); //matrix_coefficients
1530       pVui->uiMatrixCoeffs = uiCode;
1531     }
1532   }
1533   WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //chroma_loc_info_present_flag
1534   pVui->bChromaLocInfoPresentFlag = !!uiCode;
1535   if (pVui->bChromaLocInfoPresentFlag) {
1536     WELS_READ_VERIFY (BsGetUe (pBsAux, &uiCode)); //chroma_sample_loc_type_top_field
1537     pVui->uiChromaSampleLocTypeTopField = uiCode;
1538     WELS_CHECK_SE_UPPER_WARNING (pVui->uiChromaSampleLocTypeTopField, VUI_MAX_CHROMA_LOG_TYPE_TOP_BOTTOM_FIELD_MAX,
1539                                  "chroma_sample_loc_type_top_field");
1540     WELS_READ_VERIFY (BsGetUe (pBsAux, &uiCode)); //chroma_sample_loc_type_bottom_field
1541     pVui->uiChromaSampleLocTypeBottomField = uiCode;
1542     WELS_CHECK_SE_UPPER_WARNING (pVui->uiChromaSampleLocTypeBottomField, VUI_MAX_CHROMA_LOG_TYPE_TOP_BOTTOM_FIELD_MAX,
1543                                  "chroma_sample_loc_type_bottom_field");
1544   }
1545   WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //timing_info_present_flag
1546   pVui->bTimingInfoPresentFlag = !!uiCode;
1547   if (pVui->bTimingInfoPresentFlag) {
1548     uint32_t uiTmp = 0;
1549     WELS_READ_VERIFY (BsGetBits (pBsAux, 16, &uiCode)); //num_units_in_tick
1550     uiTmp = (uiCode << 16);
1551     WELS_READ_VERIFY (BsGetBits (pBsAux, 16, &uiCode)); //num_units_in_tick
1552     uiTmp |= uiCode;
1553     pVui->uiNumUnitsInTick = uiTmp;
1554     WELS_CHECK_SE_LOWER_WARNING (pVui->uiNumUnitsInTick, VUI_NUM_UNITS_IN_TICK_MIN, "num_units_in_tick");
1555     WELS_READ_VERIFY (BsGetBits (pBsAux, 16, &uiCode)); //time_scale
1556     uiTmp = (uiCode << 16);
1557     WELS_READ_VERIFY (BsGetBits (pBsAux, 16, &uiCode)); //time_scale
1558     uiTmp |= uiCode;
1559     pVui->uiTimeScale = uiTmp;
1560     WELS_CHECK_SE_LOWER_WARNING (pVui->uiNumUnitsInTick, VUI_TIME_SCALE_MIN, "time_scale");
1561     WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //fixed_frame_rate_flag
1562     pVui->bFixedFrameRateFlag = !!uiCode;
1563   }
1564   WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //nal_hrd_parameters_present_flag
1565   pVui->bNalHrdParamPresentFlag = !!uiCode;
1566   if (pVui->bNalHrdParamPresentFlag) { //Add HRD parse. the values are not being used though.
1567 #ifdef _PARSE_NALHRD_VCLHRD_PARAMS_
1568     int32_t cpb_cnt_minus1 = BsGetUe (pBsAux, &uiCode);
1569     /*bit_rate_scale = */BsGetBits (pBsAux, 4, &uiCode);
1570     /*cpb_size_scale = */BsGetBits (pBsAux, 4, &uiCode);
1571     for (int32_t i = 0; i <= cpb_cnt_minus1; i++) {
1572       /*bit_rate_value_minus1[i] = */BsGetUe (pBsAux, &uiCode);
1573       /*cpb_size_value_minus1[i] = */BsGetUe (pBsAux, &uiCode);
1574       /*cbr_flag[i] = */BsGetOneBit (pBsAux, &uiCode);
1575     }
1576     /*initial_cpb_removal_delay_length_minus1 = */BsGetBits (pBsAux, 5, &uiCode);
1577     /*cpb_removal_delay_length_minus1 = */BsGetBits (pBsAux, 5, &uiCode);
1578     /*dpb_output_delay_length_minus1 = */BsGetBits (pBsAux, 5, &uiCode);
1579     /*time_offset_length = */BsGetBits (pBsAux, 5, &uiCode);
1580 #else
1581     WelsLog (& (pCtx->sLogCtx), WELS_LOG_WARNING, "nal_hrd_parameters_present_flag = 1 not supported.");
1582     return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_UNSUPPORTED_VUI_HRD);
1583 #endif
1584   }
1585   WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //vcl_hrd_parameters_present_flag
1586   pVui->bVclHrdParamPresentFlag = !!uiCode;
1587   if (pVui->bVclHrdParamPresentFlag) {//Add HRD parse. the values are not being used though.
1588 #ifdef _PARSE_NALHRD_VCLHRD_PARAMS_
1589     int32_t cpb_cnt_minus1 = BsGetUe (pBsAux, &uiCode);
1590     /*bit_rate_scale = */BsGetBits (pBsAux, 4, &uiCode);
1591     /*cpb_size_scale = */BsGetBits (pBsAux, 4, &uiCode);
1592     for (int32_t i = 0; i <= cpb_cnt_minus1; i++) {
1593       /*bit_rate_value_minus1[i] = */BsGetUe (pBsAux, &uiCode);
1594       /*cpb_size_value_minus1[i] = */BsGetUe (pBsAux, &uiCode);
1595       /*cbr_flag[i] = */BsGetOneBit (pBsAux, &uiCode);
1596     }
1597     /*initial_cpb_removal_delay_length_minus1 = */BsGetBits (pBsAux, 5, &uiCode);
1598     /*cpb_removal_delay_length_minus1 = */BsGetBits (pBsAux, 5, &uiCode);
1599     /*dpb_output_delay_length_minus1 = */BsGetBits (pBsAux, 5, &uiCode);
1600     /*time_offset_length = */BsGetBits (pBsAux, 5, &uiCode);
1601 #else
1602     WelsLog (& (pCtx->sLogCtx), WELS_LOG_WARNING, "vcl_hrd_parameters_present_flag = 1 not supported.");
1603     return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_UNSUPPORTED_VUI_HRD);
1604 #endif
1605   }
1606 #ifdef _PARSE_NALHRD_VCLHRD_PARAMS_
1607   if (pVui->bNalHrdParamPresentFlag | pVui->bVclHrdParamPresentFlag) {
1608     /*low_delay_hrd_flag = */BsGetOneBit (pBsAux, &uiCode);
1609   }
1610 #endif
1611   WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //pic_struct_present_flag
1612   pVui->bPicStructPresentFlag = !!uiCode;
1613   WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //bitstream_restriction_flag
1614   pVui->bBitstreamRestrictionFlag = !!uiCode;
1615   if (pVui->bBitstreamRestrictionFlag) {
1616     WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //motion_vectors_over_pic_boundaries_flag
1617     pVui->bMotionVectorsOverPicBoundariesFlag = !!uiCode;
1618     WELS_READ_VERIFY (BsGetUe (pBsAux, &uiCode)); //max_bytes_per_pic_denom
1619     pVui->uiMaxBytesPerPicDenom = uiCode;
1620     WELS_CHECK_SE_UPPER_WARNING (pVui->uiMaxBytesPerPicDenom, VUI_MAX_BYTES_PER_PIC_DENOM_MAX,
1621                                  "max_bytes_per_pic_denom");
1622     WELS_READ_VERIFY (BsGetUe (pBsAux, &uiCode)); //max_bits_per_mb_denom
1623     pVui->uiMaxBitsPerMbDenom = uiCode;
1624     WELS_CHECK_SE_UPPER_WARNING (pVui->uiMaxBitsPerMbDenom, VUI_MAX_BITS_PER_MB_DENOM_MAX,
1625                                  "max_bits_per_mb_denom");
1626     WELS_READ_VERIFY (BsGetUe (pBsAux, &uiCode)); //log2_max_mv_length_horizontal
1627     pVui->uiLog2MaxMvLengthHorizontal = uiCode;
1628     WELS_CHECK_SE_UPPER_WARNING (pVui->uiLog2MaxMvLengthHorizontal, VUI_LOG2_MAX_MV_LENGTH_HOR_MAX,
1629                                  "log2_max_mv_length_horizontal");
1630     WELS_READ_VERIFY (BsGetUe (pBsAux, &uiCode)); //log2_max_mv_length_vertical
1631     pVui->uiLog2MaxMvLengthVertical = uiCode;
1632     WELS_CHECK_SE_UPPER_WARNING (pVui->uiLog2MaxMvLengthVertical, VUI_LOG2_MAX_MV_LENGTH_VER_MAX,
1633                                  "log2_max_mv_length_vertical");
1634     WELS_READ_VERIFY (BsGetUe (pBsAux, &uiCode)); //max_num_reorder_frames
1635     pVui->uiMaxNumReorderFrames = uiCode;
1636     WELS_CHECK_SE_UPPER_WARNING (pVui->uiMaxNumReorderFrames, VUI_MAX_DEC_FRAME_BUFFERING_MAX,
1637                                  "max_num_reorder_frames");
1638     WELS_READ_VERIFY (BsGetUe (pBsAux, &uiCode)); //max_dec_frame_buffering
1639     pVui->uiMaxDecFrameBuffering = uiCode;
1640     WELS_CHECK_SE_UPPER_WARNING (pVui->uiMaxDecFrameBuffering, VUI_MAX_DEC_FRAME_BUFFERING_MAX,
1641                                  "max_num_reorder_frames");
1642   }
1643   return ERR_NONE;
1644 }
1645 /*!
1646  *************************************************************************************
1647  * \brief   to parse SEI message payload
1648  *
1649  * \param   pSei        sei message to be parsed output
1650  * \param   pBsAux      bitstream reader auxiliary
1651  *
1652  * \return  0 - successed
1653  *          1 - failed
1654  *
1655  * \note    Call it in case eNalUnitType is NAL_UNIT_SEI.
1656  *************************************************************************************
1657  */
ParseSei(void * pSei,PBitStringAux pBsAux)1658 int32_t ParseSei (void* pSei, PBitStringAux pBsAux) { // reserved Sei_Msg type
1659 
1660 
1661   return ERR_NONE;
1662 }
1663 /*
1664  *************************************************************************************
1665  * \brief   to parse scalinglist message payload
1666  *
1667  * \param   pps sps scaling list matrix      message to be parsed output
1668  * \param   pBsAux      bitstream reader auxiliary
1669  *
1670  * \return  0 - successed
1671  *          1 - failed
1672  *
1673  * \note    Call it in case scaling list matrix present at sps or pps level
1674  *************************************************************************************
1675  */
SetScalingListValue(uint8_t * pScalingList,int iScalingListNum,bool * bUseDefaultScalingMatrixFlag,PBitStringAux pBsAux)1676 int32_t SetScalingListValue (uint8_t* pScalingList, int iScalingListNum, bool* bUseDefaultScalingMatrixFlag,
1677                              PBitStringAux pBsAux) { // reserved Sei_Msg type
1678   int iLastScale = 8;
1679   int iNextScale = 8;
1680   int iDeltaScale;
1681   int32_t iCode;
1682   int32_t iIdx;
1683   for (int j = 0; j < iScalingListNum; j++) {
1684     if (iNextScale != 0) {
1685       WELS_READ_VERIFY (BsGetSe (pBsAux, &iCode));
1686       WELS_CHECK_SE_BOTH_ERROR_NOLOG (iCode, SCALING_LIST_DELTA_SCALE_MIN, SCALING_LIST_DELTA_SCALE_MAX, "DeltaScale",
1687                                       ERR_SCALING_LIST_DELTA_SCALE);
1688       iDeltaScale = iCode;
1689       iNextScale = (iLastScale + iDeltaScale + 256) % 256;
1690       *bUseDefaultScalingMatrixFlag = (j == 0 && iNextScale == 0);
1691       if (*bUseDefaultScalingMatrixFlag)
1692         break;
1693     }
1694     iIdx = iScalingListNum == 16 ? g_kuiZigzagScan[j] : g_kuiZigzagScan8x8[j];
1695     pScalingList[iIdx] = (iNextScale == 0) ? iLastScale : iNextScale;
1696     iLastScale = pScalingList[iIdx];
1697   }
1698 
1699 
1700   return ERR_NONE;
1701 }
1702 
ParseScalingList(PSps pSps,PBitStringAux pBs,bool bPPS,const bool kbTrans8x8ModeFlag,bool * pScalingListPresentFlag,uint8_t (* iScalingList4x4)[16],uint8_t (* iScalingList8x8)[64])1703 int32_t ParseScalingList (PSps pSps, PBitStringAux pBs, bool bPPS, const bool kbTrans8x8ModeFlag,
1704                           bool* pScalingListPresentFlag, uint8_t (*iScalingList4x4)[16], uint8_t (*iScalingList8x8)[64]) {
1705   uint32_t uiScalingListNum;
1706   uint32_t uiCode;
1707 
1708   bool bUseDefaultScalingMatrixFlag4x4 = false;
1709   bool bUseDefaultScalingMatrixFlag8x8 = false;
1710   bool bInit = false;
1711   const uint8_t* defaultScaling[4];
1712 
1713   if (!bPPS) { //sps scaling_list
1714     uiScalingListNum = (pSps->uiChromaFormatIdc != 3) ? 8 : 12;
1715   } else { //pps scaling_list
1716     uiScalingListNum = 6 + (int32_t) kbTrans8x8ModeFlag * ((pSps->uiChromaFormatIdc != 3) ? 2 : 6);
1717     bInit = pSps->bSeqScalingMatrixPresentFlag;
1718   }
1719 
1720 //Init default_scaling_list value for sps or pps
1721   defaultScaling[0] = bInit ? pSps->iScalingList4x4[0] : g_kuiDequantScaling4x4Default[0];
1722   defaultScaling[1] = bInit ? pSps->iScalingList4x4[3] : g_kuiDequantScaling4x4Default[1];
1723   defaultScaling[2] = bInit ? pSps->iScalingList8x8[0] : g_kuiDequantScaling8x8Default[0];
1724   defaultScaling[3] = bInit ? pSps->iScalingList8x8[1] : g_kuiDequantScaling8x8Default[1];
1725 
1726   for (unsigned int i = 0; i < uiScalingListNum; i++) {
1727     WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode));
1728     pScalingListPresentFlag[i] = !!uiCode;
1729     if (!!uiCode) {
1730       if (i < 6) {//4x4 scaling list
1731         WELS_READ_VERIFY (SetScalingListValue (iScalingList4x4[i], 16, &bUseDefaultScalingMatrixFlag4x4, pBs));
1732         if (bUseDefaultScalingMatrixFlag4x4) {
1733           bUseDefaultScalingMatrixFlag4x4 = false;
1734           memcpy (iScalingList4x4[i], g_kuiDequantScaling4x4Default[i / 3], sizeof (uint8_t) * 16);
1735         }
1736 
1737 
1738       } else {
1739         WELS_READ_VERIFY (SetScalingListValue (iScalingList8x8[i - 6], 64, &bUseDefaultScalingMatrixFlag8x8, pBs));
1740 
1741         if (bUseDefaultScalingMatrixFlag8x8) {
1742           bUseDefaultScalingMatrixFlag8x8 = false;
1743           memcpy (iScalingList8x8[i - 6], g_kuiDequantScaling8x8Default[ (i - 6) & 1], sizeof (uint8_t) * 64);
1744         }
1745       }
1746 
1747     } else {
1748       if (i < 6) {
1749         if ((i != 0) && (i != 3))
1750           memcpy (iScalingList4x4[i], iScalingList4x4[i - 1], sizeof (uint8_t) * 16);
1751         else
1752           memcpy (iScalingList4x4[i], defaultScaling[i / 3], sizeof (uint8_t) * 16);
1753 
1754       } else {
1755         if ((i == 6) || (i == 7))
1756           memcpy (iScalingList8x8[i - 6], defaultScaling[ (i & 1) + 2], sizeof (uint8_t) * 64);
1757         else
1758           memcpy (iScalingList8x8[i - 6], iScalingList8x8[i - 8], sizeof (uint8_t) * 64);
1759 
1760       }
1761     }
1762   }
1763   return ERR_NONE;
1764 
1765 }
1766 
1767 /*!
1768  *************************************************************************************
1769  * \brief   reset fmo list due to got Sps now
1770  *
1771  * \param   pCtx    decoder context
1772  *
1773  * \return  count number of fmo context units are reset
1774  *************************************************************************************
1775  */
ResetFmoList(PWelsDecoderContext pCtx)1776 int32_t ResetFmoList (PWelsDecoderContext pCtx) {
1777   int32_t iCountNum = 0;
1778   if (NULL != pCtx) {
1779     // Fixed memory leak due to PPS_ID might not be continuous sometimes, 1/5/2010
1780     UninitFmoList (&pCtx->sFmoList[0], MAX_PPS_COUNT, pCtx->iActiveFmoNum, pCtx->pMemAlign);
1781     iCountNum = pCtx->iActiveFmoNum;
1782     pCtx->iActiveFmoNum = 0;
1783   }
1784   return iCountNum;
1785 }
1786 
1787 } // namespace WelsDec
1788