static av_always_inline void mc_luma_scaled(VP9Context *s, vp9_scaled_mc_func smc,

                                            vp9_mc_func (*mc)[2],

                                            uint8_t *dst, ptrdiff_t dst_stride,

                                            const uint8_t *ref, ptrdiff_t ref_stride,

                                            ThreadFrame *ref_frame,

                                            ptrdiff_t y, ptrdiff_t x, const VP56mv *in_mv,

                                            int px, int py, int pw, int ph,

                                            int bw, int bh, int w, int h, int bytesperpixel,

                                            const uint16_t *scale, const uint8_t *step)

{

    if (s->s.frames[CUR_FRAME].tf.f->width == ref_frame->f->width &&

        s->s.frames[CUR_FRAME].tf.f->height == ref_frame->f->height) {

        mc_luma_unscaled(s, mc, dst, dst_stride, ref, ref_stride, ref_frame,

                         y, x, in_mv, bw, bh, w, h, bytesperpixel);

    } else {

#define scale_mv(n, dim) (((int64_t)(n) * scale[dim]) >> 14)

    int mx, my;

    int refbw_m1, refbh_m1;

    int th;

    VP56mv mv;

    mv.x = av_clip(in_mv->x, -(x + pw - px + 4) * 8, (s->cols * 8 - x + px + 3) * 8);

    mv.y = av_clip(in_mv->y, -(y + ph - py + 4) * 8, (s->rows * 8 - y + py + 3) * 8);

    // BUG libvpx seems to scale the two components separately. This introduces

    // rounding errors but we have to reproduce them to be exactly compatible

    // with the output from libvpx...

    mx = scale_mv(mv.x * 2, 0) + scale_mv(x * 16, 0);

    my = scale_mv(mv.y * 2, 1) + scale_mv(y * 16, 1);

    y = my >> 4;

    x = mx >> 4;

    ref += y * ref_stride + x * bytesperpixel;

    mx &= 15;

    my &= 15;

    refbw_m1 = ((bw - 1) * step[0] + mx) >> 4;

    refbh_m1 = ((bh - 1) * step[1] + my) >> 4;

    // FIXME bilinear filter only needs 0/1 pixels, not 3/4

    // we use +7 because the last 7 pixels of each sbrow can be changed in

    // the longest loopfilter of the next sbrow

    th = (y + refbh_m1 + 4 + 7) >> 6;

    ff_thread_await_progress(ref_frame, FFMAX(th, 0), 0);

    if (x < 3 || y < 3 || x + 4 >= w - refbw_m1 || y + 4 >= h - refbh_m1) {

        s->vdsp.emulated_edge_mc(s->edge_emu_buffer,

                                 ref - 3 * ref_stride - 3 * bytesperpixel,

                                 288, ref_stride,

                                 refbw_m1 + 8, refbh_m1 + 8,

                                 x - 3, y - 3, w, h);

        ref = s->edge_emu_buffer + 3 * 288 + 3 * bytesperpixel;

        ref_stride = 288;

    }

    smc(dst, dst_stride, ref, ref_stride, bh, mx, my, step[0], step[1]);

    }

}


long do_rt_sigreturn(CPUSH4State *regs)

{

    struct target_rt_sigframe *frame;

    abi_ulong frame_addr;

    sigset_t blocked;

    target_ulong r0;

#if defined(DEBUG_SIGNAL)

    fprintf(stderr, "do_rt_sigreturn\n");

#endif

    frame_addr = regs->gregs[15];

    if (!lock_user_struct(VERIFY_READ, frame, frame_addr, 1))

   	goto badframe;

    target_to_host_sigset(&blocked, &frame->uc.tuc_sigmask);

    do_sigprocmask(SIG_SETMASK, &blocked, NULL);

    if (restore_sigcontext(regs, &frame->uc.tuc_mcontext, &r0))

        goto badframe;

    if (do_sigaltstack(frame_addr +

		       offsetof(struct target_rt_sigframe, uc.tuc_stack),

		       0, get_sp_from_cpustate(regs)) == -EFAULT)

        goto badframe;

    unlock_user_struct(frame, frame_addr, 0);

    return r0;

badframe:

    unlock_user_struct(frame, frame_addr, 0);

    force_sig(TARGET_SIGSEGV);

    return 0;

}


int ff_draw_init(FFDrawContext *draw, enum PixelFormat format, unsigned flags)

{

    const AVPixFmtDescriptor *desc = &av_pix_fmt_descriptors[format];

    const AVComponentDescriptor *c;

    unsigned i, nb_planes = 0;

    int pixelstep[MAX_PLANES] = { 0 };

    if (!desc->name)

        return AVERROR(EINVAL);

    if (desc->flags & ~(PIX_FMT_PLANAR | PIX_FMT_RGB))

        return AVERROR(ENOSYS);

    for (i = 0; i < desc->nb_components; i++) {

        c = &desc->comp[i];

        /* for now, only 8-bits formats */

        if (c->depth_minus1 != 8 - 1)

            return AVERROR(ENOSYS);

        if (c->plane >= MAX_PLANES)

            return AVERROR(ENOSYS);

        /* strange interleaving */

        if (pixelstep[c->plane] != 0 &&

            pixelstep[c->plane] != c->step_minus1 + 1)

            return AVERROR(ENOSYS);

        pixelstep[c->plane] = c->step_minus1 + 1;

        if (pixelstep[c->plane] >= 8)

            return AVERROR(ENOSYS);

        nb_planes = FFMAX(nb_planes, c->plane + 1);

    }

    if ((desc->log2_chroma_w || desc->log2_chroma_h) && nb_planes < 3)

        return AVERROR(ENOSYS); /* exclude NV12 and NV21 */

    memset(draw, 0, sizeof(*draw));

    draw->desc      = desc;

    draw->format    = format;

    draw->nb_planes = nb_planes;

    memcpy(draw->pixelstep, pixelstep, sizeof(draw->pixelstep));

    if (nb_planes >= 3 && !(desc->flags & PIX_FMT_RGB)) {

        draw->hsub[1] = draw->hsub[2] = draw->hsub_max = desc->log2_chroma_w;

        draw->vsub[1] = draw->vsub[2] = draw->vsub_max = desc->log2_chroma_h;

    }

    for (i = 0; i < ((desc->nb_components - 1) | 1); i++)

        draw->comp_mask[desc->comp[i].plane] |=

            1 << (desc->comp[i].offset_plus1 - 1);

    return 0;

}


static void pty_chr_close(struct CharDriverState *chr)

{

    PtyCharDriver *s = chr->opaque;

    int fd;

    remove_fd_in_watch(chr);

    fd = g_io_channel_unix_get_fd(s->fd);

    g_io_channel_unref(s->fd);

    close(fd);

    if (s->timer_tag) {

        g_source_remove(s->timer_tag);

        s->timer_tag = 0;

    }

    g_free(s);

    qemu_chr_be_event(chr, CHR_EVENT_CLOSED);

}


av_cold void ff_dct_init_mmx(DCTContext *s)

{

#if HAVE_YASM

    int has_vectors = av_get_cpu_flags();

    if (has_vectors & AV_CPU_FLAG_SSE && HAVE_SSE)

        s->dct32 = ff_dct32_float_sse;

    if (has_vectors & AV_CPU_FLAG_SSE2 && HAVE_SSE)

        s->dct32 = ff_dct32_float_sse2;

    if (has_vectors & AV_CPU_FLAG_AVX && HAVE_AVX)

        s->dct32 = ff_dct32_float_avx;

#endif

}


int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame)

{

    AVFrame *tmp;

    int ret;

    av_assert0(avctx->codec_type == AVMEDIA_TYPE_VIDEO);

    if (!frame->data[0])

        return ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);

    if (av_frame_is_writable(frame)) {

        frame->pkt_pts = avctx->internal->pkt ? avctx->internal->pkt->pts : AV_NOPTS_VALUE;

        frame->reordered_opaque = avctx->reordered_opaque;

        return 0;

    }

    tmp = av_frame_alloc();

    if (!tmp)

        return AVERROR(ENOMEM);

    av_frame_move_ref(tmp, frame);

    ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);

    if (ret < 0) {

        av_frame_free(&tmp);

        return ret;

    }

    av_frame_copy(frame, tmp);

    av_frame_free(&tmp);

    return 0;

}


static void block_dirty_bitmap_add_abort(BlkActionState *common)

{

    BlockDirtyBitmapAdd *action;

    BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,

                                             common, common);

    action = common->action->u.block_dirty_bitmap_add;

    /* Should not be able to fail: IF the bitmap was added via .prepare(),

     * then the node reference and bitmap name must have been valid.

     */

    if (state->prepared) {

        qmp_block_dirty_bitmap_remove(action->node, action->name, &error_abort);

    }

}


static int cirrus_bitblt_common_patterncopy(CirrusVGAState *s, bool videosrc)

{

    uint32_t patternsize;

    uint8_t *dst;

    uint8_t *src;

    dst = s->vga.vram_ptr + s->cirrus_blt_dstaddr;

    if (videosrc) {

        switch (s->vga.get_bpp(&s->vga)) {

        case 8:

            patternsize = 64;

            break;

        case 15:

        case 16:

            patternsize = 128;

            break;

        case 24:

        case 32:

        default:

            patternsize = 256;

            break;

        }

        s->cirrus_blt_srcaddr &= ~(patternsize - 1);

        if (s->cirrus_blt_srcaddr + patternsize > s->vga.vram_size) {

            return 0;

        }

        src = s->vga.vram_ptr + s->cirrus_blt_srcaddr;

    } else {

        src = s->cirrus_bltbuf;

    }

    if (blit_is_unsafe(s, true)) {

        return 0;

    }

    (*s->cirrus_rop) (s, dst, src,

                      s->cirrus_blt_dstpitch, 0,

                      s->cirrus_blt_width, s->cirrus_blt_height);

    cirrus_invalidate_region(s, s->cirrus_blt_dstaddr,

                             s->cirrus_blt_dstpitch, s->cirrus_blt_width,

                             s->cirrus_blt_height);

    return 1;

}


static int nbd_handle_export_name(NBDClient *client, uint32_t length)

{

    int rc = -EINVAL, csock = client->sock;

    char name[256];

    /* Client sends:

        [20 ..  xx]   export name (length bytes)

     */

    TRACE("Checking length");

    if (length > 255) {

        LOG("Bad length received");

        goto fail;

    }

    if (read_sync(csock, name, length) != length) {

        LOG("read failed");

        goto fail;

    }

    name[length] = '\0';

    client->exp = nbd_export_find(name);

    if (!client->exp) {

        LOG("export not found");

        goto fail;

    }

    QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);

    nbd_export_get(client->exp);

    rc = 0;

fail:

    return rc;

}


static void tcg_out_insn_3401(TCGContext *s, AArch64Insn insn, TCGType ext,

                              TCGReg rd, TCGReg rn, uint64_t aimm)

{

    if (aimm > 0xfff) {

        assert((aimm & 0xfff) == 0);

        aimm >>= 12;

        assert(aimm <= 0xfff);

        aimm |= 1 << 12;  /* apply LSL 12 */

    }

    tcg_out32(s, insn | ext << 31 | aimm << 10 | rn << 5 | rd);

}


static int proxy_mkdir(FsContext *fs_ctx, V9fsPath *dir_path,

                       const char *name, FsCred *credp)

{

    int retval;

    V9fsString fullname;

    v9fs_string_init(&fullname);

    v9fs_string_sprintf(&fullname, "%s/%s", dir_path->data, name);

    retval = v9fs_request(fs_ctx->private, T_MKDIR, NULL, "sddd", &fullname,

                          credp->fc_mode, credp->fc_uid, credp->fc_gid);

    v9fs_string_free(&fullname);

    if (retval < 0) {

        errno = -retval;

        retval = -1;

    }

    v9fs_string_free(&fullname);

    return retval;

}


static always_inline uint64_t float_zero_divide_excp (uint64_t arg1, uint64_t arg2)

{

    env->fpscr |= 1 << FPSCR_ZX;

    env->fpscr &= ~((1 << FPSCR_FR) | (1 << FPSCR_FI));

    /* Update the floating-point exception summary */

    env->fpscr |= 1 << FPSCR_FX;

    if (fpscr_ze != 0) {

        /* Update the floating-point enabled exception summary */

        env->fpscr |= 1 << FPSCR_FEX;

        if (msr_fe0 != 0 || msr_fe1 != 0) {

            helper_raise_exception_err(POWERPC_EXCP_PROGRAM,

                                       POWERPC_EXCP_FP | POWERPC_EXCP_FP_ZX);

        }

    } else {

        /* Set the result to infinity */

        arg1 = ((arg1 ^ arg2) & 0x8000000000000000ULL);

        arg1 |= 0x7FFULL << 52;

    }

    return arg1;

}


void *s1d13745_init(qemu_irq gpio_int)

{

    BlizzardState *s = (BlizzardState *) g_malloc0(sizeof(*s));

    DisplaySurface *surface;

    s->fb = g_malloc(0x180000);

    s->con = graphic_console_init(blizzard_update_display,

                                  blizzard_invalidate_display,

                                  blizzard_screen_dump, NULL, s);

    surface = qemu_console_surface(s->con);

    switch (surface_bits_per_pixel(surface)) {

    case 0:

        s->line_fn_tab[0] = s->line_fn_tab[1] =

                g_malloc0(sizeof(blizzard_fn_t) * 0x10);

        break;

    case 8:

        s->line_fn_tab[0] = blizzard_draw_fn_8;

        s->line_fn_tab[1] = blizzard_draw_fn_r_8;

        break;

    case 15:

        s->line_fn_tab[0] = blizzard_draw_fn_15;

        s->line_fn_tab[1] = blizzard_draw_fn_r_15;

        break;

    case 16:

        s->line_fn_tab[0] = blizzard_draw_fn_16;

        s->line_fn_tab[1] = blizzard_draw_fn_r_16;

        break;

    case 24:

        s->line_fn_tab[0] = blizzard_draw_fn_24;

        s->line_fn_tab[1] = blizzard_draw_fn_r_24;

        break;

    case 32:

        s->line_fn_tab[0] = blizzard_draw_fn_32;

        s->line_fn_tab[1] = blizzard_draw_fn_r_32;

        break;

    default:

        fprintf(stderr, "%s: Bad color depth\n", __FUNCTION__);

        exit(1);

    }

    blizzard_reset(s);

    return s;

}


static av_always_inline void h264_filter_mb_fast_internal(H264Context *h,

                                                          H264SliceContext *sl,

                                                          int mb_x, int mb_y,

                                                          uint8_t *img_y,

                                                          uint8_t *img_cb,

                                                          uint8_t *img_cr,

                                                          unsigned int linesize,

                                                          unsigned int uvlinesize,

                                                          int pixel_shift)

{

    int chroma = !(CONFIG_GRAY && (h->flags&CODEC_FLAG_GRAY));

    int chroma444 = CHROMA444(h);

    int chroma422 = CHROMA422(h);

    int mb_xy = h->mb_xy;

    int left_type = sl->left_type[LTOP];

    int top_type  = sl->top_type;

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

    int a = 52 + h->slice_alpha_c0_offset - qp_bd_offset;

    int b = 52 + h->slice_beta_offset - qp_bd_offset;

    int mb_type = h->cur_pic.mb_type[mb_xy];

    int qp      = h->cur_pic.qscale_table[mb_xy];

    int qp0     = h->cur_pic.qscale_table[mb_xy - 1];

    int qp1     = h->cur_pic.qscale_table[sl->top_mb_xy];

    int qpc = get_chroma_qp( h, 0, qp );

    int qpc0 = get_chroma_qp( h, 0, qp0 );

    int qpc1 = get_chroma_qp( h, 0, qp1 );

    qp0 = (qp + qp0 + 1) >> 1;

    qp1 = (qp + qp1 + 1) >> 1;

    qpc0 = (qpc + qpc0 + 1) >> 1;

    qpc1 = (qpc + qpc1 + 1) >> 1;

    if( IS_INTRA(mb_type) ) {

        static const int16_t bS4[4] = {4,4,4,4};

        static const int16_t bS3[4] = {3,3,3,3};

        const int16_t *bSH = FIELD_PICTURE(h) ? bS3 : bS4;

        if(left_type)

            filter_mb_edgev( &img_y[4*0<<pixel_shift], linesize, bS4, qp0, a, b, h, 1);

        if( IS_8x8DCT(mb_type) ) {

            filter_mb_edgev( &img_y[4*2<<pixel_shift], linesize, bS3, qp, a, b, h, 0);

            if(top_type){

                filter_mb_edgeh( &img_y[4*0*linesize], linesize, bSH, qp1, a, b, h, 1);

            }

            filter_mb_edgeh( &img_y[4*2*linesize], linesize, bS3, qp, a, b, h, 0);

        } else {

            filter_mb_edgev( &img_y[4*1<<pixel_shift], linesize, bS3, qp, a, b, h, 0);

            filter_mb_edgev( &img_y[4*2<<pixel_shift], linesize, bS3, qp, a, b, h, 0);

            filter_mb_edgev( &img_y[4*3<<pixel_shift], linesize, bS3, qp, a, b, h, 0);

            if(top_type){

                filter_mb_edgeh( &img_y[4*0*linesize], linesize, bSH, qp1, a, b, h, 1);

            }

            filter_mb_edgeh( &img_y[4*1*linesize], linesize, bS3, qp, a, b, h, 0);

            filter_mb_edgeh( &img_y[4*2*linesize], linesize, bS3, qp, a, b, h, 0);

            filter_mb_edgeh( &img_y[4*3*linesize], linesize, bS3, qp, a, b, h, 0);

        }

        if(chroma){

            if(chroma444){

                if(left_type){

                    filter_mb_edgev( &img_cb[4*0<<pixel_shift], linesize, bS4, qpc0, a, b, h, 1);

                    filter_mb_edgev( &img_cr[4*0<<pixel_shift], linesize, bS4, qpc0, a, b, h, 1);

                }

                if( IS_8x8DCT(mb_type) ) {

                    filter_mb_edgev( &img_cb[4*2<<pixel_shift], linesize, bS3, qpc, a, b, h, 0);

                    filter_mb_edgev( &img_cr[4*2<<pixel_shift], linesize, bS3, qpc, a, b, h, 0);

                    if(top_type){

                        filter_mb_edgeh( &img_cb[4*0*linesize], linesize, bSH, qpc1, a, b, h, 1 );

                        filter_mb_edgeh( &img_cr[4*0*linesize], linesize, bSH, qpc1, a, b, h, 1 );

                    }

                    filter_mb_edgeh( &img_cb[4*2*linesize], linesize, bS3, qpc, a, b, h, 0);

                    filter_mb_edgeh( &img_cr[4*2*linesize], linesize, bS3, qpc, a, b, h, 0);

                } else {

                    filter_mb_edgev( &img_cb[4*1<<pixel_shift], linesize, bS3, qpc, a, b, h, 0);

                    filter_mb_edgev( &img_cr[4*1<<pixel_shift], linesize, bS3, qpc, a, b, h, 0);

                    filter_mb_edgev( &img_cb[4*2<<pixel_shift], linesize, bS3, qpc, a, b, h, 0);

                    filter_mb_edgev( &img_cr[4*2<<pixel_shift], linesize, bS3, qpc, a, b, h, 0);

                    filter_mb_edgev( &img_cb[4*3<<pixel_shift], linesize, bS3, qpc, a, b, h, 0);

                    filter_mb_edgev( &img_cr[4*3<<pixel_shift], linesize, bS3, qpc, a, b, h, 0);

                    if(top_type){

                        filter_mb_edgeh( &img_cb[4*0*linesize], linesize, bSH, qpc1, a, b, h, 1);

                        filter_mb_edgeh( &img_cr[4*0*linesize], linesize, bSH, qpc1, a, b, h, 1);

                    }

                    filter_mb_edgeh( &img_cb[4*1*linesize], linesize, bS3, qpc, a, b, h, 0);

                    filter_mb_edgeh( &img_cr[4*1*linesize], linesize, bS3, qpc, a, b, h, 0);

                    filter_mb_edgeh( &img_cb[4*2*linesize], linesize, bS3, qpc, a, b, h, 0);

                    filter_mb_edgeh( &img_cr[4*2*linesize], linesize, bS3, qpc, a, b, h, 0);

                    filter_mb_edgeh( &img_cb[4*3*linesize], linesize, bS3, qpc, a, b, h, 0);

                    filter_mb_edgeh( &img_cr[4*3*linesize], linesize, bS3, qpc, a, b, h, 0);

                }

            }else if(chroma422){

                if(left_type){

                    filter_mb_edgecv(&img_cb[2*0<<pixel_shift], uvlinesize, bS4, qpc0, a, b, h, 1);

                    filter_mb_edgecv(&img_cr[2*0<<pixel_shift], uvlinesize, bS4, qpc0, a, b, h, 1);

                }

                filter_mb_edgecv(&img_cb[2*2<<pixel_shift], uvlinesize, bS3, qpc, a, b, h, 0);

                filter_mb_edgecv(&img_cr[2*2<<pixel_shift], uvlinesize, bS3, qpc, a, b, h, 0);

                if(top_type){

                    filter_mb_edgech(&img_cb[4*0*uvlinesize], uvlinesize, bSH, qpc1, a, b, h, 1);

                    filter_mb_edgech(&img_cr[4*0*uvlinesize], uvlinesize, bSH, qpc1, a, b, h, 1);

                }

                filter_mb_edgech(&img_cb[4*1*uvlinesize], uvlinesize, bS3, qpc, a, b, h, 0);

                filter_mb_edgech(&img_cr[4*1*uvlinesize], uvlinesize, bS3, qpc, a, b, h, 0);

                filter_mb_edgech(&img_cb[4*2*uvlinesize], uvlinesize, bS3, qpc, a, b, h, 0);

                filter_mb_edgech(&img_cr[4*2*uvlinesize], uvlinesize, bS3, qpc, a, b, h, 0);

                filter_mb_edgech(&img_cb[4*3*uvlinesize], uvlinesize, bS3, qpc, a, b, h, 0);

                filter_mb_edgech(&img_cr[4*3*uvlinesize], uvlinesize, bS3, qpc, a, b, h, 0);

            }else{

                if(left_type){

                    filter_mb_edgecv( &img_cb[2*0<<pixel_shift], uvlinesize, bS4, qpc0, a, b, h, 1);

                    filter_mb_edgecv( &img_cr[2*0<<pixel_shift], uvlinesize, bS4, qpc0, a, b, h, 1);

                }

                filter_mb_edgecv( &img_cb[2*2<<pixel_shift], uvlinesize, bS3, qpc, a, b, h, 0);

                filter_mb_edgecv( &img_cr[2*2<<pixel_shift], uvlinesize, bS3, qpc, a, b, h, 0);

                if(top_type){

                    filter_mb_edgech( &img_cb[2*0*uvlinesize], uvlinesize, bSH, qpc1, a, b, h, 1);

                    filter_mb_edgech( &img_cr[2*0*uvlinesize], uvlinesize, bSH, qpc1, a, b, h, 1);

                }

                filter_mb_edgech( &img_cb[2*2*uvlinesize], uvlinesize, bS3, qpc, a, b, h, 0);

                filter_mb_edgech( &img_cr[2*2*uvlinesize], uvlinesize, bS3, qpc, a, b, h, 0);

            }

        }

        return;

    } else {

        LOCAL_ALIGNED_8(int16_t, bS, [2], [4][4]);

        int edges;

        if( IS_8x8DCT(mb_type) && (sl->cbp&7) == 7 && !chroma444 ) {

            edges = 4;

            AV_WN64A(bS[0][0], 0x0002000200020002ULL);

            AV_WN64A(bS[0][2], 0x0002000200020002ULL);

            AV_WN64A(bS[1][0], 0x0002000200020002ULL);

            AV_WN64A(bS[1][2], 0x0002000200020002ULL);

        } else {

            int mask_edge1 = (3*(((5*mb_type)>>5)&1)) | (mb_type>>4); //(mb_type & (MB_TYPE_16x16 | MB_TYPE_8x16)) ? 3 : (mb_type & MB_TYPE_16x8) ? 1 : 0;

            int mask_edge0 = 3*((mask_edge1>>1) & ((5*left_type)>>5)&1); // (mb_type & (MB_TYPE_16x16 | MB_TYPE_8x16)) && (h->left_type[LTOP] & (MB_TYPE_16x16 | MB_TYPE_8x16)) ? 3 : 0;

            int step =  1+(mb_type>>24); //IS_8x8DCT(mb_type) ? 2 : 1;

            edges = 4 - 3*((mb_type>>3) & !(sl->cbp & 15)); //(mb_type & MB_TYPE_16x16) && !(h->cbp & 15) ? 1 : 4;

            h->h264dsp.h264_loop_filter_strength(bS, sl->non_zero_count_cache, sl->ref_cache, sl->mv_cache,

                                                 sl->list_count==2, edges, step, mask_edge0, mask_edge1, FIELD_PICTURE(h));

        }

        if( IS_INTRA(left_type) )

            AV_WN64A(bS[0][0], 0x0004000400040004ULL);

        if( IS_INTRA(top_type) )

            AV_WN64A(bS[1][0], FIELD_PICTURE(h) ? 0x0003000300030003ULL : 0x0004000400040004ULL);

#define FILTER(hv,dir,edge,intra)\

        if(AV_RN64A(bS[dir][edge])) {                                   \

            filter_mb_edge##hv( &img_y[4*edge*(dir?linesize:1<<pixel_shift)], linesize, bS[dir][edge], edge ? qp : qp##dir, a, b, h, intra );\

            if(chroma){\

                if(chroma444){\

                    filter_mb_edge##hv( &img_cb[4*edge*(dir?linesize:1<<pixel_shift)], linesize, bS[dir][edge], edge ? qpc : qpc##dir, a, b, h, intra );\

                    filter_mb_edge##hv( &img_cr[4*edge*(dir?linesize:1<<pixel_shift)], linesize, bS[dir][edge], edge ? qpc : qpc##dir, a, b, h, intra );\

                } else if(!(edge&1)) {\

                    filter_mb_edgec##hv( &img_cb[2*edge*(dir?uvlinesize:1<<pixel_shift)], uvlinesize, bS[dir][edge], edge ? qpc : qpc##dir, a, b, h, intra );\

                    filter_mb_edgec##hv( &img_cr[2*edge*(dir?uvlinesize:1<<pixel_shift)], uvlinesize, bS[dir][edge], edge ? qpc : qpc##dir, a, b, h, intra );\

                }\

            }\

        }

        if(left_type)

            FILTER(v,0,0,1);

        if( edges == 1 ) {

            if(top_type)

                FILTER(h,1,0,1);

        } else if( IS_8x8DCT(mb_type) ) {

            FILTER(v,0,2,0);

            if(top_type)

                FILTER(h,1,0,1);

            FILTER(h,1,2,0);

        } else {

            FILTER(v,0,1,0);

            FILTER(v,0,2,0);

            FILTER(v,0,3,0);

            if(top_type)

                FILTER(h,1,0,1);

            FILTER(h,1,1,0);

            FILTER(h,1,2,0);

            FILTER(h,1,3,0);

        }

#undef FILTER

    }

}


static void pxb_pcie_dev_realize(PCIDevice *dev, Error **errp)

{

    if (!pci_bus_is_express(dev->bus)) {

        error_setg(errp, "pxb-pcie devices cannot reside on a PCI bus");

        return;

    }

    pxb_dev_realize_common(dev, true, errp);

}


static int float64_is_unordered(int sig, float64 a, float64 b STATUS_PARAM)

{

    if (float64_is_signaling_nan(a) ||

        float64_is_signaling_nan(b) ||

        (sig && (float64_is_nan(a) || float64_is_nan(b)))) {

        float_raise(float_flag_invalid, status);

        return 1;

    } else if (float64_is_nan(a) || float64_is_nan(b)) {

        return 1;

    } else {

        return 0;

    }

}


static void qmp_input_type_str(Visitor *v, const char *name, char **obj,

                               Error **errp)

{

    QmpInputVisitor *qiv = to_qiv(v);

    QObject *qobj = qmp_input_get_object(qiv, name, true, errp);

    QString *qstr;

    *obj = NULL;

    if (!qobj) {

        return;

    }

    qstr = qobject_to_qstring(qobj);

    if (!qstr) {

        error_setg(errp, QERR_INVALID_PARAMETER_TYPE, name ? name : "null",

                   "string");

        return;

    }

    *obj = g_strdup(qstring_get_str(qstr));

}


static int curl_open(BlockDriverState *bs, const char *filename, int flags)

{

    BDRVCURLState *s = bs->opaque;

    CURLState *state = NULL;

    double d;

    #define RA_OPTSTR ":readahead="

    char *file;

    char *ra;

    const char *ra_val;

    int parse_state = 0;

    static int inited = 0;

    file = strdup(filename);

    s->readahead_size = READ_AHEAD_SIZE;

    /* Parse a trailing ":readahead=#:" param, if present. */

    ra = file + strlen(file) - 1;

    while (ra >= file) {

        if (parse_state == 0) {

            if (*ra == ':')

                parse_state++;

            else

                break;

        } else if (parse_state == 1) {

            if (*ra > '9' || *ra < '0') {

                char *opt_start = ra - strlen(RA_OPTSTR) + 1;

                if (opt_start > file &&

                    strncmp(opt_start, RA_OPTSTR, strlen(RA_OPTSTR)) == 0) {

                    ra_val = ra + 1;

                    ra -= strlen(RA_OPTSTR) - 1;

                    *ra = '\0';

                    s->readahead_size = atoi(ra_val);

                    break;

                } else {

                    break;

                }

            }

        }

        ra--;

    }

    if ((s->readahead_size & 0x1ff) != 0) {

        fprintf(stderr, "HTTP_READAHEAD_SIZE %Zd is not a multiple of 512\n",

                s->readahead_size);

        goto out_noclean;

    }

    if (!inited) {

        curl_global_init(CURL_GLOBAL_ALL);

        inited = 1;

    }

    DPRINTF("CURL: Opening %s\n", file);

    s->url = file;

    state = curl_init_state(s);

    if (!state)

        goto out_noclean;

    // Get file size

    curl_easy_setopt(state->curl, CURLOPT_NOBODY, 1);

    curl_easy_setopt(state->curl, CURLOPT_WRITEFUNCTION, (void *)curl_size_cb);

    if (curl_easy_perform(state->curl))

        goto out;

    curl_easy_getinfo(state->curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &d);

    curl_easy_setopt(state->curl, CURLOPT_WRITEFUNCTION, (void *)curl_read_cb);

    curl_easy_setopt(state->curl, CURLOPT_NOBODY, 0);

    if (d)

        s->len = (size_t)d;

    else if(!s->len)

        goto out;

    DPRINTF("CURL: Size = %lld\n", (long long)s->len);

    curl_clean_state(state);

    curl_easy_cleanup(state->curl);

    state->curl = NULL;

    // Now we know the file exists and its size, so let's

    // initialize the multi interface!

    s->multi = curl_multi_init();

    curl_multi_setopt( s->multi, CURLMOPT_SOCKETDATA, s);

    curl_multi_setopt( s->multi, CURLMOPT_SOCKETFUNCTION, curl_sock_cb );

    curl_multi_do(s);

    return 0;

out:

    fprintf(stderr, "CURL: Error opening file: %s\n", state->errmsg);

    curl_easy_cleanup(state->curl);

    state->curl = NULL;

out_noclean:

    qemu_free(file);

    return -EINVAL;

}


static void gen_ldarx(DisasContext *ctx)

{

    TCGv t0;

    gen_set_access_type(ctx, ACCESS_RES);

    t0 = tcg_temp_local_new();

    gen_addr_reg_index(ctx, t0);

    gen_check_align(ctx, t0, 0x07);

    gen_qemu_ld64(ctx, cpu_gpr[rD(ctx->opcode)], t0);

    tcg_gen_mov_tl(cpu_reserve, t0);

    tcg_temp_free(t0);

}


static void virtio_scsi_handle_ctrl(VirtIODevice *vdev, VirtQueue *vq)

{

    VirtIOSCSI *s = (VirtIOSCSI *)vdev;

    VirtIOSCSIReq *req;

    while ((req = virtio_scsi_pop_req(s, vq))) {

        int type;

        if (iov_to_buf(req->elem.out_sg, req->elem.out_num, 0,

                       &type, sizeof(type)) < sizeof(type)) {

            virtio_scsi_bad_req();

            continue;

        }

        tswap32s(&req->req.tmf->type);

        if (req->req.tmf->type == VIRTIO_SCSI_T_TMF) {

            if (virtio_scsi_parse_req(req, sizeof(VirtIOSCSICtrlTMFReq),

                                      sizeof(VirtIOSCSICtrlTMFResp)) < 0) {

                virtio_scsi_bad_req();

            } else {

                virtio_scsi_do_tmf(s, req);

            }

        } else if (req->req.tmf->type == VIRTIO_SCSI_T_AN_QUERY ||

                   req->req.tmf->type == VIRTIO_SCSI_T_AN_SUBSCRIBE) {

            if (virtio_scsi_parse_req(req, sizeof(VirtIOSCSICtrlANReq),

                                      sizeof(VirtIOSCSICtrlANResp)) < 0) {

                virtio_scsi_bad_req();

            } else {

                req->resp.an->event_actual = 0;

                req->resp.an->response = VIRTIO_SCSI_S_OK;

            }

        }

        virtio_scsi_complete_req(req);

    }

}


void arm_cpu_realize(ARMCPU *cpu)

{

    /* This function is called by cpu_arm_init() because it

     * needs to do common actions based on feature bits, etc

     * that have been set by the subclass init functions.

     * When we have QOM realize support it should become

     * a true realize function instead.

     */

    CPUARMState *env = &cpu->env;

    /* Some features automatically imply others: */

    if (arm_feature(env, ARM_FEATURE_V7)) {

        set_feature(env, ARM_FEATURE_VAPA);

        set_feature(env, ARM_FEATURE_THUMB2);

        set_feature(env, ARM_FEATURE_MPIDR);

        if (!arm_feature(env, ARM_FEATURE_M)) {

            set_feature(env, ARM_FEATURE_V6K);

        } else {

            set_feature(env, ARM_FEATURE_V6);

    if (arm_feature(env, ARM_FEATURE_V6K)) {

        set_feature(env, ARM_FEATURE_V6);

        set_feature(env, ARM_FEATURE_MVFR);

    if (arm_feature(env, ARM_FEATURE_V6)) {

        set_feature(env, ARM_FEATURE_V5);

        if (!arm_feature(env, ARM_FEATURE_M)) {

            set_feature(env, ARM_FEATURE_AUXCR);

    if (arm_feature(env, ARM_FEATURE_V5)) {

        set_feature(env, ARM_FEATURE_V4T);

    if (arm_feature(env, ARM_FEATURE_M)) {

        set_feature(env, ARM_FEATURE_THUMB_DIV);

    if (arm_feature(env, ARM_FEATURE_ARM_DIV)) {

        set_feature(env, ARM_FEATURE_THUMB_DIV);

    if (arm_feature(env, ARM_FEATURE_VFP4)) {

        set_feature(env, ARM_FEATURE_VFP3);

    if (arm_feature(env, ARM_FEATURE_VFP3)) {

        set_feature(env, ARM_FEATURE_VFP);

    register_cp_regs_for_features(cpu);


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

                             int *got_frame_ptr, AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    MPCContext *c = avctx->priv_data;

    GetBitContext gb;

    uint8_t *bits;

    int i, ch;

    int mb = -1;

    Band *bands = c->bands;

    int off, ret;

    int bits_used, bits_avail;

    memset(bands, 0, sizeof(*bands) * (c->maxbands + 1));

    if(buf_size <= 4){

        av_log(avctx, AV_LOG_ERROR, "Too small buffer passed (%i bytes)\n", buf_size);

        return AVERROR(EINVAL);

    }

    /* get output buffer */

    c->frame.nb_samples = buf[1] ? c->lastframelen : MPC_FRAME_SIZE;

    if ((ret = avctx->get_buffer(avctx, &c->frame)) < 0) {

        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");

        return ret;

    }

    bits = av_malloc(((buf_size - 1) & ~3) + FF_INPUT_BUFFER_PADDING_SIZE);

    c->dsp.bswap_buf((uint32_t*)bits, (const uint32_t*)(buf + 4), (buf_size - 4) >> 2);

    init_get_bits(&gb, bits, (buf_size - 4)* 8);

    skip_bits_long(&gb, buf[0]);

    /* read subband indexes */

    for(i = 0; i <= c->maxbands; i++){

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

            int t = 4;

            if(i) t = get_vlc2(&gb, hdr_vlc.table, MPC7_HDR_BITS, 1) - 5;

            if(t == 4) bands[i].res[ch] = get_bits(&gb, 4);

            else bands[i].res[ch] = bands[i-1].res[ch] + t;

        }

        if(bands[i].res[0] || bands[i].res[1]){

            mb = i;

            if(c->MSS) bands[i].msf = get_bits1(&gb);

        }

    }

    /* get scale indexes coding method */

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

        for(ch = 0; ch < 2; ch++)

            if(bands[i].res[ch]) bands[i].scfi[ch] = get_vlc2(&gb, scfi_vlc.table, MPC7_SCFI_BITS, 1);

    /* get scale indexes */

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

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

            if(bands[i].res[ch]){

                bands[i].scf_idx[ch][2] = c->oldDSCF[ch][i];

                bands[i].scf_idx[ch][0] = get_scale_idx(&gb, bands[i].scf_idx[ch][2]);

                switch(bands[i].scfi[ch]){

                case 0:

                    bands[i].scf_idx[ch][1] = get_scale_idx(&gb, bands[i].scf_idx[ch][0]);

                    bands[i].scf_idx[ch][2] = get_scale_idx(&gb, bands[i].scf_idx[ch][1]);

                    break;

                case 1:

                    bands[i].scf_idx[ch][1] = get_scale_idx(&gb, bands[i].scf_idx[ch][0]);

                    bands[i].scf_idx[ch][2] = bands[i].scf_idx[ch][1];

                    break;

                case 2:

                    bands[i].scf_idx[ch][1] = bands[i].scf_idx[ch][0];

                    bands[i].scf_idx[ch][2] = get_scale_idx(&gb, bands[i].scf_idx[ch][1]);

                    break;

                case 3:

                    bands[i].scf_idx[ch][2] = bands[i].scf_idx[ch][1] = bands[i].scf_idx[ch][0];

                    break;

                }

                c->oldDSCF[ch][i] = bands[i].scf_idx[ch][2];

            }

        }

    }

    /* get quantizers */

    memset(c->Q, 0, sizeof(c->Q));

    off = 0;

    for(i = 0; i < BANDS; i++, off += SAMPLES_PER_BAND)

        for(ch = 0; ch < 2; ch++)

            idx_to_quant(c, &gb, bands[i].res[ch], c->Q[ch] + off);

    ff_mpc_dequantize_and_synth(c, mb, c->frame.data[0], 2);

    av_free(bits);

    bits_used = get_bits_count(&gb);

    bits_avail = (buf_size - 4) * 8;

    if(!buf[1] && ((bits_avail < bits_used) || (bits_used + 32 <= bits_avail))){

        av_log(NULL,0, "Error decoding frame: used %i of %i bits\n", bits_used, bits_avail);

        return -1;

    }

    if(c->frames_to_skip){

        c->frames_to_skip--;

        *got_frame_ptr = 0;

        return buf_size;

    }

    *got_frame_ptr   = 1;

    *(AVFrame *)data = c->frame;

    return buf_size;

}


static void replication_start(ReplicationState *rs, ReplicationMode mode,
                              Error **errp)
{
    BlockDriverState *bs = rs->opaque;
    BDRVReplicationState *s;
    BlockDriverState *top_bs;
    int64_t active_length, hidden_length, disk_length;
    AioContext *aio_context;
    Error *local_err = NULL;
    BlockJob *job;
    aio_context = bdrv_get_aio_context(bs);
    aio_context_acquire(aio_context);
    s = bs->opaque;
    if (s->stage != BLOCK_REPLICATION_NONE) {
        error_setg(errp, "Block replication is running or done");
        aio_context_release(aio_context);
        return;
    }
    if (s->mode != mode) {
        error_setg(errp, "The parameter mode's value is invalid, needs %d,"
                   " but got %d", s->mode, mode);
        aio_context_release(aio_context);
        return;
    }
    switch (s->mode) {
    case REPLICATION_MODE_PRIMARY:
        break;
    case REPLICATION_MODE_SECONDARY:
        s->active_disk = bs->file;
        if (!s->active_disk || !s->active_disk->bs ||
                                    !s->active_disk->bs->backing) {
            error_setg(errp, "Active disk doesn't have backing file");
            aio_context_release(aio_context);
            return;
        }
        s->hidden_disk = s->active_disk->bs->backing;
        if (!s->hidden_disk->bs || !s->hidden_disk->bs->backing) {
            error_setg(errp, "Hidden disk doesn't have backing file");
            aio_context_release(aio_context);
            return;
        }
        s->secondary_disk = s->hidden_disk->bs->backing;
        if (!s->secondary_disk->bs || !bdrv_has_blk(s->secondary_disk->bs)) {
            error_setg(errp, "The secondary disk doesn't have block backend");
            aio_context_release(aio_context);
            return;
        }
        /* verify the length */
        active_length = bdrv_getlength(s->active_disk->bs);
        hidden_length = bdrv_getlength(s->hidden_disk->bs);
        disk_length = bdrv_getlength(s->secondary_disk->bs);
        if (active_length < 0 || hidden_length < 0 || disk_length < 0 ||
            active_length != hidden_length || hidden_length != disk_length) {
            error_setg(errp, "Active disk, hidden disk, secondary disk's length"
                       " are not the same");
            aio_context_release(aio_context);
            return;
        }
        if (!s->active_disk->bs->drv->bdrv_make_empty ||
            !s->hidden_disk->bs->drv->bdrv_make_empty) {
            error_setg(errp,
                       "Active disk or hidden disk doesn't support make_empty");
            aio_context_release(aio_context);
            return;
        }
        /* reopen the backing file in r/w mode */
        reopen_backing_file(bs, true, &local_err);
        if (local_err) {
            error_propagate(errp, local_err);
            aio_context_release(aio_context);
            return;
        }
        /* start backup job now */
        error_setg(&s->blocker,
                   "Block device is in use by internal backup job");
        top_bs = bdrv_lookup_bs(s->top_id, s->top_id, NULL);
        if (!top_bs || !bdrv_is_root_node(top_bs) ||
            !check_top_bs(top_bs, bs)) {
            error_setg(errp, "No top_bs or it is invalid");
            reopen_backing_file(bs, false, NULL);
            aio_context_release(aio_context);
            return;
        }
        bdrv_op_block_all(top_bs, s->blocker);
        bdrv_op_unblock(top_bs, BLOCK_OP_TYPE_DATAPLANE, s->blocker);
        job = backup_job_create(NULL, s->secondary_disk->bs, s->hidden_disk->bs,
                                0, MIRROR_SYNC_MODE_NONE, NULL, false,
                                BLOCKDEV_ON_ERROR_REPORT,
                                BLOCKDEV_ON_ERROR_REPORT, BLOCK_JOB_INTERNAL,
                                backup_job_completed, bs, NULL, &local_err);
        if (local_err) {
            error_propagate(errp, local_err);
            backup_job_cleanup(bs);
            aio_context_release(aio_context);
            return;
        }
        block_job_start(job);
        break;
    default:
        aio_context_release(aio_context);
        abort();
    }
    s->stage = BLOCK_REPLICATION_RUNNING;
    if (s->mode == REPLICATION_MODE_SECONDARY) {
        secondary_do_checkpoint(s, errp);
    }
    s->error = 0;
    aio_context_release(aio_context);
}


uint8_t* ff_AMediaCodec_getOutputBuffer(FFAMediaCodec* codec, size_t idx, size_t *out_size)

{

    uint8_t *ret = NULL;

    JNIEnv *env = NULL;

    jobject buffer = NULL;

    JNI_GET_ENV_OR_RETURN(env, codec, NULL);

    if (codec->has_get_i_o_buffer) {

        buffer = (*env)->CallObjectMethod(env, codec->object, codec->jfields.get_output_buffer_id, idx);

        if (ff_jni_exception_check(env, 1, codec) < 0) {

            goto fail;

        }

    } else {

        if (!codec->output_buffers) {

            codec->output_buffers = (*env)->CallObjectMethod(env, codec->object, codec->jfields.get_output_buffers_id);

            if (ff_jni_exception_check(env, 1, codec) < 0) {

                goto fail;

            }

            codec->output_buffers = (*env)->NewGlobalRef(env, codec->output_buffers);

            if (ff_jni_exception_check(env, 1, codec) < 0) {

                goto fail;

            }

        }

        buffer = (*env)->GetObjectArrayElement(env, codec->output_buffers, idx);

        if (ff_jni_exception_check(env, 1, codec) < 0) {

            goto fail;

        }

    }

    ret = (*env)->GetDirectBufferAddress(env, buffer);

    *out_size = (*env)->GetDirectBufferCapacity(env, buffer);

fail:

    if (buffer) {

        (*env)->DeleteLocalRef(env, buffer);

    }

    return ret;

}


int cpu_get_dump_info(ArchDumpInfo *info,

                      const struct GuestPhysBlockList *guest_phys_blocks)

{

    PowerPCCPU *cpu = POWERPC_CPU(first_cpu);

    PowerPCCPUClass *pcc = POWERPC_CPU_GET_CLASS(cpu);

    info->d_machine = EM_PPC64;

    info->d_class = ELFCLASS64;

    if ((*pcc->interrupts_big_endian)(cpu)) {

        info->d_endian = ELFDATA2MSB;

    } else {

        info->d_endian = ELFDATA2LSB;

    return 0;


static int try_decode_video_frame(AVCodecContext *codec_ctx, AVPacket *pkt, int decode)

{

    int ret = 0;

    int got_frame = 0;

    AVFrame *frame = NULL;

    int skip_frame = codec_ctx->skip_frame;

    if (!avcodec_is_open(codec_ctx)) {

        const AVCodec *codec = avcodec_find_decoder(codec_ctx->codec_id);

        ret = avcodec_open2(codec_ctx, codec, NULL);

        if (ret < 0) {

            av_log(codec_ctx, AV_LOG_ERROR, "Failed to open codec\n");

            goto end;

        }

    }

    frame = av_frame_alloc();

    if (!frame) {

        av_log(NULL, AV_LOG_ERROR, "Failed to allocate frame\n");

        goto end;

    }

    if (!decode && codec_ctx->codec->caps_internal & FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM) {

        codec_ctx->skip_frame = AVDISCARD_ALL;

    }

    do {

        ret = avcodec_decode_video2(codec_ctx, frame, &got_frame, pkt);

        av_assert0(decode || (!decode && !got_frame));

        if (ret < 0)

            break;

        pkt->data += ret;

        pkt->size -= ret;

        if (got_frame) {

            break;

        }

    } while (pkt->size > 0);

end:

    codec_ctx->skip_frame = skip_frame;

    av_frame_free(&frame);

    return ret;

}


static int tiff_decode_tag(TiffContext *s, AVFrame *frame)

{

    unsigned tag, type, count, off, value = 0, value2 = 0;

    int i, start;

    int pos;

    int ret;

    double *dp;

    ret = ff_tread_tag(&s->gb, s->le, &tag, &type, &count, &start);

    if (ret < 0) {

        goto end;

    }

    off = bytestream2_tell(&s->gb);

    if (count == 1) {

        switch (type) {

        case TIFF_BYTE:

        case TIFF_SHORT:

        case TIFF_LONG:

            value = ff_tget(&s->gb, type, s->le);

            break;

        case TIFF_RATIONAL:

            value  = ff_tget(&s->gb, TIFF_LONG, s->le);

            value2 = ff_tget(&s->gb, TIFF_LONG, s->le);

            break;

        case TIFF_STRING:

            if (count <= 4) {

                break;

            }

        default:

            value = UINT_MAX;

        }

    }

    switch (tag) {

    case TIFF_WIDTH:

        s->width = value;

        break;

    case TIFF_HEIGHT:

        s->height = value;

        break;

    case TIFF_BPP:

        s->bppcount = count;

        if (count > 4) {

            av_log(s->avctx, AV_LOG_ERROR,

                   "This format is not supported (bpp=%d, %d components)\n",

                   s->bpp, count);

            return AVERROR_INVALIDDATA;

        }

        if (count == 1)

            s->bpp = value;

        else {

            switch (type) {

            case TIFF_BYTE:

            case TIFF_SHORT:

            case TIFF_LONG:

                s->bpp = 0;

                if (bytestream2_get_bytes_left(&s->gb) < type_sizes[type] * count)

                    return AVERROR_INVALIDDATA;

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

                    s->bpp += ff_tget(&s->gb, type, s->le);

                break;

            default:

                s->bpp = -1;

            }

        }

        break;

    case TIFF_SAMPLES_PER_PIXEL:

        if (count != 1) {

            av_log(s->avctx, AV_LOG_ERROR,

                   "Samples per pixel requires a single value, many provided\n");

            return AVERROR_INVALIDDATA;

        }

        if (value > 4U) {

            av_log(s->avctx, AV_LOG_ERROR,

                   "Samples per pixel %d is too large\n", value);

            return AVERROR_INVALIDDATA;

        }

        if (s->bppcount == 1)

            s->bpp *= value;

        s->bppcount = value;

        break;

    case TIFF_COMPR:

        s->compr     = value;

        s->predictor = 0;

        switch (s->compr) {

        case TIFF_RAW:

        case TIFF_PACKBITS:

        case TIFF_LZW:

        case TIFF_CCITT_RLE:

            break;

        case TIFF_G3:

        case TIFF_G4:

            s->fax_opts = 0;

            break;

        case TIFF_DEFLATE:

        case TIFF_ADOBE_DEFLATE:

#if CONFIG_ZLIB

            break;

#else

            av_log(s->avctx, AV_LOG_ERROR, "Deflate: ZLib not compiled in\n");

            return AVERROR(ENOSYS);

#endif

        case TIFF_JPEG:

        case TIFF_NEWJPEG:

            avpriv_report_missing_feature(s->avctx, "JPEG compression");

            return AVERROR_PATCHWELCOME;

        case TIFF_LZMA:

#if CONFIG_LZMA

            break;

#else

            av_log(s->avctx, AV_LOG_ERROR, "LZMA not compiled in\n");

            return AVERROR(ENOSYS);

#endif

        default:

            av_log(s->avctx, AV_LOG_ERROR, "Unknown compression method %i\n",

                   s->compr);

            return AVERROR_INVALIDDATA;

        }

        break;

    case TIFF_ROWSPERSTRIP:

        if (!value || (type == TIFF_LONG && value == UINT_MAX))

            value = s->height;

        s->rps = FFMIN(value, s->height);

        break;

    case TIFF_STRIP_OFFS:

        if (count == 1) {

            s->strippos = 0;

            s->stripoff = value;

        } else

            s->strippos = off;

        s->strips = count;

        if (s->strips == 1)

            s->rps = s->height;

        s->sot = type;

        break;

    case TIFF_STRIP_SIZE:

        if (count == 1) {

            s->stripsizesoff = 0;

            s->stripsize     = value;

            s->strips        = 1;

        } else {

            s->stripsizesoff = off;

        }

        s->strips = count;

        s->sstype = type;

        break;

    case TIFF_XRES:

    case TIFF_YRES:

        set_sar(s, tag, value, value2);

        break;

    case TIFF_TILE_BYTE_COUNTS:

    case TIFF_TILE_LENGTH:

    case TIFF_TILE_OFFSETS:

    case TIFF_TILE_WIDTH:

        av_log(s->avctx, AV_LOG_ERROR, "Tiled images are not supported\n");

        return AVERROR_PATCHWELCOME;

        break;

    case TIFF_PREDICTOR:

        s->predictor = value;

        break;

    case TIFF_PHOTOMETRIC:

        switch (value) {

        case TIFF_PHOTOMETRIC_WHITE_IS_ZERO:

        case TIFF_PHOTOMETRIC_BLACK_IS_ZERO:

        case TIFF_PHOTOMETRIC_RGB:

        case TIFF_PHOTOMETRIC_PALETTE:

        case TIFF_PHOTOMETRIC_YCBCR:

            s->photometric = value;

            break;

        case TIFF_PHOTOMETRIC_ALPHA_MASK:

        case TIFF_PHOTOMETRIC_SEPARATED:

        case TIFF_PHOTOMETRIC_CIE_LAB:

        case TIFF_PHOTOMETRIC_ICC_LAB:

        case TIFF_PHOTOMETRIC_ITU_LAB:

        case TIFF_PHOTOMETRIC_CFA:

        case TIFF_PHOTOMETRIC_LOG_L:

        case TIFF_PHOTOMETRIC_LOG_LUV:

        case TIFF_PHOTOMETRIC_LINEAR_RAW:

            avpriv_report_missing_feature(s->avctx,

                                          "PhotometricInterpretation 0x%04X",

                                          value);

            return AVERROR_PATCHWELCOME;

        default:

            av_log(s->avctx, AV_LOG_ERROR, "PhotometricInterpretation %u is "

                   "unknown\n", value);

            return AVERROR_INVALIDDATA;

        }

        break;

    case TIFF_FILL_ORDER:

        if (value < 1 || value > 2) {

            av_log(s->avctx, AV_LOG_ERROR,

                   "Unknown FillOrder value %d, trying default one\n", value);

            value = 1;

        }

        s->fill_order = value - 1;

        break;

    case TIFF_PAL: {

        GetByteContext pal_gb[3];

        off = type_sizes[type];

        if (count / 3 > 256 ||

            bytestream2_get_bytes_left(&s->gb) < count / 3 * off * 3)

            return AVERROR_INVALIDDATA;

        pal_gb[0] = pal_gb[1] = pal_gb[2] = s->gb;

        bytestream2_skip(&pal_gb[1], count / 3 * off);

        bytestream2_skip(&pal_gb[2], count / 3 * off * 2);

        off = (type_sizes[type] - 1) << 3;

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

            uint32_t p = 0xFF000000;

            p |= (ff_tget(&pal_gb[0], type, s->le) >> off) << 16;

            p |= (ff_tget(&pal_gb[1], type, s->le) >> off) << 8;

            p |=  ff_tget(&pal_gb[2], type, s->le) >> off;

            s->palette[i] = p;

        }

        s->palette_is_set = 1;

        break;

    }

    case TIFF_PLANAR:

        s->planar = value == 2;

        break;

    case TIFF_YCBCR_SUBSAMPLING:

        if (count != 2) {

            av_log(s->avctx, AV_LOG_ERROR, "subsample count invalid\n");

            return AVERROR_INVALIDDATA;

        }

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

            s->subsampling[i] = ff_tget(&s->gb, type, s->le);

        break;

    case TIFF_T4OPTIONS:

        if (s->compr == TIFF_G3)

            s->fax_opts = value;

        break;

    case TIFF_T6OPTIONS:

        if (s->compr == TIFF_G4)

            s->fax_opts = value;

        break;

#define ADD_METADATA(count, name, sep)\

    if ((ret = add_metadata(count, type, name, sep, s, frame)) < 0) {\

        av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");\

        goto end;\

    }

    case TIFF_MODEL_PIXEL_SCALE:

        ADD_METADATA(count, "ModelPixelScaleTag", NULL);

        break;

    case TIFF_MODEL_TRANSFORMATION:

        ADD_METADATA(count, "ModelTransformationTag", NULL);

        break;

    case TIFF_MODEL_TIEPOINT:

        ADD_METADATA(count, "ModelTiepointTag", NULL);

        break;

    case TIFF_GEO_KEY_DIRECTORY:

        ADD_METADATA(1, "GeoTIFF_Version", NULL);

        ADD_METADATA(2, "GeoTIFF_Key_Revision", ".");

        s->geotag_count   = ff_tget_short(&s->gb, s->le);

        if (s->geotag_count > count / 4 - 1) {

            s->geotag_count = count / 4 - 1;

            av_log(s->avctx, AV_LOG_WARNING, "GeoTIFF key directory buffer shorter than specified\n");

        }

        if (bytestream2_get_bytes_left(&s->gb) < s->geotag_count * sizeof(int16_t) * 4) {

            s->geotag_count = 0;

            return -1;

        }

        s->geotags = av_mallocz_array(s->geotag_count, sizeof(TiffGeoTag));

        if (!s->geotags) {

            av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");

            s->geotag_count = 0;

            goto end;

        }

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

            s->geotags[i].key    = ff_tget_short(&s->gb, s->le);

            s->geotags[i].type   = ff_tget_short(&s->gb, s->le);

            s->geotags[i].count  = ff_tget_short(&s->gb, s->le);

            if (!s->geotags[i].type)

                s->geotags[i].val  = get_geokey_val(s->geotags[i].key, ff_tget_short(&s->gb, s->le));

            else

                s->geotags[i].offset = ff_tget_short(&s->gb, s->le);

        }

        break;

    case TIFF_GEO_DOUBLE_PARAMS:

        if (count >= INT_MAX / sizeof(int64_t))

            return AVERROR_INVALIDDATA;

        if (bytestream2_get_bytes_left(&s->gb) < count * sizeof(int64_t))

            return AVERROR_INVALIDDATA;

        dp = av_malloc_array(count, sizeof(double));

        if (!dp) {

            av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");

            goto end;

        }

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

            dp[i] = ff_tget_double(&s->gb, s->le);

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

            if (s->geotags[i].type == TIFF_GEO_DOUBLE_PARAMS) {

                if (s->geotags[i].count == 0

                    || s->geotags[i].offset + s->geotags[i].count > count) {

                    av_log(s->avctx, AV_LOG_WARNING, "Invalid GeoTIFF key %d\n", s->geotags[i].key);

                } else {

                    char *ap = doubles2str(&dp[s->geotags[i].offset], s->geotags[i].count, ", ");

                    if (!ap) {

                        av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");

                        av_freep(&dp);

                        return AVERROR(ENOMEM);

                    }

                    s->geotags[i].val = ap;

                }

            }

        }

        av_freep(&dp);

        break;

    case TIFF_GEO_ASCII_PARAMS:

        pos = bytestream2_tell(&s->gb);

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

            if (s->geotags[i].type == TIFF_GEO_ASCII_PARAMS) {

                if (s->geotags[i].count == 0

                    || s->geotags[i].offset +  s->geotags[i].count > count) {

                    av_log(s->avctx, AV_LOG_WARNING, "Invalid GeoTIFF key %d\n", s->geotags[i].key);

                } else {

                    char *ap;

                    bytestream2_seek(&s->gb, pos + s->geotags[i].offset, SEEK_SET);

                    if (bytestream2_get_bytes_left(&s->gb) < s->geotags[i].count)

                        return AVERROR_INVALIDDATA;

                    ap = av_malloc(s->geotags[i].count);

                    if (!ap) {

                        av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");

                        return AVERROR(ENOMEM);

                    }

                    bytestream2_get_bufferu(&s->gb, ap, s->geotags[i].count);

                    ap[s->geotags[i].count - 1] = '\0'; //replace the "|" delimiter with a 0 byte

                    s->geotags[i].val = ap;

                }

            }

        }

        break;

    case TIFF_ARTIST:

        ADD_METADATA(count, "artist", NULL);

        break;

    case TIFF_COPYRIGHT:

        ADD_METADATA(count, "copyright", NULL);

        break;

    case TIFF_DATE:

        ADD_METADATA(count, "date", NULL);

        break;

    case TIFF_DOCUMENT_NAME:

        ADD_METADATA(count, "document_name", NULL);

        break;

    case TIFF_HOST_COMPUTER:

        ADD_METADATA(count, "computer", NULL);

        break;

    case TIFF_IMAGE_DESCRIPTION:

        ADD_METADATA(count, "description", NULL);

        break;

    case TIFF_MAKE:

        ADD_METADATA(count, "make", NULL);

        break;

    case TIFF_MODEL:

        ADD_METADATA(count, "model", NULL);

        break;

    case TIFF_PAGE_NAME:

        ADD_METADATA(count, "page_name", NULL);

        break;

    case TIFF_PAGE_NUMBER:

        ADD_METADATA(count, "page_number", " / ");

        break;

    case TIFF_SOFTWARE_NAME:

        ADD_METADATA(count, "software", NULL);

        break;

    default:

        if (s->avctx->err_recognition & AV_EF_EXPLODE) {

            av_log(s->avctx, AV_LOG_ERROR,

                   "Unknown or unsupported tag %d/0X%0X\n",

                   tag, tag);

            return AVERROR_INVALIDDATA;

        }

    }

end:

    bytestream2_seek(&s->gb, start, SEEK_SET);

    return 0;

}


static int reap_filters(void)

{

    AVFilterBufferRef *picref;

    AVFrame *filtered_frame = NULL;

    int i;

    int64_t frame_pts;

    /* Reap all buffers present in the buffer sinks */

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

        OutputStream *ost = output_streams[i];

        OutputFile    *of = output_files[ost->file_index];

        int ret = 0;

        if (!ost->filter)

            continue;

        if (!ost->filtered_frame && !(ost->filtered_frame = avcodec_alloc_frame())) {

            return AVERROR(ENOMEM);

        } else

            avcodec_get_frame_defaults(ost->filtered_frame);

        filtered_frame = ost->filtered_frame;

        while (1) {

            ret = av_buffersink_get_buffer_ref(ost->filter->filter, &picref,

                                               AV_BUFFERSINK_FLAG_NO_REQUEST);

            if (ret < 0) {

                if (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) {

                    char buf[256];

                    av_strerror(ret, buf, sizeof(buf));

                    av_log(NULL, AV_LOG_WARNING,

                           "Error in av_buffersink_get_buffer_ref(): %s\n", buf);

            frame_pts = AV_NOPTS_VALUE;

            if (picref->pts != AV_NOPTS_VALUE) {

                filtered_frame->pts = frame_pts = av_rescale_q(picref->pts,

                                                ost->filter->filter->inputs[0]->time_base,

                                                ost->st->codec->time_base) -

                                    av_rescale_q(of->start_time,

                                                AV_TIME_BASE_Q,

                                                ost->st->codec->time_base);

                if (of->start_time && filtered_frame->pts < 0) {

                    avfilter_unref_buffer(picref);

                    continue;

            //if (ost->source_index >= 0)

            //    *filtered_frame= *input_streams[ost->source_index]->decoded_frame; //for me_threshold

            switch (ost->filter->filter->inputs[0]->type) {

            case AVMEDIA_TYPE_VIDEO:

                avfilter_copy_buf_props(filtered_frame, picref);

                filtered_frame->pts = frame_pts;

                if (!ost->frame_aspect_ratio)

                    ost->st->codec->sample_aspect_ratio = picref->video->sample_aspect_ratio;

                do_video_out(of->ctx, ost, filtered_frame);

            case AVMEDIA_TYPE_AUDIO:

                avfilter_copy_buf_props(filtered_frame, picref);

                filtered_frame->pts = frame_pts;

                do_audio_out(of->ctx, ost, filtered_frame);

            default:

                // TODO support subtitle filters

                av_assert0(0);

            avfilter_unref_buffer(picref);

    return 0;


static av_always_inline void hl_decode_mb_predict_luma(H264Context *h, int mb_type, int is_h264, int simple, int transform_bypass,

                                                       int pixel_shift, int *block_offset, int linesize, uint8_t *dest_y, int p)

{

    MpegEncContext * const s = &h->s;

    void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);

    void (*idct_dc_add)(uint8_t *dst, DCTELEM *block, int stride);

    int i;

    int qscale = p == 0 ? s->qscale : h->chroma_qp[p-1];

    block_offset += 16*p;

    if(IS_INTRA4x4(mb_type)){

        if(simple || !s->encoding){

            if(IS_8x8DCT(mb_type)){

                if(transform_bypass){

                    idct_dc_add =

                    idct_add    = s->dsp.add_pixels8;

                }else{

                    idct_dc_add = h->h264dsp.h264_idct8_dc_add;

                    idct_add    = h->h264dsp.h264_idct8_add;

                }

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

                    uint8_t * const ptr= dest_y + block_offset[i];

                    const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];

                    if(transform_bypass && h->sps.profile_idc==244 && dir<=1){

                        h->hpc.pred8x8l_add[dir](ptr, h->mb + (i*16+p*256 << pixel_shift), linesize);

                    }else{

                        const int nnz = h->non_zero_count_cache[ scan8[i+p*16] ];

                        h->hpc.pred8x8l[ dir ](ptr, (h->topleft_samples_available<<i)&0x8000,

                                                    (h->topright_samples_available<<i)&0x4000, linesize);

                        if(nnz){

                            if(nnz == 1 && dctcoef_get(h->mb, pixel_shift, i*16+p*256))

                                idct_dc_add(ptr, h->mb + (i*16+p*256 << pixel_shift), linesize);

                            else

                                idct_add   (ptr, h->mb + (i*16+p*256 << pixel_shift), linesize);

                        }

                    }

                }

            }else{

                if(transform_bypass){

                    idct_dc_add =

                    idct_add    = s->dsp.add_pixels4;

                }else{

                    idct_dc_add = h->h264dsp.h264_idct_dc_add;

                    idct_add    = h->h264dsp.h264_idct_add;

                }

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

                    uint8_t * const ptr= dest_y + block_offset[i];

                    const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];

                    if(transform_bypass && h->sps.profile_idc==244 && dir<=1){

                        h->hpc.pred4x4_add[dir](ptr, h->mb + (i*16+p*256 << pixel_shift), linesize);

                    }else{

                        uint8_t *topright;

                        int nnz, tr;

                        uint64_t tr_high;

                        if(dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED){

                            const int topright_avail= (h->topright_samples_available<<i)&0x8000;

                            assert(s->mb_y || linesize <= block_offset[i]);

                            if(!topright_avail){

                                if (pixel_shift) {

                                    tr_high= ((uint16_t*)ptr)[3 - linesize/2]*0x0001000100010001ULL;

                                    topright= (uint8_t*) &tr_high;

                                } else {

                                    tr= ptr[3 - linesize]*0x01010101;

                                    topright= (uint8_t*) &tr;

                                }

                            }else

                                topright= ptr + (4 << pixel_shift) - linesize;

                        }else

                            topright= NULL;

                        h->hpc.pred4x4[ dir ](ptr, topright, linesize);

                        nnz = h->non_zero_count_cache[ scan8[i+p*16] ];

                        if(nnz){

                            if(is_h264){

                                if(nnz == 1 && dctcoef_get(h->mb, pixel_shift, i*16+p*256))

                                    idct_dc_add(ptr, h->mb + (i*16+p*256 << pixel_shift), linesize);

                                else

                                    idct_add   (ptr, h->mb + (i*16+p*256 << pixel_shift), linesize);

                            }else

                                ff_svq3_add_idct_c(ptr, h->mb + i*16+p*256, linesize, qscale, 0);

                        }

                    }

                }

            }

        }

    }else{

        h->hpc.pred16x16[ h->intra16x16_pred_mode ](dest_y , linesize);

        if(is_h264){

            if(h->non_zero_count_cache[ scan8[LUMA_DC_BLOCK_INDEX+p] ]){

                if(!transform_bypass)

                    h->h264dsp.h264_luma_dc_dequant_idct(h->mb+(p*256 << pixel_shift), h->mb_luma_dc[p], h->dequant4_coeff[p][qscale][0]);

                else{

                    static const uint8_t dc_mapping[16] = { 0*16, 1*16, 4*16, 5*16, 2*16, 3*16, 6*16, 7*16,

                                                            8*16, 9*16,12*16,13*16,10*16,11*16,14*16,15*16};

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

                        dctcoef_set(h->mb+p*256, pixel_shift, dc_mapping[i], dctcoef_get(h->mb_luma_dc[p], pixel_shift, i));

                }

            }

        }else

            ff_svq3_luma_dc_dequant_idct_c(h->mb+p*256, h->mb_luma_dc[p], qscale);

    }

}


static int adx_read_packet(AVFormatContext *s, AVPacket *pkt)
{
    ADXDemuxerContext *c = s->priv_data;
    AVCodecContext *avctx = s->streams[0]->codec;
    int ret, size;
    size = BLOCK_SIZE * avctx->channels;
    pkt->pos = avio_tell(s->pb);
    pkt->stream_index = 0;
    ret = av_get_packet(s->pb, pkt, size);
    if (ret != size) {
        av_free_packet(pkt);
        return ret < 0 ? ret : AVERROR(EIO);
    if (AV_RB16(pkt->data) & 0x8000) {
        av_free_packet(pkt);
        return AVERROR_EOF;
    pkt->size     = size;
    pkt->duration = 1;
    pkt->pts      = (pkt->pos - c->header_size) / size;
    return 0;


static int execute_command(BlockDriverState *bdrv,

                           SCSIGenericReq *r, int direction,

			   BlockDriverCompletionFunc *complete)

{

    SCSIGenericState *s = DO_UPCAST(SCSIGenericState, qdev, r->req.dev);

    r->io_header.interface_id = 'S';

    r->io_header.dxfer_direction = direction;

    r->io_header.dxferp = r->buf;

    r->io_header.dxfer_len = r->buflen;

    r->io_header.cmdp = r->req.cmd.buf;

    r->io_header.cmd_len = r->req.cmd.len;

    r->io_header.mx_sb_len = sizeof(s->sensebuf);

    r->io_header.sbp = s->sensebuf;

    r->io_header.timeout = MAX_UINT;

    r->io_header.usr_ptr = r;

    r->io_header.flags |= SG_FLAG_DIRECT_IO;

    r->req.aiocb = bdrv_aio_ioctl(bdrv, SG_IO, &r->io_header, complete, r);

    if (r->req.aiocb == NULL) {

        BADF("execute_command: read failed !\n");

        return -1;

    }

    return 0;

}


static int get_int8(QEMUFile *f, void *pv, size_t size)

{

    int8_t *v = pv;

    qemu_get_s8s(f, v);

    return 0;

}


static void handle_msr(DisasContext *s, uint32_t insn, unsigned int op0,

                       unsigned int op1, unsigned int op2,

                       unsigned int crn, unsigned int crm, unsigned int rt)

{

    unsupported_encoding(s, insn);

}


static void validate_teardown(TestInputVisitorData *data,

                               const void *unused)

{

    qobject_decref(data->obj);

    data->obj = NULL;

    if (data->qiv) {

        visit_free(data->qiv);

        data->qiv = NULL;

    }

}


int kvm_arch_remove_hw_breakpoint(target_ulong addr,

                                  target_ulong len, int type)

{

    int n;

    n = find_hw_breakpoint(addr, (type == GDB_BREAKPOINT_HW) ? 1 : len, type);

    if (n < 0)

        return -ENOENT;

    nb_hw_breakpoint--;

    hw_breakpoint[n] = hw_breakpoint[nb_hw_breakpoint];

    return 0;

}


void HELPER(cas2l)(CPUM68KState *env, uint32_t regs, uint32_t a1, uint32_t a2)

{

    uint32_t Dc1 = extract32(regs, 9, 3);

    uint32_t Dc2 = extract32(regs, 6, 3);

    uint32_t Du1 = extract32(regs, 3, 3);

    uint32_t Du2 = extract32(regs, 0, 3);

    uint32_t c1 = env->dregs[Dc1];

    uint32_t c2 = env->dregs[Dc2];

    uint32_t u1 = env->dregs[Du1];

    uint32_t u2 = env->dregs[Du2];

    uint32_t l1, l2;

    uintptr_t ra = GETPC();

#if defined(CONFIG_ATOMIC64) && !defined(CONFIG_USER_ONLY)

    int mmu_idx = cpu_mmu_index(env, 0);

    TCGMemOpIdx oi;

#endif

    if (parallel_cpus) {

        /* We're executing in a parallel context -- must be atomic.  */

#ifdef CONFIG_ATOMIC64

        uint64_t c, u, l;

        if ((a1 & 7) == 0 && a2 == a1 + 4) {

            c = deposit64(c2, 32, 32, c1);

            u = deposit64(u2, 32, 32, u1);

#ifdef CONFIG_USER_ONLY

            l = helper_atomic_cmpxchgq_be(env, a1, c, u);

#else

            oi = make_memop_idx(MO_BEQ, mmu_idx);

            l = helper_atomic_cmpxchgq_be_mmu(env, a1, c, u, oi, ra);

#endif

            l1 = l >> 32;

            l2 = l;

        } else if ((a2 & 7) == 0 && a1 == a2 + 4) {

            c = deposit64(c1, 32, 32, c2);

            u = deposit64(u1, 32, 32, u2);

#ifdef CONFIG_USER_ONLY

            l = helper_atomic_cmpxchgq_be(env, a2, c, u);

#else

            oi = make_memop_idx(MO_BEQ, mmu_idx);

            l = helper_atomic_cmpxchgq_be_mmu(env, a2, c, u, oi, ra);

#endif

            l2 = l >> 32;

            l1 = l;

        } else

#endif

        {

            /* Tell the main loop we need to serialize this insn.  */

            cpu_loop_exit_atomic(ENV_GET_CPU(env), ra);

        }

    } else {

        /* We're executing in a serial context -- no need to be atomic.  */

        l1 = cpu_ldl_data_ra(env, a1, ra);

        l2 = cpu_ldl_data_ra(env, a2, ra);

        if (l1 == c1 && l2 == c2) {

            cpu_stl_data_ra(env, a1, u1, ra);

            cpu_stl_data_ra(env, a2, u2, ra);

        }

    }

    if (c1 != l1) {

        env->cc_n = l1;

        env->cc_v = c1;

    } else {

        env->cc_n = l2;

        env->cc_v = c2;

    }

    env->cc_op = CC_OP_CMPL;

    env->dregs[Dc1] = l1;

    env->dregs[Dc2] = l2;

}


static inline hwaddr booke206_page_size_to_tlb(uint64_t size)

{

    return (ffs(size >> 10) - 1) >> 1;

}


sofcantrcvmore(struct socket *so)

{

	if ((so->so_state & SS_NOFDREF) == 0) {

		shutdown(so->s,0);

		if(global_writefds) {

		  FD_CLR(so->s,global_writefds);

		}

	}

	so->so_state &= ~(SS_ISFCONNECTING);

	if (so->so_state & SS_FCANTSENDMORE) {

	   so->so_state &= SS_PERSISTENT_MASK;

	   so->so_state |= SS_NOFDREF; /* Don't select it */

	} else {

	   so->so_state |= SS_FCANTRCVMORE;

	}

}


void cpu_breakpoint_remove_all(CPUState *env, int mask)

{

#if defined(TARGET_HAS_ICE)

    CPUBreakpoint *bp, *next;

    TAILQ_FOREACH_SAFE(bp, &env->breakpoints, entry, next) {

        if (bp->flags & mask)

            cpu_breakpoint_remove_by_ref(env, bp);

    }

#endif

}


static void scsi_destroy(SCSIDevice *d)

{

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

    SCSIGenericReq *r;

    while (!QTAILQ_EMPTY(&s->qdev.requests)) {

        r = DO_UPCAST(SCSIGenericReq, req, QTAILQ_FIRST(&s->qdev.requests));

        scsi_remove_request(r);

    }

    blockdev_mark_auto_del(s->qdev.conf.dinfo->bdrv);

}


static inline void kqemu_save_seg(SegmentCache *sc,

                                  const struct kqemu_segment_cache *ksc)

{

    sc->selector = ksc->selector;

    sc->flags = ksc->flags;

    sc->limit = ksc->limit;

    sc->base = ksc->base;

}


static void omap_mpu_timer_write(void *opaque, target_phys_addr_t addr,

                                 uint64_t value, unsigned size)

{

    struct omap_mpu_timer_s *s = (struct omap_mpu_timer_s *) opaque;

    if (size != 4) {

        return omap_badwidth_write32(opaque, addr, value);

    }

    switch (addr) {

    case 0x00:	/* CNTL_TIMER */

        omap_timer_sync(s);

        s->enable = (value >> 5) & 1;

        s->ptv = (value >> 2) & 7;

        s->ar = (value >> 1) & 1;

        s->st = value & 1;

        omap_timer_update(s);

        return;

    case 0x04:	/* LOAD_TIM */

        s->reset_val = value;

        return;

    case 0x08:	/* READ_TIM */

        OMAP_RO_REG(addr);

        break;

    default:

        OMAP_BAD_REG(addr);

    }

}


bool qemu_peer_has_vnet_hdr(NetClientState *nc)

{

    if (!nc->peer || !nc->peer->info->has_vnet_hdr) {

        return false;

    }

    return nc->peer->info->has_vnet_hdr(nc->peer);

}


static void vmxnet3_cleanup(NetClientState *nc)

{

    VMXNET3State *s = qemu_get_nic_opaque(nc);

    s->nic = NULL;

}


void op_cp1_enabled(void)

{

    if (!(env->CP0_Status & (1 << CP0St_CU1))) {

        CALL_FROM_TB2(do_raise_exception_err, EXCP_CpU, 1);

    }

    RETURN();

}


static int put_flac_codecpriv(AVFormatContext *s, ByteIOContext *pb, AVCodecContext *codec)

{

    // if the extradata_size is greater than FLAC_STREAMINFO_SIZE,

    // assume that it's in Matroska format already

    if (codec->extradata_size < FLAC_STREAMINFO_SIZE) {

        av_log(s, AV_LOG_ERROR, "Invalid FLAC extradata\n");

        return -1;

    } else if (codec->extradata_size == FLAC_STREAMINFO_SIZE) {

        // only the streaminfo packet

        put_buffer(pb, "fLaC", 4);

        put_byte(pb, 0x80);

        put_be24(pb, FLAC_STREAMINFO_SIZE);

    } else if(memcmp("fLaC", codec->extradata, 4)) {

        av_log(s, AV_LOG_ERROR, "Invalid FLAC extradata\n");

        return -1;

    }

    put_buffer(pb, codec->extradata, codec->extradata_size);

    return 0;

}


static void core_region_add(MemoryListener *listener,

                            MemoryRegionSection *section)

{

    cpu_register_physical_memory_log(section, section->readonly);

}


static void kvm_mce_inj_srao_memscrub(CPUState *env, target_phys_addr_t paddr)

{

    struct kvm_x86_mce mce = {

        .bank = 9,

        .status = MCI_STATUS_VAL | MCI_STATUS_UC | MCI_STATUS_EN

                  | MCI_STATUS_MISCV | MCI_STATUS_ADDRV | MCI_STATUS_S

                  | 0xc0,

        .mcg_status = MCG_STATUS_MCIP | MCG_STATUS_RIPV,

        .addr = paddr,

        .misc = (MCM_ADDR_PHYS << 6) | 0xc,

    };

    int r;

    r = kvm_set_mce(env, &mce);

    if (r < 0) {

        fprintf(stderr, "kvm_set_mce: %s\n", strerror(errno));

        abort();

    }

    kvm_mce_broadcast_rest(env);

}


int avcodec_open(AVCodecContext *avctx, AVCodec *codec)

{

    int ret;

    if(avctx->codec)

        return -1;

    avctx->codec = codec;

    avctx->codec_id = codec->id;

    avctx->frame_number = 0;

    if (codec->priv_data_size > 0) {

        avctx->priv_data = av_mallocz(codec->priv_data_size);

        if (!avctx->priv_data)

            return -ENOMEM;

    } else {

        avctx->priv_data = NULL;

    }

    if(avctx->coded_width && avctx->coded_height)

        avcodec_set_dimensions(avctx, avctx->coded_width, avctx->coded_height);

    else if(avctx->width && avctx->height)

        avcodec_set_dimensions(avctx, avctx->width, avctx->height);

    if((avctx->coded_width||avctx->coded_height) && avcodec_check_dimensions(avctx,avctx->coded_width,avctx->coded_height)){

        av_freep(&avctx->priv_data);

        return -1;

    }

    ret = avctx->codec->init(avctx);

    if (ret < 0) {

        av_freep(&avctx->priv_data);

        return ret;

    }

    return 0;

}


static inline void RENAME(yv12touyvy)(const uint8_t *ysrc, const uint8_t *usrc, const uint8_t *vsrc, uint8_t *dst,

                                      long width, long height,

                                      long lumStride, long chromStride, long dstStride)

{

    //FIXME interpolate chroma

    RENAME(yuvPlanartouyvy)(ysrc, usrc, vsrc, dst, width, height, lumStride, chromStride, dstStride, 2);

}


static int decode_block_coeffs_internal(VP56RangeCoder *r, int16_t block[16],

                                        uint8_t probs[16][3][NUM_DCT_TOKENS - 1],

                                        int i, uint8_t *token_prob,

                                        int16_t qmul[2])

{

    VP56RangeCoder c = *r;

    goto skip_eob;

    do {

        int coeff;

        if (!vp56_rac_get_prob_branchy(&c, token_prob[0]))   // DCT_EOB

            break;

skip_eob:

        if (!vp56_rac_get_prob_branchy(&c, token_prob[1])) { // DCT_0

            if (++i == 16)

                break; // invalid input; blocks should end with EOB

            token_prob = probs[i][0];

            goto skip_eob;

        }

        if (!vp56_rac_get_prob_branchy(&c, token_prob[2])) { // DCT_1

            coeff = 1;

            token_prob = probs[i + 1][1];

        } else {

            if (!vp56_rac_get_prob_branchy(&c, token_prob[3])) { // DCT 2,3,4

                coeff = vp56_rac_get_prob_branchy(&c, token_prob[4]);

                if (coeff)

                    coeff += vp56_rac_get_prob(&c, token_prob[5]);

                coeff += 2;

            } else {

                // DCT_CAT*

                if (!vp56_rac_get_prob_branchy(&c, token_prob[6])) {

                    if (!vp56_rac_get_prob_branchy(&c, token_prob[7])) { // DCT_CAT1

                        coeff = 5 + vp56_rac_get_prob(&c, vp8_dct_cat1_prob[0]);

                    } else {                                    // DCT_CAT2

                        coeff  = 7;

                        coeff += vp56_rac_get_prob(&c, vp8_dct_cat2_prob[0]) << 1;

                        coeff += vp56_rac_get_prob(&c, vp8_dct_cat2_prob[1]);

                    }

                } else {    // DCT_CAT3 and up

                    int a   = vp56_rac_get_prob(&c, token_prob[8]);

                    int b   = vp56_rac_get_prob(&c, token_prob[9 + a]);

                    int cat = (a << 1) + b;

                    coeff  = 3 + (8 << cat);

                    coeff += vp8_rac_get_coeff(&c, ff_vp8_dct_cat_prob[cat]);

                }

            }

            token_prob = probs[i + 1][2];

        }

        block[zigzag_scan[i]] = (vp8_rac_get(&c) ? -coeff : coeff) * qmul[!!i];

    } while (++i < 16);

    *r = c;

    return i;

}


static int img_check(int argc, char **argv)

{

    int c, ret;

    OutputFormat output_format = OFORMAT_HUMAN;

    const char *filename, *fmt, *output, *cache;

    BlockBackend *blk;

    BlockDriverState *bs;

    int fix = 0;

    int flags = BDRV_O_FLAGS | BDRV_O_CHECK;

    ImageCheck *check;

    bool quiet = false;

    fmt = NULL;

    output = NULL;

    cache = BDRV_DEFAULT_CACHE;

    for(;;) {

        int option_index = 0;

        static const struct option long_options[] = {

            {"help", no_argument, 0, 'h'},

            {"format", required_argument, 0, 'f'},

            {"repair", required_argument, 0, 'r'},

            {"output", required_argument, 0, OPTION_OUTPUT},

            {0, 0, 0, 0}

        };

        c = getopt_long(argc, argv, "hf:r:T:q",

                        long_options, &option_index);

        if (c == -1) {

            break;

        }

        switch(c) {

        case '?':

        case 'h':

            help();

            break;

        case 'f':

            fmt = optarg;

            break;

        case 'r':

            flags |= BDRV_O_RDWR;

            if (!strcmp(optarg, "leaks")) {

                fix = BDRV_FIX_LEAKS;

            } else if (!strcmp(optarg, "all")) {

                fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;

            } else {

                error_exit("Unknown option value for -r "

                           "(expecting 'leaks' or 'all'): %s", optarg);

            }

            break;

        case OPTION_OUTPUT:

            output = optarg;

            break;

        case 'T':

            cache = optarg;

            break;

        case 'q':

            quiet = true;

            break;

        }

    }

    if (optind != argc - 1) {

        error_exit("Expecting one image file name");

    }

    filename = argv[optind++];

    if (output && !strcmp(output, "json")) {

        output_format = OFORMAT_JSON;

    } else if (output && !strcmp(output, "human")) {

        output_format = OFORMAT_HUMAN;

    } else if (output) {

        error_report("--output must be used with human or json as argument.");

        return 1;

    }

    ret = bdrv_parse_cache_flags(cache, &flags);

    if (ret < 0) {

        error_report("Invalid source cache option: %s", cache);

        return 1;

    }

    blk = img_open("image", filename, fmt, flags, true, quiet);

    if (!blk) {

        return 1;

    }

    bs = blk_bs(blk);

    check = g_new0(ImageCheck, 1);

    ret = collect_image_check(bs, check, filename, fmt, fix);

    if (ret == -ENOTSUP) {

        error_report("This image format does not support checks");

        ret = 63;

        goto fail;

    }

    if (check->corruptions_fixed || check->leaks_fixed) {

        int corruptions_fixed, leaks_fixed;

        leaks_fixed         = check->leaks_fixed;

        corruptions_fixed   = check->corruptions_fixed;

        if (output_format == OFORMAT_HUMAN) {

            qprintf(quiet,

                    "The following inconsistencies were found and repaired:\n\n"

                    "    %" PRId64 " leaked clusters\n"

                    "    %" PRId64 " corruptions\n\n"

                    "Double checking the fixed image now...\n",

                    check->leaks_fixed,

                    check->corruptions_fixed);

        }

        ret = collect_image_check(bs, check, filename, fmt, 0);

        check->leaks_fixed          = leaks_fixed;

        check->corruptions_fixed    = corruptions_fixed;

    }

    switch (output_format) {

    case OFORMAT_HUMAN:

        dump_human_image_check(check, quiet);

        break;

    case OFORMAT_JSON:

        dump_json_image_check(check, quiet);

        break;

    }

    if (ret || check->check_errors) {

        ret = 1;

        goto fail;

    }

    if (check->corruptions) {

        ret = 2;

    } else if (check->leaks) {

        ret = 3;

    } else {

        ret = 0;

    }

fail:

    qapi_free_ImageCheck(check);

    blk_unref(blk);

    return ret;

}


int qcow2_snapshot_load_tmp(BlockDriverState *bs,

                            const char *snapshot_id,

                            const char *name,

                            Error **errp)

{

    int i, snapshot_index;

    BDRVQcowState *s = bs->opaque;

    QCowSnapshot *sn;

    uint64_t *new_l1_table;

    int new_l1_bytes;

    int ret;

    assert(bs->read_only);

    /* Search the snapshot */

    snapshot_index = find_snapshot_by_id_and_name(bs, snapshot_id, name);

    if (snapshot_index < 0) {

        error_setg(errp,

                   "Can't find snapshot");

        return -ENOENT;

    }

    sn = &s->snapshots[snapshot_index];

    /* Allocate and read in the snapshot's L1 table */

    if (sn->l1_size > QCOW_MAX_L1_SIZE) {

        error_setg(errp, "Snapshot L1 table too large");

        return -EFBIG;

    }

    new_l1_bytes = sn->l1_size * sizeof(uint64_t);

    new_l1_table = g_malloc0(align_offset(new_l1_bytes, 512));

    ret = bdrv_pread(bs->file, sn->l1_table_offset, new_l1_table, new_l1_bytes);

    if (ret < 0) {

        error_setg(errp, "Failed to read l1 table for snapshot");

        g_free(new_l1_table);

        return ret;

    }

    /* Switch the L1 table */

    g_free(s->l1_table);

    s->l1_size = sn->l1_size;

    s->l1_table_offset = sn->l1_table_offset;

    s->l1_table = new_l1_table;

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

        be64_to_cpus(&s->l1_table[i]);

    }

    return 0;

}


static int vdi_create(const char *filename, QEMUOptionParameter *options,

                      Error **errp)

{

    int fd;

    int result = 0;

    uint64_t bytes = 0;

    uint32_t blocks;

    size_t block_size = DEFAULT_CLUSTER_SIZE;

    uint32_t image_type = VDI_TYPE_DYNAMIC;

    VdiHeader header;

    size_t i;

    size_t bmap_size;

    logout("\n");

    /* Read out options. */

    while (options && options->name) {

        if (!strcmp(options->name, BLOCK_OPT_SIZE)) {

            bytes = options->value.n;

#if defined(CONFIG_VDI_BLOCK_SIZE)

        } else if (!strcmp(options->name, BLOCK_OPT_CLUSTER_SIZE)) {

            if (options->value.n) {

                /* TODO: Additional checks (SECTOR_SIZE * 2^n, ...). */

                block_size = options->value.n;

            }

#endif

#if defined(CONFIG_VDI_STATIC_IMAGE)

        } else if (!strcmp(options->name, BLOCK_OPT_STATIC)) {

            if (options->value.n) {

                image_type = VDI_TYPE_STATIC;

            }

#endif

        }

        options++;

    }

    fd = qemu_open(filename,

                   O_WRONLY | O_CREAT | O_TRUNC | O_BINARY | O_LARGEFILE,

                   0644);

    if (fd < 0) {

        return -errno;

    }

    /* We need enough blocks to store the given disk size,

       so always round up. */

    blocks = (bytes + block_size - 1) / block_size;

    bmap_size = blocks * sizeof(uint32_t);

    bmap_size = ((bmap_size + SECTOR_SIZE - 1) & ~(SECTOR_SIZE -1));

    memset(&header, 0, sizeof(header));

    pstrcpy(header.text, sizeof(header.text), VDI_TEXT);

    header.signature = VDI_SIGNATURE;

    header.version = VDI_VERSION_1_1;

    header.header_size = 0x180;

    header.image_type = image_type;

    header.offset_bmap = 0x200;

    header.offset_data = 0x200 + bmap_size;

    header.sector_size = SECTOR_SIZE;

    header.disk_size = bytes;

    header.block_size = block_size;

    header.blocks_in_image = blocks;

    if (image_type == VDI_TYPE_STATIC) {

        header.blocks_allocated = blocks;

    }

    uuid_generate(header.uuid_image);

    uuid_generate(header.uuid_last_snap);

    /* There is no need to set header.uuid_link or header.uuid_parent here. */

#if defined(CONFIG_VDI_DEBUG)

    vdi_header_print(&header);

#endif

    vdi_header_to_le(&header);

    if (write(fd, &header, sizeof(header)) < 0) {

        result = -errno;

    }

    if (bmap_size > 0) {

        uint32_t *bmap = g_malloc0(bmap_size);

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

            if (image_type == VDI_TYPE_STATIC) {

                bmap[i] = i;

            } else {

                bmap[i] = VDI_UNALLOCATED;

            }

        }

        if (write(fd, bmap, bmap_size) < 0) {

            result = -errno;

        }

        g_free(bmap);

    }

    if (image_type == VDI_TYPE_STATIC) {

        if (ftruncate(fd, sizeof(header) + bmap_size + blocks * block_size)) {

            result = -errno;

        }

    }

    if (close(fd) < 0) {

        result = -errno;

    }

    return result;

}


static int dxa_read_header(AVFormatContext *s, AVFormatParameters *ap)

{

    AVIOContext *pb = s->pb;

    DXAContext *c = s->priv_data;

    AVStream *st, *ast;

    uint32_t tag;

    int32_t fps;

    int w, h;

    int num, den;

    int flags;

    tag = avio_rl32(pb);

    if (tag != MKTAG('D', 'E', 'X', 'A'))

        return -1;

    flags = avio_r8(pb);

    c->frames = avio_rb16(pb);

    if(!c->frames){

        av_log(s, AV_LOG_ERROR, "File contains no frames ???\n");

        return -1;

    }

    fps = avio_rb32(pb);

    if(fps > 0){

        den = 1000;

        num = fps;

    }else if (fps < 0){

        den = 100000;

        num = -fps;

    }else{

        den = 10;

        num = 1;

    }

    w = avio_rb16(pb);

    h = avio_rb16(pb);

    c->has_sound = 0;

    st = av_new_stream(s, 0);

    if (!st)

        return -1;

    // Parse WAV data header

    if(avio_rl32(pb) == MKTAG('W', 'A', 'V', 'E')){

        uint32_t size, fsize;

        c->has_sound = 1;

        size = avio_rb32(pb);

        c->vidpos = avio_tell(pb) + size;

        avio_skip(pb, 16);

        fsize = avio_rl32(pb);

        ast = av_new_stream(s, 0);

        if (!ast)

            return -1;

        ff_get_wav_header(pb, ast->codec, fsize);

        // find 'data' chunk

        while(avio_tell(pb) < c->vidpos && !pb->eof_reached){

            tag = avio_rl32(pb);

            fsize = avio_rl32(pb);

            if(tag == MKTAG('d', 'a', 't', 'a')) break;

            avio_skip(pb, fsize);

        }

        c->bpc = (fsize + c->frames - 1) / c->frames;

        if(ast->codec->block_align)

            c->bpc = ((c->bpc + ast->codec->block_align - 1) / ast->codec->block_align) * ast->codec->block_align;

        c->bytes_left = fsize;

        c->wavpos = avio_tell(pb);

        avio_seek(pb, c->vidpos, SEEK_SET);

    }

    /* now we are ready: build format streams */

    st->codec->codec_type = AVMEDIA_TYPE_VIDEO;

    st->codec->codec_id   = CODEC_ID_DXA;

    st->codec->width      = w;

    st->codec->height     = h;

    av_reduce(&den, &num, den, num, (1UL<<31)-1);

    av_set_pts_info(st, 33, num, den);

    /* flags & 0x80 means that image is interlaced,

     * flags & 0x40 means that image has double height

     * either way set true height

     */

    if(flags & 0xC0){

        st->codec->height >>= 1;

    }

    c->readvid = !c->has_sound;

    c->vidpos  = avio_tell(pb);

    s->start_time = 0;

    s->duration = (int64_t)c->frames * AV_TIME_BASE * num / den;

    av_log(s, AV_LOG_DEBUG, "%d frame(s)\n",c->frames);

    return 0;

}


static int get_cv_color_primaries(AVCodecContext *avctx,

                                  CFStringRef *primaries)

{

    enum AVColorPrimaries pri = avctx->color_primaries;

    switch (pri) {

        case AVCOL_PRI_UNSPECIFIED:

            *primaries = NULL;

            break;

        case AVCOL_PRI_BT709:

            *primaries = kCVImageBufferColorPrimaries_ITU_R_709_2;

            break;

        case AVCOL_PRI_BT2020:

            *primaries = kCVImageBufferColorPrimaries_ITU_R_2020;

            break;

        default:

            av_log(avctx, AV_LOG_ERROR, "Color primaries %s is not supported.\n", av_color_primaries_name(pri));

            *primaries = NULL;

            return -1;

    }

    return 0;

}


static void avc_wgt_4x4multiple_msa(uint8_t *data,

                                    int32_t stride,

                                    int32_t height,

                                    int32_t log2_denom,

                                    int32_t src_weight,

                                    int32_t offset_in)

{

    uint8_t cnt;

    uint32_t data0, data1, data2, data3;

    v16u8 zero = { 0 };

    v16u8 src0, src1, src2, src3;

    v8u16 temp0, temp1, temp2, temp3;

    v8i16 wgt, denom, offset;

    offset_in <<= (log2_denom);

    if (log2_denom) {

        offset_in += (1 << (log2_denom - 1));

    }

    wgt = __msa_fill_h(src_weight);

    offset = __msa_fill_h(offset_in);

    denom = __msa_fill_h(log2_denom);

    for (cnt = height / 4; cnt--;) {

        LOAD_4WORDS_WITH_STRIDE(data, stride, data0, data1, data2, data3);

        src0 = (v16u8) __msa_fill_w(data0);

        src1 = (v16u8) __msa_fill_w(data1);

        src2 = (v16u8) __msa_fill_w(data2);

        src3 = (v16u8) __msa_fill_w(data3);

        ILVR_B_4VECS_UH(src0, src1, src2, src3, zero, zero, zero, zero,

                        temp0, temp1, temp2, temp3);

        temp0 *= wgt;

        temp1 *= wgt;

        temp2 *= wgt;

        temp3 *= wgt;

        ADDS_S_H_4VECS_UH(temp0, offset, temp1, offset,

                          temp2, offset, temp3, offset,

                          temp0, temp1, temp2, temp3);

        MAXI_S_H_4VECS_UH(temp0, temp1, temp2, temp3, 0);

        SRL_H_4VECS_UH(temp0, temp1, temp2, temp3,

                       temp0, temp1, temp2, temp3, denom);

        SAT_U_H_4VECS_UH(temp0, temp1, temp2, temp3, 7);

        PCKEV_B_STORE_4_BYTES_4(temp0, temp1, temp2, temp3, data, stride);

        data += (4 * stride);

    }

}


static void FUNC(flac_decorrelate_indep_c)(uint8_t **out, int32_t **in,

                                           int channels, int len, int shift)

{

    sample *samples = (sample *) OUT(out);

    int i, j;

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

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

            S(samples, i, j) = in[i][j] << shift;

}


void object_property_add_link(Object *obj, const char *name,

                              const char *type, Object **child,

                              void (*check)(Object *, const char *,

                                            Object *, Error **),

                              ObjectPropertyLinkFlags flags,

                              Error **errp)

{

    Error *local_err = NULL;

    LinkProperty *prop = g_malloc(sizeof(*prop));

    gchar *full_type;

    ObjectProperty *op;

    prop->child = child;

    prop->check = check;

    prop->flags = flags;

    full_type = g_strdup_printf("link<%s>", type);

    op = object_property_add(obj, name, full_type,

                             object_get_link_property,

                             check ? object_set_link_property : NULL,

                             object_release_link_property,

                             prop,

                             &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        g_free(prop);

        goto out;

    }

    op->resolve = object_resolve_link_property;

out:

    g_free(full_type);

}