ZSTD_encodeSequences_body(
            void* dst, size_t dstCapacity,
            FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable,
            FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable,
            FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable,
            seqDef const* sequences, size_t nbSeq, int longOffsets)
{
    BIT_CStream_t blockStream;
    FSE_CState_t  stateMatchLength;
    FSE_CState_t  stateOffsetBits;
    FSE_CState_t  stateLitLength;

    CHECK_E(BIT_initCStream(&blockStream, dst, dstCapacity), dstSize_tooSmall); /* not enough space remaining */

    /* first symbols */
    FSE_initCState2(&stateMatchLength, CTable_MatchLength, mlCodeTable[nbSeq-1]);
    FSE_initCState2(&stateOffsetBits,  CTable_OffsetBits,  ofCodeTable[nbSeq-1]);
    FSE_initCState2(&stateLitLength,   CTable_LitLength,   llCodeTable[nbSeq-1]);
    BIT_addBits(&blockStream, sequences[nbSeq-1].litLength, LL_bits[llCodeTable[nbSeq-1]]);
    if (MEM_32bits()) BIT_flushBits(&blockStream);
    BIT_addBits(&blockStream, sequences[nbSeq-1].matchLength, ML_bits[mlCodeTable[nbSeq-1]]);
    if (MEM_32bits()) BIT_flushBits(&blockStream);
    if (longOffsets) {
        U32 const ofBits = ofCodeTable[nbSeq-1];
        int const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1);
        if (extraBits) {
            BIT_addBits(&blockStream, sequences[nbSeq-1].offset, extraBits);
            BIT_flushBits(&blockStream);
        }
        BIT_addBits(&blockStream, sequences[nbSeq-1].offset >> extraBits,
                    ofBits - extraBits);
    } else {
        BIT_addBits(&blockStream, sequences[nbSeq-1].offset, ofCodeTable[nbSeq-1]);
    }
    BIT_flushBits(&blockStream);

    {   size_t n;
        for (n=nbSeq-2 ; n<nbSeq ; n--) {      /* intentional underflow */
            BYTE const llCode = llCodeTable[n];
            BYTE const ofCode = ofCodeTable[n];
            BYTE const mlCode = mlCodeTable[n];
            U32  const llBits = LL_bits[llCode];
            U32  const ofBits = ofCode;
            U32  const mlBits = ML_bits[mlCode];
            DEBUGLOG(6, "encoding: litlen:%2u - matchlen:%2u - offCode:%7u",
                        sequences[n].litLength,
                        sequences[n].matchLength + MINMATCH,
                        sequences[n].offset);
                                                                            /* 32b*/  /* 64b*/
                                                                            /* (7)*/  /* (7)*/
            FSE_encodeSymbol(&blockStream, &stateOffsetBits, ofCode);       /* 15 */  /* 15 */
            FSE_encodeSymbol(&blockStream, &stateMatchLength, mlCode);      /* 24 */  /* 24 */
            if (MEM_32bits()) BIT_flushBits(&blockStream);                  /* (7)*/
            FSE_encodeSymbol(&blockStream, &stateLitLength, llCode);        /* 16 */  /* 33 */
            if (MEM_32bits() || (ofBits+mlBits+llBits >= 64-7-(LLFSELog+MLFSELog+OffFSELog)))
                BIT_flushBits(&blockStream);                                /* (7)*/
            BIT_addBits(&blockStream, sequences[n].litLength, llBits);
            if (MEM_32bits() && ((llBits+mlBits)>24)) BIT_flushBits(&blockStream);
            BIT_addBits(&blockStream, sequences[n].matchLength, mlBits);
            if (MEM_32bits() || (ofBits+mlBits+llBits > 56)) BIT_flushBits(&blockStream);
            if (longOffsets) {
                int const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1);
                if (extraBits) {
                    BIT_addBits(&blockStream, sequences[n].offset, extraBits);
                    BIT_flushBits(&blockStream);                            /* (7)*/
                }
                BIT_addBits(&blockStream, sequences[n].offset >> extraBits,
                            ofBits - extraBits);                            /* 31 */
            } else {
                BIT_addBits(&blockStream, sequences[n].offset, ofBits);     /* 31 */
            }
            BIT_flushBits(&blockStream);                                    /* (7)*/
    }   }

    DEBUGLOG(6, "ZSTD_encodeSequences: flushing ML state with %u bits", stateMatchLength.stateLog);
    FSE_flushCState(&blockStream, &stateMatchLength);
    DEBUGLOG(6, "ZSTD_encodeSequences: flushing Off state with %u bits", stateOffsetBits.stateLog);
    FSE_flushCState(&blockStream, &stateOffsetBits);
    DEBUGLOG(6, "ZSTD_encodeSequences: flushing LL state with %u bits", stateLitLength.stateLog);
    FSE_flushCState(&blockStream, &stateLitLength);

    {   size_t const streamSize = BIT_closeCStream(&blockStream);
        if (streamSize==0) return ERROR(dstSize_tooSmall);   /* not enough space */
        return streamSize;
    }
}


static int fuzzerTests(U32 seed, U32 nbTests, unsigned startTest, U32 const maxDurationS, double compressibility, int bigTests)
{
    static const U32 maxSrcLog = 23;
    static const U32 maxSampleLog = 22;
    size_t const srcBufferSize = (size_t)1<<maxSrcLog;
    size_t const dstBufferSize = (size_t)1<<maxSampleLog;
    size_t const cBufferSize   = ZSTD_compressBound(dstBufferSize);
    BYTE* cNoiseBuffer[5];
    BYTE* const cBuffer = (BYTE*) malloc (cBufferSize);
    BYTE* const dstBuffer = (BYTE*) malloc (dstBufferSize);
    BYTE* const mirrorBuffer = (BYTE*) malloc (dstBufferSize);
    ZSTD_CCtx* const refCtx = ZSTD_createCCtx();
    ZSTD_CCtx* const ctx = ZSTD_createCCtx();
    ZSTD_DCtx* const dctx = ZSTD_createDCtx();
    U32 result = 0;
    U32 testNb = 0;
    U32 coreSeed = seed;
    UTIL_time_t const startClock = UTIL_getTime();
    U64 const maxClockSpan = maxDurationS * SEC_TO_MICRO;
    int const cLevelLimiter = bigTests ? 3 : 2;

    /* allocation */
    cNoiseBuffer[0] = (BYTE*)malloc (srcBufferSize);
    cNoiseBuffer[1] = (BYTE*)malloc (srcBufferSize);
    cNoiseBuffer[2] = (BYTE*)malloc (srcBufferSize);
    cNoiseBuffer[3] = (BYTE*)malloc (srcBufferSize);
    cNoiseBuffer[4] = (BYTE*)malloc (srcBufferSize);
    CHECK (!cNoiseBuffer[0] || !cNoiseBuffer[1] || !cNoiseBuffer[2] || !cNoiseBuffer[3] || !cNoiseBuffer[4]
           || !dstBuffer || !mirrorBuffer || !cBuffer || !refCtx || !ctx || !dctx,
           "Not enough memory, fuzzer tests cancelled");

    /* Create initial samples */
    RDG_genBuffer(cNoiseBuffer[0], srcBufferSize, 0.00, 0., coreSeed);    /* pure noise */
    RDG_genBuffer(cNoiseBuffer[1], srcBufferSize, 0.05, 0., coreSeed);    /* barely compressible */
    RDG_genBuffer(cNoiseBuffer[2], srcBufferSize, compressibility, 0., coreSeed);
    RDG_genBuffer(cNoiseBuffer[3], srcBufferSize, 0.95, 0., coreSeed);    /* highly compressible */
    RDG_genBuffer(cNoiseBuffer[4], srcBufferSize, 1.00, 0., coreSeed);    /* sparse content */

    /* catch up testNb */
    for (testNb=1; testNb < startTest; testNb++) FUZ_rand(&coreSeed);

    /* main test loop */
    for ( ; (testNb <= nbTests) || (UTIL_clockSpanMicro(startClock) < maxClockSpan); testNb++ ) {
        BYTE* srcBuffer;   /* jumping pointer */
        U32 lseed;
        size_t sampleSize, maxTestSize, totalTestSize;
        size_t cSize, totalCSize, totalGenSize;
        U64 crcOrig;
        BYTE* sampleBuffer;
        const BYTE* dict;
        size_t dictSize;

        /* notification */
        if (nbTests >= testNb) { DISPLAYUPDATE(2, "\r%6u/%6u    ", testNb, nbTests); }
        else { DISPLAYUPDATE(2, "\r%6u          ", testNb); }

        FUZ_rand(&coreSeed);
        { U32 const prime1 = 2654435761U; lseed = coreSeed ^ prime1; }

        /* srcBuffer selection [0-4] */
        {   U32 buffNb = FUZ_rand(&lseed) & 0x7F;
            if (buffNb & 7) buffNb=2;   /* most common : compressible (P) */
            else {
                buffNb >>= 3;
                if (buffNb & 7) {
                    const U32 tnb[2] = { 1, 3 };   /* barely/highly compressible */
                    buffNb = tnb[buffNb >> 3];
                } else {
                    const U32 tnb[2] = { 0, 4 };   /* not compressible / sparse */
                    buffNb = tnb[buffNb >> 3];
            }   }
            srcBuffer = cNoiseBuffer[buffNb];
        }

        /* select src segment */
        sampleSize = FUZ_randomLength(&lseed, maxSampleLog);

        /* create sample buffer (to catch read error with valgrind & sanitizers)  */
        sampleBuffer = (BYTE*)malloc(sampleSize);
        CHECK(sampleBuffer==NULL, "not enough memory for sample buffer");
        { size_t const sampleStart = FUZ_rand(&lseed) % (srcBufferSize - sampleSize);
          memcpy(sampleBuffer, srcBuffer + sampleStart, sampleSize); }
        crcOrig = XXH64(sampleBuffer, sampleSize, 0);

        /* compression tests */
        {   int const cLevelPositive =
                    ( FUZ_rand(&lseed) %
                     (ZSTD_maxCLevel() - (FUZ_highbit32((U32)sampleSize) / cLevelLimiter)) )
                    + 1;
            int const cLevel = ((FUZ_rand(&lseed) & 15) == 3) ?
                             - (int)((FUZ_rand(&lseed) & 7) + 1) :   /* test negative cLevel */
                             cLevelPositive;
            DISPLAYLEVEL(5, "fuzzer t%u: Simple compression test (level %i) \n", testNb, cLevel);
            cSize = ZSTD_compressCCtx(ctx, cBuffer, cBufferSize, sampleBuffer, sampleSize, cLevel);
            CHECK(ZSTD_isError(cSize), "ZSTD_compressCCtx failed : %s", ZSTD_getErrorName(cSize));

            /* compression failure test : too small dest buffer */
            if (cSize > 3) {
                const size_t missing = (FUZ_rand(&lseed) % (cSize-2)) + 1;   /* no problem, as cSize > 4 (frameHeaderSizer) */
                const size_t tooSmallSize = cSize - missing;
                const U32 endMark = 0x4DC2B1A9;
                memcpy(dstBuffer+tooSmallSize, &endMark, 4);
                { size_t const errorCode = ZSTD_compressCCtx(ctx, dstBuffer, tooSmallSize, sampleBuffer, sampleSize, cLevel);
                  CHECK(!ZSTD_isError(errorCode), "ZSTD_compressCCtx should have failed ! (buffer too small : %u < %u)", (U32)tooSmallSize, (U32)cSize); }
                { U32 endCheck; memcpy(&endCheck, dstBuffer+tooSmallSize, 4);
                  CHECK(endCheck != endMark, "ZSTD_compressCCtx : dst buffer overflow"); }
        }   }

        /* frame header decompression test */
        {   ZSTD_frameHeader zfh;
            CHECK_Z( ZSTD_getFrameHeader(&zfh, cBuffer, cSize) );
            CHECK(zfh.frameContentSize != sampleSize, "Frame content size incorrect");
        }

        /* Decompressed size test */
        {   unsigned long long const rSize = ZSTD_findDecompressedSize(cBuffer, cSize);
            CHECK(rSize != sampleSize, "decompressed size incorrect");
        }

        /* successful decompression test */
        DISPLAYLEVEL(5, "fuzzer t%u: simple decompression test \n", testNb);
        {   size_t const margin = (FUZ_rand(&lseed) & 1) ? 0 : (FUZ_rand(&lseed) & 31) + 1;
            size_t const dSize = ZSTD_decompress(dstBuffer, sampleSize + margin, cBuffer, cSize);
            CHECK(dSize != sampleSize, "ZSTD_decompress failed (%s) (srcSize : %u ; cSize : %u)", ZSTD_getErrorName(dSize), (U32)sampleSize, (U32)cSize);
            {   U64 const crcDest = XXH64(dstBuffer, sampleSize, 0);
                CHECK(crcOrig != crcDest, "decompression result corrupted (pos %u / %u)", (U32)findDiff(sampleBuffer, dstBuffer, sampleSize), (U32)sampleSize);
        }   }

        free(sampleBuffer);   /* no longer useful after this point */

        /* truncated src decompression test */
        DISPLAYLEVEL(5, "fuzzer t%u: decompression of truncated source \n", testNb);
        {   size_t const missing = (FUZ_rand(&lseed) % (cSize-2)) + 1;   /* no problem, as cSize > 4 (frameHeaderSizer) */
            size_t const tooSmallSize = cSize - missing;
            void* cBufferTooSmall = malloc(tooSmallSize);   /* valgrind will catch read overflows */
            CHECK(cBufferTooSmall == NULL, "not enough memory !");
            memcpy(cBufferTooSmall, cBuffer, tooSmallSize);
            { size_t const errorCode = ZSTD_decompress(dstBuffer, dstBufferSize, cBufferTooSmall, tooSmallSize);
              CHECK(!ZSTD_isError(errorCode), "ZSTD_decompress should have failed ! (truncated src buffer)"); }
            free(cBufferTooSmall);
        }

        /* too small dst decompression test */
        DISPLAYLEVEL(5, "fuzzer t%u: decompress into too small dst buffer \n", testNb);
        if (sampleSize > 3) {
            size_t const missing = (FUZ_rand(&lseed) % (sampleSize-2)) + 1;   /* no problem, as cSize > 4 (frameHeaderSizer) */
            size_t const tooSmallSize = sampleSize - missing;
            static const BYTE token = 0xA9;
            dstBuffer[tooSmallSize] = token;
            { size_t const errorCode = ZSTD_decompress(dstBuffer, tooSmallSize, cBuffer, cSize);
              CHECK(!ZSTD_isError(errorCode), "ZSTD_decompress should have failed : %u > %u (dst buffer too small)", (U32)errorCode, (U32)tooSmallSize); }
            CHECK(dstBuffer[tooSmallSize] != token, "ZSTD_decompress : dst buffer overflow");
        }

        /* noisy src decompression test */
        if (cSize > 6) {
            /* insert noise into src */
            {   U32 const maxNbBits = FUZ_highbit32((U32)(cSize-4));
                size_t pos = 4;   /* preserve magic number (too easy to detect) */
                for (;;) {
                    /* keep some original src */
                    {   U32 const nbBits = FUZ_rand(&lseed) % maxNbBits;
                        size_t const mask = (1<<nbBits) - 1;
                        size_t const skipLength = FUZ_rand(&lseed) & mask;
                        pos += skipLength;
                    }
                    if (pos >= cSize) break;
                    /* add noise */
                    {   U32 const nbBitsCodes = FUZ_rand(&lseed) % maxNbBits;
                        U32 const nbBits = nbBitsCodes ? nbBitsCodes-1 : 0;
                        size_t const mask = (1<<nbBits) - 1;
                        size_t const rNoiseLength = (FUZ_rand(&lseed) & mask) + 1;
                        size_t const noiseLength = MIN(rNoiseLength, cSize-pos);
                        size_t const noiseStart = FUZ_rand(&lseed) % (srcBufferSize - noiseLength);
                        memcpy(cBuffer + pos, srcBuffer + noiseStart, noiseLength);
                        pos += noiseLength;
            }   }   }

            /* decompress noisy source */
            DISPLAYLEVEL(5, "fuzzer t%u: decompress noisy source \n", testNb);
            {   U32 const endMark = 0xA9B1C3D6;
                memcpy(dstBuffer+sampleSize, &endMark, 4);
                {   size_t const decompressResult = ZSTD_decompress(dstBuffer, sampleSize, cBuffer, cSize);
                    /* result *may* be an unlikely success, but even then, it must strictly respect dst buffer boundaries */
                    CHECK((!ZSTD_isError(decompressResult)) && (decompressResult>sampleSize),
                          "ZSTD_decompress on noisy src : result is too large : %u > %u (dst buffer)", (U32)decompressResult, (U32)sampleSize);
                }
                {   U32 endCheck; memcpy(&endCheck, dstBuffer+sampleSize, 4);
                    CHECK(endMark!=endCheck, "ZSTD_decompress on noisy src : dst buffer overflow");
        }   }   }   /* noisy src decompression test */

        /*=====   Bufferless streaming compression test, scattered segments and dictionary   =====*/
        DISPLAYLEVEL(5, "fuzzer t%u: Bufferless streaming compression test \n", testNb);
        {   U32 const testLog = FUZ_rand(&lseed) % maxSrcLog;
            U32 const dictLog = FUZ_rand(&lseed) % maxSrcLog;
            int const cLevel = (FUZ_rand(&lseed) %
                                (ZSTD_maxCLevel() -
                                 (MAX(testLog, dictLog) / cLevelLimiter))) +
                               1;
            maxTestSize = FUZ_rLogLength(&lseed, testLog);
            if (maxTestSize >= dstBufferSize) maxTestSize = dstBufferSize-1;

            dictSize = FUZ_rLogLength(&lseed, dictLog);   /* needed also for decompression */
            dict = srcBuffer + (FUZ_rand(&lseed) % (srcBufferSize - dictSize));

            DISPLAYLEVEL(6, "fuzzer t%u: Compressing up to <=%u bytes at level %i with dictionary size %u \n",
                            testNb, (U32)maxTestSize, cLevel, (U32)dictSize);

            if (FUZ_rand(&lseed) & 0xF) {
                CHECK_Z ( ZSTD_compressBegin_usingDict(refCtx, dict, dictSize, cLevel) );
            } else {
                ZSTD_compressionParameters const cPar = ZSTD_getCParams(cLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize);
                ZSTD_frameParameters const fPar = { FUZ_rand(&lseed)&1 /* contentSizeFlag */,
                                                    !(FUZ_rand(&lseed)&3) /* contentChecksumFlag*/,
                                                    0 /*NodictID*/ };   /* note : since dictionary is fake, dictIDflag has no impact */
                ZSTD_parameters const p = FUZ_makeParams(cPar, fPar);
                CHECK_Z ( ZSTD_compressBegin_advanced(refCtx, dict, dictSize, p, 0) );
            }
            CHECK_Z( ZSTD_copyCCtx(ctx, refCtx, 0) );
        }

        {   U32 const nbChunks = (FUZ_rand(&lseed) & 127) + 2;
            U32 n;
            XXH64_state_t xxhState;
            XXH64_reset(&xxhState, 0);
            for (totalTestSize=0, cSize=0, n=0 ; n<nbChunks ; n++) {
                size_t const segmentSize = FUZ_randomLength(&lseed, maxSampleLog);
                size_t const segmentStart = FUZ_rand(&lseed) % (srcBufferSize - segmentSize);

                if (cBufferSize-cSize < ZSTD_compressBound(segmentSize)) break;   /* avoid invalid dstBufferTooSmall */
                if (totalTestSize+segmentSize > maxTestSize) break;

                {   size_t const compressResult = ZSTD_compressContinue(ctx, cBuffer+cSize, cBufferSize-cSize, srcBuffer+segmentStart, segmentSize);
                    CHECK (ZSTD_isError(compressResult), "multi-segments compression error : %s", ZSTD_getErrorName(compressResult));
                    cSize += compressResult;
                }
                XXH64_update(&xxhState, srcBuffer+segmentStart, segmentSize);
                memcpy(mirrorBuffer + totalTestSize, srcBuffer+segmentStart, segmentSize);
                totalTestSize += segmentSize;
            }

            {   size_t const flushResult = ZSTD_compressEnd(ctx, cBuffer+cSize, cBufferSize-cSize, NULL, 0);
                CHECK (ZSTD_isError(flushResult), "multi-segments epilogue error : %s", ZSTD_getErrorName(flushResult));
                cSize += flushResult;
            }
            crcOrig = XXH64_digest(&xxhState);
        }

        /* streaming decompression test */
        DISPLAYLEVEL(5, "fuzzer t%u: Bufferless streaming decompression test \n", testNb);
        /* ensure memory requirement is good enough (should always be true) */
        {   ZSTD_frameHeader zfh;
            CHECK( ZSTD_getFrameHeader(&zfh, cBuffer, ZSTD_frameHeaderSize_max),
                  "ZSTD_getFrameHeader(): error retrieving frame information");
            {   size_t const roundBuffSize = ZSTD_decodingBufferSize_min(zfh.windowSize, zfh.frameContentSize);
                CHECK_Z(roundBuffSize);
                CHECK((roundBuffSize > totalTestSize) && (zfh.frameContentSize!=ZSTD_CONTENTSIZE_UNKNOWN),
                      "ZSTD_decodingBufferSize_min() requires more memory (%u) than necessary (%u)",
                      (U32)roundBuffSize, (U32)totalTestSize );
        }   }
        if (dictSize<8) dictSize=0, dict=NULL;   /* disable dictionary */
        CHECK_Z( ZSTD_decompressBegin_usingDict(dctx, dict, dictSize) );
        totalCSize = 0;
        totalGenSize = 0;
        while (totalCSize < cSize) {
            size_t const inSize = ZSTD_nextSrcSizeToDecompress(dctx);
            size_t const genSize = ZSTD_decompressContinue(dctx, dstBuffer+totalGenSize, dstBufferSize-totalGenSize, cBuffer+totalCSize, inSize);
            CHECK (ZSTD_isError(genSize), "ZSTD_decompressContinue error : %s", ZSTD_getErrorName(genSize));
            totalGenSize += genSize;
            totalCSize += inSize;
        }
        CHECK (ZSTD_nextSrcSizeToDecompress(dctx) != 0, "frame not fully decoded");
        CHECK (totalGenSize != totalTestSize, "streaming decompressed data : wrong size")
        CHECK (totalCSize != cSize, "compressed data should be fully read")
        {   U64 const crcDest = XXH64(dstBuffer, totalTestSize, 0);
            CHECK(crcOrig != crcDest, "streaming decompressed data corrupted (pos %u / %u)",
                (U32)findDiff(mirrorBuffer, dstBuffer, totalTestSize), (U32)totalTestSize);
        }
    }   /* for ( ; (testNb <= nbTests) */
    DISPLAY("\r%u fuzzer tests completed   \n", testNb-1);

_cleanup:
    ZSTD_freeCCtx(refCtx);
    ZSTD_freeCCtx(ctx);
    ZSTD_freeDCtx(dctx);
    free(cNoiseBuffer[0]);
    free(cNoiseBuffer[1]);
    free(cNoiseBuffer[2]);
    free(cNoiseBuffer[3]);
    free(cNoiseBuffer[4]);
    free(cBuffer);
    free(dstBuffer);
    free(mirrorBuffer);
    return result;

_output_error:
    result = 1;
    goto _cleanup;
}


static void build_inter_predictors ( MACROBLOCKD * xd , int plane , int block , int bw , int bh , int x , int y , int w , int h , int mi_x , int mi_y ) {
 struct macroblockd_plane * const pd = & xd -> plane [ plane ] ;
 const MODE_INFO * mi = xd -> mi [ 0 ] . src_mi ;
 const int is_compound = has_second_ref ( & mi -> mbmi ) ;
 const InterpKernel * kernel = vp9_get_interp_kernel ( mi -> mbmi . interp_filter ) ;
 int ref ;
 for ( ref = 0 ;
 ref < 1 + is_compound ;
 ++ ref ) {
 const struct scale_factors * const sf = & xd -> block_refs [ ref ] -> sf ;
 struct buf_2d * const pre_buf = & pd -> pre [ ref ] ;
 struct buf_2d * const dst_buf = & pd -> dst ;
 uint8_t * const dst = dst_buf -> buf + dst_buf -> stride * y + x ;
 const MV mv = mi -> mbmi . sb_type < BLOCK_8X8 ? average_split_mvs ( pd , mi , ref , block ) : mi -> mbmi . mv [ ref ] . as_mv ;
 const MV mv_q4 = clamp_mv_to_umv_border_sb ( xd , & mv , bw , bh , pd -> subsampling_x , pd -> subsampling_y ) ;
 uint8_t * pre ;
 MV32 scaled_mv ;
 int xs , ys , subpel_x , subpel_y ;
 if ( vp9_is_scaled ( sf ) ) {
 pre = pre_buf -> buf + scaled_buffer_offset ( x , y , pre_buf -> stride , sf ) ;
 scaled_mv = vp9_scale_mv ( & mv_q4 , mi_x + x , mi_y + y , sf ) ;
 xs = sf -> x_step_q4 ;
 ys = sf -> y_step_q4 ;
 }
 else {
 pre = pre_buf -> buf + ( y * pre_buf -> stride + x ) ;
 scaled_mv . row = mv_q4 . row ;
 scaled_mv . col = mv_q4 . col ;
 xs = ys = 16 ;
 }
 subpel_x = scaled_mv . col & SUBPEL_MASK ;
 subpel_y = scaled_mv . row & SUBPEL_MASK ;
 pre += ( scaled_mv . row >> SUBPEL_BITS ) * pre_buf -> stride + ( scaled_mv . col >> SUBPEL_BITS ) ;
 # if CONFIG_VP9_HIGHBITDEPTH if ( xd -> cur_buf -> flags & YV12_FLAG_HIGHBITDEPTH ) {
 high_inter_predictor ( pre , pre_buf -> stride , dst , dst_buf -> stride , subpel_x , subpel_y , sf , w , h , ref , kernel , xs , ys , xd -> bd ) ;
 }
 else {
 inter_predictor ( pre , pre_buf -> stride , dst , dst_buf -> stride , subpel_x , subpel_y , sf , w , h , ref , kernel , xs , ys ) ;
 }
 # else inter_predictor ( pre , pre_buf -> stride , dst , dst_buf -> stride , subpel_x , subpel_y , sf , w , h , ref , kernel , xs , ys ) ;
 # endif }
 }


void PackLinuxElf64::pack1(OutputFile *fo, Filter & /*ft*/)
{
    fi->seek(0, SEEK_SET);
    fi->readx(&ehdri, sizeof(ehdri));
    assert(e_phoff == sizeof(Elf64_Ehdr));  // checked by canPack()
    sz_phdrs = e_phnum * get_te16(&ehdri.e_phentsize);

    Elf64_Phdr *phdr = phdri;
    note_size = 0;
    for (unsigned j=0; j < e_phnum; ++phdr, ++j) {
        if (PT_NOTE64 == get_te32(&phdr->p_type)) {
            note_size += up4(get_te64(&phdr->p_filesz));
        }
    }
    if (note_size) {
        note_body = New(unsigned char, note_size);
        note_size = 0;
    }
    phdr = phdri;
    for (unsigned j=0; j < e_phnum; ++phdr, ++j) {
        unsigned const type = get_te32(&phdr->p_type);
        if (PT_NOTE64 == type) {
            unsigned const len = get_te64(&phdr->p_filesz);
            fi->seek(get_te64(&phdr->p_offset), SEEK_SET);
            fi->readx(&note_body[note_size], len);
            note_size += up4(len);
        }
        if (PT_LOAD64 == type) {
            unsigned x = get_te64(&phdr->p_align) >> lg2_page;
            while (x>>=1) {
                ++lg2_page;
            }
        }
        if (PT_GNU_STACK64 == type) {
            gnu_stack = phdr;
        }
    }
    page_size =  1u  <<lg2_page;
    page_mask = ~0ull<<lg2_page;

    progid = 0;  // getRandomId();  not useful, so do not clutter
    sz_elf_hdrs = sizeof(ehdri) + sz_phdrs;
    if (0!=xct_off) {  // shared library
        sz_elf_hdrs = xct_off;
        lowmem.alloc(xct_off + (!opt->o_unix.android_shlib
            ? 0
            : e_shnum * sizeof(Elf64_Shdr)));
        memcpy(lowmem, file_image, xct_off);  // android omits Shdr here
        fo->write(lowmem, xct_off);  // < SHF_EXECINSTR (typ: in .plt or .init)
        if (opt->o_unix.android_shlib) {
            // In order to pacify the runtime linker on Android "O" ("Oreo"),
            // we will splice-in a 4KiB page that contains an "extra" copy
            // of the Shdr, any PT_NOTE above xct_off, and shstrtab.
            // File order: Ehdr, Phdr[], section contents below xct_off,
            //    Shdr_copy[], PT_NOTEs.hi, shstrtab.
            xct_va  += asl_delta;
            //xct_off += asl_delta;  // not yet

            // Relocate PT_DYNAMIC (in 2nd PT_LOAD)
            Elf64_Dyn *dyn = const_cast<Elf64_Dyn *>(dynseg);
            for (; dyn->d_tag; ++dyn) {
                upx_uint64_t d_tag = get_te64(&dyn->d_tag);
                if (Elf64_Dyn::DT_FINI       == d_tag
                ||  Elf64_Dyn::DT_FINI_ARRAY == d_tag
                ||  Elf64_Dyn::DT_INIT_ARRAY == d_tag
                ||  Elf64_Dyn::DT_PREINIT_ARRAY == d_tag
                ||  Elf64_Dyn::DT_PLTGOT      == d_tag) {
                    upx_uint64_t d_val = get_te64(&dyn->d_val);
                    set_te64(&dyn->d_val, asl_delta + d_val);
                }
            }

            // Relocate dynsym (DT_SYMTAB) which is below xct_va
            upx_uint64_t const off_dynsym = get_te64(&sec_dynsym->sh_offset);
            upx_uint64_t const sz_dynsym  = get_te64(&sec_dynsym->sh_size);
            Elf64_Sym *dyntym = (Elf64_Sym *)lowmem.subref(
                "bad dynsym", off_dynsym, sz_dynsym);
            Elf64_Sym *sym = dyntym;
            for (int j = sz_dynsym / sizeof(Elf64_Sym); --j>=0; ++sym) {
                upx_uint64_t symval = get_te64(&sym->st_value);
                unsigned symsec = get_te16(&sym->st_shndx);
                if (Elf64_Sym::SHN_UNDEF != symsec
                &&  Elf64_Sym::SHN_ABS   != symsec
                &&  xct_off <= symval) {
                    set_te64(&sym->st_value, asl_delta + symval);
                }
                if (Elf64_Sym::SHN_ABS == symsec && xct_off <= symval) {
                    adjABS(sym, asl_delta);
                }
            }

            // Relocate Phdr virtual addresses, but not physical offsets and sizes
            unsigned char buf_notes[512]; memset(buf_notes, 0, sizeof(buf_notes));
            unsigned len_notes = 0;
            phdr = (Elf64_Phdr *)lowmem.subref(
                "bad e_phoff", e_phoff, e_phnum * sizeof(Elf64_Phdr));
            for (unsigned j = 0; j < e_phnum; ++j, ++phdr) {
                upx_uint64_t offset = get_te64(&phdr->p_offset);
                if (xct_off <= offset) { // above the extra page
                    if (PT_NOTE64 == get_te32(&phdr->p_type)) {
                        upx_uint64_t memsz = get_te64(&phdr->p_memsz);
                        if (sizeof(buf_notes) < (memsz + len_notes)) {
                            throwCantPack("PT_NOTES too big");
                        }
                        set_te64(&phdr->p_vaddr,
                            len_notes + (e_shnum * sizeof(Elf64_Shdr)) + xct_off);
                        phdr->p_offset = phdr->p_paddr = phdr->p_vaddr;
                        memcpy(&buf_notes[len_notes], &file_image[offset], memsz);
                        len_notes += memsz;
                    }
                    else {
                        //set_te64(&phdr->p_offset, asl_delta + offset);  // physical
                        upx_uint64_t addr = get_te64(&phdr->p_paddr);
                        set_te64(&phdr->p_paddr, asl_delta + addr);
                                     addr = get_te64(&phdr->p_vaddr);
                        set_te64(&phdr->p_vaddr, asl_delta + addr);
                    }
                }
                // .p_filesz,.p_memsz are updated in ::pack3
            }

            Elf64_Ehdr *const ehdr = (Elf64_Ehdr *)&lowmem[0];
            upx_uint64_t e_entry = get_te64(&ehdr->e_entry);
            if (xct_off < e_entry) {
                set_te64(&ehdr->e_entry, asl_delta + e_entry);
            }
            // Relocate Shdr; and Rela, Rel (below xct_off)
            set_te64(&ehdr->e_shoff, xct_off);
            memcpy(&lowmem[xct_off], shdri, e_shnum * sizeof(Elf64_Shdr));
            Elf64_Shdr *const shdro = (Elf64_Shdr *)&lowmem[xct_off];
            Elf64_Shdr *shdr = shdro;
            upx_uint64_t sz_shstrtab  = get_te64(&sec_strndx->sh_size);
            for (unsigned j = 0; j < e_shnum; ++j, ++shdr) {
                unsigned sh_type = get_te32(&shdr->sh_type);
                upx_uint64_t sh_size = get_te64(&shdr->sh_size);
                upx_uint64_t sh_offset = get_te64(&shdr->sh_offset);
                upx_uint64_t sh_entsize = get_te64(&shdr->sh_entsize);

                if (xct_off <= sh_offset) {
                    upx_uint64_t addr = get_te64(&shdr->sh_addr);
                    set_te64(&shdr->sh_addr, asl_delta + addr);
                }
                if (Elf64_Shdr::SHT_RELA == sh_type) {
                    if (sizeof(Elf64_Rela) != sh_entsize) {
                        char msg[50];
                        snprintf(msg, sizeof(msg), "bad Rela.sh_entsize %lu", (long)sh_entsize);
                        throwCantPack(msg);
                    }
                    n_jmp_slot = 0;
                    plt_off = ~0ull;
                    Elf64_Rela *const relb = (Elf64_Rela *)lowmem.subref(
                         "bad Rela offset", sh_offset, sh_size);
                    Elf64_Rela *rela = relb;
                    for (int k = sh_size / sh_entsize; --k >= 0; ++rela) {
                        upx_uint64_t r_addend = get_te64(&rela->r_addend);
                        upx_uint64_t r_offset = get_te64(&rela->r_offset);
                        upx_uint64_t r_info   = get_te64(&rela->r_info);
                        unsigned r_type = ELF64_R_TYPE(r_info);
                        if (xct_off <= r_offset) {
                            set_te64(&rela->r_offset, asl_delta + r_offset);
                        }
                        if (Elf64_Ehdr::EM_AARCH64 == e_machine) switch (r_type) {
                            default: {
                                char msg[90]; snprintf(msg, sizeof(msg),
                                    "unexpected relocation %#x [%#x]",
                                    r_type, -1 + (unsigned)(sh_size / sh_entsize) - k);
                                throwCantPack(msg);
                            } break;
                            case R_AARCH64_ABS64: // FALL THROUGH
                            case R_AARCH64_GLOB_DAT: // FALL THROUGH
                            case R_AARCH64_RELATIVE: {
                                if (xct_off <= r_addend) {
                                    set_te64(&rela->r_addend, asl_delta + r_addend);
                                }
                            } break;
                            case R_AARCH64_JUMP_SLOT: {
                                // .rela.plt contains offset of the "first time" target
                                if (plt_off > r_offset) {
                                    plt_off = r_offset;
                                }
                                upx_uint64_t d = elf_get_offset_from_address(r_offset);
                                upx_uint64_t w = get_te64(&file_image[d]);
                                if (xct_off <= w) {
                                    set_te64(&file_image[d], asl_delta + w);
                                }
                                ++n_jmp_slot;
                            } break;
                        }
                    }
                    fo->seek(sh_offset, SEEK_SET);
                    fo->rewrite(relb, sh_size);
                }
                if (Elf64_Shdr::SHT_REL == sh_type) {
                    if (sizeof(Elf64_Rel) != sh_entsize) {
                        char msg[50];
                        snprintf(msg, sizeof(msg), "bad Rel.sh_entsize %lu", (long)sh_entsize);
                        throwCantPack(msg);
                    }
                    Elf64_Rel *rel = (Elf64_Rel *)lowmem.subref(
                            "bad Rel sh_offset", sh_offset, sh_size);
                    for (int k = sh_size / sh_entsize; --k >= 0; ++rel) {
                        upx_uint64_t r_offset = get_te64(&rel->r_offset);
                        if (xct_off <= r_offset) {
                            set_te64(&rel->r_offset, asl_delta + r_offset);
                        }
                        // r_offset must be in 2nd PT_LOAD; .p_vaddr was already relocated
                        upx_uint64_t d = elf_get_offset_from_address(asl_delta + r_offset);
                        upx_uint64_t w = get_te64(&file_image[d]);
                        upx_uint64_t r_info = get_te64(&rel->r_info);
                        unsigned r_type = ELF64_R_TYPE(r_info);
                        if (xct_off <= w
                        &&  Elf64_Ehdr::EM_AARCH64 == e_machine
                        &&  (  R_AARCH64_RELATIVE  == r_type
                            || R_AARCH64_JUMP_SLOT == r_type)) {
                            set_te64(&file_image[d], asl_delta + w);
                        }
                    }
                }
                if (Elf64_Shdr::SHT_NOTE == sh_type) {
                    if (!(Elf64_Shdr::SHF_ALLOC & get_te64(&shdr->sh_flags))) {
                        // example: version numer of 'gold' linker (static binder)
                        if (sizeof(buf_notes) < (sh_size + len_notes)) {
                            throwCantPack("SHT_NOTEs too big");
                        }
                        set_te64(&shdro[j].sh_offset,
                            len_notes + (e_shnum * sizeof(Elf64_Shdr)) + xct_off);
                        memcpy(&buf_notes[len_notes], &file_image[sh_offset], sh_size);
                        len_notes += sh_size;
                    }
                    else { // SHF_ALLOC: in PT_LOAD; but move sh_addr and sh_offset
                        // Not sure why we need this conditional.
                        // Anyway, some Android have multiple SHT_NOTE sections.
                        if (xct_off <= sh_offset) {
                            upx_uint64_t pos = xct_off + e_shnum * sizeof(Elf64_Shdr);
                            set_te64(&shdr->sh_addr,   pos);
                            set_te64(&shdr->sh_offset, pos);
                        }
                    }
                }
            }
            // shstrndx will move
            set_te64(&shdro[get_te16(&ehdri.e_shstrndx)].sh_offset,
                len_notes + e_shnum * sizeof(Elf64_Shdr) + xct_off);

            // (Re-)write all changes below xct_off
            fo->seek(0, SEEK_SET);
            fo->rewrite(lowmem, xct_off);

            // New copy of Shdr
            Elf64_Shdr blank; memset(&blank, 0, sizeof(blank));
            set_te64(&blank.sh_offset, xct_off);  // hint for "upx -d"
            fo->write(&blank, sizeof(blank));
            fo->write(&shdro[1], (-1+ e_shnum) * sizeof(Elf64_Shdr));

            if (len_notes) {
                fo->write(buf_notes, len_notes);
            }

            // New copy of Shdr[.e_shstrndx].[ sh_offset, +.sh_size )
            fo->write(shstrtab,  sz_shstrtab);

            sz_elf_hdrs = fpad8(fo);
            //xct_off += asl_delta;  // wait until ::pack3
        }
        memset(&linfo, 0, sizeof(linfo));
        fo->write(&linfo, sizeof(linfo));
    }

    // only execute if option present
    if (opt->o_unix.preserve_build_id) {
        // set this so we can use elf_find_section_name
        e_shnum = get_te16(&ehdri.e_shnum);
        MemBuffer mb_shdri;
        if (!shdri) {
            mb_shdri.alloc(e_shnum * sizeof(Elf64_Shdr));
            shdri = (Elf64_Shdr *)mb_shdri.getVoidPtr();
            e_shoff = get_te64(&ehdri.e_shoff);
            fi->seek(e_shoff, SEEK_SET);
            fi->readx(shdri, e_shnum * sizeof(Elf64_Shdr));
        }
        //set the shstrtab
        sec_strndx = &shdri[get_te16(&ehdri.e_shstrndx)];

        upx_uint64_t sh_size = get_te64(&sec_strndx->sh_size);
        char *strtab = New(char, sh_size);
        fi->seek(0,SEEK_SET);
        fi->seek(sec_strndx->sh_offset,SEEK_SET);
        fi->readx(strtab, sh_size);

        shstrtab = (const char*)strtab;

        Elf64_Shdr const *buildid = elf_find_section_name(".note.gnu.build-id");
        if (buildid) {
            unsigned bid_sh_size = get_te32(&buildid->sh_size);
            unsigned char *data = New(unsigned char, bid_sh_size);
            memset(data,0,bid_sh_size);
            fi->seek(0,SEEK_SET);
            fi->seek(buildid->sh_offset,SEEK_SET);
            fi->readx(data,bid_sh_size);

            buildid_data  = data;

            o_elf_shnum = 3;
            memset(&shdrout,0,sizeof(shdrout));

            //setup the build-id
            memcpy(&shdrout.shdr[1], buildid, sizeof(shdrout.shdr[1]));
            set_te32(&shdrout.shdr[1].sh_name, 1);

            //setup the shstrtab
            memcpy(&shdrout.shdr[2], sec_strndx, sizeof(shdrout.shdr[2]));
            set_te32(&shdrout.shdr[2].sh_name, 20);
            set_te32(&shdrout.shdr[2].sh_size, 29); //size of our static shstrtab
        }
    }
}


static void uhci_class_init(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); PCIDeviceClass *k = PCI_DEVICE_CLASS(klass); UHCIPCIDeviceClass *u = container_of(k, UHCIPCIDeviceClass, parent_class); UHCIInfo *info = data; k->init = info->initfn ? info->initfn : usb_uhci_common_initfn; k->exit = info->unplug ? usb_uhci_exit : NULL; k->vendor_id = info->vendor_id; k->device_id = info->device_id; k->revision = info->revision; k->class_id = PCI_CLASS_SERIAL_USB; dc->vmsd = &vmstate_uhci; dc->props = uhci_properties; u->info = *info; }


static int convert_to_hex ( const unsigned char * src , size_t len , char * dest ) {
 int i ;
 if ( dest ) {
 * dest ++ = '#' ;
 for ( i = 0 ;
 i < len ;
 i ++ , dest += 2 ) sprintf ( dest , "%02X" , src [ i ] ) ;
 * dest ++ = '#' ;
 }
 return len * 2 + 2 ;
 }


static int raw_open_common(BlockDriverState *bs, QDict *options, int bdrv_flags, int open_flags, Error **errp) { BDRVRawState *s = bs->opaque; QemuOpts *opts; Error *local_err = NULL; const char *filename = NULL; BlockdevAioOptions aio, aio_default; int fd, ret; struct stat st; OnOffAuto locking; opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort); qemu_opts_absorb_qdict(opts, options, &local_err); if (local_err) { error_propagate(errp, local_err); ret = -EINVAL; goto fail; } filename = qemu_opt_get(opts, "filename"); ret = raw_normalize_devicepath(&filename); if (ret != 0) { error_setg_errno(errp, -ret, "Could not normalize device path"); goto fail; } aio_default = (bdrv_flags & BDRV_O_NATIVE_AIO) ? BLOCKDEV_AIO_OPTIONS_NATIVE : BLOCKDEV_AIO_OPTIONS_THREADS; aio = qapi_enum_parse(BlockdevAioOptions_lookup, qemu_opt_get(opts, "aio"), BLOCKDEV_AIO_OPTIONS__MAX, aio_default, &local_err); if (local_err) { error_propagate(errp, local_err); ret = -EINVAL; goto fail; } s->use_linux_aio = (aio == BLOCKDEV_AIO_OPTIONS_NATIVE); locking = qapi_enum_parse(OnOffAuto_lookup, qemu_opt_get(opts, "locking"), ON_OFF_AUTO__MAX, ON_OFF_AUTO_AUTO, &local_err); if (local_err) { error_propagate(errp, local_err); ret = -EINVAL; goto fail; } switch (locking) { case ON_OFF_AUTO_ON: s->use_lock = true; #ifndef F_OFD_SETLK fprintf(stderr, "File lock requested but OFD locking syscall is unavailable, " "falling back to POSIX file locks.\n" "Due to the implementation, locks can be lost unexpectedly.\n"); #endif break; case ON_OFF_AUTO_OFF: s->use_lock = false; break; case ON_OFF_AUTO_AUTO: #ifdef F_OFD_SETLK s->use_lock = true; #else s->use_lock = false; #endif break; default: abort(); } s->open_flags = open_flags; raw_parse_flags(bdrv_flags, &s->open_flags); s->fd = -1; fd = qemu_open(filename, s->open_flags, 0644); if (fd < 0) { ret = -errno; error_setg_errno(errp, errno, "Could not open '%s'", filename); if (ret == -EROFS) { ret = -EACCES; } goto fail; } s->fd = fd; s->lock_fd = -1; if (s->use_lock) { fd = qemu_open(filename, s->open_flags); if (fd < 0) { ret = -errno; error_setg_errno(errp, errno, "Could not open '%s' for locking", filename); qemu_close(s->fd); goto fail; } s->lock_fd = fd; } s->perm = 0; s->shared_perm = BLK_PERM_ALL; #ifdef CONFIG_LINUX_AIO /* Currently Linux does AIO only for files opened with O_DIRECT */ if (s->use_linux_aio && !(s->open_flags & O_DIRECT)) { error_setg(errp, "aio=native was specified, but it requires " "cache.direct=on, which was not specified."); ret = -EINVAL; goto fail; } #else if (s->use_linux_aio) { error_setg(errp, "aio=native was specified, but is not supported " "in this build."); ret = -EINVAL; goto fail; } #endif /* !defined(CONFIG_LINUX_AIO) */ s->has_discard = true; s->has_write_zeroes = true; bs->supported_zero_flags = BDRV_REQ_MAY_UNMAP; if ((bs->open_flags & BDRV_O_NOCACHE) != 0) { s->needs_alignment = true; } if (fstat(s->fd, &st) < 0) { ret = -errno; error_setg_errno(errp, errno, "Could not stat file"); goto fail; } if (S_ISREG(st.st_mode)) { s->discard_zeroes = true; s->has_fallocate = true; } if (S_ISBLK(st.st_mode)) { #ifdef BLKDISCARDZEROES unsigned int arg; if (ioctl(s->fd, BLKDISCARDZEROES, &arg) == 0 && arg) { s->discard_zeroes = true; } #endif #ifdef __linux__ /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache. Do * not rely on the contents of discarded blocks unless using O_DIRECT. * Same for BLKZEROOUT. */ if (!(bs->open_flags & BDRV_O_NOCACHE)) { s->discard_zeroes = false; s->has_write_zeroes = false; } #endif } #ifdef __FreeBSD__ if (S_ISCHR(st.st_mode)) { /* * The file is a char device (disk), which on FreeBSD isn't behind * a pager, so force all requests to be aligned. This is needed * so QEMU makes sure all IO operations on the device are aligned * to sector size, or else FreeBSD will reject them with EINVAL. */ s->needs_alignment = true; } #endif #ifdef CONFIG_XFS if (platform_test_xfs_fd(s->fd)) { s->is_xfs = true; } #endif ret = 0; fail: if (filename && (bdrv_flags & BDRV_O_TEMPORARY)) { unlink(filename); } qemu_opts_del(opts); return ret; }


_nss_dns_gethostbyname4_r (const char *name, struct gaih_addrtuple **pat,
			   char *buffer, size_t buflen, int *errnop,
			   int *herrnop, int32_t *ttlp)
{
  if (__res_maybe_init (&_res, 0) == -1)
    return NSS_STATUS_UNAVAIL;

  /*
   * if there aren't any dots, it could be a user-level alias.
   * this is also done in res_query() since we are not the only
   * function that looks up host names.
   */
  if (strchr (name, '.') == NULL)
    {
      char *tmp = alloca (NS_MAXDNAME);
      const char *cp = res_hostalias (&_res, name, tmp, NS_MAXDNAME);
      if (cp != NULL)
	name = cp;
    }

  union
  {
    querybuf *buf;
    u_char *ptr;
  } host_buffer;
  querybuf *orig_host_buffer;
  host_buffer.buf = orig_host_buffer = (querybuf *) alloca (2048);
  u_char *ans2p = NULL;
  int nans2p = 0;
  int resplen2 = 0;
  int ans2p_malloced = 0;

  int olderr = errno;
  enum nss_status status;
  int n = __libc_res_nsearch (&_res, name, C_IN, T_UNSPEC,
			      host_buffer.buf->buf, 2048, &host_buffer.ptr,
			      &ans2p, &nans2p, &resplen2, &ans2p_malloced);
  if (n >= 0)
    {
      status = gaih_getanswer (host_buffer.buf, n, (const querybuf *) ans2p,
			       resplen2, name, pat, buffer, buflen,
			       errnop, herrnop, ttlp);
    }
  else
    {
      switch (errno)
	{
	case ESRCH:
	  status = NSS_STATUS_TRYAGAIN;
	  h_errno = TRY_AGAIN;
	  break;
	/* System has run out of file descriptors.  */
	case EMFILE:
	case ENFILE:
	  h_errno = NETDB_INTERNAL;
	  /* Fall through.  */
	case ECONNREFUSED:
	case ETIMEDOUT:
	  status = NSS_STATUS_UNAVAIL;
	  break;
	default:
	  status = NSS_STATUS_NOTFOUND;
	  break;
	}

      *herrnop = h_errno;
      if (h_errno == TRY_AGAIN)
	*errnop = EAGAIN;
      else
	__set_errno (olderr);
    }

  /* Check whether ans2p was separately allocated.  */
  if (ans2p_malloced)
    free (ans2p);

  if (host_buffer.buf != orig_host_buffer)
    free (host_buffer.buf);

  return status;
}


av_cold int ff_mjpeg_decode_init(AVCodecContext *avctx) { MJpegDecodeContext *s = avctx->priv_data; if (!s->picture_ptr) { s->picture = av_frame_alloc(); if (!s->picture) return AVERROR(ENOMEM); s->picture_ptr = s->picture; } s->avctx = avctx; ff_blockdsp_init(&s->bdsp, avctx); ff_hpeldsp_init(&s->hdsp, avctx->flags); ff_idctdsp_init(&s->idsp, avctx); ff_init_scantable(s->idsp.idct_permutation, &s->scantable, ff_zigzag_direct); s->buffer_size = 0; s->buffer = NULL; s->start_code = -1; s->first_picture = 1; s->org_height = avctx->coded_height; avctx->chroma_sample_location = AVCHROMA_LOC_CENTER; avctx->colorspace = AVCOL_SPC_BT470BG; build_basic_mjpeg_vlc(s); if (s->extern_huff) { int ret; av_log(avctx, AV_LOG_INFO, "mjpeg: using external huffman table\n"); init_get_bits(&s->gb, avctx->extradata, avctx->extradata_size * 8); if ((ret = ff_mjpeg_decode_dht(s))) { av_log(avctx, AV_LOG_ERROR, "mjpeg: error using external huffman table\n"); return ret; } } if (avctx->field_order == AV_FIELD_BB) { /* quicktime icefloe 019 */ s->interlace_polarity = 1; /* bottom field first */ av_log(avctx, AV_LOG_DEBUG, "mjpeg bottom field first\n"); } if (avctx->codec->id == AV_CODEC_ID_AMV) s->flipped = 1; return 0; }


static uint32_t U_CALLCONV offsetTOCEntryCount ( const UDataMemory * pData ) {
 int32_t retVal = 0 ;
 const UDataOffsetTOC * toc = ( UDataOffsetTOC * ) pData -> toc ;
 if ( toc != NULL ) {
 retVal = toc -> count ;
 }
 return retVal ;
 }


static void printarray ( struct pskeydict * dict ) {
 int i ;
 printf ( "[" ) ;
 for ( i = 0 ;
 i < dict -> cnt ;
 ++ i ) {
 switch ( dict -> entries [ i ] . type ) {
 case ps_num : printf ( "%g" , ( double ) dict -> entries [ i ] . u . val ) ;
 break ;
 case ps_bool : printf ( "%s" , dict -> entries [ i ] . u . tf ? "true" : "false" ) ;
 break ;
 case ps_string : case ps_instr : case ps_lit : printf ( dict -> entries [ i ] . type == ps_lit ? "/" : dict -> entries [ i ] . type == ps_string ? "(" : "{
" ) ;
 printf ( "%s" , dict -> entries [ i ] . u . str ) ;
 printf ( dict -> entries [ i ] . type == ps_lit ? "" : dict -> entries [ i ] . type == ps_string ? ")" : "}
" ) ;
 break ;
 case ps_array : printarray ( & dict -> entries [ i ] . u . dict ) ;
 break ;
 case ps_void : printf ( "-- void --" ) ;
 break ;
 default : printf ( "-- nostringval --" ) ;
 break ;
 }
 printf ( " " ) ;
 }
 printf ( "]" ) ;
 }


int psf_set_stdio ( SF_PRIVATE * psf ) {
 int error = 0 ;
 switch ( psf -> file . mode ) {
 case SFM_RDWR : error = SFE_OPEN_PIPE_RDWR ;
 break ;
 case SFM_READ : psf -> file . filedes = 0 ;
 break ;
 case SFM_WRITE : psf -> file . filedes = 1 ;
 break ;
 default : error = SFE_BAD_OPEN_MODE ;
 break ;
 }
 ;
 psf -> filelength = 0 ;
 return error ;
 }


  void Compute(OpKernelContext* ctx) override {
    const Tensor& indices_tensor = ctx->input(0);
    OP_REQUIRES(ctx,
                TensorShapeUtils::IsVector(indices_tensor.shape()) ||
                    TensorShapeUtils::IsScalar(indices_tensor.shape()),
                errors::InvalidArgument(
                    "The indices can only be scalar or vector, got \"",
                    indices_tensor.shape().DebugString(), "\""));

    const Tensor& dims_tensor = ctx->input(1);
    OP_REQUIRES(
        ctx, TensorShapeUtils::IsVector(dims_tensor.shape()),
        errors::InvalidArgument("The indices can only be 1-D, got \"",
                                dims_tensor.shape().DebugString(), "\""));

    auto dims = dims_tensor.vec<Tidx>();

    // Chek to make sure indices is not out of boundary
    Eigen::Tensor<Tidx, 0, Eigen::RowMajor> dims_prod_eigen = dims.prod();
    Tidx dims_prod = dims_prod_eigen();
    const Tidx* indices = indices_tensor.flat<Tidx>().data();
    int64 size = indices_tensor.NumElements();
    bool check = std::all_of(indices, indices + size,
                             [&](Tidx index) { return index < dims_prod; });
    OP_REQUIRES(ctx, check,
                errors::InvalidArgument("index is out of bound as with dims"));

    Eigen::array<bool, 1> reverse({true});

    Tensor strides_tensor;
    OP_REQUIRES_OK(ctx,
                   ctx->allocate_temp(DataTypeToEnum<Tidx>::value,
                                      TensorShape({dims_tensor.NumElements()}),
                                      &strides_tensor));

    auto strides = strides_tensor.vec<Tidx>();
    strides = dims.reverse(reverse)
                  .scan(0, Eigen::internal::ProdReducer<Tidx>(), false)
                  .reverse(reverse);

    Tensor strides_shifted_tensor;
    OP_REQUIRES_OK(ctx,
                   ctx->allocate_temp(DataTypeToEnum<Tidx>::value,
                                      TensorShape({dims_tensor.NumElements()}),
                                      &strides_shifted_tensor));

    auto strides_shifted = strides_shifted_tensor.vec<Tidx>();
    strides_shifted = dims.reverse(reverse)
                          .scan(0, Eigen::internal::ProdReducer<Tidx>(), true)
                          .reverse(reverse);

    Tensor* output_tensor = nullptr;
    if (TensorShapeUtils::IsScalar(indices_tensor.shape())) {
      OP_REQUIRES_OK(
          ctx, ctx->allocate_output(0, TensorShape({dims_tensor.NumElements()}),
                                    &output_tensor));

      auto output = output_tensor->vec<Tidx>();

      output = output.constant(indices_tensor.scalar<Tidx>()());
      output = output.binaryExpr(strides, mod_op<Tidx>()) / strides_shifted;
    } else {
      OP_REQUIRES_OK(
          ctx, ctx->allocate_output(0,
                                    TensorShape({dims_tensor.NumElements(),
                                                 indices_tensor.NumElements()}),
                                    &output_tensor));

      auto output = output_tensor->matrix<Tidx>();

      Eigen::array<Eigen::Index, 2> reshape{
          {static_cast<Eigen::Index>(dims_tensor.NumElements()), 1}};
      Eigen::array<Eigen::Index, 2> bcast(
          {1, static_cast<Eigen::Index>(indices_tensor.NumElements())});
      Eigen::array<Eigen::Index, 2> indices_reshape{
          {1, static_cast<Eigen::Index>(indices_tensor.NumElements())}};
      Eigen::array<Eigen::Index, 2> indices_bcast(
          {static_cast<Eigen::Index>(dims_tensor.NumElements()), 1});

      output = indices_tensor.vec<Tidx>()
                   .reshape(indices_reshape)
                   .broadcast(indices_bcast);
      output = output.binaryExpr(strides.reshape(reshape).broadcast(bcast),
                                 mod_op<Tidx>()) /
               strides_shifted.reshape(reshape).broadcast(bcast);
    }
  }


static cmsBool WriteSetOfCurves ( struct _cms_typehandler_struct * self , cmsIOHANDLER * io , cmsTagTypeSignature Type , cmsStage * mpe ) {
 cmsUInt32Number i , n ;
 cmsTagTypeSignature CurrentType ;
 cmsToneCurve * * Curves ;
 n = cmsStageOutputChannels ( mpe ) ;
 Curves = _cmsStageGetPtrToCurveSet ( mpe ) ;
 for ( i = 0 ;
 i < n ;
 i ++ ) {
 CurrentType = Type ;
 if ( ( Curves [ i ] -> nSegments == 0 ) || ( ( Curves [ i ] -> nSegments == 2 ) && ( Curves [ i ] -> Segments [ 1 ] . Type == 0 ) ) ) CurrentType = cmsSigCurveType ;
 else if ( Curves [ i ] -> Segments [ 0 ] . Type < 0 ) CurrentType = cmsSigCurveType ;
 if ( ! _cmsWriteTypeBase ( io , CurrentType ) ) return FALSE ;
 switch ( CurrentType ) {
 case cmsSigCurveType : if ( ! Type_Curve_Write ( self , io , Curves [ i ] , 1 ) ) return FALSE ;
 break ;
 case cmsSigParametricCurveType : if ( ! Type_ParametricCurve_Write ( self , io , Curves [ i ] , 1 ) ) return FALSE ;
 break ;
 default : {
 char String [ 5 ] ;
 _cmsTagSignature2String ( String , ( cmsTagSignature ) Type ) ;
 cmsSignalError ( self -> ContextID , cmsERROR_UNKNOWN_EXTENSION , "Unknown curve type '%s'" , String ) ;
 }
 return FALSE ;
 }
 if ( ! _cmsWriteAlignment ( io ) ) return FALSE ;
 }
 return TRUE ;
 }


static int ac3_decode_frame(AVCodecContext * avctx, void *data, int *data_size, uint8_t *buf, int buf_size) { AC3DecodeContext *ctx = (AC3DecodeContext *)avctx->priv_data; ac3_audio_block *ab = &ctx->audio_block; int frame_start; int i, j, k, l, value; float tmp_block_first_half[128], tmp_block_second_half[128]; int16_t *out_samples = (int16_t *)data; int nfchans; //Synchronize the frame. frame_start = ac3_synchronize(buf, buf_size); if (frame_start == -1) { av_log(avctx, AV_LOG_ERROR, "frame is not synchronized\n"); *data_size = 0; return buf_size; } //Initialize the GetBitContext with the start of valid AC3 Frame. init_get_bits(&(ctx->gb), buf + frame_start, (buf_size - frame_start) * 8); //Parse the syncinfo. //If 'fscod' or 'bsid' is not valid the decoder shall mute as per the standard. if (!ac3_parse_sync_info(ctx)) { av_log(avctx, AV_LOG_ERROR, "\n"); *data_size = 0; return -1; } //Check for the errors. /* if (ac3_error_check(ctx)) { *data_size = 0; return -1; } */ //Parse the BSI. //If 'bsid' is not valid decoder shall not decode the audio as per the standard. if (ac3_parse_bsi(ctx)) { av_log(avctx, AV_LOG_ERROR, "bsid is not valid\n"); *data_size = 0; return -1; } for (i = 0; i < MAX_BLOCKS; i++) memset(ctx->delay[i], 0, sizeof(ctx->delay[i])); avctx->sample_rate = ctx->sync_info.sampling_rate; avctx->bit_rate = ctx->sync_info.bit_rate; if (avctx->channels == 0) { //avctx->channels = ctx->bsi.nfchans + ((ctx->bsi.flags & AC3_BSI_LFEON) ? 1 : 0); ctx->output = AC3_OUTPUT_UNMODIFIED; } else if ((ctx->bsi.nfchans + ((ctx->bsi.flags & AC3_BSI_LFEON) ? 1 : 0)) < avctx->channels) { av_log(avctx, AV_LOG_INFO, "ac3_decoder: AC3 Source Channels Are Less Then Specified %d: Output to %d Channels\n", avctx->channels, (ctx->bsi.nfchans + ((ctx->bsi.flags & AC3_BSI_LFEON) ? 1 : 0))); //avctx->channels = ctx->bsi.nfchans + ((ctx->bsi.flags & AC3_BSI_LFEON) ? 1 : 0); ctx->output = AC3_OUTPUT_UNMODIFIED; } else if (avctx->channels == 1) { ctx->output = AC3_OUTPUT_MONO; } else if (avctx->channels == 2) { if (ctx->bsi.dsurmod == 0x02) ctx->output = AC3_OUTPUT_DOLBY; else ctx->output = AC3_OUTPUT_STEREO; } av_log(avctx, AV_LOG_INFO, "channels = %d \t bit rate = %d \t sampling rate = %d \n", avctx->channels, avctx->sample_rate, avctx->bit_rate); //Parse the Audio Blocks. *data_size = 0; for (i = 0; i < 6; i++) { if (ac3_parse_audio_block(ctx, i)) { av_log(avctx, AV_LOG_ERROR, "error parsing the audio block\n"); *data_size = 0; return -1; } av_log(NULL, AV_LOG_INFO, "doing imdct\n"); if (ctx->bsi.flags & AC3_BSI_LFEON) { ff_imdct_calc(&ctx->imdct_ctx_512, ctx->tmp_output, ab->transform_coeffs[0], ctx->tmp_imdct); for (l = 0; l < 256; l++) ab->block_output[0][l] = ctx->tmp_output[l] * window[l] + ctx->delay[0][l] * window[255 -l]; memcpy(ctx->delay[0], ctx->tmp_output + 256, sizeof(ctx->delay[0])); } for (j = 0; j < ctx->bsi.nfchans; j++) { if (ctx->audio_block.blksw & (1 << j)) { for (k = 0; k < 128; k++) { tmp_block_first_half[k] = ab->transform_coeffs[j + 1][2 * k]; tmp_block_second_half[k] = ab->transform_coeffs[j + 1][2 * k + 1]; } ff_imdct_calc(&ctx->imdct_ctx_256, ctx->tmp_output, tmp_block_first_half, ctx->tmp_imdct); for (l = 0; l < 256; l++) ab->block_output[j + 1][l] = ctx->tmp_output[l] * window[l] + ctx->delay[j + 1][l] * window[255 - l]; ff_imdct_calc(&ctx->imdct_ctx_256, ctx->delay[j + 1], tmp_block_second_half, ctx->tmp_imdct); } else { ff_imdct_calc(&ctx->imdct_ctx_512, ctx->tmp_output, ab->transform_coeffs[j + 1], ctx->tmp_imdct); for (l = 0; l < 256; l++) ab->block_output[j + 1][l] = ctx->tmp_output[l] * window[l] + ctx->delay[j + 1][l] * window[255 - l]; memcpy(ctx->delay[j + 1], ctx->tmp_output + 256, sizeof(ctx->delay[j + 1])); } } if (ctx->bsi.flags & AC3_BSI_LFEON) { for (l = 0; l < 256; l++) { value = lrint(ab->block_output[0][l]); if (value < -32768) value = -32768; else if (value > 32767) value = 32767; *(out_samples++) = value; } *data_size += 256 * sizeof(int16_t); } do_downmix(ctx); if (ctx->output == AC3_OUTPUT_UNMODIFIED) nfchans = ctx->bsi.nfchans; else nfchans = avctx->channels; for (k = 0; k < nfchans; k++) for (l = 0; l < 256; l++) { value = lrint(ab->block_output[k + 1][l]); if (value < -32768) value = -32768; else if (value > 32767) value = 32767; *(out_samples++) = value; } *data_size += nfchans * 256 * sizeof (int16_t); } return ctx->sync_info.framesize; }


static VALUE ossl_asn1_ ## klass ( int argc , VALUE * argv , VALUE self ) \ {
 return rb_funcall3 ( cASN1 ## klass , rb_intern ( "new" ) , argc , argv ) ;
 }
 OSSL_ASN1_IMPL_FACTORY_METHOD ( Boolean ) OSSL_ASN1_IMPL_FACTORY_METHOD ( Integer ) OSSL_ASN1_IMPL_FACTORY_METHOD ( Enumerated ) OSSL_ASN1_IMPL_FACTORY_METHOD ( BitString )


void eth_get_protocols(const uint8_t *headers, uint32_t hdr_length, bool *isip4, bool *isip6, bool *isudp, bool *istcp) { int proto; size_t l2hdr_len = eth_get_l2_hdr_length(headers); assert(hdr_length >= eth_get_l2_hdr_length(headers)); *isip4 = *isip6 = *isudp = *istcp = false; proto = eth_get_l3_proto(headers, l2hdr_len); if (proto == ETH_P_IP) { *isip4 = true; struct ip_header *iphdr; assert(hdr_length >= eth_get_l2_hdr_length(headers) + sizeof(struct ip_header)); iphdr = PKT_GET_IP_HDR(headers); if (IP_HEADER_VERSION(iphdr) == IP_HEADER_VERSION_4) { if (iphdr->ip_p == IP_PROTO_TCP) { *istcp = true; } else if (iphdr->ip_p == IP_PROTO_UDP) { *isudp = true; } } } else if (proto == ETH_P_IPV6) { uint8_t l4proto; size_t full_ip6hdr_len; struct iovec hdr_vec; hdr_vec.iov_base = (void *) headers; hdr_vec.iov_len = hdr_length; *isip6 = true; if (eth_parse_ipv6_hdr(&hdr_vec, 1, l2hdr_len, &l4proto, &full_ip6hdr_len)) { if (l4proto == IP_PROTO_TCP) { *istcp = true; } else if (l4proto == IP_PROTO_UDP) { *isudp = true; } } } }


static void empty_trash_for_unmount_done ( gboolean success , gpointer user_data ) {
 UnmountData * data = user_data ;
 do_unmount ( data ) ;
 }


static void memory_init(void) { qemu_mutex_init(&flat_view_mutex); }


int setup_vpn_in_socket ( const sockaddr_t * sa ) {
 int nfd ;
 char * addrstr ;
 int option ;
 nfd = socket ( sa -> sa . sa_family , SOCK_DGRAM , IPPROTO_UDP ) ;
 if ( nfd < 0 ) {
 logger ( LOG_ERR , "Creating UDP socket failed: %s" , sockstrerror ( sockerrno ) ) ;
 return - 1 ;
 }
 # ifdef FD_CLOEXEC fcntl ( nfd , F_SETFD , FD_CLOEXEC ) ;
 # endif # ifdef O_NONBLOCK {
 int flags = fcntl ( nfd , F_GETFL ) ;
 if ( fcntl ( nfd , F_SETFL , flags | O_NONBLOCK ) < 0 ) {
 closesocket ( nfd ) ;
 logger ( LOG_ERR , "System call `%s' failed: %s" , "fcntl" , strerror ( errno ) ) ;
 return - 1 ;
 }
 }
 # elif defined ( WIN32 ) {
 unsigned long arg = 1 ;
 if ( ioctlsocket ( nfd , FIONBIO , & arg ) != 0 ) {
 closesocket ( nfd ) ;
 logger ( LOG_ERR , "Call to `%s' failed: %s" , "ioctlsocket" , sockstrerror ( sockerrno ) ) ;
 return - 1 ;
 }
 }
 # endif option = 1 ;
 setsockopt ( nfd , SOL_SOCKET , SO_REUSEADDR , ( void * ) & option , sizeof ( option ) ) ;
 setsockopt ( nfd , SOL_SOCKET , SO_BROADCAST , ( void * ) & option , sizeof ( option ) ) ;
 if ( udp_rcvbuf && setsockopt ( nfd , SOL_SOCKET , SO_RCVBUF , ( void * ) & udp_rcvbuf , sizeof ( udp_rcvbuf ) ) ) {
 logger ( LOG_WARNING , "Can't set UDP SO_RCVBUF to %i: %s" , udp_rcvbuf , strerror ( errno ) ) ;
 }
 if ( udp_sndbuf && setsockopt ( nfd , SOL_SOCKET , SO_SNDBUF , ( void * ) & udp_sndbuf , sizeof ( udp_sndbuf ) ) ) {
 logger ( LOG_WARNING , "Can't set UDP SO_SNDBUF to %i: %s" , udp_sndbuf , strerror ( errno ) ) ;
 }
 # if defined ( IPV6_V6ONLY ) if ( sa -> sa . sa_family == AF_INET6 ) {
 setsockopt ( nfd , IPPROTO_IPV6 , IPV6_V6ONLY , ( void * ) & option , sizeof ( option ) ) ;
 }
 # endif # if defined ( IP_DONTFRAG ) && ! defined ( IP_DONTFRAGMENT ) # define IP_DONTFRAGMENT IP_DONTFRAG # endif # if defined ( IP_MTU_DISCOVER ) && defined ( IP_PMTUDISC_DO ) if ( myself -> options & OPTION_PMTU_DISCOVERY ) {
 option = IP_PMTUDISC_DO ;
 setsockopt ( nfd , IPPROTO_IP , IP_MTU_DISCOVER , ( void * ) & option , sizeof ( option ) ) ;
 }
 # elif defined ( IP_DONTFRAGMENT ) if ( myself -> options & OPTION_PMTU_DISCOVERY ) {
 option = 1 ;
 setsockopt ( nfd , IPPROTO_IP , IP_DONTFRAGMENT , ( void * ) & option , sizeof ( option ) ) ;
 }
 # endif # if defined ( IPV6_MTU_DISCOVER ) && defined ( IPV6_PMTUDISC_DO ) if ( myself -> options & OPTION_PMTU_DISCOVERY ) {
 option = IPV6_PMTUDISC_DO ;
 setsockopt ( nfd , IPPROTO_IPV6 , IPV6_MTU_DISCOVER , ( void * ) & option , sizeof ( option ) ) ;
 }
 # elif defined ( IPV6_DONTFRAG ) if ( myself -> options & OPTION_PMTU_DISCOVERY ) {
 option = 1 ;
 setsockopt ( nfd , IPPROTO_IPV6 , IPV6_DONTFRAG , ( void * ) & option , sizeof ( option ) ) ;
 }
 # endif if ( ! bind_to_interface ( nfd ) ) {
 closesocket ( nfd ) ;
 return - 1 ;
 }
 if ( bind ( nfd , & sa -> sa , SALEN ( sa -> sa ) ) ) {
 closesocket ( nfd ) ;
 addrstr = sockaddr2hostname ( sa ) ;
 logger ( LOG_ERR , "Can't bind to %s/udp: %s" , addrstr , sockstrerror ( sockerrno ) ) ;
 free ( addrstr ) ;
 return - 1 ;
 }
 return nfd ;
 }


void ide_data_writel(void *opaque, uint32_t addr, uint32_t val) { IDEBus *bus = opaque; IDEState *s = idebus_active_if(bus); uint8_t *p; /* PIO data access allowed only when DRQ bit is set. The result of a write * during PIO out is indeterminate, just ignore it. */ if (!(s->status & DRQ_STAT) || ide_is_pio_out(s)) { p = s->data_ptr; *(uint32_t *)p = le32_to_cpu(val); p += 4; s->data_ptr = p; if (p >= s->data_end) s->end_transfer_func(s);


static inline struct extr_rec * extra_last_record ( struct isoent * isoent ) {
 if ( isoent -> extr_rec_list . first == NULL ) return ( NULL ) ;
 return ( ( struct extr_rec * ) ( void * ) ( ( char * ) ( isoent -> extr_rec_list . last ) - offsetof ( struct extr_rec , next ) ) ) ;
 }


static int dissect_h225_SetupAcknowledge_UUIE ( tvbuff_t * tvb _U_ , int offset _U_ , asn1_ctx_t * actx _U_ , proto_tree * tree _U_ , int hf_index _U_ ) {
 # line 428 "./asn1/h225/h225.cnf" h225_packet_info * h225_pi ;
 offset = dissect_per_sequence ( tvb , offset , actx , tree , hf_index , ett_h225_SetupAcknowledge_UUIE , SetupAcknowledge_UUIE_sequence ) ;
 # line 432 "./asn1/h225/h225.cnf" h225_pi = ( h225_packet_info * ) p_get_proto_data ( wmem_packet_scope ( ) , actx -> pinfo , proto_h225 , 0 ) ;
 if ( h225_pi != NULL ) {
 h225_pi -> cs_type = H225_SETUP_ACK ;
 g_snprintf ( h225_pi -> frame_label , 50 , "%s" , val_to_str ( h225_pi -> cs_type , T_h323_message_body_vals , "<unknown>" ) ) ;
 }
 return offset ;
 }


int jas_stream_getc_func ( jas_stream_t * stream ) {
 assert ( stream -> ptr_ - stream -> bufbase_ <= stream -> bufsize_ + JAS_STREAM_MAXPUTBACK ) ;
 return jas_stream_getc_macro ( stream ) ;
 }


static void gdb_accept(void) { GDBState *s; struct sockaddr_in sockaddr; socklen_t len; int val, fd; for(;;) { len = sizeof(sockaddr); fd = accept(gdbserver_fd, (struct sockaddr *)&sockaddr, &len); if (fd < 0 && errno != EINTR) { perror("accept"); return; } else if (fd >= 0) { break; } } /* set short latency */ val = 1; setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val)); s = qemu_mallocz(sizeof(GDBState)); s->c_cpu = first_cpu; s->g_cpu = first_cpu; s->fd = fd; gdb_has_xml = 0; gdbserver_state = s; fcntl(fd, F_SETFL, O_NONBLOCK); }


av_cold void ff_huffyuvdsp_init_ppc(HuffYUVDSPContext *c) { #if HAVE_ALTIVEC && HAVE_BIGENDIAN if (!PPC_ALTIVEC(av_get_cpu_flags())) return; c->add_bytes = add_bytes_altivec; #endif /* HAVE_ALTIVEC && HAVE_BIGENDIAN */ }


static int init_input(AVFormatContext *s, const char *filename, AVDictionary **options) { int ret; AVProbeData pd = { filename, NULL, 0 }; int score = AVPROBE_SCORE_RETRY; if (s->pb) { s->flags |= AVFMT_FLAG_CUSTOM_IO; if (!s->iformat) return av_probe_input_buffer2(s->pb, &s->iformat, filename, s, 0, s->format_probesize); else if (s->iformat->flags & AVFMT_NOFILE) av_log(s, AV_LOG_WARNING, "Custom AVIOContext makes no sense and " "will be ignored with AVFMT_NOFILE format.\n"); return 0; } if ((s->iformat && s->iformat->flags & AVFMT_NOFILE) || (!s->iformat && (s->iformat = av_probe_input_format2(&pd, 0, &score)))) return score; if ((ret = avio_open2(&s->pb, filename, AVIO_FLAG_READ | s->avio_flags, &s->interrupt_callback, options)) < 0) return ret; if (s->iformat) return 0; return av_probe_input_buffer2(s->pb, &s->iformat, filename, s, 0, s->format_probesize); }


static struct ldb_message *winsdb_message(struct ldb_context *ldb,
					  struct winsdb_record *rec,
					  TALLOC_CTX *mem_ctx)
{
	int i, ret;
	size_t addr_count;
	const char *expire_time;
	struct ldb_message *msg = ldb_msg_new(mem_ctx);
	if (msg == NULL) goto failed;

	/* make sure we don't put in corrupted records */
	addr_count = winsdb_addr_list_length(rec->addresses);
	if (rec->state == WREPL_STATE_ACTIVE && addr_count == 0) {
		rec->state = WREPL_STATE_RELEASED;
	}
	if (rec->type == WREPL_TYPE_UNIQUE && addr_count > 1) {
		rec->type = WREPL_TYPE_MHOMED;
	}

	expire_time = ldb_timestring(msg, rec->expire_time);
	if (!expire_time) {
		goto failed;
	}

	msg->dn = winsdb_dn(msg, ldb, rec->name);
	if (msg->dn == NULL) goto failed;
	ret = ldb_msg_add_fmt(msg, "type", "0x%02X", rec->name->type);
	if (rec->name->name && *rec->name->name) {
		ret |= ldb_msg_add_string(msg, "name", rec->name->name);
	}
	if (rec->name->scope && *rec->name->scope) {
		ret |= ldb_msg_add_string(msg, "scope", rec->name->scope);
	}
	ret |= ldb_msg_add_fmt(msg, "objectClass", "winsRecord");
	ret |= ldb_msg_add_fmt(msg, "recordType", "%u", rec->type);
	ret |= ldb_msg_add_fmt(msg, "recordState", "%u", rec->state);
	ret |= ldb_msg_add_fmt(msg, "nodeType", "%u", rec->node);
	ret |= ldb_msg_add_fmt(msg, "isStatic", "%u", rec->is_static);
	ret |= ldb_msg_add_empty(msg, "expireTime", 0, NULL);
	if (!(rec->is_static && rec->state == WREPL_STATE_ACTIVE)) {
		ret |= ldb_msg_add_string(msg, "expireTime", expire_time);
	}
	ret |= ldb_msg_add_fmt(msg, "versionID", "%llu", (long long)rec->version);
	ret |= ldb_msg_add_string(msg, "winsOwner", rec->wins_owner);
	ret |= ldb_msg_add_empty(msg, "address", 0, NULL);
	for (i=0;rec->addresses[i];i++) {
		ret |= ldb_msg_add_winsdb_addr(msg, rec, "address", rec->addresses[i]);
	}
	if (rec->registered_by) {
		ret |= ldb_msg_add_empty(msg, "registeredBy", 0, NULL);
		ret |= ldb_msg_add_string(msg, "registeredBy", rec->registered_by);
	}
	if (ret != LDB_SUCCESS) goto failed;
	return msg;

failed:
	talloc_free(msg);
	return NULL;
}


static int replmd_name_modify(struct replmd_replicated_request *ar,
			      struct ldb_request *req, struct ldb_dn *dn)
{
	struct ldb_message *msg;
	const char *rdn_name;
	const struct ldb_val *rdn_val;
	const struct dsdb_attribute *rdn_attr;
	int ret;

	msg = ldb_msg_new(req);
	if (msg == NULL) {
		goto failed;
	}
	msg->dn = dn;

	rdn_name = ldb_dn_get_rdn_name(dn);
	if (rdn_name == NULL) {
		goto failed;
	}

	/* normalize the rdn attribute name */
	rdn_attr = dsdb_attribute_by_lDAPDisplayName(ar->schema, rdn_name);
	if (rdn_attr == NULL) {
		goto failed;
	}
	rdn_name = rdn_attr->lDAPDisplayName;

	rdn_val = ldb_dn_get_rdn_val(dn);
	if (rdn_val == NULL) {
		goto failed;
	}

	if (ldb_msg_add_empty(msg, rdn_name, LDB_FLAG_MOD_REPLACE, NULL) != 0) {
		goto failed;
	}
	if (ldb_msg_add_value(msg, rdn_name, rdn_val, NULL) != 0) {
		goto failed;
	}
	if (ldb_msg_add_empty(msg, "name", LDB_FLAG_MOD_REPLACE, NULL) != 0) {
		goto failed;
	}
	if (ldb_msg_add_value(msg, "name", rdn_val, NULL) != 0) {
		goto failed;
	}

	/*
	 * We have to mark this as a replicated update otherwise
	 * schema_data may reject a rename in the schema partition
	 */

	ret = dsdb_module_modify(ar->module, msg,
				 DSDB_FLAG_OWN_MODULE|DSDB_FLAG_REPLICATED_UPDATE,
				 req);
	if (ret != LDB_SUCCESS) {
		DEBUG(0,(__location__ ": Failed to modify rDN/name of DN being DRS renamed '%s' - %s",
			 ldb_dn_get_linearized(dn),
			 ldb_errstring(ldb_module_get_ctx(ar->module))));
		return ret;
	}

	talloc_free(msg);

	return LDB_SUCCESS;

failed:
	talloc_free(msg);
	DEBUG(0,(__location__ ": Failed to setup modify rDN/name of DN being DRS renamed '%s'",
		 ldb_dn_get_linearized(dn)));
	return LDB_ERR_OPERATIONS_ERROR;
}


static qemu_irq *vpb_sic_init(uint32_t base, qemu_irq *parent, int irq) { vpb_sic_state *s; qemu_irq *qi; int iomemtype; s = (vpb_sic_state *)qemu_mallocz(sizeof(vpb_sic_state)); if (!s) return NULL; qi = qemu_allocate_irqs(vpb_sic_set_irq, s, 32); s->base = base; s->parent = parent; s->irq = irq; iomemtype = cpu_register_io_memory(0, vpb_sic_readfn, vpb_sic_writefn, s); cpu_register_physical_memory(base, 0x00000fff, iomemtype); /* ??? Save/restore. */ return qi; }


IN_PROC_BROWSER_TEST_F ( AppApiTest , ReloadIntoAppProcessWithJavaScript ) {
 extensions : : ProcessMap * process_map = extensions : : ProcessMap : : Get ( browser ( ) -> profile ( ) ) ;
 GURL base_url = GetTestBaseURL ( "app_process" ) ;
 LOG ( INFO ) << "Loading extension." ;
 const Extension * app = LoadExtension ( test_data_dir_ . AppendASCII ( "app_process" ) ) ;
 LOG ( INFO ) << "Loading extension - done." ;
 ASSERT_TRUE ( app ) ;
 LOG ( INFO ) << "Disabling extension." ;
 DisableExtension ( app -> id ( ) ) ;
 LOG ( INFO ) << "Disabling extension - done." ;
 LOG ( INFO ) << "Navigate to path1/empty.html." ;
 ui_test_utils : : NavigateToURL ( browser ( ) , base_url . Resolve ( "path1/empty.html" ) ) ;
 LOG ( INFO ) << "Navigate to path1/empty.html - done." ;
 WebContents * contents = browser ( ) -> tab_strip_model ( ) -> GetWebContentsAt ( 0 ) ;
 EXPECT_FALSE ( process_map -> Contains ( contents -> GetRenderProcessHost ( ) -> GetID ( ) ) ) ;
 LOG ( INFO ) << "Enabling extension." ;
 EnableExtension ( app -> id ( ) ) ;
 LOG ( INFO ) << "Enabling extension - done." ;
 content : : WindowedNotificationObserver js_reload_observer ( content : : NOTIFICATION_LOAD_STOP , content : : Source < NavigationController > ( & browser ( ) -> tab_strip_model ( ) -> GetActiveWebContents ( ) -> GetController ( ) ) ) ;
 LOG ( INFO ) << "Executing location.reload()." ;
 ASSERT_TRUE ( content : : ExecuteScript ( contents , "location.reload();
" ) ) ;
 js_reload_observer . Wait ( ) ;
 LOG ( INFO ) << "Executing location.reload() - done." ;
 EXPECT_TRUE ( process_map -> Contains ( contents -> GetRenderProcessHost ( ) -> GetID ( ) ) ) ;
 LOG ( INFO ) << "Disabling extension." ;
 DisableExtension ( app -> id ( ) ) ;
 LOG ( INFO ) << "Disabling extension - done." ;
 content : : WindowedNotificationObserver js_reload_observer2 ( content : : NOTIFICATION_LOAD_STOP , content : : Source < NavigationController > ( & browser ( ) -> tab_strip_model ( ) -> GetActiveWebContents ( ) -> GetController ( ) ) ) ;
 LOG ( INFO ) << "Executing location = location." ;
 ASSERT_TRUE ( content : : ExecuteScript ( contents , "location = location;
" ) ) ;
 js_reload_observer2 . Wait ( ) ;
 LOG ( INFO ) << "Executing location = location - done." ;
 EXPECT_FALSE ( process_map -> Contains ( contents -> GetRenderProcessHost ( ) -> GetID ( ) ) ) ;
 }


static void recovery_abort(void) {
    if (!dry_run) {
        storage_reset();
    }

    awaiting_character = false;
    memzero(mnemonic, sizeof(mnemonic));
    memzero(cipher, sizeof(cipher));
}


static int encode_picture_lossless(AVCodecContext *avctx, AVPacket *pkt, const AVFrame *pict, int *got_packet) { MpegEncContext * const s = avctx->priv_data; MJpegContext * const m = s->mjpeg_ctx; const int width= s->width; const int height= s->height; AVFrame * const p = &s->current_picture.f; const int predictor= avctx->prediction_method+1; const int mb_width = (width + s->mjpeg_hsample[0] - 1) / s->mjpeg_hsample[0]; const int mb_height = (height + s->mjpeg_vsample[0] - 1) / s->mjpeg_vsample[0]; int ret, max_pkt_size = FF_MIN_BUFFER_SIZE; if (avctx->pix_fmt == AV_PIX_FMT_BGRA) max_pkt_size += width * height * 3 * 4; else { max_pkt_size += mb_width * mb_height * 3 * 4 * s->mjpeg_hsample[0] * s->mjpeg_vsample[0]; if ((ret = ff_alloc_packet2(avctx, pkt, max_pkt_size)) < 0) init_put_bits(&s->pb, pkt->data, pkt->size); *p = *pict; p->pict_type= AV_PICTURE_TYPE_I; p->key_frame= 1; ff_mjpeg_encode_picture_header(s); s->header_bits= put_bits_count(&s->pb); if(avctx->pix_fmt == AV_PIX_FMT_BGR0 || avctx->pix_fmt == AV_PIX_FMT_BGRA || avctx->pix_fmt == AV_PIX_FMT_BGR24){ int x, y, i; const int linesize= p->linesize[0]; uint16_t (*buffer)[4]= (void *) s->rd_scratchpad; int left[3], top[3], topleft[3]; for(i=0; i<3; i++){ buffer[0][i]= 1 << (9 - 1); for(y = 0; y < height; y++) { const int modified_predictor= y ? predictor : 1; uint8_t *ptr = p->data[0] + (linesize * y); if(s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb)>>3) < width*3*4){ av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n"); return -1; for(i=0; i<3; i++){ top[i]= left[i]= topleft[i]= buffer[0][i]; for(x = 0; x < width; x++) { if(avctx->pix_fmt == AV_PIX_FMT_BGR24){ buffer[x][1] = ptr[3*x+0] - ptr[3*x+1] + 0x100; buffer[x][2] = ptr[3*x+2] - ptr[3*x+1] + 0x100; buffer[x][0] = (ptr[3*x+0] + 2*ptr[3*x+1] + ptr[3*x+2])>>2; }else{ buffer[x][1] = ptr[4*x+0] - ptr[4*x+1] + 0x100; buffer[x][2] = ptr[4*x+2] - ptr[4*x+1] + 0x100; buffer[x][0] = (ptr[4*x+0] + 2*ptr[4*x+1] + ptr[4*x+2])>>2; for(i=0;i<3;i++) { int pred, diff; PREDICT(pred, topleft[i], top[i], left[i], modified_predictor); topleft[i]= top[i]; top[i]= buffer[x+1][i]; left[i]= buffer[x][i]; diff= ((left[i] - pred + 0x100)&0x1FF) - 0x100; if(i==0) ff_mjpeg_encode_dc(s, diff, m->huff_size_dc_luminance, m->huff_code_dc_luminance); //FIXME ugly else ff_mjpeg_encode_dc(s, diff, m->huff_size_dc_chrominance, m->huff_code_dc_chrominance); }else{ int mb_x, mb_y, i; for(mb_y = 0; mb_y < mb_height; mb_y++) { if(s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb)>>3) < mb_width * 4 * 3 * s->mjpeg_hsample[0] * s->mjpeg_vsample[0]){ av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n"); return -1; for(mb_x = 0; mb_x < mb_width; mb_x++) { if(mb_x==0 || mb_y==0){ for(i=0;i<3;i++) { uint8_t *ptr; int x, y, h, v, linesize; h = s->mjpeg_hsample[i]; v = s->mjpeg_vsample[i]; linesize= p->linesize[i]; for(y=0; y<v; y++){ for(x=0; x<h; x++){ int pred; ptr = p->data[i] + (linesize * (v * mb_y + y)) + (h * mb_x + x); //FIXME optimize this crap if(y==0 && mb_y==0){ if(x==0 && mb_x==0){ pred= 128; }else{ pred= ptr[-1]; }else{ if(x==0 && mb_x==0){ pred= ptr[-linesize]; }else{ PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor); if(i==0) ff_mjpeg_encode_dc(s, *ptr - pred, m->huff_size_dc_luminance, m->huff_code_dc_luminance); //FIXME ugly else ff_mjpeg_encode_dc(s, *ptr - pred, m->huff_size_dc_chrominance, m->huff_code_dc_chrominance); }else{ for(i=0;i<3;i++) { uint8_t *ptr; int x, y, h, v, linesize; h = s->mjpeg_hsample[i]; v = s->mjpeg_vsample[i]; linesize= p->linesize[i]; for(y=0; y<v; y++){ for(x=0; x<h; x++){ int pred; ptr = p->data[i] + (linesize * (v * mb_y + y)) + (h * mb_x + x); //FIXME optimize this crap PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor); if(i==0) ff_mjpeg_encode_dc(s, *ptr - pred, m->huff_size_dc_luminance, m->huff_code_dc_luminance); //FIXME ugly else ff_mjpeg_encode_dc(s, *ptr - pred, m->huff_size_dc_chrominance, m->huff_code_dc_chrominance); emms_c(); av_assert0(s->esc_pos == s->header_bits >> 3); ff_mjpeg_encode_stuffing(s); ff_mjpeg_encode_picture_trailer(s); s->picture_number++; flush_put_bits(&s->pb); pkt->size = put_bits_ptr(&s->pb) - s->pb.buf; pkt->flags |= AV_PKT_FLAG_KEY; *got_packet = 1; return 0; // return (put_bits_count(&f->pb)+7)/8;


int VvcSpsUnit::deserialize()
{
    int rez = VvcUnit::deserialize();
    if (rez)
        return rez;
    try
    {
        sps_id = m_reader.getBits(4);
        vps_id = m_reader.getBits(4);
        max_sublayers_minus1 = m_reader.getBits(3);
        if (max_sublayers_minus1 == 7)
            return 1;
        chroma_format_idc = m_reader.getBits(2);
        unsigned sps_log2_ctu_size_minus5 = m_reader.getBits(2);
        if (sps_log2_ctu_size_minus5 > 2)
            return 1;
        int CtbLog2SizeY = sps_log2_ctu_size_minus5 + 5;
        unsigned CtbSizeY = 1 << CtbLog2SizeY;
        bool sps_ptl_dpb_hrd_params_present_flag = m_reader.getBit();
        if (sps_id == 0 && !sps_ptl_dpb_hrd_params_present_flag)
            return 1;
        if (sps_ptl_dpb_hrd_params_present_flag)
            profile_tier_level(1, max_sublayers_minus1);
        m_reader.skipBit();      // sps_gdr_enabled_flag
        if (m_reader.getBit())   // sps_ref_pic_resampling_enabled_flag
            m_reader.skipBit();  // sps_res_change_in_clvs_allowed_flag
        pic_width_max_in_luma_samples = extractUEGolombCode();
        pic_height_max_in_luma_samples = extractUEGolombCode();
        unsigned tmpWidthVal = (pic_width_max_in_luma_samples + CtbSizeY - 1) / CtbSizeY;
        unsigned tmpHeightVal = (pic_height_max_in_luma_samples + CtbSizeY - 1) / CtbSizeY;
        unsigned sps_conf_win_left_offset = 0;
        unsigned sps_conf_win_right_offset = 0;
        unsigned sps_conf_win_top_offset = 0;
        unsigned sps_conf_win_bottom_offset = 0;
        if (m_reader.getBit())  // sps_conformance_window_flag
        {
            sps_conf_win_left_offset = extractUEGolombCode();
            sps_conf_win_right_offset = extractUEGolombCode();
            sps_conf_win_top_offset = extractUEGolombCode();
            sps_conf_win_bottom_offset = extractUEGolombCode();
        }
        if (m_reader.getBit())  // sps_subpic_info_present_flag
        {
            unsigned sps_num_subpics_minus1 = extractUEGolombCode();
            if (sps_num_subpics_minus1 > 600)
                return 1;
            if (sps_num_subpics_minus1 > 0)
            {
                bool sps_independent_subpics_flag = m_reader.getBit();
                bool sps_subpic_same_size_flag = m_reader.getBit();
                for (size_t i = 0; i <= sps_num_subpics_minus1; i++)
                {
                    if (!sps_subpic_same_size_flag || i == 0)
                    {
                        if (i != 0 && pic_width_max_in_luma_samples > CtbSizeY)
                            m_reader.skipBits(ceil(log2(tmpWidthVal)));  // sps_subpic_ctu_top_left_x[i]
                        if (i != 0 && pic_height_max_in_luma_samples > CtbSizeY)
                            m_reader.skipBits(ceil(log2(tmpHeightVal)));  // sps_subpic_ctu_top_left_y[i]
                        if (i < sps_num_subpics_minus1 && pic_width_max_in_luma_samples > CtbSizeY)
                            m_reader.skipBits(ceil(log2(tmpWidthVal)));  // sps_subpic_width_minus1[i]
                        if (i < sps_num_subpics_minus1 && pic_height_max_in_luma_samples > CtbSizeY)
                            m_reader.skipBits(ceil(log2(tmpHeightVal)));  // sps_subpic_height_minus1[i]
                    }
                    if (!sps_independent_subpics_flag)
                    {
                        m_reader.skipBit();  // sps_subpic_treated_as_pic_flag
                        m_reader.skipBit();  // sps_loop_filter_across_subpic_enabled_flag
                    }
                }
            }
            unsigned sps_subpic_id_len = extractUEGolombCode() + 1;
            if (sps_subpic_id_len > 16 || (unsigned)(1 << sps_subpic_id_len) < (sps_num_subpics_minus1 + 1))
                return 1;
            if (m_reader.getBit())  // sps_subpic_id_mapping_explicitly_signalled_flag
            {
                if (m_reader.getBit())  // sps_subpic_id_mapping_present_flag
                    for (size_t i = 0; i <= sps_num_subpics_minus1; i++)
                        m_reader.skipBits(sps_subpic_id_len);  // sps_subpic_id[i]
            }
        }
        bitdepth_minus8 = extractUEGolombCode();
        if (bitdepth_minus8 > 2)
            return 1;
        int QpBdOffset = 6 * bitdepth_minus8;
        m_reader.skipBit();  // sps_entropy_coding_sync_enabled_flag
        m_reader.skipBit();  // vsps_entry_point_offsets_present_flag
        log2_max_pic_order_cnt_lsb = m_reader.getBits(4) + 4;
        if (log2_max_pic_order_cnt_lsb > 16)
            return 1;
        if (m_reader.getBit())  // sps_poc_msb_cycle_flag
        {
            if (extractUEGolombCode() /* sps_poc_msb_cycle_len_minus1 */ > 23 - log2_max_pic_order_cnt_lsb)
                return 1;
        }
        int sps_num_extra_ph_bytes = m_reader.getBits(2);
        for (size_t i = 0; i < sps_num_extra_ph_bytes; i++) m_reader.skipBits(8);  // sps_extra_ph_bit_present_flag[i]
        int sps_num_extra_sh_bytes = m_reader.getBits(2);
        for (size_t i = 0; i < sps_num_extra_sh_bytes; i++) m_reader.skipBits(8);  // sps_extra_sh_bit_present_flag[i]
        if (sps_ptl_dpb_hrd_params_present_flag)
        {
            bool sps_sublayer_dpb_params_flag = (max_sublayers_minus1 > 0) ? m_reader.getBit() : 0;
            if (dpb_parameters(max_sublayers_minus1, sps_sublayer_dpb_params_flag))
                return 1;
        }
        unsigned sps_log2_min_luma_coding_block_size_minus2 = extractUEGolombCode();
        if (sps_log2_min_luma_coding_block_size_minus2 > (unsigned)min(4, (int)sps_log2_ctu_size_minus5 + 3))
            return 1;
        unsigned MinCbLog2SizeY = sps_log2_min_luma_coding_block_size_minus2 + 2;
        unsigned MinCbSizeY = 1 << MinCbLog2SizeY;
        m_reader.skipBit();  // sps_partition_constraints_override_enabled_flag
        unsigned sps_log2_diff_min_qt_min_cb_intra_slice_luma = extractUEGolombCode();
        if (sps_log2_diff_min_qt_min_cb_intra_slice_luma > min(6, CtbLog2SizeY) - MinCbLog2SizeY)
            return 1;
        unsigned MinQtLog2SizeIntraY = sps_log2_diff_min_qt_min_cb_intra_slice_luma + MinCbLog2SizeY;
        unsigned sps_max_mtt_hierarchy_depth_intra_slice_luma = extractUEGolombCode();
        if (sps_max_mtt_hierarchy_depth_intra_slice_luma > 2 * (CtbLog2SizeY - MinCbLog2SizeY))
            return 1;
        if (sps_max_mtt_hierarchy_depth_intra_slice_luma != 0)
        {
            if (extractUEGolombCode() >
                CtbLog2SizeY - MinQtLog2SizeIntraY)  // sps_log2_diff_max_bt_min_qt_intra_slice_luma
                return 1;
            if (extractUEGolombCode() >
                min(6, CtbLog2SizeY) - MinQtLog2SizeIntraY)  // sps_log2_diff_max_tt_min_qt_intra_slice_luma
                return 1;
        }
        bool sps_qtbtt_dual_tree_intra_flag = (chroma_format_idc != 0 ? m_reader.getBit() : 0);
        if (sps_qtbtt_dual_tree_intra_flag)
        {
            unsigned sps_log2_diff_min_qt_min_cb_intra_slice_chroma = extractUEGolombCode();
            if (sps_log2_diff_min_qt_min_cb_intra_slice_chroma > min(6, CtbLog2SizeY) - MinCbLog2SizeY)  //
                return 1;
            unsigned MinQtLog2SizeIntraC = sps_log2_diff_min_qt_min_cb_intra_slice_chroma + MinCbLog2SizeY;
            unsigned sps_max_mtt_hierarchy_depth_intra_slice_chroma = extractUEGolombCode();
            if (sps_max_mtt_hierarchy_depth_intra_slice_chroma > 2 * (CtbLog2SizeY - MinCbLog2SizeY))
                return 1;
            if (sps_max_mtt_hierarchy_depth_intra_slice_chroma != 0)
            {
                if (extractUEGolombCode() >
                    min(6, CtbLog2SizeY) - MinQtLog2SizeIntraC)  // sps_log2_diff_max_bt_min_qt_intra_slice_chroma
                    return 1;
                if (extractUEGolombCode() >
                    min(6, CtbLog2SizeY) - MinQtLog2SizeIntraC)  // sps_log2_diff_max_tt_min_qt_intra_slice_chroma
                    return 1;
            }
        }
        unsigned sps_log2_diff_min_qt_min_cb_inter_slice = extractUEGolombCode();
        if (sps_log2_diff_min_qt_min_cb_inter_slice > min(6, CtbLog2SizeY) - MinCbLog2SizeY)
            return 1;
        unsigned MinQtLog2SizeInterY = sps_log2_diff_min_qt_min_cb_inter_slice + MinCbLog2SizeY;
        unsigned sps_max_mtt_hierarchy_depth_inter_slice = extractUEGolombCode();
        if (sps_max_mtt_hierarchy_depth_inter_slice > 2 * (CtbLog2SizeY - MinCbLog2SizeY))
            return 1;
        if (sps_max_mtt_hierarchy_depth_inter_slice != 0)
        {
            if (extractUEGolombCode() > CtbLog2SizeY - MinQtLog2SizeInterY)  // sps_log2_diff_max_bt_min_qt_inter_slice
                return 1;
            if (extractUEGolombCode() >
                min(6, CtbLog2SizeY) - MinQtLog2SizeInterY)  // sps_log2_diff_max_tt_min_qt_inter_slice
                return 1;
        }
        bool sps_max_luma_transform_size_64_flag = (CtbSizeY > 32 ? m_reader.getBit() : 0);
        bool sps_transform_skip_enabled_flag = m_reader.getBit();
        if (sps_transform_skip_enabled_flag)
        {
            if (extractUEGolombCode() > 3)  // sps_log2_transform_skip_max_size_minus2
                return 1;
            m_reader.skipBit();  // sps_bdpcm_enabled_flag
        }
        if (m_reader.getBit())  // sps_mts_enabled_flag
        {
            m_reader.skipBit();  // sps_explicit_mts_intra_enabled_flag
            m_reader.skipBit();  // sps_explicit_mts_inter_enabled_flag
        }
        bool sps_lfnst_enabled_flag = m_reader.getBit();
        if (chroma_format_idc != 0)
        {
            bool sps_joint_cbcr_enabled_flag = m_reader.getBit();
            int numQpTables =
                m_reader.getBit() /* sps_same_qp_table_for_chroma_flag */ ? 1 : (sps_joint_cbcr_enabled_flag ? 3 : 2);
            for (int i = 0; i < numQpTables; i++)
            {
                int sps_qp_table_start_minus26 = extractSEGolombCode();
                if (sps_qp_table_start_minus26 < (-26 - QpBdOffset) || sps_qp_table_start_minus26 > 36)
                    return 1;
                unsigned sps_num_points_in_qp_table_minus1 = extractUEGolombCode();
                if (sps_num_points_in_qp_table_minus1 > (unsigned)(36 - sps_qp_table_start_minus26))
                    return 1;
                for (size_t j = 0; j <= sps_num_points_in_qp_table_minus1; j++)
                {
                    extractUEGolombCode();  // sps_delta_qp_in_val_minus1
                    extractUEGolombCode();  // sps_delta_qp_diff_val
                }
            }
        }
        m_reader.skipBit();  // sps_sao_enabled_flag
        if (m_reader.getBit() /* sps_alf_enabled_flag */ && chroma_format_idc != 0)
            m_reader.skipBit();  // sps_ccalf_enabled_flag
        m_reader.skipBit();      // sps_lmcs_enabled_flag
        weighted_pred_flag = m_reader.getBit();
        weighted_bipred_flag = m_reader.getBit();
        long_term_ref_pics_flag = m_reader.getBit();
        inter_layer_prediction_enabled_flag = (sps_id != 0) ? m_reader.getBit() : 0;
        m_reader.skipBit();  // sps_idr_rpl_present_flag
        bool sps_rpl1_same_as_rpl0_flag = m_reader.getBit();
        for (size_t i = 0; i < (sps_rpl1_same_as_rpl0_flag ? 1 : 2); i++)
        {
            sps_num_ref_pic_lists = extractUEGolombCode();
            if (sps_num_ref_pic_lists > 64)
                return 1;
            for (size_t j = 0; j < sps_num_ref_pic_lists; j++) ref_pic_list_struct(i, j);
        }
        m_reader.skipBit();  // sps_ref_wraparound_enabled_flag
        bool sps_sbtmvp_enabled_flag = (m_reader.getBit()) /* sps_temporal_mvp_enabled_flag */ ? m_reader.getBit() : 0;
        bool sps_amvr_enabled_flag = m_reader.getBit();
        if (m_reader.getBit())   // sps_bdof_enabled_flag
            m_reader.skipBit();  // sps_bdof_control_present_in_ph_flag
        m_reader.skipBit();      // sps_smvd_enabled_flag
        if (m_reader.getBit())   // sps_dmvr_enabled_flag
            m_reader.skipBit();  // sps_dmvr_control_present_in_ph_flag
        if (m_reader.getBit())   // sps_mmvd_enabled_flag
            m_reader.skipBit();  // sps_mmvd_fullpel_only_enabled_flag
        unsigned sps_six_minus_max_num_merge_cand = extractUEGolombCode();
        if (sps_six_minus_max_num_merge_cand > 5)
            return 1;
        unsigned MaxNumMergeCand = 6 - sps_six_minus_max_num_merge_cand;
        m_reader.skipBit();     // sps_sbt_enabled_flag
        if (m_reader.getBit())  // sps_affine_enabled_flag
        {
            unsigned sps_five_minus_max_num_subblock_merge_cand = extractUEGolombCode();
            if (sps_five_minus_max_num_subblock_merge_cand + sps_sbtmvp_enabled_flag > 5)
                return 1;
            m_reader.skipBit();  // sps_6param_affine_enabled_flag
            if (sps_amvr_enabled_flag)
                m_reader.skipBit();  // sps_affine_amvr_enabled_flag
            if (m_reader.getBit())   // sps_affine_prof_enabled_flag
                m_reader.skipBit();  // sps_prof_control_present_in_ph_flag
        }
        m_reader.skipBit();  // sps_bcw_enabled_flag
        m_reader.skipBit();  // sps_ciip_enabled_flag
        if (MaxNumMergeCand >= 2)
        {
            if (m_reader.getBit() /* sps_gpm_enabled_flag */ && MaxNumMergeCand >= 3)
            {
                unsigned sps_max_num_merge_cand_minus_max_num_gpm_cand = extractUEGolombCode();
                if (sps_max_num_merge_cand_minus_max_num_gpm_cand + 2 > MaxNumMergeCand)
                    return 1;
            }
        }
        unsigned sps_log2_parallel_merge_level_minus2 = extractUEGolombCode();
        if (sps_log2_parallel_merge_level_minus2 > CtbLog2SizeY - 2)
            return 1;

        bool sps_isp_enabled_flag = m_reader.getBit();
        bool sps_mrl_enabled_flag = m_reader.getBit();
        bool sps_mip_enabled_flag = m_reader.getBit();
        if (chroma_format_idc != 0)
            bool sps_cclm_enabled_flag = m_reader.getBit();
        if (chroma_format_idc == 1)
        {
            bool sps_chroma_horizontal_collocated_flag = m_reader.getBit();
            bool sps_chroma_vertical_collocated_flag = m_reader.getBit();
        }
        bool sps_palette_enabled_flag = m_reader.getBit();
        bool sps_act_enabled_flag =
            (chroma_format_idc == 3 && !sps_max_luma_transform_size_64_flag) ? m_reader.getBit() : 0;
        if (sps_transform_skip_enabled_flag || sps_palette_enabled_flag)
        {
            unsigned sps_min_qp_prime_ts = extractUEGolombCode();
            if (sps_min_qp_prime_ts > 8)
                return 1;
        }
        if (m_reader.getBit())  // sps_ibc_enabled_flag
        {
            unsigned sps_six_minus_max_num_ibc_merge_cand = extractUEGolombCode();
            if (sps_six_minus_max_num_ibc_merge_cand > 5)
                return 1;
        }
        if (m_reader.getBit())  // sps_ladf_enabled_flag
        {
            int sps_num_ladf_intervals_minus2 = m_reader.getBits(2);
            int sps_ladf_lowest_interval_qp_offset = extractSEGolombCode();
            for (int i = 0; i < sps_num_ladf_intervals_minus2 + 1; i++)
            {
                int sps_ladf_qp_offset = extractSEGolombCode();
                unsigned sps_ladf_delta_threshold_minus1 = extractUEGolombCode();
            }
        }
        bool sps_explicit_scaling_list_enabled_flag = m_reader.getBit();
        if (sps_lfnst_enabled_flag && sps_explicit_scaling_list_enabled_flag)
            bool sps_scaling_matrix_for_lfnst_disabled_flag = m_reader.getBit();
        bool sps_scaling_matrix_for_alternative_colour_space_disabled_flag =
            (sps_act_enabled_flag && sps_explicit_scaling_list_enabled_flag) ? m_reader.getBit() : 0;
        if (sps_scaling_matrix_for_alternative_colour_space_disabled_flag)
            bool sps_scaling_matrix_designated_colour_space_flag = m_reader.getBit();
        bool sps_dep_quant_enabled_flag = m_reader.getBit();
        bool sps_sign_data_hiding_enabled_flag = m_reader.getBit();
        if (m_reader.getBit())  // sps_virtual_boundaries_enabled_flag
        {
            if (m_reader.getBit())  // sps_virtual_boundaries_present_flag
            {
                unsigned sps_num_ver_virtual_boundaries = extractUEGolombCode();
                if (sps_num_ver_virtual_boundaries > (pic_width_max_in_luma_samples <= 8 ? 0 : 3))
                    return 1;
                for (size_t i = 0; i < sps_num_ver_virtual_boundaries; i++)
                {
                    unsigned sps_virtual_boundary_pos_x_minus1 = extractUEGolombCode();
                    if (sps_virtual_boundary_pos_x_minus1 > ceil(pic_width_max_in_luma_samples / 8) - 2)
                        return 1;
                }
                unsigned sps_num_hor_virtual_boundaries = extractUEGolombCode();
                if (sps_num_hor_virtual_boundaries > (pic_height_max_in_luma_samples <= 8 ? 0 : 3))
                    return 1;
                for (size_t i = 0; i < sps_num_hor_virtual_boundaries; i++)
                {
                    unsigned sps_virtual_boundary_pos_y_minus1 = extractUEGolombCode();
                    if (sps_virtual_boundary_pos_y_minus1 > ceil(pic_height_max_in_luma_samples / 8) - 2)
                        return 1;
                }
            }
        }
        if (sps_ptl_dpb_hrd_params_present_flag)
        {
            if (m_reader.getBit())  // sps_timing_hrd_params_present_flag
            {
                if (m_sps_hrd.general_timing_hrd_parameters())
                    return 1;
                int sps_sublayer_cpb_params_present_flag = (max_sublayers_minus1 > 0) ? m_reader.getBit() : 0;
                int firstSubLayer = sps_sublayer_cpb_params_present_flag ? 0 : max_sublayers_minus1;
                m_sps_hrd.ols_timing_hrd_parameters(firstSubLayer, max_sublayers_minus1);
            }
        }
        bool sps_field_seq_flag = m_reader.getBit();
        if (m_reader.getBit())  // sps_vui_parameters_present_flag
        {
            unsigned sps_vui_payload_size_minus1 = extractUEGolombCode();
            if (sps_vui_payload_size_minus1 > 1023)
                return 1;
            m_reader.skipBits(m_reader.getBitsLeft() % 8);  // sps_vui_alignment_zero_bit
            vui_parameters();
        }
        bool sps_extension_flag = m_reader.getBit();
        return 0;
    }
    catch (VodCoreException& e)
    {
        return NOT_ENOUGH_BUFFER;
    }
}