static void execute_async(DWORD WINAPI (*func)(LPVOID), LPVOID opaque,

                          Error **errp)

{

    Error *local_err = NULL;

    if (error_is_set(errp)) {

        return;

    }

    HANDLE thread = CreateThread(NULL, 0, func, opaque, 0, NULL);

    if (!thread) {

        error_set(&local_err, QERR_QGA_COMMAND_FAILED,

                  "failed to dispatch asynchronous command");

        error_propagate(errp, local_err);

    }

}


static void spr_read_tbu(DisasContext *ctx, int gprn, int sprn)

{

    if (ctx->tb->cflags & CF_USE_ICOUNT) {

        gen_io_start();

    }

    gen_helper_load_tbu(cpu_gpr[gprn], cpu_env);

    if (ctx->tb->cflags & CF_USE_ICOUNT) {

        gen_io_end();

        gen_stop_exception(ctx);

    }

}


static void vector_fmul_window_mips(float *dst, const float *src0,

        const float *src1, const float *win, int len)

{

    int i, j;

    /*

     * variables used in inline assembler

     */

    float * dst_i, * dst_j, * dst_i2, * dst_j2;

    float temp, temp1, temp2, temp3, temp4, temp5, temp6, temp7;

    dst  += len;

    win  += len;

    src0 += len;

    for (i = -len, j = len - 1; i < 0; i += 8, j -= 8) {

        dst_i = dst + i;

        dst_j = dst + j;

        dst_i2 = dst + i + 4;

        dst_j2 = dst + j - 4;

        __asm__ volatile (

            "mul.s   %[temp],   %[s1],       %[wi]            \n\t"

            "mul.s   %[temp1],  %[s1],       %[wj]            \n\t"

            "mul.s   %[temp2],  %[s11],      %[wi1]           \n\t"

            "mul.s   %[temp3],  %[s11],      %[wj1]           \n\t"

            "msub.s  %[temp],   %[temp],     %[s0],  %[wj]    \n\t"

            "madd.s  %[temp1],  %[temp1],    %[s0],  %[wi]    \n\t"

            "msub.s  %[temp2],  %[temp2],    %[s01], %[wj1]   \n\t"

            "madd.s  %[temp3],  %[temp3],    %[s01], %[wi1]   \n\t"

            "swc1    %[temp],   0(%[dst_i])                   \n\t" /* dst[i] = s0*wj - s1*wi; */

            "swc1    %[temp1],  0(%[dst_j])                   \n\t" /* dst[j] = s0*wi + s1*wj; */

            "swc1    %[temp2],  4(%[dst_i])                   \n\t" /* dst[i+1] = s01*wj1 - s11*wi1; */

            "swc1    %[temp3], -4(%[dst_j])                   \n\t" /* dst[j-1] = s01*wi1 + s11*wj1; */

            "mul.s   %[temp4],  %[s12],      %[wi2]           \n\t"

            "mul.s   %[temp5],  %[s12],      %[wj2]           \n\t"

            "mul.s   %[temp6],  %[s13],      %[wi3]           \n\t"

            "mul.s   %[temp7],  %[s13],      %[wj3]           \n\t"

            "msub.s  %[temp4],  %[temp4],    %[s02], %[wj2]   \n\t"

            "madd.s  %[temp5],  %[temp5],    %[s02], %[wi2]   \n\t"

            "msub.s  %[temp6],  %[temp6],    %[s03], %[wj3]   \n\t"

            "madd.s  %[temp7],  %[temp7],    %[s03], %[wi3]   \n\t"

            "swc1    %[temp4],  8(%[dst_i])                   \n\t" /* dst[i+2] = s02*wj2 - s12*wi2; */

            "swc1    %[temp5], -8(%[dst_j])                   \n\t" /* dst[j-2] = s02*wi2 + s12*wj2; */

            "swc1    %[temp6],  12(%[dst_i])                  \n\t" /* dst[i+2] = s03*wj3 - s13*wi3; */

            "swc1    %[temp7], -12(%[dst_j])                  \n\t" /* dst[j-3] = s03*wi3 + s13*wj3; */

            : [temp]"=&f"(temp),  [temp1]"=&f"(temp1), [temp2]"=&f"(temp2),

              [temp3]"=&f"(temp3), [temp4]"=&f"(temp4), [temp5]"=&f"(temp5),

              [temp6]"=&f"(temp6), [temp7]"=&f"(temp7)

            : [dst_j]"r"(dst_j),     [dst_i]"r" (dst_i),

              [s0] "f"(src0[i]),     [wj] "f"(win[j]),     [s1] "f"(src1[j]),

              [wi] "f"(win[i]),      [s01]"f"(src0[i + 1]),[wj1]"f"(win[j - 1]),

              [s11]"f"(src1[j - 1]), [wi1]"f"(win[i + 1]), [s02]"f"(src0[i + 2]),

              [wj2]"f"(win[j - 2]),  [s12]"f"(src1[j - 2]),[wi2]"f"(win[i + 2]),

              [s03]"f"(src0[i + 3]), [wj3]"f"(win[j - 3]), [s13]"f"(src1[j - 3]),

              [wi3]"f"(win[i + 3])

            : "memory"

        );

        __asm__ volatile (

            "mul.s  %[temp],   %[s1],       %[wi]            \n\t"

            "mul.s  %[temp1],  %[s1],       %[wj]            \n\t"

            "mul.s  %[temp2],  %[s11],      %[wi1]           \n\t"

            "mul.s  %[temp3],  %[s11],      %[wj1]           \n\t"

            "msub.s %[temp],   %[temp],     %[s0],  %[wj]    \n\t"

            "madd.s %[temp1],  %[temp1],    %[s0],  %[wi]    \n\t"

            "msub.s %[temp2],  %[temp2],    %[s01], %[wj1]   \n\t"

            "madd.s %[temp3],  %[temp3],    %[s01], %[wi1]   \n\t"

            "swc1   %[temp],   0(%[dst_i2])                  \n\t" /* dst[i] = s0*wj - s1*wi; */

            "swc1   %[temp1],  0(%[dst_j2])                  \n\t" /* dst[j] = s0*wi + s1*wj; */

            "swc1   %[temp2],  4(%[dst_i2])                  \n\t" /* dst[i+1] = s01*wj1 - s11*wi1; */

            "swc1   %[temp3], -4(%[dst_j2])                  \n\t" /* dst[j-1] = s01*wi1 + s11*wj1; */

            "mul.s  %[temp4],  %[s12],      %[wi2]           \n\t"

            "mul.s  %[temp5],  %[s12],      %[wj2]           \n\t"

            "mul.s  %[temp6],  %[s13],      %[wi3]           \n\t"

            "mul.s  %[temp7],  %[s13],      %[wj3]           \n\t"

            "msub.s %[temp4],  %[temp4],    %[s02], %[wj2]   \n\t"

            "madd.s %[temp5],  %[temp5],    %[s02], %[wi2]   \n\t"

            "msub.s %[temp6],  %[temp6],    %[s03], %[wj3]   \n\t"

            "madd.s %[temp7],  %[temp7],    %[s03], %[wi3]   \n\t"

            "swc1   %[temp4],  8(%[dst_i2])                  \n\t" /* dst[i+2] = s02*wj2 - s12*wi2; */

            "swc1   %[temp5], -8(%[dst_j2])                  \n\t" /* dst[j-2] = s02*wi2 + s12*wj2; */

            "swc1   %[temp6],  12(%[dst_i2])                 \n\t" /* dst[i+2] = s03*wj3 - s13*wi3; */

            "swc1   %[temp7], -12(%[dst_j2])                 \n\t" /* dst[j-3] = s03*wi3 + s13*wj3; */

            : [temp]"=&f"(temp),

              [temp1]"=&f"(temp1), [temp2]"=&f"(temp2), [temp3]"=&f"(temp3),

              [temp4]"=&f"(temp4), [temp5]"=&f"(temp5), [temp6]"=&f"(temp6),

              [temp7]  "=&f" (temp7)

            : [dst_j2]"r"(dst_j2),   [dst_i2]"r"(dst_i2),

              [s0] "f"(src0[i + 4]), [wj] "f"(win[j - 4]), [s1] "f"(src1[j - 4]),

              [wi] "f"(win[i + 4]),  [s01]"f"(src0[i + 5]),[wj1]"f"(win[j - 5]),

              [s11]"f"(src1[j - 5]), [wi1]"f"(win[i + 5]), [s02]"f"(src0[i + 6]),

              [wj2]"f"(win[j - 6]),  [s12]"f"(src1[j - 6]),[wi2]"f"(win[i + 6]),

              [s03]"f"(src0[i + 7]), [wj3]"f"(win[j - 7]), [s13]"f"(src1[j - 7]),

              [wi3]"f"(win[i + 7])

            : "memory"

        );

    }

}


static CodeBook unpack_codebook(GetBitContext* gb, unsigned depth,

                                 unsigned size)

{

    unsigned i, j;

    CodeBook cb = { 0 };

    if (!can_safely_read(gb, size * 34))

        return cb;

    if (size >= INT_MAX / sizeof(MacroBlock))

        return cb;

    cb.blocks = av_malloc(size ? size * sizeof(MacroBlock) : 1);

    if (!cb.blocks)

        return cb;

    cb.depth = depth;

    cb.size = size;

    for (i = 0; i < size; i++) {

        unsigned mask_bits = get_bits(gb, 4);

        unsigned color0 = get_bits(gb, 15);

        unsigned color1 = get_bits(gb, 15);

        for (j = 0; j < 4; j++) {

            if (mask_bits & (1 << j))

                cb.blocks[i].pixels[j] = color1;

            else

                cb.blocks[i].pixels[j] = color0;

        }

    }

    return cb;

}


static inline void RENAME(hScale)(int16_t *dst, int dstW, const uint8_t *src, int srcW, int xInc,

                                  const int16_t *filter, const int16_t *filterPos, int filterSize)

{

#if COMPILE_TEMPLATE_MMX

    assert(filterSize % 4 == 0 && filterSize>0);

    if (filterSize==4) { // Always true for upscaling, sometimes for down, too.

        x86_reg counter= -2*dstW;

        filter-= counter*2;

        filterPos-= counter/2;

        dst-= counter/2;

        __asm__ volatile(

#if defined(PIC)

            "push            %%"REG_b"              \n\t"

#endif

            "pxor                %%mm7, %%mm7       \n\t"

            "push           %%"REG_BP"              \n\t" // we use 7 regs here ...

            "mov             %%"REG_a", %%"REG_BP"  \n\t"

            ASMALIGN(4)

            "1:                                     \n\t"

            "movzwl   (%2, %%"REG_BP"), %%eax       \n\t"

            "movzwl  2(%2, %%"REG_BP"), %%ebx       \n\t"

            "movq  (%1, %%"REG_BP", 4), %%mm1       \n\t"

            "movq 8(%1, %%"REG_BP", 4), %%mm3       \n\t"

            "movd      (%3, %%"REG_a"), %%mm0       \n\t"

            "movd      (%3, %%"REG_b"), %%mm2       \n\t"

            "punpcklbw           %%mm7, %%mm0       \n\t"

            "punpcklbw           %%mm7, %%mm2       \n\t"

            "pmaddwd             %%mm1, %%mm0       \n\t"

            "pmaddwd             %%mm2, %%mm3       \n\t"

            "movq                %%mm0, %%mm4       \n\t"

            "punpckldq           %%mm3, %%mm0       \n\t"

            "punpckhdq           %%mm3, %%mm4       \n\t"

            "paddd               %%mm4, %%mm0       \n\t"

            "psrad                  $7, %%mm0       \n\t"

            "packssdw            %%mm0, %%mm0       \n\t"

            "movd                %%mm0, (%4, %%"REG_BP")    \n\t"

            "add                    $4, %%"REG_BP"  \n\t"

            " jnc                   1b              \n\t"

            "pop            %%"REG_BP"              \n\t"

#if defined(PIC)

            "pop             %%"REG_b"              \n\t"

#endif

            : "+a" (counter)

            : "c" (filter), "d" (filterPos), "S" (src), "D" (dst)

#if !defined(PIC)

            : "%"REG_b

#endif

        );

    } else if (filterSize==8) {

        x86_reg counter= -2*dstW;

        filter-= counter*4;

        filterPos-= counter/2;

        dst-= counter/2;

        __asm__ volatile(

#if defined(PIC)

            "push             %%"REG_b"             \n\t"

#endif

            "pxor                 %%mm7, %%mm7      \n\t"

            "push            %%"REG_BP"             \n\t" // we use 7 regs here ...

            "mov              %%"REG_a", %%"REG_BP" \n\t"

            ASMALIGN(4)

            "1:                                     \n\t"

            "movzwl    (%2, %%"REG_BP"), %%eax      \n\t"

            "movzwl   2(%2, %%"REG_BP"), %%ebx      \n\t"

            "movq   (%1, %%"REG_BP", 8), %%mm1      \n\t"

            "movq 16(%1, %%"REG_BP", 8), %%mm3      \n\t"

            "movd       (%3, %%"REG_a"), %%mm0      \n\t"

            "movd       (%3, %%"REG_b"), %%mm2      \n\t"

            "punpcklbw            %%mm7, %%mm0      \n\t"

            "punpcklbw            %%mm7, %%mm2      \n\t"

            "pmaddwd              %%mm1, %%mm0      \n\t"

            "pmaddwd              %%mm2, %%mm3      \n\t"

            "movq  8(%1, %%"REG_BP", 8), %%mm1      \n\t"

            "movq 24(%1, %%"REG_BP", 8), %%mm5      \n\t"

            "movd      4(%3, %%"REG_a"), %%mm4      \n\t"

            "movd      4(%3, %%"REG_b"), %%mm2      \n\t"

            "punpcklbw            %%mm7, %%mm4      \n\t"

            "punpcklbw            %%mm7, %%mm2      \n\t"

            "pmaddwd              %%mm1, %%mm4      \n\t"

            "pmaddwd              %%mm2, %%mm5      \n\t"

            "paddd                %%mm4, %%mm0      \n\t"

            "paddd                %%mm5, %%mm3      \n\t"

            "movq                 %%mm0, %%mm4      \n\t"

            "punpckldq            %%mm3, %%mm0      \n\t"

            "punpckhdq            %%mm3, %%mm4      \n\t"

            "paddd                %%mm4, %%mm0      \n\t"

            "psrad                   $7, %%mm0      \n\t"

            "packssdw             %%mm0, %%mm0      \n\t"

            "movd                 %%mm0, (%4, %%"REG_BP")   \n\t"

            "add                     $4, %%"REG_BP" \n\t"

            " jnc                    1b             \n\t"

            "pop             %%"REG_BP"             \n\t"

#if defined(PIC)

            "pop              %%"REG_b"             \n\t"

#endif

            : "+a" (counter)

            : "c" (filter), "d" (filterPos), "S" (src), "D" (dst)

#if !defined(PIC)

            : "%"REG_b

#endif

        );

    } else {

        const uint8_t *offset = src+filterSize;

        x86_reg counter= -2*dstW;

        //filter-= counter*filterSize/2;

        filterPos-= counter/2;

        dst-= counter/2;

        __asm__ volatile(

            "pxor                  %%mm7, %%mm7     \n\t"

            ASMALIGN(4)

            "1:                                     \n\t"

            "mov                      %2, %%"REG_c" \n\t"

            "movzwl      (%%"REG_c", %0), %%eax     \n\t"

            "movzwl     2(%%"REG_c", %0), %%edx     \n\t"

            "mov                      %5, %%"REG_c" \n\t"

            "pxor                  %%mm4, %%mm4     \n\t"

            "pxor                  %%mm5, %%mm5     \n\t"

            "2:                                     \n\t"

            "movq                   (%1), %%mm1     \n\t"

            "movq               (%1, %6), %%mm3     \n\t"

            "movd (%%"REG_c", %%"REG_a"), %%mm0     \n\t"

            "movd (%%"REG_c", %%"REG_d"), %%mm2     \n\t"

            "punpcklbw             %%mm7, %%mm0     \n\t"

            "punpcklbw             %%mm7, %%mm2     \n\t"

            "pmaddwd               %%mm1, %%mm0     \n\t"

            "pmaddwd               %%mm2, %%mm3     \n\t"

            "paddd                 %%mm3, %%mm5     \n\t"

            "paddd                 %%mm0, %%mm4     \n\t"

            "add                      $8, %1        \n\t"

            "add                      $4, %%"REG_c" \n\t"

            "cmp                      %4, %%"REG_c" \n\t"

            " jb                      2b            \n\t"

            "add                      %6, %1        \n\t"

            "movq                  %%mm4, %%mm0     \n\t"

            "punpckldq             %%mm5, %%mm4     \n\t"

            "punpckhdq             %%mm5, %%mm0     \n\t"

            "paddd                 %%mm0, %%mm4     \n\t"

            "psrad                    $7, %%mm4     \n\t"

            "packssdw              %%mm4, %%mm4     \n\t"

            "mov                      %3, %%"REG_a" \n\t"

            "movd                  %%mm4, (%%"REG_a", %0)   \n\t"

            "add                      $4, %0        \n\t"

            " jnc                     1b            \n\t"

            : "+r" (counter), "+r" (filter)

            : "m" (filterPos), "m" (dst), "m"(offset),

            "m" (src), "r" ((x86_reg)filterSize*2)

            : "%"REG_a, "%"REG_c, "%"REG_d

        );

    }

#else

#if COMPILE_TEMPLATE_ALTIVEC

    hScale_altivec_real(dst, dstW, src, srcW, xInc, filter, filterPos, filterSize);

#else

    int i;

    for (i=0; i<dstW; i++) {

        int j;

        int srcPos= filterPos[i];

        int val=0;

        //printf("filterPos: %d\n", filterPos[i]);

        for (j=0; j<filterSize; j++) {

            //printf("filter: %d, src: %d\n", filter[i], src[srcPos + j]);

            val += ((int)src[srcPos + j])*filter[filterSize*i + j];

        }

        //filter += hFilterSize;

        dst[i] = FFMIN(val>>7, (1<<15)-1); // the cubic equation does overflow ...

        //dst[i] = val>>7;

    }

#endif /* COMPILE_TEMPLATE_ALTIVEC */

#endif /* COMPILE_MMX */

}


YUV2PACKED16WRAPPER(yuv2, rgb48, rgb48be, PIX_FMT_RGB48BE)

YUV2PACKED16WRAPPER(yuv2, rgb48, rgb48le, PIX_FMT_RGB48LE)

YUV2PACKED16WRAPPER(yuv2, rgb48, bgr48be, PIX_FMT_BGR48BE)

YUV2PACKED16WRAPPER(yuv2, rgb48, bgr48le, PIX_FMT_BGR48LE)

static av_always_inline void

yuv2rgb_write(uint8_t *_dest, int i, int Y1, int Y2,

              int U, int V, int A1, int A2,

              const void *_r, const void *_g, const void *_b, int y,

              enum PixelFormat target, int hasAlpha)

{

    if (target == PIX_FMT_ARGB || target == PIX_FMT_RGBA ||

        target == PIX_FMT_ABGR || target == PIX_FMT_BGRA) {

        uint32_t *dest = (uint32_t *) _dest;

        const uint32_t *r = (const uint32_t *) _r;

        const uint32_t *g = (const uint32_t *) _g;

        const uint32_t *b = (const uint32_t *) _b;

#if CONFIG_SMALL

        int sh = hasAlpha ? ((target == PIX_FMT_RGB32_1 || target == PIX_FMT_BGR32_1) ? 0 : 24) : 0;

        dest[i * 2 + 0] = r[Y1] + g[Y1] + b[Y1] + (hasAlpha ? A1 << sh : 0);

        dest[i * 2 + 1] = r[Y2] + g[Y2] + b[Y2] + (hasAlpha ? A2 << sh : 0);

#else

        if (hasAlpha) {

            int sh = (target == PIX_FMT_RGB32_1 || target == PIX_FMT_BGR32_1) ? 0 : 24;

            dest[i * 2 + 0] = r[Y1] + g[Y1] + b[Y1] + (A1 << sh);

            dest[i * 2 + 1] = r[Y2] + g[Y2] + b[Y2] + (A2 << sh);

        } else {

            dest[i * 2 + 0] = r[Y1] + g[Y1] + b[Y1];

            dest[i * 2 + 1] = r[Y2] + g[Y2] + b[Y2];

        }

#endif

    } else if (target == PIX_FMT_RGB24 || target == PIX_FMT_BGR24) {

        uint8_t *dest = (uint8_t *) _dest;

        const uint8_t *r = (const uint8_t *) _r;

        const uint8_t *g = (const uint8_t *) _g;

        const uint8_t *b = (const uint8_t *) _b;

#define r_b ((target == PIX_FMT_RGB24) ? r : b)

#define b_r ((target == PIX_FMT_RGB24) ? b : r)

        dest[i * 6 + 0] = r_b[Y1];

        dest[i * 6 + 1] =   g[Y1];

        dest[i * 6 + 2] = b_r[Y1];

        dest[i * 6 + 3] = r_b[Y2];

        dest[i * 6 + 4] =   g[Y2];

        dest[i * 6 + 5] = b_r[Y2];

#undef r_b

#undef b_r

    } else if (target == PIX_FMT_RGB565 || target == PIX_FMT_BGR565 ||

               target == PIX_FMT_RGB555 || target == PIX_FMT_BGR555 ||

               target == PIX_FMT_RGB444 || target == PIX_FMT_BGR444) {

        uint16_t *dest = (uint16_t *) _dest;

        const uint16_t *r = (const uint16_t *) _r;

        const uint16_t *g = (const uint16_t *) _g;

        const uint16_t *b = (const uint16_t *) _b;

        int dr1, dg1, db1, dr2, dg2, db2;

        if (target == PIX_FMT_RGB565 || target == PIX_FMT_BGR565) {

            dr1 = dither_2x2_8[ y & 1     ][0];

            dg1 = dither_2x2_4[ y & 1     ][0];

            db1 = dither_2x2_8[(y & 1) ^ 1][0];

            dr2 = dither_2x2_8[ y & 1     ][1];

            dg2 = dither_2x2_4[ y & 1     ][1];

            db2 = dither_2x2_8[(y & 1) ^ 1][1];

        } else if (target == PIX_FMT_RGB555 || target == PIX_FMT_BGR555) {

            dr1 = dither_2x2_8[ y & 1     ][0];

            dg1 = dither_2x2_8[ y & 1     ][1];

            db1 = dither_2x2_8[(y & 1) ^ 1][0];

            dr2 = dither_2x2_8[ y & 1     ][1];

            dg2 = dither_2x2_8[ y & 1     ][0];

            db2 = dither_2x2_8[(y & 1) ^ 1][1];

        } else {

            dr1 = dither_4x4_16[ y & 3     ][0];

            dg1 = dither_4x4_16[ y & 3     ][1];

            db1 = dither_4x4_16[(y & 3) ^ 3][0];

            dr2 = dither_4x4_16[ y & 3     ][1];

            dg2 = dither_4x4_16[ y & 3     ][0];

            db2 = dither_4x4_16[(y & 3) ^ 3][1];

        }

        dest[i * 2 + 0] = r[Y1 + dr1] + g[Y1 + dg1] + b[Y1 + db1];

        dest[i * 2 + 1] = r[Y2 + dr2] + g[Y2 + dg2] + b[Y2 + db2];

    } else /* 8/4-bit */ {

        uint8_t *dest = (uint8_t *) _dest;

        const uint8_t *r = (const uint8_t *) _r;

        const uint8_t *g = (const uint8_t *) _g;

        const uint8_t *b = (const uint8_t *) _b;

        int dr1, dg1, db1, dr2, dg2, db2;

        if (target == PIX_FMT_RGB8 || target == PIX_FMT_BGR8) {

            const uint8_t * const d64 = dither_8x8_73[y & 7];

            const uint8_t * const d32 = dither_8x8_32[y & 7];

            dr1 = dg1 = d32[(i * 2 + 0) & 7];

            db1 =       d64[(i * 2 + 0) & 7];

            dr2 = dg2 = d32[(i * 2 + 1) & 7];

            db2 =       d64[(i * 2 + 1) & 7];

        } else {

            const uint8_t * const d64  = dither_8x8_73 [y & 7];

            const uint8_t * const d128 = dither_8x8_220[y & 7];

            dr1 = db1 = d128[(i * 2 + 0) & 7];

            dg1 =        d64[(i * 2 + 0) & 7];

            dr2 = db2 = d128[(i * 2 + 1) & 7];

            dg2 =        d64[(i * 2 + 1) & 7];

        }

        if (target == PIX_FMT_RGB4 || target == PIX_FMT_BGR4) {

            dest[i] = r[Y1 + dr1] + g[Y1 + dg1] + b[Y1 + db1] +

                    ((r[Y2 + dr2] + g[Y2 + dg2] + b[Y2 + db2]) << 4);

        } else {

            dest[i * 2 + 0] = r[Y1 + dr1] + g[Y1 + dg1] + b[Y1 + db1];

            dest[i * 2 + 1] = r[Y2 + dr2] + g[Y2 + dg2] + b[Y2 + db2];

        }

    }

}


static void musb_rx_packet_complete(USBPacket *packey, void *opaque)

{

    /* Unfortunately we can't use packey->devep because that's the remote

     * endpoint number and may be different than our local.  */

    MUSBEndPoint *ep = (MUSBEndPoint *) opaque;

    int epnum = ep->epnum;

    MUSBState *s = ep->musb;

    ep->fifostart[1] = 0;

    ep->fifolen[1] = 0;

#ifdef CLEAR_NAK

    if (ep->status[1] != USB_RET_NAK) {

#endif

        ep->csr[1] &= ~MGC_M_RXCSR_H_REQPKT;

        if (!epnum)

            ep->csr[0] &= ~MGC_M_CSR0_H_REQPKT;

#ifdef CLEAR_NAK

    }

#endif

    /* Clear all of the imaginable error bits first */

    ep->csr[1] &= ~(MGC_M_RXCSR_H_ERROR | MGC_M_RXCSR_H_RXSTALL |

                    MGC_M_RXCSR_DATAERROR);

    if (!epnum)

        ep->csr[0] &= ~(MGC_M_CSR0_H_ERROR | MGC_M_CSR0_H_RXSTALL |

                        MGC_M_CSR0_H_NAKTIMEOUT | MGC_M_CSR0_H_NO_PING);

    if (ep->status[1] == USB_RET_STALL) {

        ep->status[1] = 0;

        packey->len = 0;

        ep->csr[1] |= MGC_M_RXCSR_H_RXSTALL;

        if (!epnum)

            ep->csr[0] |= MGC_M_CSR0_H_RXSTALL;

    }

    if (ep->status[1] == USB_RET_NAK) {

        ep->status[1] = 0;

        /* NAK timeouts are only generated in Bulk transfers and

         * Data-errors in Isochronous.  */

        if (ep->interrupt[1])

            return musb_packet(s, ep, epnum, USB_TOKEN_IN,

                            packey->len, musb_rx_packet_complete, 1);

        ep->csr[1] |= MGC_M_RXCSR_DATAERROR;

        if (!epnum)

            ep->csr[0] |= MGC_M_CSR0_H_NAKTIMEOUT;

    }

    if (ep->status[1] < 0) {

        if (ep->status[1] == USB_RET_BABBLE) {

            musb_intr_set(s, musb_irq_rst_babble, 1);

            return;

        }

        /* Pretend we've tried three times already and failed (in

         * case of a control transfer).  */

        ep->csr[1] |= MGC_M_RXCSR_H_ERROR;

        if (!epnum)

            ep->csr[0] |= MGC_M_CSR0_H_ERROR;

        musb_rx_intr_set(s, epnum, 1);

        return;

    }

    /* TODO: check len for over/underruns of an OUT packet?  */

    /* TODO: perhaps make use of e->ext_size[1] here.  */

    packey->len = ep->status[1];

    if (!(ep->csr[1] & (MGC_M_RXCSR_H_RXSTALL | MGC_M_RXCSR_DATAERROR))) {

        ep->csr[1] |= MGC_M_RXCSR_FIFOFULL | MGC_M_RXCSR_RXPKTRDY;

        if (!epnum)

            ep->csr[0] |= MGC_M_CSR0_RXPKTRDY;

        ep->rxcount = packey->len; /* XXX: MIN(packey->len, ep->maxp[1]); */

        /* In DMA mode: assert DMA request for this EP */

    }

    /* Only if DMA has not been asserted */

    musb_rx_intr_set(s, epnum, 1);

}


static int process_requests(int sock)

{

    int flags;

    int size = 0;

    int retval = 0;

    uint64_t offset;

    ProxyHeader header;

    int mode, uid, gid;

    V9fsString name, value;

    struct timespec spec[2];

    V9fsString oldpath, path;

    struct iovec in_iovec, out_iovec;

    in_iovec.iov_base  = g_malloc(PROXY_MAX_IO_SZ + PROXY_HDR_SZ);

    in_iovec.iov_len   = PROXY_MAX_IO_SZ + PROXY_HDR_SZ;

    out_iovec.iov_base = g_malloc(PROXY_MAX_IO_SZ + PROXY_HDR_SZ);

    out_iovec.iov_len  = PROXY_MAX_IO_SZ + PROXY_HDR_SZ;

    while (1) {

        /*

         * initialize the header type, so that we send

         * response to proper request type.

         */

        header.type = 0;

        retval = read_request(sock, &in_iovec, &header);

        if (retval < 0) {

            goto err_out;

        }

        switch (header.type) {

        case T_OPEN:

            retval = do_open(&in_iovec);

            break;

        case T_CREATE:

            retval = do_create(&in_iovec);

            break;

        case T_MKNOD:

        case T_MKDIR:

        case T_SYMLINK:

            retval = do_create_others(header.type, &in_iovec);

            break;

        case T_LINK:

            v9fs_string_init(&path);

            v9fs_string_init(&oldpath);

            retval = proxy_unmarshal(&in_iovec, PROXY_HDR_SZ,

                                     "ss", &oldpath, &path);

            if (retval > 0) {

                retval = link(oldpath.data, path.data);

                if (retval < 0) {

                    retval = -errno;

                }

            }

            v9fs_string_free(&oldpath);

            v9fs_string_free(&path);

            break;

        case T_LSTAT:

        case T_STATFS:

            retval = do_stat(header.type, &in_iovec, &out_iovec);

            break;

        case T_READLINK:

            retval = do_readlink(&in_iovec, &out_iovec);

            break;

        case T_CHMOD:

            v9fs_string_init(&path);

            retval = proxy_unmarshal(&in_iovec, PROXY_HDR_SZ,

                                     "sd", &path, &mode);

            if (retval > 0) {

                retval = chmod(path.data, mode);

                if (retval < 0) {

                    retval = -errno;

                }

            }

            v9fs_string_free(&path);

            break;

        case T_CHOWN:

            v9fs_string_init(&path);

            retval = proxy_unmarshal(&in_iovec, PROXY_HDR_SZ, "sdd", &path,

                                     &uid, &gid);

            if (retval > 0) {

                retval = lchown(path.data, uid, gid);

                if (retval < 0) {

                    retval = -errno;

                }

            }

            v9fs_string_free(&path);

            break;

        case T_TRUNCATE:

            v9fs_string_init(&path);

            retval = proxy_unmarshal(&in_iovec, PROXY_HDR_SZ, "sq",

                                     &path, &offset);

            if (retval > 0) {

                retval = truncate(path.data, offset);

                if (retval < 0) {

                    retval = -errno;

                }

            }

            v9fs_string_free(&path);

            break;

        case T_UTIME:

            v9fs_string_init(&path);

            retval = proxy_unmarshal(&in_iovec, PROXY_HDR_SZ, "sqqqq", &path,

                                     &spec[0].tv_sec, &spec[0].tv_nsec,

                                     &spec[1].tv_sec, &spec[1].tv_nsec);

            if (retval > 0) {

                retval = qemu_utimens(path.data, spec);

                if (retval < 0) {

                    retval = -errno;

                }

            }

            v9fs_string_free(&path);

            break;

        case T_RENAME:

            v9fs_string_init(&path);

            v9fs_string_init(&oldpath);

            retval = proxy_unmarshal(&in_iovec, PROXY_HDR_SZ,

                                     "ss", &oldpath, &path);

            if (retval > 0) {

                retval = rename(oldpath.data, path.data);

                if (retval < 0) {

                    retval = -errno;

                }

            }

            v9fs_string_free(&oldpath);

            v9fs_string_free(&path);

            break;

        case T_REMOVE:

            v9fs_string_init(&path);

            retval = proxy_unmarshal(&in_iovec, PROXY_HDR_SZ, "s", &path);

            if (retval > 0) {

                retval = remove(path.data);

                if (retval < 0) {

                    retval = -errno;

                }

            }

            v9fs_string_free(&path);

            break;

        case T_LGETXATTR:

        case T_LLISTXATTR:

            retval = do_getxattr(header.type, &in_iovec, &out_iovec);

            break;

        case T_LSETXATTR:

            v9fs_string_init(&path);

            v9fs_string_init(&name);

            v9fs_string_init(&value);

            retval = proxy_unmarshal(&in_iovec, PROXY_HDR_SZ, "sssdd", &path,

                                     &name, &value, &size, &flags);

            if (retval > 0) {

                retval = lsetxattr(path.data,

                                   name.data, value.data, size, flags);

                if (retval < 0) {

                    retval = -errno;

                }

            }

            v9fs_string_free(&path);

            v9fs_string_free(&name);

            v9fs_string_free(&value);

            break;

        case T_LREMOVEXATTR:

            v9fs_string_init(&path);

            v9fs_string_init(&name);

            retval = proxy_unmarshal(&in_iovec,

                                     PROXY_HDR_SZ, "ss", &path, &name);

            if (retval > 0) {

                retval = lremovexattr(path.data, name.data);

                if (retval < 0) {

                    retval = -errno;

                }

            }

            v9fs_string_free(&path);

            v9fs_string_free(&name);

            break;

        case T_GETVERSION:

            retval = do_getversion(&in_iovec, &out_iovec);

            break;

        default:

            goto err_out;

            break;

        }

        if (process_reply(sock, header.type, &out_iovec, retval) < 0) {

            goto err_out;

        }

    }

err_out:

    g_free(in_iovec.iov_base);

    g_free(out_iovec.iov_base);

    return -1;

}


static av_cold int pcx_init(AVCodecContext *avctx) {

    PCXContext *s = avctx->priv_data;

    avcodec_get_frame_defaults(&s->picture);

    avctx->coded_frame= &s->picture;

    return 0;

}


static void find_compressor(char * compressor_name, int len, MOVTrack *track)

{

    AVDictionaryEntry *encoder;

    int xdcam_res =  (track->par->width == 1280 && track->par->height == 720)

                  || (track->par->width == 1440 && track->par->height == 1080)

                  || (track->par->width == 1920 && track->par->height == 1080);

    if (track->mode == MODE_MOV &&

        (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {

        av_strlcpy(compressor_name, encoder->value, 32);

    } else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {

        int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;

        AVStream *st = track->st;

        int rate = av_q2d(find_fps(NULL, st));

        av_strlcatf(compressor_name, len, "XDCAM");

        if (track->par->format == AV_PIX_FMT_YUV422P) {

            av_strlcatf(compressor_name, len, " HD422");

        } else if(track->par->width == 1440) {

            av_strlcatf(compressor_name, len, " HD");

        } else

            av_strlcatf(compressor_name, len, " EX");

        av_strlcatf(compressor_name, len, " %d%c", track->par->height, interlaced ? 'i' : 'p');

        av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));

    }

}


const char *print_wrid(int wrid)

{

    if (wrid >= RDMA_WRID_RECV_CONTROL) {

        return wrid_desc[RDMA_WRID_RECV_CONTROL];

    }

    return wrid_desc[wrid];

}


void ff_set_mpeg4_time(MpegEncContext * s){

    if(s->pict_type==AV_PICTURE_TYPE_B){

        ff_mpeg4_init_direct_mv(s);

    }else{

        s->last_time_base= s->time_base;

        s->time_base= s->time/s->avctx->time_base.den;

    }

}


static int skeleton_header(AVFormatContext *s, int idx)

{

    struct ogg *ogg = s->priv_data;

    struct ogg_stream *os = ogg->streams + idx;

    AVStream *st = s->streams[idx];

    uint8_t *buf = os->buf + os->pstart;

    int version_major, version_minor;

    int64_t start_num, start_den, start_granule;

    int target_idx, start_time;

    strcpy(st->codec->codec_name, "skeleton");

    st->codec->codec_type = AVMEDIA_TYPE_DATA;

    if (os->psize < 8)

        return -1;

    if (!strncmp(buf, "fishead", 8)) {

        if (os->psize < 64)

            return -1;

        version_major = AV_RL16(buf+8);

        version_minor = AV_RL16(buf+10);

        if (version_major != 3 && version_major != 4) {

            av_log(s, AV_LOG_WARNING, "Unknown skeleton version %d.%d\n",

                   version_major, version_minor);

            return -1;

        }

        // This is the overall start time. We use it for the start time of

        // of the skeleton stream since if left unset lavf assumes 0,

        // which we don't want since skeleton is timeless

        // FIXME: the real meaning of this field is "start playback at

        // this time which can be in the middle of a packet

        start_num = AV_RL64(buf+12);

        start_den = AV_RL64(buf+20);

        if (start_den) {

            int base_den;

            av_reduce(&start_time, &base_den, start_num, start_den, INT_MAX);

            avpriv_set_pts_info(st, 64, 1, base_den);

            os->lastpts =

            st->start_time = start_time;

        }

    } else if (!strncmp(buf, "fisbone", 8)) {

        if (os->psize < 52)

            return -1;

        target_idx = ogg_find_stream(ogg, AV_RL32(buf+12));

        start_granule = AV_RL64(buf+36);

        if (target_idx >= 0 && start_granule != -1) {

            ogg->streams[target_idx].lastpts =

            s->streams[target_idx]->start_time = ogg_gptopts(s, target_idx, start_granule, NULL);

        }

    }

    return 1;

}


static void virtio_net_set_status(struct VirtIODevice *vdev, uint8_t status)

{

    VirtIONet *n = VIRTIO_NET(vdev);

    VirtIONetQueue *q;

    int i;

    uint8_t queue_status;

    virtio_net_vnet_endian_status(n, status);

    virtio_net_vhost_status(n, status);

    for (i = 0; i < n->max_queues; i++) {

        NetClientState *ncs = qemu_get_subqueue(n->nic, i);

        bool queue_started;

        q = &n->vqs[i];

        if ((!n->multiqueue && i != 0) || i >= n->curr_queues) {

            queue_status = 0;

        } else {

            queue_status = status;

        }

        queue_started =

            virtio_net_started(n, queue_status) && !n->vhost_started;

        if (queue_started) {

            qemu_flush_queued_packets(ncs);

        }

        if (!q->tx_waiting) {

            continue;

        }

        if (queue_started) {

            if (q->tx_timer) {

                timer_mod(q->tx_timer,

                               qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + n->tx_timeout);

            } else {

                qemu_bh_schedule(q->tx_bh);

            }

        } else {

            if (q->tx_timer) {

                timer_del(q->tx_timer);

            } else {

                qemu_bh_cancel(q->tx_bh);

            }

            if ((n->status & VIRTIO_NET_S_LINK_UP) == 0 &&

                (queue_status & VIRTIO_CONFIG_S_DRIVER_OK)) {

                /* if tx is waiting we are likely have some packets in tx queue

                 * and disabled notification */

                q->tx_waiting = 0;

                virtio_queue_set_notification(q->tx_vq, 1);

                virtio_net_drop_tx_queue_data(vdev, q->tx_vq);

            }

        }

    }

}


static void alloc_picture(void *opaque)

{

    VideoState *is = opaque;

    VideoPicture *vp;

    vp = &is->pictq[is->pictq_windex];

    if (vp->bmp)

        SDL_FreeYUVOverlay(vp->bmp);

#if CONFIG_AVFILTER

    if (vp->picref)

        avfilter_unref_buffer(vp->picref);

    vp->picref = NULL;

    vp->width   = is->out_video_filter->inputs[0]->w;

    vp->height  = is->out_video_filter->inputs[0]->h;

    vp->pix_fmt = is->out_video_filter->inputs[0]->format;

#else

    vp->width   = is->video_st->codec->width;

    vp->height  = is->video_st->codec->height;

    vp->pix_fmt = is->video_st->codec->pix_fmt;

#endif

    vp->bmp = SDL_CreateYUVOverlay(vp->width, vp->height,

                                   SDL_YV12_OVERLAY,

                                   screen);

    if (!vp->bmp || vp->bmp->pitches[0] < vp->width) {

        /* SDL allocates a buffer smaller than requested if the video

         * overlay hardware is unable to support the requested size. */

        fprintf(stderr, "Error: the video system does not support an image\n"

                        "size of %dx%d pixels. Try using -vf \"scale=w:h\"\n"

                        "to reduce the image size.\n", vp->width, vp->height );

        do_exit(is);

    }

    SDL_LockMutex(is->pictq_mutex);

    vp->allocated = 1;

    SDL_CondSignal(is->pictq_cond);

    SDL_UnlockMutex(is->pictq_mutex);

}


static void int_to_int16(int16_t *out, const int *inp)

{

    int i;

    for (i=0; i<30; i++)

        *(out++) = *(inp++);

}


static int decode_frame_adu(AVCodecContext *avctx, void *data,

                            int *got_frame_ptr, AVPacket *avpkt)

{

    const uint8_t *buf  = avpkt->data;

    int buf_size        = avpkt->size;

    MPADecodeContext *s = avctx->priv_data;

    uint32_t header;

    int len, ret;

    len = buf_size;

    // Discard too short frames

    if (buf_size < HEADER_SIZE) {

        av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");

        return AVERROR_INVALIDDATA;

    }

    if (len > MPA_MAX_CODED_FRAME_SIZE)

        len = MPA_MAX_CODED_FRAME_SIZE;

    // Get header and restore sync word

    header = AV_RB32(buf) | 0xffe00000;

    if (ff_mpa_check_header(header) < 0) { // Bad header, discard frame

        av_log(avctx, AV_LOG_ERROR, "Invalid frame header\n");

        return AVERROR_INVALIDDATA;

    }

    avpriv_mpegaudio_decode_header((MPADecodeHeader *)s, header);

    /* update codec info */

    avctx->sample_rate = s->sample_rate;

    avctx->channels    = s->nb_channels;

    avctx->channel_layout = s->nb_channels == 1 ? AV_CH_LAYOUT_MONO : AV_CH_LAYOUT_STEREO;

    if (!avctx->bit_rate)

        avctx->bit_rate = s->bit_rate;

    s->frame_size = len;

    s->frame = data;

    ret = mp_decode_frame(s, NULL, buf, buf_size);

    if (ret < 0) {

        av_log(avctx, AV_LOG_ERROR, "Error while decoding MPEG audio frame.\n");

        return ret;

    }

    *got_frame_ptr = 1;

    return buf_size;

}


static void fill_caches(H264Context *h, int mb_type, int for_deblock){

    MpegEncContext * const s = &h->s;

    const int mb_xy= h->mb_xy;

    int topleft_xy, top_xy, topright_xy, left_xy[2];

    int topleft_type, top_type, topright_type, left_type[2];

    int * left_block;

    int topleft_partition= -1;

    int i;

    top_xy     = mb_xy  - (s->mb_stride << FIELD_PICTURE);

    //FIXME deblocking could skip the intra and nnz parts.

    if(for_deblock && (h->slice_num == 1 || h->slice_table[mb_xy] == h->slice_table[top_xy]) && !FRAME_MBAFF)

        return;

    /* Wow, what a mess, why didn't they simplify the interlacing & intra

     * stuff, I can't imagine that these complex rules are worth it. */

    topleft_xy = top_xy - 1;

    topright_xy= top_xy + 1;

    left_xy[1] = left_xy[0] = mb_xy-1;

    left_block = left_block_options[0];

    if(FRAME_MBAFF){

        const int pair_xy          = s->mb_x     + (s->mb_y & ~1)*s->mb_stride;

        const int top_pair_xy      = pair_xy     - s->mb_stride;

        const int topleft_pair_xy  = top_pair_xy - 1;

        const int topright_pair_xy = top_pair_xy + 1;

        const int topleft_mb_frame_flag  = !IS_INTERLACED(s->current_picture.mb_type[topleft_pair_xy]);

        const int top_mb_frame_flag      = !IS_INTERLACED(s->current_picture.mb_type[top_pair_xy]);

        const int topright_mb_frame_flag = !IS_INTERLACED(s->current_picture.mb_type[topright_pair_xy]);

        const int left_mb_frame_flag = !IS_INTERLACED(s->current_picture.mb_type[pair_xy-1]);

        const int curr_mb_frame_flag = !IS_INTERLACED(mb_type);

        const int bottom = (s->mb_y & 1);

        tprintf(s->avctx, "fill_caches: curr_mb_frame_flag:%d, left_mb_frame_flag:%d, topleft_mb_frame_flag:%d, top_mb_frame_flag:%d, topright_mb_frame_flag:%d\n", curr_mb_frame_flag, left_mb_frame_flag, topleft_mb_frame_flag, top_mb_frame_flag, topright_mb_frame_flag);

        if (bottom

                ? !curr_mb_frame_flag // bottom macroblock

                : (!curr_mb_frame_flag && !top_mb_frame_flag) // top macroblock

                ) {

            top_xy -= s->mb_stride;

        }

        if (bottom

                ? !curr_mb_frame_flag // bottom macroblock

                : (!curr_mb_frame_flag && !topleft_mb_frame_flag) // top macroblock

                ) {

            topleft_xy -= s->mb_stride;

        } else if(bottom && curr_mb_frame_flag && !left_mb_frame_flag) {

            topleft_xy += s->mb_stride;

            // take top left mv from the middle of the mb, as opposed to all other modes which use the bottom right partition

            topleft_partition = 0;

        }

        if (bottom

                ? !curr_mb_frame_flag // bottom macroblock

                : (!curr_mb_frame_flag && !topright_mb_frame_flag) // top macroblock

                ) {

            topright_xy -= s->mb_stride;

        }

        if (left_mb_frame_flag != curr_mb_frame_flag) {

            left_xy[1] = left_xy[0] = pair_xy - 1;

            if (curr_mb_frame_flag) {

                if (bottom) {

                    left_block = left_block_options[1];

                } else {

                    left_block= left_block_options[2];

                }

            } else {

                left_xy[1] += s->mb_stride;

                left_block = left_block_options[3];

            }

        }

    }

    h->top_mb_xy = top_xy;

    h->left_mb_xy[0] = left_xy[0];

    h->left_mb_xy[1] = left_xy[1];

    if(for_deblock){

        topleft_type = 0;

        topright_type = 0;

        top_type     = h->slice_table[top_xy     ] < 255 ? s->current_picture.mb_type[top_xy]     : 0;

        left_type[0] = h->slice_table[left_xy[0] ] < 255 ? s->current_picture.mb_type[left_xy[0]] : 0;

        left_type[1] = h->slice_table[left_xy[1] ] < 255 ? s->current_picture.mb_type[left_xy[1]] : 0;

        if(FRAME_MBAFF && !IS_INTRA(mb_type)){

            int list;

            for(list=0; list<h->list_count; list++){

                if(USES_LIST(mb_type,list)){

                    uint32_t *src = (uint32_t*)s->current_picture.motion_val[list][h->mb2b_xy[mb_xy]];

                    uint32_t *dst = (uint32_t*)h->mv_cache[list][scan8[0]];

                    int8_t *ref = &s->current_picture.ref_index[list][h->mb2b8_xy[mb_xy]];

                    for(i=0; i<4; i++, dst+=8, src+=h->b_stride){

                        dst[0] = src[0];

                        dst[1] = src[1];

                        dst[2] = src[2];

                        dst[3] = src[3];

                    }

                    *(uint32_t*)&h->ref_cache[list][scan8[ 0]] =

                    *(uint32_t*)&h->ref_cache[list][scan8[ 2]] = pack16to32(ref[0],ref[1])*0x0101;

                    ref += h->b8_stride;

                    *(uint32_t*)&h->ref_cache[list][scan8[ 8]] =

                    *(uint32_t*)&h->ref_cache[list][scan8[10]] = pack16to32(ref[0],ref[1])*0x0101;

                }else{

                    fill_rectangle(&h-> mv_cache[list][scan8[ 0]], 4, 4, 8, 0, 4);

                    fill_rectangle(&h->ref_cache[list][scan8[ 0]], 4, 4, 8, (uint8_t)LIST_NOT_USED, 1);

                }

            }

        }

    }else{

        topleft_type = h->slice_table[topleft_xy ] == h->slice_num ? s->current_picture.mb_type[topleft_xy] : 0;

        top_type     = h->slice_table[top_xy     ] == h->slice_num ? s->current_picture.mb_type[top_xy]     : 0;

        topright_type= h->slice_table[topright_xy] == h->slice_num ? s->current_picture.mb_type[topright_xy]: 0;

        left_type[0] = h->slice_table[left_xy[0] ] == h->slice_num ? s->current_picture.mb_type[left_xy[0]] : 0;

        left_type[1] = h->slice_table[left_xy[1] ] == h->slice_num ? s->current_picture.mb_type[left_xy[1]] : 0;

    }

    if(IS_INTRA(mb_type)){

        h->topleft_samples_available=

        h->top_samples_available=

        h->left_samples_available= 0xFFFF;

        h->topright_samples_available= 0xEEEA;

        if(!IS_INTRA(top_type) && (top_type==0 || h->pps.constrained_intra_pred)){

            h->topleft_samples_available= 0xB3FF;

            h->top_samples_available= 0x33FF;

            h->topright_samples_available= 0x26EA;

        }

        for(i=0; i<2; i++){

            if(!IS_INTRA(left_type[i]) && (left_type[i]==0 || h->pps.constrained_intra_pred)){

                h->topleft_samples_available&= 0xDF5F;

                h->left_samples_available&= 0x5F5F;

            }

        }

        if(!IS_INTRA(topleft_type) && (topleft_type==0 || h->pps.constrained_intra_pred))

            h->topleft_samples_available&= 0x7FFF;

        if(!IS_INTRA(topright_type) && (topright_type==0 || h->pps.constrained_intra_pred))

            h->topright_samples_available&= 0xFBFF;

        if(IS_INTRA4x4(mb_type)){

            if(IS_INTRA4x4(top_type)){

                h->intra4x4_pred_mode_cache[4+8*0]= h->intra4x4_pred_mode[top_xy][4];

                h->intra4x4_pred_mode_cache[5+8*0]= h->intra4x4_pred_mode[top_xy][5];

                h->intra4x4_pred_mode_cache[6+8*0]= h->intra4x4_pred_mode[top_xy][6];

                h->intra4x4_pred_mode_cache[7+8*0]= h->intra4x4_pred_mode[top_xy][3];

            }else{

                int pred;

                if(!top_type || (IS_INTER(top_type) && h->pps.constrained_intra_pred))

                    pred= -1;

                else{

                    pred= 2;

                }

                h->intra4x4_pred_mode_cache[4+8*0]=

                h->intra4x4_pred_mode_cache[5+8*0]=

                h->intra4x4_pred_mode_cache[6+8*0]=

                h->intra4x4_pred_mode_cache[7+8*0]= pred;

            }

            for(i=0; i<2; i++){

                if(IS_INTRA4x4(left_type[i])){

                    h->intra4x4_pred_mode_cache[3+8*1 + 2*8*i]= h->intra4x4_pred_mode[left_xy[i]][left_block[0+2*i]];

                    h->intra4x4_pred_mode_cache[3+8*2 + 2*8*i]= h->intra4x4_pred_mode[left_xy[i]][left_block[1+2*i]];

                }else{

                    int pred;

                    if(!left_type[i] || (IS_INTER(left_type[i]) && h->pps.constrained_intra_pred))

                        pred= -1;

                    else{

                        pred= 2;

                    }

                    h->intra4x4_pred_mode_cache[3+8*1 + 2*8*i]=

                    h->intra4x4_pred_mode_cache[3+8*2 + 2*8*i]= pred;

                }

            }

        }

    }

/*

0 . T T. T T T T

1 L . .L . . . .

2 L . .L . . . .

3 . T TL . . . .

4 L . .L . . . .

5 L . .. . . . .

*/

//FIXME constraint_intra_pred & partitioning & nnz (let us hope this is just a typo in the spec)

    if(top_type){

        h->non_zero_count_cache[4+8*0]= h->non_zero_count[top_xy][4];

        h->non_zero_count_cache[5+8*0]= h->non_zero_count[top_xy][5];

        h->non_zero_count_cache[6+8*0]= h->non_zero_count[top_xy][6];

        h->non_zero_count_cache[7+8*0]= h->non_zero_count[top_xy][3];

        h->non_zero_count_cache[1+8*0]= h->non_zero_count[top_xy][9];

        h->non_zero_count_cache[2+8*0]= h->non_zero_count[top_xy][8];

        h->non_zero_count_cache[1+8*3]= h->non_zero_count[top_xy][12];

        h->non_zero_count_cache[2+8*3]= h->non_zero_count[top_xy][11];

    }else{

        h->non_zero_count_cache[4+8*0]=

        h->non_zero_count_cache[5+8*0]=

        h->non_zero_count_cache[6+8*0]=

        h->non_zero_count_cache[7+8*0]=

        h->non_zero_count_cache[1+8*0]=

        h->non_zero_count_cache[2+8*0]=

        h->non_zero_count_cache[1+8*3]=

        h->non_zero_count_cache[2+8*3]= h->pps.cabac && !IS_INTRA(mb_type) ? 0 : 64;

    }

    for (i=0; i<2; i++) {

        if(left_type[i]){

            h->non_zero_count_cache[3+8*1 + 2*8*i]= h->non_zero_count[left_xy[i]][left_block[0+2*i]];

            h->non_zero_count_cache[3+8*2 + 2*8*i]= h->non_zero_count[left_xy[i]][left_block[1+2*i]];

            h->non_zero_count_cache[0+8*1 +   8*i]= h->non_zero_count[left_xy[i]][left_block[4+2*i]];

            h->non_zero_count_cache[0+8*4 +   8*i]= h->non_zero_count[left_xy[i]][left_block[5+2*i]];

        }else{

            h->non_zero_count_cache[3+8*1 + 2*8*i]=

            h->non_zero_count_cache[3+8*2 + 2*8*i]=

            h->non_zero_count_cache[0+8*1 +   8*i]=

            h->non_zero_count_cache[0+8*4 +   8*i]= h->pps.cabac && !IS_INTRA(mb_type) ? 0 : 64;

        }

    }

    if( h->pps.cabac ) {

        // top_cbp

        if(top_type) {

            h->top_cbp = h->cbp_table[top_xy];

        } else if(IS_INTRA(mb_type)) {

            h->top_cbp = 0x1C0;

        } else {

            h->top_cbp = 0;

        }

        // left_cbp

        if (left_type[0]) {

            h->left_cbp = h->cbp_table[left_xy[0]] & 0x1f0;

        } else if(IS_INTRA(mb_type)) {

            h->left_cbp = 0x1C0;

        } else {

            h->left_cbp = 0;

        }

        if (left_type[0]) {

            h->left_cbp |= ((h->cbp_table[left_xy[0]]>>((left_block[0]&(~1))+1))&0x1) << 1;

        }

        if (left_type[1]) {

            h->left_cbp |= ((h->cbp_table[left_xy[1]]>>((left_block[2]&(~1))+1))&0x1) << 3;

        }

    }

#if 1

    if(IS_INTER(mb_type) || IS_DIRECT(mb_type)){

        int list;

        for(list=0; list<h->list_count; list++){

            if(!USES_LIST(mb_type, list) && !IS_DIRECT(mb_type) && !h->deblocking_filter){

                /*if(!h->mv_cache_clean[list]){

                    memset(h->mv_cache [list],  0, 8*5*2*sizeof(int16_t)); //FIXME clean only input? clean at all?

                    memset(h->ref_cache[list], PART_NOT_AVAILABLE, 8*5*sizeof(int8_t));

                    h->mv_cache_clean[list]= 1;

                }*/

                continue;

            }

            h->mv_cache_clean[list]= 0;

            if(USES_LIST(top_type, list)){

                const int b_xy= h->mb2b_xy[top_xy] + 3*h->b_stride;

                const int b8_xy= h->mb2b8_xy[top_xy] + h->b8_stride;

                *(uint32_t*)h->mv_cache[list][scan8[0] + 0 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + 0];

                *(uint32_t*)h->mv_cache[list][scan8[0] + 1 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + 1];

                *(uint32_t*)h->mv_cache[list][scan8[0] + 2 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + 2];

                *(uint32_t*)h->mv_cache[list][scan8[0] + 3 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + 3];

                h->ref_cache[list][scan8[0] + 0 - 1*8]=

                h->ref_cache[list][scan8[0] + 1 - 1*8]= s->current_picture.ref_index[list][b8_xy + 0];

                h->ref_cache[list][scan8[0] + 2 - 1*8]=

                h->ref_cache[list][scan8[0] + 3 - 1*8]= s->current_picture.ref_index[list][b8_xy + 1];

            }else{

                *(uint32_t*)h->mv_cache [list][scan8[0] + 0 - 1*8]=

                *(uint32_t*)h->mv_cache [list][scan8[0] + 1 - 1*8]=

                *(uint32_t*)h->mv_cache [list][scan8[0] + 2 - 1*8]=

                *(uint32_t*)h->mv_cache [list][scan8[0] + 3 - 1*8]= 0;

                *(uint32_t*)&h->ref_cache[list][scan8[0] + 0 - 1*8]= ((top_type ? LIST_NOT_USED : PART_NOT_AVAILABLE)&0xFF)*0x01010101;

            }

            for(i=0; i<2; i++){

                int cache_idx = scan8[0] - 1 + i*2*8;

                if(USES_LIST(left_type[i], list)){

                    const int b_xy= h->mb2b_xy[left_xy[i]] + 3;

                    const int b8_xy= h->mb2b8_xy[left_xy[i]] + 1;

                    *(uint32_t*)h->mv_cache[list][cache_idx  ]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + h->b_stride*left_block[0+i*2]];

                    *(uint32_t*)h->mv_cache[list][cache_idx+8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + h->b_stride*left_block[1+i*2]];

                    h->ref_cache[list][cache_idx  ]= s->current_picture.ref_index[list][b8_xy + h->b8_stride*(left_block[0+i*2]>>1)];

                    h->ref_cache[list][cache_idx+8]= s->current_picture.ref_index[list][b8_xy + h->b8_stride*(left_block[1+i*2]>>1)];

                }else{

                    *(uint32_t*)h->mv_cache [list][cache_idx  ]=

                    *(uint32_t*)h->mv_cache [list][cache_idx+8]= 0;

                    h->ref_cache[list][cache_idx  ]=

                    h->ref_cache[list][cache_idx+8]= left_type[i] ? LIST_NOT_USED : PART_NOT_AVAILABLE;

                }

            }

            if((for_deblock || (IS_DIRECT(mb_type) && !h->direct_spatial_mv_pred)) && !FRAME_MBAFF)

                continue;

            if(USES_LIST(topleft_type, list)){

                const int b_xy = h->mb2b_xy[topleft_xy] + 3 + h->b_stride + (topleft_partition & 2*h->b_stride);

                const int b8_xy= h->mb2b8_xy[topleft_xy] + 1 + (topleft_partition & h->b8_stride);

                *(uint32_t*)h->mv_cache[list][scan8[0] - 1 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy];

                h->ref_cache[list][scan8[0] - 1 - 1*8]= s->current_picture.ref_index[list][b8_xy];

            }else{

                *(uint32_t*)h->mv_cache[list][scan8[0] - 1 - 1*8]= 0;

                h->ref_cache[list][scan8[0] - 1 - 1*8]= topleft_type ? LIST_NOT_USED : PART_NOT_AVAILABLE;

            }

            if(USES_LIST(topright_type, list)){

                const int b_xy= h->mb2b_xy[topright_xy] + 3*h->b_stride;

                const int b8_xy= h->mb2b8_xy[topright_xy] + h->b8_stride;

                *(uint32_t*)h->mv_cache[list][scan8[0] + 4 - 1*8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy];

                h->ref_cache[list][scan8[0] + 4 - 1*8]= s->current_picture.ref_index[list][b8_xy];

            }else{

                *(uint32_t*)h->mv_cache [list][scan8[0] + 4 - 1*8]= 0;

                h->ref_cache[list][scan8[0] + 4 - 1*8]= topright_type ? LIST_NOT_USED : PART_NOT_AVAILABLE;

            }

            if((IS_SKIP(mb_type) || IS_DIRECT(mb_type)) && !FRAME_MBAFF)

                continue;

            h->ref_cache[list][scan8[5 ]+1] =

            h->ref_cache[list][scan8[7 ]+1] =

            h->ref_cache[list][scan8[13]+1] =  //FIXME remove past 3 (init somewhere else)

            h->ref_cache[list][scan8[4 ]] =

            h->ref_cache[list][scan8[12]] = PART_NOT_AVAILABLE;

            *(uint32_t*)h->mv_cache [list][scan8[5 ]+1]=

            *(uint32_t*)h->mv_cache [list][scan8[7 ]+1]=

            *(uint32_t*)h->mv_cache [list][scan8[13]+1]= //FIXME remove past 3 (init somewhere else)

            *(uint32_t*)h->mv_cache [list][scan8[4 ]]=

            *(uint32_t*)h->mv_cache [list][scan8[12]]= 0;

            if( h->pps.cabac ) {

                /* XXX beurk, Load mvd */

                if(USES_LIST(top_type, list)){

                    const int b_xy= h->mb2b_xy[top_xy] + 3*h->b_stride;

                    *(uint32_t*)h->mvd_cache[list][scan8[0] + 0 - 1*8]= *(uint32_t*)h->mvd_table[list][b_xy + 0];

                    *(uint32_t*)h->mvd_cache[list][scan8[0] + 1 - 1*8]= *(uint32_t*)h->mvd_table[list][b_xy + 1];

                    *(uint32_t*)h->mvd_cache[list][scan8[0] + 2 - 1*8]= *(uint32_t*)h->mvd_table[list][b_xy + 2];

                    *(uint32_t*)h->mvd_cache[list][scan8[0] + 3 - 1*8]= *(uint32_t*)h->mvd_table[list][b_xy + 3];

                }else{

                    *(uint32_t*)h->mvd_cache [list][scan8[0] + 0 - 1*8]=

                    *(uint32_t*)h->mvd_cache [list][scan8[0] + 1 - 1*8]=

                    *(uint32_t*)h->mvd_cache [list][scan8[0] + 2 - 1*8]=

                    *(uint32_t*)h->mvd_cache [list][scan8[0] + 3 - 1*8]= 0;

                }

                if(USES_LIST(left_type[0], list)){

                    const int b_xy= h->mb2b_xy[left_xy[0]] + 3;

                    *(uint32_t*)h->mvd_cache[list][scan8[0] - 1 + 0*8]= *(uint32_t*)h->mvd_table[list][b_xy + h->b_stride*left_block[0]];

                    *(uint32_t*)h->mvd_cache[list][scan8[0] - 1 + 1*8]= *(uint32_t*)h->mvd_table[list][b_xy + h->b_stride*left_block[1]];

                }else{

                    *(uint32_t*)h->mvd_cache [list][scan8[0] - 1 + 0*8]=

                    *(uint32_t*)h->mvd_cache [list][scan8[0] - 1 + 1*8]= 0;

                }

                if(USES_LIST(left_type[1], list)){

                    const int b_xy= h->mb2b_xy[left_xy[1]] + 3;

                    *(uint32_t*)h->mvd_cache[list][scan8[0] - 1 + 2*8]= *(uint32_t*)h->mvd_table[list][b_xy + h->b_stride*left_block[2]];

                    *(uint32_t*)h->mvd_cache[list][scan8[0] - 1 + 3*8]= *(uint32_t*)h->mvd_table[list][b_xy + h->b_stride*left_block[3]];

                }else{

                    *(uint32_t*)h->mvd_cache [list][scan8[0] - 1 + 2*8]=

                    *(uint32_t*)h->mvd_cache [list][scan8[0] - 1 + 3*8]= 0;

                }

                *(uint32_t*)h->mvd_cache [list][scan8[5 ]+1]=

                *(uint32_t*)h->mvd_cache [list][scan8[7 ]+1]=

                *(uint32_t*)h->mvd_cache [list][scan8[13]+1]= //FIXME remove past 3 (init somewhere else)

                *(uint32_t*)h->mvd_cache [list][scan8[4 ]]=

                *(uint32_t*)h->mvd_cache [list][scan8[12]]= 0;

                if(h->slice_type_nos == FF_B_TYPE){

                    fill_rectangle(&h->direct_cache[scan8[0]], 4, 4, 8, 0, 1);

                    if(IS_DIRECT(top_type)){

                        *(uint32_t*)&h->direct_cache[scan8[0] - 1*8]= 0x01010101;

                    }else if(IS_8X8(top_type)){

                        int b8_xy = h->mb2b8_xy[top_xy] + h->b8_stride;

                        h->direct_cache[scan8[0] + 0 - 1*8]= h->direct_table[b8_xy];

                        h->direct_cache[scan8[0] + 2 - 1*8]= h->direct_table[b8_xy + 1];

                    }else{

                        *(uint32_t*)&h->direct_cache[scan8[0] - 1*8]= 0;

                    }

                    if(IS_DIRECT(left_type[0]))

                        h->direct_cache[scan8[0] - 1 + 0*8]= 1;

                    else if(IS_8X8(left_type[0]))

                        h->direct_cache[scan8[0] - 1 + 0*8]= h->direct_table[h->mb2b8_xy[left_xy[0]] + 1 + h->b8_stride*(left_block[0]>>1)];

                    else

                        h->direct_cache[scan8[0] - 1 + 0*8]= 0;

                    if(IS_DIRECT(left_type[1]))

                        h->direct_cache[scan8[0] - 1 + 2*8]= 1;

                    else if(IS_8X8(left_type[1]))

                        h->direct_cache[scan8[0] - 1 + 2*8]= h->direct_table[h->mb2b8_xy[left_xy[1]] + 1 + h->b8_stride*(left_block[2]>>1)];

                    else

                        h->direct_cache[scan8[0] - 1 + 2*8]= 0;

                }

            }

            if(FRAME_MBAFF){

#define MAP_MVS\

                    MAP_F2F(scan8[0] - 1 - 1*8, topleft_type)\

                    MAP_F2F(scan8[0] + 0 - 1*8, top_type)\

                    MAP_F2F(scan8[0] + 1 - 1*8, top_type)\

                    MAP_F2F(scan8[0] + 2 - 1*8, top_type)\

                    MAP_F2F(scan8[0] + 3 - 1*8, top_type)\

                    MAP_F2F(scan8[0] + 4 - 1*8, topright_type)\

                    MAP_F2F(scan8[0] - 1 + 0*8, left_type[0])\

                    MAP_F2F(scan8[0] - 1 + 1*8, left_type[0])\

                    MAP_F2F(scan8[0] - 1 + 2*8, left_type[1])\

                    MAP_F2F(scan8[0] - 1 + 3*8, left_type[1])

                if(MB_FIELD){

#define MAP_F2F(idx, mb_type)\

                    if(!IS_INTERLACED(mb_type) && h->ref_cache[list][idx] >= 0){\

                        h->ref_cache[list][idx] <<= 1;\

                        h->mv_cache[list][idx][1] /= 2;\

                        h->mvd_cache[list][idx][1] /= 2;\

                    }

                    MAP_MVS

#undef MAP_F2F

                }else{

#define MAP_F2F(idx, mb_type)\

                    if(IS_INTERLACED(mb_type) && h->ref_cache[list][idx] >= 0){\

                        h->ref_cache[list][idx] >>= 1;\

                        h->mv_cache[list][idx][1] <<= 1;\

                        h->mvd_cache[list][idx][1] <<= 1;\

                    }

                    MAP_MVS

#undef MAP_F2F

                }

            }

        }

    }

#endif

    h->neighbor_transform_size= !!IS_8x8DCT(top_type) + !!IS_8x8DCT(left_type[0]);

}


int virtio_gpu_create_mapping_iov(struct virtio_gpu_resource_attach_backing *ab,

                                  struct virtio_gpu_ctrl_command *cmd,

                                  struct iovec **iov)

{

    struct virtio_gpu_mem_entry *ents;

    size_t esize, s;

    int i;

    if (ab->nr_entries > 16384) {

        qemu_log_mask(LOG_GUEST_ERROR,

                      "%s: nr_entries is too big (%d > 16384)\n",

                      __func__, ab->nr_entries);

        return -1;

    }

    esize = sizeof(*ents) * ab->nr_entries;

    ents = g_malloc(esize);

    s = iov_to_buf(cmd->elem.out_sg, cmd->elem.out_num,

                   sizeof(*ab), ents, esize);

    if (s != esize) {

        qemu_log_mask(LOG_GUEST_ERROR,

                      "%s: command data size incorrect %zu vs %zu\n",

                      __func__, s, esize);

        g_free(ents);

        return -1;

    }

    *iov = g_malloc0(sizeof(struct iovec) * ab->nr_entries);

    for (i = 0; i < ab->nr_entries; i++) {

        hwaddr len = ents[i].length;

        (*iov)[i].iov_len = ents[i].length;

        (*iov)[i].iov_base = cpu_physical_memory_map(ents[i].addr, &len, 1);

        if (!(*iov)[i].iov_base || len != ents[i].length) {

            qemu_log_mask(LOG_GUEST_ERROR, "%s: failed to map MMIO memory for"

                          " resource %d element %d\n",

                          __func__, ab->resource_id, i);

            virtio_gpu_cleanup_mapping_iov(*iov, i);

            g_free(ents);

            g_free(*iov);

            *iov = NULL;

            return -1;

        }

    }

    g_free(ents);

    return 0;

}


static int check_refcounts_l2(BlockDriverState *bs,
    uint16_t *refcount_table, int refcount_table_size, int64_t l2_offset,
    int check_copied)
{
    BDRVQcowState *s = bs->opaque;
    uint64_t *l2_table, offset;
    int i, l2_size, nb_csectors, refcount;
    int errors = 0;
    /* Read L2 table from disk */
    l2_size = s->l2_size * sizeof(uint64_t);
    l2_table = qemu_malloc(l2_size);
    if (bdrv_pread(s->hd, l2_offset, l2_table, l2_size) != l2_size)
        goto fail;
    /* Do the actual checks */
    for(i = 0; i < s->l2_size; i++) {
        offset = be64_to_cpu(l2_table[i]);
        if (offset != 0) {
            if (offset & QCOW_OFLAG_COMPRESSED) {
                /* Compressed clusters don't have QCOW_OFLAG_COPIED */
                if (offset & QCOW_OFLAG_COPIED) {
                    fprintf(stderr, "ERROR: cluster %" PRId64 ": "
                        "copied flag must never be set for compressed "
                        "clusters\n", offset >> s->cluster_bits);
                    offset &= ~QCOW_OFLAG_COPIED;
                /* Mark cluster as used */
                nb_csectors = ((offset >> s->csize_shift) &
                               s->csize_mask) + 1;
                offset &= s->cluster_offset_mask;
                errors += inc_refcounts(bs, refcount_table,
                              refcount_table_size,
                              offset & ~511, nb_csectors * 512);
            } else {
                /* QCOW_OFLAG_COPIED must be set iff refcount == 1 */
                if (check_copied) {
                    uint64_t entry = offset;
                    offset &= ~QCOW_OFLAG_COPIED;
                    refcount = get_refcount(bs, offset >> s->cluster_bits);
                    if ((refcount == 1) != ((entry & QCOW_OFLAG_COPIED) != 0)) {
                        fprintf(stderr, "ERROR OFLAG_COPIED: offset=%"
                            PRIx64 " refcount=%d\n", entry, refcount);
                /* Mark cluster as used */
                offset &= ~QCOW_OFLAG_COPIED;
                errors += inc_refcounts(bs, refcount_table,
                              refcount_table_size,
                              offset, s->cluster_size);
    qemu_free(l2_table);
    return errors;
fail:
    fprintf(stderr, "ERROR: I/O error in check_refcounts_l1\n");
    qemu_free(l2_table);
    return -EIO;


static inline void direct_ref_list_init(H264Context * const h){

    MpegEncContext * const s = &h->s;

    Picture * const ref1 = &h->ref_list[1][0];

    Picture * const cur = s->current_picture_ptr;

    int list, i, j;

    int sidx= s->picture_structure&1;

    int ref1sidx= ref1->reference&1;

    for(list=0; list<2; list++){

        cur->ref_count[sidx][list] = h->ref_count[list];

        for(j=0; j<h->ref_count[list]; j++)

            cur->ref_poc[sidx][list][j] = h->ref_list[list][j].poc;

    }

    if(s->picture_structure == PICT_FRAME){

        memcpy(cur->ref_count[0], cur->ref_count[1], sizeof(cur->ref_count[0]));

        memcpy(cur->ref_poc  [0], cur->ref_poc  [1], sizeof(cur->ref_poc  [0]));

    }

    if(cur->pict_type != FF_B_TYPE || h->direct_spatial_mv_pred)

        return;

    for(list=0; list<2; list++){

        for(i=0; i<ref1->ref_count[ref1sidx][list]; i++){

            const int poc = ref1->ref_poc[ref1sidx][list][i];

            h->map_col_to_list0[list][i] = 0; /* bogus; fills in for missing frames */

            for(j=0; j<h->ref_count[list]; j++)

                if(h->ref_list[list][j].poc == poc){

                    h->map_col_to_list0[list][i] = j;

                    break;

                }

        }

    }

    if(FRAME_MBAFF){

        for(list=0; list<2; list++){

            for(i=0; i<ref1->ref_count[ref1sidx][list]; i++){

                j = h->map_col_to_list0[list][i];

                h->map_col_to_list0_field[list][2*i] = 2*j;

                h->map_col_to_list0_field[list][2*i+1] = 2*j+1;

            }

        }

    }

}


static inline void tm2_high_chroma(int *data, int stride, int *last, int *CD, int *deltas)

{

    int i, j;

    for (j = 0; j < 2; j++) {

        for (i = 0; i < 2; i++)  {

            CD[j]   += deltas[i + j * 2];

            last[i] += CD[j];

            data[i]  = last[i];

        }

        data += stride;

    }

}


static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,

                                   size_t size)

{

    int64_t len;

    if (!bdrv_is_inserted(bs))

        return -ENOMEDIUM;

    if (bs->growable)

        return 0;

    len = bdrv_getlength(bs);

    if ((offset + size) > len)

        return -EIO;

    return 0;

}


static int aiff_read_header(AVFormatContext *s)

{

    int ret, size, filesize;

    int64_t offset = 0, position;

    uint32_t tag;

    unsigned version = AIFF_C_VERSION1;

    AVIOContext *pb = s->pb;

    AVStream * st;

    AIFFInputContext *aiff = s->priv_data;

    ID3v2ExtraMeta *id3v2_extra_meta = NULL;

    /* check FORM header */

    filesize = get_tag(pb, &tag);

    if (filesize < 0 || tag != MKTAG('F', 'O', 'R', 'M'))

        return AVERROR_INVALIDDATA;

    /* AIFF data type */

    tag = avio_rl32(pb);

    if (tag == MKTAG('A', 'I', 'F', 'F'))       /* Got an AIFF file */

        version = AIFF;

    else if (tag != MKTAG('A', 'I', 'F', 'C'))  /* An AIFF-C file then */

        return AVERROR_INVALIDDATA;

    filesize -= 4;

    st = avformat_new_stream(s, NULL);

    if (!st)

        return AVERROR(ENOMEM);

    while (filesize > 0) {

        /* parse different chunks */

        size = get_tag(pb, &tag);

        if (size == AVERROR_EOF && offset > 0 && st->codecpar->block_align) {

            av_log(s, AV_LOG_WARNING, "header parser hit EOF\n");

            goto got_sound;

        }

        if (size < 0)

            return size;

        filesize -= size + 8;

        switch (tag) {

        case MKTAG('C', 'O', 'M', 'M'):     /* Common chunk */

            /* Then for the complete header info */

            st->nb_frames = get_aiff_header(s, size, version);

            if (st->nb_frames < 0)

                return st->nb_frames;

            if (offset > 0) // COMM is after SSND

                goto got_sound;

            break;

        case MKTAG('I', 'D', '3', ' '):

            position = avio_tell(pb);

            ff_id3v2_read(s, ID3v2_DEFAULT_MAGIC, &id3v2_extra_meta, size);

            if (id3v2_extra_meta)

                if ((ret = ff_id3v2_parse_apic(s, &id3v2_extra_meta)) < 0) {

                    ff_id3v2_free_extra_meta(&id3v2_extra_meta);

                    return ret;

                }

            ff_id3v2_free_extra_meta(&id3v2_extra_meta);

            if (position + size > avio_tell(pb))

                avio_skip(pb, position + size - avio_tell(pb));

            break;

        case MKTAG('F', 'V', 'E', 'R'):     /* Version chunk */

            version = avio_rb32(pb);

            break;

        case MKTAG('N', 'A', 'M', 'E'):     /* Sample name chunk */

            get_meta(s, "title"    , size);

            break;

        case MKTAG('A', 'U', 'T', 'H'):     /* Author chunk */

            get_meta(s, "author"   , size);

            break;

        case MKTAG('(', 'c', ')', ' '):     /* Copyright chunk */

            get_meta(s, "copyright", size);

            break;

        case MKTAG('A', 'N', 'N', 'O'):     /* Annotation chunk */

            get_meta(s, "comment"  , size);

            break;

        case MKTAG('S', 'S', 'N', 'D'):     /* Sampled sound chunk */

            aiff->data_end = avio_tell(pb) + size;

            offset = avio_rb32(pb);      /* Offset of sound data */

            avio_rb32(pb);               /* BlockSize... don't care */

            offset += avio_tell(pb);    /* Compute absolute data offset */

            if (st->codecpar->block_align && !pb->seekable)    /* Assume COMM already parsed */

                goto got_sound;

            if (!pb->seekable) {

                av_log(s, AV_LOG_ERROR, "file is not seekable\n");

                return -1;

            }

            avio_skip(pb, size - 8);

            break;

        case MKTAG('w', 'a', 'v', 'e'):

            if ((uint64_t)size > (1<<30))

                return -1;

            if (ff_get_extradata(s, st->codecpar, pb, size) < 0)

                return AVERROR(ENOMEM);

            if (   (st->codecpar->codec_id == AV_CODEC_ID_QDMC || st->codecpar->codec_id == AV_CODEC_ID_QDM2)

                && size>=12*4 && !st->codecpar->block_align) {

                st->codecpar->block_align = AV_RB32(st->codecpar->extradata+11*4);

                aiff->block_duration = AV_RB32(st->codecpar->extradata+9*4);

            } else if (st->codecpar->codec_id == AV_CODEC_ID_QCELP) {

                char rate = 0;

                if (size >= 25)

                    rate = st->codecpar->extradata[24];

                switch (rate) {

                case 'H': // RATE_HALF

                    st->codecpar->block_align = 17;

                    break;

                case 'F': // RATE_FULL

                default:

                    st->codecpar->block_align = 35;

                }

                aiff->block_duration = 160;

                st->codecpar->bit_rate = st->codecpar->sample_rate * (st->codecpar->block_align << 3) /

                                         aiff->block_duration;

            }

            break;

        case MKTAG('C','H','A','N'):

            if(ff_mov_read_chan(s, pb, st, size) < 0)

                return AVERROR_INVALIDDATA;

            break;

        case 0:

            if (offset > 0 && st->codecpar->block_align) // COMM && SSND

                goto got_sound;

        default: /* Jump */

            if (size & 1)   /* Always even aligned */

                size++;

            avio_skip(pb, size);

        }

    }

got_sound:

    if (!st->codecpar->block_align && st->codecpar->codec_id == AV_CODEC_ID_QCELP) {

        av_log(s, AV_LOG_WARNING, "qcelp without wave chunk, assuming full rate\n");

        st->codecpar->block_align = 35;

    } else if (!st->codecpar->block_align) {

        av_log(s, AV_LOG_ERROR, "could not find COMM tag or invalid block_align value\n");

        return -1;

    }

    /* Now positioned, get the sound data start and end */

    avpriv_set_pts_info(st, 64, 1, st->codecpar->sample_rate);

    st->start_time = 0;

    st->duration = st->nb_frames * aiff->block_duration;

    /* Position the stream at the first block */

    avio_seek(pb, offset, SEEK_SET);

    return 0;

}


static int qemu_signal_init(void)

{

    int sigfd;

    sigset_t set;

#ifdef CONFIG_IOTHREAD

    /* SIGUSR2 used by posix-aio-compat.c */

    sigemptyset(&set);

    sigaddset(&set, SIGUSR2);

    pthread_sigmask(SIG_UNBLOCK, &set, NULL);

    /*

     * SIG_IPI must be blocked in the main thread and must not be caught

     * by sigwait() in the signal thread. Otherwise, the cpu thread will

     * not catch it reliably.

     */

    sigemptyset(&set);

    sigaddset(&set, SIG_IPI);

    pthread_sigmask(SIG_BLOCK, &set, NULL);

    sigemptyset(&set);

    sigaddset(&set, SIGIO);

    sigaddset(&set, SIGALRM);

    sigaddset(&set, SIGBUS);

#else

    sigemptyset(&set);

    sigaddset(&set, SIGBUS);

    if (kvm_enabled()) {

        /*

         * We need to process timer signals synchronously to avoid a race

         * between exit_request check and KVM vcpu entry.

         */

        sigaddset(&set, SIGIO);

        sigaddset(&set, SIGALRM);

    }

#endif

    pthread_sigmask(SIG_BLOCK, &set, NULL);

    sigfd = qemu_signalfd(&set);

    if (sigfd == -1) {

        fprintf(stderr, "failed to create signalfd\n");

        return -errno;

    }

    fcntl_setfl(sigfd, O_NONBLOCK);

    qemu_set_fd_handler2(sigfd, NULL, sigfd_handler, NULL,

                         (void *)(intptr_t)sigfd);

    return 0;

}


static void gen_neon_dup_high16(TCGv var)

{

    TCGv tmp = new_tmp();

    tcg_gen_andi_i32(var, var, 0xffff0000);

    tcg_gen_shri_i32(tmp, var, 16);

    tcg_gen_or_i32(var, var, tmp);

    dead_tmp(tmp);

}


static void lx60_net_init(MemoryRegion *address_space,

        hwaddr base,

        hwaddr descriptors,

        hwaddr buffers,

        qemu_irq irq, NICInfo *nd)

{

    DeviceState *dev;

    SysBusDevice *s;

    MemoryRegion *ram;

    dev = qdev_create(NULL, "open_eth");

    qdev_set_nic_properties(dev, nd);

    qdev_init_nofail(dev);

    s = SYS_BUS_DEVICE(dev);

    sysbus_connect_irq(s, 0, irq);

    memory_region_add_subregion(address_space, base,

            sysbus_mmio_get_region(s, 0));

    memory_region_add_subregion(address_space, descriptors,

            sysbus_mmio_get_region(s, 1));

    ram = g_malloc(sizeof(*ram));

    memory_region_init_ram(ram, OBJECT(s), "open_eth.ram", 16384, &error_abort);

    vmstate_register_ram_global(ram);

    memory_region_add_subregion(address_space, buffers, ram);

}


void destroy_nic(dev_match_fn *match_fn, void *arg)

{

    int i;

    NICInfo *nic;

    for (i = 0; i < MAX_NICS; i++) {

        nic = &nd_table[i];

        if (nic->used) {

            if (nic->private && match_fn(nic->private, arg)) {

                if (nic->vlan) {

                    VLANClientState *vc;

                    vc = qemu_find_vlan_client(nic->vlan, nic->private);

                    if (vc)

                        qemu_del_vlan_client(vc);

                }

                net_client_uninit(nic);

            }

        }

    }

}


static av_cold int pcm_encode_close(AVCodecContext *avctx)

{

    av_freep(&avctx->coded_frame);

    return 0;

}


static void extract_exponents(AC3EncodeContext *s)

{

    int blk, ch, i;

    for (ch = 0; ch < s->channels; ch++) {

        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {

            AC3Block *block = &s->blocks[blk];

            for (i = 0; i < AC3_MAX_COEFS; i++) {

                int e;

                int v = abs(SCALE_COEF(block->mdct_coef[ch][i]));

                if (v == 0)

                    e = 24;

                else {

                    e = 23 - av_log2(v) + block->exp_shift[ch];

                    if (e >= 24) {

                        e = 24;

                        block->mdct_coef[ch][i] = 0;

                    }

                }

                block->exp[ch][i] = e;

            }

        }

    }

}


static av_cold int nvenc_dyload_cuda(AVCodecContext *avctx)

{

    NvencContext *ctx = avctx->priv_data;

    NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;

#if CONFIG_CUDA

    dl_fn->cu_init                      = cuInit;

    dl_fn->cu_device_get_count          = cuDeviceGetCount;

    dl_fn->cu_device_get                = cuDeviceGet;

    dl_fn->cu_device_get_name           = cuDeviceGetName;

    dl_fn->cu_device_compute_capability = cuDeviceComputeCapability;

    dl_fn->cu_ctx_create                = cuCtxCreate_v2;

    dl_fn->cu_ctx_pop_current           = cuCtxPopCurrent_v2;

    dl_fn->cu_ctx_destroy               = cuCtxDestroy_v2;

    return 1;

#else

    if (dl_fn->cuda_lib)

        return 1;

#if defined(_WIN32)

    dl_fn->cuda_lib = LoadLibrary(TEXT("nvcuda.dll"));

#else

    dl_fn->cuda_lib = dlopen("libcuda.so", RTLD_LAZY);

#endif

    if (!dl_fn->cuda_lib) {

        av_log(avctx, AV_LOG_FATAL, "Failed loading CUDA library\n");

        goto error;

    }

    CHECK_LOAD_FUNC(PCUINIT, dl_fn->cu_init, "cuInit");

    CHECK_LOAD_FUNC(PCUDEVICEGETCOUNT, dl_fn->cu_device_get_count, "cuDeviceGetCount");

    CHECK_LOAD_FUNC(PCUDEVICEGET, dl_fn->cu_device_get, "cuDeviceGet");

    CHECK_LOAD_FUNC(PCUDEVICEGETNAME, dl_fn->cu_device_get_name, "cuDeviceGetName");

    CHECK_LOAD_FUNC(PCUDEVICECOMPUTECAPABILITY, dl_fn->cu_device_compute_capability, "cuDeviceComputeCapability");

    CHECK_LOAD_FUNC(PCUCTXCREATE, dl_fn->cu_ctx_create, "cuCtxCreate_v2");

    CHECK_LOAD_FUNC(PCUCTXPOPCURRENT, dl_fn->cu_ctx_pop_current, "cuCtxPopCurrent_v2");

    CHECK_LOAD_FUNC(PCUCTXDESTROY, dl_fn->cu_ctx_destroy, "cuCtxDestroy_v2");

    return 1;

error:

    if (dl_fn->cuda_lib)

        DL_CLOSE_FUNC(dl_fn->cuda_lib);

    dl_fn->cuda_lib = NULL;

    return 0;

#endif

}


static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)

{

    MpegTSContext *ts = filter->u.section_filter.opaque;

    MpegTSSectionFilter *tssf = &filter->u.section_filter;

    SectionHeader h1, *h = &h1;

    const uint8_t *p, *p_end;

    int sid, pmt_pid;

    AVProgram *program;

    av_log(ts->stream, AV_LOG_TRACE, "PAT:\n");

    hex_dump_debug(ts->stream, section, section_len);

    p_end = section + section_len - 4;

    p     = section;

    if (parse_section_header(h, &p, p_end) < 0)

        return;

    if (h->tid != PAT_TID)

        return;

    if (ts->skip_changes)

        return;

    if (h->version == tssf->last_ver)

        return;

    tssf->last_ver = h->version;

    ts->stream->ts_id = h->id;

    clear_programs(ts);

    for (;;) {

        sid = get16(&p, p_end);

        if (sid < 0)

            break;

        pmt_pid = get16(&p, p_end);

        if (pmt_pid < 0)

            break;

        pmt_pid &= 0x1fff;

        if (pmt_pid == ts->current_pid)

            break;

        av_log(ts->stream, AV_LOG_TRACE, "sid=0x%x pid=0x%x\n", sid, pmt_pid);

        if (sid == 0x0000) {

            /* NIT info */

        } else {

            MpegTSFilter *fil = ts->pids[pmt_pid];

            program = av_new_program(ts->stream, sid);

            if (program) {

                program->program_num = sid;

                program->pmt_pid = pmt_pid;

            }

            if (fil)

                if (   fil->type != MPEGTS_SECTION

                    || fil->pid != pmt_pid

                    || fil->u.section_filter.section_cb != pmt_cb)

                    mpegts_close_filter(ts, ts->pids[pmt_pid]);

            if (!ts->pids[pmt_pid])

                mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);

            add_pat_entry(ts, sid);

            add_pid_to_pmt(ts, sid, 0); // add pat pid to program

            add_pid_to_pmt(ts, sid, pmt_pid);

        }

    }

    if (sid < 0) {

        int i,j;

        for (j=0; j<ts->stream->nb_programs; j++) {

            for (i = 0; i < ts->nb_prg; i++)

                if (ts->prg[i].id == ts->stream->programs[j]->id)

                    break;

            if (i==ts->nb_prg && !ts->skip_clear)

                clear_avprogram(ts, ts->stream->programs[j]->id);

        }

    }

}


int ff_wma_init(AVCodecContext * avctx, int flags2)
{
    WMACodecContext *s = avctx->priv_data;
    int i;
    float *window;
    float bps1, high_freq;
    volatile float bps;
    int sample_rate1;
    int coef_vlc_table;
    s->sample_rate = avctx->sample_rate;
    s->nb_channels = avctx->channels;
    s->bit_rate = avctx->bit_rate;
    s->block_align = avctx->block_align;
    dsputil_init(&s->dsp, avctx);
    if (avctx->codec->id == CODEC_ID_WMAV1) {
        s->version = 1;
    } else {
        s->version = 2;
    }
    /* compute MDCT block size */
    if (s->sample_rate <= 16000) {
        s->frame_len_bits = 9;
    } else if (s->sample_rate <= 22050 ||
               (s->sample_rate <= 32000 && s->version == 1)) {
        s->frame_len_bits = 10;
    } else {
        s->frame_len_bits = 11;
    }
    s->frame_len = 1 << s->frame_len_bits;
    if (s->use_variable_block_len) {
        int nb_max, nb;
        nb = ((flags2 >> 3) & 3) + 1;
        if ((s->bit_rate / s->nb_channels) >= 32000)
            nb += 2;
        nb_max = s->frame_len_bits - BLOCK_MIN_BITS;
        if (nb > nb_max)
            nb = nb_max;
        s->nb_block_sizes = nb + 1;
    } else {
        s->nb_block_sizes = 1;
    }
    /* init rate dependent parameters */
    s->use_noise_coding = 1;
    high_freq = s->sample_rate * 0.5;
    /* if version 2, then the rates are normalized */
    sample_rate1 = s->sample_rate;
    if (s->version == 2) {
        if (sample_rate1 >= 44100)
            sample_rate1 = 44100;
        else if (sample_rate1 >= 22050)
            sample_rate1 = 22050;
        else if (sample_rate1 >= 16000)
            sample_rate1 = 16000;
        else if (sample_rate1 >= 11025)
            sample_rate1 = 11025;
        else if (sample_rate1 >= 8000)
            sample_rate1 = 8000;
    }
    bps = (float)s->bit_rate / (float)(s->nb_channels * s->sample_rate);
    s->byte_offset_bits = av_log2((int)(bps * s->frame_len / 8.0 + 0.5)) + 2;
    /* compute high frequency value and choose if noise coding should
       be activated */
    bps1 = bps;
    if (s->nb_channels == 2)
        bps1 = bps * 1.6;
    if (sample_rate1 == 44100) {
        if (bps1 >= 0.61)
            s->use_noise_coding = 0;
        else
            high_freq = high_freq * 0.4;
    } else if (sample_rate1 == 22050) {
        if (bps1 >= 1.16)
            s->use_noise_coding = 0;
        else if (bps1 >= 0.72)
            high_freq = high_freq * 0.7;
        else
            high_freq = high_freq * 0.6;
    } else if (sample_rate1 == 16000) {
        if (bps > 0.5)
            high_freq = high_freq * 0.5;
        else
            high_freq = high_freq * 0.3;
    } else if (sample_rate1 == 11025) {
        high_freq = high_freq * 0.7;
    } else if (sample_rate1 == 8000) {
        if (bps <= 0.625) {
            high_freq = high_freq * 0.5;
        } else if (bps > 0.75) {
            s->use_noise_coding = 0;
        } else {
            high_freq = high_freq * 0.65;
        }
    } else {
        if (bps >= 0.8) {
            high_freq = high_freq * 0.75;
        } else if (bps >= 0.6) {
            high_freq = high_freq * 0.6;
        } else {
            high_freq = high_freq * 0.5;
        }
    }
    dprintf(s->avctx, "flags2=0x%x\n", flags2);
    dprintf(s->avctx, "version=%d channels=%d sample_rate=%d bitrate=%d block_align=%d\n",
           s->version, s->nb_channels, s->sample_rate, s->bit_rate,
           s->block_align);
    dprintf(s->avctx, "bps=%f bps1=%f high_freq=%f bitoffset=%d\n",
           bps, bps1, high_freq, s->byte_offset_bits);
    dprintf(s->avctx, "use_noise_coding=%d use_exp_vlc=%d nb_block_sizes=%d\n",
           s->use_noise_coding, s->use_exp_vlc, s->nb_block_sizes);
    /* compute the scale factor band sizes for each MDCT block size */
    {
        int a, b, pos, lpos, k, block_len, i, j, n;
        const uint8_t *table;
        if (s->version == 1) {
            s->coefs_start = 3;
        } else {
            s->coefs_start = 0;
        }
        for(k = 0; k < s->nb_block_sizes; k++) {
            block_len = s->frame_len >> k;
            if (s->version == 1) {
                lpos = 0;
                for(i=0;i<25;i++) {
                    a = wma_critical_freqs[i];
                    b = s->sample_rate;
                    pos = ((block_len * 2 * a)  + (b >> 1)) / b;
                    if (pos > block_len)
                        pos = block_len;
                    s->exponent_bands[0][i] = pos - lpos;
                    if (pos >= block_len) {
                        i++;
                        break;
                    }
                    lpos = pos;
                }
                s->exponent_sizes[0] = i;
            } else {
                /* hardcoded tables */
                table = NULL;
                a = s->frame_len_bits - BLOCK_MIN_BITS - k;
                if (a < 3) {
                    if (s->sample_rate >= 44100)
                        table = exponent_band_44100[a];
                    else if (s->sample_rate >= 32000)
                        table = exponent_band_32000[a];
                    else if (s->sample_rate >= 22050)
                        table = exponent_band_22050[a];
                }
                if (table) {
                    n = *table++;
                    for(i=0;i<n;i++)
                        s->exponent_bands[k][i] = table[i];
                    s->exponent_sizes[k] = n;
                } else {
                    j = 0;
                    lpos = 0;
                    for(i=0;i<25;i++) {
                        a = wma_critical_freqs[i];
                        b = s->sample_rate;
                        pos = ((block_len * 2 * a)  + (b << 1)) / (4 * b);
                        pos <<= 2;
                        if (pos > block_len)
                            pos = block_len;
                        if (pos > lpos)
                            s->exponent_bands[k][j++] = pos - lpos;
                        if (pos >= block_len)
                            break;
                        lpos = pos;
                    }
                    s->exponent_sizes[k] = j;
                }
            }
            /* max number of coefs */
            s->coefs_end[k] = (s->frame_len - ((s->frame_len * 9) / 100)) >> k;
            /* high freq computation */
            s->high_band_start[k] = (int)((block_len * 2 * high_freq) /
                                          s->sample_rate + 0.5);
            n = s->exponent_sizes[k];
            j = 0;
            pos = 0;
            for(i=0;i<n;i++) {
                int start, end;
                start = pos;
                pos += s->exponent_bands[k][i];
                end = pos;
                if (start < s->high_band_start[k])
                    start = s->high_band_start[k];
                if (end > s->coefs_end[k])
                    end = s->coefs_end[k];
                if (end > start)
                    s->exponent_high_bands[k][j++] = end - start;
            }
            s->exponent_high_sizes[k] = j;
#if 0
            tprintf(s->avctx, "%5d: coefs_end=%d high_band_start=%d nb_high_bands=%d: ",
                  s->frame_len >> k,
                  s->coefs_end[k],
                  s->high_band_start[k],
                  s->exponent_high_sizes[k]);
            for(j=0;j<s->exponent_high_sizes[k];j++)
                tprintf(s->avctx, " %d", s->exponent_high_bands[k][j]);
            tprintf(s->avctx, "\n");
#endif
        }
    }
#ifdef TRACE
    {
        int i, j;
        for(i = 0; i < s->nb_block_sizes; i++) {
            tprintf(s->avctx, "%5d: n=%2d:",
                   s->frame_len >> i,
                   s->exponent_sizes[i]);
            for(j=0;j<s->exponent_sizes[i];j++)
                tprintf(s->avctx, " %d", s->exponent_bands[i][j]);
            tprintf(s->avctx, "\n");
        }
    }
#endif
    /* init MDCT windows : simple sinus window */
    for(i = 0; i < s->nb_block_sizes; i++) {
        int n, j;
        float alpha;
        n = 1 << (s->frame_len_bits - i);
        window = av_malloc(sizeof(float) * n);
        alpha = M_PI / (2.0 * n);
        for(j=0;j<n;j++) {
            window[j] = sin((j + 0.5) * alpha);
        }
        s->windows[i] = window;
    }
    s->reset_block_lengths = 1;
    if (s->use_noise_coding) {
        /* init the noise generator */
        if (s->use_exp_vlc)
            s->noise_mult = 0.02;
        else
            s->noise_mult = 0.04;
#ifdef TRACE
        for(i=0;i<NOISE_TAB_SIZE;i++)
            s->noise_table[i] = 1.0 * s->noise_mult;
#else
        {
            unsigned int seed;
            float norm;
            seed = 1;
            norm = (1.0 / (float)(1LL << 31)) * sqrt(3) * s->noise_mult;
            for(i=0;i<NOISE_TAB_SIZE;i++) {
                seed = seed * 314159 + 1;
                s->noise_table[i] = (float)((int)seed) * norm;
            }
        }
#endif
    }
    /* choose the VLC tables for the coefficients */
    coef_vlc_table = 2;
    if (s->sample_rate >= 32000) {
        if (bps1 < 0.72)
            coef_vlc_table = 0;
        else if (bps1 < 1.16)
            coef_vlc_table = 1;
    }
    s->coef_vlcs[0]= &coef_vlcs[coef_vlc_table * 2    ];
    s->coef_vlcs[1]= &coef_vlcs[coef_vlc_table * 2 + 1];
    init_coef_vlc(&s->coef_vlc[0], &s->run_table[0], &s->level_table[0], &s->int_table[0],
                  s->coef_vlcs[0]);
    init_coef_vlc(&s->coef_vlc[1], &s->run_table[1], &s->level_table[1], &s->int_table[1],
                  s->coef_vlcs[1]);
    return 0;
}


void do_blockdev_backup(BlockdevBackup *backup, BlockJobTxn *txn, Error **errp)

{

    BlockDriverState *bs;

    BlockDriverState *target_bs;

    Error *local_err = NULL;

    AioContext *aio_context;

    if (!backup->has_speed) {

        backup->speed = 0;

    }

    if (!backup->has_on_source_error) {

        backup->on_source_error = BLOCKDEV_ON_ERROR_REPORT;

    }

    if (!backup->has_on_target_error) {

        backup->on_target_error = BLOCKDEV_ON_ERROR_REPORT;

    }

    if (!backup->has_job_id) {

        backup->job_id = NULL;

    }

    if (!backup->has_compress) {

        backup->compress = false;

    }

    bs = qmp_get_root_bs(backup->device, errp);

    if (!bs) {

        return;

    }

    aio_context = bdrv_get_aio_context(bs);

    aio_context_acquire(aio_context);

    target_bs = bdrv_lookup_bs(backup->target, backup->target, errp);

    if (!target_bs) {

        goto out;

    }

    if (bdrv_get_aio_context(target_bs) != aio_context) {

        if (!bdrv_has_blk(target_bs)) {

            /* The target BDS is not attached, we can safely move it to another

             * AioContext. */

            bdrv_set_aio_context(target_bs, aio_context);

        } else {

            error_setg(errp, "Target is attached to a different thread from "

                             "source.");

            goto out;

        }

    }

    backup_start(backup->job_id, bs, target_bs, backup->speed, backup->sync,

                 NULL, backup->compress, backup->on_source_error,

                 backup->on_target_error, BLOCK_JOB_DEFAULT,

                 NULL, NULL, txn, &local_err);

    if (local_err != NULL) {

        error_propagate(errp, local_err);

    }

out:

    aio_context_release(aio_context);

}


static int decode_extradata(AVFormatContext *s, ADTSContext *adts, uint8_t *buf, int size)

{

    GetBitContext gb;

    init_get_bits(&gb, buf, size * 8);

    adts->objecttype = get_bits(&gb, 5) - 1;

    adts->sample_rate_index = get_bits(&gb, 4);

    adts->channel_conf = get_bits(&gb, 4);

    if (adts->objecttype > 3) {

        av_log(s, AV_LOG_ERROR, "MPEG-4 AOT %d is not allowed in ADTS\n", adts->objecttype);

        return -1;

    }

    if (adts->sample_rate_index == 15) {

        av_log(s, AV_LOG_ERROR, "Escape sample rate index illegal in ADTS\n");

        return -1;

    }

    if (adts->channel_conf == 0) {

        ff_log_missing_feature(s, "PCE based channel configuration", 0);

        return -1;

    }

    adts->write_adts = 1;

    return 0;

}


static int scsi_write_data(SCSIDevice *d, uint32_t tag)

{

    SCSIGenericState *s = DO_UPCAST(SCSIGenericState, qdev, d);

    SCSIGenericReq *r;

    int ret;

    DPRINTF("scsi_write_data 0x%x\n", tag);

    r = scsi_find_request(s, tag);

    if (!r) {

        BADF("Bad write tag 0x%x\n", tag);

        /* ??? This is the wrong error.  */

        scsi_command_complete(r, -EINVAL);

        return 0;

    }

    if (r->len == 0) {

        r->len = r->buflen;

        scsi_req_data(&r->req, r->len);

        return 0;

    }

    ret = execute_command(s->bs, r, SG_DXFER_TO_DEV, scsi_write_complete);

    if (ret == -1) {

        scsi_command_complete(r, -EINVAL);

        return 1;

    }

    return 0;

}


static void sd_reset(SDState *sd, BlockDriverState *bdrv)

{

    uint64_t size;

    uint64_t sect;

    if (bdrv) {

        bdrv_get_geometry(bdrv, &sect);

    } else {

        sect = 0;

    }

    sect <<= 9;

    size = sect + 1;

    sect = (size >> (HWBLOCK_SHIFT + SECTOR_SHIFT + WPGROUP_SHIFT)) + 1;

    sd->state = sd_idle_state;

    sd->rca = 0x0000;

    sd_set_ocr(sd);

    sd_set_scr(sd);

    sd_set_cid(sd);

    sd_set_csd(sd, size);

    sd_set_cardstatus(sd);

    sd_set_sdstatus(sd);

    sd->bdrv = bdrv;

    if (sd->wp_groups)

        qemu_free(sd->wp_groups);

    sd->wp_switch = bdrv ? bdrv_is_read_only(bdrv) : 0;

    sd->wp_groups = (int *) qemu_mallocz(sizeof(int) * sect);

    memset(sd->function_group, 0, sizeof(int) * 6);

    sd->erase_start = 0;

    sd->erase_end = 0;

    sd->size = size;

    sd->blk_len = 0x200;

    sd->pwd_len = 0;

}


static void arm_idct_put(UINT8 *dest, int line_size, DCTELEM *block)

{

    j_rev_dct_ARM (block);

    put_pixels_clamped(block, dest, line_size);

}


int ff_lpc_calc_coefs(DSPContext *s,

                      const int32_t *samples, int blocksize, int max_order,

                      int precision, int32_t coefs[][MAX_LPC_ORDER],

                      int *shift, int use_lpc, int omethod, int max_shift, int zero_shift)

{

    double autoc[MAX_LPC_ORDER+1];

    double ref[MAX_LPC_ORDER];

    double lpc[MAX_LPC_ORDER][MAX_LPC_ORDER];

    int i, j, pass;

    int opt_order;

    assert(max_order >= MIN_LPC_ORDER && max_order <= MAX_LPC_ORDER);

    if(use_lpc == 1){

        s->flac_compute_autocorr(samples, blocksize, max_order, autoc);

        compute_lpc_coefs(autoc, max_order, lpc, ref);

    }else{

        LLSModel m[2];

        double var[MAX_LPC_ORDER+1], weight;

        for(pass=0; pass<use_lpc-1; pass++){

            av_init_lls(&m[pass&1], max_order);

            weight=0;

            for(i=max_order; i<blocksize; i++){

                for(j=0; j<=max_order; j++)

                    var[j]= samples[i-j];

                if(pass){

                    double eval, inv, rinv;

                    eval= av_evaluate_lls(&m[(pass-1)&1], var+1, max_order-1);

                    eval= (512>>pass) + fabs(eval - var[0]);

                    inv = 1/eval;

                    rinv = sqrt(inv);

                    for(j=0; j<=max_order; j++)

                        var[j] *= rinv;

                    weight += inv;

                }else

                    weight++;

                av_update_lls(&m[pass&1], var, 1.0);

            }

            av_solve_lls(&m[pass&1], 0.001, 0);

        }

        for(i=0; i<max_order; i++){

            for(j=0; j<max_order; j++)

                lpc[i][j]= m[(pass-1)&1].coeff[i][j];

            ref[i]= sqrt(m[(pass-1)&1].variance[i] / weight) * (blocksize - max_order) / 4000;

        }

        for(i=max_order-1; i>0; i--)

            ref[i] = ref[i-1] - ref[i];

    }

    opt_order = max_order;

    if(omethod == ORDER_METHOD_EST) {

        opt_order = estimate_best_order(ref, max_order);

        i = opt_order-1;

        quantize_lpc_coefs(lpc[i], i+1, precision, coefs[i], &shift[i], max_shift, zero_shift);

    } else {

        for(i=0; i<max_order; i++) {

            quantize_lpc_coefs(lpc[i], i+1, precision, coefs[i], &shift[i], max_shift, zero_shift);

        }

    }

    return opt_order;

}


static inline av_flatten int get_symbol_inline(RangeCoder *c, uint8_t *state,

                                               int is_signed)

{

    if (get_rac(c, state + 0))

        return 0;

    else {

        int i, e, a;

        e = 0;

        while (get_rac(c, state + 1 + FFMIN(e, 9))) // 1..10

            e++;

        a = 1;

        for (i = e - 1; i >= 0; i--)

            a += a + get_rac(c, state + 22 + FFMIN(i, 9));  // 22..31

        e = -(is_signed && get_rac(c, state + 11 + FFMIN(e, 10))); // 11..21

        return (a ^ e) - e;

    }

}