void ff_id3v2_free_extra_meta(ID3v2ExtraMeta **extra_meta)

{

    ID3v2ExtraMeta *current = *extra_meta, *next;

    void (*free_func)(ID3v2ExtraMeta*);

    while (current) {

        if ((free_func = get_extra_meta_func(current->tag, 1)->free))

            free_func(current->data);

        next = current->next;

        av_freep(&current);

        current = next;

    }

}


static int adb_mouse_request(ADBDevice *d, uint8_t *obuf,

                             const uint8_t *buf, int len)

{

    MouseState *s = ADB_MOUSE(d);

    int cmd, reg, olen;

    if ((buf[0] & 0x0f) == ADB_FLUSH) {

        /* flush mouse fifo */

        s->buttons_state = s->last_buttons_state;

        s->dx = 0;

        s->dy = 0;

        s->dz = 0;

        return 0;

    }

    cmd = buf[0] & 0xc;

    reg = buf[0] & 0x3;

    olen = 0;

    switch(cmd) {

    case ADB_WRITEREG:

        ADB_DPRINTF("write reg %d val 0x%2.2x\n", reg, buf[1]);

        switch(reg) {

        case 2:

            break;

        case 3:

            switch(buf[2]) {

            case ADB_CMD_SELF_TEST:

                break;

            case ADB_CMD_CHANGE_ID:

            case ADB_CMD_CHANGE_ID_AND_ACT:

            case ADB_CMD_CHANGE_ID_AND_ENABLE:

                d->devaddr = buf[1] & 0xf;

                break;

            default:

                d->devaddr = buf[1] & 0xf;

                /* we support handlers:

                 * 0x01: Classic Apple Mouse Protocol / 100 cpi operations

                 * 0x02: Classic Apple Mouse Protocol / 200 cpi operations

                 * we don't support handlers (at least):

                 * 0x03: Mouse systems A3 trackball

                 * 0x04: Extended Apple Mouse Protocol

                 * 0x2f: Microspeed mouse

                 * 0x42: Macally

                 * 0x5f: Microspeed mouse

                 * 0x66: Microspeed mouse

                 */

                if (buf[2] == 1 || buf[2] == 2) {

                    d->handler = buf[2];

                }

                break;

            }

        }

        break;

    case ADB_READREG:

        switch(reg) {

        case 0:

            olen = adb_mouse_poll(d, obuf);

            break;

        case 1:

            break;

        case 3:

            obuf[0] = d->handler;

            obuf[1] = d->devaddr;

            olen = 2;

            break;

        }

        ADB_DPRINTF("read reg %d obuf[0] 0x%2.2x obuf[1] 0x%2.2x\n", reg,

                    obuf[0], obuf[1]);

        break;

    }

    return olen;

}


static int net_init_nic(const NetClientOptions *opts, const char *name,

                        NetClientState *peer, Error **errp)

{

    /* FIXME error_setg(errp, ...) on failure */

    int idx;

    NICInfo *nd;

    const NetLegacyNicOptions *nic;

    assert(opts->kind == NET_CLIENT_OPTIONS_KIND_NIC);

    nic = opts->nic;

    idx = nic_get_free_idx();

    if (idx == -1 || nb_nics >= MAX_NICS) {

        error_report("Too Many NICs");

        return -1;

    }

    nd = &nd_table[idx];

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

    if (nic->has_netdev) {

        nd->netdev = qemu_find_netdev(nic->netdev);

        if (!nd->netdev) {

            error_report("netdev '%s' not found", nic->netdev);

            return -1;

        }

    } else {

        assert(peer);

        nd->netdev = peer;

    }

    nd->name = g_strdup(name);

    if (nic->has_model) {

        nd->model = g_strdup(nic->model);

    }

    if (nic->has_addr) {

        nd->devaddr = g_strdup(nic->addr);

    }

    if (nic->has_macaddr &&

        net_parse_macaddr(nd->macaddr.a, nic->macaddr) < 0) {

        error_report("invalid syntax for ethernet address");

        return -1;

    }

    if (nic->has_macaddr &&

        is_multicast_ether_addr(nd->macaddr.a)) {

        error_report("NIC cannot have multicast MAC address (odd 1st byte)");

        return -1;

    }

    qemu_macaddr_default_if_unset(&nd->macaddr);

    if (nic->has_vectors) {

        if (nic->vectors > 0x7ffffff) {

            error_report("invalid # of vectors: %"PRIu32, nic->vectors);

            return -1;

        }

        nd->nvectors = nic->vectors;

    } else {

        nd->nvectors = DEV_NVECTORS_UNSPECIFIED;

    }

    nd->used = 1;

    nb_nics++;

    return idx;

}


void migrate_del_blocker(Error *reason)

{

    migration_blockers = g_slist_remove(migration_blockers, reason);

}


char *desc_get_buf(DescInfo *info, bool read_only)

{

    PCIDevice *dev = PCI_DEVICE(info->ring->r);

    size_t size = read_only ? le16_to_cpu(info->desc.tlv_size) :

                              le16_to_cpu(info->desc.buf_size);

    if (size > info->buf_size) {

        info->buf = g_realloc(info->buf, size);

        info->buf_size = size;

    }

    if (!info->buf) {

        return NULL;

    }

    pci_dma_read(dev, le64_to_cpu(info->desc.buf_addr), info->buf, size);

    return info->buf;

}


int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,

                  int64_t sector_num, int nb_sectors)

{

    int n1;

    if ((sector_num + nb_sectors) <= bs->total_sectors)

        return nb_sectors;

    if (sector_num >= bs->total_sectors)

        n1 = 0;

    else

        n1 = bs->total_sectors - sector_num;

    qemu_iovec_memset(qiov, 0, 512 * (nb_sectors - n1));

    return n1;

}


void helper_stqf(CPUSPARCState *env, target_ulong addr, int mem_idx)

{

    /* XXX add 128 bit store */

    CPU_QuadU u;

    helper_check_align(env, addr, 7);

#if !defined(CONFIG_USER_ONLY)

    switch (mem_idx) {

    case MMU_USER_IDX:

        u.q = QT0;

        cpu_stq_user(env, addr, u.ll.upper);

        cpu_stq_user(env, addr + 8, u.ll.lower);

        break;

    case MMU_KERNEL_IDX:

        u.q = QT0;

        cpu_stq_kernel(env, addr, u.ll.upper);

        cpu_stq_kernel(env, addr + 8, u.ll.lower);

        break;

#ifdef TARGET_SPARC64

    case MMU_HYPV_IDX:

        u.q = QT0;

        cpu_stq_hypv(env, addr, u.ll.upper);

        cpu_stq_hypv(env, addr + 8, u.ll.lower);

        break;

#endif

    default:

        DPRINTF_MMU("helper_stqf: need to check MMU idx %d\n", mem_idx);

        break;

    }

#else

    u.q = QT0;

    stq_raw(address_mask(env, addr), u.ll.upper);

    stq_raw(address_mask(env, addr + 8), u.ll.lower);

#endif

}


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

{

    uint64_t *v = pv;

    qemu_get_be64s(f, v);

    return 0;

}


static inline void vhost_dev_log_resize(struct vhost_dev* dev, uint64_t size)

{

    vhost_log_chunk_t *log;

    uint64_t log_base;

    int r;

    if (size) {

        log = g_malloc0(size * sizeof *log);

    } else {

        log = NULL;

    }

    log_base = (uint64_t)(unsigned long)log;

    r = ioctl(dev->control, VHOST_SET_LOG_BASE, &log_base);

    assert(r >= 0);

    vhost_client_sync_dirty_bitmap(&dev->client, 0,

                                   (target_phys_addr_t)~0x0ull);

    if (dev->log) {

        g_free(dev->log);

    }

    dev->log = log;

    dev->log_size = size;

}


static void memory_dump(Monitor *mon, int count, int format, int wsize,

                        hwaddr addr, int is_physical)

{

    int l, line_size, i, max_digits, len;

    uint8_t buf[16];

    uint64_t v;

    if (format == 'i') {

        int flags = 0;

#ifdef TARGET_I386

        CPUArchState *env = mon_get_cpu_env();

        if (wsize == 2) {

            flags = 1;

        } else if (wsize == 4) {

            flags = 0;

        } else {

            /* as default we use the current CS size */

            flags = 0;

            if (env) {

#ifdef TARGET_X86_64

                if ((env->efer & MSR_EFER_LMA) &&

                    (env->segs[R_CS].flags & DESC_L_MASK))

                    flags = 2;

                else

#endif

                if (!(env->segs[R_CS].flags & DESC_B_MASK))

                    flags = 1;

            }

        }

#endif

#ifdef TARGET_PPC

        CPUArchState *env = mon_get_cpu_env();

        flags = msr_le << 16;

        flags |= env->bfd_mach;

#endif

        monitor_disas(mon, mon_get_cpu(), addr, count, is_physical, flags);

        return;

    }

    len = wsize * count;

    if (wsize == 1)

        line_size = 8;

    else

        line_size = 16;

    max_digits = 0;

    switch(format) {

    case 'o':

        max_digits = (wsize * 8 + 2) / 3;

        break;

    default:

    case 'x':

        max_digits = (wsize * 8) / 4;

        break;

    case 'u':

    case 'd':

        max_digits = (wsize * 8 * 10 + 32) / 33;

        break;

    case 'c':

        wsize = 1;

        break;

    }

    while (len > 0) {

        if (is_physical)

            monitor_printf(mon, TARGET_FMT_plx ":", addr);

        else

            monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);

        l = len;

        if (l > line_size)

            l = line_size;

        if (is_physical) {

            cpu_physical_memory_read(addr, buf, l);

        } else {

            if (cpu_memory_rw_debug(mon_get_cpu(), addr, buf, l, 0) < 0) {

                monitor_printf(mon, " Cannot access memory\n");

                break;

            }

        }

        i = 0;

        while (i < l) {

            switch(wsize) {

            default:

            case 1:

                v = ldub_p(buf + i);

                break;

            case 2:

                v = lduw_p(buf + i);

                break;

            case 4:

                v = (uint32_t)ldl_p(buf + i);

                break;

            case 8:

                v = ldq_p(buf + i);

                break;

            }

            monitor_printf(mon, " ");

            switch(format) {

            case 'o':

                monitor_printf(mon, "%#*" PRIo64, max_digits, v);

                break;

            case 'x':

                monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);

                break;

            case 'u':

                monitor_printf(mon, "%*" PRIu64, max_digits, v);

                break;

            case 'd':

                monitor_printf(mon, "%*" PRId64, max_digits, v);

                break;

            case 'c':

                monitor_printc(mon, v);

                break;

            }

            i += wsize;

        }

        monitor_printf(mon, "\n");

        addr += l;

        len -= l;

    }

}


static void v9fs_version(void *opaque)
{
    V9fsPDU *pdu = opaque;
    V9fsState *s = pdu->s;
    V9fsString version;
    size_t offset = 7;
    pdu_unmarshal(pdu, offset, "ds", &s->msize, &version);
    trace_v9fs_version(pdu->tag, pdu->id, s->msize, version.data);
    if (!strcmp(version.data, "9P2000.u")) {
        s->proto_version = V9FS_PROTO_2000U;
    } else if (!strcmp(version.data, "9P2000.L")) {
        s->proto_version = V9FS_PROTO_2000L;
    } else {
        v9fs_string_sprintf(&version, "unknown");
    }
    offset += pdu_marshal(pdu, offset, "ds", s->msize, &version);
    complete_pdu(s, pdu, offset);
    v9fs_string_free(&version);
    return;
}


static void core_prop_set_core_id(Object *obj, Visitor *v, const char *name,
                                  void *opaque, Error **errp)
{
    CPUCore *core = CPU_CORE(obj);
    Error *local_err = NULL;
    int64_t value;
    visit_type_int(v, name, &value, &local_err);
    if (local_err) {
        error_propagate(errp, local_err);
    core->core_id = value;


static int flv_read_header(AVFormatContext *s)

{

    int flags;

    FLVContext *flv = s->priv_data;

    int offset;

    avio_skip(s->pb, 4);

    flags = avio_r8(s->pb);

    flv->missing_streams = flags & (FLV_HEADER_FLAG_HASVIDEO | FLV_HEADER_FLAG_HASAUDIO);

    s->ctx_flags |= AVFMTCTX_NOHEADER;

    offset = avio_rb32(s->pb);

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

    avio_skip(s->pb, 4);

    s->start_time = 0;

    flv->sum_flv_tag_size = 0;

    flv->last_keyframe_stream_index = -1;

    return 0;

}


static inline void mix_3f_2r_to_mono(AC3DecodeContext *ctx)

{

    int i;

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

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

        output[1][i] += (output[2][i] + output[3][i] + output[4][i] + output[5][i]);

    memset(output[2], 0, sizeof(output[2]));

    memset(output[3], 0, sizeof(output[3]));

    memset(output[4], 0, sizeof(output[4]));

    memset(output[5], 0, sizeof(output[5]));

}


static int hds_write_header(AVFormatContext *s)

{

    HDSContext *c = s->priv_data;

    int ret = 0, i;

    AVOutputFormat *oformat;

    mkdir(s->filename, 0777);

    oformat = av_guess_format("flv", NULL, NULL);

    if (!oformat) {

        ret = AVERROR_MUXER_NOT_FOUND;

        goto fail;

    }

    c->streams = av_mallocz(sizeof(*c->streams) * s->nb_streams);

    if (!c->streams) {

        ret = AVERROR(ENOMEM);

        goto fail;

    }

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

        OutputStream *os = &c->streams[c->nb_streams];

        AVFormatContext *ctx;

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

        if (!st->codec->bit_rate) {

            av_log(s, AV_LOG_ERROR, "No bit rate set for stream %d\n", i);

            ret = AVERROR(EINVAL);

            goto fail;

        }

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

            if (os->has_video) {

                c->nb_streams++;

                os++;

            }

            os->has_video = 1;

        } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {

            if (os->has_audio) {

                c->nb_streams++;

                os++;

            }

            os->has_audio = 1;

        } else {

            av_log(s, AV_LOG_ERROR, "Unsupported stream type in stream %d\n", i);

            ret = AVERROR(EINVAL);

            goto fail;

        }

        os->bitrate += s->streams[i]->codec->bit_rate;

        if (!os->ctx) {

            os->first_stream = i;

            ctx = avformat_alloc_context();

            if (!ctx) {

                ret = AVERROR(ENOMEM);

                goto fail;

            }

            os->ctx = ctx;

            ctx->oformat = oformat;

            ctx->interrupt_callback = s->interrupt_callback;

            ctx->pb = avio_alloc_context(os->iobuf, sizeof(os->iobuf),

                                         AVIO_FLAG_WRITE, os,

                                         NULL, hds_write, NULL);

            if (!ctx->pb) {

                ret = AVERROR(ENOMEM);

                goto fail;

            }

        } else {

            ctx = os->ctx;

        }

        s->streams[i]->id = c->nb_streams;

        if (!(st = avformat_new_stream(ctx, NULL))) {

            ret = AVERROR(ENOMEM);

            goto fail;

        }

        avcodec_copy_context(st->codec, s->streams[i]->codec);

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

    }

    if (c->streams[c->nb_streams].ctx)

        c->nb_streams++;

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

        OutputStream *os = &c->streams[i];

        int j;

        if ((ret = avformat_write_header(os->ctx, NULL)) < 0) {

             goto fail;

        }

        os->ctx_inited = 1;

        avio_flush(os->ctx->pb);

        for (j = 0; j < os->ctx->nb_streams; j++)

            s->streams[os->first_stream + j]->time_base = os->ctx->streams[j]->time_base;

        snprintf(os->temp_filename, sizeof(os->temp_filename),

                 "%s/stream%d_temp", s->filename, i);

        init_file(s, os, 0);

        if (!os->has_video && c->min_frag_duration <= 0) {

            av_log(s, AV_LOG_WARNING,

                   "No video stream in output stream %d and no min frag duration set\n", i);

            ret = AVERROR(EINVAL);

        }

        os->fragment_index = 1;

        write_abst(s, os, 0);

    }

    ret = write_manifest(s, 0);

fail:

    if (ret)

        hds_free(s);

    return ret;

}


int ff_h264_fill_default_ref_list(H264Context *h, H264SliceContext *sl)

{

    int i, len;

    int j;

    if (sl->slice_type_nos == AV_PICTURE_TYPE_B) {

        H264Picture *sorted[32];

        int cur_poc, list;

        int lens[2];

        if (FIELD_PICTURE(h))

            cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure == PICT_BOTTOM_FIELD];

        else

            cur_poc = h->cur_pic_ptr->poc;

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

            len  = add_sorted(sorted,       h->short_ref, h->short_ref_count, cur_poc, 1 ^ list);

            len += add_sorted(sorted + len, h->short_ref, h->short_ref_count, cur_poc, 0 ^ list);

            av_assert0(len <= 32);

            len  = build_def_list(h->default_ref_list[list], FF_ARRAY_ELEMS(h->default_ref_list[0]),

                                  sorted, len, 0, h->picture_structure);

            len += build_def_list(h->default_ref_list[list] + len,

                                  FF_ARRAY_ELEMS(h->default_ref_list[0]) - len,

                                  h->long_ref, 16, 1, h->picture_structure);

            av_assert0(len <= 32);

            if (len < sl->ref_count[list])

                memset(&h->default_ref_list[list][len], 0, sizeof(H264Ref) * (sl->ref_count[list] - len));

            lens[list] = len;

        }

        if (lens[0] == lens[1] && lens[1] > 1) {

            for (i = 0; i < lens[0] &&

                        h->default_ref_list[0][i].parent->f->buf[0]->buffer ==

                        h->default_ref_list[1][i].parent->f->buf[0]->buffer; i++);

            if (i == lens[0]) {

                FFSWAP(H264Ref, h->default_ref_list[1][0], h->default_ref_list[1][1]);

            }

        }

    } else {

        len  = build_def_list(h->default_ref_list[0], FF_ARRAY_ELEMS(h->default_ref_list[0]),

                              h->short_ref, h->short_ref_count, 0, h->picture_structure);

        len += build_def_list(h->default_ref_list[0] + len,

                              FF_ARRAY_ELEMS(h->default_ref_list[0]) - len,

                              h-> long_ref, 16, 1, h->picture_structure);

        av_assert0(len <= 32);

        if (len < sl->ref_count[0])

            memset(&h->default_ref_list[0][len], 0, sizeof(H264Ref) * (sl->ref_count[0] - len));

    }

#ifdef TRACE

    for (i = 0; i < sl->ref_count[0]; i++) {

        ff_tlog(h->avctx, "List0: %s fn:%d 0x%p\n",

                h->default_ref_list[0][i].parent ? (h->default_ref_list[0][i].parent->long_ref ? "LT" : "ST") : "NULL",

                h->default_ref_list[0][i].pic_id,

                h->default_ref_list[0][i].parent ? h->default_ref_list[0][i].parent->f->data[0] : 0);

    }

    if (sl->slice_type_nos == AV_PICTURE_TYPE_B) {

        for (i = 0; i < sl->ref_count[1]; i++) {

            ff_tlog(h->avctx, "List1: %s fn:%d 0x%p\n",

                    h->default_ref_list[1][i].parent ? (h->default_ref_list[1][i].parent->long_ref ? "LT" : "ST") : "NULL",

                    h->default_ref_list[1][i].pic_id,

                    h->default_ref_list[1][i].parent ? h->default_ref_list[1][i].parent->f->data[0] : 0);

        }

    }

#endif

    for (j = 0; j<1+(sl->slice_type_nos == AV_PICTURE_TYPE_B); j++) {

        for (i = 0; i < sl->ref_count[j]; i++) {

            if (h->default_ref_list[j][i].parent) {

                AVFrame *f = h->default_ref_list[j][i].parent->f;

                if (h->cur_pic_ptr->f->width  != f->width ||

                    h->cur_pic_ptr->f->height != f->height ||

                    h->cur_pic_ptr->f->format != f->format) {

                    av_log(h->avctx, AV_LOG_ERROR, "Discarding mismatching reference\n");

                    memset(&h->default_ref_list[j][i], 0, sizeof(h->default_ref_list[j][i]));

                }

            }

        }

    }

    return 0;

}


int ff_listen_connect(int fd, const struct sockaddr *addr,

                      socklen_t addrlen, int timeout, URLContext *h,

                      int will_try_next)

{

    struct pollfd p = {fd, POLLOUT, 0};

    int ret;

    socklen_t optlen;

    ff_socket_nonblock(fd, 1);

    while ((ret = connect(fd, addr, addrlen))) {

        ret = ff_neterrno();

        switch (ret) {

        case AVERROR(EINTR):

            if (ff_check_interrupt(&h->interrupt_callback))

                return AVERROR_EXIT;

            continue;

        case AVERROR(EINPROGRESS):

        case AVERROR(EAGAIN):

            ret = ff_poll_interrupt(&p, 1, timeout, &h->interrupt_callback);

            if (ret < 0)

                return ret;

            optlen = sizeof(ret);

            if (getsockopt (fd, SOL_SOCKET, SO_ERROR, &ret, &optlen))

                ret = AVUNERROR(ff_neterrno());

            if (ret != 0) {

                char errbuf[100];

                ret = AVERROR(ret);

                av_strerror(ret, errbuf, sizeof(errbuf));

                if (will_try_next)

                    av_log(h, AV_LOG_WARNING,

                           "Connection to %s failed (%s), trying next address\n",

                           h->filename, errbuf);

                else

                    av_log(h, AV_LOG_ERROR, "Connection to %s failed: %s\n",

                           h->filename, errbuf);

            }

        default:

            return ret;

        }

    }

    return ret;

}


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

{

    BDRVRawState *s = bs->opaque;

    int ret;

    posix_aio_init();

    s->type = FTYPE_FD;

    /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */

    ret = raw_open_common(bs, filename, flags, O_NONBLOCK);

    if (ret)

        return ret;

    /* close fd so that we can reopen it as needed */

    close(s->fd);

    s->fd = -1;

    s->fd_media_changed = 1;

    return 0;

}


static void tcg_opt_gen_mov(TCGArg *gen_args, TCGArg dst, TCGArg src,

                            int nb_temps, int nb_globals)

{

        reset_temp(dst, nb_temps, nb_globals);

        assert(temps[src].state != TCG_TEMP_COPY);

        if (src >= nb_globals) {

            assert(temps[src].state != TCG_TEMP_CONST);

            if (temps[src].state != TCG_TEMP_HAS_COPY) {

                temps[src].state = TCG_TEMP_HAS_COPY;

                temps[src].next_copy = src;

                temps[src].prev_copy = src;

            }

            temps[dst].state = TCG_TEMP_COPY;

            temps[dst].val = src;

            temps[dst].next_copy = temps[src].next_copy;

            temps[dst].prev_copy = src;

            temps[temps[dst].next_copy].prev_copy = dst;

            temps[src].next_copy = dst;

        }

        gen_args[0] = dst;

        gen_args[1] = src;

}


static void machvirt_init(MachineState *machine)

{

    VirtMachineState *vms = VIRT_MACHINE(machine);

    VirtMachineClass *vmc = VIRT_MACHINE_GET_CLASS(machine);

    qemu_irq pic[NUM_IRQS];

    MemoryRegion *sysmem = get_system_memory();

    MemoryRegion *secure_sysmem = NULL;

    int n, virt_max_cpus;

    MemoryRegion *ram = g_new(MemoryRegion, 1);

    const char *cpu_model = machine->cpu_model;

    char **cpustr;

    ObjectClass *oc;

    const char *typename;

    CPUClass *cc;

    Error *err = NULL;

    bool firmware_loaded = bios_name || drive_get(IF_PFLASH, 0, 0);

    if (!cpu_model) {

        cpu_model = "cortex-a15";

    }

    /* We can probe only here because during property set

     * KVM is not available yet

     */

    if (!vms->gic_version) {

        if (!kvm_enabled()) {

            error_report("gic-version=host requires KVM");

            exit(1);

        }

        vms->gic_version = kvm_arm_vgic_probe();

        if (!vms->gic_version) {

            error_report("Unable to determine GIC version supported by host");

            exit(1);

        }

    }

    /* Separate the actual CPU model name from any appended features */

    cpustr = g_strsplit(cpu_model, ",", 2);

    if (!cpuname_valid(cpustr[0])) {

        error_report("mach-virt: CPU %s not supported", cpustr[0]);

        exit(1);

    }

    /* If we have an EL3 boot ROM then the assumption is that it will

     * implement PSCI itself, so disable QEMU's internal implementation

     * so it doesn't get in the way. Instead of starting secondary

     * CPUs in PSCI powerdown state we will start them all running and

     * let the boot ROM sort them out.

     * The usual case is that we do use QEMU's PSCI implementation;

     * if the guest has EL2 then we will use SMC as the conduit,

     * and otherwise we will use HVC (for backwards compatibility and

     * because if we're using KVM then we must use HVC).

     */

    if (vms->secure && firmware_loaded) {

        vms->psci_conduit = QEMU_PSCI_CONDUIT_DISABLED;

    } else if (vms->virt) {

        vms->psci_conduit = QEMU_PSCI_CONDUIT_SMC;

    } else {

        vms->psci_conduit = QEMU_PSCI_CONDUIT_HVC;

    }

    /* The maximum number of CPUs depends on the GIC version, or on how

     * many redistributors we can fit into the memory map.

     */

    if (vms->gic_version == 3) {

        virt_max_cpus = vms->memmap[VIRT_GIC_REDIST].size / 0x20000;

    } else {

        virt_max_cpus = GIC_NCPU;

    }

    if (max_cpus > virt_max_cpus) {

        error_report("Number of SMP CPUs requested (%d) exceeds max CPUs "

                     "supported by machine 'mach-virt' (%d)",

                     max_cpus, virt_max_cpus);

        exit(1);

    }

    vms->smp_cpus = smp_cpus;

    if (machine->ram_size > vms->memmap[VIRT_MEM].size) {

        error_report("mach-virt: cannot model more than %dGB RAM", RAMLIMIT_GB);

        exit(1);

    }

    if (vms->virt && kvm_enabled()) {

        error_report("mach-virt: KVM does not support providing "

                     "Virtualization extensions to the guest CPU");

        exit(1);

    }

    if (vms->secure) {

        if (kvm_enabled()) {

            error_report("mach-virt: KVM does not support Security extensions");

            exit(1);

        }

        /* The Secure view of the world is the same as the NonSecure,

         * but with a few extra devices. Create it as a container region

         * containing the system memory at low priority; any secure-only

         * devices go in at higher priority and take precedence.

         */

        secure_sysmem = g_new(MemoryRegion, 1);

        memory_region_init(secure_sysmem, OBJECT(machine), "secure-memory",

                           UINT64_MAX);

        memory_region_add_subregion_overlap(secure_sysmem, 0, sysmem, -1);

    }

    create_fdt(vms);

    oc = cpu_class_by_name(TYPE_ARM_CPU, cpustr[0]);

    if (!oc) {

        error_report("Unable to find CPU definition");

        exit(1);

    }

    typename = object_class_get_name(oc);

    /* convert -smp CPU options specified by the user into global props */

    cc = CPU_CLASS(oc);

    cc->parse_features(typename, cpustr[1], &err);

    g_strfreev(cpustr);

    if (err) {

        error_report_err(err);

        exit(1);

    }

    for (n = 0; n < smp_cpus; n++) {

        Object *cpuobj = object_new(typename);

        object_property_set_int(cpuobj, virt_cpu_mp_affinity(vms, n),

                                "mp-affinity", NULL);

        if (!vms->secure) {

            object_property_set_bool(cpuobj, false, "has_el3", NULL);

        }

        if (!vms->virt && object_property_find(cpuobj, "has_el2", NULL)) {

            object_property_set_bool(cpuobj, false, "has_el2", NULL);

        }

        if (vms->psci_conduit != QEMU_PSCI_CONDUIT_DISABLED) {

            object_property_set_int(cpuobj, vms->psci_conduit,

                                    "psci-conduit", NULL);

            /* Secondary CPUs start in PSCI powered-down state */

            if (n > 0) {

                object_property_set_bool(cpuobj, true,

                                         "start-powered-off", NULL);

            }

        }

        if (vmc->no_pmu && object_property_find(cpuobj, "pmu", NULL)) {

            object_property_set_bool(cpuobj, false, "pmu", NULL);

        }

        if (object_property_find(cpuobj, "reset-cbar", NULL)) {

            object_property_set_int(cpuobj, vms->memmap[VIRT_CPUPERIPHS].base,

                                    "reset-cbar", &error_abort);

        }

        object_property_set_link(cpuobj, OBJECT(sysmem), "memory",

                                 &error_abort);

        if (vms->secure) {

            object_property_set_link(cpuobj, OBJECT(secure_sysmem),

                                     "secure-memory", &error_abort);

        }

        object_property_set_bool(cpuobj, true, "realized", NULL);

        object_unref(cpuobj);

    }

    fdt_add_timer_nodes(vms);

    fdt_add_cpu_nodes(vms);

    fdt_add_psci_node(vms);

    memory_region_allocate_system_memory(ram, NULL, "mach-virt.ram",

                                         machine->ram_size);

    memory_region_add_subregion(sysmem, vms->memmap[VIRT_MEM].base, ram);

    create_flash(vms, sysmem, secure_sysmem ? secure_sysmem : sysmem);

    create_gic(vms, pic);

    fdt_add_pmu_nodes(vms);

    create_uart(vms, pic, VIRT_UART, sysmem, serial_hds[0]);

    if (vms->secure) {

        create_secure_ram(vms, secure_sysmem);

        create_uart(vms, pic, VIRT_SECURE_UART, secure_sysmem, serial_hds[1]);

    }

    create_rtc(vms, pic);

    create_pcie(vms, pic);

    create_gpio(vms, pic);

    /* Create mmio transports, so the user can create virtio backends

     * (which will be automatically plugged in to the transports). If

     * no backend is created the transport will just sit harmlessly idle.

     */

    create_virtio_devices(vms, pic);

    vms->fw_cfg = create_fw_cfg(vms, &address_space_memory);

    rom_set_fw(vms->fw_cfg);

    vms->machine_done.notify = virt_machine_done;

    qemu_add_machine_init_done_notifier(&vms->machine_done);

    vms->bootinfo.ram_size = machine->ram_size;

    vms->bootinfo.kernel_filename = machine->kernel_filename;

    vms->bootinfo.kernel_cmdline = machine->kernel_cmdline;

    vms->bootinfo.initrd_filename = machine->initrd_filename;

    vms->bootinfo.nb_cpus = smp_cpus;

    vms->bootinfo.board_id = -1;

    vms->bootinfo.loader_start = vms->memmap[VIRT_MEM].base;

    vms->bootinfo.get_dtb = machvirt_dtb;

    vms->bootinfo.firmware_loaded = firmware_loaded;

    arm_load_kernel(ARM_CPU(first_cpu), &vms->bootinfo);

    /*

     * arm_load_kernel machine init done notifier registration must

     * happen before the platform_bus_create call. In this latter,

     * another notifier is registered which adds platform bus nodes.

     * Notifiers are executed in registration reverse order.

     */

    create_platform_bus(vms, pic);

}


static int cow_create(const char *filename, QemuOpts *opts, Error **errp)

{

    struct cow_header_v2 cow_header;

    struct stat st;

    int64_t image_sectors = 0;

    char *image_filename = NULL;

    Error *local_err = NULL;

    int ret;

    BlockDriverState *cow_bs = NULL;

    /* Read out options */

    image_sectors = DIV_ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),

                                 BDRV_SECTOR_SIZE);

    image_filename = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);

    ret = bdrv_create_file(filename, opts, &local_err);

    if (ret < 0) {

        error_propagate(errp, local_err);

        goto exit;

    }

    ret = bdrv_open(&cow_bs, filename, NULL, NULL,

                    BDRV_O_RDWR | BDRV_O_PROTOCOL, NULL, &local_err);

    if (ret < 0) {

        error_propagate(errp, local_err);

        goto exit;

    }

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

    cow_header.magic = cpu_to_be32(COW_MAGIC);

    cow_header.version = cpu_to_be32(COW_VERSION);

    if (image_filename) {

        /* Note: if no file, we put a dummy mtime */

        cow_header.mtime = cpu_to_be32(0);

        if (stat(image_filename, &st) != 0) {

            goto mtime_fail;

        }

        cow_header.mtime = cpu_to_be32(st.st_mtime);

    mtime_fail:

        pstrcpy(cow_header.backing_file, sizeof(cow_header.backing_file),

                image_filename);

    }

    cow_header.sectorsize = cpu_to_be32(512);

    cow_header.size = cpu_to_be64(image_sectors * 512);

    ret = bdrv_pwrite(cow_bs, 0, &cow_header, sizeof(cow_header));

    if (ret < 0) {

        goto exit;

    }

    /* resize to include at least all the bitmap */

    ret = bdrv_truncate(cow_bs,

        sizeof(cow_header) + ((image_sectors + 7) >> 3));

    if (ret < 0) {

        goto exit;

    }

exit:

    g_free(image_filename);

    if (cow_bs) {

        bdrv_unref(cow_bs);

    }

    return ret;

}


socket_sockaddr_to_address_inet(struct sockaddr_storage *sa,

                                socklen_t salen,

                                Error **errp)

{

    char host[NI_MAXHOST];

    char serv[NI_MAXSERV];

    SocketAddressLegacy *addr;

    InetSocketAddress *inet;

    int ret;

    ret = getnameinfo((struct sockaddr *)sa, salen,

                      host, sizeof(host),

                      serv, sizeof(serv),

                      NI_NUMERICHOST | NI_NUMERICSERV);

    if (ret != 0) {

        error_setg(errp, "Cannot format numeric socket address: %s",

                   gai_strerror(ret));

        return NULL;

    }

    addr = g_new0(SocketAddressLegacy, 1);

    addr->type = SOCKET_ADDRESS_LEGACY_KIND_INET;

    inet = addr->u.inet.data = g_new0(InetSocketAddress, 1);

    inet->host = g_strdup(host);

    inet->port = g_strdup(serv);

    if (sa->ss_family == AF_INET) {

        inet->has_ipv4 = inet->ipv4 = true;

    } else {

        inet->has_ipv6 = inet->ipv6 = true;

    }

    return addr;

}


static void entropy_decode(APEContext *ctx, int blockstodecode, int stereo)

{

    int32_t *decoded0 = ctx->decoded[0];

    int32_t *decoded1 = ctx->decoded[1];

    while (blockstodecode--) {

        *decoded0++ = ape_decode_value(ctx, &ctx->riceY);

        if (stereo)

            *decoded1++ = ape_decode_value(ctx, &ctx->riceX);

    }

}


static int kvm_get_fpu(CPUState *env)

{

    struct kvm_fpu fpu;

    int i, ret;

    ret = kvm_vcpu_ioctl(env, KVM_GET_FPU, &fpu);

    if (ret < 0)

        return ret;

    env->fpstt = (fpu.fsw >> 11) & 7;

    env->fpus = fpu.fsw;

    env->fpuc = fpu.fcw;

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

	env->fptags[i] = !((fpu.ftwx >> i) & 1);

    memcpy(env->fpregs, fpu.fpr, sizeof env->fpregs);

    memcpy(env->xmm_regs, fpu.xmm, sizeof env->xmm_regs);

    env->mxcsr = fpu.mxcsr;

    return 0;

}


static void dump_aml_files(test_data *data, bool rebuild)

{

    AcpiSdtTable *sdt;

    GError *error = NULL;

    gchar *aml_file = NULL;

    gint fd;

    ssize_t ret;

    int i;

    for (i = 0; i < data->tables->len; ++i) {

        const char *ext = data->variant ? data->variant : "";

        sdt = &g_array_index(data->tables, AcpiSdtTable, i);

        g_assert(sdt->aml);

        if (rebuild) {

            uint32_t signature = cpu_to_le32(sdt->header.signature);

            aml_file = g_strdup_printf("%s/%s/%.4s%s", data_dir, data->machine,

                                       (gchar *)&signature, ext);

            fd = g_open(aml_file, O_WRONLY|O_TRUNC|O_CREAT,

                        S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH);

        } else {

            fd = g_file_open_tmp("aml-XXXXXX", &sdt->aml_file, &error);

            g_assert_no_error(error);

        }

        g_assert(fd >= 0);

        ret = qemu_write_full(fd, sdt, sizeof(AcpiTableHeader));

        g_assert(ret == sizeof(AcpiTableHeader));

        ret = qemu_write_full(fd, sdt->aml, sdt->aml_len);

        g_assert(ret == sdt->aml_len);

        close(fd);

        if (aml_file) {

            g_free(aml_file);

        }

    }

}


int nbd_init(int fd, QIOChannelSocket *sioc, uint32_t flags, off_t size)

{

    TRACE("Setting NBD socket");

    if (ioctl(fd, NBD_SET_SOCK, sioc->fd) < 0) {

        int serrno = errno;

        LOG("Failed to set NBD socket");

        return -serrno;

    }

    TRACE("Setting block size to %lu", (unsigned long)BDRV_SECTOR_SIZE);

    if (ioctl(fd, NBD_SET_BLKSIZE, (size_t)BDRV_SECTOR_SIZE) < 0) {

        int serrno = errno;

        LOG("Failed setting NBD block size");

        return -serrno;

    }

    TRACE("Setting size to %zd block(s)", (size_t)(size / BDRV_SECTOR_SIZE));

    if (ioctl(fd, NBD_SET_SIZE_BLOCKS, (size_t)(size / BDRV_SECTOR_SIZE)) < 0) {

        int serrno = errno;

        LOG("Failed setting size (in blocks)");

        return -serrno;

    }

    if (ioctl(fd, NBD_SET_FLAGS, flags) < 0) {

        if (errno == ENOTTY) {

            int read_only = (flags & NBD_FLAG_READ_ONLY) != 0;

            TRACE("Setting readonly attribute");

            if (ioctl(fd, BLKROSET, (unsigned long) &read_only) < 0) {

                int serrno = errno;

                LOG("Failed setting read-only attribute");

                return -serrno;

            }

        } else {

            int serrno = errno;

            LOG("Failed setting flags");

            return -serrno;

        }

    }

    TRACE("Negotiation ended");

    return 0;

}


static void smbios_build_type_0_fields(QemuOpts *opts)

{

    const char *val;

    unsigned char major, minor;

    val = qemu_opt_get(opts, "vendor");

    if (val) {

        smbios_add_field(0, offsetof(struct smbios_type_0, vendor_str),

                         val, strlen(val) + 1);

    }

    val = qemu_opt_get(opts, "version");

    if (val) {

        smbios_add_field(0, offsetof(struct smbios_type_0, bios_version_str),

                         val, strlen(val) + 1);

    }

    val = qemu_opt_get(opts, "date");

    if (val) {

        smbios_add_field(0, offsetof(struct smbios_type_0,

                                     bios_release_date_str),

                         val, strlen(val) + 1);

    }

    val = qemu_opt_get(opts, "release");

    if (val) {

        if (sscanf(val, "%hhu.%hhu", &major, &minor) != 2) {

            error_report("Invalid release");

            exit(1);

        }

        smbios_add_field(0, offsetof(struct smbios_type_0,

                                     system_bios_major_release),

                         &major, 1);

        smbios_add_field(0, offsetof(struct smbios_type_0,

                                     system_bios_minor_release),

                         &minor, 1);

    }

}


SimpleSpiceUpdate *qemu_spice_create_update(SimpleSpiceDisplay *ssd)

{

    SimpleSpiceUpdate *update;

    QXLDrawable *drawable;

    QXLImage *image;

    QXLCommand *cmd;

    uint8_t *src, *dst;

    int by, bw, bh;

    if (qemu_spice_rect_is_empty(&ssd->dirty)) {

        return NULL;

    };

    pthread_mutex_lock(&ssd->lock);

    dprint(2, "%s: lr %d -> %d,  tb -> %d -> %d\n", __FUNCTION__,

           ssd->dirty.left, ssd->dirty.right,

           ssd->dirty.top, ssd->dirty.bottom);

    update   = qemu_mallocz(sizeof(*update));

    drawable = &update->drawable;

    image    = &update->image;

    cmd      = &update->ext.cmd;

    bw       = ssd->dirty.right - ssd->dirty.left;

    bh       = ssd->dirty.bottom - ssd->dirty.top;

    update->bitmap = qemu_malloc(bw * bh * 4);

    drawable->bbox            = ssd->dirty;

    drawable->clip.type       = SPICE_CLIP_TYPE_NONE;

    drawable->effect          = QXL_EFFECT_OPAQUE;

    drawable->release_info.id = (intptr_t)update;

    drawable->type            = QXL_DRAW_COPY;

    drawable->surfaces_dest[0] = -1;

    drawable->surfaces_dest[1] = -1;

    drawable->surfaces_dest[2] = -1;

    drawable->u.copy.rop_descriptor  = SPICE_ROPD_OP_PUT;

    drawable->u.copy.src_bitmap      = (intptr_t)image;

    drawable->u.copy.src_area.right  = bw;

    drawable->u.copy.src_area.bottom = bh;

    QXL_SET_IMAGE_ID(image, QXL_IMAGE_GROUP_DEVICE, ssd->unique++);

    image->descriptor.type   = SPICE_IMAGE_TYPE_BITMAP;

    image->bitmap.flags      = QXL_BITMAP_DIRECT | QXL_BITMAP_TOP_DOWN;

    image->bitmap.stride     = bw * 4;

    image->descriptor.width  = image->bitmap.x = bw;

    image->descriptor.height = image->bitmap.y = bh;

    image->bitmap.data = (intptr_t)(update->bitmap);

    image->bitmap.palette = 0;

    image->bitmap.format = SPICE_BITMAP_FMT_32BIT;

    if (ssd->conv == NULL) {

        PixelFormat dst = qemu_default_pixelformat(32);

        ssd->conv = qemu_pf_conv_get(&dst, &ssd->ds->surface->pf);

        assert(ssd->conv);

    }

    src = ds_get_data(ssd->ds) +

        ssd->dirty.top * ds_get_linesize(ssd->ds) +

        ssd->dirty.left * ds_get_bytes_per_pixel(ssd->ds);

    dst = update->bitmap;

    for (by = 0; by < bh; by++) {

        qemu_pf_conv_run(ssd->conv, dst, src, bw);

        src += ds_get_linesize(ssd->ds);

        dst += image->bitmap.stride;

    }

    cmd->type = QXL_CMD_DRAW;

    cmd->data = (intptr_t)drawable;

    memset(&ssd->dirty, 0, sizeof(ssd->dirty));

    pthread_mutex_unlock(&ssd->lock);

    return update;

}


void HELPER(set_cp15)(CPUARMState *env, uint32_t insn, uint32_t val)

{

    int op1;

    int op2;

    int crm;

    op1 = (insn >> 21) & 7;

    op2 = (insn >> 5) & 7;

    crm = insn & 0xf;

    switch ((insn >> 16) & 0xf) {

    case 0:

        /* ID codes.  */

        if (arm_feature(env, ARM_FEATURE_XSCALE))

            break;

        if (arm_feature(env, ARM_FEATURE_OMAPCP))

            break;

        if (arm_feature(env, ARM_FEATURE_V7)

                && op1 == 2 && crm == 0 && op2 == 0) {

            env->cp15.c0_cssel = val & 0xf;

            break;

        }

        goto bad_reg;

    case 1: /* System configuration.  */

        if (arm_feature(env, ARM_FEATURE_V7)

                && op1 == 0 && crm == 1 && op2 == 0) {

            env->cp15.c1_scr = val;

            break;

        }

        if (arm_feature(env, ARM_FEATURE_OMAPCP))

            op2 = 0;

        switch (op2) {

        case 0:

            if (!arm_feature(env, ARM_FEATURE_XSCALE) || crm == 0)

                env->cp15.c1_sys = val;

            /* ??? Lots of these bits are not implemented.  */

            /* This may enable/disable the MMU, so do a TLB flush.  */

            tlb_flush(env, 1);

            break;

        case 1: /* Auxiliary control register.  */

            if (arm_feature(env, ARM_FEATURE_XSCALE)) {

                env->cp15.c1_xscaleauxcr = val;

                break;

            }

            /* Not implemented.  */

            break;

        case 2:

            if (arm_feature(env, ARM_FEATURE_XSCALE))

                goto bad_reg;

            if (env->cp15.c1_coproc != val) {

                env->cp15.c1_coproc = val;

                /* ??? Is this safe when called from within a TB?  */

                tb_flush(env);

            }

            break;

        default:

            goto bad_reg;

        }

        break;

    case 4: /* Reserved.  */

        goto bad_reg;

    case 6: /* MMU Fault address / MPU base/size.  */

        if (arm_feature(env, ARM_FEATURE_MPU)) {

            if (crm >= 8)

                goto bad_reg;

            env->cp15.c6_region[crm] = val;

        } else {

            if (arm_feature(env, ARM_FEATURE_OMAPCP))

                op2 = 0;

            switch (op2) {

            case 0:

                env->cp15.c6_data = val;

                break;

            case 1: /* ??? This is WFAR on armv6 */

            case 2:

                env->cp15.c6_insn = val;

                break;

            default:

                goto bad_reg;

            }

        }

        break;

    case 7: /* Cache control.  */

        env->cp15.c15_i_max = 0x000;

        env->cp15.c15_i_min = 0xff0;

        if (op1 != 0) {

            goto bad_reg;

        }

        break;

    case 9:

        if (arm_feature(env, ARM_FEATURE_OMAPCP))

            break;

        if (arm_feature(env, ARM_FEATURE_STRONGARM))

            break; /* Ignore ReadBuffer access */

        switch (crm) {

        case 0: /* Cache lockdown.  */

	    switch (op1) {

	    case 0: /* L1 cache.  */

		switch (op2) {

		case 0:

		    env->cp15.c9_data = val;

		    break;

		case 1:

		    env->cp15.c9_insn = val;

		    break;

		default:

		    goto bad_reg;

		}

		break;

	    case 1: /* L2 cache.  */

		/* Ignore writes to L2 lockdown/auxiliary registers.  */

		break;

	    default:

		goto bad_reg;

	    }

	    break;

        case 1: /* TCM memory region registers.  */

            /* Not implemented.  */

            goto bad_reg;

        default:

            goto bad_reg;

        }

        break;

    case 12: /* Reserved.  */

        goto bad_reg;

    }

    return;

bad_reg:

    /* ??? For debugging only.  Should raise illegal instruction exception.  */

    cpu_abort(env, "Unimplemented cp15 register write (c%d, c%d, {%d, %d})\n",

              (insn >> 16) & 0xf, crm, op1, op2);

}


static int decode_profile_tier_level(HEVCLocalContext *lc, PTL *ptl,

                                     int max_num_sub_layers)

{

    int i, j;

    GetBitContext *gb = &lc->gb;

    ptl->general_profile_space = get_bits(gb, 2);

    ptl->general_tier_flag     = get_bits1(gb);

    ptl->general_profile_idc   = get_bits(gb, 5);

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

        ptl->general_profile_compatibility_flag[i] = get_bits1(gb);

    skip_bits1(gb); // general_progressive_source_flag

    skip_bits1(gb); // general_interlaced_source_flag

    skip_bits1(gb); // general_non_packed_constraint_flag

    skip_bits1(gb); // general_frame_only_constraint_flag

    if (get_bits(gb, 16) != 0) // XXX_reserved_zero_44bits[0..15]

        return -1;

    if (get_bits(gb, 16) != 0) // XXX_reserved_zero_44bits[16..31]

        return -1;

    if (get_bits(gb, 12) != 0) // XXX_reserved_zero_44bits[32..43]

        return -1;

    ptl->general_level_idc = get_bits(gb, 8);

    for (i = 0; i < max_num_sub_layers - 1; i++) {

        ptl->sub_layer_profile_present_flag[i] = get_bits1(gb);

        ptl->sub_layer_level_present_flag[i]   = get_bits1(gb);

    }

    if (max_num_sub_layers - 1 > 0)

        for (i = max_num_sub_layers - 1; i < 8; i++)

            skip_bits(gb, 2);  // reserved_zero_2bits[i]

    for (i = 0; i < max_num_sub_layers - 1; i++) {

        if (ptl->sub_layer_profile_present_flag[i]) {

            ptl->sub_layer_profile_space[i] = get_bits(gb, 2);

            ptl->sub_layer_tier_flag[i]     = get_bits(gb, 1);

            ptl->sub_layer_profile_idc[i]   = get_bits(gb, 5);

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

                ptl->sub_layer_profile_compatibility_flags[i][j] = get_bits1(gb);

            skip_bits1(gb); // sub_layer_progressive_source_flag

            skip_bits1(gb); // sub_layer_interlaced_source_flag

            skip_bits1(gb); // sub_layer_non_packed_constraint_flag

            skip_bits1(gb); // sub_layer_frame_only_constraint_flag

            if (get_bits(gb, 16) != 0) // sub_layer_reserved_zero_44bits[0..15]

                return -1;

            if (get_bits(gb, 16) != 0) // sub_layer_reserved_zero_44bits[16..31]

                return -1;

            if (get_bits(gb, 12) != 0) // sub_layer_reserved_zero_44bits[32..43]

                return -1;

        }

        if (ptl->sub_layer_level_present_flag[i])

            ptl->sub_layer_level_idc[i] = get_bits(gb, 8);

    }

    return 0;

}


static void tcx_init(hwaddr addr, qemu_irq irq, int vram_size, int width,

                     int height, int depth)

{

    DeviceState *dev;

    SysBusDevice *s;

    dev = qdev_create(NULL, "SUNW,tcx");

    qdev_prop_set_uint32(dev, "vram_size", vram_size);

    qdev_prop_set_uint16(dev, "width", width);

    qdev_prop_set_uint16(dev, "height", height);

    qdev_prop_set_uint16(dev, "depth", depth);

    qdev_prop_set_uint64(dev, "prom_addr", addr);

    qdev_init_nofail(dev);

    s = SYS_BUS_DEVICE(dev);

    /* 10/ROM : FCode ROM */

    sysbus_mmio_map(s, 0, addr);

    /* 2/STIP : Stipple */

    sysbus_mmio_map(s, 1, addr + 0x04000000ULL);

    /* 3/BLIT : Blitter */

    sysbus_mmio_map(s, 2, addr + 0x06000000ULL);

    /* 5/RSTIP : Raw Stipple */

    sysbus_mmio_map(s, 3, addr + 0x0c000000ULL);

    /* 6/RBLIT : Raw Blitter */

    sysbus_mmio_map(s, 4, addr + 0x0e000000ULL);

    /* 7/TEC : Transform Engine */

    sysbus_mmio_map(s, 5, addr + 0x00700000ULL);

    /* 8/CMAP  : DAC */

    sysbus_mmio_map(s, 6, addr + 0x00200000ULL);

    /* 9/THC : */

    if (depth == 8) {

        sysbus_mmio_map(s, 7, addr + 0x00300000ULL);

    } else {

        sysbus_mmio_map(s, 7, addr + 0x00301000ULL);

    }

    /* 11/DHC : */

    sysbus_mmio_map(s, 8, addr + 0x00240000ULL);

    /* 12/ALT : */

    sysbus_mmio_map(s, 9, addr + 0x00280000ULL);

    /* 0/DFB8 : 8-bit plane */

    sysbus_mmio_map(s, 10, addr + 0x00800000ULL);

    /* 1/DFB24 : 24bit plane */

    sysbus_mmio_map(s, 11, addr + 0x02000000ULL);

    /* 4/RDFB32: Raw framebuffer. Control plane */

    sysbus_mmio_map(s, 12, addr + 0x0a000000ULL);

    /* 9/THC24bits : NetBSD writes here even with 8-bit display: dummy */

    if (depth == 8) {

        sysbus_mmio_map(s, 13, addr + 0x00301000ULL);

    }

    sysbus_connect_irq(s, 0, irq);

}


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

                       const char *name, FsCred *credp)

{

    int err = -1;

    int dirfd;

    if (fs_ctx->export_flags & V9FS_SM_MAPPED_FILE &&

        local_is_mapped_file_metadata(fs_ctx, name)) {

        errno = EINVAL;

        return -1;

    }

    dirfd = local_opendir_nofollow(fs_ctx, dir_path->data);

    if (dirfd == -1) {

        return -1;

    }

    if (fs_ctx->export_flags & V9FS_SM_MAPPED ||

        fs_ctx->export_flags & V9FS_SM_MAPPED_FILE) {

        err = mknodat(dirfd, name, SM_LOCAL_MODE_BITS | S_IFREG, 0);

        if (err == -1) {

            goto out;

        }

        if (fs_ctx->export_flags & V9FS_SM_MAPPED) {

            err = local_set_xattrat(dirfd, name, credp);

        } else {

            err = local_set_mapped_file_attrat(dirfd, name, credp);

        }

        if (err == -1) {

            goto err_end;

        }

    } else if (fs_ctx->export_flags & V9FS_SM_PASSTHROUGH ||

               fs_ctx->export_flags & V9FS_SM_NONE) {

        err = mknodat(dirfd, name, credp->fc_mode, credp->fc_rdev);

        if (err == -1) {

            goto out;

        }

        err = local_set_cred_passthrough(fs_ctx, dirfd, name, credp);

        if (err == -1) {

            goto err_end;

        }

    }

    goto out;

err_end:

    unlinkat_preserve_errno(dirfd, name, 0);

out:

    close_preserve_errno(dirfd);

    return err;

}


static void tpm_passthrough_worker_thread(gpointer data,

                                          gpointer user_data)

{

    TPMPassthruThreadParams *thr_parms = user_data;

    TPMPassthruState *tpm_pt = thr_parms->tb->s.tpm_pt;

    TPMBackendCmd cmd = (TPMBackendCmd)data;

    DPRINTF("tpm_passthrough: processing command type %d\n", cmd);

    switch (cmd) {

    case TPM_BACKEND_CMD_PROCESS_CMD:

        tpm_passthrough_unix_transfer(tpm_pt->tpm_fd,

                                      thr_parms->tpm_state->locty_data);

        thr_parms->recv_data_callback(thr_parms->tpm_state,

                                      thr_parms->tpm_state->locty_number);

        break;

    case TPM_BACKEND_CMD_INIT:

    case TPM_BACKEND_CMD_END:

    case TPM_BACKEND_CMD_TPM_RESET:

        /* nothing to do */

        break;

    }

}


static ram_addr_t ram_save_remaining(void)

{

    return ram_list.dirty_pages;

}


static int ide_dev_initfn(IDEDevice *dev, IDEDriveKind kind)

{

    IDEBus *bus = DO_UPCAST(IDEBus, qbus, dev->qdev.parent_bus);

    IDEState *s = bus->ifs + dev->unit;

    const char *serial;

    DriveInfo *dinfo;

    if (dev->conf.discard_granularity && dev->conf.discard_granularity != 512) {

        error_report("discard_granularity must be 512 for ide");

        return -1;

    }

    serial = dev->serial;

    if (!serial) {

        /* try to fall back to value set with legacy -drive serial=... */

        dinfo = drive_get_by_blockdev(dev->conf.bs);

        if (*dinfo->serial) {

            serial = dinfo->serial;

        }

    }

    if (ide_init_drive(s, dev->conf.bs, kind, dev->version, serial) < 0) {

        return -1;

    }

    if (!dev->version) {

        dev->version = g_strdup(s->version);

    }

    if (!dev->serial) {

        dev->serial = g_strdup(s->drive_serial_str);

    }

    add_boot_device_path(dev->conf.bootindex, &dev->qdev,

                         dev->unit ? "/disk@1" : "/disk@0");

    return 0;

}


static void qmp_output_start_list(Visitor *v, const char *name,

                                  GenericList **listp, size_t size,

                                  Error **errp)

{

    QmpOutputVisitor *qov = to_qov(v);

    QList *list = qlist_new();

    qmp_output_add(qov, name, list);

    qmp_output_push(qov, list, listp);

}


int ff_default_query_formats(AVFilterContext *ctx)

{

    return default_query_formats_common(ctx, ff_all_channel_layouts);

}


static int uncouple_channels(AC3DecodeContext * ctx)

{

    ac3_audio_block *ab = &ctx->audio_block;

    int ch, sbnd, bin;

    int index;

    float (*samples)[256];

    int16_t mantissa;

    samples = (float (*)[256])((ctx->bsi.flags & AC3_BSI_LFEON) ? (ctx->samples + 256) : (ctx->samples));

    /* uncouple channels */

    for (ch = 0; ch < ctx->bsi.nfchans; ch++)

        if (ab->chincpl & (1 << ch))

            for (sbnd = ab->cplbegf; sbnd < 3 + ab->cplendf; sbnd++)

                for (bin = 0; bin < 12; bin++) {

                    index = sbnd * 12 + bin + 37;

                    samples[ch][index] = ab->cplcoeffs[index] * ab->cplco[ch][sbnd] * ab->chcoeffs[ch];

                }

    /* generate dither if required */

    for (ch = 0; ch < ctx->bsi.nfchans; ch++)

        if ((ab->chincpl & (1 << ch)) && (ab->dithflag & (1 << ch)))

            for (index = 0; index < ab->endmant[ch]; index++)

                if (!ab->bap[ch][index]) {

                    mantissa = dither_int16(&ctx->state);

                    samples[ch][index] = to_float(ab->dexps[ch][index], mantissa) * ab->chcoeffs[ch];

                }

    return 0;

}


long do_rt_sigreturn(CPUTLGState *env)

{

    abi_ulong frame_addr = env->regs[TILEGX_R_SP];

    struct target_rt_sigframe *frame;

    sigset_t set;

    trace_user_do_rt_sigreturn(env, frame_addr);

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

        goto badframe;

    }

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

    do_sigprocmask(SIG_SETMASK, &set, NULL);

    restore_sigcontext(env, &frame->uc.tuc_mcontext);

    if (do_sigaltstack(frame_addr + offsetof(struct target_rt_sigframe,

                                             uc.tuc_stack),

                       0, env->regs[TILEGX_R_SP]) == -EFAULT) {

        goto badframe;

    }

    unlock_user_struct(frame, frame_addr, 0);

    return env->regs[TILEGX_R_RE];

 badframe:

    unlock_user_struct(frame, frame_addr, 0);

    force_sig(TARGET_SIGSEGV);

}


int ff_hevc_decode_nal_vps(HEVCContext *s)

{

    int i,j;

    GetBitContext *gb = &s->HEVClc->gb;

    int vps_id = 0;

    HEVCVPS *vps;

    AVBufferRef *vps_buf = av_buffer_allocz(sizeof(*vps));

    if (!vps_buf)

        return AVERROR(ENOMEM);

    vps = (HEVCVPS*)vps_buf->data;

    av_log(s->avctx, AV_LOG_DEBUG, "Decoding VPS\n");

    vps_id = get_bits(gb, 4);

    if (vps_id >= MAX_VPS_COUNT) {

        av_log(s->avctx, AV_LOG_ERROR, "VPS id out of range: %d\n", vps_id);

        goto err;

    }

    if (get_bits(gb, 2) != 3) { // vps_reserved_three_2bits

        av_log(s->avctx, AV_LOG_ERROR, "vps_reserved_three_2bits is not three\n");

        goto err;

    }

    vps->vps_max_layers               = get_bits(gb, 6) + 1;

    vps->vps_max_sub_layers           = get_bits(gb, 3) + 1;

    vps->vps_temporal_id_nesting_flag = get_bits1(gb);

    if (get_bits(gb, 16) != 0xffff) { // vps_reserved_ffff_16bits

        av_log(s->avctx, AV_LOG_ERROR, "vps_reserved_ffff_16bits is not 0xffff\n");

        goto err;

    }

    if (vps->vps_max_sub_layers > MAX_SUB_LAYERS) {

        av_log(s->avctx, AV_LOG_ERROR, "vps_max_sub_layers out of range: %d\n",

               vps->vps_max_sub_layers);

        goto err;

    }

    if (parse_ptl(s, &vps->ptl, vps->vps_max_sub_layers) < 0)

        goto err;

    vps->vps_sub_layer_ordering_info_present_flag = get_bits1(gb);

    i = vps->vps_sub_layer_ordering_info_present_flag ? 0 : vps->vps_max_sub_layers - 1;

    for (; i < vps->vps_max_sub_layers; i++) {

        vps->vps_max_dec_pic_buffering[i] = get_ue_golomb_long(gb) + 1;

        vps->vps_num_reorder_pics[i]      = get_ue_golomb_long(gb);

        vps->vps_max_latency_increase[i]  = get_ue_golomb_long(gb) - 1;

        if (vps->vps_max_dec_pic_buffering[i] > MAX_DPB_SIZE || !vps->vps_max_dec_pic_buffering[i]) {

            av_log(s->avctx, AV_LOG_ERROR, "vps_max_dec_pic_buffering_minus1 out of range: %d\n",

                   vps->vps_max_dec_pic_buffering[i] - 1);

            goto err;

        }

        if (vps->vps_num_reorder_pics[i] > vps->vps_max_dec_pic_buffering[i] - 1) {

            av_log(s->avctx, AV_LOG_WARNING, "vps_max_num_reorder_pics out of range: %d\n",

                   vps->vps_num_reorder_pics[i]);

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

                goto err;

        }

    }

    vps->vps_max_layer_id   = get_bits(gb, 6);

    vps->vps_num_layer_sets = get_ue_golomb_long(gb) + 1;

    if (vps->vps_num_layer_sets < 1 || vps->vps_num_layer_sets > 1024 ||

        (vps->vps_num_layer_sets - 1LL) * (vps->vps_max_layer_id + 1LL) > get_bits_left(gb)) {

        av_log(s->avctx, AV_LOG_ERROR, "too many layer_id_included_flags\n");

        goto err;

    }

    for (i = 1; i < vps->vps_num_layer_sets; i++)

        for (j = 0; j <= vps->vps_max_layer_id; j++)

            skip_bits(gb, 1);  // layer_id_included_flag[i][j]

    vps->vps_timing_info_present_flag = get_bits1(gb);

    if (vps->vps_timing_info_present_flag) {

        vps->vps_num_units_in_tick               = get_bits_long(gb, 32);

        vps->vps_time_scale                      = get_bits_long(gb, 32);

        vps->vps_poc_proportional_to_timing_flag = get_bits1(gb);

        if (vps->vps_poc_proportional_to_timing_flag)

            vps->vps_num_ticks_poc_diff_one = get_ue_golomb_long(gb) + 1;

        vps->vps_num_hrd_parameters = get_ue_golomb_long(gb);

        if (vps->vps_num_hrd_parameters > (unsigned)vps->vps_num_layer_sets) {

            av_log(s->avctx, AV_LOG_ERROR,

                   "vps_num_hrd_parameters %d is invalid\n", vps->vps_num_hrd_parameters);

            goto err;

        }

        for (i = 0; i < vps->vps_num_hrd_parameters; i++) {

            int common_inf_present = 1;

            get_ue_golomb_long(gb); // hrd_layer_set_idx

            if (i)

                common_inf_present = get_bits1(gb);

            decode_hrd(s, common_inf_present, vps->vps_max_sub_layers);

        }

    }

    get_bits1(gb); /* vps_extension_flag */

    if (get_bits_left(gb) < 0) {

        av_log(s->avctx, AV_LOG_ERROR,

               "Overread VPS by %d bits\n", -get_bits_left(gb));

        goto err;

    }

    if (s->vps_list[vps_id] &&

        !memcmp(s->vps_list[vps_id]->data, vps_buf->data, vps_buf->size)) {

        av_buffer_unref(&vps_buf);

    } else {

        remove_vps(s, vps_id);

        s->vps_list[vps_id] = vps_buf;

    }

    return 0;

err:

    av_buffer_unref(&vps_buf);

    return AVERROR_INVALIDDATA;

}


static void probe_group_enter(const char *name, int type)

{

    int64_t count = -1;

    octx.prefix =

        av_realloc(octx.prefix, sizeof(PrintElement) * (octx.level + 1));

    if (!octx.prefix || !name) {

        fprintf(stderr, "Out of memory\n");

        exit(1);

    }

    if (octx.level) {

        PrintElement *parent = octx.prefix + octx.level -1;

        if (parent->type == ARRAY)

            count = parent->nb_elems;

        parent->nb_elems++;

    }

    octx.prefix[octx.level++] = (PrintElement){name, type, count, 0};

}


static gboolean tcp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)

{

    CharDriverState *chr = opaque;

    TCPCharDriver *s = chr->opaque;

    uint8_t buf[READ_BUF_LEN];

    int len, size;

    if (!s->connected || s->max_size <= 0) {

        return TRUE;

    }

    len = sizeof(buf);

    if (len > s->max_size)

        len = s->max_size;

    size = tcp_chr_recv(chr, (void *)buf, len);

    if (size == 0) {

        /* connection closed */

        s->connected = 0;

        if (s->listen_chan) {

            s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN, tcp_chr_accept, chr);

        }

        if (s->tag) {

            g_source_remove(s->tag);

            s->tag = 0;

        }

        g_io_channel_unref(s->chan);

        s->chan = NULL;

        closesocket(s->fd);

        s->fd = -1;

        qemu_chr_be_event(chr, CHR_EVENT_CLOSED);

    } else if (size > 0) {

        if (s->do_telnetopt)

            tcp_chr_process_IAC_bytes(chr, s, buf, &size);

        if (size > 0)

            qemu_chr_be_write(chr, buf, size);

    }

    return TRUE;

}


static void wmv2_add_block(Wmv2Context *w, DCTELEM *block1, uint8_t *dst, int stride, int n){

    MpegEncContext * const s= &w->s;

    switch(w->abt_type_table[n]){

    case 0:

        if (s->block_last_index[n] >= 0) {

            s->dsp.idct_add (dst, stride, block1);

        }

        break;

    case 1:

        simple_idct84_add(dst           , stride, block1);

        simple_idct84_add(dst + 4*stride, stride, w->abt_block2[n]);

        memset(w->abt_block2[n], 0, 64*sizeof(DCTELEM));

        break;

    case 2:

        simple_idct48_add(dst           , stride, block1);

        simple_idct48_add(dst + 4       , stride, w->abt_block2[n]);

        memset(w->abt_block2[n], 0, 64*sizeof(DCTELEM));

        break;

    default:

        av_log(s->avctx, AV_LOG_ERROR, "internal error in WMV2 abt\n");

    }

}


static int msrle_decode_init(AVCodecContext *avctx)

{

    MsrleContext *s = (MsrleContext *)avctx->priv_data;

    int i, j;

    unsigned char *palette;

    s->avctx = avctx;

    avctx->pix_fmt = PIX_FMT_PAL8;

    avctx->has_b_frames = 0;

    s->frame.data[0] = s->prev_frame.data[0] = NULL;

    /* convert palette */

    palette = (unsigned char *)s->avctx->extradata;

    memset (s->palette, 0, 256 * 4);

    for (i = 0, j = 0; i < s->avctx->extradata_size / 4; i++, j += 4)

        s->palette[i] =

            (palette[j + 2] << 16) |

            (palette[j + 1] <<  8) |

            (palette[j + 0] <<  0);

    return 0;

}


static void mpeg_decode_extension(AVCodecContext *avctx,

                                  UINT8 *buf, int buf_size)

{

    Mpeg1Context *s1 = avctx->priv_data;

    MpegEncContext *s = &s1->mpeg_enc_ctx;

    int ext_type;

    init_get_bits(&s->gb, buf, buf_size);

    ext_type = get_bits(&s->gb, 4);

    switch(ext_type) {

    case 0x1:

        /* sequence ext */

        mpeg_decode_sequence_extension(s);

        break;

    case 0x3:

        /* quant matrix extension */

        mpeg_decode_quant_matrix_extension(s);

        break;

    case 0x8:

        /* picture extension */

        mpeg_decode_picture_coding_extension(s);

        break;

    }

}


static int vorbis_parse_setup_hdr_residues(vorbis_context *vc)

{

    GetBitContext *gb = &vc->gb;

    uint_fast8_t i, j, k;

    vc->residue_count = get_bits(gb, 6)+1;

    vc->residues      = av_mallocz(vc->residue_count * sizeof(vorbis_residue));

    AV_DEBUG(" There are %d residues. \n", vc->residue_count);

    for (i = 0; i < vc->residue_count; ++i) {

        vorbis_residue *res_setup = &vc->residues[i];

        uint_fast8_t cascade[64];

        uint_fast8_t high_bits;

        uint_fast8_t low_bits;

        res_setup->type = get_bits(gb, 16);

        AV_DEBUG(" %d. residue type %d \n", i, res_setup->type);

        res_setup->begin          = get_bits(gb, 24);

        res_setup->end            = get_bits(gb, 24);

        res_setup->partition_size = get_bits(gb, 24) + 1;

        /* Validations to prevent a buffer overflow later. */

        if (res_setup->begin>res_setup->end ||

            res_setup->end > vc->avccontext->channels * vc->blocksize[1] / (res_setup->type == 2 ? 1 : 2) ||

            (res_setup->end-res_setup->begin) / res_setup->partition_size > V_MAX_PARTITIONS) {

            av_log(vc->avccontext, AV_LOG_ERROR, "partition out of bounds: type, begin, end, size, blocksize: %"PRIdFAST16", %"PRIdFAST32", %"PRIdFAST32", %u, %"PRIdFAST32"\n", res_setup->type, res_setup->begin, res_setup->end, res_setup->partition_size, vc->blocksize[1] / 2);

            return -1;

        }

        res_setup->classifications = get_bits(gb, 6) + 1;

        GET_VALIDATED_INDEX(res_setup->classbook, 8, vc->codebook_count)

        res_setup->ptns_to_read =

            (res_setup->end - res_setup->begin) / res_setup->partition_size;

        res_setup->classifs = av_malloc(res_setup->ptns_to_read *

                                        vc->audio_channels *

                                        sizeof(*res_setup->classifs));

        if (!res_setup->classifs)

            return AVERROR(ENOMEM);

        AV_DEBUG("    begin %d end %d part.size %d classif.s %d classbook %d \n", res_setup->begin, res_setup->end, res_setup->partition_size,

          res_setup->classifications, res_setup->classbook);

        for (j = 0; j < res_setup->classifications; ++j) {

            high_bits = 0;

            low_bits  = get_bits(gb, 3);

            if (get_bits1(gb))

                high_bits = get_bits(gb, 5);

            cascade[j] = (high_bits << 3) + low_bits;

            AV_DEBUG("     %d class casscade depth: %d \n", j, ilog(cascade[j]));

        }

        res_setup->maxpass = 0;

        for (j = 0; j < res_setup->classifications; ++j) {

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

                if (cascade[j]&(1 << k)) {

                    GET_VALIDATED_INDEX(res_setup->books[j][k], 8, vc->codebook_count)

                    AV_DEBUG("     %d class casscade depth %d book: %d \n", j, k, res_setup->books[j][k]);

                    if (k>res_setup->maxpass)

                        res_setup->maxpass = k;

                } else {

                    res_setup->books[j][k] = -1;

                }

            }

        }

    }

    return 0;

}


static int mp3_read_header(AVFormatContext *s,

                           AVFormatParameters *ap)

{

    AVStream *st;

    int64_t off;

    st = av_new_stream(s, 0);

    if (!st)

        return AVERROR(ENOMEM);

    st->codec->codec_type = CODEC_TYPE_AUDIO;

    st->codec->codec_id = CODEC_ID_MP3;

    st->need_parsing = AVSTREAM_PARSE_FULL;

    st->start_time = 0;

    ff_id3v1_read(s);

    ff_id3v2_read(s);

    off = url_ftell(s->pb);

    if (mp3_parse_vbr_tags(s, st, off) < 0)

        url_fseek(s->pb, off, SEEK_SET);

    /* the parameters will be extracted from the compressed bitstream */

    return 0;

}


int ff_query_formats_all(AVFilterContext *ctx)

{

    return default_query_formats_common(ctx, ff_all_channel_counts);

}


static void put_pixels_clamped_c(const int16_t *block, uint8_t *av_restrict pixels,

                                 ptrdiff_t line_size)

{

    int i;

    /* read the pixels */

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

        pixels[0] = av_clip_uint8(block[0]);

        pixels[1] = av_clip_uint8(block[1]);

        pixels[2] = av_clip_uint8(block[2]);

        pixels[3] = av_clip_uint8(block[3]);

        pixels[4] = av_clip_uint8(block[4]);

        pixels[5] = av_clip_uint8(block[5]);

        pixels[6] = av_clip_uint8(block[6]);

        pixels[7] = av_clip_uint8(block[7]);

        pixels += line_size;

        block  += 8;

    }

}


static void m68k_cpu_class_init(ObjectClass *c, void *data)
{
    M68kCPUClass *mcc = M68K_CPU_CLASS(c);
    CPUClass *cc = CPU_CLASS(c);
    DeviceClass *dc = DEVICE_CLASS(c);
    mcc->parent_realize = dc->realize;
    dc->realize = m68k_cpu_realizefn;
    mcc->parent_reset = cc->reset;
    cc->reset = m68k_cpu_reset;
    cc->class_by_name = m68k_cpu_class_by_name;
    cc->has_work = m68k_cpu_has_work;
    cc->do_interrupt = m68k_cpu_do_interrupt;
    cc->cpu_exec_interrupt = m68k_cpu_exec_interrupt;
    cc->dump_state = m68k_cpu_dump_state;
    cc->set_pc = m68k_cpu_set_pc;
    cc->gdb_read_register = m68k_cpu_gdb_read_register;
    cc->gdb_write_register = m68k_cpu_gdb_write_register;
#ifdef CONFIG_USER_ONLY
    cc->handle_mmu_fault = m68k_cpu_handle_mmu_fault;
#else
    cc->get_phys_page_debug = m68k_cpu_get_phys_page_debug;
#endif
    cc->cpu_exec_enter = m68k_cpu_exec_enter;
    cc->cpu_exec_exit = m68k_cpu_exec_exit;
    dc->vmsd = &vmstate_m68k_cpu;
    cc->gdb_num_core_regs = 18;
    cc->gdb_core_xml_file = "cf-core.xml";
}


static const uint8_t *read_huffman_tables(FourXContext *f, const uint8_t * const buf){

    int frequency[512];

    uint8_t flag[512];

    int up[512];

    uint8_t len_tab[257];

    int bits_tab[257];

    int start, end;

    const uint8_t *ptr= buf;

    int j;

    memset(frequency, 0, sizeof(frequency));

    memset(up, -1, sizeof(up));

    start= *ptr++;

    end= *ptr++;

    for(;;){

        int i;

        for(i=start; i<=end; i++){

            frequency[i]= *ptr++;

        }

        start= *ptr++;

        if(start==0) break;

        end= *ptr++;

    }

    frequency[256]=1;

    while((ptr - buf)&3) ptr++; // 4byte align

    for(j=257; j<512; j++){

        int min_freq[2]= {256*256, 256*256};

        int smallest[2]= {0, 0};

        int i;

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

            if(frequency[i] == 0) continue;

            if(frequency[i] < min_freq[1]){

                if(frequency[i] < min_freq[0]){

                    min_freq[1]= min_freq[0]; smallest[1]= smallest[0];

                    min_freq[0]= frequency[i];smallest[0]= i;

                }else{

                    min_freq[1]= frequency[i];smallest[1]= i;

                }

            }

        }

        if(min_freq[1] == 256*256) break;

        frequency[j]= min_freq[0] + min_freq[1];

        flag[ smallest[0] ]= 0;

        flag[ smallest[1] ]= 1;

        up[ smallest[0] ]=

        up[ smallest[1] ]= j;

        frequency[ smallest[0] ]= frequency[ smallest[1] ]= 0;

    }

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

        int node;

        int len=0;

        int bits=0;

        for(node= j; up[node] != -1; node= up[node]){

            bits += flag[node]<<len;

            len++;

            if(len > 31) av_log(f->avctx, AV_LOG_ERROR, "vlc length overflow\n"); //can this happen at all ?

        }

        bits_tab[j]= bits;

        len_tab[j]= len;

    }

    init_vlc(&f->pre_vlc, ACDC_VLC_BITS, 257,

             len_tab , 1, 1,

             bits_tab, 4, 4, 0);

    return ptr;

}


void sws_rgb2rgb_init(int flags){

#if (defined(HAVE_MMX2) || defined(HAVE_3DNOW) || defined(HAVE_MMX))  && defined(CONFIG_GPL)

	if(flags & SWS_CPU_CAPS_MMX2)

		rgb2rgb_init_MMX2();

	else if(flags & SWS_CPU_CAPS_3DNOW)

		rgb2rgb_init_3DNOW();

	else if(flags & SWS_CPU_CAPS_MMX)

		rgb2rgb_init_MMX();

	else

#endif /* defined(HAVE_MMX2) || defined(HAVE_3DNOW) || defined(HAVE_MMX) */

		rgb2rgb_init_C();

}


int cpu_exec(CPUState *env1)

{

#define DECLARE_HOST_REGS 1

#include "hostregs_helper.h"

#if defined(TARGET_SPARC)

#if defined(reg_REGWPTR)

    uint32_t *saved_regwptr;

#endif

#endif

    int ret, interrupt_request;

    long (*gen_func)(void);

    TranslationBlock *tb;

    uint8_t *tc_ptr;

    if (cpu_halted(env1) == EXCP_HALTED)

        return EXCP_HALTED;

    cpu_single_env = env1;

    /* first we save global registers */

#define SAVE_HOST_REGS 1

#include "hostregs_helper.h"

    env = env1;

    SAVE_GLOBALS();

    env_to_regs();

#if defined(TARGET_I386)

    /* put eflags in CPU temporary format */

    CC_SRC = env->eflags & (CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C);

    DF = 1 - (2 * ((env->eflags >> 10) & 1));

    CC_OP = CC_OP_EFLAGS;

    env->eflags &= ~(DF_MASK | CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C);

#elif defined(TARGET_SPARC)

#if defined(reg_REGWPTR)

    saved_regwptr = REGWPTR;

#endif

#elif defined(TARGET_M68K)

    env->cc_op = CC_OP_FLAGS;

    env->cc_dest = env->sr & 0xf;

    env->cc_x = (env->sr >> 4) & 1;

#elif defined(TARGET_ALPHA)

#elif defined(TARGET_ARM)

#elif defined(TARGET_PPC)

#elif defined(TARGET_MIPS)

#elif defined(TARGET_SH4)

#elif defined(TARGET_CRIS)

    /* XXXXX */

#else

#error unsupported target CPU

#endif

    env->exception_index = -1;

    /* prepare setjmp context for exception handling */

    for(;;) {

        if (setjmp(env->jmp_env) == 0) {

            env->current_tb = NULL;

            /* if an exception is pending, we execute it here */

            if (env->exception_index >= 0) {

                if (env->exception_index >= EXCP_INTERRUPT) {

                    /* exit request from the cpu execution loop */

                    ret = env->exception_index;

                    break;

                } else if (env->user_mode_only) {

                    /* if user mode only, we simulate a fake exception

                       which will be handled outside the cpu execution

                       loop */

#if defined(TARGET_I386)

                    do_interrupt_user(env->exception_index,

                                      env->exception_is_int,

                                      env->error_code,

                                      env->exception_next_eip);

#endif

                    ret = env->exception_index;

                    break;

                } else {

#if defined(TARGET_I386)

                    /* simulate a real cpu exception. On i386, it can

                       trigger new exceptions, but we do not handle

                       double or triple faults yet. */

                    do_interrupt(env->exception_index,

                                 env->exception_is_int,

                                 env->error_code,

                                 env->exception_next_eip, 0);

                    /* successfully delivered */

                    env->old_exception = -1;

#elif defined(TARGET_PPC)

                    do_interrupt(env);

#elif defined(TARGET_MIPS)

                    do_interrupt(env);

#elif defined(TARGET_SPARC)

                    do_interrupt(env->exception_index);

#elif defined(TARGET_ARM)

                    do_interrupt(env);

#elif defined(TARGET_SH4)

		    do_interrupt(env);

#elif defined(TARGET_ALPHA)

                    do_interrupt(env);

#elif defined(TARGET_CRIS)

                    do_interrupt(env);

#elif defined(TARGET_M68K)

                    do_interrupt(0);

#endif

                }

                env->exception_index = -1;

            }

#ifdef USE_KQEMU

            if (kqemu_is_ok(env) && env->interrupt_request == 0) {

                int ret;

                env->eflags = env->eflags | cc_table[CC_OP].compute_all() | (DF & DF_MASK);

                ret = kqemu_cpu_exec(env);

                /* put eflags in CPU temporary format */

                CC_SRC = env->eflags & (CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C);

                DF = 1 - (2 * ((env->eflags >> 10) & 1));

                CC_OP = CC_OP_EFLAGS;

                env->eflags &= ~(DF_MASK | CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C);

                if (ret == 1) {

                    /* exception */

                    longjmp(env->jmp_env, 1);

                } else if (ret == 2) {

                    /* softmmu execution needed */

                } else {

                    if (env->interrupt_request != 0) {

                        /* hardware interrupt will be executed just after */

                    } else {

                        /* otherwise, we restart */

                        longjmp(env->jmp_env, 1);

                    }

                }

            }

#endif

            T0 = 0; /* force lookup of first TB */

            for(;;) {

                SAVE_GLOBALS();

                interrupt_request = env->interrupt_request;

                if (__builtin_expect(interrupt_request, 0)

#if defined(TARGET_I386)

			&& env->hflags & HF_GIF_MASK

#endif

				) {

                    if (interrupt_request & CPU_INTERRUPT_DEBUG) {

                        env->interrupt_request &= ~CPU_INTERRUPT_DEBUG;

                        env->exception_index = EXCP_DEBUG;

                        cpu_loop_exit();

                    }

#if defined(TARGET_ARM) || defined(TARGET_SPARC) || defined(TARGET_MIPS) || \

    defined(TARGET_PPC) || defined(TARGET_ALPHA) || defined(TARGET_CRIS)

                    if (interrupt_request & CPU_INTERRUPT_HALT) {

                        env->interrupt_request &= ~CPU_INTERRUPT_HALT;

                        env->halted = 1;

                        env->exception_index = EXCP_HLT;

                        cpu_loop_exit();

                    }

#endif

#if defined(TARGET_I386)

                    if ((interrupt_request & CPU_INTERRUPT_SMI) &&

                        !(env->hflags & HF_SMM_MASK)) {

                        svm_check_intercept(SVM_EXIT_SMI);

                        env->interrupt_request &= ~CPU_INTERRUPT_SMI;

                        do_smm_enter();

                        BREAK_CHAIN;

                    } else if ((interrupt_request & CPU_INTERRUPT_NMI) &&

                        !(env->hflags & HF_NMI_MASK)) {

                        env->interrupt_request &= ~CPU_INTERRUPT_NMI;

                        env->hflags |= HF_NMI_MASK;

                        do_interrupt(EXCP02_NMI, 0, 0, 0, 1);

                        BREAK_CHAIN;

                    } else if ((interrupt_request & CPU_INTERRUPT_HARD) &&

                        (env->eflags & IF_MASK || env->hflags & HF_HIF_MASK) &&

                        !(env->hflags & HF_INHIBIT_IRQ_MASK)) {

                        int intno;

                        svm_check_intercept(SVM_EXIT_INTR);

                        env->interrupt_request &= ~(CPU_INTERRUPT_HARD | CPU_INTERRUPT_VIRQ);

                        intno = cpu_get_pic_interrupt(env);

                        if (loglevel & CPU_LOG_TB_IN_ASM) {

                            fprintf(logfile, "Servicing hardware INT=0x%02x\n", intno);

                        }

                        do_interrupt(intno, 0, 0, 0, 1);

                        /* ensure that no TB jump will be modified as

                           the program flow was changed */

                        BREAK_CHAIN;

#if !defined(CONFIG_USER_ONLY)

                    } else if ((interrupt_request & CPU_INTERRUPT_VIRQ) &&

                        (env->eflags & IF_MASK) && !(env->hflags & HF_INHIBIT_IRQ_MASK)) {

                         int intno;

                         /* FIXME: this should respect TPR */

                         env->interrupt_request &= ~CPU_INTERRUPT_VIRQ;

                         svm_check_intercept(SVM_EXIT_VINTR);

                         intno = ldl_phys(env->vm_vmcb + offsetof(struct vmcb, control.int_vector));

                         if (loglevel & CPU_LOG_TB_IN_ASM)

                             fprintf(logfile, "Servicing virtual hardware INT=0x%02x\n", intno);

	                 do_interrupt(intno, 0, 0, -1, 1);

                         stl_phys(env->vm_vmcb + offsetof(struct vmcb, control.int_ctl),

                                  ldl_phys(env->vm_vmcb + offsetof(struct vmcb, control.int_ctl)) & ~V_IRQ_MASK);

                        BREAK_CHAIN;

#endif

                    }

#elif defined(TARGET_PPC)

#if 0

                    if ((interrupt_request & CPU_INTERRUPT_RESET)) {

                        cpu_ppc_reset(env);

                    }

#endif

                    if (interrupt_request & CPU_INTERRUPT_HARD) {

                        ppc_hw_interrupt(env);

                        if (env->pending_interrupts == 0)

                            env->interrupt_request &= ~CPU_INTERRUPT_HARD;

                        BREAK_CHAIN;

                    }

#elif defined(TARGET_MIPS)

                    if ((interrupt_request & CPU_INTERRUPT_HARD) &&

                        (env->CP0_Status & env->CP0_Cause & CP0Ca_IP_mask) &&

                        (env->CP0_Status & (1 << CP0St_IE)) &&

                        !(env->CP0_Status & (1 << CP0St_EXL)) &&

                        !(env->CP0_Status & (1 << CP0St_ERL)) &&

                        !(env->hflags & MIPS_HFLAG_DM)) {

                        /* Raise it */

                        env->exception_index = EXCP_EXT_INTERRUPT;

                        env->error_code = 0;

                        do_interrupt(env);

                        BREAK_CHAIN;

                    }

#elif defined(TARGET_SPARC)

                    if ((interrupt_request & CPU_INTERRUPT_HARD) &&

			(env->psret != 0)) {

			int pil = env->interrupt_index & 15;

			int type = env->interrupt_index & 0xf0;

			if (((type == TT_EXTINT) &&

			     (pil == 15 || pil > env->psrpil)) ||

			    type != TT_EXTINT) {

			    env->interrupt_request &= ~CPU_INTERRUPT_HARD;

			    do_interrupt(env->interrupt_index);

			    env->interrupt_index = 0;

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

                            cpu_check_irqs(env);

#endif

                        BREAK_CHAIN;

			}

		    } else if (interrupt_request & CPU_INTERRUPT_TIMER) {

			//do_interrupt(0, 0, 0, 0, 0);

			env->interrupt_request &= ~CPU_INTERRUPT_TIMER;

		    }

#elif defined(TARGET_ARM)

                    if (interrupt_request & CPU_INTERRUPT_FIQ

                        && !(env->uncached_cpsr & CPSR_F)) {

                        env->exception_index = EXCP_FIQ;

                        do_interrupt(env);

                        BREAK_CHAIN;

                    }

                    /* ARMv7-M interrupt return works by loading a magic value

                       into the PC.  On real hardware the load causes the

                       return to occur.  The qemu implementation performs the

                       jump normally, then does the exception return when the

                       CPU tries to execute code at the magic address.

                       This will cause the magic PC value to be pushed to

                       the stack if an interrupt occured at the wrong time.

                       We avoid this by disabling interrupts when

                       pc contains a magic address.  */

                    if (interrupt_request & CPU_INTERRUPT_HARD

                        && ((IS_M(env) && env->regs[15] < 0xfffffff0)

                            || !(env->uncached_cpsr & CPSR_I))) {

                        env->exception_index = EXCP_IRQ;

                        do_interrupt(env);

                        BREAK_CHAIN;

                    }

#elif defined(TARGET_SH4)

                    if (interrupt_request & CPU_INTERRUPT_HARD) {

                        do_interrupt(env);

                        BREAK_CHAIN;

                    }

#elif defined(TARGET_ALPHA)

                    if (interrupt_request & CPU_INTERRUPT_HARD) {

                        do_interrupt(env);

                        BREAK_CHAIN;

                    }

#elif defined(TARGET_CRIS)

                    if (interrupt_request & CPU_INTERRUPT_HARD) {

                        do_interrupt(env);

                        BREAK_CHAIN;

                    }

#elif defined(TARGET_M68K)

                    if (interrupt_request & CPU_INTERRUPT_HARD

                        && ((env->sr & SR_I) >> SR_I_SHIFT)

                            < env->pending_level) {

                        /* Real hardware gets the interrupt vector via an

                           IACK cycle at this point.  Current emulated

                           hardware doesn't rely on this, so we

                           provide/save the vector when the interrupt is

                           first signalled.  */

                        env->exception_index = env->pending_vector;

                        do_interrupt(1);

                        BREAK_CHAIN;

                    }

#endif

                   /* Don't use the cached interupt_request value,

                      do_interrupt may have updated the EXITTB flag. */

                    if (env->interrupt_request & CPU_INTERRUPT_EXITTB) {

                        env->interrupt_request &= ~CPU_INTERRUPT_EXITTB;

                        /* ensure that no TB jump will be modified as

                           the program flow was changed */

                        BREAK_CHAIN;

                    }

                    if (interrupt_request & CPU_INTERRUPT_EXIT) {

                        env->interrupt_request &= ~CPU_INTERRUPT_EXIT;

                        env->exception_index = EXCP_INTERRUPT;

                        cpu_loop_exit();

                    }

                }

#ifdef DEBUG_EXEC

                if ((loglevel & CPU_LOG_TB_CPU)) {

                    /* restore flags in standard format */

                    regs_to_env();

#if defined(TARGET_I386)

                    env->eflags = env->eflags | cc_table[CC_OP].compute_all() | (DF & DF_MASK);

                    cpu_dump_state(env, logfile, fprintf, X86_DUMP_CCOP);

                    env->eflags &= ~(DF_MASK | CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C);

#elif defined(TARGET_ARM)

                    cpu_dump_state(env, logfile, fprintf, 0);

#elif defined(TARGET_SPARC)

		    REGWPTR = env->regbase + (env->cwp * 16);

		    env->regwptr = REGWPTR;

                    cpu_dump_state(env, logfile, fprintf, 0);

#elif defined(TARGET_PPC)

                    cpu_dump_state(env, logfile, fprintf, 0);

#elif defined(TARGET_M68K)

                    cpu_m68k_flush_flags(env, env->cc_op);

                    env->cc_op = CC_OP_FLAGS;

                    env->sr = (env->sr & 0xffe0)

                              | env->cc_dest | (env->cc_x << 4);

                    cpu_dump_state(env, logfile, fprintf, 0);

#elif defined(TARGET_MIPS)

                    cpu_dump_state(env, logfile, fprintf, 0);

#elif defined(TARGET_SH4)

		    cpu_dump_state(env, logfile, fprintf, 0);

#elif defined(TARGET_ALPHA)

                    cpu_dump_state(env, logfile, fprintf, 0);

#elif defined(TARGET_CRIS)

                    cpu_dump_state(env, logfile, fprintf, 0);

#else

#error unsupported target CPU

#endif

                }

#endif

                tb = tb_find_fast();

#ifdef DEBUG_EXEC

                if ((loglevel & CPU_LOG_EXEC)) {

                    fprintf(logfile, "Trace 0x%08lx [" TARGET_FMT_lx "] %s\n",

                            (long)tb->tc_ptr, tb->pc,

                            lookup_symbol(tb->pc));

                }

#endif

                RESTORE_GLOBALS();

                /* see if we can patch the calling TB. When the TB

                   spans two pages, we cannot safely do a direct

                   jump. */

                {

                    if (T0 != 0 &&

#if USE_KQEMU

                        (env->kqemu_enabled != 2) &&

#endif

                        tb->page_addr[1] == -1) {

                    spin_lock(&tb_lock);

                    tb_add_jump((TranslationBlock *)(long)(T0 & ~3), T0 & 3, tb);

                    spin_unlock(&tb_lock);

                }

                }

                tc_ptr = tb->tc_ptr;

                env->current_tb = tb;

                /* execute the generated code */

                gen_func = (void *)tc_ptr;

#if defined(__sparc__)

                __asm__ __volatile__("call	%0\n\t"

                                     "mov	%%o7,%%i0"

                                     : /* no outputs */

                                     : "r" (gen_func)

                                     : "i0", "i1", "i2", "i3", "i4", "i5",

                                       "o0", "o1", "o2", "o3", "o4", "o5",

                                       "l0", "l1", "l2", "l3", "l4", "l5",

                                       "l6", "l7");

#elif defined(__hppa__)

                asm volatile ("ble  0(%%sr4,%1)\n"

                              "copy %%r31,%%r18\n"

                              "copy %%r28,%0\n"

                              : "=r" (T0)

                              : "r" (gen_func)

                              : "r1", "r2", "r3", "r4", "r5", "r6", "r7",

                                "r8", "r9", "r10", "r11", "r12", "r13",

                                "r18", "r19", "r20", "r21", "r22", "r23",

                                "r24", "r25", "r26", "r27", "r28", "r29",

                                "r30", "r31");

#elif defined(__arm__)

                asm volatile ("mov pc, %0\n\t"

                              ".global exec_loop\n\t"

                              "exec_loop:\n\t"

                              : /* no outputs */

                              : "r" (gen_func)

                              : "r1", "r2", "r3", "r8", "r9", "r10", "r12", "r14");

#elif defined(__ia64)

		struct fptr {

			void *ip;

			void *gp;

		} fp;

		fp.ip = tc_ptr;

		fp.gp = code_gen_buffer + 2 * (1 << 20);

		(*(void (*)(void)) &fp)();

#else

                T0 = gen_func();

#endif

                env->current_tb = NULL;

                /* reset soft MMU for next block (it can currently

                   only be set by a memory fault) */

#if defined(TARGET_I386) && !defined(CONFIG_SOFTMMU)

                if (env->hflags & HF_SOFTMMU_MASK) {

                    env->hflags &= ~HF_SOFTMMU_MASK;

                    /* do not allow linking to another block */

                    T0 = 0;

                }

#endif

#if defined(USE_KQEMU)

#define MIN_CYCLE_BEFORE_SWITCH (100 * 1000)

                if (kqemu_is_ok(env) &&

                    (cpu_get_time_fast() - env->last_io_time) >= MIN_CYCLE_BEFORE_SWITCH) {

                    cpu_loop_exit();

                }

#endif

            } /* for(;;) */

        } else {

            env_to_regs();

        }

    } /* for(;;) */

#if defined(TARGET_I386)

    /* restore flags in standard format */

    env->eflags = env->eflags | cc_table[CC_OP].compute_all() | (DF & DF_MASK);

#elif defined(TARGET_ARM)

    /* XXX: Save/restore host fpu exception state?.  */

#elif defined(TARGET_SPARC)

#if defined(reg_REGWPTR)

    REGWPTR = saved_regwptr;

#endif

#elif defined(TARGET_PPC)

#elif defined(TARGET_M68K)

    cpu_m68k_flush_flags(env, env->cc_op);

    env->cc_op = CC_OP_FLAGS;

    env->sr = (env->sr & 0xffe0)

              | env->cc_dest | (env->cc_x << 4);

#elif defined(TARGET_MIPS)

#elif defined(TARGET_SH4)

#elif defined(TARGET_ALPHA)

#elif defined(TARGET_CRIS)

    /* XXXXX */

#else

#error unsupported target CPU

#endif

    /* restore global registers */

    RESTORE_GLOBALS();

#include "hostregs_helper.h"

    /* fail safe : never use cpu_single_env outside cpu_exec() */

    cpu_single_env = NULL;

    return ret;

}


static av_always_inline void decode_line(FFV1Context *s, int w, int_fast16_t *sample[2], int plane_index, int bits){

    PlaneContext * const p= &s->plane[plane_index];

    RangeCoder * const c= &s->c;

    int x;

    int run_count=0;

    int run_mode=0;

    int run_index= s->run_index;

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

        int diff, context, sign;

        context= get_context(s, sample[1] + x, sample[0] + x, sample[1] + x);

        if(context < 0){

            context= -context;

            sign=1;

        }else

            sign=0;

        if(s->ac){

            diff= get_symbol_inline(c, p->state[context], 1);

        }else{

            if(context == 0 && run_mode==0) run_mode=1;

            if(run_mode){

                if(run_count==0 && run_mode==1){

                    if(get_bits1(&s->gb)){

                        run_count = 1<<ff_log2_run[run_index];

                        if(x + run_count <= w) run_index++;

                    }else{

                        if(ff_log2_run[run_index]) run_count = get_bits(&s->gb, ff_log2_run[run_index]);

                        else run_count=0;

                        if(run_index) run_index--;

                        run_mode=2;

                    }

                }

                run_count--;

                if(run_count < 0){

                    run_mode=0;

                    run_count=0;

                    diff= get_vlc_symbol(&s->gb, &p->vlc_state[context], bits);

                    if(diff>=0) diff++;

                }else

                    diff=0;

            }else

                diff= get_vlc_symbol(&s->gb, &p->vlc_state[context], bits);

//            printf("count:%d index:%d, mode:%d, x:%d y:%d pos:%d\n", run_count, run_index, run_mode, x, y, get_bits_count(&s->gb));

        }

        if(sign) diff= -diff;

        sample[1][x]= (predict(sample[1] + x, sample[0] + x) + diff) & ((1<<bits)-1);

    }

    s->run_index= run_index;

}


static void do_video_out(AVFormatContext *s,

                         AVOutputStream *ost,

                         AVInputStream *ist,

                         AVPicture *picture1,

                         int *frame_size)

{

    int n1, n2, nb, i, ret, frame_number, dec_frame_rate;

    AVPicture *picture, *picture2, *pict;

    AVPicture picture_tmp1, picture_tmp2;

    UINT8 *video_buffer;

    UINT8 *buf = NULL, *buf1 = NULL;

    AVCodecContext *enc, *dec;

#define VIDEO_BUFFER_SIZE (1024*1024)

    enc = &ost->st->codec;

    dec = &ist->st->codec;

    frame_number = ist->frame_number;

    dec_frame_rate = ist->st->r_frame_rate;

    //    fprintf(stderr, "\n%d", dec_frame_rate);

    /* first drop frame if needed */

    n1 = ((INT64)frame_number * enc->frame_rate) / dec_frame_rate;

    n2 = (((INT64)frame_number + 1) * enc->frame_rate) / dec_frame_rate;

    nb = n2 - n1;

    if (nb <= 0)

        return;

    video_buffer= av_malloc(VIDEO_BUFFER_SIZE);

    if(!video_buffer) return;

    /* deinterlace : must be done before any resize */

    if (do_deinterlace) {

        int size;

        /* create temporary picture */

        size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);

        buf1 = av_malloc(size);

        if (!buf1)

            return;

        picture2 = &picture_tmp2;

        avpicture_fill(picture2, buf1, dec->pix_fmt, dec->width, dec->height);

        if (avpicture_deinterlace(picture2, picture1,

                                  dec->pix_fmt, dec->width, dec->height) < 0) {

            /* if error, do not deinterlace */

            av_free(buf1);

            buf1 = NULL;

            picture2 = picture1;

        }

    } else {

        picture2 = picture1;

    }

    /* convert pixel format if needed */

    if (enc->pix_fmt != dec->pix_fmt) {

        int size;

        /* create temporary picture */

        size = avpicture_get_size(enc->pix_fmt, dec->width, dec->height);

        buf = av_malloc(size);

        if (!buf)

            return;

        pict = &picture_tmp1;

        avpicture_fill(pict, buf, enc->pix_fmt, dec->width, dec->height);

        if (img_convert(pict, enc->pix_fmt,

                        picture2, dec->pix_fmt,

                        dec->width, dec->height) < 0) {

            fprintf(stderr, "pixel format conversion not handled\n");

            goto the_end;

        }

    } else {

        pict = picture2;

    }

    /* XXX: resampling could be done before raw format convertion in

       some cases to go faster */

    /* XXX: only works for YUV420P */

    if (ost->video_resample) {

        picture = &ost->pict_tmp;

        img_resample(ost->img_resample_ctx, picture, pict);

    } else {

        picture = pict;

    }

    nb=1;

    /* duplicates frame if needed */

    /* XXX: pb because no interleaving */

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

        if (enc->codec_id != CODEC_ID_RAWVIDEO) {

            /* handles sameq here. This is not correct because it may

               not be a global option */

            if (same_quality) {

                enc->quality = dec->quality;

            }

            ret = avcodec_encode_video(enc,

                                       video_buffer, VIDEO_BUFFER_SIZE,

                                       picture);

            //enc->frame_number = enc->real_pict_num;

            s->oformat->write_packet(s, ost->index, video_buffer, ret, 0);

            *frame_size = ret;

            //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",

            //        enc->frame_number-1, enc->real_pict_num, ret,

            //        enc->pict_type);

        } else {

            write_picture(s, ost->index, picture, enc->pix_fmt, enc->width, enc->height);

        }

    }

    the_end:

    av_free(buf);

    av_free(buf1);

    av_free(video_buffer);

}


static void add_codec(FFServerStream *stream, AVCodecContext *av)

{

    AVStream *st;

    if(stream->nb_streams >= FF_ARRAY_ELEMS(stream->streams))

        return;

    /* compute default parameters */

    switch(av->codec_type) {

    case AVMEDIA_TYPE_AUDIO:

        if (av->bit_rate == 0)

            av->bit_rate = 64000;

        if (av->sample_rate == 0)

            av->sample_rate = 22050;

        if (av->channels == 0)

            av->channels = 1;

        break;

    case AVMEDIA_TYPE_VIDEO:

        if (av->bit_rate == 0)

            av->bit_rate = 64000;

        if (av->time_base.num == 0){

            av->time_base.den = 5;

            av->time_base.num = 1;

        }

        if (av->width == 0 || av->height == 0) {

            av->width = 160;

            av->height = 128;

        }

        /* Bitrate tolerance is less for streaming */

        if (av->bit_rate_tolerance == 0)

            av->bit_rate_tolerance = FFMAX(av->bit_rate / 4,

                      (int64_t)av->bit_rate*av->time_base.num/av->time_base.den);

        if (av->qmin == 0)

            av->qmin = 3;

        if (av->qmax == 0)

            av->qmax = 31;

        if (av->max_qdiff == 0)

            av->max_qdiff = 3;

        av->qcompress = 0.5;

        av->qblur = 0.5;

        if (!av->nsse_weight)

            av->nsse_weight = 8;

        av->frame_skip_cmp = FF_CMP_DCTMAX;

        if (!av->me_method)

            av->me_method = ME_EPZS;

        av->rc_buffer_aggressivity = 1.0;

        if (!av->rc_eq)

            av->rc_eq = av_strdup("tex^qComp");

        if (!av->i_quant_factor)

            av->i_quant_factor = -0.8;

        if (!av->b_quant_factor)

            av->b_quant_factor = 1.25;

        if (!av->b_quant_offset)

            av->b_quant_offset = 1.25;

        if (!av->rc_max_rate)

            av->rc_max_rate = av->bit_rate * 2;

        if (av->rc_max_rate && !av->rc_buffer_size) {

            av->rc_buffer_size = av->rc_max_rate;

        }

        break;

    default:

        abort();

    }

    st = av_mallocz(sizeof(AVStream));

    if (!st)

        return;

    st->codec = avcodec_alloc_context3(NULL);

    stream->streams[stream->nb_streams++] = st;

    memcpy(st->codec, av, sizeof(AVCodecContext));

}