static void decode_b(AVCodecContext *ctx, int row, int col,

                     struct VP9Filter *lflvl, ptrdiff_t yoff, ptrdiff_t uvoff,

                     enum BlockLevel bl, enum BlockPartition bp)

{

    VP9Context *s = ctx->priv_data;

    VP9Block *b = s->b;

    enum BlockSize bs = bl * 3 + bp;

    int bytesperpixel = s->bytesperpixel;

    int w4 = bwh_tab[1][bs][0], h4 = bwh_tab[1][bs][1], lvl;

    int emu[2];

    AVFrame *f = s->frames[CUR_FRAME].tf.f;

    s->row = row;

    s->row7 = row & 7;

    s->col = col;

    s->col7 = col & 7;

    s->min_mv.x = -(128 + col * 64);

    s->min_mv.y = -(128 + row * 64);

    s->max_mv.x = 128 + (s->cols - col - w4) * 64;

    s->max_mv.y = 128 + (s->rows - row - h4) * 64;

    if (s->pass < 2) {

        b->bs = bs;

        b->bl = bl;

        b->bp = bp;

        decode_mode(ctx);

        b->uvtx = b->tx - ((s->ss_h && w4 * 2 == (1 << b->tx)) ||

                           (s->ss_v && h4 * 2 == (1 << b->tx)));

        if (!b->skip) {

            int has_coeffs;

            if (bytesperpixel == 1) {

                has_coeffs = decode_coeffs_8bpp(ctx);

            } else {

                has_coeffs = decode_coeffs_16bpp(ctx);

            }

            if (!has_coeffs && b->bs <= BS_8x8 && !b->intra) {

                b->skip = 1;

                memset(&s->above_skip_ctx[col], 1, w4);

                memset(&s->left_skip_ctx[s->row7], 1, h4);

            }

        } else {

            int row7 = s->row7;

#define SPLAT_ZERO_CTX(v, n) \

    switch (n) { \

    case 1:  v = 0;          break; \

    case 2:  AV_ZERO16(&v);  break; \

    case 4:  AV_ZERO32(&v);  break; \

    case 8:  AV_ZERO64(&v);  break; \

    case 16: AV_ZERO128(&v); break; \

    }

#define SPLAT_ZERO_YUV(dir, var, off, n, dir2) \

    do { \

        SPLAT_ZERO_CTX(s->dir##_y_##var[off * 2], n * 2); \

        if (s->ss_##dir2) { \

            SPLAT_ZERO_CTX(s->dir##_uv_##var[0][off], n); \

            SPLAT_ZERO_CTX(s->dir##_uv_##var[1][off], n); \

        } else { \

            SPLAT_ZERO_CTX(s->dir##_uv_##var[0][off * 2], n * 2); \

            SPLAT_ZERO_CTX(s->dir##_uv_##var[1][off * 2], n * 2); \

        } \

    } while (0)

            switch (w4) {

            case 1: SPLAT_ZERO_YUV(above, nnz_ctx, col, 1, h); break;

            case 2: SPLAT_ZERO_YUV(above, nnz_ctx, col, 2, h); break;

            case 4: SPLAT_ZERO_YUV(above, nnz_ctx, col, 4, h); break;

            case 8: SPLAT_ZERO_YUV(above, nnz_ctx, col, 8, h); break;

            }

            switch (h4) {

            case 1: SPLAT_ZERO_YUV(left, nnz_ctx, row7, 1, v); break;

            case 2: SPLAT_ZERO_YUV(left, nnz_ctx, row7, 2, v); break;

            case 4: SPLAT_ZERO_YUV(left, nnz_ctx, row7, 4, v); break;

            case 8: SPLAT_ZERO_YUV(left, nnz_ctx, row7, 8, v); break;

            }

        }

        if (s->pass == 1) {

            s->b++;

            s->block += w4 * h4 * 64 * bytesperpixel;

            s->uvblock[0] += w4 * h4 * 64 * bytesperpixel >> (s->ss_h + s->ss_v);

            s->uvblock[1] += w4 * h4 * 64 * bytesperpixel >> (s->ss_h + s->ss_v);

            s->eob += 4 * w4 * h4;

            s->uveob[0] += 4 * w4 * h4 >> (s->ss_h + s->ss_v);

            s->uveob[1] += 4 * w4 * h4 >> (s->ss_h + s->ss_v);

            return;

        }

    }

    // emulated overhangs if the stride of the target buffer can't hold. This

    // makes it possible to support emu-edge and so on even if we have large block

    // overhangs

    emu[0] = (col + w4) * 8 > f->linesize[0] ||

             (row + h4) > s->rows;

    emu[1] = (col + w4) * 4 > f->linesize[1] ||

             (row + h4) > s->rows;

    if (emu[0]) {

        s->dst[0] = s->tmp_y;

        s->y_stride = 128;

    } else {

        s->dst[0] = f->data[0] + yoff;

        s->y_stride = f->linesize[0];

    }

    if (emu[1]) {

        s->dst[1] = s->tmp_uv[0];

        s->dst[2] = s->tmp_uv[1];

        s->uv_stride = 128;

    } else {

        s->dst[1] = f->data[1] + uvoff;

        s->dst[2] = f->data[2] + uvoff;

        s->uv_stride = f->linesize[1];

    }

    if (b->intra) {

        if (s->bpp > 8) {

            intra_recon_16bpp(ctx, yoff, uvoff);

        } else {

            intra_recon_8bpp(ctx, yoff, uvoff);

        }

    } else {

        if (s->bpp > 8) {

            inter_recon_16bpp(ctx);

        } else {

            inter_recon_8bpp(ctx);

        }

    }

    if (emu[0]) {

        int w = FFMIN(s->cols - col, w4) * 8, h = FFMIN(s->rows - row, h4) * 8, n, o = 0;

        for (n = 0; o < w; n++) {

            int bw = 64 >> n;

            av_assert2(n <= 4);

            if (w & bw) {

                s->dsp.mc[n][0][0][0][0](f->data[0] + yoff + o * bytesperpixel, f->linesize[0],

                                         s->tmp_y + o * bytesperpixel, 128, h, 0, 0);

                o += bw;

            }

        }

    }

    if (emu[1]) {

        int w = FFMIN(s->cols - col, w4) * 8 >> s->ss_h;

        int h = FFMIN(s->rows - row, h4) * 8 >> s->ss_v, n, o = 0;

        for (n = s->ss_h; o < w; n++) {

            int bw = 64 >> n;

            av_assert2(n <= 4);

            if (w & bw) {

                s->dsp.mc[n][0][0][0][0](f->data[1] + uvoff + o * bytesperpixel, f->linesize[1],

                                         s->tmp_uv[0] + o * bytesperpixel, 128, h, 0, 0);

                s->dsp.mc[n][0][0][0][0](f->data[2] + uvoff + o * bytesperpixel, f->linesize[2],

                                         s->tmp_uv[1] + o * bytesperpixel, 128, h, 0, 0);

                o += bw;

            }

        }

    }

    // pick filter level and find edges to apply filter to

    if (s->filter.level &&

        (lvl = s->segmentation.feat[b->seg_id].lflvl[b->intra ? 0 : b->ref[0] + 1]

                                                    [b->mode[3] != ZEROMV]) > 0) {

        int x_end = FFMIN(s->cols - col, w4), y_end = FFMIN(s->rows - row, h4);

        int skip_inter = !b->intra && b->skip, col7 = s->col7, row7 = s->row7;

        setctx_2d(&lflvl->level[row7 * 8 + col7], w4, h4, 8, lvl);

        mask_edges(lflvl->mask[0], 0, 0, row7, col7, x_end, y_end, 0, 0, b->tx, skip_inter);

        if (s->ss_h || s->ss_v)

            mask_edges(lflvl->mask[1], s->ss_h, s->ss_v, row7, col7, x_end, y_end,

                       s->cols & 1 && col + w4 >= s->cols ? s->cols & 7 : 0,

                       s->rows & 1 && row + h4 >= s->rows ? s->rows & 7 : 0,

                       b->uvtx, skip_inter);

        if (!s->filter.lim_lut[lvl]) {

            int sharp = s->filter.sharpness;

            int limit = lvl;

            if (sharp > 0) {

                limit >>= (sharp + 3) >> 2;

                limit = FFMIN(limit, 9 - sharp);

            }

            limit = FFMAX(limit, 1);

            s->filter.lim_lut[lvl] = limit;

            s->filter.mblim_lut[lvl] = 2 * (lvl + 2) + limit;

        }

    }

    if (s->pass == 2) {

        s->b++;

        s->block += w4 * h4 * 64 * bytesperpixel;

        s->uvblock[0] += w4 * h4 * 64 * bytesperpixel >> (s->ss_v + s->ss_h);

        s->uvblock[1] += w4 * h4 * 64 * bytesperpixel >> (s->ss_v + s->ss_h);

        s->eob += 4 * w4 * h4;

        s->uveob[0] += 4 * w4 * h4 >> (s->ss_v + s->ss_h);

        s->uveob[1] += 4 * w4 * h4 >> (s->ss_v + s->ss_h);

    }

}


static void unset_dirty_tracking(void)

{

    BlkMigDevState *bmds;

    QSIMPLEQ_FOREACH(bmds, &block_mig_state.bmds_list, entry) {

        bdrv_release_dirty_bitmap(bmds->bs, bmds->dirty_bitmap);

    }

}


static void get_sel_entry(IPMIBmcSim *ibs,

                          uint8_t *cmd, unsigned int cmd_len,

                          uint8_t *rsp, unsigned int *rsp_len,

                          unsigned int max_rsp_len)

{

    unsigned int val;

    IPMI_CHECK_CMD_LEN(8);

    if (cmd[6]) {

        IPMI_CHECK_RESERVATION(2, ibs->sel.reservation);

    }

    if (ibs->sel.next_free == 0) {

        rsp[2] = IPMI_CC_REQ_ENTRY_NOT_PRESENT;

        return;

    }

    if (cmd[6] > 15) {

        rsp[2] = IPMI_CC_INVALID_DATA_FIELD;

        return;

    }

    if (cmd[7] == 0xff) {

        cmd[7] = 16;

    } else if ((cmd[7] + cmd[6]) > 16) {

        rsp[2] = IPMI_CC_INVALID_DATA_FIELD;

        return;

    } else {

        cmd[7] += cmd[6];

    }

    val = cmd[4] | (cmd[5] << 8);

    if (val == 0xffff) {

        val = ibs->sel.next_free - 1;

    } else if (val >= ibs->sel.next_free) {

        rsp[2] = IPMI_CC_REQ_ENTRY_NOT_PRESENT;

        return;

    }

    if ((val + 1) == ibs->sel.next_free) {

        IPMI_ADD_RSP_DATA(0xff);

        IPMI_ADD_RSP_DATA(0xff);

    } else {

        IPMI_ADD_RSP_DATA((val + 1) & 0xff);

        IPMI_ADD_RSP_DATA(((val + 1) >> 8) & 0xff);

    }

    for (; cmd[6] < cmd[7]; cmd[6]++) {

        IPMI_ADD_RSP_DATA(ibs->sel.sel[val][cmd[6]]);

    }

}


int inet_dgram_opts(QemuOpts *opts, Error **errp)

{

    struct addrinfo ai, *peer = NULL, *local = NULL;

    const char *addr;

    const char *port;

    int sock = -1, rc;

    /* lookup peer addr */

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

    ai.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;

    ai.ai_family = PF_UNSPEC;

    ai.ai_socktype = SOCK_DGRAM;

    addr = qemu_opt_get(opts, "host");

    port = qemu_opt_get(opts, "port");

    if (addr == NULL || strlen(addr) == 0) {

        addr = "localhost";

    }

    if (port == NULL || strlen(port) == 0) {

        error_setg(errp, "remote port not specified");

        return -1;

    }

    if (qemu_opt_get_bool(opts, "ipv4", 0))

        ai.ai_family = PF_INET;

    if (qemu_opt_get_bool(opts, "ipv6", 0))

        ai.ai_family = PF_INET6;

    if (0 != (rc = getaddrinfo(addr, port, &ai, &peer))) {

        error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,

                   gai_strerror(rc));

	return -1;

    }

    /* lookup local addr */

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

    ai.ai_flags = AI_PASSIVE;

    ai.ai_family = peer->ai_family;

    ai.ai_socktype = SOCK_DGRAM;

    addr = qemu_opt_get(opts, "localaddr");

    port = qemu_opt_get(opts, "localport");

    if (addr == NULL || strlen(addr) == 0) {

        addr = NULL;

    }

    if (!port || strlen(port) == 0)

        port = "0";

    if (0 != (rc = getaddrinfo(addr, port, &ai, &local))) {

        error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,

                   gai_strerror(rc));

        goto err;

    }

    /* create socket */

    sock = qemu_socket(peer->ai_family, peer->ai_socktype, peer->ai_protocol);

    if (sock < 0) {

        error_setg_errno(errp, errno, "Failed to create socket");

        goto err;

    }

    socket_set_fast_reuse(sock);

    /* bind socket */

    if (bind(sock, local->ai_addr, local->ai_addrlen) < 0) {

        error_setg_errno(errp, errno, "Failed to bind socket");

        goto err;

    }

    /* connect to peer */

    if (connect(sock,peer->ai_addr,peer->ai_addrlen) < 0) {

        error_setg_errno(errp, errno, "Failed to connect socket");

        goto err;

    }

    freeaddrinfo(local);

    freeaddrinfo(peer);

    return sock;

err:

    if (-1 != sock)

        closesocket(sock);

    if (local)

        freeaddrinfo(local);

    if (peer)

        freeaddrinfo(peer);

    return -1;

}


e1000e_io_write(void *opaque, hwaddr addr,

                uint64_t val, unsigned size)

{

    E1000EState *s = opaque;

    uint32_t idx;

    switch (addr) {

    case E1000_IOADDR:

        trace_e1000e_io_write_addr(val);

        s->ioaddr = (uint32_t) val;

        return;

    case E1000_IODATA:

        if (e1000e_io_get_reg_index(s, &idx)) {

            trace_e1000e_io_write_data(idx, val);

            e1000e_core_write(&s->core, idx, val, sizeof(val));

        }

        return;

    default:

        trace_e1000e_wrn_io_write_unknown(addr);

        return;

    }

}


static int find_partition(BlockDriverState *bs, int partition,

                          off_t *offset, off_t *size)

{

    struct partition_record mbr[4];

    uint8_t data[512];

    int i;

    int ext_partnum = 4;

    if (bdrv_read(bs, 0, data, 1))

        errx(EINVAL, "error while reading");

    if (data[510] != 0x55 || data[511] != 0xaa) {

        errno = -EINVAL;

        return -1;

    }

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

        read_partition(&data[446 + 16 * i], &mbr[i]);

        if (!mbr[i].nb_sectors_abs)

            continue;

        if (mbr[i].system == 0xF || mbr[i].system == 0x5) {

            struct partition_record ext[4];

            uint8_t data1[512];

            int j;

            if (bdrv_read(bs, mbr[i].start_sector_abs, data1, 1))

                errx(EINVAL, "error while reading");

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

                read_partition(&data1[446 + 16 * j], &ext[j]);

                if (!ext[j].nb_sectors_abs)

                    continue;

                if ((ext_partnum + j + 1) == partition) {

                    *offset = (uint64_t)ext[j].start_sector_abs << 9;

                    *size = (uint64_t)ext[j].nb_sectors_abs << 9;

                    return 0;

                }

            }

            ext_partnum += 4;

        } else if ((i + 1) == partition) {

            *offset = (uint64_t)mbr[i].start_sector_abs << 9;

            *size = (uint64_t)mbr[i].nb_sectors_abs << 9;

            return 0;

        }

    }

    errno = -ENOENT;

    return -1;

}


int register_savevm_live(DeviceState *dev,

                         const char *idstr,

                         int instance_id,

                         int version_id,

                         SaveVMHandlers *ops,

                         void *opaque)

{

    SaveStateEntry *se;

    se = g_malloc0(sizeof(SaveStateEntry));

    se->version_id = version_id;

    se->section_id = savevm_state.global_section_id++;

    se->ops = ops;

    se->opaque = opaque;

    se->vmsd = NULL;

    /* if this is a live_savem then set is_ram */

    if (ops->save_live_setup != NULL) {

        se->is_ram = 1;

    }

    if (dev) {

        char *id = qdev_get_dev_path(dev);

        if (id) {

            pstrcpy(se->idstr, sizeof(se->idstr), id);

            pstrcat(se->idstr, sizeof(se->idstr), "/");

            g_free(id);

            se->compat = g_malloc0(sizeof(CompatEntry));

            pstrcpy(se->compat->idstr, sizeof(se->compat->idstr), idstr);

            se->compat->instance_id = instance_id == -1 ?

                         calculate_compat_instance_id(idstr) : instance_id;

            instance_id = -1;

        }

    }

    pstrcat(se->idstr, sizeof(se->idstr), idstr);

    if (instance_id == -1) {

        se->instance_id = calculate_new_instance_id(se->idstr);

    } else {

        se->instance_id = instance_id;

    }

    assert(!se->compat || se->instance_id == 0);

    /* add at the end of list */

    QTAILQ_INSERT_TAIL(&savevm_state.handlers, se, entry);

    return 0;

}


static int l2_load(BlockDriverState *bs, uint64_t l2_offset,

    uint64_t **l2_table)

{

    BDRVQcowState *s = bs->opaque;

    int min_index;

    int ret;

    /* seek if the table for the given offset is in the cache */

    *l2_table = seek_l2_table(s, l2_offset);

    if (*l2_table != NULL) {

        return 0;

    }

    /* not found: load a new entry in the least used one */

    min_index = l2_cache_new_entry(bs);

    *l2_table = s->l2_cache + (min_index << s->l2_bits);

    BLKDBG_EVENT(bs->file, BLKDBG_L2_LOAD);

    ret = bdrv_pread(bs->file, l2_offset, *l2_table,

        s->l2_size * sizeof(uint64_t));

    if (ret < 0) {

        return ret;

    }

    s->l2_cache_offsets[min_index] = l2_offset;

    s->l2_cache_counts[min_index] = 1;

    return 0;

}


print_operand_value (char *buf, size_t bufsize, int hex, bfd_vma disp)

{

  if (address_mode == mode_64bit)

    {

      if (hex)

	{

	  char tmp[30];

	  int i;

	  buf[0] = '0';

	  buf[1] = 'x';

          snprintf_vma (tmp, sizeof(tmp), disp);

	  for (i = 0; tmp[i] == '0' && tmp[i + 1]; i++);

          pstrcpy (buf + 2, bufsize - 2, tmp + i);

	}

      else

	{

	  bfd_signed_vma v = disp;

	  char tmp[30];

	  int i;

	  if (v < 0)

	    {

	      *(buf++) = '-';

	      v = -disp;

	      /* Check for possible overflow on 0x8000000000000000.  */

	      if (v < 0)

		{

                  pstrcpy (buf, bufsize, "9223372036854775808");

		  return;

		}

	    }

	  if (!v)

	    {

                pstrcpy (buf, bufsize, "0");

	      return;

	    }

	  i = 0;

	  tmp[29] = 0;

	  while (v)

	    {

	      tmp[28 - i] = (v % 10) + '0';

	      v /= 10;

	      i++;

	    }

          pstrcpy (buf, bufsize, tmp + 29 - i);

	}

    }

  else

    {

      if (hex)

        snprintf (buf, bufsize, "0x%x", (unsigned int) disp);

      else

        snprintf (buf, bufsize, "%d", (int) disp);

    }

}


void OPPROTO op_4xx_tlbsx_check (void)

{

    int tmp;

    tmp = xer_so;

    if (T0 != -1)

        tmp |= 0x02;

    env->crf[0] = tmp;

    RETURN();

}


Jpeg2000TgtNode *ff_j2k_tag_tree_init(int w, int h)

{

    int pw = w, ph = h;

    Jpeg2000TgtNode *res, *t, *t2;

    int32_t tt_size;

    tt_size = tag_tree_size(w, h);

    t = res = av_mallocz(tt_size, sizeof(*t));

    if (!res)

        return NULL;

    while (w > 1 || h > 1) {

        int i, j;

        pw = w;

        ph = h;

        w  = (w + 1) >> 1;

        h  = (h + 1) >> 1;

        t2 = t + pw * ph;

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

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

                t[i * pw + j].parent = &t2[(i >> 1) * w + (j >> 1)];

        t = t2;

    }

    t[0].parent = NULL;

    return res;

}


static void test_hmac_speed(const void *opaque)

{

    size_t chunk_size = (size_t)opaque;

    QCryptoHmac *hmac = NULL;

    uint8_t *in = NULL, *out = NULL;

    size_t out_len = 0;

    double total = 0.0;

    struct iovec iov;

    Error *err = NULL;

    int ret;

    if (!qcrypto_hmac_supports(QCRYPTO_HASH_ALG_SHA256)) {

        return;

    }

    in = g_new0(uint8_t, chunk_size);

    memset(in, g_test_rand_int(), chunk_size);

    iov.iov_base = (char *)in;

    iov.iov_len = chunk_size;

    g_test_timer_start();

    do {

        hmac = qcrypto_hmac_new(QCRYPTO_HASH_ALG_SHA256,

                                (const uint8_t *)KEY, strlen(KEY), &err);

        g_assert(err == NULL);

        g_assert(hmac != NULL);

        ret = qcrypto_hmac_bytesv(hmac, &iov, 1, &out, &out_len, &err);

        g_assert(ret == 0);

        g_assert(err == NULL);

        qcrypto_hmac_free(hmac);

        total += chunk_size;

    } while (g_test_timer_elapsed() < 5.0);

    total /= 1024 * 1024; /* to MB */

    g_print("hmac(sha256): ");

    g_print("Testing chunk_size %ld bytes ", chunk_size);

    g_print("done: %.2f MB in %.2f secs: ", total, g_test_timer_last());

    g_print("%.2f MB/sec\n", total / g_test_timer_last());

    g_free(out);

    g_free(in);

}


static int smush_read_packet(AVFormatContext *ctx, AVPacket *pkt)

{

    SMUSHContext *smush = ctx->priv_data;

    AVIOContext *pb = ctx->pb;

    int done = 0;

    while (!done) {

        uint32_t sig, size;

        if (url_feof(pb))

            return AVERROR_EOF;

        sig    = avio_rb32(pb);

        size   = avio_rb32(pb);

        switch (sig) {

        case MKBETAG('F', 'R', 'M', 'E'):

            if (smush->version)

                break;

            if (av_get_packet(pb, pkt, size) < 0)

                return AVERROR(EIO);

            pkt->stream_index = smush->video_stream_index;

            done = 1;

            break;

        case MKBETAG('B', 'l', '1', '6'):

            if (av_get_packet(pb, pkt, size) < 0)

                return AVERROR(EIO);

            pkt->stream_index = smush->video_stream_index;

            pkt->duration = 1;

            done = 1;

            break;

        case MKBETAG('W', 'a', 'v', 'e'):

            if (size < 13)

                return AVERROR_INVALIDDATA;

            if (av_get_packet(pb, pkt, size) < 0)

                return AVERROR(EIO);

            pkt->stream_index = smush->audio_stream_index;

            pkt->flags       |= AV_PKT_FLAG_KEY;

            pkt->duration = AV_RB32(pkt->data);

            if (pkt->duration == 0xFFFFFFFFu)

                pkt->duration = AV_RB32(pkt->data + 8);

            done = 1;

            break;

        default:

            avio_skip(pb, size);

            break;

        }

    }

    return 0;

}


static inline void mix_dualmono_to_stereo(AC3DecodeContext *ctx)

{

    int i;

    float tmp;

    float (*output)[256] = ctx->audio_block.block_output;

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

        tmp = output[1][i] + output[2][i];

        output[1][i] = output[2][i] = tmp;

    }

}


static OSStatus ffat_encode_callback(AudioConverterRef converter, UInt32 *nb_packets,

                                     AudioBufferList *data,

                                     AudioStreamPacketDescription **packets,

                                     void *inctx)

{

    AVCodecContext *avctx = inctx;

    ATDecodeContext *at = avctx->priv_data;

    if (at->eof) {

        *nb_packets = 0;

        return 0;

    }

    av_frame_unref(&at->in_frame);

    av_frame_move_ref(&at->in_frame, &at->new_in_frame);

    if (!at->in_frame.data[0]) {

        *nb_packets = 0;

        return 1;

    }

    data->mNumberBuffers              = 1;

    data->mBuffers[0].mNumberChannels = avctx->channels;

    data->mBuffers[0].mDataByteSize   = at->in_frame.nb_samples *

                                        av_get_bytes_per_sample(avctx->sample_fmt) *

                                        avctx->channels;

    data->mBuffers[0].mData           = at->in_frame.data[0];

    if (*nb_packets > at->in_frame.nb_samples)

        *nb_packets = at->in_frame.nb_samples;

    return 0;

}


void rgb16tobgr16(const uint8_t *src, uint8_t *dst, long src_size)

{

	long i;

	long num_pixels = src_size >> 1;

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

	{

	    unsigned b,g,r;

	    register uint16_t rgb;

	    rgb = src[2*i];

	    r = rgb&0x1F;

	    g = (rgb&0x7E0)>>5;

	    b = (rgb&0xF800)>>11;

	    dst[2*i] = (b&0x1F) | ((g&0x3F)<<5) | ((r&0x1F)<<11);

	}

}


static uint32_t ehci_mem_readl(void *ptr, target_phys_addr_t addr)

{

    EHCIState *s = ptr;

    uint32_t val;

    val = s->mmio[addr] | (s->mmio[addr+1] << 8) |

          (s->mmio[addr+2] << 16) | (s->mmio[addr+3] << 24);

    trace_usb_ehci_mmio_readl(addr, addr2str(addr), val);

    return val;

}


static void qmp_input_type_number(Visitor *v, double *obj, const char *name,

                                  Error **errp)

{

    QmpInputVisitor *qiv = to_qiv(v);

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

    if (!qobj || (qobject_type(qobj) != QTYPE_QFLOAT &&

        qobject_type(qobj) != QTYPE_QINT)) {

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

                   "number");

        return;

    }

    if (qobject_type(qobj) == QTYPE_QINT) {

        *obj = qint_get_int(qobject_to_qint(qobj));

    } else {

        *obj = qfloat_get_double(qobject_to_qfloat(qobj));

    }

}


int bdrv_all_find_snapshot(const char *name, BlockDriverState **first_bad_bs)

{

    QEMUSnapshotInfo sn;

    int err = 0;

    BlockDriverState *bs;

    BdrvNextIterator *it = NULL;

    while (err == 0 && (it = bdrv_next(it, &bs))) {

        AioContext *ctx = bdrv_get_aio_context(bs);

        aio_context_acquire(ctx);

        if (bdrv_can_snapshot(bs)) {

            err = bdrv_snapshot_find(bs, &sn, name);

        }

        aio_context_release(ctx);

    }

    *first_bad_bs = bs;

    return err;

}


static int cow_is_allocated(BlockDriverState *bs, int64_t sector_num,

        int nb_sectors, int *num_same)

{

    int changed;

    if (nb_sectors == 0) {

	*num_same = nb_sectors;

	return 0;

    }

    changed = is_bit_set(bs, sector_num);

    if (changed < 0) {

        return 0; /* XXX: how to return I/O errors? */

    }

    for (*num_same = 1; *num_same < nb_sectors; (*num_same)++) {

	if (is_bit_set(bs, sector_num + *num_same) != changed)

	    break;

    }

    return changed;

}


static inline void gen_goto_tb(DisasContext *ctx, int n, target_ulong dest)

{

    TranslationBlock *tb;

    tb = ctx->tb;

    if ((tb->pc & TARGET_PAGE_MASK) == (dest & TARGET_PAGE_MASK)) {

        if (n == 0)

            gen_op_goto_tb0(TBPARAM(tb));

        else

            gen_op_goto_tb1(TBPARAM(tb));

        gen_op_set_T1(dest);

        gen_op_b_T1();

        gen_op_set_T0((long)tb + n);

        if (ctx->singlestep_enabled)

            gen_op_debug();

        gen_op_exit_tb();

    } else {

        gen_op_set_T1(dest);

        gen_op_b_T1();

        gen_op_reset_T0();

        if (ctx->singlestep_enabled)

            gen_op_debug();

        gen_op_exit_tb();

    }

}


int qcow2_alloc_cluster_link_l2(BlockDriverState *bs, QCowL2Meta *m)

{

    BDRVQcowState *s = bs->opaque;

    int i, j = 0, l2_index, ret;

    uint64_t *old_cluster, *l2_table;

    uint64_t cluster_offset = m->alloc_offset;

    trace_qcow2_cluster_link_l2(qemu_coroutine_self(), m->nb_clusters);

    assert(m->nb_clusters > 0);

    old_cluster = g_malloc(m->nb_clusters * sizeof(uint64_t));

    /* copy content of unmodified sectors */

    ret = perform_cow(bs, m, &m->cow_start);

    if (ret < 0) {

        goto err;

    }

    ret = perform_cow(bs, m, &m->cow_end);

    if (ret < 0) {

        goto err;

    }

    /* Update L2 table. */

    if (s->use_lazy_refcounts) {

        qcow2_mark_dirty(bs);

    }

    if (qcow2_need_accurate_refcounts(s)) {

        qcow2_cache_set_dependency(bs, s->l2_table_cache,

                                   s->refcount_block_cache);

    }

    ret = get_cluster_table(bs, m->offset, &l2_table, &l2_index);

    if (ret < 0) {

        goto err;

    }

    qcow2_cache_entry_mark_dirty(s->l2_table_cache, l2_table);

    for (i = 0; i < m->nb_clusters; i++) {

        /* if two concurrent writes happen to the same unallocated cluster

	 * each write allocates separate cluster and writes data concurrently.

	 * The first one to complete updates l2 table with pointer to its

	 * cluster the second one has to do RMW (which is done above by

	 * copy_sectors()), update l2 table with its cluster pointer and free

	 * old cluster. This is what this loop does */

        if(l2_table[l2_index + i] != 0)

            old_cluster[j++] = l2_table[l2_index + i];

        l2_table[l2_index + i] = cpu_to_be64((cluster_offset +

                    (i << s->cluster_bits)) | QCOW_OFLAG_COPIED);

     }

    ret = qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);

    if (ret < 0) {

        goto err;

    }

    /*

     * If this was a COW, we need to decrease the refcount of the old cluster.

     * Also flush bs->file to get the right order for L2 and refcount update.

     *

     * Don't discard clusters that reach a refcount of 0 (e.g. compressed

     * clusters), the next write will reuse them anyway.

     */

    if (j != 0) {

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

            qcow2_free_any_clusters(bs, be64_to_cpu(old_cluster[i]), 1,

                                    QCOW2_DISCARD_NEVER);

        }

    }

    ret = 0;

err:

    g_free(old_cluster);

    return ret;

 }


int ff_vp8_decode_frame(AVCodecContext *avctx, void *data, int *got_frame,

                        AVPacket *avpkt)

{

    VP8Context *s = avctx->priv_data;

    int ret, i, referenced, num_jobs;

    enum AVDiscard skip_thresh;

    VP8Frame *av_uninit(curframe), *prev_frame;

    if ((ret = decode_frame_header(s, avpkt->data, avpkt->size)) < 0)

        goto err;

    prev_frame = s->framep[VP56_FRAME_CURRENT];

    referenced = s->update_last || s->update_golden == VP56_FRAME_CURRENT ||

                 s->update_altref == VP56_FRAME_CURRENT;

    skip_thresh = !referenced ? AVDISCARD_NONREF

                              : !s->keyframe ? AVDISCARD_NONKEY

                                             : AVDISCARD_ALL;

    if (avctx->skip_frame >= skip_thresh) {

        s->invisible = 1;

        memcpy(&s->next_framep[0], &s->framep[0], sizeof(s->framep[0]) * 4);

        goto skip_decode;

    }

    s->deblock_filter = s->filter.level && avctx->skip_loop_filter < skip_thresh;

    // release no longer referenced frames

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

        if (s->frames[i].tf.f->data[0] &&

            &s->frames[i] != prev_frame &&

            &s->frames[i] != s->framep[VP56_FRAME_PREVIOUS] &&

            &s->frames[i] != s->framep[VP56_FRAME_GOLDEN]   &&

            &s->frames[i] != s->framep[VP56_FRAME_GOLDEN2])

            vp8_release_frame(s, &s->frames[i]);

    // find a free buffer

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

        if (&s->frames[i] != prev_frame &&

            &s->frames[i] != s->framep[VP56_FRAME_PREVIOUS] &&

            &s->frames[i] != s->framep[VP56_FRAME_GOLDEN]   &&

            &s->frames[i] != s->framep[VP56_FRAME_GOLDEN2]) {

            curframe = s->framep[VP56_FRAME_CURRENT] = &s->frames[i];

            break;

        }

    if (i == 5) {

        av_log(avctx, AV_LOG_FATAL, "Ran out of free frames!\n");

        abort();

    }

    if (curframe->tf.f->data[0])

        vp8_release_frame(s, curframe);

    /* Given that arithmetic probabilities are updated every frame, it's quite

     * likely that the values we have on a random interframe are complete

     * junk if we didn't start decode on a keyframe. So just don't display

     * anything rather than junk. */

    if (!s->keyframe && (!s->framep[VP56_FRAME_PREVIOUS] ||

                         !s->framep[VP56_FRAME_GOLDEN]   ||

                         !s->framep[VP56_FRAME_GOLDEN2])) {

        av_log(avctx, AV_LOG_WARNING,

               "Discarding interframe without a prior keyframe!\n");

        ret = AVERROR_INVALIDDATA;

        goto err;

    }

    curframe->tf.f->key_frame = s->keyframe;

    curframe->tf.f->pict_type = s->keyframe ? AV_PICTURE_TYPE_I

                                            : AV_PICTURE_TYPE_P;

    if ((ret = vp8_alloc_frame(s, curframe, referenced))) {

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

        goto err;

    }

    // check if golden and altref are swapped

    if (s->update_altref != VP56_FRAME_NONE)

        s->next_framep[VP56_FRAME_GOLDEN2] = s->framep[s->update_altref];

    else

        s->next_framep[VP56_FRAME_GOLDEN2] = s->framep[VP56_FRAME_GOLDEN2];

    if (s->update_golden != VP56_FRAME_NONE)

        s->next_framep[VP56_FRAME_GOLDEN] = s->framep[s->update_golden];

    else

        s->next_framep[VP56_FRAME_GOLDEN] = s->framep[VP56_FRAME_GOLDEN];

    if (s->update_last)

        s->next_framep[VP56_FRAME_PREVIOUS] = curframe;

    else

        s->next_framep[VP56_FRAME_PREVIOUS] = s->framep[VP56_FRAME_PREVIOUS];

    s->next_framep[VP56_FRAME_CURRENT] = curframe;

    ff_thread_finish_setup(avctx);

    s->linesize   = curframe->tf.f->linesize[0];

    s->uvlinesize = curframe->tf.f->linesize[1];

    memset(s->top_nnz, 0, s->mb_width * sizeof(*s->top_nnz));

    /* Zero macroblock structures for top/top-left prediction

     * from outside the frame. */

    if (!s->mb_layout)

        memset(s->macroblocks + s->mb_height * 2 - 1, 0,

               (s->mb_width + 1) * sizeof(*s->macroblocks));

    if (!s->mb_layout && s->keyframe)

        memset(s->intra4x4_pred_mode_top, DC_PRED, s->mb_width * 4);

    memset(s->ref_count, 0, sizeof(s->ref_count));

    if (s->mb_layout == 1) {

        // Make sure the previous frame has read its segmentation map,

        // if we re-use the same map.

        if (prev_frame && s->segmentation.enabled &&

            !s->segmentation.update_map)

            ff_thread_await_progress(&prev_frame->tf, 1, 0);

        vp8_decode_mv_mb_modes(avctx, curframe, prev_frame);

    }

    if (avctx->active_thread_type == FF_THREAD_FRAME)

        num_jobs = 1;

    else

        num_jobs = FFMIN(s->num_coeff_partitions, avctx->thread_count);

    s->num_jobs   = num_jobs;

    s->curframe   = curframe;

    s->prev_frame = prev_frame;

    s->mv_min.y   = -MARGIN;

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

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

        s->thread_data[i].thread_mb_pos = 0;

        s->thread_data[i].wait_mb_pos   = INT_MAX;

    }

    avctx->execute2(avctx, vp8_decode_mb_row_sliced,

                    s->thread_data, NULL, num_jobs);

    ff_thread_report_progress(&curframe->tf, INT_MAX, 0);

    memcpy(&s->framep[0], &s->next_framep[0], sizeof(s->framep[0]) * 4);

skip_decode:

    // if future frames don't use the updated probabilities,

    // reset them to the values we saved

    if (!s->update_probabilities)

        s->prob[0] = s->prob[1];

    if (!s->invisible) {

        if ((ret = av_frame_ref(data, curframe->tf.f)) < 0)

            return ret;

        *got_frame = 1;

    }

    return avpkt->size;

err:

    memcpy(&s->next_framep[0], &s->framep[0], sizeof(s->framep[0]) * 4);

    return ret;

}


static void test_visitor_in_null(TestInputVisitorData *data,

                                 const void *unused)

{

    Visitor *v;

    Error *err = NULL;

    char *tmp;

    /*

     * FIXME: Since QAPI doesn't know the 'null' type yet, we can't

     * test visit_type_null() by reading into a QAPI struct then

     * checking that it was populated correctly.  The best we can do

     * for now is ensure that we consumed null from the input, proven

     * by the fact that we can't re-read the key; and that we detect

     * when input is not null.

     */

    v = visitor_input_test_init(data, "{ 'a': null, 'b': '', 'c': null }");

    visit_start_struct(v, NULL, NULL, 0, &error_abort);

    visit_type_null(v, "a", &error_abort);

    visit_type_null(v, "b", &err);

    error_free_or_abort(&err);

    visit_type_str(v, "c", &tmp, &err);

    g_assert(!tmp);

    error_free_or_abort(&err);

    visit_check_struct(v, &error_abort);

    visit_end_struct(v, NULL);

}


static av_cold int dnxhd_decode_init(AVCodecContext *avctx)

{

    DNXHDContext *ctx = avctx->priv_data;

    ctx->avctx = avctx;

    ctx->cid = -1;

    avctx->colorspace = AVCOL_SPC_BT709;

    avctx->coded_width  = FFALIGN(avctx->width,  16);

    avctx->coded_height = FFALIGN(avctx->height, 16);

    ctx->rows = av_mallocz_array(avctx->thread_count, sizeof(RowContext));

    if (!ctx->rows)

        return AVERROR(ENOMEM);

    return 0;

}


static int usb_net_handle_statusin(USBNetState *s, USBPacket *p)

{

    int ret = 8;

    if (p->len < 8)

        return USB_RET_STALL;

    ((le32 *) p->data)[0] = cpu_to_le32(1);

    ((le32 *) p->data)[1] = cpu_to_le32(0);

    if (!s->rndis_resp.tqh_first)

        ret = USB_RET_NAK;

#ifdef TRAFFIC_DEBUG

    fprintf(stderr, "usbnet: interrupt poll len %u return %d", p->len, ret);

    {

        int i;

        fprintf(stderr, ":");

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

            if (!(i & 15))

                fprintf(stderr, "\n%04x:", i);

            fprintf(stderr, " %02x", p->data[i]);

        }

        fprintf(stderr, "\n\n");

    }

#endif

    return ret;

}


static OutputStream *new_audio_stream(OptionsContext *o, AVFormatContext *oc, int source_index)

{

    int n;

    AVStream *st;

    OutputStream *ost;

    AVCodecContext *audio_enc;

    ost = new_output_stream(o, oc, AVMEDIA_TYPE_AUDIO, source_index);

    st  = ost->st;

    audio_enc = st->codec;

    audio_enc->codec_type = AVMEDIA_TYPE_AUDIO;

    if (!ost->stream_copy) {

        char *sample_fmt = NULL;

        MATCH_PER_STREAM_OPT(audio_channels, i, audio_enc->channels, oc, st);

        MATCH_PER_STREAM_OPT(sample_fmts, str, sample_fmt, oc, st);

        if (sample_fmt &&

            (audio_enc->sample_fmt = av_get_sample_fmt(sample_fmt)) == AV_SAMPLE_FMT_NONE) {

            av_log(NULL, AV_LOG_FATAL, "Invalid sample format '%s'\n", sample_fmt);

            exit_program(1);

        }

        MATCH_PER_STREAM_OPT(audio_sample_rate, i, audio_enc->sample_rate, oc, st);

        ost->rematrix_volume=1.0;

        MATCH_PER_STREAM_OPT(rematrix_volume, f, ost->rematrix_volume, oc, st);

    }

    /* check for channel mapping for this audio stream */

    for (n = 0; n < o->nb_audio_channel_maps; n++) {

        AudioChannelMap *map = &o->audio_channel_maps[n];

        InputStream *ist = input_streams[ost->source_index];

        if ((map->channel_idx == -1 || (ist->file_index == map->file_idx && ist->st->index == map->stream_idx)) &&

            (map->ofile_idx   == -1 || ost->file_index == map->ofile_idx) &&

            (map->ostream_idx == -1 || ost->st->index  == map->ostream_idx)) {

            if (ost->audio_channels_mapped < FF_ARRAY_ELEMS(ost->audio_channels_map))

                ost->audio_channels_map[ost->audio_channels_mapped++] = map->channel_idx;

            else

                av_log(NULL, AV_LOG_FATAL, "Max channel mapping for output %d.%d reached\n",

                       ost->file_index, ost->st->index);

        }

    }

    return ost;

}


static void RENAME(uyvytoyuv422)(uint8_t *ydst, uint8_t *udst, uint8_t *vdst, const uint8_t *src,

                                 int width, int height,

                                 int lumStride, int chromStride, int srcStride)

{

    int y;

    const int chromWidth = FF_CEIL_RSHIFT(width, 1);

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

        RENAME(extract_even)(src+1, ydst, width);

        RENAME(extract_even2)(src, udst, vdst, chromWidth);

        src += srcStride;

        ydst+= lumStride;

        udst+= chromStride;

        vdst+= chromStride;

    }

    __asm__(

            EMMS"       \n\t"

            SFENCE"     \n\t"

            ::: "memory"

        );

}


uint64_t helper_subqv(CPUAlphaState *env, uint64_t op1, uint64_t op2)

{

    uint64_t res;

    res = op1 - op2;

    if (unlikely((op1 ^ op2) & (res ^ op1) & (1ULL << 63))) {

        arith_excp(env, GETPC(), EXC_M_IOV, 0);

    }

    return res;

}


static int decode_idat_chunk(AVCodecContext *avctx, PNGDecContext *s,

                             uint32_t length, AVFrame *p)

{

    int ret;

    size_t byte_depth = s->bit_depth > 8 ? 2 : 1;

    if (!(s->state & PNG_IHDR)) {

        av_log(avctx, AV_LOG_ERROR, "IDAT without IHDR\n");

        return AVERROR_INVALIDDATA;

    }

    if (!(s->state & PNG_IDAT)) {

        /* init image info */

        avctx->width  = s->width;

        avctx->height = s->height;

        s->channels       = ff_png_get_nb_channels(s->color_type);

        s->bits_per_pixel = s->bit_depth * s->channels;

        s->bpp            = (s->bits_per_pixel + 7) >> 3;

        s->row_size       = (s->cur_w * s->bits_per_pixel + 7) >> 3;

        if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&

                s->color_type == PNG_COLOR_TYPE_RGB) {

            avctx->pix_fmt = AV_PIX_FMT_RGB24;

        } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&

                s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {

            avctx->pix_fmt = AV_PIX_FMT_RGBA;

        } else if ((s->bit_depth == 2 || s->bit_depth == 4 || s->bit_depth == 8) &&

                s->color_type == PNG_COLOR_TYPE_GRAY) {

            avctx->pix_fmt = AV_PIX_FMT_GRAY8;

        } else if (s->bit_depth == 16 &&

                s->color_type == PNG_COLOR_TYPE_GRAY) {

            avctx->pix_fmt = AV_PIX_FMT_GRAY16BE;

        } else if (s->bit_depth == 16 &&

                s->color_type == PNG_COLOR_TYPE_RGB) {

            avctx->pix_fmt = AV_PIX_FMT_RGB48BE;

        } else if (s->bit_depth == 16 &&

                s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {

            avctx->pix_fmt = AV_PIX_FMT_RGBA64BE;

        } else if ((s->bits_per_pixel == 1 || s->bits_per_pixel == 2 || s->bits_per_pixel == 4 || s->bits_per_pixel == 8) &&

                s->color_type == PNG_COLOR_TYPE_PALETTE) {

            avctx->pix_fmt = AV_PIX_FMT_PAL8;

        } else if (s->bit_depth == 1 && s->bits_per_pixel == 1 && avctx->codec_id != AV_CODEC_ID_APNG) {

            avctx->pix_fmt = AV_PIX_FMT_MONOBLACK;

        } else if (s->bit_depth == 8 &&

                s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {

            avctx->pix_fmt = AV_PIX_FMT_YA8;

        } else if (s->bit_depth == 16 &&

                s->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {

            avctx->pix_fmt = AV_PIX_FMT_YA16BE;

        } else {

            av_log(avctx, AV_LOG_ERROR, "unsupported bit depth %d "

                    "and color type %d\n",

                    s->bit_depth, s->color_type);

            return AVERROR_INVALIDDATA;

        }

        if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) {

            switch (avctx->pix_fmt) {

            case AV_PIX_FMT_RGB24:

                avctx->pix_fmt = AV_PIX_FMT_RGBA;

                break;

            case AV_PIX_FMT_RGB48BE:

                avctx->pix_fmt = AV_PIX_FMT_RGBA64BE;

                break;

            case AV_PIX_FMT_GRAY8:

                avctx->pix_fmt = AV_PIX_FMT_YA8;

                break;

            case AV_PIX_FMT_GRAY16BE:

                avctx->pix_fmt = AV_PIX_FMT_YA16BE;

                break;

            default:

                avpriv_request_sample(avctx, "bit depth %d "

                        "and color type %d with TRNS",

                        s->bit_depth, s->color_type);

                return AVERROR_INVALIDDATA;

            }

            s->bpp += byte_depth;

        }

        if ((ret = ff_thread_get_buffer(avctx, &s->picture, AV_GET_BUFFER_FLAG_REF)) < 0)

            return ret;

        if (avctx->codec_id == AV_CODEC_ID_APNG && s->last_dispose_op != APNG_DISPOSE_OP_PREVIOUS) {

            ff_thread_release_buffer(avctx, &s->previous_picture);

            if ((ret = ff_thread_get_buffer(avctx, &s->previous_picture, AV_GET_BUFFER_FLAG_REF)) < 0)

                return ret;

        }

        ff_thread_finish_setup(avctx);

        p->pict_type        = AV_PICTURE_TYPE_I;

        p->key_frame        = 1;

        p->interlaced_frame = !!s->interlace_type;

        /* compute the compressed row size */

        if (!s->interlace_type) {

            s->crow_size = s->row_size + 1;

        } else {

            s->pass          = 0;

            s->pass_row_size = ff_png_pass_row_size(s->pass,

                    s->bits_per_pixel,

                    s->cur_w);

            s->crow_size = s->pass_row_size + 1;

        }

        ff_dlog(avctx, "row_size=%d crow_size =%d\n",

                s->row_size, s->crow_size);

        s->image_buf      = p->data[0];

        s->image_linesize = p->linesize[0];

        /* copy the palette if needed */

        if (avctx->pix_fmt == AV_PIX_FMT_PAL8)

            memcpy(p->data[1], s->palette, 256 * sizeof(uint32_t));

        /* empty row is used if differencing to the first row */

        av_fast_padded_mallocz(&s->last_row, &s->last_row_size, s->row_size);

        if (!s->last_row)

            return AVERROR_INVALIDDATA;

        if (s->interlace_type ||

                s->color_type == PNG_COLOR_TYPE_RGB_ALPHA) {

            av_fast_padded_malloc(&s->tmp_row, &s->tmp_row_size, s->row_size);

            if (!s->tmp_row)

                return AVERROR_INVALIDDATA;

        }

        /* compressed row */

        av_fast_padded_malloc(&s->buffer, &s->buffer_size, s->row_size + 16);

        if (!s->buffer)

            return AVERROR(ENOMEM);

        /* we want crow_buf+1 to be 16-byte aligned */

        s->crow_buf          = s->buffer + 15;

        s->zstream.avail_out = s->crow_size;

        s->zstream.next_out  = s->crow_buf;

    }

    s->state |= PNG_IDAT;

    /* set image to non-transparent bpp while decompressing */

    if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE)

        s->bpp -= byte_depth;

    ret = png_decode_idat(s, length);

    if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE)

        s->bpp += byte_depth;

    if (ret < 0)

        return ret;

    bytestream2_skip(&s->gb, 4); /* crc */

    return 0;

}


static void qxl_render_update_area_unlocked(PCIQXLDevice *qxl)

{

    VGACommonState *vga = &qxl->vga;

    DisplaySurface *surface;

    int i;

    if (qxl->guest_primary.resized) {

        qxl->guest_primary.resized = 0;

        qxl->guest_primary.data = qxl_phys2virt(qxl,

                                                qxl->guest_primary.surface.mem,

                                                MEMSLOT_GROUP_GUEST);

        if (!qxl->guest_primary.data) {

            return;

        }

        qxl_set_rect_to_surface(qxl, &qxl->dirty[0]);

        qxl->num_dirty_rects = 1;

        trace_qxl_render_guest_primary_resized(

               qxl->guest_primary.surface.width,

               qxl->guest_primary.surface.height,

               qxl->guest_primary.qxl_stride,

               qxl->guest_primary.bytes_pp,

               qxl->guest_primary.bits_pp);

        if (qxl->guest_primary.qxl_stride > 0) {

            surface = qemu_create_displaysurface_from

                (qxl->guest_primary.surface.width,

                 qxl->guest_primary.surface.height,

                 qxl->guest_primary.bits_pp,

                 qxl->guest_primary.abs_stride,

                 qxl->guest_primary.data,

                 false);

        } else {

            surface = qemu_create_displaysurface

                (qxl->guest_primary.surface.width,

                 qxl->guest_primary.surface.height);

        }

        dpy_gfx_replace_surface(vga->con, surface);

    }

    if (!qxl->guest_primary.data) {

        return;

    }

    for (i = 0; i < qxl->num_dirty_rects; i++) {

        if (qemu_spice_rect_is_empty(qxl->dirty+i)) {

            break;

        }

        if (qxl->dirty[i].left > qxl->dirty[i].right ||

            qxl->dirty[i].top > qxl->dirty[i].bottom ||

            qxl->dirty[i].right > qxl->guest_primary.surface.width ||

            qxl->dirty[i].bottom > qxl->guest_primary.surface.height) {

            continue;

        }

        qxl_blit(qxl, qxl->dirty+i);

        dpy_gfx_update(vga->con,

                       qxl->dirty[i].left, qxl->dirty[i].top,

                       qxl->dirty[i].right - qxl->dirty[i].left,

                       qxl->dirty[i].bottom - qxl->dirty[i].top);

    }

    qxl->num_dirty_rects = 0;

}


void vga_common_init(VGAState *s, DisplayState *ds, uint8_t *vga_ram_base,

                     ram_addr_t vga_ram_offset, int vga_ram_size)

{

    int i, j, v, b;

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

        v = 0;

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

            v |= ((i >> j) & 1) << (j * 4);

        }

        expand4[i] = v;

        v = 0;

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

            v |= ((i >> (2 * j)) & 3) << (j * 4);

        }

        expand2[i] = v;

    }

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

        v = 0;

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

            b = ((i >> j) & 1);

            v |= b << (2 * j);

            v |= b << (2 * j + 1);

        }

        expand4to8[i] = v;

    }

    s->vram_ptr = vga_ram_base;

    s->vram_offset = vga_ram_offset;

    s->vram_size = vga_ram_size;

    s->ds = ds;

    s->get_bpp = vga_get_bpp;

    s->get_offsets = vga_get_offsets;

    s->get_resolution = vga_get_resolution;

    s->update = vga_update_display;

    s->invalidate = vga_invalidate_display;

    s->screen_dump = vga_screen_dump;

    s->text_update = vga_update_text;

    switch (vga_retrace_method) {

    case VGA_RETRACE_DUMB:

        s->retrace = vga_dumb_retrace;

        s->update_retrace_info = vga_dumb_update_retrace_info;

        break;

    case VGA_RETRACE_PRECISE:

        s->retrace = vga_precise_retrace;

        s->update_retrace_info = vga_precise_update_retrace_info;

        break;

    }

    qemu_register_reset(vga_reset, s);

    vga_reset(s);

}


static int rtp_parse_packet_internal(RTPDemuxContext *s, AVPacket *pkt,

                                     const uint8_t *buf, int len)

{

    unsigned int ssrc, h;

    int payload_type, seq, ret, flags = 0;

    int ext;

    AVStream *st;

    uint32_t timestamp;

    int rv = 0;

    ext          = buf[0] & 0x10;

    payload_type = buf[1] & 0x7f;

    if (buf[1] & 0x80)

        flags |= RTP_FLAG_MARKER;

    seq       = AV_RB16(buf + 2);

    timestamp = AV_RB32(buf + 4);

    ssrc      = AV_RB32(buf + 8);

    /* store the ssrc in the RTPDemuxContext */

    s->ssrc = ssrc;

    /* NOTE: we can handle only one payload type */

    if (s->payload_type != payload_type)

        return -1;

    st = s->st;

    // only do something with this if all the rtp checks pass...

    if (!rtp_valid_packet_in_sequence(&s->statistics, seq)) {

        av_log(st ? st->codec : NULL, AV_LOG_ERROR,

               "RTP: PT=%02x: bad cseq %04x expected=%04x\n",

               payload_type, seq, ((s->seq + 1) & 0xffff));

        return -1;

    }

    if (buf[0] & 0x20) {

        int padding = buf[len - 1];

        if (len >= 12 + padding)

            len -= padding;

    }

    s->seq = seq;

    len   -= 12;

    buf   += 12;

    /* RFC 3550 Section 5.3.1 RTP Header Extension handling */

    if (ext) {

        if (len < 4)

            return -1;

        /* calculate the header extension length (stored as number

         * of 32-bit words) */

        ext = (AV_RB16(buf + 2) + 1) << 2;

        if (len < ext)

            return -1;

        // skip past RTP header extension

        len -= ext;

        buf += ext;

    }

    if (!st) {

        /* specific MPEG2-TS demux support */

        ret = ff_mpegts_parse_packet(s->ts, pkt, buf, len);

        /* The only error that can be returned from ff_mpegts_parse_packet

         * is "no more data to return from the provided buffer", so return

         * AVERROR(EAGAIN) for all errors */

        if (ret < 0)

            return AVERROR(EAGAIN);

        if (ret < len) {

            s->read_buf_size = len - ret;

            memcpy(s->buf, buf + ret, s->read_buf_size);

            s->read_buf_index = 0;

            return 1;

        }

        return 0;

    } else if (s->parse_packet) {

        rv = s->parse_packet(s->ic, s->dynamic_protocol_context,

                             s->st, pkt, &timestamp, buf, len, flags);

    } else {

        /* At this point, the RTP header has been stripped;

         * This is ASSUMING that there is only 1 CSRC, which isn't wise. */

        switch (st->codec->codec_id) {

        case AV_CODEC_ID_MP2:

        case AV_CODEC_ID_MP3:

            /* better than nothing: skip MPEG audio RTP header */

            if (len <= 4)

                return -1;

            h    = AV_RB32(buf);

            len -= 4;

            buf += 4;

            av_new_packet(pkt, len);

            memcpy(pkt->data, buf, len);

            break;

        case AV_CODEC_ID_MPEG1VIDEO:

        case AV_CODEC_ID_MPEG2VIDEO:

            /* better than nothing: skip MPEG video RTP header */

            if (len <= 4)

                return -1;

            h    = AV_RB32(buf);

            buf += 4;

            len -= 4;

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

                /* MPEG-2 */

                if (len <= 4)

                    return -1;

                buf += 4;

                len -= 4;

            }

            av_new_packet(pkt, len);

            memcpy(pkt->data, buf, len);

            break;

        default:

            av_new_packet(pkt, len);

            memcpy(pkt->data, buf, len);

            break;

        }

        pkt->stream_index = st->index;

    }

    // now perform timestamp things....

    finalize_packet(s, pkt, timestamp);

    return rv;

}


static int tiff_decode_tag(TiffContext *s, const uint8_t *start, const uint8_t *buf, const uint8_t *end_buf)

{

    int tag, type, count, off, value = 0;

    int i, j;

    uint32_t *pal;

    const uint8_t *rp, *gp, *bp;

    tag = tget_short(&buf, s->le);

    type = tget_short(&buf, s->le);

    count = tget_long(&buf, s->le);

    off = tget_long(&buf, s->le);

    if(count == 1){

        switch(type){

        case TIFF_BYTE:

        case TIFF_SHORT:

            buf -= 4;

            value = tget(&buf, type, s->le);

            buf = NULL;

            break;

        case TIFF_LONG:

            value = off;

            buf = NULL;

            break;

        case TIFF_STRING:

            if(count <= 4){

                buf -= 4;

                break;

            }

        default:

            value = -1;

            buf = start + off;

        }

    }else if(type_sizes[type] * count <= 4){

        buf -= 4;

    }else{

        buf = start + off;

    }

    if(buf && (buf < start || buf > end_buf)){

        av_log(s->avctx, AV_LOG_ERROR, "Tag referencing position outside the image\n");

        return -1;

    }

    switch(tag){

    case TIFF_WIDTH:

        s->width = value;

        break;

    case TIFF_HEIGHT:

        s->height = value;

        break;

    case TIFF_BPP:

        if(count == 1) s->bpp = value;

        else{

            switch(type){

            case TIFF_BYTE:

                s->bpp = (off & 0xFF) + ((off >> 8) & 0xFF) + ((off >> 16) & 0xFF) + ((off >> 24) & 0xFF);

                break;

            case TIFF_SHORT:

            case TIFF_LONG:

                s->bpp = 0;

                for(i = 0; i < count; i++) s->bpp += tget(&buf, type, s->le);

                break;

            default:

                s->bpp = -1;

            }

        }

        if(count > 4){

            av_log(s->avctx, AV_LOG_ERROR, "This format is not supported (bpp=%d, %d components)\n", s->bpp, count);

            return -1;

        }

        switch(s->bpp*10 + count){

        case 11:

            s->avctx->pix_fmt = PIX_FMT_MONOBLACK;

            break;

        case 81:

            s->avctx->pix_fmt = PIX_FMT_PAL8;

            break;

        case 243:

            s->avctx->pix_fmt = PIX_FMT_RGB24;

            break;

        case 161:

            s->avctx->pix_fmt = PIX_FMT_GRAY16BE;

            break;

        case 324:

            s->avctx->pix_fmt = PIX_FMT_RGBA;

            break;

        case 483:

            s->avctx->pix_fmt = s->le ? PIX_FMT_RGB48LE : PIX_FMT_RGB48BE;

            break;

        default:

            av_log(s->avctx, AV_LOG_ERROR, "This format is not supported (bpp=%d, %d components)\n", s->bpp, count);

            return -1;

        }

        if(s->width != s->avctx->width || s->height != s->avctx->height){

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

                return -1;

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

        }

        if(s->picture.data[0])

            s->avctx->release_buffer(s->avctx, &s->picture);

        if(s->avctx->get_buffer(s->avctx, &s->picture) < 0){

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

            return -1;

        }

        if(s->bpp == 8){

            /* make default grayscale pal */

            pal = (uint32_t *) s->picture.data[1];

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

                pal[i] = i * 0x010101;

        }

        break;

    case TIFF_COMPR:

        s->compr = value;

        s->predictor = 0;

        switch(s->compr){

        case TIFF_RAW:

        case TIFF_PACKBITS:

        case TIFF_LZW:

        case TIFF_CCITT_RLE:

            break;

        case TIFF_G3:

        case TIFF_G4:

            s->fax_opts = 0;

            break;

        case TIFF_DEFLATE:

        case TIFF_ADOBE_DEFLATE:

#if CONFIG_ZLIB

            break;

#else

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

            return -1;

#endif

        case TIFF_JPEG:

        case TIFF_NEWJPEG:

            av_log(s->avctx, AV_LOG_ERROR, "JPEG compression is not supported\n");

            return -1;

        default:

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

            return -1;

        }

        break;

    case TIFF_ROWSPERSTRIP:

        if(type == TIFF_LONG && value == -1)

            value = s->avctx->height;

        if(value < 1){

            av_log(s->avctx, AV_LOG_ERROR, "Incorrect value of rows per strip\n");

            return -1;

        }

        s->rps = value;

        break;

    case TIFF_STRIP_OFFS:

        if(count == 1){

            s->stripdata = NULL;

            s->stripoff = value;

        }else

            s->stripdata = start + off;

        s->strips = count;

        if(s->strips == 1) s->rps = s->height;

        s->sot = type;

        if(s->stripdata > end_buf){

            av_log(s->avctx, AV_LOG_ERROR, "Tag referencing position outside the image\n");

            return -1;

        }

        break;

    case TIFF_STRIP_SIZE:

        if(count == 1){

            s->stripsizes = NULL;

            s->stripsize = value;

            s->strips = 1;

        }else{

            s->stripsizes = start + off;

        }

        s->strips = count;

        s->sstype = type;

        if(s->stripsizes > end_buf){

            av_log(s->avctx, AV_LOG_ERROR, "Tag referencing position outside the image\n");

            return -1;

        }

        break;

    case TIFF_PREDICTOR:

        s->predictor = value;

        break;

    case TIFF_INVERT:

        switch(value){

        case 0:

            s->invert = 1;

            break;

        case 1:

            s->invert = 0;

            break;

        case 2:

        case 3:

            break;

        default:

            av_log(s->avctx, AV_LOG_ERROR, "Color mode %d is not supported\n", value);

            return -1;

        }

        break;

    case TIFF_FILL_ORDER:

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

            av_log(s->avctx, AV_LOG_ERROR, "Unknown FillOrder value %d, trying default one\n", value);

            value = 1;

        }

        s->fill_order = value - 1;

        break;

    case TIFF_PAL:

        if(s->avctx->pix_fmt != PIX_FMT_PAL8){

            av_log(s->avctx, AV_LOG_ERROR, "Palette met but this is not palettized format\n");

            return -1;

        }

        pal = (uint32_t *) s->picture.data[1];

        off = type_sizes[type];

        rp = buf;

        gp = buf + count / 3 * off;

        bp = buf + count / 3 * off * 2;

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

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

            j = (tget(&rp, type, s->le) >> off) << 16;

            j |= (tget(&gp, type, s->le) >> off) << 8;

            j |= tget(&bp, type, s->le) >> off;

            pal[i] = j;

        }

        break;

    case TIFF_PLANAR:

        if(value == 2){

            av_log(s->avctx, AV_LOG_ERROR, "Planar format is not supported\n");

            return -1;

        }

        break;

    case TIFF_T4OPTIONS:

        if(s->compr == TIFF_G3)

            s->fax_opts = value;

        break;

    case TIFF_T6OPTIONS:

        if(s->compr == TIFF_G4)

            s->fax_opts = value;

        break;

    }

    return 0;

}


static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
                      Error **errp)
{
    BDRVQcowState *s = bs->opaque;
    int len, i, ret = 0;
    QCowHeader header;
    QemuOpts *opts;
    Error *local_err = NULL;
    uint64_t ext_end;
    uint64_t l1_vm_state_index;
    const char *opt_overlap_check;
    int overlap_check_template = 0;
    ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
    if (ret < 0) {
        error_setg_errno(errp, -ret, "Could not read qcow2 header");
    be32_to_cpus(&header.magic);
    be32_to_cpus(&header.version);
    be64_to_cpus(&header.backing_file_offset);
    be32_to_cpus(&header.backing_file_size);
    be64_to_cpus(&header.size);
    be32_to_cpus(&header.cluster_bits);
    be32_to_cpus(&header.crypt_method);
    be64_to_cpus(&header.l1_table_offset);
    be32_to_cpus(&header.l1_size);
    be64_to_cpus(&header.refcount_table_offset);
    be32_to_cpus(&header.refcount_table_clusters);
    be64_to_cpus(&header.snapshots_offset);
    be32_to_cpus(&header.nb_snapshots);
    if (header.magic != QCOW_MAGIC) {
        error_setg(errp, "Image is not in qcow2 format");
    if (header.version < 2 || header.version > 3) {
        report_unsupported(bs, errp, "QCOW version %d", header.version);
        ret = -ENOTSUP;
    s->qcow_version = header.version;
    /* Initialise cluster size */
    if (header.cluster_bits < MIN_CLUSTER_BITS ||
        header.cluster_bits > MAX_CLUSTER_BITS) {
        error_setg(errp, "Unsupported cluster size: 2^%i", header.cluster_bits);
    s->cluster_bits = header.cluster_bits;
    s->cluster_size = 1 << s->cluster_bits;
    s->cluster_sectors = 1 << (s->cluster_bits - 9);
    /* Initialise version 3 header fields */
    if (header.version == 2) {
        header.incompatible_features    = 0;
        header.compatible_features      = 0;
        header.autoclear_features       = 0;
        header.refcount_order           = 4;
        header.header_length            = 72;
    } else {
        be64_to_cpus(&header.incompatible_features);
        be64_to_cpus(&header.compatible_features);
        be64_to_cpus(&header.autoclear_features);
        be32_to_cpus(&header.refcount_order);
        be32_to_cpus(&header.header_length);
        if (header.header_length < 104) {
            error_setg(errp, "qcow2 header too short");
    if (header.header_length > s->cluster_size) {
        error_setg(errp, "qcow2 header exceeds cluster size");
    if (header.header_length > sizeof(header)) {
        s->unknown_header_fields_size = header.header_length - sizeof(header);
        s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
        ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
                         s->unknown_header_fields_size);
        if (ret < 0) {
            error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
                             "fields");
    if (header.backing_file_offset) {
        ext_end = header.backing_file_offset;
    } else {
        ext_end = 1 << header.cluster_bits;
    /* Handle feature bits */
    s->incompatible_features    = header.incompatible_features;
    s->compatible_features      = header.compatible_features;
    s->autoclear_features       = header.autoclear_features;
    if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
        void *feature_table = NULL;
        qcow2_read_extensions(bs, header.header_length, ext_end,
                              &feature_table, NULL);
        report_unsupported_feature(bs, errp, feature_table,
                                   s->incompatible_features &
                                   ~QCOW2_INCOMPAT_MASK);
        ret = -ENOTSUP;
        g_free(feature_table);
    if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
        /* Corrupt images may not be written to unless they are being repaired
         */
        if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
            error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
                       "read/write");
            ret = -EACCES;
    /* Check support for various header values */
    if (header.refcount_order != 4) {
        report_unsupported(bs, errp, "%d bit reference counts",
                           1 << header.refcount_order);
        ret = -ENOTSUP;
    s->refcount_order = header.refcount_order;
    if (header.crypt_method > QCOW_CRYPT_AES) {
        error_setg(errp, "Unsupported encryption method: %i",
                   header.crypt_method);
    s->crypt_method_header = header.crypt_method;
    if (s->crypt_method_header) {
        bs->encrypted = 1;
    s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
    s->l2_size = 1 << s->l2_bits;
    bs->total_sectors = header.size / 512;
    s->csize_shift = (62 - (s->cluster_bits - 8));
    s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
    s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
    s->refcount_table_offset = header.refcount_table_offset;
    s->refcount_table_size =
        header.refcount_table_clusters << (s->cluster_bits - 3);
    s->snapshots_offset = header.snapshots_offset;
    s->nb_snapshots = header.nb_snapshots;
    /* read the level 1 table */
    s->l1_size = header.l1_size;
    l1_vm_state_index = size_to_l1(s, header.size);
    if (l1_vm_state_index > INT_MAX) {
        error_setg(errp, "Image is too big");
        ret = -EFBIG;
    s->l1_vm_state_index = l1_vm_state_index;
    /* the L1 table must contain at least enough entries to put
       header.size bytes */
    if (s->l1_size < s->l1_vm_state_index) {
        error_setg(errp, "L1 table is too small");
    s->l1_table_offset = header.l1_table_offset;
    if (s->l1_size > 0) {
        s->l1_table = g_malloc0(
            align_offset(s->l1_size * sizeof(uint64_t), 512));
        ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
                         s->l1_size * sizeof(uint64_t));
        if (ret < 0) {
            error_setg_errno(errp, -ret, "Could not read L1 table");
        for(i = 0;i < s->l1_size; i++) {
            be64_to_cpus(&s->l1_table[i]);
    /* alloc L2 table/refcount block cache */
    s->l2_table_cache = qcow2_cache_create(bs, L2_CACHE_SIZE);
    s->refcount_block_cache = qcow2_cache_create(bs, REFCOUNT_CACHE_SIZE);
    s->cluster_cache = g_malloc(s->cluster_size);
    /* one more sector for decompressed data alignment */
    s->cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
                                  + 512);
    s->cluster_cache_offset = -1;
    s->flags = flags;
    ret = qcow2_refcount_init(bs);
    if (ret != 0) {
        error_setg_errno(errp, -ret, "Could not initialize refcount handling");
    QLIST_INIT(&s->cluster_allocs);
    QTAILQ_INIT(&s->discards);
    /* read qcow2 extensions */
    if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
        &local_err)) {
        error_propagate(errp, local_err);
    /* read the backing file name */
    if (header.backing_file_offset != 0) {
        len = header.backing_file_size;
        if (len > 1023) {
            len = 1023;
        ret = bdrv_pread(bs->file, header.backing_file_offset,
                         bs->backing_file, len);
        if (ret < 0) {
            error_setg_errno(errp, -ret, "Could not read backing file name");
        bs->backing_file[len] = '\0';
    ret = qcow2_read_snapshots(bs);
    if (ret < 0) {
        error_setg_errno(errp, -ret, "Could not read snapshots");
    /* Clear unknown autoclear feature bits */
    if (!bs->read_only && !(flags & BDRV_O_INCOMING) && s->autoclear_features) {
        s->autoclear_features = 0;
        ret = qcow2_update_header(bs);
        if (ret < 0) {
            error_setg_errno(errp, -ret, "Could not update qcow2 header");
    /* Initialise locks */
    qemu_co_mutex_init(&s->lock);
    /* Repair image if dirty */
    if (!(flags & (BDRV_O_CHECK | BDRV_O_INCOMING)) && !bs->read_only &&
        (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
        BdrvCheckResult result = {0};
        ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS);
        if (ret < 0) {
            error_setg_errno(errp, -ret, "Could not repair dirty image");
    /* Enable lazy_refcounts according to image and command line options */
    opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
    qemu_opts_absorb_qdict(opts, options, &local_err);
    if (local_err) {
        error_propagate(errp, local_err);
    s->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
        (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
    s->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
    s->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
    s->discard_passthrough[QCOW2_DISCARD_REQUEST] =
        qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
                          flags & BDRV_O_UNMAP);
    s->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
        qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
    s->discard_passthrough[QCOW2_DISCARD_OTHER] =
        qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
    opt_overlap_check = qemu_opt_get(opts, "overlap-check") ?: "cached";
    if (!strcmp(opt_overlap_check, "none")) {
        overlap_check_template = 0;
    } else if (!strcmp(opt_overlap_check, "constant")) {
        overlap_check_template = QCOW2_OL_CONSTANT;
    } else if (!strcmp(opt_overlap_check, "cached")) {
        overlap_check_template = QCOW2_OL_CACHED;
    } else if (!strcmp(opt_overlap_check, "all")) {
        overlap_check_template = QCOW2_OL_ALL;
    } else {
        error_setg(errp, "Unsupported value '%s' for qcow2 option "
                   "'overlap-check'. Allowed are either of the following: "
                   "none, constant, cached, all", opt_overlap_check);
        qemu_opts_del(opts);
    s->overlap_check = 0;
    for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
        /* overlap-check defines a template bitmask, but every flag may be
         * overwritten through the associated boolean option */
        s->overlap_check |=
            qemu_opt_get_bool(opts, overlap_bool_option_names[i],
                              overlap_check_template & (1 << i)) << i;
    qemu_opts_del(opts);
    if (s->use_lazy_refcounts && s->qcow_version < 3) {
        error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
                   "qemu 1.1 compatibility level");
#ifdef DEBUG_ALLOC
    {
        BdrvCheckResult result = {0};
        qcow2_check_refcounts(bs, &result, 0);
#endif
    return ret;
 fail:
    g_free(s->unknown_header_fields);
    cleanup_unknown_header_ext(bs);
    qcow2_free_snapshots(bs);
    qcow2_refcount_close(bs);
    g_free(s->l1_table);
    /* else pre-write overlap checks in cache_destroy may crash */
    s->l1_table = NULL;
    if (s->l2_table_cache) {
        qcow2_cache_destroy(bs, s->l2_table_cache);
    if (s->refcount_block_cache) {
        qcow2_cache_destroy(bs, s->refcount_block_cache);
    g_free(s->cluster_cache);
    qemu_vfree(s->cluster_data);
    return ret;


static void ape_unpack_mono(APEContext *ctx, int count)

{

    if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {

        /* We are pure silence, so we're done. */

        av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence mono\n");

        return;

    }

    entropy_decode(ctx, count, 0);

    ape_apply_filters(ctx, ctx->decoded[0], NULL, count);

    /* Now apply the predictor decoding */

    predictor_decode_mono(ctx, count);

    /* Pseudo-stereo - just copy left channel to right channel */

    if (ctx->channels == 2) {

        memcpy(ctx->decoded[1], ctx->decoded[0], count * sizeof(*ctx->decoded[1]));

    }

}


static int _do_bit_allocation(AC3DecodeContext *ctx, int chnl)

{

    ac3_audio_block *ab = &ctx->audio_block;

    int16_t sdecay, fdecay, sgain, dbknee, floor;

    int16_t lowcomp, fgain, snroffset, fastleak, slowleak;

    int16_t psd[256], bndpsd[50], excite[50], mask[50], delta;

    uint8_t start, end, bin, i, j, k, lastbin, bndstrt, bndend, begin, deltnseg, band, seg, address;

    uint8_t fscod = ctx->sync_info.fscod;

    uint8_t *exps, *deltoffst, *deltlen, *deltba;

    uint8_t *baps;

    int do_delta = 0;

    /* initialization */

    sdecay = sdecaytab[ab->sdcycod];

    fdecay = fdecaytab[ab->fdcycod];

    sgain = sgaintab[ab->sgaincod];

    dbknee = dbkneetab[ab->dbpbcod];

    floor = floortab[ab->floorcod];

    if (chnl == 5) {

        start = ab->cplstrtmant;

        end = ab->cplendmant;

        fgain = fgaintab[ab->cplfgaincod];

        snroffset = (((ab->csnroffst - 15) << 4) + ab->cplfsnroffst) << 2;

        fastleak = (ab->cplfleak << 8) + 768;

        slowleak = (ab->cplsleak << 8) + 768;

        exps = ab->dcplexps;

        baps = ab->cplbap;

        if (ab->cpldeltbae == 0 || ab->cpldeltbae == 1) {

            do_delta = 1;

            deltnseg = ab->cpldeltnseg;

            deltoffst = ab->cpldeltoffst;

            deltlen = ab->cpldeltlen;

            deltba = ab->cpldeltba;

        }

    }

    else if (chnl == 6) {

        start = 0;

        end = 7;

        lowcomp = 0;

        fgain = fgaintab[ab->lfefgaincod];

        snroffset = (((ab->csnroffst - 15) << 4) + ab->lfefsnroffst) << 2;

        exps = ab->dlfeexps;

        baps = ab->lfebap;

    }

    else {

        start = 0;

        end = ab->endmant[chnl];

        lowcomp = 0;

        fgain = fgaintab[ab->fgaincod[chnl]];

        snroffset = (((ab->csnroffst - 15) << 4) + ab->fsnroffst[chnl]) << 2;

        exps = ab->dexps[chnl];

        baps = ab->bap[chnl];

        if (ab->deltbae[chnl] == 0 || ab->deltbae[chnl] == 1) {

            do_delta = 1;

            deltnseg = ab->deltnseg[chnl];

            deltoffst = ab->deltoffst[chnl];

            deltlen = ab->deltlen[chnl];

            deltba = ab->deltba[chnl];

        }

    }

    for (bin = start; bin < end; bin++) /* exponent mapping into psd */

        psd[bin] = (3072 - ((int16_t) (exps[bin] << 7)));

    /* psd integration */

    j = start;

    k = masktab[start];

    do {

        lastbin = FFMIN(bndtab[k] + bndsz[k], end);

        bndpsd[k] = psd[j];

        j++;

        for (i = j; i < lastbin; i++) {

            bndpsd[k] = logadd(bndpsd[k], psd[j]);

            j++;

        }

        k++;

    } while (end > lastbin);

    /* compute the excite function */

    bndstrt = masktab[start];

    bndend = masktab[end - 1] + 1;

    if (bndstrt == 0) {

        lowcomp = calc_lowcomp(lowcomp, bndpsd[0], bndpsd[1], 0);

        excite[0] = bndpsd[0] - fgain - lowcomp;

        lowcomp = calc_lowcomp(lowcomp, bndpsd[1], bndpsd[2], 1);

        excite[1] = bndpsd[1] - fgain - lowcomp;

        begin = 7;

        for (bin = 2; bin < 7; bin++) {

            if (bndend != 7 || bin != 6)

                lowcomp = calc_lowcomp(lowcomp, bndpsd[bin], bndpsd[bin + 1], bin);

            fastleak = bndpsd[bin] - fgain;

            slowleak = bndpsd[bin] - sgain;

            excite[bin] = fastleak - lowcomp;

            if (bndend != 7 || bin != 6)

                if (bndpsd[bin] <= bndpsd[bin + 1]) {

                    begin = bin + 1;

                    break;

                }

        }

        for (bin = begin; bin < (FFMIN(bndend, 22)); bin++) {

            if (bndend != 7 || bin != 6)

                lowcomp = calc_lowcomp(lowcomp, bndpsd[bin], bndpsd[bin + 1], bin);

            fastleak -= fdecay;

            fastleak = FFMAX(fastleak, bndpsd[bin] - fgain);

            slowleak -= sdecay;

            slowleak = FFMAX(slowleak, bndpsd[bin] - sgain);

            excite[bin] = FFMAX(fastleak - lowcomp, slowleak);

        }

        begin = 22;

    }

    else {

        begin = bndstrt;

    }

    for (bin = begin; bin < bndend; bin++) {

        fastleak -= fdecay;

        fastleak = FFMAX(fastleak, bndpsd[bin] - fgain);

        slowleak -= sdecay;

        slowleak = FFMAX(slowleak, bndpsd[bin] - sgain);

        excite[bin] = FFMAX(fastleak, slowleak);

    }

    /* compute the masking curve */

    for (bin = bndstrt; bin < bndend; bin++) {

        if (bndpsd[bin] < dbknee)

            excite[bin] += ((dbknee - bndpsd[bin]) >> 2);

        mask[bin] = FFMAX(excite[bin], hth[bin][fscod]);

    }

    /* apply the delta bit allocation */

    if (do_delta) {

        band = 0;

        for (seg = 0; seg < deltnseg + 1; seg++) {

            band += deltoffst[seg];

            if (deltba[seg] >= 4)

                delta = (deltba[seg] - 3) << 7;

            else

                delta = (deltba[seg] - 4) << 7;

            for (k = 0; k < deltlen[seg]; k++) {

                mask[band] += delta;

                band++;

            }

        }

    }

    /*compute the bit allocation */

    i = start;

    j = masktab[start];

    do {

        lastbin = FFMIN(bndtab[j] + bndsz[j], end);

        mask[j] -= snroffset;

        mask[j] -= floor;

        if (mask[j] < 0)

            mask[j] = 0;

        mask[j] &= 0x1fe0;

        mask[j] += floor;

        for (k = i; k < lastbin; k++) {

            address = (psd[i] - mask[j]) >> 5;

            address = FFMIN(63, (FFMAX(0, address)));

            baps[i] = baptab[address];

            i++;

        }

        j++;

    } while (end > lastbin);

    return 0;

}


struct omap_mcspi_s *omap_mcspi_init(struct omap_target_agent_s *ta, int chnum,

                qemu_irq irq, qemu_irq *drq, omap_clk fclk, omap_clk iclk)

{

    struct omap_mcspi_s *s = (struct omap_mcspi_s *)

            g_malloc0(sizeof(struct omap_mcspi_s));

    struct omap_mcspi_ch_s *ch = s->ch;

    s->irq = irq;

    s->chnum = chnum;

    while (chnum --) {

        ch->txdrq = *drq ++;

        ch->rxdrq = *drq ++;

        ch ++;

    }

    omap_mcspi_reset(s);

    memory_region_init_io(&s->iomem, NULL, &omap_mcspi_ops, s, "omap.mcspi",

                          omap_l4_region_size(ta, 0));

    omap_l4_attach(ta, 0, &s->iomem);

    return s;

}


int pci_vga_init(PCIBus *bus,

                 unsigned long vga_bios_offset, int vga_bios_size)

{

    PCIDevice *dev;

    dev = pci_create(bus, -1, "VGA");

    qdev_prop_set_uint32(&dev->qdev, "bios-offset", vga_bios_offset);

    qdev_prop_set_uint32(&dev->qdev, "bios-size", vga_bios_offset);

    qdev_init(&dev->qdev);

    return 0;

}


void vm_start(void)

{

    RunState requested;

    qemu_vmstop_requested(&requested);

    if (runstate_is_running() && requested == RUN_STATE__MAX) {

        return;

    }

    /* Ensure that a STOP/RESUME pair of events is emitted if a

     * vmstop request was pending.  The BLOCK_IO_ERROR event, for

     * example, according to documentation is always followed by

     * the STOP event.

     */

    if (runstate_is_running()) {

        qapi_event_send_stop(&error_abort);

    } else {

        cpu_enable_ticks();

        runstate_set(RUN_STATE_RUNNING);

        vm_state_notify(1, RUN_STATE_RUNNING);

        resume_all_vcpus();

    }

    qapi_event_send_resume(&error_abort);

}


static inline void RENAME(rgb32tobgr32)(const uint8_t *src, uint8_t *dst, unsigned int src_size)

{

#ifdef HAVE_MMX

/* TODO: unroll this loop */

	asm volatile (

		"xor %%"REG_a", %%"REG_a"	\n\t"

		".balign 16			\n\t"

		"1:				\n\t"

		PREFETCH" 32(%0, %%"REG_a")	\n\t"

		"movq (%0, %%"REG_a"), %%mm0	\n\t"

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

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

		"pslld $16, %%mm0		\n\t"

		"psrld $16, %%mm1		\n\t"

		"pand "MANGLE(mask32r)", %%mm0	\n\t"

		"pand "MANGLE(mask32g)", %%mm2	\n\t"

		"pand "MANGLE(mask32b)", %%mm1	\n\t"

		"por %%mm0, %%mm2		\n\t"

		"por %%mm1, %%mm2		\n\t"

		MOVNTQ" %%mm2, (%1, %%"REG_a")	\n\t"

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

		"cmp %2, %%"REG_a"		\n\t"

		" jb 1b				\n\t"

		:: "r" (src), "r"(dst), "r" ((long)src_size-7)

		: "%"REG_a

	);

	__asm __volatile(SFENCE:::"memory");

	__asm __volatile(EMMS:::"memory");

#else

	unsigned i;

	unsigned num_pixels = src_size >> 2;

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

	{

#ifdef WORDS_BIGENDIAN

	  dst[4*i + 1] = src[4*i + 3];

	  dst[4*i + 2] = src[4*i + 2];

	  dst[4*i + 3] = src[4*i + 1];

#else

	  dst[4*i + 0] = src[4*i + 2];

	  dst[4*i + 1] = src[4*i + 1];

	  dst[4*i + 2] = src[4*i + 0];

#endif

	}

#endif

}


static void v9fs_xattrcreate(void *opaque)

{

    int flags;

    int32_t fid;

    int64_t size;

    ssize_t err = 0;

    V9fsString name;

    size_t offset = 7;

    V9fsFidState *file_fidp;

    V9fsFidState *xattr_fidp;

    V9fsPDU *pdu = opaque;

    V9fsState *s = pdu->s;

    pdu_unmarshal(pdu, offset, "dsqd",

                  &fid, &name, &size, &flags);

    file_fidp = get_fid(pdu, fid);

    if (file_fidp == NULL) {

        err = -EINVAL;

        goto out_nofid;

    }

    /* Make the file fid point to xattr */

    xattr_fidp = file_fidp;

    xattr_fidp->fid_type = P9_FID_XATTR;

    xattr_fidp->fs.xattr.copied_len = 0;

    xattr_fidp->fs.xattr.len = size;

    xattr_fidp->fs.xattr.flags = flags;

    v9fs_string_init(&xattr_fidp->fs.xattr.name);

    v9fs_string_copy(&xattr_fidp->fs.xattr.name, &name);

    if (size) {

        xattr_fidp->fs.xattr.value = g_malloc(size);

    } else {

        xattr_fidp->fs.xattr.value = NULL;

    }

    err = offset;

    put_fid(pdu, file_fidp);

out_nofid:

    complete_pdu(s, pdu, err);

    v9fs_string_free(&name);

}


static void spr_read_sdr1 (void *opaque, int gprn, int sprn)

{

    tcg_gen_ld_tl(cpu_gpr[gprn], cpu_env, offsetof(CPUState, sdr1));

}


void isa_cirrus_vga_init(DisplayState *ds, uint8_t *vga_ram_base,

                         unsigned long vga_ram_offset, int vga_ram_size)

{

    CirrusVGAState *s;

    s = qemu_mallocz(sizeof(CirrusVGAState));

    vga_common_init((VGAState *)s,

                    ds, vga_ram_base, vga_ram_offset, vga_ram_size);

    cirrus_init_common(s, CIRRUS_ID_CLGD5430, 0);

    s->console = graphic_console_init(s->ds, s->update, s->invalidate,

                                      s->screen_dump, s->text_update, s);

    /* XXX ISA-LFB support */

}


StringInputVisitor *string_input_visitor_new(const char *str)

{

    StringInputVisitor *v;

    v = g_malloc0(sizeof(*v));

    v->visitor.type = VISITOR_INPUT;

    v->visitor.type_int64 = parse_type_int64;

    v->visitor.type_uint64 = parse_type_uint64;

    v->visitor.type_size = parse_type_size;

    v->visitor.type_bool = parse_type_bool;

    v->visitor.type_str = parse_type_str;

    v->visitor.type_number = parse_type_number;

    v->visitor.start_list = start_list;

    v->visitor.next_list = next_list;

    v->visitor.end_list = end_list;

    v->visitor.optional = parse_optional;

    v->string = str;

    v->head = true;

    return v;

}


void spapr_vio_bus_register_withprop(VIOsPAPRDeviceInfo *info)

{

    info->qdev.init = spapr_vio_busdev_init;

    info->qdev.bus_info = &spapr_vio_bus_info;

    assert(info->qdev.size >= sizeof(VIOsPAPRDevice));

    qdev_register(&info->qdev);

}


static inline void tcg_out_adr(TCGContext *s, TCGReg rd, void *target)

{

    ptrdiff_t offset = tcg_pcrel_diff(s, target);

    assert(offset == sextract64(offset, 0, 21));

    tcg_out_insn(s, 3406, ADR, rd, offset);

}


static int pc_boot_set(void *opaque, const char *boot_device)

{

    return set_boot_dev(opaque, boot_device);

}


static TCGReg tcg_out_tlb_read(TCGContext *s, TCGReg addrlo, TCGReg addrhi,

                               TCGMemOp opc, int mem_index, bool is_load)

{

    TCGReg base = TCG_AREG0;

    int cmp_off =

        (is_load

         ? offsetof(CPUArchState, tlb_table[mem_index][0].addr_read)

         : offsetof(CPUArchState, tlb_table[mem_index][0].addr_write));

    int add_off = offsetof(CPUArchState, tlb_table[mem_index][0].addend);

    unsigned s_bits = opc & MO_SIZE;

    unsigned a_bits = get_alignment_bits(opc);

    /* V7 generates the following:

     *   ubfx   r0, addrlo, #TARGET_PAGE_BITS, #CPU_TLB_BITS

     *   add    r2, env, #high

     *   add    r2, r2, r0, lsl #CPU_TLB_ENTRY_BITS

     *   ldr    r0, [r2, #cmp]

     *   ldr    r2, [r2, #add]

     *   movw   tmp, #page_align_mask

     *   bic    tmp, addrlo, tmp

     *   cmp    r0, tmp

     *

     * Otherwise we generate:

     *   shr    tmp, addrlo, #TARGET_PAGE_BITS

     *   add    r2, env, #high

     *   and    r0, tmp, #(CPU_TLB_SIZE - 1)

     *   add    r2, r2, r0, lsl #CPU_TLB_ENTRY_BITS

     *   ldr    r0, [r2, #cmp]

     *   ldr    r2, [r2, #add]

     *   tst    addrlo, #s_mask

     *   cmpeq  r0, tmp, lsl #TARGET_PAGE_BITS

     */

    if (use_armv7_instructions) {

        tcg_out_extract(s, COND_AL, TCG_REG_R0, addrlo,

                        TARGET_PAGE_BITS, CPU_TLB_BITS);

    } else {

        tcg_out_dat_reg(s, COND_AL, ARITH_MOV, TCG_REG_TMP,

                        0, addrlo, SHIFT_IMM_LSR(TARGET_PAGE_BITS));

    }

    /* We checked that the offset is contained within 16 bits above.  */

    if (add_off > 0xfff || (use_armv6_instructions && cmp_off > 0xff)) {

        tcg_out_dat_imm(s, COND_AL, ARITH_ADD, TCG_REG_R2, base,

                        (24 << 7) | (cmp_off >> 8));

        base = TCG_REG_R2;

        add_off -= cmp_off & 0xff00;

        cmp_off &= 0xff;

    }

    if (!use_armv7_instructions) {

        tcg_out_dat_imm(s, COND_AL, ARITH_AND,

                        TCG_REG_R0, TCG_REG_TMP, CPU_TLB_SIZE - 1);

    }

    tcg_out_dat_reg(s, COND_AL, ARITH_ADD, TCG_REG_R2, base,

                    TCG_REG_R0, SHIFT_IMM_LSL(CPU_TLB_ENTRY_BITS));

    /* Load the tlb comparator.  Use ldrd if needed and available,

       but due to how the pointer needs setting up, ldm isn't useful.

       Base arm5 doesn't have ldrd, but armv5te does.  */

    if (use_armv6_instructions && TARGET_LONG_BITS == 64) {

        tcg_out_ldrd_8(s, COND_AL, TCG_REG_R0, TCG_REG_R2, cmp_off);

    } else {

        tcg_out_ld32_12(s, COND_AL, TCG_REG_R0, TCG_REG_R2, cmp_off);

        if (TARGET_LONG_BITS == 64) {

            tcg_out_ld32_12(s, COND_AL, TCG_REG_R1, TCG_REG_R2, cmp_off + 4);

        }

    }

    /* Load the tlb addend.  */

    tcg_out_ld32_12(s, COND_AL, TCG_REG_R2, TCG_REG_R2, add_off);

    /* Check alignment.  We don't support inline unaligned acceses,

       but we can easily support overalignment checks.  */

    if (a_bits < s_bits) {

        a_bits = s_bits;

    }

    if (use_armv7_instructions) {

        tcg_target_ulong mask = ~(TARGET_PAGE_MASK | ((1 << a_bits) - 1));

        int rot = encode_imm(mask);

        if (rot >= 0) {

            tcg_out_dat_imm(s, COND_AL, ARITH_BIC, TCG_REG_TMP, addrlo,

                            rotl(mask, rot) | (rot << 7));

        } else {

            tcg_out_movi32(s, COND_AL, TCG_REG_TMP, mask);

            tcg_out_dat_reg(s, COND_AL, ARITH_BIC, TCG_REG_TMP,

                            addrlo, TCG_REG_TMP, 0);

        }

        tcg_out_dat_reg(s, COND_AL, ARITH_CMP, 0, TCG_REG_R0, TCG_REG_TMP, 0);

    } else {

        if (a_bits) {

            tcg_out_dat_imm(s, COND_AL, ARITH_TST, 0, addrlo,

                            (1 << a_bits) - 1);

        }

        tcg_out_dat_reg(s, (a_bits ? COND_EQ : COND_AL), ARITH_CMP,

                        0, TCG_REG_R0, TCG_REG_TMP,

                        SHIFT_IMM_LSL(TARGET_PAGE_BITS));

    }

    if (TARGET_LONG_BITS == 64) {

        tcg_out_dat_reg(s, COND_EQ, ARITH_CMP, 0, TCG_REG_R1, addrhi, 0);

    }

    return TCG_REG_R2;

}


static void tcg_opt_gen_movi(TCGContext *s, TCGOp *op, TCGArg *args,

                             TCGArg dst, TCGArg val)

{

    TCGOpcode new_op = op_to_movi(op->opc);

    tcg_target_ulong mask;

    op->opc = new_op;

    reset_temp(dst);

    temps[dst].state = TCG_TEMP_CONST;

    temps[dst].val = val;

    mask = val;

    if (TCG_TARGET_REG_BITS > 32 && new_op == INDEX_op_mov_i32) {

        /* High bits of the destination are now garbage.  */

        mask |= ~0xffffffffull;

    }

    temps[dst].mask = mask;

    args[0] = dst;

    args[1] = val;

}


static int colo_do_checkpoint_transaction(MigrationState *s)

{

    Error *local_err = NULL;

    colo_send_message(s->to_dst_file, COLO_MESSAGE_CHECKPOINT_REQUEST,

                      &local_err);

    if (local_err) {

        goto out;

    }

    colo_receive_check_message(s->rp_state.from_dst_file,

                    COLO_MESSAGE_CHECKPOINT_REPLY, &local_err);

    if (local_err) {

        goto out;

    }

    /* TODO: suspend and save vm state to colo buffer */

    colo_send_message(s->to_dst_file, COLO_MESSAGE_VMSTATE_SEND, &local_err);

    if (local_err) {

        goto out;

    }

    /* TODO: send vmstate to Secondary */

    colo_receive_check_message(s->rp_state.from_dst_file,

                       COLO_MESSAGE_VMSTATE_RECEIVED, &local_err);

    if (local_err) {

        goto out;

    }

    colo_receive_check_message(s->rp_state.from_dst_file,

                       COLO_MESSAGE_VMSTATE_LOADED, &local_err);

    if (local_err) {

        goto out;

    }

    /* TODO: resume Primary */

    return 0;

out:

    if (local_err) {

        error_report_err(local_err);

    }

    return -EINVAL;

}


static int load_ipmovie_packet(IPMVEContext *s, AVIOContext *pb,

    AVPacket *pkt) {

    int chunk_type;

    if (s->audio_chunk_offset && s->audio_channels && s->audio_bits) {

        if (s->audio_type == AV_CODEC_ID_NONE) {

            av_log(s->avf, AV_LOG_ERROR, "Can not read audio packet before"

                   "audio codec is known\n");

                return CHUNK_BAD;

        }

        /* adjust for PCM audio by skipping chunk header */

        if (s->audio_type != AV_CODEC_ID_INTERPLAY_DPCM) {

            s->audio_chunk_offset += 6;

            s->audio_chunk_size -= 6;

        }

        avio_seek(pb, s->audio_chunk_offset, SEEK_SET);

        s->audio_chunk_offset = 0;

        if (s->audio_chunk_size != av_get_packet(pb, pkt, s->audio_chunk_size))

            return CHUNK_EOF;

        pkt->stream_index = s->audio_stream_index;

        pkt->pts = s->audio_frame_count;

        /* audio frame maintenance */

        if (s->audio_type != AV_CODEC_ID_INTERPLAY_DPCM)

            s->audio_frame_count +=

            (s->audio_chunk_size / s->audio_channels / (s->audio_bits / 8));

        else

            s->audio_frame_count +=

                (s->audio_chunk_size - 6 - s->audio_channels) / s->audio_channels;

        av_log(s->avf, AV_LOG_TRACE, "sending audio frame with pts %"PRId64" (%d audio frames)\n",

                pkt->pts, s->audio_frame_count);

        chunk_type = CHUNK_VIDEO;

    } else if (s->decode_map_chunk_offset) {

        /* send both the decode map and the video data together */

        if (av_new_packet(pkt, 2 + s->decode_map_chunk_size + s->video_chunk_size))

            return CHUNK_NOMEM;

        if (s->has_palette) {

            uint8_t *pal;

            pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE,

                                          AVPALETTE_SIZE);

            if (pal) {

                memcpy(pal, s->palette, AVPALETTE_SIZE);

                s->has_palette = 0;

            }

        }

        if (s->changed) {

            ff_add_param_change(pkt, 0, 0, 0, s->video_width, s->video_height);

            s->changed = 0;

        }

        pkt->pos= s->decode_map_chunk_offset;

        avio_seek(pb, s->decode_map_chunk_offset, SEEK_SET);

        s->decode_map_chunk_offset = 0;

        AV_WL16(pkt->data, s->decode_map_chunk_size);

        if (avio_read(pb, pkt->data + 2, s->decode_map_chunk_size) !=

            s->decode_map_chunk_size) {

            av_packet_unref(pkt);

            return CHUNK_EOF;

        }

        avio_seek(pb, s->video_chunk_offset, SEEK_SET);

        s->video_chunk_offset = 0;

        if (avio_read(pb, pkt->data + 2 + s->decode_map_chunk_size,

            s->video_chunk_size) != s->video_chunk_size) {

            av_packet_unref(pkt);

            return CHUNK_EOF;

        }

        pkt->stream_index = s->video_stream_index;

        pkt->pts = s->video_pts;

        av_log(s->avf, AV_LOG_TRACE, "sending video frame with pts %"PRId64"\n", pkt->pts);

        s->video_pts += s->frame_pts_inc;

        chunk_type = CHUNK_VIDEO;

    } else {

        avio_seek(pb, s->next_chunk_offset, SEEK_SET);

        chunk_type = CHUNK_DONE;

    }

    return chunk_type;

}


static void verdex_init(ram_addr_t ram_size, int vga_ram_size,

                const char *boot_device,

                const char *kernel_filename, const char *kernel_cmdline,

                const char *initrd_filename, const char *cpu_model)

{

    struct pxa2xx_state_s *cpu;

    int index;

    uint32_t verdex_rom = 0x02000000;

    uint32_t verdex_ram = 0x10000000;

    if (ram_size < (verdex_ram + verdex_rom + PXA2XX_INTERNAL_SIZE)) {

        fprintf(stderr, "This platform requires %i bytes of memory\n",

                verdex_ram + verdex_rom + PXA2XX_INTERNAL_SIZE);

        exit(1);

    }

    cpu = pxa270_init(verdex_ram, cpu_model ?: "pxa270-c0");

    index = drive_get_index(IF_PFLASH, 0, 0);

    if (index == -1) {

        fprintf(stderr, "A flash image must be given with the "

                "'pflash' parameter\n");

        exit(1);

    }

    if (!pflash_cfi01_register(0x00000000, qemu_ram_alloc(verdex_rom),

            drives_table[index].bdrv, sector_len, verdex_rom / sector_len,

            2, 0, 0, 0, 0)) {

        fprintf(stderr, "qemu: Error registering flash memory.\n");

        exit(1);

    }

    cpu->env->regs[15] = 0x00000000;

    /* Interrupt line of NIC is connected to GPIO line 99 */

    smc91c111_init(&nd_table[0], 0x04000300,

                    pxa2xx_gpio_in_get(cpu->gpio)[99]);

}


void pci_device_save(PCIDevice *s, QEMUFile *f)

{

    int i;

    qemu_put_be32(f, s->version_id); /* PCI device version */

    qemu_put_buffer(f, s->config, 256);

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

        qemu_put_be32(f, s->irq_state[i]);

}


static void qxl_flip(PCIQXLDevice *qxl, QXLRect *rect)

{

    uint8_t *src = qxl->guest_primary.data;

    uint8_t *dst = qxl->guest_primary.flipped;

    int len, i;

    src += (qxl->guest_primary.surface.height - rect->top - 1) *

        qxl->guest_primary.stride;

    dst += rect->top  * qxl->guest_primary.stride;

    src += rect->left * qxl->guest_primary.bytes_pp;

    dst += rect->left * qxl->guest_primary.bytes_pp;

    len  = (rect->right - rect->left) * qxl->guest_primary.bytes_pp;

    for (i = rect->top; i < rect->bottom; i++) {

        memcpy(dst, src, len);

        dst += qxl->guest_primary.stride;

        src -= qxl->guest_primary.stride;

    }

}


START_TEST(qdict_destroy_simple_test)

{

    QDict *qdict;

    qdict = qdict_new();

    qdict_put_obj(qdict, "num", QOBJECT(qint_from_int(0)));

    qdict_put_obj(qdict, "str", QOBJECT(qstring_from_str("foo")));

    QDECREF(qdict);

}


static int pcibus_reset(BusState *qbus)

{

    pci_bus_reset(DO_UPCAST(PCIBus, qbus, qbus));

    /* topology traverse is done by pci_bus_reset().

       Tell qbus/qdev walker not to traverse the tree */

    return 1;

}


int AC3_NAME(encode_frame)(AVCodecContext *avctx, AVPacket *avpkt,

                           const AVFrame *frame, int *got_packet_ptr)

{

    AC3EncodeContext *s = avctx->priv_data;

    int ret;

    if (s->options.allow_per_frame_metadata) {

        ret = ff_ac3_validate_metadata(s);

        if (ret)

            return ret;

    }

    if (s->bit_alloc.sr_code == 1 || s->eac3)

        ff_ac3_adjust_frame_size(s);

    copy_input_samples(s, (SampleType **)frame->extended_data);

    apply_mdct(s);

    if (s->fixed_point)

        scale_coefficients(s);

    clip_coefficients(&s->dsp, s->blocks[0].mdct_coef[1],

                      AC3_MAX_COEFS * s->num_blocks * s->channels);

    s->cpl_on = s->cpl_enabled;

    ff_ac3_compute_coupling_strategy(s);

    if (s->cpl_on)

        apply_channel_coupling(s);

    compute_rematrixing_strategy(s);

    if (!s->fixed_point)

        scale_coefficients(s);

    ff_ac3_apply_rematrixing(s);

    ff_ac3_process_exponents(s);

    ret = ff_ac3_compute_bit_allocation(s);

    if (ret) {

        av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");

        return ret;

    }

    ff_ac3_group_exponents(s);

    ff_ac3_quantize_mantissas(s);

    if ((ret = ff_alloc_packet2(avctx, avpkt, s->frame_size)))

        return ret;

    ff_ac3_output_frame(s, avpkt->data);

    if (frame->pts != AV_NOPTS_VALUE)

        avpkt->pts = frame->pts - ff_samples_to_time_base(avctx, avctx->delay);

    *got_packet_ptr = 1;

    return 0;

}


static int read_channel_params(MLPDecodeContext *m, unsigned int substr,

                               GetBitContext *gbp, unsigned int ch)

{

    ChannelParams *cp = &m->channel_params[ch];

    FilterParams *fir = &cp->filter_params[FIR];

    FilterParams *iir = &cp->filter_params[IIR];

    SubStream *s = &m->substream[substr];

    if (s->param_presence_flags & PARAM_FIR)

        if (get_bits1(gbp))

            if (read_filter_params(m, gbp, ch, FIR) < 0)

                return -1;

    if (s->param_presence_flags & PARAM_IIR)

        if (get_bits1(gbp))

            if (read_filter_params(m, gbp, ch, IIR) < 0)

                return -1;

    if (fir->order && iir->order &&

        fir->shift != iir->shift) {

        av_log(m->avctx, AV_LOG_ERROR,

                "FIR and IIR filters must use the same precision.\n");

        return -1;

    }

    /* The FIR and IIR filters must have the same precision.

        * To simplify the filtering code, only the precision of the

        * FIR filter is considered. If only the IIR filter is employed,

        * the FIR filter precision is set to that of the IIR filter, so

        * that the filtering code can use it. */

    if (!fir->order && iir->order)

        fir->shift = iir->shift;

    if (s->param_presence_flags & PARAM_HUFFOFFSET)

        if (get_bits1(gbp))

            cp->huff_offset = get_sbits(gbp, 15);

    cp->codebook  = get_bits(gbp, 2);

    cp->huff_lsbs = get_bits(gbp, 5);

    cp->sign_huff_offset = calculate_sign_huff(m, substr, ch);

    /* TODO: validate */

    return 0;

}


static int64_t rm_read_dts(AVFormatContext *s, int stream_index,

                               int64_t *ppos, int64_t pos_limit)

{

    RMDemuxContext *rm = s->priv_data;

    int64_t pos, dts;

    int stream_index2, flags, len, h;

    pos = *ppos;

    if(rm->old_format)

        return AV_NOPTS_VALUE;

    avio_seek(s->pb, pos, SEEK_SET);

    rm->remaining_len=0;

    for(;;){

        int seq=1;

        AVStream *st;

        len=sync(s, &dts, &flags, &stream_index2, &pos);

        if(len<0)

            return AV_NOPTS_VALUE;

        st = s->streams[stream_index2];

        if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {

            h= avio_r8(s->pb); len--;

            if(!(h & 0x40)){

                seq = avio_r8(s->pb); len--;

            }

        }

        if((flags&2) && (seq&0x7F) == 1){

//            av_log(s, AV_LOG_DEBUG, "%d %d-%d %"PRId64" %d\n", flags, stream_index2, stream_index, dts, seq);

            av_add_index_entry(st, pos, dts, 0, 0, AVINDEX_KEYFRAME);

            if(stream_index2 == stream_index)

                break;

        }

        avio_skip(s->pb, len);

    }

    *ppos = pos;

    return dts;

}