static inline int RENAME(yuv420_rgb15)(SwsContext *c, uint8_t* src[], int srcStride[], int srcSliceY,

             int srcSliceH, uint8_t* dst[], int dstStride[]){

    int y, h_size;

    if(c->srcFormat == PIX_FMT_YUV422P){

	srcStride[1] *= 2;

	srcStride[2] *= 2;

    }

    h_size= (c->dstW+7)&~7;

    if(h_size*2 > FFABS(dstStride[0])) h_size-=8;

    __asm__ __volatile__ ("pxor %mm4, %mm4;" /* zero mm4 */ );

//printf("%X %X %X %X %X %X %X %X %X %X\n", (int)&c->redDither, (int)&b5Dither, (int)src[0], (int)src[1], (int)src[2], (int)dst[0],

//srcStride[0],srcStride[1],srcStride[2],dstStride[0]);

    for (y= 0; y<srcSliceH; y++ ) {

	uint8_t *_image = dst[0] + (y+srcSliceY)*dstStride[0];

	uint8_t *_py = src[0] + y*srcStride[0];

	uint8_t *_pu = src[1] + (y>>1)*srcStride[1];

	uint8_t *_pv = src[2] + (y>>1)*srcStride[2];

	long index= -h_size/2;

	b5Dither= dither8[y&1];

	g6Dither= dither4[y&1];

	g5Dither= dither8[y&1];

	r5Dither= dither8[(y+1)&1];

	    /* this mmx assembly code deals with SINGLE scan line at a time, it convert 8

	       pixels in each iteration */

	    __asm__ __volatile__ (

	/* load data for start of next scan line */

		     "movd (%2, %0), %%mm0;" /* Load 4 Cb 00 00 00 00 u3 u2 u1 u0 */

		     "movd (%3, %0), %%mm1;" /* Load 4 Cr 00 00 00 00 v3 v2 v1 v0 */

		     "movq (%5, %0, 2), %%mm6;" /* Load 8  Y Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y0 */

//		    ".balign 16			\n\t"

		    "1:				\n\t"

YUV2RGB

#ifdef DITHER1XBPP

			"paddusb "MANGLE(b5Dither)", %%mm0	\n\t"

			"paddusb "MANGLE(g5Dither)", %%mm2	\n\t"

			"paddusb "MANGLE(r5Dither)", %%mm1	\n\t"

#endif

		     /* mask unneeded bits off */

		     "pand "MANGLE(mmx_redmask)", %%mm0;" /* b7b6b5b4 b3_0_0_0 b7b6b5b4 b3_0_0_0 */

		     "pand "MANGLE(mmx_redmask)", %%mm2;" /* g7g6g5g4 g3_0_0_0 g7g6g5g4 g3_0_0_0 */

		     "pand "MANGLE(mmx_redmask)", %%mm1;" /* r7r6r5r4 r3_0_0_0 r7r6r5r4 r3_0_0_0 */

		     "psrlw $3,%%mm0;" /* 0_0_0_b7 b6b5b4b3 0_0_0_b7 b6b5b4b3 */

		     "psrlw $1,%%mm1;"            /* 0_r7r6r5  r4r3_0_0 0_r7r6r5 r4r3_0_0 */

		     "pxor %%mm4, %%mm4;" /* zero mm4 */

		     "movq %%mm0, %%mm5;" /* Copy B7-B0 */

		     "movq %%mm2, %%mm7;" /* Copy G7-G0 */

		     /* convert rgb24 plane to rgb16 pack for pixel 0-3 */

		     "punpcklbw %%mm4, %%mm2;" /* 0_0_0_0 0_0_0_0 g7g6g5g4 g3_0_0_0 */

		     "punpcklbw %%mm1, %%mm0;" /* r7r6r5r4 r3_0_0_0 0_0_0_b7 b6b5b4b3 */

		     "psllw $2, %%mm2;" /* 0_0_0_0 0_0_g7g6 g5g4g3_0 0_0_0_0 */

		     "por %%mm2, %%mm0;" /* 0_r7r6r5 r4r3g7g6 g5g4g3b7 b6b5b4b3 */

		     "movq 8 (%5, %0, 2), %%mm6;" /* Load 8 Y Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y0 */

		     MOVNTQ " %%mm0, (%1);" /* store pixel 0-3 */

		     /* convert rgb24 plane to rgb16 pack for pixel 0-3 */

		     "punpckhbw %%mm4, %%mm7;" /* 0_0_0_0 0_0_0_0 0_g7g6g5 g4g3_0_0 */

		     "punpckhbw %%mm1, %%mm5;" /* r7r6r5r4 r3_0_0_0 0_0_0_b7 b6b5b4b3 */

		     "psllw $2, %%mm7;" /* 0_0_0_0 0_0_g7g6 g5g4g3_0 0_0_0_0 */

		     "movd 4 (%2, %0), %%mm0;" /* Load 4 Cb 00 00 00 00 u3 u2 u1 u0 */

		     "por %%mm7, %%mm5;" /* 0_r7r6r5 r4r3g7g6 g5g4g3b7 b6b5b4b3 */

		     "movd 4 (%3, %0), %%mm1;" /* Load 4 Cr 00 00 00 00 v3 v2 v1 v0 */

		     MOVNTQ " %%mm5, 8 (%1);" /* store pixel 4-7 */

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

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

		     " js 1b				\n\t"

		     : "+r" (index), "+r" (_image)

		     : "r" (_pu - index), "r" (_pv - index), "r"(&c->redDither), "r" (_py - 2*index)

		     );

    }

    __asm__ __volatile__ (EMMS);

    return srcSliceH;

}


void OPPROTO op_subfco (void)

{

    do_subfco();

    RETURN();

}


void tcg_target_qemu_prologue(TCGContext *s)

{

    /* stmdb sp!, { r9 - r11, lr } */

    tcg_out32(s, (COND_AL << 28) | 0x092d4e00);

    tcg_out_bx(s, COND_AL, TCG_REG_R0);

    tb_ret_addr = s->code_ptr;

    /* ldmia sp!, { r9 - r11, pc } */

    tcg_out32(s, (COND_AL << 28) | 0x08bd8e00);

}


static int scsi_disk_emulate_mode_sense(SCSIRequest *req, uint8_t *outbuf)

{

    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);

    uint64_t nb_sectors;

    int page, dbd, buflen;

    uint8_t *p;

    uint8_t dev_specific_param;

    dbd = req->cmd.buf[1]  & 0x8;

    page = req->cmd.buf[2] & 0x3f;

    DPRINTF("Mode Sense (page %d, len %zd)\n", page, req->cmd.xfer);

    memset(outbuf, 0, req->cmd.xfer);

    p = outbuf;

    if (bdrv_is_read_only(s->bs)) {

        dev_specific_param = 0x80; /* Readonly.  */

    } else {

        dev_specific_param = 0x00;

    }

    if (req->cmd.buf[0] == MODE_SENSE) {

        p[1] = 0; /* Default media type.  */

        p[2] = dev_specific_param;

        p[3] = 0; /* Block descriptor length.  */

        p += 4;

    } else { /* MODE_SENSE_10 */

        p[2] = 0; /* Default media type.  */

        p[3] = dev_specific_param;

        p[6] = p[7] = 0; /* Block descriptor length.  */

        p += 8;

    }

    bdrv_get_geometry(s->bs, &nb_sectors);

    if ((~dbd) & nb_sectors) {

        if (req->cmd.buf[0] == MODE_SENSE) {

            outbuf[3] = 8; /* Block descriptor length  */

        } else { /* MODE_SENSE_10 */

            outbuf[7] = 8; /* Block descriptor length  */

        }

        nb_sectors /= s->cluster_size;

        nb_sectors--;

        if (nb_sectors > 0xffffff)

            nb_sectors = 0xffffff;

        p[0] = 0; /* media density code */

        p[1] = (nb_sectors >> 16) & 0xff;

        p[2] = (nb_sectors >> 8) & 0xff;

        p[3] = nb_sectors & 0xff;

        p[4] = 0; /* reserved */

        p[5] = 0; /* bytes 5-7 are the sector size in bytes */

        p[6] = s->cluster_size * 2;

        p[7] = 0;

        p += 8;

    }

    switch (page) {

    case 0x04:

    case 0x05:

    case 0x08:

    case 0x2a:

        p += mode_sense_page(req, page, p);

        break;

    case 0x3f:

        p += mode_sense_page(req, 0x08, p);

        p += mode_sense_page(req, 0x2a, p);

        break;

    }

    buflen = p - outbuf;

    /*

     * The mode data length field specifies the length in bytes of the

     * following data that is available to be transferred. The mode data

     * length does not include itself.

     */

    if (req->cmd.buf[0] == MODE_SENSE) {

        outbuf[0] = buflen - 1;

    } else { /* MODE_SENSE_10 */

        outbuf[0] = ((buflen - 2) >> 8) & 0xff;

        outbuf[1] = (buflen - 2) & 0xff;

    }

    if (buflen > req->cmd.xfer)

        buflen = req->cmd.xfer;

    return buflen;

}


void qpci_msix_enable(QPCIDevice *dev)

{

    uint8_t addr;

    uint16_t val;

    uint32_t table;

    uint8_t bir_table;

    uint8_t bir_pba;

    void *offset;

    addr = qpci_find_capability(dev, PCI_CAP_ID_MSIX);

    g_assert_cmphex(addr, !=, 0);

    val = qpci_config_readw(dev, addr + PCI_MSIX_FLAGS);

    qpci_config_writew(dev, addr + PCI_MSIX_FLAGS, val | PCI_MSIX_FLAGS_ENABLE);

    table = qpci_config_readl(dev, addr + PCI_MSIX_TABLE);

    bir_table = table & PCI_MSIX_FLAGS_BIRMASK;

    offset = qpci_iomap(dev, bir_table, NULL);

    dev->msix_table = offset + (table & ~PCI_MSIX_FLAGS_BIRMASK);

    table = qpci_config_readl(dev, addr + PCI_MSIX_PBA);

    bir_pba = table & PCI_MSIX_FLAGS_BIRMASK;

    if (bir_pba != bir_table) {

        offset = qpci_iomap(dev, bir_pba, NULL);

    }

    dev->msix_pba = offset + (table & ~PCI_MSIX_FLAGS_BIRMASK);

    g_assert(dev->msix_table != NULL);

    g_assert(dev->msix_pba != NULL);

    dev->msix_enabled = true;

}


av_cold void ff_lpc_end(LPCContext *s)

{

    av_freep(&s->windowed_samples);

}


static void *handle_apdu_thread(void* arg)

{

    EmulatedState *card = arg;

    uint8_t recv_data[APDU_BUF_SIZE];

    int recv_len;

    VReaderStatus reader_status;

    EmulEvent *event;

    while (1) {

        qemu_mutex_lock(&card->handle_apdu_mutex);

        qemu_cond_wait(&card->handle_apdu_cond, &card->handle_apdu_mutex);

        qemu_mutex_unlock(&card->handle_apdu_mutex);

        if (card->quit_apdu_thread) {

            card->quit_apdu_thread = 0; /* debugging */

            break;

        }

        qemu_mutex_lock(&card->vreader_mutex);

        while (!QSIMPLEQ_EMPTY(&card->guest_apdu_list)) {

            event = QSIMPLEQ_FIRST(&card->guest_apdu_list);

            assert((unsigned long)event > 1000);

            QSIMPLEQ_REMOVE_HEAD(&card->guest_apdu_list, entry);

            if (event->p.data.type != EMUL_GUEST_APDU) {

                DPRINTF(card, 1, "unexpected message in handle_apdu_thread\n");

                g_free(event);

                continue;

            }

            if (card->reader == NULL) {

                DPRINTF(card, 1, "reader is NULL\n");

                g_free(event);

                continue;

            }

            recv_len = sizeof(recv_data);

            reader_status = vreader_xfr_bytes(card->reader,

                    event->p.data.data, event->p.data.len,

                    recv_data, &recv_len);

            DPRINTF(card, 2, "got back apdu of length %d\n", recv_len);

            if (reader_status == VREADER_OK) {

                emulated_push_response_apdu(card, recv_data, recv_len);

            } else {

                emulated_push_error(card, reader_status);

            }

            g_free(event);

        }

        qemu_mutex_unlock(&card->vreader_mutex);

    }

    qemu_mutex_lock(&card->apdu_thread_quit_mutex);

    qemu_cond_signal(&card->apdu_thread_quit_cond);

    qemu_mutex_unlock(&card->apdu_thread_quit_mutex);

    return NULL;

}


static void write_codec_attr(AVStream *st, VariantStream *vs) {

    int codec_strlen = strlen(vs->codec_attr);

    char attr[32];

    if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)

        return;

    if (vs->attr_status == CODEC_ATTRIBUTE_WILL_NOT_BE_WRITTEN)

        return;

    if (st->codecpar->codec_id == AV_CODEC_ID_H264) {

        uint8_t *data = st->codecpar->extradata;

        if ((data[0] | data[1] | data[2]) == 0 && data[3] == 1 && (data[4] & 0x1F) == 7) {

            snprintf(attr, sizeof(attr),

                     "avc1.%02x%02x%02x", data[5], data[6], data[7]);

        } else {

            goto fail;

        }

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

        snprintf(attr, sizeof(attr), "mp4a.40.33");

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

        snprintf(attr, sizeof(attr), "mp4a.40.34");

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

        /* TODO : For HE-AAC, HE-AACv2, the last digit needs to be set to 5 and 29 respectively */

        snprintf(attr, sizeof(attr), "mp4a.40.2");

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

        snprintf(attr, sizeof(attr), "ac-3");

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

        snprintf(attr, sizeof(attr), "ec-3");

    } else {

        goto fail;

    }

    // Don't write the same attribute multiple times

    if (!av_stristr(vs->codec_attr, attr)) {

        snprintf(vs->codec_attr + codec_strlen,

                 sizeof(vs->codec_attr) - codec_strlen,

                 "%s%s", codec_strlen ? "," : "", attr);

    }

    return;

fail:

    vs->codec_attr[0] = '\0';

    vs->attr_status = CODEC_ATTRIBUTE_WILL_NOT_BE_WRITTEN;

    return;

}


static inline void update_rice(APERice *rice, int x)

{

    rice->ksum += ((x + 1) / 2) - ((rice->ksum + 16) >> 5);

    if (rice->k == 0)

        rice->k = 1;

    else if (rice->ksum < (1 << (rice->k + 4)))

        rice->k--;

    else if (rice->ksum >= (1 << (rice->k + 5)))

        rice->k++;

}


static void mpegts_write_pmt(AVFormatContext *s, MpegTSService *service)

{

    MpegTSWrite *ts = s->priv_data;

    uint8_t data[SECTION_LENGTH], *q, *desc_length_ptr, *program_info_length_ptr;

    int val, stream_type, i;

    q = data;

    put16(&q, 0xe000 | service->pcr_pid);

    program_info_length_ptr = q;

    q += 2; /* patched after */

    /* put program info here */

    val = 0xf000 | (q - program_info_length_ptr - 2);

    program_info_length_ptr[0] = val >> 8;

    program_info_length_ptr[1] = val;

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

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

        MpegTSWriteStream *ts_st = st->priv_data;

        AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL, 0);

        switch (st->codec->codec_id) {

        case AV_CODEC_ID_MPEG1VIDEO:

        case AV_CODEC_ID_MPEG2VIDEO:

            stream_type = STREAM_TYPE_VIDEO_MPEG2;

            break;

        case AV_CODEC_ID_MPEG4:

            stream_type = STREAM_TYPE_VIDEO_MPEG4;

            break;

        case AV_CODEC_ID_H264:

            stream_type = STREAM_TYPE_VIDEO_H264;

            break;

        case AV_CODEC_ID_HEVC:

            stream_type = STREAM_TYPE_VIDEO_HEVC;

            break;

        case AV_CODEC_ID_CAVS:

            stream_type = STREAM_TYPE_VIDEO_CAVS;

            break;

        case AV_CODEC_ID_DIRAC:

            stream_type = STREAM_TYPE_VIDEO_DIRAC;

            break;

        case AV_CODEC_ID_MP2:

        case AV_CODEC_ID_MP3:

            stream_type = STREAM_TYPE_AUDIO_MPEG1;

            break;

        case AV_CODEC_ID_AAC:

            stream_type = (ts->flags & MPEGTS_FLAG_AAC_LATM)

                          ? STREAM_TYPE_AUDIO_AAC_LATM

                          : STREAM_TYPE_AUDIO_AAC;

            break;

        case AV_CODEC_ID_AAC_LATM:

            stream_type = STREAM_TYPE_AUDIO_AAC_LATM;

            break;

        case AV_CODEC_ID_AC3:

            stream_type = STREAM_TYPE_AUDIO_AC3;

            break;

        default:

            stream_type = STREAM_TYPE_PRIVATE_DATA;

            break;

        }

        *q++ = stream_type;

        put16(&q, 0xe000 | ts_st->pid);

        desc_length_ptr = q;

        q += 2; /* patched after */

        /* write optional descriptors here */

        switch (st->codec->codec_type) {

        case AVMEDIA_TYPE_AUDIO:

            if (lang) {

                char *p;

                char *next = lang->value;

                uint8_t *len_ptr;

                *q++     = 0x0a; /* ISO 639 language descriptor */

                len_ptr  = q++;

                *len_ptr = 0;

                for (p = lang->value; next && *len_ptr < 255 / 4 * 4; p = next + 1) {

                    next = strchr(p, ',');

                    if (strlen(p) != 3 && (!next || next != p + 3))

                        continue; /* not a 3-letter code */

                    *q++ = *p++;

                    *q++ = *p++;

                    *q++ = *p++;

                    if (st->disposition & AV_DISPOSITION_CLEAN_EFFECTS)

                        *q++ = 0x01;

                    else if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)

                        *q++ = 0x02;

                    else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)

                        *q++ = 0x03;

                    else

                        *q++ = 0; /* undefined type */

                    *len_ptr += 4;

                }

                if (*len_ptr == 0)

                    q -= 2; /* no language codes were written */

            }

            break;

        case AVMEDIA_TYPE_SUBTITLE:

        {

            const char *language;

            language = lang && strlen(lang->value) == 3 ? lang->value : "eng";

            *q++ = 0x59;

            *q++ = 8;

            *q++ = language[0];

            *q++ = language[1];

            *q++ = language[2];

            *q++ = 0x10; /* normal subtitles (0x20 = if hearing pb) */

            if (st->codec->extradata_size == 4) {

                memcpy(q, st->codec->extradata, 4);

                q += 4;

            } else {

                put16(&q, 1);     /* page id */

                put16(&q, 1);     /* ancillary page id */

            }

        }

        break;

        case AVMEDIA_TYPE_VIDEO:

            if (stream_type == STREAM_TYPE_VIDEO_DIRAC) {

                *q++ = 0x05; /*MPEG-2 registration descriptor*/

                *q++ = 4;

                *q++ = 'd';

                *q++ = 'r';

                *q++ = 'a';

                *q++ = 'c';

            }

            break;

        }

        val = 0xf000 | (q - desc_length_ptr - 2);

        desc_length_ptr[0] = val >> 8;

        desc_length_ptr[1] = val;

    }

    mpegts_write_section1(&service->pmt, PMT_TID, service->sid, 0, 0, 0,

                          data, q - data);

}


static void vnc_init_basic_info_from_server_addr(QIOChannelSocket *ioc,
                                                 VncBasicInfo *info,
                                                 Error **errp)
{
    SocketAddress *addr = NULL;
    addr = qio_channel_socket_get_local_address(ioc, errp);
    if (!addr) {
    vnc_init_basic_info(addr, info, errp);
    qapi_free_SocketAddress(addr);


static void external_snapshot_prepare(BlkActionState *common,

                                      Error **errp)

{

    int flags = 0;

    QDict *options = NULL;

    Error *local_err = NULL;

    /* Device and node name of the image to generate the snapshot from */

    const char *device;

    const char *node_name;

    /* Reference to the new image (for 'blockdev-snapshot') */

    const char *snapshot_ref;

    /* File name of the new image (for 'blockdev-snapshot-sync') */

    const char *new_image_file;

    ExternalSnapshotState *state =

                             DO_UPCAST(ExternalSnapshotState, common, common);

    TransactionAction *action = common->action;

    /* 'blockdev-snapshot' and 'blockdev-snapshot-sync' have similar

     * purpose but a different set of parameters */

    switch (action->type) {

    case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT:

        {

            BlockdevSnapshot *s = action->u.blockdev_snapshot.data;

            device = s->node;

            node_name = s->node;

            new_image_file = NULL;

            snapshot_ref = s->overlay;

        }

        break;

    case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC:

        {

            BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;

            device = s->has_device ? s->device : NULL;

            node_name = s->has_node_name ? s->node_name : NULL;

            new_image_file = s->snapshot_file;

            snapshot_ref = NULL;

        }

        break;

    default:

        g_assert_not_reached();

    }

    /* start processing */

    if (action_check_completion_mode(common, errp) < 0) {

        return;

    }

    state->old_bs = bdrv_lookup_bs(device, node_name, errp);

    if (!state->old_bs) {

        return;

    }

    /* Acquire AioContext now so any threads operating on old_bs stop */

    state->aio_context = bdrv_get_aio_context(state->old_bs);

    aio_context_acquire(state->aio_context);

    bdrv_drained_begin(state->old_bs);

    if (!bdrv_is_inserted(state->old_bs)) {

        error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);

        return;

    }

    if (bdrv_op_is_blocked(state->old_bs,

                           BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {

        return;

    }

    if (!bdrv_is_read_only(state->old_bs)) {

        if (bdrv_flush(state->old_bs)) {

            error_setg(errp, QERR_IO_ERROR);

            return;

        }

    }

    if (!bdrv_is_first_non_filter(state->old_bs)) {

        error_setg(errp, QERR_FEATURE_DISABLED, "snapshot");

        return;

    }

    if (action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC) {

        BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;

        const char *format = s->has_format ? s->format : "qcow2";

        enum NewImageMode mode;

        const char *snapshot_node_name =

            s->has_snapshot_node_name ? s->snapshot_node_name : NULL;

        if (node_name && !snapshot_node_name) {

            error_setg(errp, "New snapshot node name missing");

            return;

        }

        if (snapshot_node_name &&

            bdrv_lookup_bs(snapshot_node_name, snapshot_node_name, NULL)) {

            error_setg(errp, "New snapshot node name already in use");

            return;

        }

        flags = state->old_bs->open_flags;

        flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);

        /* create new image w/backing file */

        mode = s->has_mode ? s->mode : NEW_IMAGE_MODE_ABSOLUTE_PATHS;

        if (mode != NEW_IMAGE_MODE_EXISTING) {

            int64_t size = bdrv_getlength(state->old_bs);

            if (size < 0) {

                error_setg_errno(errp, -size, "bdrv_getlength failed");

                return;

            }

            bdrv_img_create(new_image_file, format,

                            state->old_bs->filename,

                            state->old_bs->drv->format_name,

                            NULL, size, flags, false, &local_err);

            if (local_err) {

                error_propagate(errp, local_err);

                return;

            }

        }

        options = qdict_new();

        if (s->has_snapshot_node_name) {

            qdict_put_str(options, "node-name", snapshot_node_name);

        }

        qdict_put_str(options, "driver", format);

        flags |= BDRV_O_NO_BACKING;

    }

    state->new_bs = bdrv_open(new_image_file, snapshot_ref, options, flags,

                              errp);

    /* We will manually add the backing_hd field to the bs later */

    if (!state->new_bs) {

        return;

    }

    if (bdrv_has_blk(state->new_bs)) {

        error_setg(errp, "The snapshot is already in use");

        return;

    }

    if (bdrv_op_is_blocked(state->new_bs, BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT,

                           errp)) {

        return;

    }

    if (state->new_bs->backing != NULL) {

        error_setg(errp, "The snapshot already has a backing image");

        return;

    }

    if (!state->new_bs->drv->supports_backing) {

        error_setg(errp, "The snapshot does not support backing images");

        return;

    }

    bdrv_set_aio_context(state->new_bs, state->aio_context);

    /* This removes our old bs and adds the new bs. This is an operation that

     * can fail, so we need to do it in .prepare; undoing it for abort is

     * always possible. */

    bdrv_ref(state->new_bs);

    bdrv_append(state->new_bs, state->old_bs, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        return;

    }

    state->overlay_appended = true;

}


void qemu_system_reset(bool report)

{

    MachineClass *mc;

    mc = current_machine ? MACHINE_GET_CLASS(current_machine) : NULL;

    cpu_synchronize_all_states();

    if (mc && mc->reset) {

        mc->reset();

    } else {

        qemu_devices_reset();

    }

    if (report) {

        qapi_event_send_reset(&error_abort);

    }

    cpu_synchronize_all_post_reset();

}


void DBDMA_register_channel(void *dbdma, int nchan, qemu_irq irq,

                            DBDMA_rw rw, DBDMA_flush flush,

                            void *opaque)

{

    DBDMAState *s = dbdma;

    DBDMA_channel *ch = &s->channels[nchan];

    DBDMA_DPRINTF("DBDMA_register_channel 0x%x\n", nchan);

    ch->irq = irq;

    ch->channel = nchan;

    ch->rw = rw;

    ch->flush = flush;

    ch->io.opaque = opaque;

    ch->io.channel = ch;

}


void vp78_decode_mv_mb_modes(AVCodecContext *avctx, VP8Frame *curframe,

                                    VP8Frame *prev_frame, int is_vp7)

{

    VP8Context *s = avctx->priv_data;

    int mb_x, mb_y;

    s->mv_min.y = -MARGIN;

    s->mv_max.y = ((s->mb_height - 1) << 6) + MARGIN;

    for (mb_y = 0; mb_y < s->mb_height; mb_y++) {

        VP8Macroblock *mb = s->macroblocks_base +

                            ((s->mb_width + 1) * (mb_y + 1) + 1);

        int mb_xy = mb_y * s->mb_width;

        AV_WN32A(s->intra4x4_pred_mode_left, DC_PRED * 0x01010101);

        s->mv_min.x = -MARGIN;

        s->mv_max.x = ((s->mb_width - 1) << 6) + MARGIN;

        for (mb_x = 0; mb_x < s->mb_width; mb_x++, mb_xy++, mb++) {

            if (mb_y == 0)

                AV_WN32A((mb - s->mb_width - 1)->intra4x4_pred_mode_top,

                         DC_PRED * 0x01010101);

            decode_mb_mode(s, mb, mb_x, mb_y, curframe->seg_map->data + mb_xy,

                           prev_frame && prev_frame->seg_map ?

                           prev_frame->seg_map->data + mb_xy : NULL, 1, is_vp7);

            s->mv_min.x -= 64;

            s->mv_max.x -= 64;

        }

        s->mv_min.y -= 64;

        s->mv_max.y -= 64;

    }

}


static int read_high_coeffs(AVCodecContext *avctx, uint8_t *src, int16_t *dst, int size,

                            int c, int a, int d,

                            int width, ptrdiff_t stride)

{

    PixletContext *ctx = avctx->priv_data;

    GetBitContext *b = &ctx->gbit;

    unsigned cnt1, shbits, rlen, nbits, length, i = 0, j = 0, k;

    int ret, escape, pfx, value, yflag, xflag, flag = 0;

    int64_t state = 3, tmp;

    if ((ret = init_get_bits8(b, src, bytestream2_get_bytes_left(&ctx->gb))) < 0)

      return ret;

    if ((a >= 0) + (a ^ (a >> 31)) - (a >> 31) != 1) {

        nbits = 33 - ff_clz((a >= 0) + (a ^ (a >> 31)) - (a >> 31) - 1);

        if (nbits > 16)

            return AVERROR_INVALIDDATA;

    } else {

        nbits = 1;

    }

    length = 25 - nbits;

    while (i < size) {

        if (state >> 8 != -3) {

            value = ff_clz((state >> 8) + 3) ^ 0x1F;

        } else {

            value = -1;

        }

        cnt1 = get_unary(b, 0, length);

        if (cnt1 >= length) {

            cnt1 = get_bits(b, nbits);

        } else {

            pfx = 14 + ((((uint64_t)(value - 14)) >> 32) & (value - 14));

            cnt1 *= (1 << pfx) - 1;

            shbits = show_bits(b, pfx);

            if (shbits <= 1) {

                skip_bits(b, pfx - 1);

            } else {

                skip_bits(b, pfx);

                cnt1 += shbits - 1;

            }

        }

        xflag = flag + cnt1;

        yflag = xflag;

        if (flag + cnt1 == 0) {

            value = 0;

        } else {

            xflag &= 1u;

            tmp = c * ((yflag + 1) >> 1) + (c >> 1);

            value = xflag + (tmp ^ -xflag);

        }

        i++;

        dst[j++] = value;

        if (j == width) {

            j = 0;

            dst += stride;

        }

        state += d * yflag - (d * state >> 8);

        flag = 0;

        if (state * 4 > 0xFF || i >= size)

            continue;

        pfx = ((state + 8) >> 5) + (state ? ff_clz(state): 32) - 24;

        escape = av_mod_uintp2(16383, pfx);

        cnt1 = get_unary(b, 0, 8);

        if (cnt1 < 8) {

            if (pfx < 1 || pfx > 25)

                return AVERROR_INVALIDDATA;

            value = show_bits(b, pfx);

            if (value > 1) {

                skip_bits(b, pfx);

                rlen = value + escape * cnt1 - 1;

            } else {

                skip_bits(b, pfx - 1);

                rlen = escape * cnt1;

            }

        } else {

            if (get_bits1(b))

                value = get_bits(b, 16);

            else

                value = get_bits(b, 8);

            rlen = value + 8 * escape;

        }

        if (rlen > 0xFFFF || i + rlen > size)

            return AVERROR_INVALIDDATA;

        i += rlen;

        for (k = 0; k < rlen; k++) {

            dst[j++] = 0;

            if (j == width) {

                j = 0;

                dst += stride;

            }

        }

        state = 0;

        flag = rlen < 0xFFFF ? 1 : 0;

    }

    align_get_bits(b);

    return get_bits_count(b) >> 3;

}


static void vc1_decode_i_blocks_adv(VC1Context *v)

{

    int k;

    MpegEncContext *s = &v->s;

    int cbp, val;

    uint8_t *coded_val;

    int mb_pos;

    int mquant = v->pq;

    int mqdiff;

    GetBitContext *gb = &s->gb;

    /* select codingmode used for VLC tables selection */

    switch(v->y_ac_table_index){

    case 0:

        v->codingset = (v->pqindex <= 8) ? CS_HIGH_RATE_INTRA : CS_LOW_MOT_INTRA;

        break;

    case 1:

        v->codingset = CS_HIGH_MOT_INTRA;

        break;

    case 2:

        v->codingset = CS_MID_RATE_INTRA;

        break;

    }

    switch(v->c_ac_table_index){

    case 0:

        v->codingset2 = (v->pqindex <= 8) ? CS_HIGH_RATE_INTER : CS_LOW_MOT_INTER;

        break;

    case 1:

        v->codingset2 = CS_HIGH_MOT_INTER;

        break;

    case 2:

        v->codingset2 = CS_MID_RATE_INTER;

        break;

    }

    //do frame decode

    s->mb_x = s->mb_y = 0;

    s->mb_intra = 1;

    s->first_slice_line = 1;

    s->mb_y = s->start_mb_y;

    if (s->start_mb_y) {

        s->mb_x = 0;

        ff_init_block_index(s);

        memset(&s->coded_block[s->block_index[0]-s->b8_stride], 0,

               s->b8_stride * sizeof(*s->coded_block));

    }

    for(; s->mb_y < s->end_mb_y; s->mb_y++) {

        s->mb_x = 0;

        ff_init_block_index(s);

        for(;s->mb_x < s->mb_width; s->mb_x++) {

            DCTELEM (*block)[64] = v->block[v->cur_blk_idx];

            ff_update_block_index(s);

            s->dsp.clear_blocks(block[0]);

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

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

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

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

            // do actual MB decoding and displaying

            cbp = get_vlc2(&v->s.gb, ff_msmp4_mb_i_vlc.table, MB_INTRA_VLC_BITS, 2);

            if(v->acpred_is_raw)

                v->s.ac_pred = get_bits1(&v->s.gb);

            else

                v->s.ac_pred = v->acpred_plane[mb_pos];

            if (v->condover == CONDOVER_SELECT && v->overflg_is_raw)

                v->over_flags_plane[mb_pos] = get_bits1(&v->s.gb);

            GET_MQUANT();

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

            /* Set DC scale - y and c use the same */

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

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

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

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

                if (k < 4) {

                    int pred = vc1_coded_block_pred(&v->s, k, &coded_val);

                    val = val ^ pred;

                    *coded_val = val;

                }

                cbp |= val << (5 - k);

                v->a_avail = !s->first_slice_line || (k==2 || k==3);

                v->c_avail = !!s->mb_x || (k==1 || k==3);

                vc1_decode_i_block_adv(v, block[k], k, val, (k<4)? v->codingset : v->codingset2, mquant);

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

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

            }

            vc1_smooth_overlap_filter_iblk(v);

            vc1_put_signed_blocks_clamped(v);

            if(v->s.loop_filter) vc1_loop_filter_iblk_delayed(v, v->pq);

            if(get_bits_count(&s->gb) > v->bits) {

                ff_er_add_slice(s, 0, s->start_mb_y, s->mb_x, s->mb_y, (AC_END|DC_END|MV_END));

                av_log(s->avctx, AV_LOG_ERROR, "Bits overconsumption: %i > %i\n", get_bits_count(&s->gb), v->bits);

                return;

            }

        }

        if (!v->s.loop_filter)

            ff_draw_horiz_band(s, s->mb_y * 16, 16);

        else if (s->mb_y)

            ff_draw_horiz_band(s, (s->mb_y-1) * 16, 16);

        s->first_slice_line = 0;

    }

    /* raw bottom MB row */

    s->mb_x = 0;

    ff_init_block_index(s);

    for(;s->mb_x < s->mb_width; s->mb_x++) {

        ff_update_block_index(s);

        vc1_put_signed_blocks_clamped(v);

        if(v->s.loop_filter) vc1_loop_filter_iblk_delayed(v, v->pq);

    }

    if (v->s.loop_filter)

        ff_draw_horiz_band(s, (s->mb_height-1)*16, 16);

    ff_er_add_slice(s, 0, s->start_mb_y, s->mb_width - 1, s->end_mb_y - 1, (AC_END|DC_END|MV_END));

}


static int rtp_mpegts_write_header(AVFormatContext *s)

{

    struct MuxChain *chain = s->priv_data;

    AVFormatContext *mpegts_ctx = NULL, *rtp_ctx = NULL;

    AVOutputFormat *mpegts_format = av_guess_format("mpegts", NULL, NULL);

    AVOutputFormat *rtp_format    = av_guess_format("rtp", NULL, NULL);

    int i, ret = AVERROR(ENOMEM);

    AVStream *st;

    if (!mpegts_format || !rtp_format)

        return AVERROR(ENOSYS);

    mpegts_ctx = avformat_alloc_context();

    if (!mpegts_ctx)

        return AVERROR(ENOMEM);

    mpegts_ctx->oformat   = mpegts_format;

    mpegts_ctx->max_delay = s->max_delay;

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

        AVStream* st = avformat_new_stream(mpegts_ctx, NULL);

        if (!st)

        st->time_base           = s->streams[i]->time_base;

        st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;

        avcodec_parameters_copy(st->codecpar, s->streams[i]->codecpar);

    if ((ret = avio_open_dyn_buf(&mpegts_ctx->pb)) < 0)

    if ((ret = avformat_write_header(mpegts_ctx, NULL)) < 0)

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

        s->streams[i]->time_base = mpegts_ctx->streams[i]->time_base;

    chain->mpegts_ctx = mpegts_ctx;

    mpegts_ctx = NULL;

    rtp_ctx = avformat_alloc_context();

    if (!rtp_ctx) {

    rtp_ctx->oformat = rtp_format;

    st = avformat_new_stream(rtp_ctx, NULL);

    st->time_base.num   = 1;

    st->time_base.den   = 90000;

    st->codecpar->codec_id = AV_CODEC_ID_MPEG2TS;

    rtp_ctx->pb = s->pb;

    if ((ret = avformat_write_header(rtp_ctx, NULL)) < 0)

    chain->rtp_ctx = rtp_ctx;

    return 0;

fail:

    if (mpegts_ctx) {

        ffio_free_dyn_buf(&mpegts_ctx->pb);

        avformat_free_context(mpegts_ctx);

    if (rtp_ctx)

        avformat_free_context(rtp_ctx);

    rtp_mpegts_write_close(s);

    return ret;


void qemu_aio_coroutine_enter(AioContext *ctx, Coroutine *co)
{
    Coroutine *self = qemu_coroutine_self();
    CoroutineAction ret;
    trace_qemu_aio_coroutine_enter(ctx, self, co, co->entry_arg);
    if (co->caller) {
        fprintf(stderr, "Co-routine re-entered recursively\n");
    co->caller = self;
    co->ctx = ctx;
    /* Store co->ctx before anything that stores co.  Matches
     * barrier in aio_co_wake and qemu_co_mutex_wake.
     */
    smp_wmb();
    ret = qemu_coroutine_switch(self, co, COROUTINE_ENTER);
    qemu_co_queue_run_restart(co);
    /* Beware, if ret == COROUTINE_YIELD and qemu_co_queue_run_restart()
     * has started any other coroutine, "co" might have been reentered
     * and even freed by now!  So be careful and do not touch it.
     */
    switch (ret) {
    case COROUTINE_YIELD:
        return;
    case COROUTINE_TERMINATE:
        assert(!co->locks_held);
        trace_qemu_coroutine_terminate(co);
        coroutine_delete(co);
        return;
    default:


static sPAPRDIMMState *spapr_recover_pending_dimm_state(sPAPRMachineState *ms,

                                                        PCDIMMDevice *dimm)

{

    sPAPRDRConnector *drc;

    PCDIMMDeviceClass *ddc = PC_DIMM_GET_CLASS(dimm);

    MemoryRegion *mr = ddc->get_memory_region(dimm);

    uint64_t size = memory_region_size(mr);

    uint32_t nr_lmbs = size / SPAPR_MEMORY_BLOCK_SIZE;

    uint32_t avail_lmbs = 0;

    uint64_t addr_start, addr;

    int i;

    sPAPRDIMMState *ds;

    addr_start = object_property_get_int(OBJECT(dimm), PC_DIMM_ADDR_PROP,

                                         &error_abort);

    addr = addr_start;

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

        drc = spapr_drc_by_id(TYPE_SPAPR_DRC_LMB,

                              addr / SPAPR_MEMORY_BLOCK_SIZE);

        g_assert(drc);

        if (drc->indicator_state != SPAPR_DR_INDICATOR_STATE_INACTIVE) {

            avail_lmbs++;

        }

        addr += SPAPR_MEMORY_BLOCK_SIZE;

    }

    ds = g_malloc0(sizeof(sPAPRDIMMState));

    ds->nr_lmbs = avail_lmbs;

    ds->dimm = dimm;

    spapr_pending_dimm_unplugs_add(ms, ds);

    return ds;

}


static void term_print_cmdline (const char *cmdline)

{

    term_show_prompt();

    term_printf(cmdline);

    term_flush();

}


static void dvbsub_parse_clut_segment(AVCodecContext *avctx,

                                        const uint8_t *buf, int buf_size)

{

    DVBSubContext *ctx = avctx->priv_data;

    const uint8_t *buf_end = buf + buf_size;

    int i, clut_id;

    int version;

    DVBSubCLUT *clut;

    int entry_id, depth , full_range;

    int y, cr, cb, alpha;

    int r, g, b, r_add, g_add, b_add;

    av_dlog(avctx, "DVB clut packet:\n");

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

        av_dlog(avctx, "%02x ", buf[i]);

        if (i % 16 == 15)

            av_dlog(avctx, "\n");

    }

    if (i % 16)

        av_dlog(avctx, "\n");

    clut_id = *buf++;

    version = ((*buf)>>4)&15;

    buf += 1;

    clut = get_clut(ctx, clut_id);

    if (!clut) {

        clut = av_malloc(sizeof(DVBSubCLUT));

        memcpy(clut, &default_clut, sizeof(DVBSubCLUT));

        clut->id = clut_id;

        clut->version = -1;

        clut->next = ctx->clut_list;

        ctx->clut_list = clut;

    }

    if (clut->version != version) {

    clut->version = version;

    while (buf + 4 < buf_end) {

        entry_id = *buf++;

        depth = (*buf) & 0xe0;

        if (depth == 0) {

            av_log(avctx, AV_LOG_ERROR, "Invalid clut depth 0x%x!\n", *buf);

            return;

        }

        full_range = (*buf++) & 1;

        if (full_range) {

            y = *buf++;

            cr = *buf++;

            cb = *buf++;

            alpha = *buf++;

        } else {

            y = buf[0] & 0xfc;

            cr = (((buf[0] & 3) << 2) | ((buf[1] >> 6) & 3)) << 4;

            cb = (buf[1] << 2) & 0xf0;

            alpha = (buf[1] << 6) & 0xc0;

            buf += 2;

        }

        if (y == 0)

            alpha = 0xff;

        YUV_TO_RGB1_CCIR(cb, cr);

        YUV_TO_RGB2_CCIR(r, g, b, y);

        av_dlog(avctx, "clut %d := (%d,%d,%d,%d)\n", entry_id, r, g, b, alpha);

        if (depth & 0x80)

            clut->clut4[entry_id] = RGBA(r,g,b,255 - alpha);

        else if (depth & 0x40)

            clut->clut16[entry_id] = RGBA(r,g,b,255 - alpha);

        else if (depth & 0x20)

            clut->clut256[entry_id] = RGBA(r,g,b,255 - alpha);

    }

    }

}


static SCSIGenericReq *scsi_find_request(SCSIGenericState *s, uint32_t tag)

{

    return DO_UPCAST(SCSIGenericReq, req, scsi_req_find(&s->qdev, tag));

}


static void do_safe_dpy_refresh(CPUState *cpu, run_on_cpu_data opaque)

{

    DisplayChangeListener *dcl = opaque.host_ptr;

    dcl->ops->dpy_refresh(dcl);

}


void HELPER(exception_return)(CPUARMState *env)

{

    int cur_el = arm_current_el(env);

    unsigned int spsr_idx = aarch64_banked_spsr_index(cur_el);

    uint32_t spsr = env->banked_spsr[spsr_idx];

    int new_el;

    aarch64_save_sp(env, cur_el);

    env->exclusive_addr = -1;

    /* We must squash the PSTATE.SS bit to zero unless both of the

     * following hold:

     *  1. debug exceptions are currently disabled

     *  2. singlestep will be active in the EL we return to

     * We check 1 here and 2 after we've done the pstate/cpsr write() to

     * transition to the EL we're going to.

     */

    if (arm_generate_debug_exceptions(env)) {

        spsr &= ~PSTATE_SS;

    }

    if (spsr & PSTATE_nRW) {

        /* TODO: We currently assume EL1/2/3 are running in AArch64.  */

        env->aarch64 = 0;

        new_el = 0;

        env->uncached_cpsr = 0x10;

        cpsr_write(env, spsr, ~0);

        if (!arm_singlestep_active(env)) {

            env->uncached_cpsr &= ~PSTATE_SS;

        }

        aarch64_sync_64_to_32(env);

        env->regs[15] = env->elr_el[1] & ~0x1;

    } else {

        new_el = extract32(spsr, 2, 2);

        if (new_el > cur_el

            || (new_el == 2 && !arm_feature(env, ARM_FEATURE_EL2))) {

            /* Disallow return to an EL which is unimplemented or higher

             * than the current one.

             */

            goto illegal_return;

        }

        if (extract32(spsr, 1, 1)) {

            /* Return with reserved M[1] bit set */

            goto illegal_return;

        }

        if (new_el == 0 && (spsr & PSTATE_SP)) {

            /* Return to EL0 with M[0] bit set */

            goto illegal_return;

        }

        env->aarch64 = 1;

        pstate_write(env, spsr);

        if (!arm_singlestep_active(env)) {

            env->pstate &= ~PSTATE_SS;

        }

        aarch64_restore_sp(env, new_el);

        env->pc = env->elr_el[cur_el];

    }

    return;

illegal_return:

    /* Illegal return events of various kinds have architecturally

     * mandated behaviour:

     * restore NZCV and DAIF from SPSR_ELx

     * set PSTATE.IL

     * restore PC from ELR_ELx

     * no change to exception level, execution state or stack pointer

     */

    env->pstate |= PSTATE_IL;

    env->pc = env->elr_el[cur_el];

    spsr &= PSTATE_NZCV | PSTATE_DAIF;

    spsr |= pstate_read(env) & ~(PSTATE_NZCV | PSTATE_DAIF);

    pstate_write(env, spsr);

    if (!arm_singlestep_active(env)) {

        env->pstate &= ~PSTATE_SS;

    }

}


target_ulong helper_evpe(CPUMIPSState *env)

{

    CPUMIPSState *other_cpu = first_cpu;

    target_ulong prev = env->mvp->CP0_MVPControl;

    do {

        if (other_cpu != env

           /* If the VPE is WFI, don't disturb its sleep.  */

           && !mips_vpe_is_wfi(other_cpu)) {

            /* Enable the VPE.  */

            other_cpu->mvp->CP0_MVPControl |= (1 << CP0MVPCo_EVP);

            mips_vpe_wake(other_cpu); /* And wake it up.  */

        }

        other_cpu = other_cpu->next_cpu;

    } while (other_cpu);

    return prev;

}


static void gen_tlbld_74xx(DisasContext *ctx)

{

#if defined(CONFIG_USER_ONLY)

    gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

#else

    if (unlikely(ctx->pr)) {

        gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

        return;

    }

    gen_helper_74xx_tlbd(cpu_env, cpu_gpr[rB(ctx->opcode)]);

#endif

}


static void kvmclock_realize(DeviceState *dev, Error **errp)
{
    KVMClockState *s = KVM_CLOCK(dev);
    kvm_update_clock(s);
    qemu_add_vm_change_state_handler(kvmclock_vm_state_change, s);


static const uint8_t *pcx_rle_decode(const uint8_t *src, uint8_t *dst,

                                     unsigned int bytes_per_scanline,

                                     int compressed)

{

    unsigned int i = 0;

    unsigned char run, value;

    if (compressed) {

        while (i < bytes_per_scanline) {

            run   = 1;

            value = *src++;

            if (value >= 0xc0) {

                run   = value & 0x3f;

                value = *src++;

            }

            while (i < bytes_per_scanline && run--)

                dst[i++] = value;

        }

    } else {

        memcpy(dst, src, bytes_per_scanline);

        src += bytes_per_scanline;

    }

    return src;

}


void checkasm_check_h264pred(void)

{

    static const struct {

        void (*func)(H264PredContext*, uint8_t*, uint8_t*, int, int, int);

        const char *name;

    } tests[] = {

        { check_pred4x4,   "pred4x4"   },

        { check_pred8x8,   "pred8x8"   },

        { check_pred16x16, "pred16x16" },

        { check_pred8x8l,  "pred8x8l"  },

    };

    DECLARE_ALIGNED(16, uint8_t, buf0)[BUF_SIZE];

    DECLARE_ALIGNED(16, uint8_t, buf1)[BUF_SIZE];

    H264PredContext h;

    int test, codec, chroma_format, bit_depth;

    for (test = 0; test < FF_ARRAY_ELEMS(tests); test++) {

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

            int codec_id = codec_ids[codec];

            for (bit_depth = 8; bit_depth <= (codec_id == AV_CODEC_ID_H264 ? 10 : 8); bit_depth++)

                for (chroma_format = 1; chroma_format <= (codec_id == AV_CODEC_ID_H264 ? 2 : 1); chroma_format++) {

                    ff_h264_pred_init(&h, codec_id, bit_depth, chroma_format);

                    tests[test].func(&h, buf0, buf1, codec, chroma_format, bit_depth);

                }

        }

        report("%s", tests[test].name);

    }

}


static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)

{

    AVStream *st;

    MOVStreamContext *sc;

    unsigned int i, entries;

    if (c->fc->nb_streams < 1)

        return 0;

    st = c->fc->streams[c->fc->nb_streams-1];

    sc = st->priv_data;

    avio_r8(pb); /* version */

    avio_rb24(pb); /* flags */

    entries = avio_rb32(pb);

    av_log(c->fc, AV_LOG_TRACE, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);

    if (!entries)

        return 0;

    if (entries >= UINT_MAX / sizeof(*sc->ctts_data))

        return AVERROR_INVALIDDATA;

    av_freep(&sc->ctts_data);

    sc->ctts_data = av_realloc(NULL, entries * sizeof(*sc->ctts_data));

    if (!sc->ctts_data)

        return AVERROR(ENOMEM);

    for (i = 0; i < entries && !pb->eof_reached; i++) {

        int count    =avio_rb32(pb);

        int duration =avio_rb32(pb);

        sc->ctts_data[i].count   = count;

        sc->ctts_data[i].duration= duration;

        av_log(c->fc, AV_LOG_TRACE, "count=%d, duration=%d\n",

                count, duration);

        if (FFABS(duration) > (1<<28) && i+2<entries) {

            av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");

            av_freep(&sc->ctts_data);

            sc->ctts_count = 0;

            return 0;

        }

        if (i+2<entries)

            mov_update_dts_shift(sc, duration);

    }

    sc->ctts_count = i;

    if (pb->eof_reached)

        return AVERROR_EOF;

    av_log(c->fc, AV_LOG_TRACE, "dts shift %d\n", sc->dts_shift);

    return 0;

}


static ssize_t nc_sendv_compat(NetClientState *nc, const struct iovec *iov,

                               int iovcnt, unsigned flags)

{

    uint8_t *buf = NULL;

    uint8_t *buffer;

    size_t offset;

    ssize_t ret;

    if (iovcnt == 1) {

        buffer = iov[0].iov_base;

        offset = iov[0].iov_len;

    } else {

        buf = g_new(uint8_t, NET_BUFSIZE);

        buffer = buf;

        offset = iov_to_buf(iov, iovcnt, 0, buf, NET_BUFSIZE);

    }

    if (flags & QEMU_NET_PACKET_FLAG_RAW && nc->info->receive_raw) {

        ret = nc->info->receive_raw(nc, buffer, offset);

    } else {

        ret = nc->info->receive(nc, buffer, offset);

    }

    g_free(buf);

    return ret;

}


qemu_irq *arm_gic_init(uint32_t base, qemu_irq parent_irq)

{

    gic_state *s;

    qemu_irq *qi;

    int iomemtype;

    s = (gic_state *)qemu_mallocz(sizeof(gic_state));

    if (!s)

        return NULL;

    qi = qemu_allocate_irqs(gic_set_irq, s, GIC_NIRQ);

    s->parent_irq = parent_irq;

    if (base != 0xffffffff) {

        iomemtype = cpu_register_io_memory(0, gic_cpu_readfn,

                                           gic_cpu_writefn, s);

        cpu_register_physical_memory(base, 0x00000fff, iomemtype);

        iomemtype = cpu_register_io_memory(0, gic_dist_readfn,

                                           gic_dist_writefn, s);

        cpu_register_physical_memory(base + 0x1000, 0x00000fff, iomemtype);

        s->base = base;

    } else {

        s->base = 0;

    }

    gic_reset(s);

    return qi;

}


static int qcow_create2(const char *filename, int64_t total_size,

                        const char *backing_file, const char *backing_format,

                        int flags, size_t cluster_size, int prealloc)

{

    int fd, header_size, backing_filename_len, l1_size, i, shift, l2_bits;

    int ref_clusters, backing_format_len = 0;

    int rounded_ext_bf_len = 0;

    QCowHeader header;

    uint64_t tmp, offset;

    QCowCreateState s1, *s = &s1;

    QCowExtension ext_bf = {0, 0};

    int ret;

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

    fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);

    if (fd < 0)

        return -1;

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

    header.magic = cpu_to_be32(QCOW_MAGIC);

    header.version = cpu_to_be32(QCOW_VERSION);

    header.size = cpu_to_be64(total_size * 512);

    header_size = sizeof(header);

    backing_filename_len = 0;

    if (backing_file) {

        if (backing_format) {

            ext_bf.magic = QCOW_EXT_MAGIC_BACKING_FORMAT;

            backing_format_len = strlen(backing_format);

            ext_bf.len = backing_format_len;

            rounded_ext_bf_len = (sizeof(ext_bf) + ext_bf.len + 7) & ~7;

            header_size += rounded_ext_bf_len;

        }

        header.backing_file_offset = cpu_to_be64(header_size);

        backing_filename_len = strlen(backing_file);

        header.backing_file_size = cpu_to_be32(backing_filename_len);

        header_size += backing_filename_len;

    }

    /* Cluster size */

    s->cluster_bits = get_bits_from_size(cluster_size);

    if (s->cluster_bits < MIN_CLUSTER_BITS ||

        s->cluster_bits > MAX_CLUSTER_BITS)

    {

        fprintf(stderr, "Cluster size must be a power of two between "

            "%d and %dk\n",

            1 << MIN_CLUSTER_BITS,

            1 << (MAX_CLUSTER_BITS - 10));

        return -EINVAL;

    }

    s->cluster_size = 1 << s->cluster_bits;

    header.cluster_bits = cpu_to_be32(s->cluster_bits);

    header_size = (header_size + 7) & ~7;

    if (flags & BLOCK_FLAG_ENCRYPT) {

        header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES);

    } else {

        header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);

    }

    l2_bits = s->cluster_bits - 3;

    shift = s->cluster_bits + l2_bits;

    l1_size = (((total_size * 512) + (1LL << shift) - 1) >> shift);

    offset = align_offset(header_size, s->cluster_size);

    s->l1_table_offset = offset;

    header.l1_table_offset = cpu_to_be64(s->l1_table_offset);

    header.l1_size = cpu_to_be32(l1_size);

    offset += align_offset(l1_size * sizeof(uint64_t), s->cluster_size);

    s->refcount_table = qemu_mallocz(s->cluster_size);

    s->refcount_table_offset = offset;

    header.refcount_table_offset = cpu_to_be64(offset);

    header.refcount_table_clusters = cpu_to_be32(1);

    offset += s->cluster_size;

    s->refcount_block_offset = offset;

    /* count how many refcount blocks needed */

    tmp = offset >> s->cluster_bits;

    ref_clusters = (tmp >> (s->cluster_bits - REFCOUNT_SHIFT)) + 1;

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

        s->refcount_table[i] = cpu_to_be64(offset);

        offset += s->cluster_size;

    }

    s->refcount_block = qemu_mallocz(ref_clusters * s->cluster_size);

    /* update refcounts */

    qcow2_create_refcount_update(s, 0, header_size);

    qcow2_create_refcount_update(s, s->l1_table_offset,

        l1_size * sizeof(uint64_t));

    qcow2_create_refcount_update(s, s->refcount_table_offset, s->cluster_size);

    qcow2_create_refcount_update(s, s->refcount_block_offset,

        ref_clusters * s->cluster_size);

    /* write all the data */

    ret = qemu_write_full(fd, &header, sizeof(header));

    if (ret != sizeof(header)) {

        ret = -1;

        goto exit;

    }

    if (backing_file) {

        if (backing_format_len) {

            char zero[16];

            int padding = rounded_ext_bf_len - (ext_bf.len + sizeof(ext_bf));

            memset(zero, 0, sizeof(zero));

            cpu_to_be32s(&ext_bf.magic);

            cpu_to_be32s(&ext_bf.len);

            ret = qemu_write_full(fd, &ext_bf, sizeof(ext_bf));

            if (ret != sizeof(ext_bf)) {

                ret = -1;

                goto exit;

            }

            ret = qemu_write_full(fd, backing_format, backing_format_len);

            if (ret != backing_format_len) {

                ret = -1;

                goto exit;

            }

            if (padding > 0) {

                ret = qemu_write_full(fd, zero, padding);

                if (ret != padding) {

                    ret = -1;

                    goto exit;

                }

            }

        }

        ret = qemu_write_full(fd, backing_file, backing_filename_len);

        if (ret != backing_filename_len) {

            ret = -1;

            goto exit;

        }

    }

    lseek(fd, s->l1_table_offset, SEEK_SET);

    tmp = 0;

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

        ret = qemu_write_full(fd, &tmp, sizeof(tmp));

        if (ret != sizeof(tmp)) {

            ret = -1;

            goto exit;

        }

    }

    lseek(fd, s->refcount_table_offset, SEEK_SET);

    ret = qemu_write_full(fd, s->refcount_table, s->cluster_size);

    if (ret != s->cluster_size) {

        ret = -1;

        goto exit;

    }

    lseek(fd, s->refcount_block_offset, SEEK_SET);

    ret = qemu_write_full(fd, s->refcount_block,

		    ref_clusters * s->cluster_size);

    if (ret != s->cluster_size) {

        ret = -1;

        goto exit;

    }

    ret = 0;

exit:

    qemu_free(s->refcount_table);

    qemu_free(s->refcount_block);

    close(fd);

    /* Preallocate metadata */

    if (prealloc) {

        BlockDriverState *bs;

        bs = bdrv_new("");

        bdrv_open(bs, filename, BDRV_O_CACHE_WB | BDRV_O_RDWR);

        preallocate(bs);

        bdrv_close(bs);

    }

    return ret;

}


static void chroma_4mv_motion(MpegEncContext *s,

                              uint8_t *dest_cb, uint8_t *dest_cr,

                              uint8_t **ref_picture,

                              op_pixels_func *pix_op,

                              int mx, int my)

{

    int dxy, emu=0, src_x, src_y, offset;

    uint8_t *ptr;

    /* In case of 8X8, we construct a single chroma motion vector

       with a special rounding */

    mx= ff_h263_round_chroma(mx);

    my= ff_h263_round_chroma(my);

    dxy = ((my & 1) << 1) | (mx & 1);

    mx >>= 1;

    my >>= 1;

    src_x = s->mb_x * 8 + mx;

    src_y = s->mb_y * 8 + my;

    src_x = av_clip(src_x, -8, (s->width >> 1));

    if (src_x == (s->width >> 1))

        dxy &= ~1;

    src_y = av_clip(src_y, -8, (s->height >> 1));

    if (src_y == (s->height >> 1))

        dxy &= ~2;

    offset = src_y * s->uvlinesize + src_x;

    ptr = ref_picture[1] + offset;

    if(s->flags&CODEC_FLAG_EMU_EDGE){

        if(   (unsigned)src_x > FFMAX((s->h_edge_pos>>1) - (dxy &1) - 8, 0)

           || (unsigned)src_y > FFMAX((s->v_edge_pos>>1) - (dxy>>1) - 8, 0)){

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

                                9, 9, src_x, src_y,

                                s->h_edge_pos>>1, s->v_edge_pos>>1);

            ptr= s->edge_emu_buffer;

            emu=1;

        }

    }

    pix_op[dxy](dest_cb, ptr, s->uvlinesize, 8);

    ptr = ref_picture[2] + offset;

    if(emu){

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

                            9, 9, src_x, src_y,

                            s->h_edge_pos>>1, s->v_edge_pos>>1);

        ptr= s->edge_emu_buffer;

    }

    pix_op[dxy](dest_cr, ptr, s->uvlinesize, 8);

}


static void super2xsai(AVFilterContext *ctx,

                       uint8_t *src, int src_linesize,

                       uint8_t *dst, int dst_linesize,

                       int width, int height)

{

    Super2xSaIContext *sai = ctx->priv;

    unsigned int x, y;

    uint32_t color[4][4];

    unsigned char *src_line[4];

    const int bpp = sai->bpp;

    const uint32_t hi_pixel_mask = sai->hi_pixel_mask;

    const uint32_t lo_pixel_mask = sai->lo_pixel_mask;

    const uint32_t q_hi_pixel_mask = sai->q_hi_pixel_mask;

    const uint32_t q_lo_pixel_mask = sai->q_lo_pixel_mask;

    /* Point to the first 4 lines, first line is duplicated */

    src_line[0] = src;

    src_line[1] = src;

    src_line[2] = src + src_linesize*FFMIN(1, height-1);

    src_line[3] = src + src_linesize*FFMIN(2, height-1);

#define READ_COLOR4(dst, src_line, off) dst = *((const uint32_t *)src_line + off)

#define READ_COLOR3(dst, src_line, off) dst = AV_RL24 (src_line + 3*off)

#define READ_COLOR2(dst, src_line, off) dst = *((const uint16_t *)src_line + off)

    /* Initialise the color matrix for this row. */

    switch (bpp) {

    case 4:

        READ_COLOR4(color[0][0], src_line[0], 0); color[0][1] = color[0][0]; READ_COLOR4(color[0][2], src_line[0], 1); READ_COLOR4(color[0][3], src_line[0], 2);

        READ_COLOR4(color[1][0], src_line[1], 0); color[1][1] = color[1][0]; READ_COLOR4(color[1][2], src_line[1], 1); READ_COLOR4(color[1][3], src_line[1], 2);

        READ_COLOR4(color[2][0], src_line[2], 0); color[2][1] = color[2][0]; READ_COLOR4(color[2][2], src_line[2], 1); READ_COLOR4(color[2][3], src_line[2], 2);

        READ_COLOR4(color[3][0], src_line[3], 0); color[3][1] = color[3][0]; READ_COLOR4(color[3][2], src_line[3], 1); READ_COLOR4(color[3][3], src_line[3], 2);

        break;

    case 3:

        READ_COLOR3(color[0][0], src_line[0], 0); color[0][1] = color[0][0]; READ_COLOR3(color[0][2], src_line[0], 1); READ_COLOR3(color[0][3], src_line[0], 2);

        READ_COLOR3(color[1][0], src_line[1], 0); color[1][1] = color[1][0]; READ_COLOR3(color[1][2], src_line[1], 1); READ_COLOR3(color[1][3], src_line[1], 2);

        READ_COLOR3(color[2][0], src_line[2], 0); color[2][1] = color[2][0]; READ_COLOR3(color[2][2], src_line[2], 1); READ_COLOR3(color[2][3], src_line[2], 2);

        READ_COLOR3(color[3][0], src_line[3], 0); color[3][1] = color[3][0]; READ_COLOR3(color[3][2], src_line[3], 1); READ_COLOR3(color[3][3], src_line[3], 2);

        break;

    default:

        READ_COLOR2(color[0][0], src_line[0], 0); color[0][1] = color[0][0]; READ_COLOR2(color[0][2], src_line[0], 1); READ_COLOR2(color[0][3], src_line[0], 2);

        READ_COLOR2(color[1][0], src_line[1], 0); color[1][1] = color[1][0]; READ_COLOR2(color[1][2], src_line[1], 1); READ_COLOR2(color[1][3], src_line[1], 2);

        READ_COLOR2(color[2][0], src_line[2], 0); color[2][1] = color[2][0]; READ_COLOR2(color[2][2], src_line[2], 1); READ_COLOR2(color[2][3], src_line[2], 2);

        READ_COLOR2(color[3][0], src_line[3], 0); color[3][1] = color[3][0]; READ_COLOR2(color[3][2], src_line[3], 1); READ_COLOR2(color[3][3], src_line[3], 2);

    }

    for (y = 0; y < height; y++) {

        uint8_t *dst_line[2];

        dst_line[0] = dst + dst_linesize*2*y;

        dst_line[1] = dst + dst_linesize*(2*y+1);

        for (x = 0; x < width; x++) {

            uint32_t product1a, product1b, product2a, product2b;

//---------------------------------------  B0 B1 B2 B3    0  1  2  3

//                                         4  5* 6  S2 -> 4  5* 6  7

//                                         1  2  3  S1    8  9 10 11

//                                         A0 A1 A2 A3   12 13 14 15

//--------------------------------------

            if (color[2][1] == color[1][2] && color[1][1] != color[2][2]) {

                product2b = color[2][1];

                product1b = product2b;

            } else if (color[1][1] == color[2][2] && color[2][1] != color[1][2]) {

                product2b = color[1][1];

                product1b = product2b;

            } else if (color[1][1] == color[2][2] && color[2][1] == color[1][2]) {

                int r = 0;

                r += GET_RESULT(color[1][2], color[1][1], color[1][0], color[3][1]);

                r += GET_RESULT(color[1][2], color[1][1], color[2][0], color[0][1]);

                r += GET_RESULT(color[1][2], color[1][1], color[3][2], color[2][3]);

                r += GET_RESULT(color[1][2], color[1][1], color[0][2], color[1][3]);

                if (r > 0)

                    product1b = color[1][2];

                else if (r < 0)

                    product1b = color[1][1];

                else

                    product1b = INTERPOLATE(color[1][1], color[1][2]);

                product2b = product1b;

            } else {

                if (color[1][2] == color[2][2] && color[2][2] == color[3][1] && color[2][1] != color[3][2] && color[2][2] != color[3][0])

                    product2b = Q_INTERPOLATE(color[2][2], color[2][2], color[2][2], color[2][1]);

                else if (color[1][1] == color[2][1] && color[2][1] == color[3][2] && color[3][1] != color[2][2] && color[2][1] != color[3][3])

                    product2b = Q_INTERPOLATE(color[2][1], color[2][1], color[2][1], color[2][2]);

                else

                    product2b = INTERPOLATE(color[2][1], color[2][2]);

                if (color[1][2] == color[2][2] && color[1][2] == color[0][1] && color[1][1] != color[0][2] && color[1][2] != color[0][0])

                    product1b = Q_INTERPOLATE(color[1][2], color[1][2], color[1][2], color[1][1]);

                else if (color[1][1] == color[2][1] && color[1][1] == color[0][2] && color[0][1] != color[1][2] && color[1][1] != color[0][3])

                    product1b = Q_INTERPOLATE(color[1][2], color[1][1], color[1][1], color[1][1]);

                else

                    product1b = INTERPOLATE(color[1][1], color[1][2]);

            }

            if (color[1][1] == color[2][2] && color[2][1] != color[1][2] && color[1][0] == color[1][1] && color[1][1] != color[3][2])

                product2a = INTERPOLATE(color[2][1], color[1][1]);

            else if (color[1][1] == color[2][0] && color[1][2] == color[1][1] && color[1][0] != color[2][1] && color[1][1] != color[3][0])

                product2a = INTERPOLATE(color[2][1], color[1][1]);

            else

                product2a = color[2][1];

            if (color[2][1] == color[1][2] && color[1][1] != color[2][2] && color[2][0] == color[2][1] && color[2][1] != color[0][2])

                product1a = INTERPOLATE(color[2][1], color[1][1]);

            else if (color[1][0] == color[2][1] && color[2][2] == color[2][1] && color[2][0] != color[1][1] && color[2][1] != color[0][0])

                product1a = INTERPOLATE(color[2][1], color[1][1]);

            else

                product1a = color[1][1];

            /* Set the calculated pixels */

            switch (bpp) {

            case 4:

                AV_WN32A(dst_line[0] + x * 8,     product1a);

                AV_WN32A(dst_line[0] + x * 8 + 4, product1b);

                AV_WN32A(dst_line[1] + x * 8,     product2a);

                AV_WN32A(dst_line[1] + x * 8 + 4, product2b);

                break;

            case 3:

                AV_WL24(dst_line[0] + x * 6,     product1a);

                AV_WL24(dst_line[0] + x * 6 + 3, product1b);

                AV_WL24(dst_line[1] + x * 6,     product2a);

                AV_WL24(dst_line[1] + x * 6 + 3, product2b);

                break;

            default: // bpp = 2

                AV_WN32A(dst_line[0] + x * 4, product1a | (product1b << 16));

                AV_WN32A(dst_line[1] + x * 4, product2a | (product2b << 16));

            }

            /* Move color matrix forward */

            color[0][0] = color[0][1]; color[0][1] = color[0][2]; color[0][2] = color[0][3];

            color[1][0] = color[1][1]; color[1][1] = color[1][2]; color[1][2] = color[1][3];

            color[2][0] = color[2][1]; color[2][1] = color[2][2]; color[2][2] = color[2][3];

            color[3][0] = color[3][1]; color[3][1] = color[3][2]; color[3][2] = color[3][3];

            if (x < width - 3) {

                x += 3;

                switch (bpp) {

                case 4:

                    READ_COLOR4(color[0][3], src_line[0], x);

                    READ_COLOR4(color[1][3], src_line[1], x);

                    READ_COLOR4(color[2][3], src_line[2], x);

                    READ_COLOR4(color[3][3], src_line[3], x);

                    break;

                case 3:

                    READ_COLOR3(color[0][3], src_line[0], x);

                    READ_COLOR3(color[1][3], src_line[1], x);

                    READ_COLOR3(color[2][3], src_line[2], x);

                    READ_COLOR3(color[3][3], src_line[3], x);

                    break;

                default:        /* case 2 */

                    READ_COLOR2(color[0][3], src_line[0], x);

                    READ_COLOR2(color[1][3], src_line[1], x);

                    READ_COLOR2(color[2][3], src_line[2], x);

                    READ_COLOR2(color[3][3], src_line[3], x);

                }

                x -= 3;

            }

        }

        /* We're done with one line, so we shift the source lines up */

        src_line[0] = src_line[1];

        src_line[1] = src_line[2];

        src_line[2] = src_line[3];

        /* Read next line */

        src_line[3] = src_line[2];

        if (y < height - 3)

            src_line[3] += src_linesize;

        switch (bpp) {

        case 4:

            READ_COLOR4(color[0][0], src_line[0], 0); color[0][1] = color[0][0]; READ_COLOR4(color[0][2], src_line[0], 1); READ_COLOR4(color[0][3], src_line[0], 2);

            READ_COLOR4(color[1][0], src_line[1], 0); color[1][1] = color[1][0]; READ_COLOR4(color[1][2], src_line[1], 1); READ_COLOR4(color[1][3], src_line[1], 2);

            READ_COLOR4(color[2][0], src_line[2], 0); color[2][1] = color[2][0]; READ_COLOR4(color[2][2], src_line[2], 1); READ_COLOR4(color[2][3], src_line[2], 2);

            READ_COLOR4(color[3][0], src_line[3], 0); color[3][1] = color[3][0]; READ_COLOR4(color[3][2], src_line[3], 1); READ_COLOR4(color[3][3], src_line[3], 2);

            break;

        case 3:

            READ_COLOR3(color[0][0], src_line[0], 0); color[0][1] = color[0][0]; READ_COLOR3(color[0][2], src_line[0], 1); READ_COLOR3(color[0][3], src_line[0], 2);

            READ_COLOR3(color[1][0], src_line[1], 0); color[1][1] = color[1][0]; READ_COLOR3(color[1][2], src_line[1], 1); READ_COLOR3(color[1][3], src_line[1], 2);

            READ_COLOR3(color[2][0], src_line[2], 0); color[2][1] = color[2][0]; READ_COLOR3(color[2][2], src_line[2], 1); READ_COLOR3(color[2][3], src_line[2], 2);

            READ_COLOR3(color[3][0], src_line[3], 0); color[3][1] = color[3][0]; READ_COLOR3(color[3][2], src_line[3], 1); READ_COLOR3(color[3][3], src_line[3], 2);

            break;

        default:

            READ_COLOR2(color[0][0], src_line[0], 0); color[0][1] = color[0][0]; READ_COLOR2(color[0][2], src_line[0], 1); READ_COLOR2(color[0][3], src_line[0], 2);

            READ_COLOR2(color[1][0], src_line[1], 0); color[1][1] = color[1][0]; READ_COLOR2(color[1][2], src_line[1], 1); READ_COLOR2(color[1][3], src_line[1], 2);

            READ_COLOR2(color[2][0], src_line[2], 0); color[2][1] = color[2][0]; READ_COLOR2(color[2][2], src_line[2], 1); READ_COLOR2(color[2][3], src_line[2], 2);

            READ_COLOR2(color[3][0], src_line[3], 0); color[3][1] = color[3][0]; READ_COLOR2(color[3][2], src_line[3], 1); READ_COLOR2(color[3][3], src_line[3], 2);

        }

    } // y loop

}


static inline int pic_is_unused(MpegEncContext *s, Picture *pic)

{

    if (pic->f->buf[0] == NULL)

        return 1;

    if (pic->needs_realloc && !(pic->reference & DELAYED_PIC_REF))

        return 1;

    return 0;

}


static inline int wv_unpack_mono(WavpackFrameContext *s, GetBitContext *gb,
                                 void *dst, const int type)
{
    int i, j, count = 0;
    int last, t;
    int A, S, T;
    int pos                  = s->pos;
    uint32_t crc             = s->sc.crc;
    uint32_t crc_extra_bits  = s->extra_sc.crc;
    int16_t *dst16           = dst;
    int32_t *dst32           = dst;
    float *dstfl             = dst;
    s->one = s->zero = s->zeroes = 0;
    do {
        T = wv_get_value(s, gb, 0, &last);
        S = 0;
        if (last)
            break;
        for (i = 0; i < s->terms; i++) {
            t = s->decorr[i].value;
            if (t > 8) {
                if (t & 1)
                    A =  2 * s->decorr[i].samplesA[0] - s->decorr[i].samplesA[1];
                else
                    A = (3 * s->decorr[i].samplesA[0] - s->decorr[i].samplesA[1]) >> 1;
                s->decorr[i].samplesA[1] = s->decorr[i].samplesA[0];
                j                        = 0;
            } else {
                A = s->decorr[i].samplesA[pos];
                j = (pos + t) & 7;
            if (type != AV_SAMPLE_FMT_S16P)
                S = T + ((s->decorr[i].weightA * (int64_t)A + 512) >> 10);
            else
                S = T + ((s->decorr[i].weightA * A + 512) >> 10);
            if (A && T)
                s->decorr[i].weightA -= ((((T ^ A) >> 30) & 2) - 1) * s->decorr[i].delta;
            s->decorr[i].samplesA[j] = T = S;
        pos = (pos + 1) & 7;
        crc = crc * 3 + S;
        if (type == AV_SAMPLE_FMT_FLTP) {
            *dstfl++ = wv_get_value_float(s, &crc_extra_bits, S);
        } else if (type == AV_SAMPLE_FMT_S32P) {
            *dst32++ = wv_get_value_integer(s, &crc_extra_bits, S);
        } else {
            *dst16++ = wv_get_value_integer(s, &crc_extra_bits, S);
        count++;
    } while (!last && count < s->samples);
    wv_reset_saved_context(s);
    if (s->avctx->err_recognition & AV_EF_CRCCHECK) {
        int ret = wv_check_crc(s, crc, crc_extra_bits);
        if (ret < 0 && s->avctx->err_recognition & AV_EF_EXPLODE)
            return ret;
    return 0;


void ff_cavs_mv(AVSContext *h, enum cavs_mv_loc nP, enum cavs_mv_loc nC,

                enum cavs_mv_pred mode, enum cavs_block size, int ref)

{

    cavs_vector *mvP = &h->mv[nP];

    cavs_vector *mvA = &h->mv[nP-1];

    cavs_vector *mvB = &h->mv[nP-4];

    cavs_vector *mvC = &h->mv[nC];

    const cavs_vector *mvP2 = NULL;

    mvP->ref  = ref;

    mvP->dist = h->dist[mvP->ref];

    if (mvC->ref == NOT_AVAIL || (nP == MV_FWD_X3) || (nP == MV_BWD_X3 ))

        mvC = &h->mv[nP - 5];  // set to top-left (mvD)

    if (mode == MV_PRED_PSKIP &&

        (mvA->ref == NOT_AVAIL ||

         mvB->ref == NOT_AVAIL ||

         (mvA->x | mvA->y | mvA->ref) == 0 ||

         (mvB->x | mvB->y | mvB->ref) == 0)) {

        mvP2 = &un_mv;

    /* if there is only one suitable candidate, take it */

    } else if (mvA->ref >= 0 && mvB->ref < 0  && mvC->ref < 0) {

        mvP2 = mvA;

    } else if (mvA->ref < 0  && mvB->ref >= 0 && mvC->ref < 0) {

        mvP2 = mvB;

    } else if (mvA->ref < 0  && mvB->ref < 0  && mvC->ref >= 0) {

        mvP2 = mvC;

    } else if (mode == MV_PRED_LEFT     && mvA->ref == ref) {

        mvP2 = mvA;

    } else if (mode == MV_PRED_TOP      && mvB->ref == ref) {

        mvP2 = mvB;

    } else if (mode == MV_PRED_TOPRIGHT && mvC->ref == ref) {

        mvP2 = mvC;

    }

    if (mvP2) {

        mvP->x = mvP2->x;

        mvP->y = mvP2->y;

    } else

        mv_pred_median(h, mvP, mvA, mvB, mvC);

    if (mode < MV_PRED_PSKIP) {

        mvP->x += get_se_golomb(&h->gb);

        mvP->y += get_se_golomb(&h->gb);

    }

    set_mvs(mvP, size);

}


static int usbredir_handle_iso_data(USBRedirDevice *dev, USBPacket *p,

                                     uint8_t ep)

{

    int status, len;

    if (!dev->endpoint[EP2I(ep)].iso_started &&

            !dev->endpoint[EP2I(ep)].iso_error) {

        struct usb_redir_start_iso_stream_header start_iso = {

            .endpoint = ep,

            /* TODO maybe do something with these depending on ep interval? */

            .pkts_per_urb = 32,

            .no_urbs = 3,

        };

        /* No id, we look at the ep when receiving a status back */

        usbredirparser_send_start_iso_stream(dev->parser, 0, &start_iso);

        usbredirparser_do_write(dev->parser);

        DPRINTF("iso stream started ep %02X\n", ep);

        dev->endpoint[EP2I(ep)].iso_started = 1;

    }

    if (ep & USB_DIR_IN) {

        struct buf_packet *isop;

        isop = QTAILQ_FIRST(&dev->endpoint[EP2I(ep)].bufpq);

        if (isop == NULL) {

            DPRINTF2("iso-token-in ep %02X, no isop\n", ep);

            /* Check iso_error for stream errors, otherwise its an underrun */

            status = dev->endpoint[EP2I(ep)].iso_error;

            dev->endpoint[EP2I(ep)].iso_error = 0;

            return usbredir_handle_status(dev, status, 0);

        }

        DPRINTF2("iso-token-in ep %02X status %d len %d\n", ep, isop->status,

                 isop->len);

        status = isop->status;

        if (status != usb_redir_success) {

            bufp_free(dev, isop, ep);

            return usbredir_handle_status(dev, status, 0);

        }

        len = isop->len;

        if (len > p->len) {

            ERROR("received iso data is larger then packet ep %02X\n", ep);

            bufp_free(dev, isop, ep);

            return USB_RET_NAK;

        }

        memcpy(p->data, isop->data, len);

        bufp_free(dev, isop, ep);

        return len;

    } else {

        /* If the stream was not started because of a pending error don't

           send the packet to the usb-host */

        if (dev->endpoint[EP2I(ep)].iso_started) {

            struct usb_redir_iso_packet_header iso_packet = {

                .endpoint = ep,

                .length = p->len

            };

            /* No id, we look at the ep when receiving a status back */

            usbredirparser_send_iso_packet(dev->parser, 0, &iso_packet,

                                           p->data, p->len);

            usbredirparser_do_write(dev->parser);

        }

        status = dev->endpoint[EP2I(ep)].iso_error;

        dev->endpoint[EP2I(ep)].iso_error = 0;

        DPRINTF2("iso-token-out ep %02X status %d len %d\n", ep, status,

                 p->len);

        return usbredir_handle_status(dev, status, p->len);

    }

}


static inline void vmsvga_check_size(struct vmsvga_state_s *s)

{

    DisplaySurface *surface = qemu_console_surface(s->vga.con);

    if (s->new_width != surface_width(surface) ||

        s->new_height != surface_height(surface)) {

        qemu_console_resize(s->vga.con, s->new_width, s->new_height);

        s->invalidated = 1;

    }

}


void vga_init(VGACommonState *s, Object *obj, MemoryRegion *address_space,

              MemoryRegion *address_space_io, bool init_vga_ports)

{

    MemoryRegion *vga_io_memory;

    const MemoryRegionPortio *vga_ports, *vbe_ports;

    PortioList *vga_port_list = g_new(PortioList, 1);

    PortioList *vbe_port_list = g_new(PortioList, 1);

    qemu_register_reset(vga_reset, s);

    s->bank_offset = 0;

    s->legacy_address_space = address_space;

    vga_io_memory = vga_init_io(s, obj, &vga_ports, &vbe_ports);

    memory_region_add_subregion_overlap(address_space,

                                        isa_mem_base + 0x000a0000,

                                        vga_io_memory,

                                        1);

    memory_region_set_coalescing(vga_io_memory);

    if (init_vga_ports) {

        portio_list_init(vga_port_list, obj, vga_ports, s, "vga");

        portio_list_set_flush_coalesced(vga_port_list);

        portio_list_add(vga_port_list, address_space_io, 0x3b0);

    }

    if (vbe_ports) {

        portio_list_init(vbe_port_list, obj, vbe_ports, s, "vbe");

        portio_list_add(vbe_port_list, address_space_io, 0x1ce);

    }

}


static void msix_mmio_write(void *opaque, target_phys_addr_t addr,

                            uint64_t val, unsigned size)

{

    PCIDevice *dev = opaque;

    unsigned int offset = addr & (MSIX_PAGE_SIZE - 1) & ~0x3;

    int vector = offset / PCI_MSIX_ENTRY_SIZE;

    /* MSI-X page includes a read-only PBA and a writeable Vector Control. */

    if (vector >= dev->msix_entries_nr) {

        return;

    }

    pci_set_long(dev->msix_table_page + offset, val);

    msix_handle_mask_update(dev, vector);

}


static void qemu_laio_completion_cb(EventNotifier *e)

{

    struct qemu_laio_state *s = container_of(e, struct qemu_laio_state, e);

    while (event_notifier_test_and_clear(&s->e)) {

        struct io_event events[MAX_EVENTS];

        struct timespec ts = { 0 };

        int nevents, i;

        do {

            nevents = io_getevents(s->ctx, MAX_EVENTS, MAX_EVENTS, events, &ts);

        } while (nevents == -EINTR);

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

            struct iocb *iocb = events[i].obj;

            struct qemu_laiocb *laiocb =

                    container_of(iocb, struct qemu_laiocb, iocb);

            laiocb->ret = io_event_ret(&events[i]);

            qemu_laio_process_completion(s, laiocb);

        }

    }

}


static void spapr_rng_class_init(ObjectClass *oc, void *data)

{

    DeviceClass *dc = DEVICE_CLASS(oc);

    dc->realize = spapr_rng_realize;

    set_bit(DEVICE_CATEGORY_MISC, dc->categories);

    dc->props = spapr_rng_properties;

}


static void process_incoming_migration_co(void *opaque)

{

    QEMUFile *f = opaque;

    MigrationIncomingState *mis = migration_incoming_get_current();

    PostcopyState ps;

    int ret;

    mis->from_src_file = f;

    mis->largest_page_size = qemu_ram_pagesize_largest();

    postcopy_state_set(POSTCOPY_INCOMING_NONE);

    migrate_set_state(&mis->state, MIGRATION_STATUS_NONE,

                      MIGRATION_STATUS_ACTIVE);

    ret = qemu_loadvm_state(f);

    ps = postcopy_state_get();

    trace_process_incoming_migration_co_end(ret, ps);

    if (ps != POSTCOPY_INCOMING_NONE) {

        if (ps == POSTCOPY_INCOMING_ADVISE) {

            /*

             * Where a migration had postcopy enabled (and thus went to advise)

             * but managed to complete within the precopy period, we can use

             * the normal exit.

             */

            postcopy_ram_incoming_cleanup(mis);

        } else if (ret >= 0) {

            /*

             * Postcopy was started, cleanup should happen at the end of the

             * postcopy thread.

             */

            trace_process_incoming_migration_co_postcopy_end_main();

            return;

        }

        /* Else if something went wrong then just fall out of the normal exit */

    }

    /* we get COLO info, and know if we are in COLO mode */

    if (!ret && migration_incoming_enable_colo()) {

        mis->migration_incoming_co = qemu_coroutine_self();

        qemu_thread_create(&mis->colo_incoming_thread, "COLO incoming",

             colo_process_incoming_thread, mis, QEMU_THREAD_JOINABLE);

        mis->have_colo_incoming_thread = true;

        qemu_coroutine_yield();

        /* Wait checkpoint incoming thread exit before free resource */

        qemu_thread_join(&mis->colo_incoming_thread);

    }

    qemu_fclose(f);

    free_xbzrle_decoded_buf();

    if (ret < 0) {

        migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,

                          MIGRATION_STATUS_FAILED);

        error_report("load of migration failed: %s", strerror(-ret));

        migrate_decompress_threads_join();

        exit(EXIT_FAILURE);

    }

    mis->bh = qemu_bh_new(process_incoming_migration_bh, mis);

    qemu_bh_schedule(mis->bh);

}


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

{

    uint32_t type, size;

    int64_t pos;

    int ret;

    if (avio_feof(s->pb))

        return AVERROR_EOF;

    pos  = avio_tell(s->pb);

    type = avio_rl32(s->pb);

    size = avio_rb32(s->pb);

    if (size > INT_MAX / s->streams[0]->codecpar->channels)

        return AVERROR_INVALIDDATA;

    size *= s->streams[0]->codecpar->channels;

    if ((ret = avio_skip(s->pb, 24)) < 0) // padding

        return ret;

    if (type == MKTAG('B','L','C','K')) {

        ret = av_get_packet(s->pb, pkt, size);

        pkt->stream_index = 0;

        pkt->pos = pos;

    } else {

        av_log(s, AV_LOG_ERROR, "unknown chunk %x\n", type);

        avio_skip(s->pb, size);

        ret = AVERROR_INVALIDDATA;

    }

    return ret;

}


static void do_apply_filter(APEContext *ctx, int version, APEFilter *f,

                            int32_t *data, int count, int order, int fracbits)

{

    int res;

    int absres;

    while (count--) {

        /* round fixedpoint scalar product */

        res = ctx->adsp.scalarproduct_and_madd_int16(f->coeffs,

                                                     f->delay - order,

                                                     f->adaptcoeffs - order,

                                                     order, APESIGN(*data));

        res = (res + (1 << (fracbits - 1))) >> fracbits;

        res += *data;

        *data++ = res;

        /* Update the output history */

        *f->delay++ = av_clip_int16(res);

        if (version < 3980) {

            /* Version ??? to < 3.98 files (untested) */

            f->adaptcoeffs[0]  = (res == 0) ? 0 : ((res >> 28) & 8) - 4;

            f->adaptcoeffs[-4] >>= 1;

            f->adaptcoeffs[-8] >>= 1;

        } else {

            /* Version 3.98 and later files */

            /* Update the adaption coefficients */

            absres = FFABS(res);

            if (absres)

                *f->adaptcoeffs = ((res & (-1<<31)) ^ (-1<<30)) >>

                                  (25 + (absres <= f->avg*3) + (absres <= f->avg*4/3));

            else

                *f->adaptcoeffs = 0;

            f->avg += (absres - f->avg) / 16;

            f->adaptcoeffs[-1] >>= 1;

            f->adaptcoeffs[-2] >>= 1;

            f->adaptcoeffs[-8] >>= 1;

        }

        f->adaptcoeffs++;

        /* Have we filled the history buffer? */

        if (f->delay == f->historybuffer + HISTORY_SIZE + (order * 2)) {

            memmove(f->historybuffer, f->delay - (order * 2),

                    (order * 2) * sizeof(*f->historybuffer));

            f->delay = f->historybuffer + order * 2;

            f->adaptcoeffs = f->historybuffer + order;

        }

    }

}


static int fill_filter_caches(H264Context *h, H264SliceContext *sl, int mb_type)

{

    const int mb_xy = h->mb_xy;

    int top_xy, left_xy[LEFT_MBS];

    int top_type, left_type[LEFT_MBS];

    uint8_t *nnz;

    uint8_t *nnz_cache;

    top_xy = mb_xy - (h->mb_stride << MB_FIELD(h));

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

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

    left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;

    if (FRAME_MBAFF(h)) {

        const int left_mb_field_flag = IS_INTERLACED(h->cur_pic.mb_type[mb_xy - 1]);

        const int curr_mb_field_flag = IS_INTERLACED(mb_type);

        if (h->mb_y & 1) {

            if (left_mb_field_flag != curr_mb_field_flag)

                left_xy[LTOP] -= h->mb_stride;

        } else {

            if (curr_mb_field_flag)

                top_xy += h->mb_stride &

                          (((h->cur_pic.mb_type[top_xy] >> 7) & 1) - 1);

            if (left_mb_field_flag != curr_mb_field_flag)

                left_xy[LBOT] += h->mb_stride;

        }

    }

    sl->top_mb_xy        = top_xy;

    sl->left_mb_xy[LTOP] = left_xy[LTOP];

    sl->left_mb_xy[LBOT] = left_xy[LBOT];

    {

        /* For sufficiently low qp, filtering wouldn't do anything.

         * This is a conservative estimate: could also check beta_offset

         * and more accurate chroma_qp. */

        int qp_thresh = sl->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice

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

        if (qp <= qp_thresh &&

            (left_xy[LTOP] < 0 ||

             ((qp + h->cur_pic.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&

            (top_xy < 0 ||

             ((qp + h->cur_pic.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {

            if (!FRAME_MBAFF(h))

                return 1;

            if ((left_xy[LTOP] < 0 ||

                 ((qp + h->cur_pic.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&

                (top_xy < h->mb_stride ||

                 ((qp + h->cur_pic.qscale_table[top_xy - h->mb_stride] + 1) >> 1) <= qp_thresh))

                return 1;

        }

    }

    top_type        = h->cur_pic.mb_type[top_xy];

    left_type[LTOP] = h->cur_pic.mb_type[left_xy[LTOP]];

    left_type[LBOT] = h->cur_pic.mb_type[left_xy[LBOT]];

    if (h->deblocking_filter == 2) {

        if (h->slice_table[top_xy] != sl->slice_num)

            top_type = 0;

        if (h->slice_table[left_xy[LBOT]] != sl->slice_num)

            left_type[LTOP] = left_type[LBOT] = 0;

    } else {

        if (h->slice_table[top_xy] == 0xFFFF)

            top_type = 0;

        if (h->slice_table[left_xy[LBOT]] == 0xFFFF)

            left_type[LTOP] = left_type[LBOT] = 0;

    }

    sl->top_type        = top_type;

    sl->left_type[LTOP] = left_type[LTOP];

    sl->left_type[LBOT] = left_type[LBOT];

    if (IS_INTRA(mb_type))

        return 0;

    fill_filter_caches_inter(h, sl, mb_type, top_xy, left_xy,

                             top_type, left_type, mb_xy, 0);

    if (sl->list_count == 2)

        fill_filter_caches_inter(h, sl, mb_type, top_xy, left_xy,

                                 top_type, left_type, mb_xy, 1);

    nnz       = h->non_zero_count[mb_xy];

    nnz_cache = sl->non_zero_count_cache;

    AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);

    AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);

    AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);

    AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);

    sl->cbp = h->cbp_table[mb_xy];

    if (top_type) {

        nnz = h->non_zero_count[top_xy];

        AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);

    }

    if (left_type[LTOP]) {

        nnz = h->non_zero_count[left_xy[LTOP]];

        nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];

        nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];

        nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];

        nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];

    }

    /* CAVLC 8x8dct requires NNZ values for residual decoding that differ

     * from what the loop filter needs */

    if (!CABAC(h) && h->pps.transform_8x8_mode) {

        if (IS_8x8DCT(top_type)) {

            nnz_cache[4 + 8 * 0] =

            nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;

            nnz_cache[6 + 8 * 0] =

            nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;

        }

        if (IS_8x8DCT(left_type[LTOP])) {

            nnz_cache[3 + 8 * 1] =

            nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF

        }

        if (IS_8x8DCT(left_type[LBOT])) {

            nnz_cache[3 + 8 * 3] =

            nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF

        }

        if (IS_8x8DCT(mb_type)) {

            nnz_cache[scan8[0]] =

            nnz_cache[scan8[1]] =

            nnz_cache[scan8[2]] =

            nnz_cache[scan8[3]] = (sl->cbp & 0x1000) >> 12;

            nnz_cache[scan8[0 + 4]] =

            nnz_cache[scan8[1 + 4]] =

            nnz_cache[scan8[2 + 4]] =

            nnz_cache[scan8[3 + 4]] = (sl->cbp & 0x2000) >> 12;

            nnz_cache[scan8[0 + 8]] =

            nnz_cache[scan8[1 + 8]] =

            nnz_cache[scan8[2 + 8]] =

            nnz_cache[scan8[3 + 8]] = (sl->cbp & 0x4000) >> 12;

            nnz_cache[scan8[0 + 12]] =

            nnz_cache[scan8[1 + 12]] =

            nnz_cache[scan8[2 + 12]] =

            nnz_cache[scan8[3 + 12]] = (sl->cbp & 0x8000) >> 12;

        }

    }

    return 0;

}


av_cold void ff_init_lls_x86(LLSModel *m)

{

    int cpu_flags = av_get_cpu_flags();

    if (EXTERNAL_SSE2(cpu_flags)) {

        m->update_lls = ff_update_lls_sse2;

        if (m->indep_count >= 4)

            m->evaluate_lls = ff_evaluate_lls_sse2;

    }

    if (EXTERNAL_AVX(cpu_flags)) {

        m->update_lls = ff_update_lls_avx;

    }

}


static inline void RENAME(yuv2yuvX)(SwsContext *c, int16_t *lumFilter, int16_t **lumSrc, int lumFilterSize,

                                    int16_t *chrFilter, int16_t **chrSrc, int chrFilterSize,

                                    uint8_t *dest, uint8_t *uDest, uint8_t *vDest, long dstW, long chrDstW)

{

#ifdef HAVE_MMX

    if (c->flags & SWS_ACCURATE_RND){

        if (uDest){

            YSCALEYUV2YV12X_ACCURATE(   0, CHR_MMX_FILTER_OFFSET, uDest, chrDstW)

            YSCALEYUV2YV12X_ACCURATE(4096, CHR_MMX_FILTER_OFFSET, vDest, chrDstW)

        }

        YSCALEYUV2YV12X_ACCURATE(0, LUM_MMX_FILTER_OFFSET, dest, dstW)

    }else{

        if (uDest){

            YSCALEYUV2YV12X(   0, CHR_MMX_FILTER_OFFSET, uDest, chrDstW)

            YSCALEYUV2YV12X(4096, CHR_MMX_FILTER_OFFSET, vDest, chrDstW)

        }

        YSCALEYUV2YV12X(0, LUM_MMX_FILTER_OFFSET, dest, dstW)

    }

#else

#ifdef HAVE_ALTIVEC

yuv2yuvX_altivec_real(lumFilter, lumSrc, lumFilterSize,

                      chrFilter, chrSrc, chrFilterSize,

                      dest, uDest, vDest, dstW, chrDstW);

#else //HAVE_ALTIVEC

yuv2yuvXinC(lumFilter, lumSrc, lumFilterSize,

            chrFilter, chrSrc, chrFilterSize,

            dest, uDest, vDest, dstW, chrDstW);

#endif //!HAVE_ALTIVEC

#endif /* HAVE_MMX */

}


static void vmxnet3_update_rx_mode(VMXNET3State *s)

{

    s->rx_mode = VMXNET3_READ_DRV_SHARED32(s->drv_shmem,

                                           devRead.rxFilterConf.rxMode);

    VMW_CFPRN("RX mode: 0x%08X", s->rx_mode);

}


static int qemu_peek_byte(QEMUFile *f)

{

    if (f->is_write) {

        abort();

    }

    if (f->buf_index >= f->buf_size) {

        qemu_fill_buffer(f);

        if (f->buf_index >= f->buf_size) {

            return 0;

        }

    }

    return f->buf[f->buf_index];

}


static int virtio_ccw_set_vqs(SubchDev *sch, uint64_t addr, uint32_t align,

                              uint16_t index, uint16_t num)

{

    VirtIODevice *vdev = virtio_ccw_get_vdev(sch);

    if (index > VIRTIO_PCI_QUEUE_MAX) {

        return -EINVAL;

    }

    /* Current code in virtio.c relies on 4K alignment. */

    if (addr && (align != 4096)) {

        return -EINVAL;

    }

    if (!vdev) {

        return -EINVAL;

    }

    virtio_queue_set_addr(vdev, index, addr);

    if (!addr) {

        virtio_queue_set_vector(vdev, index, 0);

    } else {

        /* Fail if we don't have a big enough queue. */

        /* TODO: Add interface to handle vring.num changing */

        if (virtio_queue_get_num(vdev, index) > num) {

            return -EINVAL;

        }

        virtio_queue_set_vector(vdev, index, index);

    }

    /* tell notify handler in case of config change */

    vdev->config_vector = VIRTIO_PCI_QUEUE_MAX;

    return 0;

}


static bool cuda_cmd_set_time(CUDAState *s,

                              const uint8_t *in_data, int in_len,

                              uint8_t *out_data, int *out_len)

{

    uint32_t ti;

    if (in_len != 4) {

        return false;

    }

    ti = (((uint32_t)in_data[1]) << 24) + (((uint32_t)in_data[2]) << 16)

         + (((uint32_t)in_data[3]) << 8) + in_data[4];

    s->tick_offset = ti - (qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL)

                           / NANOSECONDS_PER_SECOND);

    return true;

}


static void vscsi_send_request_sense(VSCSIState *s, vscsi_req *req)

{

    SCSIDevice *sdev = req->sdev;

    uint8_t *cdb = req->iu.srp.cmd.cdb;

    int n;

    cdb[0] = 3;

    cdb[1] = 0;

    cdb[2] = 0;

    cdb[3] = 0;

    cdb[4] = 96;

    cdb[5] = 0;

    req->sensing = 1;

    n = sdev->info->send_command(sdev, req->qtag, cdb, req->lun);

    dprintf("VSCSI: Queued request sense tag 0x%x\n", req->qtag);

    if (n < 0) {

        fprintf(stderr, "VSCSI: REQUEST_SENSE wants write data !?!?!?\n");

        sdev->info->cancel_io(sdev, req->qtag);

        vscsi_makeup_sense(s, req, HARDWARE_ERROR, 0, 0);

        vscsi_send_rsp(s, req, CHECK_CONDITION, 0, 0);

        vscsi_put_req(s, req);

        return;

    } else if (n == 0) {

        return;

    }

    sdev->info->read_data(sdev, req->qtag);

}


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 uint64_t pmsav5_data_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)

{

    return simple_mpu_ap_bits(env->cp15.c5_data);

}


static void flat(WaveformContext *s, AVFrame *in, AVFrame *out,

                 int component, int intensity, int offset, int column)

{

    const int plane = s->desc->comp[component].plane;

    const int mirror = s->mirror;

    const int c0_linesize = in->linesize[ plane + 0 ];

    const int c1_linesize = in->linesize[(plane + 1) % s->ncomp];

    const int c2_linesize = in->linesize[(plane + 2) % s->ncomp];

    const int d0_linesize = out->linesize[ plane + 0 ];

    const int d1_linesize = out->linesize[(plane + 1) % s->ncomp];

    const int max = 255 - intensity;

    const int src_h = in->height;

    const int src_w = in->width;

    int x, y;

    if (column) {

        const int d0_signed_linesize = d0_linesize * (mirror == 1 ? -1 : 1);

        const int d1_signed_linesize = d1_linesize * (mirror == 1 ? -1 : 1);

        for (x = 0; x < src_w; x++) {

            const uint8_t *c0_data = in->data[plane + 0];

            const uint8_t *c1_data = in->data[(plane + 1) % s->ncomp];

            const uint8_t *c2_data = in->data[(plane + 2) % s->ncomp];

            uint8_t *d0_data = out->data[plane] + offset * d0_linesize;

            uint8_t *d1_data = out->data[(plane + 1) % s->ncomp] + offset * d1_linesize;

            uint8_t * const d0_bottom_line = d0_data + d0_linesize * (s->size - 1);

            uint8_t * const d0 = (mirror ? d0_bottom_line : d0_data);

            uint8_t * const d1_bottom_line = d1_data + d1_linesize * (s->size - 1);

            uint8_t * const d1 = (mirror ? d1_bottom_line : d1_data);

            for (y = 0; y < src_h; y++) {

                const int c0 = c0_data[x] + 256;

                const int c1 = FFABS(c1_data[x] - 128) + FFABS(c2_data[x] - 128);

                uint8_t *target;

                int p;

                target = d0 + x + d0_signed_linesize * c0;

                update(target, max, intensity);

                for (p = c0 - c1; p < c0 + c1; p++) {

                    target = d1 + x + d1_signed_linesize * p;

                    update(target, max, 1);

                }

                c0_data += c0_linesize;

                c1_data += c1_linesize;

                c2_data += c2_linesize;

                d0_data += d0_linesize;

                d1_data += d1_linesize;

            }

        }

    } else {

        const uint8_t *c0_data = in->data[plane];

        const uint8_t *c1_data = in->data[(plane + 1) % s->ncomp];

        const uint8_t *c2_data = in->data[(plane + 2) % s->ncomp];

        uint8_t *d0_data = out->data[plane] + offset;

        uint8_t *d1_data = out->data[(plane + 1) % s->ncomp] + offset;

        if (mirror) {

            d0_data += s->size - 1;

            d1_data += s->size - 1;

        }

        for (y = 0; y < src_h; y++) {

            for (x = 0; x < src_w; x++) {

                int c0 = c0_data[x] + 256;

                const int c1 = FFABS(c1_data[x] - 128) + FFABS(c2_data[x] - 128);

                uint8_t *target;

                int p;

                if (mirror)

                    target = d0_data - c0;

                else

                    target = d0_data + c0;

                update(target, max, intensity);

                for (p = c0 - c1; p < c0 + c1; p++) {

                    if (mirror)

                        target = d1_data - p;

                    else

                        target = d1_data + p;

                    update(target, max, 1);

                }

            }

            c0_data += c0_linesize;

            c1_data += c1_linesize;

            c2_data += c2_linesize;

            d0_data += d0_linesize;

            d1_data += d1_linesize;

        }

    }

    envelope(s, out, plane, plane);

    envelope(s, out, plane, (plane + 1) % s->ncomp);

}


av_cold int ff_mpv_common_init(MpegEncContext *s)

{

    int i;

    int nb_slices = (HAVE_THREADS &&

                     s->avctx->active_thread_type & FF_THREAD_SLICE) ?

                    s->avctx->thread_count : 1;

    if (s->encoding && s->avctx->slices)

        nb_slices = s->avctx->slices;

    if (s->codec_id == AV_CODEC_ID_MPEG2VIDEO && !s->progressive_sequence)

        s->mb_height = (s->height + 31) / 32 * 2;

    else

        s->mb_height = (s->height + 15) / 16;

    if (s->avctx->pix_fmt == AV_PIX_FMT_NONE) {

        av_log(s->avctx, AV_LOG_ERROR,

               "decoding to AV_PIX_FMT_NONE is not supported.\n");

        return -1;

    }

    if (nb_slices > MAX_THREADS || (nb_slices > s->mb_height && s->mb_height)) {

        int max_slices;

        if (s->mb_height)

            max_slices = FFMIN(MAX_THREADS, s->mb_height);

        else

            max_slices = MAX_THREADS;

        av_log(s->avctx, AV_LOG_WARNING, "too many threads/slices (%d),"

               " reducing to %d\n", nb_slices, max_slices);

        nb_slices = max_slices;

    }

    if ((s->width || s->height) &&

        av_image_check_size(s->width, s->height, 0, s->avctx))

        return -1;

    dct_init(s);

    /* set chroma shifts */

    avcodec_get_chroma_sub_sample(s->avctx->pix_fmt,

                                  &s->chroma_x_shift,

                                  &s->chroma_y_shift);

    FF_ALLOCZ_OR_GOTO(s->avctx, s->picture,

                      MAX_PICTURE_COUNT * sizeof(Picture), fail);

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

        s->picture[i].f = av_frame_alloc();

        if (!s->picture[i].f)

            goto fail;

    }

    memset(&s->next_picture, 0, sizeof(s->next_picture));

    memset(&s->last_picture, 0, sizeof(s->last_picture));

    memset(&s->current_picture, 0, sizeof(s->current_picture));

    memset(&s->new_picture, 0, sizeof(s->new_picture));

    s->next_picture.f = av_frame_alloc();

    if (!s->next_picture.f)

        goto fail;

    s->last_picture.f = av_frame_alloc();

    if (!s->last_picture.f)

        goto fail;

    s->current_picture.f = av_frame_alloc();

    if (!s->current_picture.f)

        goto fail;

    s->new_picture.f = av_frame_alloc();

    if (!s->new_picture.f)

        goto fail;

        if (init_context_frame(s))

            goto fail;

        s->parse_context.state = -1;

        s->context_initialized = 1;

        s->thread_context[0]   = s;

//     if (s->width && s->height) {

        if (nb_slices > 1) {

            for (i = 1; i < nb_slices; i++) {

                s->thread_context[i] = av_malloc(sizeof(MpegEncContext));

                memcpy(s->thread_context[i], s, sizeof(MpegEncContext));

            }

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

                if (init_duplicate_context(s->thread_context[i]) < 0)

                    goto fail;

                    s->thread_context[i]->start_mb_y =

                        (s->mb_height * (i) + nb_slices / 2) / nb_slices;

                    s->thread_context[i]->end_mb_y   =

                        (s->mb_height * (i + 1) + nb_slices / 2) / nb_slices;

            }

        } else {

            if (init_duplicate_context(s) < 0)

                goto fail;

            s->start_mb_y = 0;

            s->end_mb_y   = s->mb_height;

        }

        s->slice_context_count = nb_slices;

//     }

    return 0;

 fail:

    ff_mpv_common_end(s);

    return -1;

}