static void av_always_inline filter_mb_mbaff_edgev( H264Context *h, uint8_t *pix, int stride, const int16_t bS[7], int bsi, int qp, int intra ) {

    const int qp_bd_offset = 6 * (h->sps.bit_depth_luma - 8);

    int index_a = qp - qp_bd_offset + h->slice_alpha_c0_offset;

    int alpha = alpha_table[index_a];

    int beta  = beta_table[qp - qp_bd_offset + h->slice_beta_offset];

    if (alpha ==0 || beta == 0) return;

    if( bS[0] < 4 || !intra ) {

        int8_t tc[4];

        tc[0] = tc0_table[index_a][bS[0*bsi]];

        tc[1] = tc0_table[index_a][bS[1*bsi]];

        tc[2] = tc0_table[index_a][bS[2*bsi]];

        tc[3] = tc0_table[index_a][bS[3*bsi]];

        h->h264dsp.h264_h_loop_filter_luma_mbaff(pix, stride, alpha, beta, tc);

    } else {

        h->h264dsp.h264_h_loop_filter_luma_mbaff_intra(pix, stride, alpha, beta);

    }

}


static int config(struct vf_instance *vf,

        int width, int height, int d_width, int d_height,

        unsigned int flags, unsigned int outfmt){

        int i;

        AVCodec *enc= avcodec_find_encoder(AV_CODEC_ID_SNOW);

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

            int is_chroma= !!i;

            int w= ((width  + 4*BLOCK-1) & (~(2*BLOCK-1)))>>is_chroma;

            int h= ((height + 4*BLOCK-1) & (~(2*BLOCK-1)))>>is_chroma;

            vf->priv->temp_stride[i]= w;

            vf->priv->temp[i]= malloc(vf->priv->temp_stride[i]*h*sizeof(int16_t));

            vf->priv->src [i]= malloc(vf->priv->temp_stride[i]*h*sizeof(uint8_t));

        }

        for(i=0; i< (1<<vf->priv->log2_count); i++){

            AVCodecContext *avctx_enc;

            AVDictionary *opts = NULL;

            avctx_enc=

            vf->priv->avctx_enc[i]= avcodec_alloc_context3(NULL);

            avctx_enc->width = width + BLOCK;

            avctx_enc->height = height + BLOCK;

            avctx_enc->time_base= (AVRational){1,25};  // meaningless

            avctx_enc->gop_size = 300;

            avctx_enc->max_b_frames= 0;

            avctx_enc->pix_fmt = AV_PIX_FMT_YUV420P;

            avctx_enc->flags = CODEC_FLAG_QSCALE | CODEC_FLAG_LOW_DELAY;

            avctx_enc->strict_std_compliance = FF_COMPLIANCE_EXPERIMENTAL;

            avctx_enc->global_quality= 123;

            av_dict_set(&opts, "no_bitstream", "1", 0);

            avcodec_open2(avctx_enc, enc, &opts);

            av_dict_free(&opts);

            assert(avctx_enc->codec);

        }

        vf->priv->frame= av_frame_alloc();

        vf->priv->frame_dec= av_frame_alloc();

        vf->priv->outbuf_size= (width + BLOCK)*(height + BLOCK)*10;

        vf->priv->outbuf= malloc(vf->priv->outbuf_size);

        return ff_vf_next_config(vf,width,height,d_width,d_height,flags,outfmt);

}


double av_expr_eval(AVExpr *e, const double *const_values, void *opaque)

{

    Parser p;

    p.const_values = const_values;

    p.opaque     = opaque;

    return eval_expr(&p, e);

}


static void cirrus_bitblt_cputovideo_next(CirrusVGAState * s)

{

    int copy_count;

    uint8_t *end_ptr;

    if (s->cirrus_srccounter > 0) {

        if (s->cirrus_blt_mode & CIRRUS_BLTMODE_PATTERNCOPY) {

            cirrus_bitblt_common_patterncopy(s, false);

        the_end:

            s->cirrus_srccounter = 0;

            cirrus_bitblt_reset(s);

        } else {

            /* at least one scan line */

            do {

                (*s->cirrus_rop)(s, s->vga.vram_ptr + s->cirrus_blt_dstaddr,

                                  s->cirrus_bltbuf, 0, 0, s->cirrus_blt_width, 1);

                cirrus_invalidate_region(s, s->cirrus_blt_dstaddr, 0,

                                         s->cirrus_blt_width, 1);

                s->cirrus_blt_dstaddr += s->cirrus_blt_dstpitch;

                s->cirrus_srccounter -= s->cirrus_blt_srcpitch;

                if (s->cirrus_srccounter <= 0)

                    goto the_end;

                /* more bytes than needed can be transferred because of

                   word alignment, so we keep them for the next line */

                /* XXX: keep alignment to speed up transfer */

                end_ptr = s->cirrus_bltbuf + s->cirrus_blt_srcpitch;

                copy_count = s->cirrus_srcptr_end - end_ptr;

                memmove(s->cirrus_bltbuf, end_ptr, copy_count);

                s->cirrus_srcptr = s->cirrus_bltbuf + copy_count;

                s->cirrus_srcptr_end = s->cirrus_bltbuf + s->cirrus_blt_srcpitch;

            } while (s->cirrus_srcptr >= s->cirrus_srcptr_end);

        }

    }

}


static coroutine_fn int nbd_negotiate(NBDClient *client, Error **errp)

{

    char buf[8 + 8 + 8 + 128];

    int ret;

    const uint16_t myflags = (NBD_FLAG_HAS_FLAGS | NBD_FLAG_SEND_TRIM |

                              NBD_FLAG_SEND_FLUSH | NBD_FLAG_SEND_FUA |

                              NBD_FLAG_SEND_WRITE_ZEROES);

    bool oldStyle;

    /* Old style negotiation header without options

        [ 0 ..   7]   passwd       ("NBDMAGIC")

        [ 8 ..  15]   magic        (NBD_CLIENT_MAGIC)

        [16 ..  23]   size

        [24 ..  25]   server flags (0)

        [26 ..  27]   export flags

        [28 .. 151]   reserved     (0)

       New style negotiation header with options

        [ 0 ..   7]   passwd       ("NBDMAGIC")

        [ 8 ..  15]   magic        (NBD_OPTS_MAGIC)

        [16 ..  17]   server flags (0)

        ....options sent, ending in NBD_OPT_EXPORT_NAME or NBD_OPT_GO....

     */

    qio_channel_set_blocking(client->ioc, false, NULL);

    trace_nbd_negotiate_begin();

    memset(buf, 0, sizeof(buf));

    memcpy(buf, "NBDMAGIC", 8);

    oldStyle = client->exp != NULL && !client->tlscreds;

    if (oldStyle) {

        trace_nbd_negotiate_old_style(client->exp->size,

                                      client->exp->nbdflags | myflags);

        stq_be_p(buf + 8, NBD_CLIENT_MAGIC);

        stq_be_p(buf + 16, client->exp->size);

        stw_be_p(buf + 26, client->exp->nbdflags | myflags);

        if (nbd_write(client->ioc, buf, sizeof(buf), errp) < 0) {

            error_prepend(errp, "write failed: ");

            return -EINVAL;

        }

    } else {

        stq_be_p(buf + 8, NBD_OPTS_MAGIC);

        stw_be_p(buf + 16, NBD_FLAG_FIXED_NEWSTYLE | NBD_FLAG_NO_ZEROES);

        if (nbd_write(client->ioc, buf, 18, errp) < 0) {

            error_prepend(errp, "write failed: ");

            return -EINVAL;

        }

        ret = nbd_negotiate_options(client, myflags, errp);

        if (ret != 0) {

            if (ret < 0) {

                error_prepend(errp, "option negotiation failed: ");

            }

            return ret;

        }

    }

    trace_nbd_negotiate_success();

    return 0;

}


static void intel_hda_update_irq(IntelHDAState *d)

{

    bool msi = msi_enabled(&d->pci);

    int level;

    intel_hda_update_int_sts(d);

    if (d->int_sts & (1U << 31) && d->int_ctl & (1U << 31)) {

        level = 1;

    } else {

        level = 0;

    }

    dprint(d, 2, "%s: level %d [%s]\n", __FUNCTION__,

           level, msi ? "msi" : "intx");

    if (msi) {

        if (level) {

            msi_notify(&d->pci, 0);

        }

    } else {

        pci_set_irq(&d->pci, level);

    }

}


static void tcg_out_ext8s(TCGContext *s, int dest, int src, int rexw)

{

    /* movsbl */

    assert(src < 4 || TCG_TARGET_REG_BITS == 64);

    tcg_out_modrm(s, OPC_MOVSBL + P_REXB_RM + rexw, dest, src);

}


static void *bamboo_load_device_tree(target_phys_addr_t addr,

                                     uint32_t ramsize,

                                     target_phys_addr_t initrd_base,

                                     target_phys_addr_t initrd_size,

                                     const char *kernel_cmdline)

{

    void *fdt = NULL;

#ifdef CONFIG_FDT

    uint32_t mem_reg_property[] = { 0, 0, ramsize };

    char *filename;

    int fdt_size;

    int ret;

    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, BINARY_DEVICE_TREE_FILE);

    if (!filename) {

        goto out;

    }

    fdt = load_device_tree(filename, &fdt_size);

    qemu_free(filename);

    if (fdt == NULL) {

        goto out;

    }

    /* Manipulate device tree in memory. */

    ret = qemu_devtree_setprop(fdt, "/memory", "reg", mem_reg_property,

                               sizeof(mem_reg_property));

    if (ret < 0)

        fprintf(stderr, "couldn't set /memory/reg\n");

    ret = qemu_devtree_setprop_cell(fdt, "/chosen", "linux,initrd-start",

                                    initrd_base);

    if (ret < 0)

        fprintf(stderr, "couldn't set /chosen/linux,initrd-start\n");

    ret = qemu_devtree_setprop_cell(fdt, "/chosen", "linux,initrd-end",

                                    (initrd_base + initrd_size));

    if (ret < 0)

        fprintf(stderr, "couldn't set /chosen/linux,initrd-end\n");

    ret = qemu_devtree_setprop_string(fdt, "/chosen", "bootargs",

                                      kernel_cmdline);

    if (ret < 0)

        fprintf(stderr, "couldn't set /chosen/bootargs\n");

    if (kvm_enabled())

        kvmppc_fdt_update(fdt);

    cpu_physical_memory_write (addr, (void *)fdt, fdt_size);

out:

#endif

    return fdt;

}


static uint64_t lan9118_16bit_mode_read(void *opaque, target_phys_addr_t offset,

                                        unsigned size)

{

    switch (size) {

    case 2:

        return lan9118_readw(opaque, offset);

    case 4:

        return lan9118_readl(opaque, offset, size);

    }

    hw_error("lan9118_read: Bad size 0x%x\n", size);

    return 0;

}


static int local_lremovexattr(FsContext *ctx,

                              const char *path, const char *name)

{

    if ((ctx->fs_sm == SM_MAPPED) &&

        (strncmp(name, "user.virtfs.", 12) == 0)) {

        /*

         * Don't allow fetch of user.virtfs namesapce

         * in case of mapped security

         */

        errno = EACCES;

        return -1;

    }

    return lremovexattr(rpath(ctx, path), name);

}


static void nvic_writel(NVICState *s, uint32_t offset, uint32_t value,

                        MemTxAttrs attrs)

{

    ARMCPU *cpu = s->cpu;

    switch (offset) {

    case 0xd04: /* Interrupt Control State.  */

        if (value & (1 << 31)) {

            armv7m_nvic_set_pending(s, ARMV7M_EXCP_NMI);

        }

        if (value & (1 << 28)) {

            armv7m_nvic_set_pending(s, ARMV7M_EXCP_PENDSV);

        } else if (value & (1 << 27)) {

            armv7m_nvic_clear_pending(s, ARMV7M_EXCP_PENDSV);

        }

        if (value & (1 << 26)) {

            armv7m_nvic_set_pending(s, ARMV7M_EXCP_SYSTICK);

        } else if (value & (1 << 25)) {

            armv7m_nvic_clear_pending(s, ARMV7M_EXCP_SYSTICK);

        }

        break;

    case 0xd08: /* Vector Table Offset.  */

        cpu->env.v7m.vecbase[attrs.secure] = value & 0xffffff80;

        break;

    case 0xd0c: /* Application Interrupt/Reset Control.  */

        if ((value >> 16) == 0x05fa) {

            if (value & 4) {

                qemu_irq_pulse(s->sysresetreq);

            }

            if (value & 2) {

                qemu_log_mask(LOG_GUEST_ERROR,

                              "Setting VECTCLRACTIVE when not in DEBUG mode "

                              "is UNPREDICTABLE\n");

            }

            if (value & 1) {

                qemu_log_mask(LOG_GUEST_ERROR,

                              "Setting VECTRESET when not in DEBUG mode "

                              "is UNPREDICTABLE\n");

            }

            s->prigroup = extract32(value, 8, 3);

            nvic_irq_update(s);

        }

        break;

    case 0xd10: /* System Control.  */

        /* TODO: Implement control registers.  */

        qemu_log_mask(LOG_UNIMP, "NVIC: SCR unimplemented\n");

        break;

    case 0xd14: /* Configuration Control.  */

        /* Enforce RAZ/WI on reserved and must-RAZ/WI bits */

        value &= (R_V7M_CCR_STKALIGN_MASK |

                  R_V7M_CCR_BFHFNMIGN_MASK |

                  R_V7M_CCR_DIV_0_TRP_MASK |

                  R_V7M_CCR_UNALIGN_TRP_MASK |

                  R_V7M_CCR_USERSETMPEND_MASK |

                  R_V7M_CCR_NONBASETHRDENA_MASK);

        cpu->env.v7m.ccr = value;

        break;

    case 0xd24: /* System Handler Control.  */

        s->vectors[ARMV7M_EXCP_MEM].active = (value & (1 << 0)) != 0;

        s->vectors[ARMV7M_EXCP_BUS].active = (value & (1 << 1)) != 0;

        s->vectors[ARMV7M_EXCP_USAGE].active = (value & (1 << 3)) != 0;

        s->vectors[ARMV7M_EXCP_SVC].active = (value & (1 << 7)) != 0;

        s->vectors[ARMV7M_EXCP_DEBUG].active = (value & (1 << 8)) != 0;

        s->vectors[ARMV7M_EXCP_PENDSV].active = (value & (1 << 10)) != 0;

        s->vectors[ARMV7M_EXCP_SYSTICK].active = (value & (1 << 11)) != 0;

        s->vectors[ARMV7M_EXCP_USAGE].pending = (value & (1 << 12)) != 0;

        s->vectors[ARMV7M_EXCP_MEM].pending = (value & (1 << 13)) != 0;

        s->vectors[ARMV7M_EXCP_BUS].pending = (value & (1 << 14)) != 0;

        s->vectors[ARMV7M_EXCP_SVC].pending = (value & (1 << 15)) != 0;

        s->vectors[ARMV7M_EXCP_MEM].enabled = (value & (1 << 16)) != 0;

        s->vectors[ARMV7M_EXCP_BUS].enabled = (value & (1 << 17)) != 0;

        s->vectors[ARMV7M_EXCP_USAGE].enabled = (value & (1 << 18)) != 0;

        nvic_irq_update(s);

        break;

    case 0xd28: /* Configurable Fault Status.  */

        cpu->env.v7m.cfsr &= ~value; /* W1C */

        break;

    case 0xd2c: /* Hard Fault Status.  */

        cpu->env.v7m.hfsr &= ~value; /* W1C */

        break;

    case 0xd30: /* Debug Fault Status.  */

        cpu->env.v7m.dfsr &= ~value; /* W1C */

        break;

    case 0xd34: /* Mem Manage Address.  */

        cpu->env.v7m.mmfar = value;

        return;

    case 0xd38: /* Bus Fault Address.  */

        cpu->env.v7m.bfar = value;

        return;

    case 0xd3c: /* Aux Fault Status.  */

        qemu_log_mask(LOG_UNIMP,

                      "NVIC: Aux fault status registers unimplemented\n");

        break;

    case 0xd90: /* MPU_TYPE */

        return; /* RO */

    case 0xd94: /* MPU_CTRL */

        if ((value &

             (R_V7M_MPU_CTRL_HFNMIENA_MASK | R_V7M_MPU_CTRL_ENABLE_MASK))

            == R_V7M_MPU_CTRL_HFNMIENA_MASK) {

            qemu_log_mask(LOG_GUEST_ERROR, "MPU_CTRL: HFNMIENA and !ENABLE is "

                          "UNPREDICTABLE\n");

        }

        cpu->env.v7m.mpu_ctrl = value & (R_V7M_MPU_CTRL_ENABLE_MASK |

                                         R_V7M_MPU_CTRL_HFNMIENA_MASK |

                                         R_V7M_MPU_CTRL_PRIVDEFENA_MASK);

        tlb_flush(CPU(cpu));

        break;

    case 0xd98: /* MPU_RNR */

        if (value >= cpu->pmsav7_dregion) {

            qemu_log_mask(LOG_GUEST_ERROR, "MPU region out of range %"

                          PRIu32 "/%" PRIu32 "\n",

                          value, cpu->pmsav7_dregion);

        } else {

            cpu->env.pmsav7.rnr = value;

        }

        break;

    case 0xd9c: /* MPU_RBAR */

    case 0xda4: /* MPU_RBAR_A1 */

    case 0xdac: /* MPU_RBAR_A2 */

    case 0xdb4: /* MPU_RBAR_A3 */

    {

        int region;

        if (arm_feature(&cpu->env, ARM_FEATURE_V8)) {

            /* PMSAv8M handling of the aliases is different from v7M:

             * aliases A1, A2, A3 override the low two bits of the region

             * number in MPU_RNR, and there is no 'region' field in the

             * RBAR register.

             */

            int aliasno = (offset - 0xd9c) / 8; /* 0..3 */

            region = cpu->env.pmsav7.rnr;

            if (aliasno) {

                region = deposit32(region, 0, 2, aliasno);

            }

            if (region >= cpu->pmsav7_dregion) {

                return;

            }

            cpu->env.pmsav8.rbar[attrs.secure][region] = value;

            tlb_flush(CPU(cpu));

            return;

        }

        if (value & (1 << 4)) {

            /* VALID bit means use the region number specified in this

             * value and also update MPU_RNR.REGION with that value.

             */

            region = extract32(value, 0, 4);

            if (region >= cpu->pmsav7_dregion) {

                qemu_log_mask(LOG_GUEST_ERROR,

                              "MPU region out of range %u/%" PRIu32 "\n",

                              region, cpu->pmsav7_dregion);

                return;

            }

            cpu->env.pmsav7.rnr = region;

        } else {

            region = cpu->env.pmsav7.rnr;

        }

        if (region >= cpu->pmsav7_dregion) {

            return;

        }

        cpu->env.pmsav7.drbar[region] = value & ~0x1f;

        tlb_flush(CPU(cpu));

        break;

    }

    case 0xda0: /* MPU_RASR (v7M), MPU_RLAR (v8M) */

    case 0xda8: /* MPU_RASR_A1 (v7M), MPU_RLAR_A1 (v8M) */

    case 0xdb0: /* MPU_RASR_A2 (v7M), MPU_RLAR_A2 (v8M) */

    case 0xdb8: /* MPU_RASR_A3 (v7M), MPU_RLAR_A3 (v8M) */

    {

        int region = cpu->env.pmsav7.rnr;

        if (arm_feature(&cpu->env, ARM_FEATURE_V8)) {

            /* PMSAv8M handling of the aliases is different from v7M:

             * aliases A1, A2, A3 override the low two bits of the region

             * number in MPU_RNR.

             */

            int aliasno = (offset - 0xd9c) / 8; /* 0..3 */

            region = cpu->env.pmsav7.rnr;

            if (aliasno) {

                region = deposit32(region, 0, 2, aliasno);

            }

            if (region >= cpu->pmsav7_dregion) {

                return;

            }

            cpu->env.pmsav8.rlar[attrs.secure][region] = value;

            tlb_flush(CPU(cpu));

            return;

        }

        if (region >= cpu->pmsav7_dregion) {

            return;

        }

        cpu->env.pmsav7.drsr[region] = value & 0xff3f;

        cpu->env.pmsav7.dracr[region] = (value >> 16) & 0x173f;

        tlb_flush(CPU(cpu));

        break;

    }

    case 0xdc0: /* MPU_MAIR0 */

        if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {

            goto bad_offset;

        }

        if (cpu->pmsav7_dregion) {

            /* Register is RES0 if no MPU regions are implemented */

            cpu->env.pmsav8.mair0[attrs.secure] = value;

        }

        /* We don't need to do anything else because memory attributes

         * only affect cacheability, and we don't implement caching.

         */

        break;

    case 0xdc4: /* MPU_MAIR1 */

        if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {

            goto bad_offset;

        }

        if (cpu->pmsav7_dregion) {

            /* Register is RES0 if no MPU regions are implemented */

            cpu->env.pmsav8.mair1[attrs.secure] = value;

        }

        /* We don't need to do anything else because memory attributes

         * only affect cacheability, and we don't implement caching.

         */

        break;

    case 0xf00: /* Software Triggered Interrupt Register */

    {

        int excnum = (value & 0x1ff) + NVIC_FIRST_IRQ;

        if (excnum < s->num_irq) {

            armv7m_nvic_set_pending(s, excnum);

        }

        break;

    }

    default:

    bad_offset:

        qemu_log_mask(LOG_GUEST_ERROR,

                      "NVIC: Bad write offset 0x%x\n", offset);

    }

}


static int start_auth_vencrypt(VncState *vs)

{

    /* Send VeNCrypt version 0.2 */

    vnc_write_u8(vs, 0);

    vnc_write_u8(vs, 2);

    vnc_read_when(vs, protocol_client_vencrypt_init, 2);

    return 0;

}


static void gen_dmfc0(DisasContext *ctx, TCGv arg, int reg, int sel)

{

    const char *rn = "invalid";

    if (sel != 0)

        check_insn(ctx, ISA_MIPS64);

    switch (reg) {

    case 0:

        switch (sel) {

        case 0:

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Index));

            rn = "Index";

            break;

        case 1:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mfc0_mvpcontrol(arg, cpu_env);

            rn = "MVPControl";

            break;

        case 2:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mfc0_mvpconf0(arg, cpu_env);

            rn = "MVPConf0";

            break;

        case 3:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mfc0_mvpconf1(arg, cpu_env);

            rn = "MVPConf1";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 1:

        switch (sel) {

        case 0:

            CP0_CHECK(!(ctx->insn_flags & ISA_MIPS32R6));

            gen_helper_mfc0_random(arg, cpu_env);

            rn = "Random";

            break;

        case 1:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_VPEControl));

            rn = "VPEControl";

            break;

        case 2:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_VPEConf0));

            rn = "VPEConf0";

            break;

        case 3:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_VPEConf1));

            rn = "VPEConf1";

            break;

        case 4:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            tcg_gen_ld_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_YQMask));

            rn = "YQMask";

            break;

        case 5:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            tcg_gen_ld_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_VPESchedule));

            rn = "VPESchedule";

            break;

        case 6:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            tcg_gen_ld_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_VPEScheFBack));

            rn = "VPEScheFBack";

            break;

        case 7:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_VPEOpt));

            rn = "VPEOpt";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 2:

        switch (sel) {

        case 0:

            tcg_gen_ld_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_EntryLo0));

            rn = "EntryLo0";

            break;

        case 1:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mfc0_tcstatus(arg, cpu_env);

            rn = "TCStatus";

            break;

        case 2:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_mfc0_tcbind(arg, cpu_env);

            rn = "TCBind";

            break;

        case 3:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_dmfc0_tcrestart(arg, cpu_env);

            rn = "TCRestart";

            break;

        case 4:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_dmfc0_tchalt(arg, cpu_env);

            rn = "TCHalt";

            break;

        case 5:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_dmfc0_tccontext(arg, cpu_env);

            rn = "TCContext";

            break;

        case 6:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_dmfc0_tcschedule(arg, cpu_env);

            rn = "TCSchedule";

            break;

        case 7:

            CP0_CHECK(ctx->insn_flags & ASE_MT);

            gen_helper_dmfc0_tcschefback(arg, cpu_env);

            rn = "TCScheFBack";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 3:

        switch (sel) {

        case 0:

            tcg_gen_ld_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_EntryLo1));

            rn = "EntryLo1";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 4:

        switch (sel) {

        case 0:

            tcg_gen_ld_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_Context));

            rn = "Context";

            break;

        case 1:

//            gen_helper_dmfc0_contextconfig(arg); /* SmartMIPS ASE */

            rn = "ContextConfig";

            goto cp0_unimplemented;

//            break;

        case 2:

            CP0_CHECK(ctx->ulri);

            tcg_gen_ld_tl(arg, cpu_env,

                          offsetof(CPUMIPSState, active_tc.CP0_UserLocal));

            rn = "UserLocal";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 5:

        switch (sel) {

        case 0:

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_PageMask));

            rn = "PageMask";

            break;

        case 1:

            check_insn(ctx, ISA_MIPS32R2);

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_PageGrain));

            rn = "PageGrain";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 6:

        switch (sel) {

        case 0:

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Wired));

            rn = "Wired";

            break;

        case 1:

            check_insn(ctx, ISA_MIPS32R2);

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_SRSConf0));

            rn = "SRSConf0";

            break;

        case 2:

            check_insn(ctx, ISA_MIPS32R2);

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_SRSConf1));

            rn = "SRSConf1";

            break;

        case 3:

            check_insn(ctx, ISA_MIPS32R2);

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_SRSConf2));

            rn = "SRSConf2";

            break;

        case 4:

            check_insn(ctx, ISA_MIPS32R2);

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_SRSConf3));

            rn = "SRSConf3";

            break;

        case 5:

            check_insn(ctx, ISA_MIPS32R2);

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_SRSConf4));

            rn = "SRSConf4";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 7:

        switch (sel) {

        case 0:

            check_insn(ctx, ISA_MIPS32R2);

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_HWREna));

            rn = "HWREna";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 8:

        switch (sel) {

        case 0:

            tcg_gen_ld_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_BadVAddr));

            rn = "BadVAddr";

            break;

        case 1:

            CP0_CHECK(ctx->bi);

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_BadInstr));

            rn = "BadInstr";

            break;

        case 2:

            CP0_CHECK(ctx->bp);

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_BadInstrP));

            rn = "BadInstrP";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 9:

        switch (sel) {

        case 0:

            /* Mark as an IO operation because we read the time.  */

            if (use_icount)

                gen_io_start();

            gen_helper_mfc0_count(arg, cpu_env);

            if (use_icount) {

                gen_io_end();

            }

            /* Break the TB to be able to take timer interrupts immediately

               after reading count.  */

            ctx->bstate = BS_STOP;

            rn = "Count";

            break;

        /* 6,7 are implementation dependent */

        default:

            goto cp0_unimplemented;

        }

        break;

    case 10:

        switch (sel) {

        case 0:

            tcg_gen_ld_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_EntryHi));

            rn = "EntryHi";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 11:

        switch (sel) {

        case 0:

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Compare));

            rn = "Compare";

            break;

        /* 6,7 are implementation dependent */

        default:

            goto cp0_unimplemented;

        }

        break;

    case 12:

        switch (sel) {

        case 0:

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Status));

            rn = "Status";

            break;

        case 1:

            check_insn(ctx, ISA_MIPS32R2);

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_IntCtl));

            rn = "IntCtl";

            break;

        case 2:

            check_insn(ctx, ISA_MIPS32R2);

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_SRSCtl));

            rn = "SRSCtl";

            break;

        case 3:

            check_insn(ctx, ISA_MIPS32R2);

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_SRSMap));

            rn = "SRSMap";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 13:

        switch (sel) {

        case 0:

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Cause));

            rn = "Cause";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 14:

        switch (sel) {

        case 0:

            tcg_gen_ld_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_EPC));

            rn = "EPC";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 15:

        switch (sel) {

        case 0:

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_PRid));

            rn = "PRid";

            break;

        case 1:

            check_insn(ctx, ISA_MIPS32R2);

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_EBase));

            rn = "EBase";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 16:

        switch (sel) {

        case 0:

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Config0));

            rn = "Config";

            break;

        case 1:

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Config1));

            rn = "Config1";

            break;

        case 2:

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Config2));

            rn = "Config2";

            break;

        case 3:

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Config3));

            rn = "Config3";

            break;

        case 4:

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Config4));

            rn = "Config4";

            break;

        case 5:

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Config5));

            rn = "Config5";

            break;

       /* 6,7 are implementation dependent */

        case 6:

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Config6));

            rn = "Config6";

            break;

        case 7:

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Config7));

            rn = "Config7";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 17:

        switch (sel) {

        case 0:

            gen_helper_dmfc0_lladdr(arg, cpu_env);

            rn = "LLAddr";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 18:

        switch (sel) {

        case 0 ... 7:

            gen_helper_1e0i(dmfc0_watchlo, arg, sel);

            rn = "WatchLo";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 19:

        switch (sel) {

        case 0 ... 7:

            gen_helper_1e0i(mfc0_watchhi, arg, sel);

            rn = "WatchHi";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 20:

        switch (sel) {

        case 0:

            check_insn(ctx, ISA_MIPS3);

            tcg_gen_ld_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_XContext));

            rn = "XContext";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 21:

       /* Officially reserved, but sel 0 is used for R1x000 framemask */

        CP0_CHECK(!(ctx->insn_flags & ISA_MIPS32R6));

        switch (sel) {

        case 0:

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Framemask));

            rn = "Framemask";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 22:

        tcg_gen_movi_tl(arg, 0); /* unimplemented */

        rn = "'Diagnostic"; /* implementation dependent */

        break;

    case 23:

        switch (sel) {

        case 0:

            gen_helper_mfc0_debug(arg, cpu_env); /* EJTAG support */

            rn = "Debug";

            break;

        case 1:

//            gen_helper_dmfc0_tracecontrol(arg, cpu_env); /* PDtrace support */

            rn = "TraceControl";

//            break;

        case 2:

//            gen_helper_dmfc0_tracecontrol2(arg, cpu_env); /* PDtrace support */

            rn = "TraceControl2";

//            break;

        case 3:

//            gen_helper_dmfc0_usertracedata(arg, cpu_env); /* PDtrace support */

            rn = "UserTraceData";

//            break;

        case 4:

//            gen_helper_dmfc0_tracebpc(arg, cpu_env); /* PDtrace support */

            rn = "TraceBPC";

//            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 24:

        switch (sel) {

        case 0:

            /* EJTAG support */

            tcg_gen_ld_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_DEPC));

            rn = "DEPC";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 25:

        switch (sel) {

        case 0:

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_Performance0));

            rn = "Performance0";

            break;

        case 1:

//            gen_helper_dmfc0_performance1(arg);

            rn = "Performance1";

//            break;

        case 2:

//            gen_helper_dmfc0_performance2(arg);

            rn = "Performance2";

//            break;

        case 3:

//            gen_helper_dmfc0_performance3(arg);

            rn = "Performance3";

//            break;

        case 4:

//            gen_helper_dmfc0_performance4(arg);

            rn = "Performance4";

//            break;

        case 5:

//            gen_helper_dmfc0_performance5(arg);

            rn = "Performance5";

//            break;

        case 6:

//            gen_helper_dmfc0_performance6(arg);

            rn = "Performance6";

//            break;

        case 7:

//            gen_helper_dmfc0_performance7(arg);

            rn = "Performance7";

//            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 26:

        tcg_gen_movi_tl(arg, 0); /* unimplemented */

        rn = "ECC";

        break;

    case 27:

        switch (sel) {

        /* ignored */

        case 0 ... 3:

            tcg_gen_movi_tl(arg, 0); /* unimplemented */

            rn = "CacheErr";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 28:

        switch (sel) {

        case 0:

        case 2:

        case 4:

        case 6:

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_TagLo));

            rn = "TagLo";

            break;

        case 1:

        case 3:

        case 5:

        case 7:

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_DataLo));

            rn = "DataLo";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 29:

        switch (sel) {

        case 0:

        case 2:

        case 4:

        case 6:

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_TagHi));

            rn = "TagHi";

            break;

        case 1:

        case 3:

        case 5:

        case 7:

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_DataHi));

            rn = "DataHi";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 30:

        switch (sel) {

        case 0:

            tcg_gen_ld_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_ErrorEPC));

            rn = "ErrorEPC";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    case 31:

        switch (sel) {

        case 0:

            /* EJTAG support */

            gen_mfc0_load32(arg, offsetof(CPUMIPSState, CP0_DESAVE));

            rn = "DESAVE";

            break;

        case 2 ... 7:

            CP0_CHECK(ctx->kscrexist & (1 << sel));

            tcg_gen_ld_tl(arg, cpu_env,

                          offsetof(CPUMIPSState, CP0_KScratch[sel-2]));

            rn = "KScratch";

            break;

        default:

            goto cp0_unimplemented;

        }

        break;

    default:

        goto cp0_unimplemented;

    }

    (void)rn; /* avoid a compiler warning */

    LOG_DISAS("dmfc0 %s (reg %d sel %d)\n", rn, reg, sel);

    return;

cp0_unimplemented:

    LOG_DISAS("dmfc0 %s (reg %d sel %d)\n", rn, reg, sel);

    gen_mfc0_unimplemented(ctx, arg);

}


static int avi_read_idx1(AVFormatContext *s, int size)

{

    AVIContext *avi = s->priv_data;

    AVIOContext *pb = s->pb;

    int nb_index_entries, i;

    AVStream *st;

    AVIStream *ast;

    unsigned int index, tag, flags, pos, len, first_packet = 1;

    unsigned last_pos= -1;

    int64_t idx1_pos, first_packet_pos = 0, data_offset = 0;

    nb_index_entries = size / 16;

    if (nb_index_entries <= 0)

        return -1;

    idx1_pos = avio_tell(pb);

    avio_seek(pb, avi->movi_list+4, SEEK_SET);

    if (avi_sync(s, 1) == 0) {

        first_packet_pos = avio_tell(pb) - 8;

    }

    avi->stream_index = -1;

    avio_seek(pb, idx1_pos, SEEK_SET);

    /* Read the entries and sort them in each stream component. */

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

        tag = avio_rl32(pb);

        flags = avio_rl32(pb);

        pos = avio_rl32(pb);

        len = avio_rl32(pb);

        av_dlog(s, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",

                i, tag, flags, pos, len);

        index = ((tag & 0xff) - '0') * 10;

        index += ((tag >> 8) & 0xff) - '0';

        if (index >= s->nb_streams)

            continue;

        st = s->streams[index];

        ast = st->priv_data;

        if(first_packet && first_packet_pos && len) {

            data_offset = first_packet_pos - pos;

            first_packet = 0;

        }

        pos += data_offset;

        av_dlog(s, "%d cum_len=%"PRId64"\n", len, ast->cum_len);

        if(pb->eof_reached)

            return -1;

        if(last_pos == pos)

            avi->non_interleaved= 1;

        else if(len || !ast->sample_size)

            av_add_index_entry(st, pos, ast->cum_len, len, 0, (flags&AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);

        ast->cum_len += get_duration(ast, len);

        last_pos= pos;

    }

    return 0;

}


nvdimm_build_structure_memdev(GArray *structures, DeviceState *dev)

{

    NvdimmNfitMemDev *nfit_memdev;

    uint64_t addr = object_property_get_int(OBJECT(dev), PC_DIMM_ADDR_PROP,

                                            NULL);

    uint64_t size = object_property_get_int(OBJECT(dev), PC_DIMM_SIZE_PROP,

                                            NULL);

    int slot = object_property_get_int(OBJECT(dev), PC_DIMM_SLOT_PROP,

                                            NULL);

    uint32_t handle = nvdimm_slot_to_handle(slot);

    nfit_memdev = acpi_data_push(structures, sizeof(*nfit_memdev));

    nfit_memdev->type = cpu_to_le16(1 /* Memory Device to System Address

                                         Range Map Structure*/);

    nfit_memdev->length = cpu_to_le16(sizeof(*nfit_memdev));

    nfit_memdev->nfit_handle = cpu_to_le32(handle);

    /*

     * associate memory device with System Physical Address Range

     * Structure.

     */

    nfit_memdev->spa_index = cpu_to_le16(nvdimm_slot_to_spa_index(slot));

    /* associate memory device with Control Region Structure. */

    nfit_memdev->dcr_index = cpu_to_le16(nvdimm_slot_to_dcr_index(slot));

    /* The memory region on the device. */

    nfit_memdev->region_len = cpu_to_le64(size);

    nfit_memdev->region_dpa = cpu_to_le64(addr);

    /* Only one interleave for PMEM. */

    nfit_memdev->interleave_ways = cpu_to_le16(1);

}


static void apic_reset(void *opaque)

{

    APICState *s = opaque;

    int bsp = cpu_is_bsp(s->cpu_env);

    s->apicbase = 0xfee00000 |

        (bsp ? MSR_IA32_APICBASE_BSP : 0) | MSR_IA32_APICBASE_ENABLE;

    apic_init_ipi(s);

    if (bsp) {

        /*

         * LINT0 delivery mode on CPU #0 is set to ExtInt at initialization

         * time typically by BIOS, so PIC interrupt can be delivered to the

         * processor when local APIC is enabled.

         */

        s->lvt[APIC_LVT_LINT0] = 0x700;

    }

}


static void mipsnet_cleanup(NetClientState *nc)

{

    MIPSnetState *s = qemu_get_nic_opaque(nc);

    s->nic = NULL;

}


int virtio_set_status(VirtIODevice *vdev, uint8_t val)

{

    VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);

    trace_virtio_set_status(vdev, val);

    if (virtio_has_feature(vdev, VIRTIO_F_VERSION_1)) {

        if (!(vdev->status & VIRTIO_CONFIG_S_FEATURES_OK) &&

            val & VIRTIO_CONFIG_S_FEATURES_OK) {

            int ret = virtio_validate_features(vdev);

            if (ret) {

                return ret;

            }

        }

    }

    if (k->set_status) {

        k->set_status(vdev, val);

    }

    vdev->status = val;

    return 0;

}


START_TEST(unterminated_string)

{

    QObject *obj = qobject_from_json("\"abc");

    fail_unless(obj == NULL);

}


qio_channel_socket_accept(QIOChannelSocket *ioc,

                          Error **errp)

{

    QIOChannelSocket *cioc;

    cioc = QIO_CHANNEL_SOCKET(object_new(TYPE_QIO_CHANNEL_SOCKET));

    cioc->fd = -1;

    cioc->remoteAddrLen = sizeof(ioc->remoteAddr);

    cioc->localAddrLen = sizeof(ioc->localAddr);

#ifdef WIN32

    QIO_CHANNEL(cioc)->event = CreateEvent(NULL, FALSE, FALSE, NULL);

#endif

 retry:

    trace_qio_channel_socket_accept(ioc);

    cioc->fd = qemu_accept(ioc->fd, (struct sockaddr *)&cioc->remoteAddr,

                           &cioc->remoteAddrLen);

    if (cioc->fd < 0) {

        trace_qio_channel_socket_accept_fail(ioc);

        if (errno == EINTR) {

            goto retry;

        }

        goto error;

    }

    if (getsockname(cioc->fd, (struct sockaddr *)&cioc->localAddr,

                    &cioc->localAddrLen) < 0) {

        error_setg_errno(errp, errno,

                         "Unable to query local socket address");

        goto error;

    }

#ifndef WIN32

    if (cioc->localAddr.ss_family == AF_UNIX) {

        QIOChannel *ioc_local = QIO_CHANNEL(cioc);

        qio_channel_set_feature(ioc_local, QIO_CHANNEL_FEATURE_FD_PASS);

    }

#endif /* WIN32 */

    trace_qio_channel_socket_accept_complete(ioc, cioc, cioc->fd);

    return cioc;

 error:

    object_unref(OBJECT(cioc));

    return NULL;

}


static av_cold int encode_init_ls(AVCodecContext *ctx)

{

    ctx->coded_frame = av_frame_alloc();

    if (!ctx->coded_frame)

        return AVERROR(ENOMEM);

    ctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;

    ctx->coded_frame->key_frame = 1;

    if (ctx->pix_fmt != AV_PIX_FMT_GRAY8  &&

        ctx->pix_fmt != AV_PIX_FMT_GRAY16 &&

        ctx->pix_fmt != AV_PIX_FMT_RGB24  &&

        ctx->pix_fmt != AV_PIX_FMT_BGR24) {

        av_log(ctx, AV_LOG_ERROR,

               "Only grayscale and RGB24/BGR24 images are supported\n");

        return -1;

    }

    return 0;

}


static int mov_flush_fragment(AVFormatContext *s)

{

    MOVMuxContext *mov = s->priv_data;

    int i, first_track = -1;

    int64_t mdat_size = 0;

    if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))

        return 0;

    if (mov->fragments == 0) {

        int64_t pos = avio_tell(s->pb);

        uint8_t *buf;

        int buf_size, moov_size;

        for (i = 0; i < mov->nb_streams; i++)

            if (!mov->tracks[i].entry)

                break;

        /* Don't write the initial moov unless all tracks have data */

        if (i < mov->nb_streams)

            return 0;

        moov_size = get_moov_size(s);

        for (i = 0; i < mov->nb_streams; i++)

            mov->tracks[i].data_offset = pos + moov_size + 8;

        if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)

            mov_write_identification(s->pb, s);

        mov_write_moov_tag(s->pb, mov, s);

        if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) {

            if (mov->flags & FF_MOV_FLAG_FASTSTART)

                mov->reserved_moov_pos = avio_tell(s->pb);

            avio_flush(s->pb);

            mov->fragments++;

            return 0;

        }

        buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);

        mov->mdat_buf = NULL;

        avio_wb32(s->pb, buf_size + 8);

        ffio_wfourcc(s->pb, "mdat");

        avio_write(s->pb, buf, buf_size);

        av_free(buf);

        mov->fragments++;

        mov->mdat_size = 0;

        for (i = 0; i < mov->nb_streams; i++) {

            if (mov->tracks[i].entry)

                mov->tracks[i].frag_start += mov->tracks[i].start_dts +

                                             mov->tracks[i].track_duration -

                                             mov->tracks[i].cluster[0].dts;

            mov->tracks[i].entry = 0;

        }

        avio_flush(s->pb);

        return 0;

    }

    for (i = 0; i < mov->nb_streams; i++) {

        MOVTrack *track = &mov->tracks[i];

        if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF)

            track->data_offset = 0;

        else

            track->data_offset = mdat_size;

        if (!track->mdat_buf)

            continue;

        mdat_size += avio_tell(track->mdat_buf);

        if (first_track < 0)

            first_track = i;

    }

    if (!mdat_size)

        return 0;

    for (i = 0; i < mov->nb_streams; i++) {

        MOVTrack *track = &mov->tracks[i];

        int buf_size, write_moof = 1, moof_tracks = -1;

        uint8_t *buf;

        int64_t duration = 0;

        if (track->entry)

            duration = track->start_dts + track->track_duration -

                       track->cluster[0].dts;

        if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {

            if (!track->mdat_buf)

                continue;

            mdat_size = avio_tell(track->mdat_buf);

            moof_tracks = i;

        } else {

            write_moof = i == first_track;

        }

        if (write_moof) {

            avio_flush(s->pb);

            mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size);

            mov->fragments++;

            avio_wb32(s->pb, mdat_size + 8);

            ffio_wfourcc(s->pb, "mdat");

        }

        if (track->entry)

            track->frag_start += duration;

        track->entry = 0;

        if (!track->mdat_buf)

            continue;

        buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);

        track->mdat_buf = NULL;

        avio_write(s->pb, buf, buf_size);

        av_free(buf);

    }

    mov->mdat_size = 0;

    avio_flush(s->pb);

    return 0;

}


void dsputil_init_mmi(void)

{

    clear_blocks = clear_blocks_mmi;

    put_pixels_tab[1][0] = put_pixels8_mmi;

    put_no_rnd_pixels_tab[1][0] = put_pixels8_mmi;

    put_pixels_tab[0][0] = put_pixels16_mmi;

    put_no_rnd_pixels_tab[0][0] = put_pixels16_mmi;

    get_pixels = get_pixels_mmi;

}


static void usbredir_put_bufpq(QEMUFile *f, void *priv, size_t unused)

{

    struct endp_data *endp = priv;

    USBRedirDevice *dev = endp->dev;

    struct buf_packet *bufp;

    int i = 0;

    qemu_put_be32(f, endp->bufpq_size);

    QTAILQ_FOREACH(bufp, &endp->bufpq, next) {

        DPRINTF("put_bufpq %d/%d len %d status %d\n", i + 1, endp->bufpq_size,

                bufp->len, bufp->status);

        qemu_put_be32(f, bufp->len);

        qemu_put_be32(f, bufp->status);

        qemu_put_buffer(f, bufp->data, bufp->len);

        i++;

    }

    assert(i == endp->bufpq_size);

}


void palette8tobgr15(const uint8_t *src, uint8_t *dst, long num_pixels, const uint8_t *palette)

{

	long i;

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

		((uint16_t *)dst)[i] = bswap_16(((uint16_t *)palette)[ src[i] ]);

}


static inline int16_t mipsdsp_sat_add_i16(int16_t a, int16_t b,

                                          CPUMIPSState *env)

{

    int16_t tempS;

    tempS = a + b;

    if (MIPSDSP_OVERFLOW(a, b, tempS, 0x8000)) {

        if (a > 0) {

            tempS = 0x7FFF;

        } else {

            tempS = 0x8000;

        }

        set_DSPControl_overflow_flag(1, 20, env);

    }

    return tempS;

}


static int config(struct vf_instance *vf,

                  int width, int height, int d_width, int d_height,

                  unsigned int flags, unsigned int outfmt)

{

        /* FIXME - also support UYVY output? */

        return ff_vf_next_config(vf, width * vf->priv->scalew,

                              height / vf->priv->scaleh - vf->priv->skipline, d_width, d_height, flags, IMGFMT_YV12);

}


void av_register_input_format(AVInputFormat *format)

{

    AVInputFormat **p = last_iformat;

    format->next = NULL;

    while(*p || avpriv_atomic_ptr_cas((void * volatile *)p, NULL, format))

        p = &(*p)->next;

    last_iformat = &format->next;

}


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

                            int rownb, int threadnb)

{

    const DNXHDContext *ctx = avctx->priv_data;

    uint32_t offset = ctx->mb_scan_index[rownb];

    RowContext *row = ctx->rows + threadnb;

    int x;

    row->last_dc[0] =

    row->last_dc[1] =

    row->last_dc[2] = 1 << (ctx->bit_depth + 2); // for levels +2^(bitdepth-1)

    init_get_bits(&row->gb, ctx->buf + offset, (ctx->buf_size - offset) << 3);

    for (x = 0; x < ctx->mb_width; x++) {

        //START_TIMER;

        dnxhd_decode_macroblock(ctx, row, data, x, rownb);

        //STOP_TIMER("decode macroblock");

    }

    return 0;

}


static inline int onenand_prog_main(OneNANDState *s, int sec, int secn,

                void *src)

{

    int result = 0;

    if (secn > 0) {

        uint32_t size = (uint32_t)secn * 512;

        const uint8_t *sp = (const uint8_t *)src;

        uint8_t *dp = 0;

        if (s->blk_cur) {

            dp = g_malloc(size);

            if (!dp || blk_read(s->blk_cur, sec, dp, secn) < 0) {

                result = 1;

            }

        } else {

            if (sec + secn > s->secs_cur) {

                result = 1;

            } else {

                dp = (uint8_t *)s->current + (sec << 9);

            }

        }

        if (!result) {

            uint32_t i;

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

                dp[i] &= sp[i];

            }

            if (s->blk_cur) {

                result = blk_write(s->blk_cur, sec, dp, secn) < 0;

            }

        }

        if (dp && s->blk_cur) {

            g_free(dp);

        }

    }

    return result;

}


static gboolean ga_channel_listen_accept(GIOChannel *channel,

                                         GIOCondition condition, gpointer data)

{

    GAChannel *c = data;

    int ret, client_fd;

    bool accepted = false;

    struct sockaddr_un addr;

    socklen_t addrlen = sizeof(addr);

    g_assert(channel != NULL);

    client_fd = qemu_accept(g_io_channel_unix_get_fd(channel),

                            (struct sockaddr *)&addr, &addrlen);

    if (client_fd == -1) {

        g_warning("error converting fd to gsocket: %s", strerror(errno));

        goto out;

    }

    fcntl(client_fd, F_SETFL, O_NONBLOCK);

    ret = ga_channel_client_add(c, client_fd);

    if (ret) {

        g_warning("error setting up connection");

        goto out;

    }

    accepted = true;

out:

    /* only accept 1 connection at a time */

    return !accepted;

}


static int decode_simple_internal(AVCodecContext *avctx, AVFrame *frame)

{

    AVCodecInternal   *avci = avctx->internal;

    DecodeSimpleContext *ds = &avci->ds;

    AVPacket           *pkt = ds->in_pkt;

    // copy to ensure we do not change pkt

    AVPacket tmp;

    int got_frame, actual_got_frame, did_split;

    int ret;

    if (!pkt->data && !avci->draining) {

        av_packet_unref(pkt);

        ret = ff_decode_get_packet(avctx, pkt);

        if (ret < 0 && ret != AVERROR_EOF)

            return ret;

    }

    // Some codecs (at least wma lossless) will crash when feeding drain packets

    // after EOF was signaled.

    if (avci->draining_done)

        return AVERROR_EOF;

    if (!pkt->data &&

        !(avctx->codec->capabilities & AV_CODEC_CAP_DELAY ||

          avctx->active_thread_type & FF_THREAD_FRAME))

        return AVERROR_EOF;

    tmp = *pkt;

#if FF_API_MERGE_SD

FF_DISABLE_DEPRECATION_WARNINGS

    did_split = av_packet_split_side_data(&tmp);

    if (did_split) {

        ret = extract_packet_props(avctx->internal, &tmp);

        if (ret < 0)

            return ret;

        ret = apply_param_change(avctx, &tmp);

        if (ret < 0)

            return ret;

    }

FF_ENABLE_DEPRECATION_WARNINGS

#endif

    got_frame = 0;

    if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME) {

        ret = ff_thread_decode_frame(avctx, frame, &got_frame, &tmp);

    } else {

        ret = avctx->codec->decode(avctx, frame, &got_frame, &tmp);

        if (!(avctx->codec->caps_internal & FF_CODEC_CAP_SETS_PKT_DTS))

            frame->pkt_dts = pkt->dts;

        if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {

            if(!avctx->has_b_frames)

                frame->pkt_pos = pkt->pos;

            //FIXME these should be under if(!avctx->has_b_frames)

            /* get_buffer is supposed to set frame parameters */

            if (!(avctx->codec->capabilities & AV_CODEC_CAP_DR1)) {

                if (!frame->sample_aspect_ratio.num)  frame->sample_aspect_ratio = avctx->sample_aspect_ratio;

                if (!frame->width)                    frame->width               = avctx->width;

                if (!frame->height)                   frame->height              = avctx->height;

                if (frame->format == AV_PIX_FMT_NONE) frame->format              = avctx->pix_fmt;

            }

        }

    }

    emms_c();

    actual_got_frame = got_frame;

    if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {

        if (frame->flags & AV_FRAME_FLAG_DISCARD)

            got_frame = 0;

        if (got_frame)

            frame->best_effort_timestamp = guess_correct_pts(avctx,

                                                             frame->pts,

                                                             frame->pkt_dts);

    } else if (avctx->codec->type == AVMEDIA_TYPE_AUDIO) {

        uint8_t *side;

        int side_size;

        uint32_t discard_padding = 0;

        uint8_t skip_reason = 0;

        uint8_t discard_reason = 0;

        if (ret >= 0 && got_frame) {

            frame->best_effort_timestamp = guess_correct_pts(avctx,

                                                             frame->pts,

                                                             frame->pkt_dts);

            if (frame->format == AV_SAMPLE_FMT_NONE)

                frame->format = avctx->sample_fmt;

            if (!frame->channel_layout)

                frame->channel_layout = avctx->channel_layout;

            if (!frame->channels)

                frame->channels = avctx->channels;

            if (!frame->sample_rate)

                frame->sample_rate = avctx->sample_rate;

        }

        side= av_packet_get_side_data(pkt, AV_PKT_DATA_SKIP_SAMPLES, &side_size);

        if(side && side_size>=10) {

            avctx->internal->skip_samples = AV_RL32(side) * avctx->internal->skip_samples_multiplier;

            discard_padding = AV_RL32(side + 4);

            av_log(avctx, AV_LOG_DEBUG, "skip %d / discard %d samples due to side data\n",

                   avctx->internal->skip_samples, (int)discard_padding);

            skip_reason = AV_RL8(side + 8);

            discard_reason = AV_RL8(side + 9);

        }

        if ((frame->flags & AV_FRAME_FLAG_DISCARD) && got_frame &&

            !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {

            avctx->internal->skip_samples = FFMAX(0, avctx->internal->skip_samples - frame->nb_samples);

            got_frame = 0;

        }

        if (avctx->internal->skip_samples > 0 && got_frame &&

            !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {

            if(frame->nb_samples <= avctx->internal->skip_samples){

                got_frame = 0;

                avctx->internal->skip_samples -= frame->nb_samples;

                av_log(avctx, AV_LOG_DEBUG, "skip whole frame, skip left: %d\n",

                       avctx->internal->skip_samples);

            } else {

                av_samples_copy(frame->extended_data, frame->extended_data, 0, avctx->internal->skip_samples,

                                frame->nb_samples - avctx->internal->skip_samples, avctx->channels, frame->format);

                if(avctx->pkt_timebase.num && avctx->sample_rate) {

                    int64_t diff_ts = av_rescale_q(avctx->internal->skip_samples,

                                                   (AVRational){1, avctx->sample_rate},

                                                   avctx->pkt_timebase);

                    if(frame->pts!=AV_NOPTS_VALUE)

                        frame->pts += diff_ts;

#if FF_API_PKT_PTS

FF_DISABLE_DEPRECATION_WARNINGS

                    if(frame->pkt_pts!=AV_NOPTS_VALUE)

                        frame->pkt_pts += diff_ts;

FF_ENABLE_DEPRECATION_WARNINGS

#endif

                    if(frame->pkt_dts!=AV_NOPTS_VALUE)

                        frame->pkt_dts += diff_ts;

                    if (frame->pkt_duration >= diff_ts)

                        frame->pkt_duration -= diff_ts;

                } else {

                    av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for skipped samples.\n");

                }

                av_log(avctx, AV_LOG_DEBUG, "skip %d/%d samples\n",

                       avctx->internal->skip_samples, frame->nb_samples);

                frame->nb_samples -= avctx->internal->skip_samples;

                avctx->internal->skip_samples = 0;

            }

        }

        if (discard_padding > 0 && discard_padding <= frame->nb_samples && got_frame &&

            !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {

            if (discard_padding == frame->nb_samples) {

                got_frame = 0;

            } else {

                if(avctx->pkt_timebase.num && avctx->sample_rate) {

                    int64_t diff_ts = av_rescale_q(frame->nb_samples - discard_padding,

                                                   (AVRational){1, avctx->sample_rate},

                                                   avctx->pkt_timebase);

                    frame->pkt_duration = diff_ts;

                } else {

                    av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for discarded samples.\n");

                }

                av_log(avctx, AV_LOG_DEBUG, "discard %d/%d samples\n",

                       (int)discard_padding, frame->nb_samples);

                frame->nb_samples -= discard_padding;

            }

        }

        if ((avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL) && got_frame) {

            AVFrameSideData *fside = av_frame_new_side_data(frame, AV_FRAME_DATA_SKIP_SAMPLES, 10);

            if (fside) {

                AV_WL32(fside->data, avctx->internal->skip_samples);

                AV_WL32(fside->data + 4, discard_padding);

                AV_WL8(fside->data + 8, skip_reason);

                AV_WL8(fside->data + 9, discard_reason);

                avctx->internal->skip_samples = 0;

            }

        }

    }

#if FF_API_MERGE_SD

    if (did_split) {

        av_packet_free_side_data(&tmp);

        if(ret == tmp.size)

            ret = pkt->size;

    }

#endif

    if (avctx->codec->type == AVMEDIA_TYPE_AUDIO &&

        !avci->showed_multi_packet_warning &&

        ret >= 0 && ret != pkt->size && !(avctx->codec->capabilities & AV_CODEC_CAP_SUBFRAMES)) {

        av_log(avctx, AV_LOG_WARNING, "Multiple frames in a packet.\n");

        avci->showed_multi_packet_warning = 1;

    }

    if (!got_frame)

        av_frame_unref(frame);

    if (ret >= 0 && avctx->codec->type == AVMEDIA_TYPE_VIDEO && !(avctx->flags & AV_CODEC_FLAG_TRUNCATED))

        ret = pkt->size;

#if FF_API_AVCTX_TIMEBASE

    if (avctx->framerate.num > 0 && avctx->framerate.den > 0)

        avctx->time_base = av_inv_q(av_mul_q(avctx->framerate, (AVRational){avctx->ticks_per_frame, 1}));

#endif

    /* do not stop draining when actual_got_frame != 0 or ret < 0 */

    /* got_frame == 0 but actual_got_frame != 0 when frame is discarded */

    if (avctx->internal->draining && !actual_got_frame) {

        if (ret < 0) {

            /* prevent infinite loop if a decoder wrongly always return error on draining */

            /* reasonable nb_errors_max = maximum b frames + thread count */

            int nb_errors_max = 20 + (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME ?

                                avctx->thread_count : 1);

            if (avci->nb_draining_errors++ >= nb_errors_max) {

                av_log(avctx, AV_LOG_ERROR, "Too many errors when draining, this is a bug. "

                       "Stop draining and force EOF.\n");

                avci->draining_done = 1;

                ret = AVERROR_BUG;

            }

        } else {

            avci->draining_done = 1;

        }

    }

    avci->compat_decode_consumed += ret;

    if (ret >= pkt->size || ret < 0) {

        av_packet_unref(pkt);

    } else {

        int consumed = ret;

        pkt->data                += consumed;

        pkt->size                -= consumed;

        avci->last_pkt_props->size -= consumed; // See extract_packet_props() comment.

        pkt->pts                  = AV_NOPTS_VALUE;

        pkt->dts                  = AV_NOPTS_VALUE;

        avci->last_pkt_props->pts = AV_NOPTS_VALUE;

        avci->last_pkt_props->dts = AV_NOPTS_VALUE;

    }

    if (got_frame)

        av_assert0(frame->buf[0]);

    return ret < 0 ? ret : 0;

}


static void pool_release_buffer(void *opaque, uint8_t *data)

{

    BufferPoolEntry *buf = opaque;

    AVBufferPool *pool = buf->pool;

    add_to_pool(buf);

    if (!avpriv_atomic_int_add_and_fetch(&pool->refcount, -1))

        buffer_pool_free(pool);

}


static int nbd_negotiate_options(NBDClient *client)

{

    uint32_t flags;

    bool fixedNewstyle = false;

    /* Client sends:

        [ 0 ..   3]   client flags

        [ 0 ..   7]   NBD_OPTS_MAGIC

        [ 8 ..  11]   NBD option

        [12 ..  15]   Data length

        ...           Rest of request

        [ 0 ..   7]   NBD_OPTS_MAGIC

        [ 8 ..  11]   Second NBD option

        [12 ..  15]   Data length

        ...           Rest of request

    */

    if (nbd_negotiate_read(client->ioc, &flags, sizeof(flags)) !=

        sizeof(flags)) {

        LOG("read failed");

        return -EIO;

    }

    TRACE("Checking client flags");

    be32_to_cpus(&flags);

    if (flags & NBD_FLAG_C_FIXED_NEWSTYLE) {

        TRACE("Client supports fixed newstyle handshake");

        fixedNewstyle = true;

        flags &= ~NBD_FLAG_C_FIXED_NEWSTYLE;

    }

    if (flags != 0) {

        TRACE("Unknown client flags 0x%" PRIx32 " received", flags);

        return -EIO;

    }

    while (1) {

        int ret;

        uint32_t clientflags, length;

        uint64_t magic;

        if (nbd_negotiate_read(client->ioc, &magic, sizeof(magic)) !=

            sizeof(magic)) {

            LOG("read failed");

            return -EINVAL;

        }

        TRACE("Checking opts magic");

        if (magic != be64_to_cpu(NBD_OPTS_MAGIC)) {

            LOG("Bad magic received");

            return -EINVAL;

        }

        if (nbd_negotiate_read(client->ioc, &clientflags,

                               sizeof(clientflags)) != sizeof(clientflags)) {

            LOG("read failed");

            return -EINVAL;

        }

        clientflags = be32_to_cpu(clientflags);

        if (nbd_negotiate_read(client->ioc, &length, sizeof(length)) !=

            sizeof(length)) {

            LOG("read failed");

            return -EINVAL;

        }

        length = be32_to_cpu(length);

        TRACE("Checking option 0x%" PRIx32, clientflags);

        if (client->tlscreds &&

            client->ioc == (QIOChannel *)client->sioc) {

            QIOChannel *tioc;

            if (!fixedNewstyle) {

                TRACE("Unsupported option 0x%" PRIx32, clientflags);

                return -EINVAL;

            }

            switch (clientflags) {

            case NBD_OPT_STARTTLS:

                tioc = nbd_negotiate_handle_starttls(client, length);

                if (!tioc) {

                    return -EIO;

                }

                object_unref(OBJECT(client->ioc));

                client->ioc = QIO_CHANNEL(tioc);

                break;

            case NBD_OPT_EXPORT_NAME:

                /* No way to return an error to client, so drop connection */

                TRACE("Option 0x%x not permitted before TLS", clientflags);

                return -EINVAL;

            default:

                TRACE("Option 0x%" PRIx32 " not permitted before TLS",

                      clientflags);

                if (nbd_negotiate_drop_sync(client->ioc, length) != length) {

                    return -EIO;

                }

                nbd_negotiate_send_rep(client->ioc, NBD_REP_ERR_TLS_REQD,

                                       clientflags);

                break;

            }

        } else if (fixedNewstyle) {

            switch (clientflags) {

            case NBD_OPT_LIST:

                ret = nbd_negotiate_handle_list(client, length);

                if (ret < 0) {

                    return ret;

                }

                break;

            case NBD_OPT_ABORT:

                return -EINVAL;

            case NBD_OPT_EXPORT_NAME:

                return nbd_negotiate_handle_export_name(client, length);

            case NBD_OPT_STARTTLS:

                if (nbd_negotiate_drop_sync(client->ioc, length) != length) {

                    return -EIO;

                }

                if (client->tlscreds) {

                    TRACE("TLS already enabled");

                    nbd_negotiate_send_rep(client->ioc, NBD_REP_ERR_INVALID,

                                           clientflags);

                } else {

                    TRACE("TLS not configured");

                    nbd_negotiate_send_rep(client->ioc, NBD_REP_ERR_POLICY,

                                           clientflags);

                }

                break;

            default:

                TRACE("Unsupported option 0x%" PRIx32, clientflags);

                if (nbd_negotiate_drop_sync(client->ioc, length) != length) {

                    return -EIO;

                }

                nbd_negotiate_send_rep(client->ioc, NBD_REP_ERR_UNSUP,

                                       clientflags);

                break;

            }

        } else {

            /*

             * If broken new-style we should drop the connection

             * for anything except NBD_OPT_EXPORT_NAME

             */

            switch (clientflags) {

            case NBD_OPT_EXPORT_NAME:

                return nbd_negotiate_handle_export_name(client, length);

            default:

                TRACE("Unsupported option 0x%" PRIx32, clientflags);

                return -EINVAL;

            }

        }

    }

}


static inline void gen_store(DisasContext *s, int opsize, TCGv addr, TCGv val)

{

    int index = IS_USER(s);

    s->is_mem = 1;

    switch(opsize) {

    case OS_BYTE:

        tcg_gen_qemu_st8(val, addr, index);

        break;

    case OS_WORD:

        tcg_gen_qemu_st16(val, addr, index);

        break;

    case OS_LONG:

    case OS_SINGLE:

        tcg_gen_qemu_st32(val, addr, index);

        break;

    default:

        qemu_assert(0, "bad store size");

    }

    gen_throws_exception = gen_last_qop;

}


void blk_mig_init(void)

{

    QSIMPLEQ_INIT(&block_mig_state.bmds_list);

    QSIMPLEQ_INIT(&block_mig_state.blk_list);

    qemu_mutex_init(&block_mig_state.lock);

    register_savevm_live(NULL, "block", 0, 1, &savevm_block_handlers,

                         &block_mig_state);

}


qcrypto_tls_session_check_certificate(QCryptoTLSSession *session,

                                      Error **errp)

{

    int ret;

    unsigned int status;

    const gnutls_datum_t *certs;

    unsigned int nCerts, i;

    time_t now;

    gnutls_x509_crt_t cert = NULL;

    now = time(NULL);

    if (now == ((time_t)-1)) {

        error_setg_errno(errp, errno, "Cannot get current time");

        return -1;

    }

    ret = gnutls_certificate_verify_peers2(session->handle, &status);

    if (ret < 0) {

        error_setg(errp, "Verify failed: %s", gnutls_strerror(ret));

        return -1;

    }

    if (status != 0) {

        const char *reason = "Invalid certificate";

        if (status & GNUTLS_CERT_INVALID) {

            reason = "The certificate is not trusted";

        }

        if (status & GNUTLS_CERT_SIGNER_NOT_FOUND) {

            reason = "The certificate hasn't got a known issuer";

        }

        if (status & GNUTLS_CERT_REVOKED) {

            reason = "The certificate has been revoked";

        }

        if (status & GNUTLS_CERT_INSECURE_ALGORITHM) {

            reason = "The certificate uses an insecure algorithm";

        }

        error_setg(errp, "%s", reason);

        return -1;

    }

    certs = gnutls_certificate_get_peers(session->handle, &nCerts);

    if (!certs) {

        error_setg(errp, "No certificate peers");

        return -1;

    }

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

        ret = gnutls_x509_crt_init(&cert);

        if (ret < 0) {

            error_setg(errp, "Cannot initialize certificate: %s",

                       gnutls_strerror(ret));

            return -1;

        }

        ret = gnutls_x509_crt_import(cert, &certs[i], GNUTLS_X509_FMT_DER);

        if (ret < 0) {

            error_setg(errp, "Cannot import certificate: %s",

                       gnutls_strerror(ret));

            goto error;

        }

        if (gnutls_x509_crt_get_expiration_time(cert) < now) {

            error_setg(errp, "The certificate has expired");

            goto error;

        }

        if (gnutls_x509_crt_get_activation_time(cert) > now) {

            error_setg(errp, "The certificate is not yet activated");

            goto error;

        }

        if (gnutls_x509_crt_get_activation_time(cert) > now) {

            error_setg(errp, "The certificate is not yet activated");

            goto error;

        }

        if (i == 0) {

            size_t dnameSize = 1024;

            session->peername = g_malloc(dnameSize);

        requery:

            ret = gnutls_x509_crt_get_dn(cert, session->peername, &dnameSize);

            if (ret < 0) {

                if (ret == GNUTLS_E_SHORT_MEMORY_BUFFER) {

                    session->peername = g_realloc(session->peername,

                                                  dnameSize);

                    goto requery;

                }

                error_setg(errp, "Cannot get client distinguished name: %s",

                           gnutls_strerror(ret));

                goto error;

            }

            if (session->aclname) {

                qemu_acl *acl = qemu_acl_find(session->aclname);

                int allow;

                if (!acl) {

                    error_setg(errp, "Cannot find ACL %s",

                               session->aclname);

                    goto error;

                }

                allow = qemu_acl_party_is_allowed(acl, session->peername);

                error_setg(errp, "TLS x509 ACL check for %s is %s",

                           session->peername, allow ? "allowed" : "denied");

                if (!allow) {

                    goto error;

                }

            }

            if (session->hostname) {

                if (!gnutls_x509_crt_check_hostname(cert, session->hostname)) {

                    error_setg(errp,

                               "Certificate does not match the hostname %s",

                               session->hostname);

                    goto error;

                }

            }

        }

        gnutls_x509_crt_deinit(cert);

    }

    return 0;

 error:

    gnutls_x509_crt_deinit(cert);

    return -1;

}


static inline int32_t mipsdsp_add_i32(int32_t a, int32_t b, CPUMIPSState *env)

{

    int32_t temp;

    temp = a + b;

    if (MIPSDSP_OVERFLOW(a, b, temp, 0x80000000)) {

        set_DSPControl_overflow_flag(1, 20, env);

    }

    return temp;

}


static void qtrle_decode_8bpp(QtrleContext *s, int stream_ptr, int row_ptr, int lines_to_change)

{

    int rle_code;

    int pixel_ptr;

    int row_inc = s->frame.linesize[0];

    unsigned char pi1, pi2, pi3, pi4;  /* 4 palette indexes */

    unsigned char *rgb = s->frame.data[0];

    int pixel_limit = s->frame.linesize[0] * s->avctx->height;

    while (lines_to_change--) {

        CHECK_STREAM_PTR(2);

        pixel_ptr = row_ptr + (4 * (s->buf[stream_ptr++] - 1));

        while ((rle_code = (signed char)s->buf[stream_ptr++]) != -1) {

            if (rle_code == 0) {

                /* there's another skip code in the stream */

                CHECK_STREAM_PTR(1);

                pixel_ptr += (4 * (s->buf[stream_ptr++] - 1));

            } else if (rle_code < 0) {

                /* decode the run length code */

                rle_code = -rle_code;

                /* get the next 4 bytes from the stream, treat them as palette

                 * indexes, and output them rle_code times */

                CHECK_STREAM_PTR(4);

                pi1 = s->buf[stream_ptr++];

                pi2 = s->buf[stream_ptr++];

                pi3 = s->buf[stream_ptr++];

                pi4 = s->buf[stream_ptr++];

                CHECK_PIXEL_PTR(rle_code * 4);

                while (rle_code--) {

                    rgb[pixel_ptr++] = pi1;

                    rgb[pixel_ptr++] = pi2;

                    rgb[pixel_ptr++] = pi3;

                    rgb[pixel_ptr++] = pi4;

                }

            } else {

                /* copy the same pixel directly to output 4 times */

                rle_code *= 4;

                CHECK_STREAM_PTR(rle_code);

                CHECK_PIXEL_PTR(rle_code);

                while (rle_code--) {

                    rgb[pixel_ptr++] = s->buf[stream_ptr++];

                }

            }

        }

        row_ptr += row_inc;

    }

}


static inline void libopenjpeg_copyto16(AVFrame *picture, opj_image_t *image) {

    int *comp_data;

    uint16_t *img_ptr;

    int index, x, y;

    int adjust[4];

    for (x = 0; x < image->numcomps; x++)

        adjust[x] = FFMAX(FFMIN(av_pix_fmt_desc_get(picture->format)->comp[x].depth_minus1 + 1 - image->comps[x].prec, 8), 0);

    for (index = 0; index < image->numcomps; index++) {

        comp_data = image->comps[index].data;

        for (y = 0; y < image->comps[index].h; y++) {

            img_ptr = (uint16_t*) (picture->data[index] + y * picture->linesize[index]);

            for (x = 0; x < image->comps[index].w; x++) {

                *img_ptr = 0x8000 * image->comps[index].sgnd + (*comp_data << adjust[index]);

                img_ptr++;

                comp_data++;

            }

        }

    }

}


static int filter_frame(AVFilterLink *inlink, AVFrame *buf)

{

    AVFilterContext *ctx = inlink->dst;

    VolumeContext *vol    = inlink->dst->priv;

    AVFilterLink *outlink = inlink->dst->outputs[0];

    int nb_samples        = buf->nb_samples;

    AVFrame *out_buf;

    int64_t pos;

    AVFrameSideData *sd = av_frame_get_side_data(buf, AV_FRAME_DATA_REPLAYGAIN);

    int ret;

    if (sd && vol->replaygain != REPLAYGAIN_IGNORE) {

        if (vol->replaygain != REPLAYGAIN_DROP) {

            AVReplayGain *replaygain = (AVReplayGain*)sd->data;

            int32_t gain  = 100000;

            uint32_t peak = 100000;

            float g, p;

            if (vol->replaygain == REPLAYGAIN_TRACK &&

                replaygain->track_gain != INT32_MIN) {

                gain = replaygain->track_gain;

                if (replaygain->track_peak != 0)

                    peak = replaygain->track_peak;

            } else if (replaygain->album_gain != INT32_MIN) {

                gain = replaygain->album_gain;

                if (replaygain->album_peak != 0)

                    peak = replaygain->album_peak;

            } else {

                av_log(inlink->dst, AV_LOG_WARNING, "Both ReplayGain gain "

                       "values are unknown.\n");

            }

            g = gain / 100000.0f;

            p = peak / 100000.0f;

            av_log(inlink->dst, AV_LOG_VERBOSE,

                   "Using gain %f dB from replaygain side data.\n", g);

            vol->volume   = ff_exp10((g + vol->replaygain_preamp) / 20);

            if (vol->replaygain_noclip)

                vol->volume = FFMIN(vol->volume, 1.0 / p);

            vol->volume_i = (int)(vol->volume * 256 + 0.5);

            volume_init(vol);

        }

        av_frame_remove_side_data(buf, AV_FRAME_DATA_REPLAYGAIN);

    }

    if (isnan(vol->var_values[VAR_STARTPTS])) {

        vol->var_values[VAR_STARTPTS] = TS2D(buf->pts);

        vol->var_values[VAR_STARTT  ] = TS2T(buf->pts, inlink->time_base);

    }

    vol->var_values[VAR_PTS] = TS2D(buf->pts);

    vol->var_values[VAR_T  ] = TS2T(buf->pts, inlink->time_base);

    vol->var_values[VAR_N  ] = inlink->frame_count_out;

    pos = buf->pkt_pos;

    vol->var_values[VAR_POS] = pos == -1 ? NAN : pos;

    if (vol->eval_mode == EVAL_MODE_FRAME)

        set_volume(ctx);

    if (vol->volume == 1.0 || vol->volume_i == 256) {

        out_buf = buf;

        goto end;

    }

    /* do volume scaling in-place if input buffer is writable */

    if (av_frame_is_writable(buf)

            && (vol->precision != PRECISION_FIXED || vol->volume_i > 0)) {

        out_buf = buf;

    } else {

        out_buf = ff_get_audio_buffer(inlink, nb_samples);

        if (!out_buf)

            return AVERROR(ENOMEM);

        ret = av_frame_copy_props(out_buf, buf);

        if (ret < 0) {

            av_frame_free(&out_buf);

            av_frame_free(&buf);

            return ret;

        }

    }

    if (vol->precision != PRECISION_FIXED || vol->volume_i > 0) {

        int p, plane_samples;

        if (av_sample_fmt_is_planar(buf->format))

            plane_samples = FFALIGN(nb_samples, vol->samples_align);

        else

            plane_samples = FFALIGN(nb_samples * vol->channels, vol->samples_align);

        if (vol->precision == PRECISION_FIXED) {

            for (p = 0; p < vol->planes; p++) {

                vol->scale_samples(out_buf->extended_data[p],

                                   buf->extended_data[p], plane_samples,

                                   vol->volume_i);

            }

        } else if (av_get_packed_sample_fmt(vol->sample_fmt) == AV_SAMPLE_FMT_FLT) {

            for (p = 0; p < vol->planes; p++) {

                vol->fdsp->vector_fmul_scalar((float *)out_buf->extended_data[p],

                                             (const float *)buf->extended_data[p],

                                             vol->volume, plane_samples);

            }

        } else {

            for (p = 0; p < vol->planes; p++) {

                vol->fdsp->vector_dmul_scalar((double *)out_buf->extended_data[p],

                                             (const double *)buf->extended_data[p],

                                             vol->volume, plane_samples);

            }

        }

    }

    emms_c();

    if (buf != out_buf)

        av_frame_free(&buf);

end:

    vol->var_values[VAR_NB_CONSUMED_SAMPLES] += out_buf->nb_samples;

    return ff_filter_frame(outlink, out_buf);

}


static int hnm_read_packet(AVFormatContext *s, AVPacket *pkt)

{

    Hnm4DemuxContext *hnm = s->priv_data;

    AVIOContext *pb = s->pb;

    int ret = 0;

    uint32_t superchunk_size, chunk_size;

    uint16_t chunk_id;

    if (hnm->currentframe == hnm->frames || pb->eof_reached)

        return AVERROR_EOF;

    if (hnm->superchunk_remaining == 0) {

        /* parse next superchunk */

        superchunk_size = avio_rl24(pb);

        avio_skip(pb, 1);

        hnm->superchunk_remaining = superchunk_size - 4;

    }

    chunk_size = avio_rl24(pb);

    avio_skip(pb, 1);

    chunk_id = avio_rl16(pb);

    avio_skip(pb, 2);

    if (chunk_size > hnm->superchunk_remaining) {

        av_log(s, AV_LOG_ERROR, "invalid chunk size: %u, offset: %u\n",

               chunk_size, (int) avio_tell(pb));

        avio_skip(pb, hnm->superchunk_remaining - 8);

        hnm->superchunk_remaining = 0;

    }

    switch (chunk_id) {

    case HNM4_CHUNK_ID_PL:

    case HNM4_CHUNK_ID_IZ:

    case HNM4_CHUNK_ID_IU:

        avio_seek(pb, -8, SEEK_CUR);

        ret += av_get_packet(pb, pkt, chunk_size);

        hnm->superchunk_remaining -= chunk_size;

        if (chunk_id == HNM4_CHUNK_ID_IZ || chunk_id == HNM4_CHUNK_ID_IU)

            hnm->currentframe++;

        break;

    case HNM4_CHUNK_ID_SD:

        avio_skip(pb, chunk_size - 8);

        hnm->superchunk_remaining -= chunk_size;

        break;

    default:

        av_log(s, AV_LOG_WARNING, "unknown chunk found: %d, offset: %d\n",

               chunk_id, (int) avio_tell(pb));

        avio_skip(pb, chunk_size - 8);

        hnm->superchunk_remaining -= chunk_size;

        break;

    }

    return ret;

}


static int flv_write_packet(AVFormatContext *s, AVPacket *pkt)

{

    AVIOContext *pb = s->pb;

    AVCodecContext *enc = s->streams[pkt->stream_index]->codec;

    FLVContext *flv = s->priv_data;

    unsigned ts;

    int size= pkt->size;

    uint8_t *data= NULL;

    int flags, flags_size;

//    av_log(s, AV_LOG_DEBUG, "type:%d pts: %"PRId64" size:%d\n", enc->codec_type, timestamp, size);

    if(enc->codec_id == CODEC_ID_VP6 || enc->codec_id == CODEC_ID_VP6F ||

       enc->codec_id == CODEC_ID_AAC)

        flags_size= 2;

    else if(enc->codec_id == CODEC_ID_H264)

        flags_size= 5;

    else

        flags_size= 1;

    if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {

        avio_w8(pb, FLV_TAG_TYPE_VIDEO);

        flags = enc->codec_tag;

        if(flags == 0) {

            av_log(enc, AV_LOG_ERROR, "video codec %X not compatible with flv\n",enc->codec_id);

            return -1;

        }

        flags |= pkt->flags & AV_PKT_FLAG_KEY ? FLV_FRAME_KEY : FLV_FRAME_INTER;

    } else {

        assert(enc->codec_type == AVMEDIA_TYPE_AUDIO);

        flags = get_audio_flags(enc);

        assert(size);

        avio_w8(pb, FLV_TAG_TYPE_AUDIO);

    }

    if (enc->codec_id == CODEC_ID_H264) {

        /* check if extradata looks like mp4 formated */

        if (enc->extradata_size > 0 && *(uint8_t*)enc->extradata != 1) {

            if (ff_avc_parse_nal_units_buf(pkt->data, &data, &size) < 0)

                return -1;

        }

    }

    if (!flv->delay && pkt->dts < 0)

        flv->delay = -pkt->dts;

    ts = pkt->dts + flv->delay; // add delay to force positive dts

    if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {

        if (flv->last_video_ts < ts)

            flv->last_video_ts = ts;

    }

    avio_wb24(pb,size + flags_size);

    avio_wb24(pb,ts);

    avio_w8(pb,(ts >> 24) & 0x7F); // timestamps are 32bits _signed_

    avio_wb24(pb,flv->reserved);

    avio_w8(pb,flags);

    if (enc->codec_id == CODEC_ID_VP6)

        avio_w8(pb,0);

    if (enc->codec_id == CODEC_ID_VP6F)

        avio_w8(pb, enc->extradata_size ? enc->extradata[0] : 0);

    else if (enc->codec_id == CODEC_ID_AAC)

        avio_w8(pb,1); // AAC raw

    else if (enc->codec_id == CODEC_ID_H264) {

        avio_w8(pb,1); // AVC NALU

        avio_wb24(pb,pkt->pts - pkt->dts);

    }

    avio_write(pb, data ? data : pkt->data, size);

    avio_wb32(pb,size+flags_size+11); // previous tag size

    flv->duration = FFMAX(flv->duration, pkt->pts + flv->delay + pkt->duration);

    avio_flush(pb);

    av_free(data);

    return pb->error;

}


static int avi_write_idx1(AVFormatContext *s)

{

    AVIOContext *pb = s->pb;

    AVIContext *avi = s->priv_data;

    int64_t idx_chunk;

    int i;

    char tag[5];

    if (pb->seekable) {

        AVIStream *avist;

        AVIIentry *ie = 0, *tie;

        int empty, stream_id = -1;

        idx_chunk = ff_start_tag(pb, "idx1");

        for (i = 0; i < s->nb_streams; i++) {

            avist        = s->streams[i]->priv_data;

            avist->entry = 0;

        }

        do {

            empty = 1;

            for (i = 0; i < s->nb_streams; i++) {

                avist = s->streams[i]->priv_data;

                if (avist->indexes.entry <= avist->entry)

                    continue;

                tie = avi_get_ientry(&avist->indexes, avist->entry);

                if (empty || tie->pos < ie->pos) {

                    ie        = tie;

                    stream_id = i;

                }

                empty = 0;

            }

            if (!empty) {

                avist = s->streams[stream_id]->priv_data;

                avi_stream2fourcc(tag, stream_id,

                                  s->streams[stream_id]->codecpar->codec_type);

                ffio_wfourcc(pb, tag);

                avio_wl32(pb, ie->flags);

                avio_wl32(pb, ie->pos);

                avio_wl32(pb, ie->len);

                avist->entry++;

            }

        } while (!empty);

        ff_end_tag(pb, idx_chunk);

        avi_write_counters(s, avi->riff_id);

    }

    return 0;

}


static int vc1_decode_p_mb_intfr(VC1Context *v)

{

    MpegEncContext *s = &v->s;

    GetBitContext *gb = &s->gb;

    int i;

    int mb_pos = s->mb_x + s->mb_y * s->mb_stride;

    int cbp = 0; /* cbp decoding stuff */

    int mqdiff, mquant; /* MB quantization */

    int ttmb = v->ttfrm; /* MB Transform type */

    int mb_has_coeffs = 1; /* last_flag */

    int dmv_x, dmv_y; /* Differential MV components */

    int val; /* temp value */

    int first_block = 1;

    int dst_idx, off;

    int skipped, fourmv = 0, twomv = 0;

    int block_cbp = 0, pat, block_tt = 0;

    int idx_mbmode = 0, mvbp;

    int stride_y, fieldtx;

    mquant = v->pq; /* Lossy initialization */

    if (v->skip_is_raw)

        skipped = get_bits1(gb);

    else

        skipped = v->s.mbskip_table[mb_pos];

    if (!skipped) {

        if (v->fourmvswitch)

            idx_mbmode = get_vlc2(gb, v->mbmode_vlc->table, VC1_INTFR_4MV_MBMODE_VLC_BITS, 2); // try getting this done

        else

            idx_mbmode = get_vlc2(gb, v->mbmode_vlc->table, VC1_INTFR_NON4MV_MBMODE_VLC_BITS, 2); // in a single line

        switch (ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][0]) {

        /* store the motion vector type in a flag (useful later) */

        case MV_PMODE_INTFR_4MV:

            fourmv = 1;

            v->blk_mv_type[s->block_index[0]] = 0;

            v->blk_mv_type[s->block_index[1]] = 0;

            v->blk_mv_type[s->block_index[2]] = 0;

            v->blk_mv_type[s->block_index[3]] = 0;

            break;

        case MV_PMODE_INTFR_4MV_FIELD:

            fourmv = 1;

            v->blk_mv_type[s->block_index[0]] = 1;

            v->blk_mv_type[s->block_index[1]] = 1;

            v->blk_mv_type[s->block_index[2]] = 1;

            v->blk_mv_type[s->block_index[3]] = 1;

            break;

        case MV_PMODE_INTFR_2MV_FIELD:

            twomv = 1;

            v->blk_mv_type[s->block_index[0]] = 1;

            v->blk_mv_type[s->block_index[1]] = 1;

            v->blk_mv_type[s->block_index[2]] = 1;

            v->blk_mv_type[s->block_index[3]] = 1;

            break;

        case MV_PMODE_INTFR_1MV:

            v->blk_mv_type[s->block_index[0]] = 0;

            v->blk_mv_type[s->block_index[1]] = 0;

            v->blk_mv_type[s->block_index[2]] = 0;

            v->blk_mv_type[s->block_index[3]] = 0;

            break;

        }

        if (ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][0] == MV_PMODE_INTFR_INTRA) { // intra MB

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

                s->current_picture.motion_val[1][s->block_index[i]][0] = 0;

                s->current_picture.motion_val[1][s->block_index[i]][1] = 0;

            }

            v->is_intra[s->mb_x] = 0x3f; // Set the bitfield to all 1.

            s->mb_intra          = 1;

            s->current_picture.mb_type[mb_pos] = MB_TYPE_INTRA;

            fieldtx = v->fieldtx_plane[mb_pos] = get_bits1(gb);

            mb_has_coeffs = get_bits1(gb);

            if (mb_has_coeffs)

                cbp = 1 + get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2);

            v->s.ac_pred = v->acpred_plane[mb_pos] = get_bits1(gb);

            GET_MQUANT();

            s->current_picture.qscale_table[mb_pos] = mquant;

            /* Set DC scale - y and c use the same (not sure if necessary here) */

            s->y_dc_scale = s->y_dc_scale_table[mquant];

            s->c_dc_scale = s->c_dc_scale_table[mquant];

            dst_idx = 0;

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

                v->a_avail = v->c_avail          = 0;

                v->mb_type[0][s->block_index[i]] = 1;

                s->dc_val[0][s->block_index[i]]  = 0;

                dst_idx += i >> 2;

                val = ((cbp >> (5 - i)) & 1);

                if (i == 2 || i == 3 || !s->first_slice_line)

                    v->a_avail = v->mb_type[0][s->block_index[i] - s->block_wrap[i]];

                if (i == 1 || i == 3 || s->mb_x)

                    v->c_avail = v->mb_type[0][s->block_index[i] - 1];

                vc1_decode_intra_block(v, s->block[i], i, val, mquant,

                                       (i & 4) ? v->codingset2 : v->codingset);

                if ((i>3) && (s->flags & CODEC_FLAG_GRAY)) continue;

                v->vc1dsp.vc1_inv_trans_8x8(s->block[i]);

                if (i < 4) {

                    stride_y = s->linesize << fieldtx;

                    off = (fieldtx) ? ((i & 1) * 8) + ((i & 2) >> 1) * s->linesize : (i & 1) * 8 + 4 * (i & 2) * s->linesize;

                } else {

                    stride_y = s->uvlinesize;

                    off = 0;

                }

                s->idsp.put_signed_pixels_clamped(s->block[i],

                                                  s->dest[dst_idx] + off,

                                                  stride_y);

                //TODO: loop filter

            }

        } else { // inter MB

            mb_has_coeffs = ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][3];

            if (mb_has_coeffs)

                cbp = 1 + get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2);

            if (ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][0] == MV_PMODE_INTFR_2MV_FIELD) {

                v->twomvbp = get_vlc2(gb, v->twomvbp_vlc->table, VC1_2MV_BLOCK_PATTERN_VLC_BITS, 1);

            } else {

                if ((ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][0] == MV_PMODE_INTFR_4MV)

                    || (ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][0] == MV_PMODE_INTFR_4MV_FIELD)) {

                    v->fourmvbp = get_vlc2(gb, v->fourmvbp_vlc->table, VC1_4MV_BLOCK_PATTERN_VLC_BITS, 1);

                }

            }

            s->mb_intra = v->is_intra[s->mb_x] = 0;

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

                v->mb_type[0][s->block_index[i]] = 0;

            fieldtx = v->fieldtx_plane[mb_pos] = ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][1];

            /* for all motion vector read MVDATA and motion compensate each block */

            dst_idx = 0;

            if (fourmv) {

                mvbp = v->fourmvbp;

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

                    if (i < 4) {

                        dmv_x = dmv_y = 0;

                        val   = ((mvbp >> (3 - i)) & 1);

                        if (val) {

                            get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0);

                        }

                        ff_vc1_pred_mv_intfr(v, i, dmv_x, dmv_y, 0, v->range_x, v->range_y, v->mb_type[0], 0);

                        ff_vc1_mc_4mv_luma(v, i, 0, 0);

                    } else if (i == 4) {

                        ff_vc1_mc_4mv_chroma4(v, 0, 0, 0);

                    }

                }

            } else if (twomv) {

                mvbp  = v->twomvbp;

                dmv_x = dmv_y = 0;

                if (mvbp & 2) {

                    get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0);

                }

                ff_vc1_pred_mv_intfr(v, 0, dmv_x, dmv_y, 2, v->range_x, v->range_y, v->mb_type[0], 0);

                ff_vc1_mc_4mv_luma(v, 0, 0, 0);

                ff_vc1_mc_4mv_luma(v, 1, 0, 0);

                dmv_x = dmv_y = 0;

                if (mvbp & 1) {

                    get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0);

                }

                ff_vc1_pred_mv_intfr(v, 2, dmv_x, dmv_y, 2, v->range_x, v->range_y, v->mb_type[0], 0);

                ff_vc1_mc_4mv_luma(v, 2, 0, 0);

                ff_vc1_mc_4mv_luma(v, 3, 0, 0);

                ff_vc1_mc_4mv_chroma4(v, 0, 0, 0);

            } else {

                mvbp = ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][2];

                dmv_x = dmv_y = 0;

                if (mvbp) {

                    get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0);

                }

                ff_vc1_pred_mv_intfr(v, 0, dmv_x, dmv_y, 1, v->range_x, v->range_y, v->mb_type[0], 0);

                ff_vc1_mc_1mv(v, 0);

            }

            if (cbp)

                GET_MQUANT();  // p. 227

            s->current_picture.qscale_table[mb_pos] = mquant;

            if (!v->ttmbf && cbp)

                ttmb = get_vlc2(gb, ff_vc1_ttmb_vlc[v->tt_index].table, VC1_TTMB_VLC_BITS, 2);

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

                s->dc_val[0][s->block_index[i]] = 0;

                dst_idx += i >> 2;

                val = ((cbp >> (5 - i)) & 1);

                if (!fieldtx)

                    off = (i & 4) ? 0 : ((i & 1) * 8 + (i & 2) * 4 * s->linesize);

                else

                    off = (i & 4) ? 0 : ((i & 1) * 8 + ((i > 1) * s->linesize));

                if (val) {

                    pat = vc1_decode_p_block(v, s->block[i], i, mquant, ttmb,

                                             first_block, s->dest[dst_idx] + off,

                                             (i & 4) ? s->uvlinesize : (s->linesize << fieldtx),

                                             (i & 4) && (s->flags & CODEC_FLAG_GRAY), &block_tt);

                    block_cbp |= pat << (i << 2);

                    if (!v->ttmbf && ttmb < 8)

                        ttmb = -1;

                    first_block = 0;

                }

            }

        }

    } else { // skipped

        s->mb_intra = v->is_intra[s->mb_x] = 0;

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

            v->mb_type[0][s->block_index[i]] = 0;

            s->dc_val[0][s->block_index[i]] = 0;

        }

        s->current_picture.mb_type[mb_pos]      = MB_TYPE_SKIP;

        s->current_picture.qscale_table[mb_pos] = 0;

        v->blk_mv_type[s->block_index[0]] = 0;

        v->blk_mv_type[s->block_index[1]] = 0;

        v->blk_mv_type[s->block_index[2]] = 0;

        v->blk_mv_type[s->block_index[3]] = 0;

        ff_vc1_pred_mv_intfr(v, 0, 0, 0, 1, v->range_x, v->range_y, v->mb_type[0], 0);

        ff_vc1_mc_1mv(v, 0);

    }

    if (s->mb_x == s->mb_width - 1)

        memmove(v->is_intra_base, v->is_intra, sizeof(v->is_intra_base[0])*s->mb_stride);

    return 0;

}