static void spapr_dt_rtas(sPAPRMachineState *spapr, void *fdt)

{

    int rtas;

    GString *hypertas = g_string_sized_new(256);

    GString *qemu_hypertas = g_string_sized_new(256);

    uint32_t refpoints[] = { cpu_to_be32(0x4), cpu_to_be32(0x4) };

    uint64_t max_hotplug_addr = spapr->hotplug_memory.base +

        memory_region_size(&spapr->hotplug_memory.mr);

    uint32_t lrdr_capacity[] = {

        cpu_to_be32(max_hotplug_addr >> 32),

        cpu_to_be32(max_hotplug_addr & 0xffffffff),

        0, cpu_to_be32(SPAPR_MEMORY_BLOCK_SIZE),

        cpu_to_be32(max_cpus / smp_threads),

    };

    _FDT(rtas = fdt_add_subnode(fdt, 0, "rtas"));

    /* hypertas */

    add_str(hypertas, "hcall-pft");

    add_str(hypertas, "hcall-term");

    add_str(hypertas, "hcall-dabr");

    add_str(hypertas, "hcall-interrupt");

    add_str(hypertas, "hcall-tce");

    add_str(hypertas, "hcall-vio");

    add_str(hypertas, "hcall-splpar");

    add_str(hypertas, "hcall-bulk");

    add_str(hypertas, "hcall-set-mode");

    add_str(hypertas, "hcall-sprg0");

    add_str(hypertas, "hcall-copy");

    add_str(hypertas, "hcall-debug");

    add_str(qemu_hypertas, "hcall-memop1");

    if (!kvm_enabled() || kvmppc_spapr_use_multitce()) {

        add_str(hypertas, "hcall-multi-tce");

    }

    if (spapr->resize_hpt != SPAPR_RESIZE_HPT_DISABLED) {

        add_str(hypertas, "hcall-hpt-resize");

    }

    _FDT(fdt_setprop(fdt, rtas, "ibm,hypertas-functions",

                     hypertas->str, hypertas->len));

    g_string_free(hypertas, TRUE);

    _FDT(fdt_setprop(fdt, rtas, "qemu,hypertas-functions",

                     qemu_hypertas->str, qemu_hypertas->len));

    g_string_free(qemu_hypertas, TRUE);

    _FDT(fdt_setprop(fdt, rtas, "ibm,associativity-reference-points",

                     refpoints, sizeof(refpoints)));

    _FDT(fdt_setprop_cell(fdt, rtas, "rtas-error-log-max",

                          RTAS_ERROR_LOG_MAX));

    _FDT(fdt_setprop_cell(fdt, rtas, "rtas-event-scan-rate",

                          RTAS_EVENT_SCAN_RATE));

    if (msi_nonbroken) {

        _FDT(fdt_setprop(fdt, rtas, "ibm,change-msix-capable", NULL, 0));

    }

    /*

     * According to PAPR, rtas ibm,os-term does not guarantee a return

     * back to the guest cpu.

     *

     * While an additional ibm,extended-os-term property indicates

     * that rtas call return will always occur. Set this property.

     */

    _FDT(fdt_setprop(fdt, rtas, "ibm,extended-os-term", NULL, 0));

    _FDT(fdt_setprop(fdt, rtas, "ibm,lrdr-capacity",

                     lrdr_capacity, sizeof(lrdr_capacity)));

    spapr_dt_rtas_tokens(fdt, rtas);

}


static ssize_t nbd_co_receive_request(NBDRequest *req,

                                      struct nbd_request *request)

{

    NBDClient *client = req->client;

    uint32_t command;

    ssize_t rc;

    g_assert(qemu_in_coroutine());

    client->recv_coroutine = qemu_coroutine_self();

    nbd_update_can_read(client);

    rc = nbd_receive_request(client->ioc, request);

    if (rc < 0) {

        if (rc != -EAGAIN) {

            rc = -EIO;

        }

        goto out;

    }

    TRACE("Decoding type");

    command = request->type & NBD_CMD_MASK_COMMAND;

    if (command != NBD_CMD_WRITE) {

        /* No payload, we are ready to read the next request.  */

        req->complete = true;

    }

    if (command == NBD_CMD_DISC) {

        /* Special case: we're going to disconnect without a reply,

         * whether or not flags, from, or len are bogus */

        TRACE("Request type is DISCONNECT");

        rc = -EIO;

        goto out;

    }

    /* Check for sanity in the parameters, part 1.  Defer as many

     * checks as possible until after reading any NBD_CMD_WRITE

     * payload, so we can try and keep the connection alive.  */

    if ((request->from + request->len) < request->from) {

        LOG("integer overflow detected, you're probably being attacked");

        rc = -EINVAL;

        goto out;

    }

    if (command == NBD_CMD_READ || command == NBD_CMD_WRITE) {

        if (request->len > NBD_MAX_BUFFER_SIZE) {

            LOG("len (%" PRIu32" ) is larger than max len (%u)",

                request->len, NBD_MAX_BUFFER_SIZE);

            rc = -EINVAL;

            goto out;

        }

        req->data = blk_try_blockalign(client->exp->blk, request->len);

        if (req->data == NULL) {

            rc = -ENOMEM;

            goto out;

        }

    }

    if (command == NBD_CMD_WRITE) {

        TRACE("Reading %" PRIu32 " byte(s)", request->len);

        if (read_sync(client->ioc, req->data, request->len) != request->len) {

            LOG("reading from socket failed");

            rc = -EIO;

            goto out;

        }

        req->complete = true;

    }

    /* Sanity checks, part 2. */

    if (request->from + request->len > client->exp->size) {

        LOG("operation past EOF; From: %" PRIu64 ", Len: %" PRIu32

            ", Size: %" PRIu64, request->from, request->len,

            (uint64_t)client->exp->size);

        rc = command == NBD_CMD_WRITE ? -ENOSPC : -EINVAL;

        goto out;

    }

    if (request->type & ~NBD_CMD_MASK_COMMAND & ~NBD_CMD_FLAG_FUA) {

        LOG("unsupported flags (got 0x%x)",

            request->type & ~NBD_CMD_MASK_COMMAND);

        rc = -EINVAL;

        goto out;

    }

    rc = 0;

out:

    client->recv_coroutine = NULL;

    nbd_update_can_read(client);

    return rc;

}


static void qio_channel_socket_listen_worker(QIOTask *task,

                                             gpointer opaque)

{

    QIOChannelSocket *ioc = QIO_CHANNEL_SOCKET(qio_task_get_source(task));

    SocketAddressLegacy *addr = opaque;

    Error *err = NULL;

    qio_channel_socket_listen_sync(ioc, addr, &err);

    qio_task_set_error(task, err);

}


static void smp_parse(QemuOpts *opts)

{

    if (opts) {

        unsigned cpus    = qemu_opt_get_number(opts, "cpus", 0);

        unsigned sockets = qemu_opt_get_number(opts, "sockets", 0);

        unsigned cores   = qemu_opt_get_number(opts, "cores", 0);

        unsigned threads = qemu_opt_get_number(opts, "threads", 0);

        /* compute missing values, prefer sockets over cores over threads */

        if (cpus == 0 || sockets == 0) {

            sockets = sockets > 0 ? sockets : 1;

            cores = cores > 0 ? cores : 1;

            threads = threads > 0 ? threads : 1;

            if (cpus == 0) {

                cpus = cores * threads * sockets;

            }

        } else if (cores == 0) {

            threads = threads > 0 ? threads : 1;

            cores = cpus / (sockets * threads);

        } else if (threads == 0) {

            threads = cpus / (cores * sockets);

        } else if (sockets * cores * threads < cpus) {

            error_report("cpu topology: "

                         "sockets (%u) * cores (%u) * threads (%u) < "

                         "smp_cpus (%u)",

                         sockets, cores, threads, cpus);

            exit(1);

        }

        max_cpus = qemu_opt_get_number(opts, "maxcpus", cpus);

        if (sockets * cores * threads > max_cpus) {

            error_report("cpu topology: "

                         "sockets (%u) * cores (%u) * threads (%u) > "

                         "maxcpus (%u)",

                         sockets, cores, threads, max_cpus);

            exit(1);

        }

        smp_cpus = cpus;

        smp_cores = cores > 0 ? cores : 1;

        smp_threads = threads > 0 ? threads : 1;

    }

    if (max_cpus == 0) {

        max_cpus = smp_cpus;

    }

    if (max_cpus > MAX_CPUMASK_BITS) {

        error_report("unsupported number of maxcpus");

        exit(1);

    }

    if (max_cpus < smp_cpus) {

        error_report("maxcpus must be equal to or greater than smp");

        exit(1);

    }

    if (smp_cpus > 1 || smp_cores > 1 || smp_threads > 1) {

        Error *blocker = NULL;

        error_setg(&blocker, QERR_REPLAY_NOT_SUPPORTED, "smp");

        replay_add_blocker(blocker);

    }

}


static void vp8_idct_dc_add4y_c(uint8_t *dst, int16_t block[4][16], ptrdiff_t stride)

{

    vp8_idct_dc_add_c(dst+ 0, block[0], stride);

    vp8_idct_dc_add_c(dst+ 4, block[1], stride);

    vp8_idct_dc_add_c(dst+ 8, block[2], stride);

    vp8_idct_dc_add_c(dst+12, block[3], stride);

}


static void rtl8139_io_writeb(void *opaque, uint8_t addr, uint32_t val)

{

    RTL8139State *s = opaque;

    switch (addr)

    {

        case MAC0 ... MAC0+5:

            s->phys[addr - MAC0] = val;

            qemu_format_nic_info_str(qemu_get_queue(s->nic), s->phys);

            break;

        case MAC0+6 ... MAC0+7:

            /* reserved */

            break;

        case MAR0 ... MAR0+7:

            s->mult[addr - MAR0] = val;

            break;

        case ChipCmd:

            rtl8139_ChipCmd_write(s, val);

            break;

        case Cfg9346:

            rtl8139_Cfg9346_write(s, val);

            break;

        case TxConfig: /* windows driver sometimes writes using byte-lenth call */

            rtl8139_TxConfig_writeb(s, val);

            break;

        case Config0:

            rtl8139_Config0_write(s, val);

            break;

        case Config1:

            rtl8139_Config1_write(s, val);

            break;

        case Config3:

            rtl8139_Config3_write(s, val);

            break;

        case Config4:

            rtl8139_Config4_write(s, val);

            break;

        case Config5:

            rtl8139_Config5_write(s, val);

            break;

        case MediaStatus:

            /* ignore */

            DPRINTF("not implemented write(b) to MediaStatus val=0x%02x\n",

                val);

            break;

        case HltClk:

            DPRINTF("HltClk write val=0x%08x\n", val);

            if (val == 'R')

            {

                s->clock_enabled = 1;

            }

            else if (val == 'H')

            {

                s->clock_enabled = 0;

            }

            break;

        case TxThresh:

            DPRINTF("C+ TxThresh write(b) val=0x%02x\n", val);

            s->TxThresh = val;

            break;

        case TxPoll:

            DPRINTF("C+ TxPoll write(b) val=0x%02x\n", val);

            if (val & (1 << 7))

            {

                DPRINTF("C+ TxPoll high priority transmission (not "

                    "implemented)\n");

                //rtl8139_cplus_transmit(s);

            }

            if (val & (1 << 6))

            {

                DPRINTF("C+ TxPoll normal priority transmission\n");

                rtl8139_cplus_transmit(s);

            }

            break;

        default:

            DPRINTF("not implemented write(b) addr=0x%x val=0x%02x\n", addr,

                val);

            break;

    }

}


static void test_validate_fail_union(TestInputVisitorData *data,

                                      const void *unused)

{

    UserDefUnion *tmp = NULL;

    Error *err = NULL;

    Visitor *v;

    v = validate_test_init(data, "{ 'type': 'b', 'data' : { 'integer': 42 } }");

    visit_type_UserDefUnion(v, &tmp, NULL, &err);

    g_assert(err);

    qapi_free_UserDefUnion(tmp);

}


static void nabm_writew (void *opaque, uint32_t addr, uint32_t val)

{

    PCIAC97LinkState *d = opaque;

    AC97LinkState *s = &d->ac97;

    AC97BusMasterRegs *r = NULL;

    uint32_t index = addr - s->base[1];

    switch (index) {

    case PI_SR:

    case PO_SR:

    case MC_SR:

        r = &s->bm_regs[GET_BM (index)];

        r->sr |= val & ~(SR_RO_MASK | SR_WCLEAR_MASK);

        update_sr (s, r, r->sr & ~(val & SR_WCLEAR_MASK));

        dolog ("SR[%d] <- %#x (sr %#x)\n", GET_BM (index), val, r->sr);

        break;

    default:

        dolog ("U nabm writew %#x <- %#x\n", addr, val);

        break;

    }

}


static void musicpal_misc_write(void *opaque, target_phys_addr_t offset,

                                uint64_t value, unsigned size)

{

}


void HELPER(ucf64_cmpd)(float64 a, float64 b, uint32_t c, CPUUniCore32State *env)

{

    int flag;

    flag = float64_compare_quiet(a, b, &env->ucf64.fp_status);

    env->CF = 0;

    switch (c & 0x7) {

    case 0: /* F */

        break;

    case 1: /* UN */

        if (flag == 2) {

            env->CF = 1;

        }

        break;

    case 2: /* EQ */

        if (flag == 0) {

            env->CF = 1;

        }

        break;

    case 3: /* UEQ */

        if ((flag == 0) || (flag == 2)) {

            env->CF = 1;

        }

        break;

    case 4: /* OLT */

        if (flag == -1) {

            env->CF = 1;

        }

        break;

    case 5: /* ULT */

        if ((flag == -1) || (flag == 2)) {

            env->CF = 1;

        }

        break;

    case 6: /* OLE */

        if ((flag == -1) || (flag == 0)) {

            env->CF = 1;

        }

        break;

    case 7: /* ULE */

        if (flag != 1) {

            env->CF = 1;

        }

        break;

    }

    env->ucf64.xregs[UC32_UCF64_FPSCR] = (env->CF << 29)

                    | (env->ucf64.xregs[UC32_UCF64_FPSCR] & 0x0fffffff);

}


static void acpi_align_size(GArray *blob, unsigned align)

{

    /* Align size to multiple of given size. This reduces the chance

     * we need to change size in the future (breaking cross version migration).

     */

    g_array_set_size(blob, (ROUND_UP(acpi_data_len(blob), align) +

                            g_array_get_element_size(blob) - 1) /

                             g_array_get_element_size(blob));

}


int fd_start_outgoing_migration(MigrationState *s, const char *fdname)

{

    s->fd = monitor_get_fd(s->mon, fdname);

    if (s->fd == -1) {

        DPRINTF("fd_migration: invalid file descriptor identifier\n");

        goto err_after_get_fd;

    }

    if (fcntl(s->fd, F_SETFL, O_NONBLOCK) == -1) {

        DPRINTF("Unable to set nonblocking mode on file descriptor\n");

        goto err_after_open;

    }

    s->get_error = fd_errno;

    s->write = fd_write;

    s->close = fd_close;

    migrate_fd_connect(s);

    return 0;

err_after_open:

    close(s->fd);

err_after_get_fd:

    return -1;

}


int msmpeg4_decode_picture_header(MpegEncContext * s)

{

    int code;

#if 0

{

int i;

for(i=0; i<s->gb.size*8; i++)

    printf("%d", get_bits1(&s->gb));

//    get_bits1(&s->gb);

printf("END\n");

return -1;

}

#endif

    if(s->msmpeg4_version==1){

        int start_code, num;

        start_code = (get_bits(&s->gb, 16)<<16) | get_bits(&s->gb, 16);

        if(start_code!=0x00000100){

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

            return -1;

        }

        num= get_bits(&s->gb, 5); // frame number */

    }

    s->pict_type = get_bits(&s->gb, 2) + 1;

    if (s->pict_type != I_TYPE &&

        s->pict_type != P_TYPE){

        fprintf(stderr, "invalid picture type\n");

        return -1;

    }

#if 0

{

    static int had_i=0;

    if(s->pict_type == I_TYPE) had_i=1;

    if(!had_i) return -1;

}

#endif

    s->qscale = get_bits(&s->gb, 5);

    if (s->pict_type == I_TYPE) {

        code = get_bits(&s->gb, 5);

        if(s->msmpeg4_version==1){

            if(code==0 || code>s->mb_height){

                fprintf(stderr, "invalid slice height %d\n", code);

                return -1;

            }

            s->slice_height = code;

        }else{

            /* 0x17: one slice, 0x18: two slices, ... */

            if (code < 0x17){

                fprintf(stderr, "error, slice code was %X\n", code);

                return -1;

            }

            s->slice_height = s->mb_height / (code - 0x16);

        }

        switch(s->msmpeg4_version){

        case 1:

        case 2:

            s->rl_chroma_table_index = 2;

            s->rl_table_index = 2;

            s->dc_table_index = 0; //not used

            break;

        case 3:

            s->rl_chroma_table_index = decode012(&s->gb);

            s->rl_table_index = decode012(&s->gb);

            s->dc_table_index = get_bits1(&s->gb);

            break;

        case 4:

            msmpeg4_decode_ext_header(s, (2+5+5+17+7)/8);

            if(s->bit_rate > MBAC_BITRATE) s->per_mb_rl_table= get_bits1(&s->gb);

            else                           s->per_mb_rl_table= 0;

            if(!s->per_mb_rl_table){

                s->rl_chroma_table_index = decode012(&s->gb);

                s->rl_table_index = decode012(&s->gb);

            }

            s->dc_table_index = get_bits1(&s->gb);

            s->inter_intra_pred= 0;

            break;

        }

        s->no_rounding = 1;

/*	printf("qscale:%d rlc:%d rl:%d dc:%d mbrl:%d slice:%d   \n",

		s->qscale,

		s->rl_chroma_table_index,

		s->rl_table_index,

		s->dc_table_index,

                s->per_mb_rl_table,

                s->slice_height);*/

    } else {

        switch(s->msmpeg4_version){

        case 1:

        case 2:

            if(s->msmpeg4_version==1)

                s->use_skip_mb_code = 1;

            else

                s->use_skip_mb_code = get_bits1(&s->gb);

            s->rl_table_index = 2;

            s->rl_chroma_table_index = s->rl_table_index;

            s->dc_table_index = 0; //not used

            s->mv_table_index = 0;

            break;

        case 3:

            s->use_skip_mb_code = get_bits1(&s->gb);

            s->rl_table_index = decode012(&s->gb);

            s->rl_chroma_table_index = s->rl_table_index;

            s->dc_table_index = get_bits1(&s->gb);

            s->mv_table_index = get_bits1(&s->gb);

            break;

        case 4:

            s->use_skip_mb_code = get_bits1(&s->gb);

            if(s->bit_rate > MBAC_BITRATE) s->per_mb_rl_table= get_bits1(&s->gb);

            else                           s->per_mb_rl_table= 0;

            if(!s->per_mb_rl_table){

                s->rl_table_index = decode012(&s->gb);

                s->rl_chroma_table_index = s->rl_table_index;

            }

            s->dc_table_index = get_bits1(&s->gb);

            s->mv_table_index = get_bits1(&s->gb);

            s->inter_intra_pred= (s->width*s->height < 320*240 && s->bit_rate<=II_BITRATE);

            break;

        }

/*	printf("skip:%d rl:%d rlc:%d dc:%d mv:%d mbrl:%d qp:%d   \n",

		s->use_skip_mb_code,

		s->rl_table_index,

		s->rl_chroma_table_index,

		s->dc_table_index,

		s->mv_table_index,

                s->per_mb_rl_table,

                s->qscale);*/

	if(s->flipflop_rounding){

	    s->no_rounding ^= 1;

	}else{

	    s->no_rounding = 0;

	}

    }

//printf("%d %d %d %d %d\n", s->pict_type, s->bit_rate, s->inter_intra_pred, s->width, s->height);

    s->esc3_level_length= 0;

    s->esc3_run_length= 0;

#ifdef DEBUG

    printf("*****frame %d:\n", frame_count++);

#endif

    return 0;

}


static void usbnet_receive(void *opaque, const uint8_t *buf, size_t size)

{

    USBNetState *s = opaque;

    struct rndis_packet_msg_type *msg;

    if (s->rndis) {

        msg = (struct rndis_packet_msg_type *) s->in_buf;

        if (!s->rndis_state == RNDIS_DATA_INITIALIZED)

            return;

        if (size + sizeof(struct rndis_packet_msg_type) > sizeof(s->in_buf))

            return;

        memset(msg, 0, sizeof(struct rndis_packet_msg_type));

        msg->MessageType = cpu_to_le32(RNDIS_PACKET_MSG);

        msg->MessageLength = cpu_to_le32(size + sizeof(struct rndis_packet_msg_type));

        msg->DataOffset = cpu_to_le32(sizeof(struct rndis_packet_msg_type) - 8);

        msg->DataLength = cpu_to_le32(size);

        /* msg->OOBDataOffset;

         * msg->OOBDataLength;

         * msg->NumOOBDataElements;

         * msg->PerPacketInfoOffset;

         * msg->PerPacketInfoLength;

         * msg->VcHandle;

         * msg->Reserved;

         */

        memcpy(msg + 1, buf, size);

        s->in_len = size + sizeof(struct rndis_packet_msg_type);

    } else {

        if (size > sizeof(s->in_buf))

            return;

        memcpy(s->in_buf, buf, size);

        s->in_len = size;

    }

    s->in_ptr = 0;

}


static int v9fs_walk_marshal(V9fsPDU *pdu, uint16_t nwnames, V9fsQID *qids)

{

    int i;

    size_t offset = 7;

    offset += pdu_marshal(pdu, offset, "w", nwnames);

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

        offset += pdu_marshal(pdu, offset, "Q", &qids[i]);

    }

    return offset;

}


static void close_unused_images(BlockDriverState *top, BlockDriverState *base,

                                const char *base_id)

{

    BlockDriverState *intermediate;

    intermediate = top->backing_hd;

    while (intermediate) {

        BlockDriverState *unused;

        /* reached base */

        if (intermediate == base) {

            break;

        }

        unused = intermediate;

        intermediate = intermediate->backing_hd;

        unused->backing_hd = NULL;

        bdrv_delete(unused);

    }

    top->backing_hd = base;

}


static void qemu_paio_submit(struct qemu_paiocb *aiocb)

{

    aiocb->ret = -EINPROGRESS;

    aiocb->active = 0;

    mutex_lock(&lock);

    if (idle_threads == 0 && cur_threads < max_threads)

        spawn_thread();

    TAILQ_INSERT_TAIL(&request_list, aiocb, node);

    mutex_unlock(&lock);

    cond_signal(&cond);

}


static int raw_media_changed(BlockDriverState *bs)

{

    return bdrv_media_changed(bs->file->bs);

}


bool is_tcg_gen_code(uintptr_t tc_ptr)

{

    /* This can be called during code generation, code_gen_buffer_max_size

       is used instead of code_gen_ptr for upper boundary checking */

    return (tc_ptr >= (uintptr_t)tcg_ctx.code_gen_buffer &&

            tc_ptr < (uintptr_t)(tcg_ctx.code_gen_buffer +

                    tcg_ctx.code_gen_buffer_max_size));

}


int ff_h264_decode_sei(H264Context *h)

{

    while (get_bits_left(&h->gb) > 16) {

        int size = 0;

        int type = 0;

        int ret  = 0;

        int last = 0;

        while (get_bits_left(&h->gb) >= 8 &&

               (last = get_bits(&h->gb, 8)) == 255) {

            type += 255;

        }

        type += last;

        last = 0;

        while (get_bits_left(&h->gb) >= 8 &&

               (last = get_bits(&h->gb, 8)) == 255) {

            size += 255;

        }

        size += last;

        if (size > get_bits_left(&h->gb) / 8) {

            av_log(h->avctx, AV_LOG_ERROR, "SEI type %d truncated at %d\n",

                   type, get_bits_left(&h->gb));

            return AVERROR_INVALIDDATA;

        }

        switch (type) {

        case SEI_TYPE_PIC_TIMING: // Picture timing SEI

            ret = decode_picture_timing(h);

            if (ret < 0)

                return ret;

            break;

        case SEI_TYPE_USER_DATA_UNREGISTERED:

            ret = decode_unregistered_user_data(h, size);

            if (ret < 0)

                return ret;

            break;

        case SEI_TYPE_RECOVERY_POINT:

            ret = decode_recovery_point(h);

            if (ret < 0)

                return ret;

            break;

        case SEI_TYPE_BUFFERING_PERIOD:

            ret = decode_buffering_period(h);

            if (ret < 0)

                return ret;

            break;

        case SEI_TYPE_FRAME_PACKING:

            ret = decode_frame_packing_arrangement(h);

            if (ret < 0)

                return ret;

            break;

        case SEI_TYPE_DISPLAY_ORIENTATION:

            ret = decode_display_orientation(h);

            if (ret < 0)

                return ret;

            break;

        default:

            av_log(h->avctx, AV_LOG_DEBUG, "unknown SEI type %d\n", type);

            skip_bits(&h->gb, 8 * size);

        }

        // FIXME check bits here

        align_get_bits(&h->gb);

    }

    return 0;

}


av_cold int ff_yuv2rgb_c_init_tables(SwsContext *c, const int inv_table[4],

                                     int fullRange, int brightness,

                                     int contrast, int saturation)

{

    const int isRgb = c->dstFormat == AV_PIX_FMT_RGB32     ||

                      c->dstFormat == AV_PIX_FMT_RGB32_1   ||

                      c->dstFormat == AV_PIX_FMT_BGR24     ||

                      c->dstFormat == AV_PIX_FMT_RGB565BE  ||

                      c->dstFormat == AV_PIX_FMT_RGB565LE  ||

                      c->dstFormat == AV_PIX_FMT_RGB555BE  ||

                      c->dstFormat == AV_PIX_FMT_RGB555LE  ||

                      c->dstFormat == AV_PIX_FMT_RGB444BE  ||

                      c->dstFormat == AV_PIX_FMT_RGB444LE  ||

                      c->dstFormat == AV_PIX_FMT_RGB8      ||

                      c->dstFormat == AV_PIX_FMT_RGB4      ||

                      c->dstFormat == AV_PIX_FMT_RGB4_BYTE ||

                      c->dstFormat == AV_PIX_FMT_MONOBLACK;

    const int isNotNe = c->dstFormat == AV_PIX_FMT_NE(RGB565LE, RGB565BE) ||

                        c->dstFormat == AV_PIX_FMT_NE(RGB555LE, RGB555BE) ||

                        c->dstFormat == AV_PIX_FMT_NE(RGB444LE, RGB444BE) ||

                        c->dstFormat == AV_PIX_FMT_NE(BGR565LE, BGR565BE) ||

                        c->dstFormat == AV_PIX_FMT_NE(BGR555LE, BGR555BE) ||

                        c->dstFormat == AV_PIX_FMT_NE(BGR444LE, BGR444BE);

    const int bpp = c->dstFormatBpp;

    uint8_t *y_table;

    uint16_t *y_table16;

    uint32_t *y_table32;

    int i, base, rbase, gbase, bbase, abase, needAlpha;

    const int yoffs = fullRange ? 384 : 326;

    int64_t crv =  inv_table[0];

    int64_t cbu =  inv_table[1];

    int64_t cgu = -inv_table[2];

    int64_t cgv = -inv_table[3];

    int64_t cy  = 1 << 16;

    int64_t oy  = 0;

    int64_t yb  = 0;

    if (!fullRange) {

        cy = (cy * 255) / 219;

        oy = 16 << 16;

    } else {

        crv = (crv * 224) / 255;

        cbu = (cbu * 224) / 255;

        cgu = (cgu * 224) / 255;

        cgv = (cgv * 224) / 255;

    }

    cy   = (cy  * contrast)              >> 16;

    crv  = (crv * contrast * saturation) >> 32;

    cbu  = (cbu * contrast * saturation) >> 32;

    cgu  = (cgu * contrast * saturation) >> 32;

    cgv  = (cgv * contrast * saturation) >> 32;

    oy  -= 256 * brightness;

    c->uOffset = 0x0400040004000400LL;

    c->vOffset = 0x0400040004000400LL;

    c->yCoeff  = roundToInt16(cy  * 8192) * 0x0001000100010001ULL;

    c->vrCoeff = roundToInt16(crv * 8192) * 0x0001000100010001ULL;

    c->ubCoeff = roundToInt16(cbu * 8192) * 0x0001000100010001ULL;

    c->vgCoeff = roundToInt16(cgv * 8192) * 0x0001000100010001ULL;

    c->ugCoeff = roundToInt16(cgu * 8192) * 0x0001000100010001ULL;

    c->yOffset = roundToInt16(oy  *    8) * 0x0001000100010001ULL;

    c->yuv2rgb_y_coeff   = (int16_t)roundToInt16(cy  << 13);

    c->yuv2rgb_y_offset  = (int16_t)roundToInt16(oy  <<  9);

    c->yuv2rgb_v2r_coeff = (int16_t)roundToInt16(crv << 13);

    c->yuv2rgb_v2g_coeff = (int16_t)roundToInt16(cgv << 13);

    c->yuv2rgb_u2g_coeff = (int16_t)roundToInt16(cgu << 13);

    c->yuv2rgb_u2b_coeff = (int16_t)roundToInt16(cbu << 13);

    //scale coefficients by cy

    crv = ((crv << 16) + 0x8000) / cy;

    cbu = ((cbu << 16) + 0x8000) / cy;

    cgu = ((cgu << 16) + 0x8000) / cy;

    cgv = ((cgv << 16) + 0x8000) / cy;

    av_free(c->yuvTable);

    switch (bpp) {

    case 1:

        c->yuvTable = av_malloc(1024);

        y_table     = c->yuvTable;

        yb = -(384 << 16) - oy;

        for (i = 0; i < 1024 - 110; i++) {

            y_table[i + 110]  = av_clip_uint8((yb + 0x8000) >> 16) >> 7;

            yb               += cy;

        }

        fill_table(c->table_gU, 1, cgu, y_table + yoffs);

        fill_gv_table(c->table_gV, 1, cgv);

        break;

    case 4:

    case 4 | 128:

        rbase       = isRgb ? 3 : 0;

        gbase       = 1;

        bbase       = isRgb ? 0 : 3;

        c->yuvTable = av_malloc(1024 * 3);

        y_table     = c->yuvTable;

        yb = -(384 << 16) - oy;

        for (i = 0; i < 1024 - 110; i++) {

            int yval                = av_clip_uint8((yb + 0x8000) >> 16);

            y_table[i + 110]        = (yval >> 7)        << rbase;

            y_table[i +  37 + 1024] = ((yval + 43) / 85) << gbase;

            y_table[i + 110 + 2048] = (yval >> 7)        << bbase;

            yb += cy;

        }

        fill_table(c->table_rV, 1, crv, y_table + yoffs);

        fill_table(c->table_gU, 1, cgu, y_table + yoffs + 1024);

        fill_table(c->table_bU, 1, cbu, y_table + yoffs + 2048);

        fill_gv_table(c->table_gV, 1, cgv);

        break;

    case 8:

        rbase       = isRgb ? 5 : 0;

        gbase       = isRgb ? 2 : 3;

        bbase       = isRgb ? 0 : 6;

        c->yuvTable = av_malloc(1024 * 3);

        y_table     = c->yuvTable;

        yb = -(384 << 16) - oy;

        for (i = 0; i < 1024 - 38; i++) {

            int yval               = av_clip_uint8((yb + 0x8000) >> 16);

            y_table[i + 16]        = ((yval + 18) / 36) << rbase;

            y_table[i + 16 + 1024] = ((yval + 18) / 36) << gbase;

            y_table[i + 37 + 2048] = ((yval + 43) / 85) << bbase;

            yb += cy;

        }

        fill_table(c->table_rV, 1, crv, y_table + yoffs);

        fill_table(c->table_gU, 1, cgu, y_table + yoffs + 1024);

        fill_table(c->table_bU, 1, cbu, y_table + yoffs + 2048);

        fill_gv_table(c->table_gV, 1, cgv);

        break;

    case 12:

        rbase       = isRgb ? 8 : 0;

        gbase       = 4;

        bbase       = isRgb ? 0 : 8;

        c->yuvTable = av_malloc(1024 * 3 * 2);

        y_table16   = c->yuvTable;

        yb = -(384 << 16) - oy;

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

            uint8_t yval        = av_clip_uint8((yb + 0x8000) >> 16);

            y_table16[i]        = (yval >> 4) << rbase;

            y_table16[i + 1024] = (yval >> 4) << gbase;

            y_table16[i + 2048] = (yval >> 4) << bbase;

            yb += cy;

        }

        if (isNotNe)

            for (i = 0; i < 1024 * 3; i++)

                y_table16[i] = av_bswap16(y_table16[i]);

        fill_table(c->table_rV, 2, crv, y_table16 + yoffs);

        fill_table(c->table_gU, 2, cgu, y_table16 + yoffs + 1024);

        fill_table(c->table_bU, 2, cbu, y_table16 + yoffs + 2048);

        fill_gv_table(c->table_gV, 2, cgv);

        break;

    case 15:

    case 16:

        rbase       = isRgb ? bpp - 5 : 0;

        gbase       = 5;

        bbase       = isRgb ? 0 : (bpp - 5);

        c->yuvTable = av_malloc(1024 * 3 * 2);

        y_table16   = c->yuvTable;

        yb = -(384 << 16) - oy;

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

            uint8_t yval        = av_clip_uint8((yb + 0x8000) >> 16);

            y_table16[i]        = (yval >> 3)          << rbase;

            y_table16[i + 1024] = (yval >> (18 - bpp)) << gbase;

            y_table16[i + 2048] = (yval >> 3)          << bbase;

            yb += cy;

        }

        if (isNotNe)

            for (i = 0; i < 1024 * 3; i++)

                y_table16[i] = av_bswap16(y_table16[i]);

        fill_table(c->table_rV, 2, crv, y_table16 + yoffs);

        fill_table(c->table_gU, 2, cgu, y_table16 + yoffs + 1024);

        fill_table(c->table_bU, 2, cbu, y_table16 + yoffs + 2048);

        fill_gv_table(c->table_gV, 2, cgv);

        break;

    case 24:

    case 48:

        c->yuvTable = av_malloc(1024);

        y_table     = c->yuvTable;

        yb = -(384 << 16) - oy;

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

            y_table[i]  = av_clip_uint8((yb + 0x8000) >> 16);

            yb         += cy;

        }

        fill_table(c->table_rV, 1, crv, y_table + yoffs);

        fill_table(c->table_gU, 1, cgu, y_table + yoffs);

        fill_table(c->table_bU, 1, cbu, y_table + yoffs);

        fill_gv_table(c->table_gV, 1, cgv);

        break;

    case 32:

        base      = (c->dstFormat == AV_PIX_FMT_RGB32_1 ||

                     c->dstFormat == AV_PIX_FMT_BGR32_1) ? 8 : 0;

        rbase     = base + (isRgb ? 16 : 0);

        gbase     = base + 8;

        bbase     = base + (isRgb ? 0 : 16);

        needAlpha = CONFIG_SWSCALE_ALPHA && isALPHA(c->srcFormat);

        if (!needAlpha)

            abase = (base + 24) & 31;

        c->yuvTable = av_malloc(1024 * 3 * 4);

        y_table32   = c->yuvTable;

        yb = -(384 << 16) - oy;

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

            unsigned yval       = av_clip_uint8((yb + 0x8000) >> 16);

            y_table32[i]        = (yval << rbase) +

                                  (needAlpha ? 0 : (255u << abase));

            y_table32[i + 1024] =  yval << gbase;

            y_table32[i + 2048] =  yval << bbase;

            yb += cy;

        }

        fill_table(c->table_rV, 4, crv, y_table32 + yoffs);

        fill_table(c->table_gU, 4, cgu, y_table32 + yoffs + 1024);

        fill_table(c->table_bU, 4, cbu, y_table32 + yoffs + 2048);

        fill_gv_table(c->table_gV, 4, cgv);

        break;

    default:

        c->yuvTable = NULL;

        if(!isPlanar(c->dstFormat) || bpp <= 24)

            av_log(c, AV_LOG_ERROR, "%ibpp not supported by yuv2rgb\n", bpp);

        return -1;

    }

    return 0;

}


static int vp3_decode_init(AVCodecContext *avctx)

{

    Vp3DecodeContext *s = avctx->priv_data;

    int i;

    s->avctx = avctx;

    s->width = avctx->width;

    s->height = avctx->height;

    avctx->pix_fmt = PIX_FMT_YUV420P;

    avctx->has_b_frames = 0;

    dsputil_init(&s->dsp, avctx);

    /* initialize to an impossible value which will force a recalculation

     * in the first frame decode */

    s->quality_index = -1;

    s->superblock_width = (s->width + 31) / 32;

    s->superblock_height = (s->height + 31) / 32;

    s->superblock_count = s->superblock_width * s->superblock_height * 3 / 2;

    s->u_superblock_start = s->superblock_width * s->superblock_height;

    s->v_superblock_start = s->superblock_width * s->superblock_height * 5 / 4;

    s->superblock_coding = av_malloc(s->superblock_count);

    s->macroblock_width = (s->width + 15) / 16;

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

    s->macroblock_count = s->macroblock_width * s->macroblock_height;

    s->fragment_width = s->width / FRAGMENT_PIXELS;

    s->fragment_height = s->height / FRAGMENT_PIXELS;

    /* fragment count covers all 8x8 blocks for all 3 planes */

    s->fragment_count = s->fragment_width * s->fragment_height * 3 / 2;

    s->u_fragment_start = s->fragment_width * s->fragment_height;

    s->v_fragment_start = s->fragment_width * s->fragment_height * 5 / 4;

    debug_init("  width: %d x %d\n", s->width, s->height);

    debug_init("  superblocks: %d x %d, %d total\n",

        s->superblock_width, s->superblock_height, s->superblock_count);

    debug_init("  macroblocks: %d x %d, %d total\n",

        s->macroblock_width, s->macroblock_height, s->macroblock_count);

    debug_init("  %d fragments, %d x %d, u starts @ %d, v starts @ %d\n",

        s->fragment_count,

        s->fragment_width,

        s->fragment_height,

        s->u_fragment_start,

        s->v_fragment_start);

    s->all_fragments = av_malloc(s->fragment_count * sizeof(Vp3Fragment));

    s->coded_fragment_list = av_malloc(s->fragment_count * sizeof(int));

    s->pixel_addresses_inited = 0;

    /* init VLC tables */

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

        /* Dc histograms */

        init_vlc(&s->dc_vlc[i], 5, 32,

            &dc_bias[i][0][1], 4, 2,

            &dc_bias[i][0][0], 4, 2);

        /* group 1 AC histograms */

        init_vlc(&s->ac_vlc_1[i], 5, 32,

            &ac_bias_0[i][0][1], 4, 2,

            &ac_bias_0[i][0][0], 4, 2);

        /* group 2 AC histograms */

        init_vlc(&s->ac_vlc_2[i], 5, 32,

            &ac_bias_1[i][0][1], 4, 2,

            &ac_bias_1[i][0][0], 4, 2);

        /* group 3 AC histograms */

        init_vlc(&s->ac_vlc_3[i], 5, 32,

            &ac_bias_2[i][0][1], 4, 2,

            &ac_bias_2[i][0][0], 4, 2);

        /* group 4 AC histograms */

        init_vlc(&s->ac_vlc_4[i], 5, 32,

            &ac_bias_3[i][0][1], 4, 2,

            &ac_bias_3[i][0][0], 4, 2);

    }

    /* build quantization table */

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

        quant_index[dequant_index[i]] = i;

    /* work out the block mapping tables */

    s->superblock_fragments = av_malloc(s->superblock_count * 16 * sizeof(int));

    s->superblock_macroblocks = av_malloc(s->superblock_count * 4 * sizeof(int));

    s->macroblock_fragments = av_malloc(s->macroblock_count * 6 * sizeof(int));

    s->macroblock_coded = av_malloc(s->macroblock_count + 1);

    init_block_mapping(s);

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

        s->current_frame.data[i] = NULL;

        s->last_frame.data[i] = NULL;

        s->golden_frame.data[i] = NULL;

    }

    return 0;

}


static void gen_tlbsync(DisasContext *ctx)

{

#if defined(CONFIG_USER_ONLY)

    GEN_PRIV;

#else

    CHK_HV;

    /* tlbsync is a nop for server, ptesync handles delayed tlb flush,

     * embedded however needs to deal with tlbsync. We don't try to be

     * fancy and swallow the overhead of checking for both.

     */

    gen_check_tlb_flush(ctx);

#endif /* defined(CONFIG_USER_ONLY) */

}


static void search_for_ms(AACEncContext *s, ChannelElement *cpe)

{

    int start = 0, i, w, w2, g, sid_sf_boost;

    float M[128], S[128];

    float *L34 = s->scoefs, *R34 = s->scoefs + 128, *M34 = s->scoefs + 128*2, *S34 = s->scoefs + 128*3;

    const float lambda = s->lambda;

    const float mslambda = FFMIN(1.0f, lambda / 120.f);

    SingleChannelElement *sce0 = &cpe->ch[0];

    SingleChannelElement *sce1 = &cpe->ch[1];

    if (!cpe->common_window)

        return;

    for (w = 0; w < sce0->ics.num_windows; w += sce0->ics.group_len[w]) {

        int min_sf_idx_mid = SCALE_MAX_POS;

        int min_sf_idx_side = SCALE_MAX_POS;

        for (g = 0; g < sce0->ics.num_swb; g++) {

            if (!sce0->zeroes[w*16+g] && sce0->band_type[w*16+g] < RESERVED_BT)

                min_sf_idx_mid = FFMIN(min_sf_idx_mid, sce0->sf_idx[w*16+g]);

            if (!sce1->zeroes[w*16+g] && sce1->band_type[w*16+g] < RESERVED_BT)

                min_sf_idx_side = FFMIN(min_sf_idx_side, sce1->sf_idx[w*16+g]);

        }

        start = 0;

        for (g = 0;  g < sce0->ics.num_swb; g++) {

            float bmax = bval2bmax(g * 17.0f / sce0->ics.num_swb) / 0.0045f;

            cpe->ms_mask[w*16+g] = 0;

            if (!cpe->ch[0].zeroes[w*16+g] && !cpe->ch[1].zeroes[w*16+g]) {

                float Mmax = 0.0f, Smax = 0.0f;

                /* Must compute mid/side SF and book for the whole window group */

                for (w2 = 0; w2 < sce0->ics.group_len[w]; w2++) {

                    for (i = 0; i < sce0->ics.swb_sizes[g]; i++) {

                        M[i] = (sce0->coeffs[start+(w+w2)*128+i]

                              + sce1->coeffs[start+(w+w2)*128+i]) * 0.5;

                        S[i] =  M[i]

                              - sce1->coeffs[start+(w+w2)*128+i];

                    }

                    abs_pow34_v(M34, M, sce0->ics.swb_sizes[g]);

                    abs_pow34_v(S34, S, sce0->ics.swb_sizes[g]);

                    for (i = 0; i < sce0->ics.swb_sizes[g]; i++ ) {

                        Mmax = FFMAX(Mmax, M34[i]);

                        Smax = FFMAX(Smax, S34[i]);

                    }

                }

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

                    float dist1 = 0.0f, dist2 = 0.0f;

                    int B0 = 0, B1 = 0;

                    int minidx;

                    int mididx, sididx;

                    int midcb, sidcb;

                    minidx = FFMIN(sce0->sf_idx[w*16+g], sce1->sf_idx[w*16+g]);

                    mididx = av_clip(minidx, min_sf_idx_mid, min_sf_idx_mid + SCALE_MAX_DIFF);

                    sididx = av_clip(minidx - sid_sf_boost * 3, min_sf_idx_side, min_sf_idx_side + SCALE_MAX_DIFF);

                    midcb = find_min_book(Mmax, mididx);

                    sidcb = find_min_book(Smax, sididx);

                    if ((mididx > minidx) || (sididx > minidx)) {

                        /* scalefactor range violation, bad stuff, will decrease quality unacceptably */

                        continue;

                    }

                    /* No CB can be zero */

                    midcb = FFMAX(1,midcb);

                    sidcb = FFMAX(1,sidcb);

                    for (w2 = 0; w2 < sce0->ics.group_len[w]; w2++) {

                        FFPsyBand *band0 = &s->psy.ch[s->cur_channel+0].psy_bands[(w+w2)*16+g];

                        FFPsyBand *band1 = &s->psy.ch[s->cur_channel+1].psy_bands[(w+w2)*16+g];

                        float minthr = FFMIN(band0->threshold, band1->threshold);

                        int b1,b2,b3,b4;

                        for (i = 0; i < sce0->ics.swb_sizes[g]; i++) {

                            M[i] = (sce0->coeffs[start+(w+w2)*128+i]

                                  + sce1->coeffs[start+(w+w2)*128+i]) * 0.5;

                            S[i] =  M[i]

                                  - sce1->coeffs[start+(w+w2)*128+i];

                        }

                        abs_pow34_v(L34, sce0->coeffs+start+(w+w2)*128, sce0->ics.swb_sizes[g]);

                        abs_pow34_v(R34, sce1->coeffs+start+(w+w2)*128, sce0->ics.swb_sizes[g]);

                        abs_pow34_v(M34, M,                         sce0->ics.swb_sizes[g]);

                        abs_pow34_v(S34, S,                         sce0->ics.swb_sizes[g]);

                        dist1 += quantize_band_cost(s, &sce0->coeffs[start + (w+w2)*128],

                                                    L34,

                                                    sce0->ics.swb_sizes[g],

                                                    sce0->sf_idx[(w+w2)*16+g],

                                                    sce0->band_type[(w+w2)*16+g],

                                                    lambda / band0->threshold, INFINITY, &b1, NULL, 0);

                        dist1 += quantize_band_cost(s, &sce1->coeffs[start + (w+w2)*128],

                                                    R34,

                                                    sce1->ics.swb_sizes[g],

                                                    sce1->sf_idx[(w+w2)*16+g],

                                                    sce1->band_type[(w+w2)*16+g],

                                                    lambda / band1->threshold, INFINITY, &b2, NULL, 0);

                        dist2 += quantize_band_cost(s, M,

                                                    M34,

                                                    sce0->ics.swb_sizes[g],

                                                    sce0->sf_idx[(w+w2)*16+g],

                                                    sce0->band_type[(w+w2)*16+g],

                                                    lambda / minthr, INFINITY, &b3, NULL, 0);

                        dist2 += quantize_band_cost(s, S,

                                                    S34,

                                                    sce1->ics.swb_sizes[g],

                                                    sce1->sf_idx[(w+w2)*16+g],

                                                    sce1->band_type[(w+w2)*16+g],

                                                    mslambda / (minthr * bmax), INFINITY, &b4, NULL, 0);

                        B0 += b1+b2;

                        B1 += b3+b4;

                        dist1 -= B0;

                        dist2 -= B1;

                    }

                    cpe->ms_mask[w*16+g] = dist2 <= dist1 && B1 < B0;

                    if (cpe->ms_mask[w*16+g]) {

                        /* Setting the M/S mask is useful with I/S or PNS, but only the flag */

                        if (!cpe->is_mask[w*16+g] && sce0->band_type[w*16+g] != NOISE_BT && sce1->band_type[w*16+g] != NOISE_BT) {

                            sce0->sf_idx[w*16+g] = mididx;

                            sce1->sf_idx[w*16+g] = sididx;

                            sce0->band_type[w*16+g] = midcb;

                            sce1->band_type[w*16+g] = sidcb;

                        }

                        break;

                    } else if (B1 > B0) {

                        /* More boost won't fix this */

                        break;

                    }

                }

            }

            start += sce0->ics.swb_sizes[g];

        }

    }

}


static void net_tx_pkt_do_sw_csum(struct NetTxPkt *pkt)

{

    struct iovec *iov = &pkt->vec[NET_TX_PKT_L2HDR_FRAG];

    uint32_t csum_cntr;

    uint16_t csum = 0;

    uint32_t cso;

    /* num of iovec without vhdr */

    uint32_t iov_len = pkt->payload_frags + NET_TX_PKT_PL_START_FRAG - 1;

    uint16_t csl;

    struct ip_header *iphdr;

    size_t csum_offset = pkt->virt_hdr.csum_start + pkt->virt_hdr.csum_offset;

    /* Put zero to checksum field */

    iov_from_buf(iov, iov_len, csum_offset, &csum, sizeof csum);

    /* Calculate L4 TCP/UDP checksum */

    csl = pkt->payload_len;

    /* add pseudo header to csum */

    iphdr = pkt->vec[NET_TX_PKT_L3HDR_FRAG].iov_base;

    csum_cntr = eth_calc_ip4_pseudo_hdr_csum(iphdr, csl, &cso);

    /* data checksum */

    csum_cntr +=

        net_checksum_add_iov(iov, iov_len, pkt->virt_hdr.csum_start, csl, cso);

    /* Put the checksum obtained into the packet */

    csum = cpu_to_be16(net_checksum_finish(csum_cntr));

    iov_from_buf(iov, iov_len, csum_offset, &csum, sizeof csum);

}


static av_cold int xvid_encode_init(AVCodecContext *avctx)

{

    int xerr, i, ret = -1;

    int xvid_flags = avctx->flags;

    struct xvid_context *x = avctx->priv_data;

    uint16_t *intra, *inter;

    int fd;

    xvid_plugin_single_t      single          = { 0 };

    struct xvid_ff_pass1      rc2pass1        = { 0 };

    xvid_plugin_2pass2_t      rc2pass2        = { 0 };

    xvid_plugin_lumimasking_t masking_l       = { 0 }; /* For lumi masking */

    xvid_plugin_lumimasking_t masking_v       = { 0 }; /* For variance AQ */

    xvid_plugin_ssim_t        ssim            = { 0 };

    xvid_gbl_init_t           xvid_gbl_init   = { 0 };

    xvid_enc_create_t         xvid_enc_create = { 0 };

    xvid_enc_plugin_t         plugins[4];

    x->twopassfd = -1;

    /* Bring in VOP flags from ffmpeg command-line */

    x->vop_flags = XVID_VOP_HALFPEL;              /* Bare minimum quality */

    if (xvid_flags & AV_CODEC_FLAG_4MV)

        x->vop_flags    |= XVID_VOP_INTER4V;      /* Level 3 */

    if (avctx->trellis)

        x->vop_flags    |= XVID_VOP_TRELLISQUANT; /* Level 5 */

    if (xvid_flags & AV_CODEC_FLAG_AC_PRED)

        x->vop_flags    |= XVID_VOP_HQACPRED;     /* Level 6 */

    if (xvid_flags & AV_CODEC_FLAG_GRAY)

        x->vop_flags    |= XVID_VOP_GREYSCALE;

    /* Decide which ME quality setting to use */

    x->me_flags = 0;

    switch (x->me_quality) {

    case 6:

    case 5:

        x->me_flags |= XVID_ME_EXTSEARCH16 |

                       XVID_ME_EXTSEARCH8;

    case 4:

    case 3:

        x->me_flags |= XVID_ME_ADVANCEDDIAMOND8 |

                       XVID_ME_HALFPELREFINE8   |

                       XVID_ME_CHROMA_PVOP      |

                       XVID_ME_CHROMA_BVOP;

    case 2:

    case 1:

        x->me_flags |= XVID_ME_ADVANCEDDIAMOND16 |

                       XVID_ME_HALFPELREFINE16;

#if FF_API_MOTION_EST

FF_DISABLE_DEPRECATION_WARNINGS

        break;

    default:

        switch (avctx->me_method) {

        case ME_FULL:   /* Quality 6 */

             x->me_flags |= XVID_ME_EXTSEARCH16 |

                            XVID_ME_EXTSEARCH8;

        case ME_EPZS:   /* Quality 4 */

             x->me_flags |= XVID_ME_ADVANCEDDIAMOND8 |

                            XVID_ME_HALFPELREFINE8   |

                            XVID_ME_CHROMA_PVOP      |

                            XVID_ME_CHROMA_BVOP;

        case ME_LOG:    /* Quality 2 */

        case ME_PHODS:

        case ME_X1:

             x->me_flags |= XVID_ME_ADVANCEDDIAMOND16 |

                            XVID_ME_HALFPELREFINE16;

        case ME_ZERO:   /* Quality 0 */

        default:

            break;

        }

FF_ENABLE_DEPRECATION_WARNINGS

#endif

    }

    /* Decide how we should decide blocks */

    switch (avctx->mb_decision) {

    case 2:

        x->vop_flags |=  XVID_VOP_MODEDECISION_RD;

        x->me_flags  |=  XVID_ME_HALFPELREFINE8_RD    |

                         XVID_ME_QUARTERPELREFINE8_RD |

                         XVID_ME_EXTSEARCH_RD         |

                         XVID_ME_CHECKPREDICTION_RD;

    case 1:

        if (!(x->vop_flags & XVID_VOP_MODEDECISION_RD))

            x->vop_flags |= XVID_VOP_FAST_MODEDECISION_RD;

        x->me_flags |= XVID_ME_HALFPELREFINE16_RD |

                       XVID_ME_QUARTERPELREFINE16_RD;

    default:

        break;

    }

    /* Bring in VOL flags from ffmpeg command-line */

#if FF_API_GMC

    if (avctx->flags & CODEC_FLAG_GMC)

        x->gmc = 1;

#endif

    x->vol_flags = 0;

    if (x->gmc) {

        x->vol_flags |= XVID_VOL_GMC;

        x->me_flags  |= XVID_ME_GME_REFINE;

    }

    if (xvid_flags & AV_CODEC_FLAG_QPEL) {

        x->vol_flags |= XVID_VOL_QUARTERPEL;

        x->me_flags  |= XVID_ME_QUARTERPELREFINE16;

        if (x->vop_flags & XVID_VOP_INTER4V)

            x->me_flags |= XVID_ME_QUARTERPELREFINE8;

    }

    xvid_gbl_init.version   = XVID_VERSION;

    xvid_gbl_init.debug     = 0;

    xvid_gbl_init.cpu_flags = 0;

    /* Initialize */

    xvid_global(NULL, XVID_GBL_INIT, &xvid_gbl_init, NULL);

    /* Create the encoder reference */

    xvid_enc_create.version = XVID_VERSION;

    /* Store the desired frame size */

    xvid_enc_create.width  =

    x->xsize               = avctx->width;

    xvid_enc_create.height =

    x->ysize               = avctx->height;

    /* Xvid can determine the proper profile to use */

    /* xvid_enc_create.profile = XVID_PROFILE_S_L3; */

    /* We don't use zones */

    xvid_enc_create.zones     = NULL;

    xvid_enc_create.num_zones = 0;

    xvid_enc_create.num_threads = avctx->thread_count;

#if (XVID_VERSION <= 0x010303) && (XVID_VERSION >= 0x010300)

    /* workaround for a bug in libxvidcore */

    if (avctx->height <= 16) {

        if (avctx->thread_count < 2) {

            xvid_enc_create.num_threads = 0;

        } else {

            av_log(avctx, AV_LOG_ERROR,

                   "Too small height for threads > 1.");

            return AVERROR(EINVAL);

        }

    }

#endif

    xvid_enc_create.plugins     = plugins;

    xvid_enc_create.num_plugins = 0;

    /* Initialize Buffers */

    x->twopassbuffer     = NULL;

    x->old_twopassbuffer = NULL;

    x->twopassfile       = NULL;

    if (xvid_flags & AV_CODEC_FLAG_PASS1) {

        rc2pass1.version     = XVID_VERSION;

        rc2pass1.context     = x;

        x->twopassbuffer     = av_malloc(BUFFER_SIZE);

        x->old_twopassbuffer = av_malloc(BUFFER_SIZE);

        if (!x->twopassbuffer || !x->old_twopassbuffer) {

            av_log(avctx, AV_LOG_ERROR,

                   "Xvid: Cannot allocate 2-pass log buffers\n");

            return AVERROR(ENOMEM);

        }

        x->twopassbuffer[0]     =

        x->old_twopassbuffer[0] = 0;

        plugins[xvid_enc_create.num_plugins].func  = xvid_ff_2pass;

        plugins[xvid_enc_create.num_plugins].param = &rc2pass1;

        xvid_enc_create.num_plugins++;

    } else if (xvid_flags & AV_CODEC_FLAG_PASS2) {

        rc2pass2.version = XVID_VERSION;

        rc2pass2.bitrate = avctx->bit_rate;

        fd = avpriv_tempfile("xvidff.", &x->twopassfile, 0, avctx);

        if (fd < 0) {

            av_log(avctx, AV_LOG_ERROR, "Xvid: Cannot write 2-pass pipe\n");

            return fd;

        }

        x->twopassfd = fd;

        if (!avctx->stats_in) {

            av_log(avctx, AV_LOG_ERROR,

                   "Xvid: No 2-pass information loaded for second pass\n");

            return AVERROR(EINVAL);

        }

        ret = write(fd, avctx->stats_in, strlen(avctx->stats_in));

        if (ret == -1)

            ret = AVERROR(errno);

        else if (strlen(avctx->stats_in) > ret) {

            av_log(avctx, AV_LOG_ERROR, "Xvid: Cannot write to 2-pass pipe\n");

            ret = AVERROR(EIO);

        }

        if (ret < 0)

            return ret;

        rc2pass2.filename                          = x->twopassfile;

        plugins[xvid_enc_create.num_plugins].func  = xvid_plugin_2pass2;

        plugins[xvid_enc_create.num_plugins].param = &rc2pass2;

        xvid_enc_create.num_plugins++;

    } else if (!(xvid_flags & AV_CODEC_FLAG_QSCALE)) {

        /* Single Pass Bitrate Control! */

        single.version = XVID_VERSION;

        single.bitrate = avctx->bit_rate;

        plugins[xvid_enc_create.num_plugins].func  = xvid_plugin_single;

        plugins[xvid_enc_create.num_plugins].param = &single;

        xvid_enc_create.num_plugins++;

    }

    if (avctx->lumi_masking != 0.0)

        x->lumi_aq = 1;

    /* Luminance Masking */

    if (x->lumi_aq) {

        masking_l.method                          = 0;

        plugins[xvid_enc_create.num_plugins].func = xvid_plugin_lumimasking;

        /* The old behavior is that when avctx->lumi_masking is specified,

         * plugins[...].param = NULL. Trying to keep the old behavior here. */

        plugins[xvid_enc_create.num_plugins].param =

            avctx->lumi_masking ? NULL : &masking_l;

        xvid_enc_create.num_plugins++;

    }

    /* Variance AQ */

    if (x->variance_aq) {

        masking_v.method                           = 1;

        plugins[xvid_enc_create.num_plugins].func  = xvid_plugin_lumimasking;

        plugins[xvid_enc_create.num_plugins].param = &masking_v;

        xvid_enc_create.num_plugins++;

    }

    if (x->lumi_aq && x->variance_aq )

        av_log(avctx, AV_LOG_INFO,

               "Both lumi_aq and variance_aq are enabled. The resulting quality"

               "will be the worse one of the two effects made by the AQ.\n");

    /* SSIM */

    if (x->ssim) {

        plugins[xvid_enc_create.num_plugins].func  = xvid_plugin_ssim;

        ssim.b_printstat                           = x->ssim == 2;

        ssim.acc                                   = x->ssim_acc;

        ssim.cpu_flags                             = xvid_gbl_init.cpu_flags;

        ssim.b_visualize                           = 0;

        plugins[xvid_enc_create.num_plugins].param = &ssim;

        xvid_enc_create.num_plugins++;

    }

    /* Frame Rate and Key Frames */

    xvid_correct_framerate(avctx);

    xvid_enc_create.fincr = avctx->time_base.num;

    xvid_enc_create.fbase = avctx->time_base.den;

    if (avctx->gop_size > 0)

        xvid_enc_create.max_key_interval = avctx->gop_size;

    else

        xvid_enc_create.max_key_interval = 240; /* Xvid's best default */

    /* Quants */

    if (xvid_flags & AV_CODEC_FLAG_QSCALE)

        x->qscale = 1;

    else

        x->qscale = 0;

    xvid_enc_create.min_quant[0] = avctx->qmin;

    xvid_enc_create.min_quant[1] = avctx->qmin;

    xvid_enc_create.min_quant[2] = avctx->qmin;

    xvid_enc_create.max_quant[0] = avctx->qmax;

    xvid_enc_create.max_quant[1] = avctx->qmax;

    xvid_enc_create.max_quant[2] = avctx->qmax;

    /* Quant Matrices */

    x->intra_matrix =

    x->inter_matrix = NULL;

#if FF_API_PRIVATE_OPT

FF_DISABLE_DEPRECATION_WARNINGS

    if (avctx->mpeg_quant)

        x->mpeg_quant = avctx->mpeg_quant;

FF_ENABLE_DEPRECATION_WARNINGS

#endif

    if (x->mpeg_quant)

        x->vol_flags |= XVID_VOL_MPEGQUANT;

    if ((avctx->intra_matrix || avctx->inter_matrix)) {

        x->vol_flags |= XVID_VOL_MPEGQUANT;

        if (avctx->intra_matrix) {

            intra           = avctx->intra_matrix;

            x->intra_matrix = av_malloc(sizeof(unsigned char) * 64);

            if (!x->intra_matrix)

                return AVERROR(ENOMEM);

        } else

            intra = NULL;

        if (avctx->inter_matrix) {

            inter           = avctx->inter_matrix;

            x->inter_matrix = av_malloc(sizeof(unsigned char) * 64);

            if (!x->inter_matrix)

                return AVERROR(ENOMEM);

        } else

            inter = NULL;

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

            if (intra)

                x->intra_matrix[i] = (unsigned char) intra[i];

            if (inter)

                x->inter_matrix[i] = (unsigned char) inter[i];

        }

    }

    /* Misc Settings */

    xvid_enc_create.frame_drop_ratio = 0;

    xvid_enc_create.global           = 0;

    if (xvid_flags & AV_CODEC_FLAG_CLOSED_GOP)

        xvid_enc_create.global |= XVID_GLOBAL_CLOSED_GOP;

    /* Determines which codec mode we are operating in */

    avctx->extradata      = NULL;

    avctx->extradata_size = 0;

    if (xvid_flags & AV_CODEC_FLAG_GLOBAL_HEADER) {

        /* In this case, we are claiming to be MPEG4 */

        x->quicktime_format = 1;

        avctx->codec_id     = AV_CODEC_ID_MPEG4;

    } else {

        /* We are claiming to be Xvid */

        x->quicktime_format = 0;

        if (!avctx->codec_tag)

            avctx->codec_tag = AV_RL32("xvid");

    }

    /* Bframes */

    xvid_enc_create.max_bframes   = avctx->max_b_frames;

    xvid_enc_create.bquant_offset = 100 * avctx->b_quant_offset;

    xvid_enc_create.bquant_ratio  = 100 * avctx->b_quant_factor;

    if (avctx->max_b_frames > 0 && !x->quicktime_format)

        xvid_enc_create.global |= XVID_GLOBAL_PACKED;

    av_assert0(xvid_enc_create.num_plugins + (!!x->ssim) + (!!x->variance_aq) + (!!x->lumi_aq) <= FF_ARRAY_ELEMS(plugins));

    /* Encode a dummy frame to get the extradata immediately */

    if (x->quicktime_format) {

        AVFrame *picture;

        AVPacket packet;

        int size, got_packet, ret;

        av_init_packet(&packet);

        picture = av_frame_alloc();

        if (!picture)

            return AVERROR(ENOMEM);

        xerr = xvid_encore(NULL, XVID_ENC_CREATE, &xvid_enc_create, NULL);

        if( xerr ) {

            av_frame_free(&picture);

            av_log(avctx, AV_LOG_ERROR, "Xvid: Could not create encoder reference\n");

            return AVERROR_EXTERNAL;

        }

        x->encoder_handle = xvid_enc_create.handle;

        size = ((avctx->width + 1) & ~1) * ((avctx->height + 1) & ~1);

        picture->data[0] = av_malloc(size + size / 2);

        if (!picture->data[0]) {

            av_frame_free(&picture);

            return AVERROR(ENOMEM);

        }

        picture->data[1] = picture->data[0] + size;

        picture->data[2] = picture->data[1] + size / 4;

        memset(picture->data[0], 0, size);

        memset(picture->data[1], 128, size / 2);

        ret = xvid_encode_frame(avctx, &packet, picture, &got_packet);

        if (!ret && got_packet)

            av_packet_unref(&packet);

        av_free(picture->data[0]);

        av_frame_free(&picture);

        xvid_encore(x->encoder_handle, XVID_ENC_DESTROY, NULL, NULL);

    }

    /* Create encoder context */

    xerr = xvid_encore(NULL, XVID_ENC_CREATE, &xvid_enc_create, NULL);

    if (xerr) {

        av_log(avctx, AV_LOG_ERROR, "Xvid: Could not create encoder reference\n");

        return AVERROR_EXTERNAL;

    }

    x->encoder_handle  = xvid_enc_create.handle;

    return 0;

}


static void test_submit_co(void)

{

    WorkerTestData data;

    Coroutine *co = qemu_coroutine_create(co_test_cb);

    qemu_coroutine_enter(co, &data);

    /* Back here once the worker has started.  */

    g_assert_cmpint(active, ==, 1);

    g_assert_cmpint(data.ret, ==, -EINPROGRESS);

    /* qemu_aio_wait_all will execute the rest of the coroutine.  */

    qemu_aio_wait_all();

    /* Back here after the coroutine has finished.  */

    g_assert_cmpint(active, ==, 0);

    g_assert_cmpint(data.ret, ==, 0);

}


static void pcnet_transmit(PCNetState *s)

{

    hwaddr xmit_cxda = 0;

    int count = CSR_XMTRL(s)-1;

    int add_crc = 0;

    int bcnt;

    s->xmit_pos = -1;

    if (!CSR_TXON(s)) {

        s->csr[0] &= ~0x0008;

        return;

    }

    s->tx_busy = 1;

    txagain:

    if (pcnet_tdte_poll(s)) {

        struct pcnet_TMD tmd;

        TMDLOAD(&tmd, PHYSADDR(s,CSR_CXDA(s)));

#ifdef PCNET_DEBUG_TMD

        printf("  TMDLOAD 0x%08x\n", PHYSADDR(s,CSR_CXDA(s)));

        PRINT_TMD(&tmd);

#endif

        if (GET_FIELD(tmd.status, TMDS, STP)) {

            s->xmit_pos = 0;

            xmit_cxda = PHYSADDR(s,CSR_CXDA(s));

            if (BCR_SWSTYLE(s) != 1)

                add_crc = GET_FIELD(tmd.status, TMDS, ADDFCS);

        }

        if (s->lnkst == 0 &&

            (!CSR_LOOP(s) || (!CSR_INTL(s) && !BCR_TMAULOOP(s)))) {

            SET_FIELD(&tmd.misc, TMDM, LCAR, 1);

            SET_FIELD(&tmd.status, TMDS, ERR, 1);

            SET_FIELD(&tmd.status, TMDS, OWN, 0);

            s->csr[0] |= 0xa000; /* ERR | CERR */

            s->xmit_pos = -1;

            goto txdone;

        }

        if (s->xmit_pos < 0) {

            goto txdone;

        }

        bcnt = 4096 - GET_FIELD(tmd.length, TMDL, BCNT);

        /* if multi-tmd packet outsizes s->buffer then skip it silently.

           Note: this is not what real hw does */

        if (s->xmit_pos + bcnt > sizeof(s->buffer)) {

            s->xmit_pos = -1;

            goto txdone;

        }

        s->phys_mem_read(s->dma_opaque, PHYSADDR(s, tmd.tbadr),

                         s->buffer + s->xmit_pos, bcnt, CSR_BSWP(s));

        s->xmit_pos += bcnt;

        if (!GET_FIELD(tmd.status, TMDS, ENP)) {

            goto txdone;

        }

#ifdef PCNET_DEBUG

        printf("pcnet_transmit size=%d\n", s->xmit_pos);

#endif

        if (CSR_LOOP(s)) {

            if (BCR_SWSTYLE(s) == 1)

                add_crc = !GET_FIELD(tmd.status, TMDS, NOFCS);

            s->looptest = add_crc ? PCNET_LOOPTEST_CRC : PCNET_LOOPTEST_NOCRC;

            pcnet_receive(qemu_get_queue(s->nic), s->buffer, s->xmit_pos);

            s->looptest = 0;

        } else {

            if (s->nic) {

                qemu_send_packet(qemu_get_queue(s->nic), s->buffer,

                                 s->xmit_pos);

            }

        }

        s->csr[0] &= ~0x0008;   /* clear TDMD */

        s->csr[4] |= 0x0004;    /* set TXSTRT */

        s->xmit_pos = -1;

    txdone:

        SET_FIELD(&tmd.status, TMDS, OWN, 0);

        TMDSTORE(&tmd, PHYSADDR(s,CSR_CXDA(s)));

        if (!CSR_TOKINTD(s) || (CSR_LTINTEN(s) && GET_FIELD(tmd.status, TMDS, LTINT)))

            s->csr[0] |= 0x0200;    /* set TINT */

        if (CSR_XMTRC(s)<=1)

            CSR_XMTRC(s) = CSR_XMTRL(s);

        else

            CSR_XMTRC(s)--;

        if (count--)

            goto txagain;

    } else

    if (s->xmit_pos >= 0) {

        struct pcnet_TMD tmd;

        TMDLOAD(&tmd, xmit_cxda);

        SET_FIELD(&tmd.misc, TMDM, BUFF, 1);

        SET_FIELD(&tmd.misc, TMDM, UFLO, 1);

        SET_FIELD(&tmd.status, TMDS, ERR, 1);

        SET_FIELD(&tmd.status, TMDS, OWN, 0);

        TMDSTORE(&tmd, xmit_cxda);

        s->csr[0] |= 0x0200;    /* set TINT */

        if (!CSR_DXSUFLO(s)) {

            s->csr[0] &= ~0x0010;

        } else

        if (count--)

          goto txagain;

    }

    s->tx_busy = 0;

}


long do_sigreturn(CPUMBState *env)

{

    struct target_signal_frame *frame;

    abi_ulong frame_addr;

    target_sigset_t target_set;

    sigset_t set;

    int i;

    frame_addr = env->regs[R_SP];

    trace_user_do_sigreturn(env, frame_addr);

    /* Make sure the guest isn't playing games.  */

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

        goto badframe;

    /* Restore blocked signals */

    __get_user(target_set.sig[0], &frame->uc.tuc_mcontext.oldmask);

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

        __get_user(target_set.sig[i], &frame->extramask[i - 1]);

    }

    target_to_host_sigset_internal(&set, &target_set);

    do_sigprocmask(SIG_SETMASK, &set, NULL);

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

    /* We got here through a sigreturn syscall, our path back is via an

       rtb insn so setup r14 for that.  */

    env->regs[14] = env->sregs[SR_PC];

    unlock_user_struct(frame, frame_addr, 0);

    return env->regs[10];

badframe:

    force_sig(TARGET_SIGSEGV);

}


static hwaddr ppc_hash64_pteg_search(PowerPCCPU *cpu, hwaddr hash,

                                     bool secondary, target_ulong ptem,

                                     ppc_hash_pte64_t *pte)

{

    CPUPPCState *env = &cpu->env;

    int i;

    uint64_t token;

    target_ulong pte0, pte1;

    target_ulong pte_index;

    pte_index = (hash & env->htab_mask) * HPTES_PER_GROUP;

    token = ppc_hash64_start_access(cpu, pte_index);

    if (!token) {

        return -1;

    }

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

        pte0 = ppc_hash64_load_hpte0(cpu, token, i);

        pte1 = ppc_hash64_load_hpte1(cpu, token, i);

        if ((pte0 & HPTE64_V_VALID)

            && (secondary == !!(pte0 & HPTE64_V_SECONDARY))

            && HPTE64_V_COMPARE(pte0, ptem)) {

            pte->pte0 = pte0;

            pte->pte1 = pte1;

            ppc_hash64_stop_access(cpu, token);

            return (pte_index + i) * HASH_PTE_SIZE_64;

        }

    }

    ppc_hash64_stop_access(cpu, token);

    /*

     * We didn't find a valid entry.

     */

    return -1;

}


static void qemu_kvm_eat_signal(CPUState *env, int timeout)

{

    struct timespec ts;

    int r, e;

    siginfo_t siginfo;

    sigset_t waitset;

    ts.tv_sec = timeout / 1000;

    ts.tv_nsec = (timeout % 1000) * 1000000;

    sigemptyset(&waitset);

    sigaddset(&waitset, SIG_IPI);

    qemu_mutex_unlock(&qemu_global_mutex);

    r = sigtimedwait(&waitset, &siginfo, &ts);

    e = errno;

    qemu_mutex_lock(&qemu_global_mutex);

    if (r == -1 && !(e == EAGAIN || e == EINTR)) {

        fprintf(stderr, "sigtimedwait: %s\n", strerror(e));

        exit(1);

    }

}


static int write_representation(AVFormatContext *s, AVStream *stream, char *id,

                                int output_width, int output_height,

                                int output_sample_rate) {

    WebMDashMuxContext *w = s->priv_data;

    AVDictionaryEntry *irange = av_dict_get(stream->metadata, INITIALIZATION_RANGE, NULL, 0);

    AVDictionaryEntry *cues_start = av_dict_get(stream->metadata, CUES_START, NULL, 0);

    AVDictionaryEntry *cues_end = av_dict_get(stream->metadata, CUES_END, NULL, 0);

    AVDictionaryEntry *filename = av_dict_get(stream->metadata, FILENAME, NULL, 0);

    AVDictionaryEntry *bandwidth = av_dict_get(stream->metadata, BANDWIDTH, NULL, 0);

    if ((w->is_live && (!filename)) ||

        (!w->is_live && (!irange || !cues_start || !cues_end || !filename || !bandwidth))) {

        return -1;

    }

    avio_printf(s->pb, "<Representation id=\"%s\"", id);

    // FIXME: For live, This should be obtained from the input file or as an AVOption.

    avio_printf(s->pb, " bandwidth=\"%s\"",

                w->is_live ? (stream->codec->codec_type == AVMEDIA_TYPE_AUDIO ? "128000" : "1000000") : bandwidth->value);

    if (stream->codec->codec_type == AVMEDIA_TYPE_VIDEO && output_width)

        avio_printf(s->pb, " width=\"%d\"", stream->codec->width);

    if (stream->codec->codec_type == AVMEDIA_TYPE_VIDEO && output_height)

        avio_printf(s->pb, " height=\"%d\"", stream->codec->height);

    if (stream->codec->codec_type = AVMEDIA_TYPE_AUDIO && output_sample_rate)

        avio_printf(s->pb, " audioSamplingRate=\"%d\"", stream->codec->sample_rate);

    if (w->is_live) {

        // For live streams, Codec and Mime Type always go in the Representation tag.

        avio_printf(s->pb, " codecs=\"%s\"", get_codec_name(stream->codec->codec_id));

        avio_printf(s->pb, " mimeType=\"%s/webm\"",

                    stream->codec->codec_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio");

        // For live streams, subsegments always start with key frames. So this

        // is always 1.

        avio_printf(s->pb, " startsWithSAP=\"1\"");

        avio_printf(s->pb, ">");

    } else {

        avio_printf(s->pb, ">\n");

        avio_printf(s->pb, "<BaseURL>%s</BaseURL>\n", filename->value);

        avio_printf(s->pb, "<SegmentBase\n");

        avio_printf(s->pb, "  indexRange=\"%s-%s\">\n", cues_start->value, cues_end->value);

        avio_printf(s->pb, "<Initialization\n");

        avio_printf(s->pb, "  range=\"0-%s\" />\n", irange->value);

        avio_printf(s->pb, "</SegmentBase>\n");

    }

    avio_printf(s->pb, "</Representation>\n");

    return 0;

}


static inline int set_options(AVFilterContext *ctx, const char *args)

{

    HueContext *hue = ctx->priv;

    int n, ret;

    char c1 = 0, c2 = 0;

    char   *old_hue_expr,  *old_hue_deg_expr,  *old_saturation_expr;

    AVExpr *old_hue_pexpr, *old_hue_deg_pexpr, *old_saturation_pexpr;

    if (args) {

        /* named options syntax */

        if (strchr(args, '=')) {

            old_hue_expr        = hue->hue_expr;

            old_hue_deg_expr    = hue->hue_deg_expr;

            old_saturation_expr = hue->saturation_expr;

            old_hue_pexpr        = hue->hue_pexpr;

            old_hue_deg_pexpr    = hue->hue_deg_pexpr;

            old_saturation_pexpr = hue->saturation_pexpr;

            hue->hue_expr     = NULL;

            hue->hue_deg_expr = NULL;

            hue->saturation_expr = NULL;

            if ((ret = av_set_options_string(hue, args, "=", ":")) < 0)

                return ret;

            if (hue->hue_expr && hue->hue_deg_expr) {

                av_log(ctx, AV_LOG_ERROR,

                       "H and h options are incompatible and cannot be specified "

                       "at the same time\n");

                hue->hue_expr     = old_hue_expr;

                hue->hue_deg_expr = old_hue_deg_expr;

                return AVERROR(EINVAL);

            }

            /*

             * if both 'H' and 'h' options have not been specified, restore the

             * old values

             */

            if (!hue->hue_expr && !hue->hue_deg_expr) {

                hue->hue_expr     = old_hue_expr;

                hue->hue_deg_expr = old_hue_deg_expr;

            }

            if (hue->hue_deg_expr)

                PARSE_EXPRESSION(hue_deg, h);

            if (hue->hue_expr)

                PARSE_EXPRESSION(hue, H);

            if (hue->saturation_expr)

                PARSE_EXPRESSION(saturation, s);

            hue->flat_syntax = 0;

            av_log(ctx, AV_LOG_VERBOSE,

                   "H_expr:%s h_deg_expr:%s s_expr:%s\n",

                   hue->hue_expr, hue->hue_deg_expr, hue->saturation_expr);

        /* compatibility h:s syntax */

        } else {

            n = sscanf(args, "%f%c%f%c", &hue->hue_deg, &c1, &hue->saturation, &c2);

            if (n != 1 && (n != 3 || c1 != ':')) {

                av_log(ctx, AV_LOG_ERROR,

                       "Invalid syntax for argument '%s': "

                       "must be in the form 'hue[:saturation]'\n", args);

                return AVERROR(EINVAL);

            }

            if (hue->saturation < SAT_MIN_VAL || hue->saturation > SAT_MAX_VAL) {

                av_log(ctx, AV_LOG_ERROR,

                       "Invalid value for saturation %0.1f: "

                       "must be included between range %d and +%d\n",

                       hue->saturation, SAT_MIN_VAL, SAT_MAX_VAL);

                return AVERROR(EINVAL);

            }

            hue->hue = hue->hue_deg * M_PI / 180;

            hue->flat_syntax = 1;

            av_log(ctx, AV_LOG_VERBOSE,

                   "H:%0.1f h:%0.1f s:%0.1f\n",

                   hue->hue, hue->hue_deg, hue->saturation);

        }

    }

    compute_sin_and_cos(hue);

    return 0;

}


static int iothread_stop(Object *object, void *opaque)

{

    IOThread *iothread;

    iothread = (IOThread *)object_dynamic_cast(object, TYPE_IOTHREAD);

    if (!iothread || !iothread->ctx) {

        return 0;

    }

    iothread->stopping = true;

    aio_notify(iothread->ctx);

    if (atomic_read(&iothread->main_loop)) {

        g_main_loop_quit(iothread->main_loop);

    }

    qemu_thread_join(&iothread->thread);

    return 0;

}


SCSIDevice *scsi_disk_init(BlockDriverState *bdrv, int tcq,

                           scsi_completionfn completion, void *opaque)

{

    SCSIDevice *d;

    SCSIDeviceState *s;

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

    s->bdrv = bdrv;

    s->tcq = tcq;

    s->completion = completion;

    s->opaque = opaque;

    if (bdrv_get_type_hint(s->bdrv) == BDRV_TYPE_CDROM) {

        s->cluster_size = 4;

    } else {

        s->cluster_size = 1;

    }

    bdrv_get_geometry(s->bdrv, &nb_sectors);

    nb_sectors /= s->cluster_size;

    if (nb_sectors)

        nb_sectors--;

    s->max_lba = nb_sectors;

    strncpy(s->drive_serial_str, drive_get_serial(s->bdrv),

            sizeof(s->drive_serial_str));

    if (strlen(s->drive_serial_str) == 0)

        pstrcpy(s->drive_serial_str, sizeof(s->drive_serial_str), "0");

    qemu_add_vm_change_state_handler(scsi_dma_restart_cb, s);

    d = (SCSIDevice *)qemu_mallocz(sizeof(SCSIDevice));

    d->state = s;

    d->destroy = scsi_destroy;

    d->send_command = scsi_send_command;

    d->read_data = scsi_read_data;

    d->write_data = scsi_write_data;

    d->cancel_io = scsi_cancel_io;

    d->get_buf = scsi_get_buf;

    return d;

}


static void usbredir_handle_destroy(USBDevice *udev)

{

    USBRedirDevice *dev = DO_UPCAST(USBRedirDevice, dev, udev);

    qemu_chr_delete(dev->cs);

    /* Note must be done after qemu_chr_close, as that causes a close event */

    qemu_bh_delete(dev->chardev_close_bh);

    qemu_del_timer(dev->attach_timer);

    qemu_free_timer(dev->attach_timer);

    usbredir_cleanup_device_queues(dev);

    if (dev->parser) {

        usbredirparser_destroy(dev->parser);

    }

    if (dev->watch) {

        g_source_remove(dev->watch);

    }

    free(dev->filter_rules);

}


static int find_optimal_param(uint32_t sum, int n)

{

    int k;

    uint32_t sum2;

    if (sum <= n >> 1)

        return 0;

    sum2 = sum - (n >> 1);

    k    = av_log2(n < 256 ? FASTDIV(sum2, n) : sum2 / n);

    return FFMIN(k, MAX_RICE_PARAM);

}


static void set_pixel_format(VncState *vs,

			     int bits_per_pixel, int depth,

			     int big_endian_flag, int true_color_flag,

			     int red_max, int green_max, int blue_max,

			     int red_shift, int green_shift, int blue_shift)

{

    int host_big_endian_flag;

#ifdef WORDS_BIGENDIAN

    host_big_endian_flag = 1;

#else

    host_big_endian_flag = 0;

#endif

    if (!true_color_flag) {

    fail:

	vnc_client_error(vs);

        return;

    }

    if (bits_per_pixel == 32 &&

        bits_per_pixel == vs->depth * 8 &&

        host_big_endian_flag == big_endian_flag &&

        red_max == 0xff && green_max == 0xff && blue_max == 0xff &&

        red_shift == 16 && green_shift == 8 && blue_shift == 0) {

        vs->depth = 4;

        vs->write_pixels = vnc_write_pixels_copy;

        vs->send_hextile_tile = send_hextile_tile_32;

    } else

    if (bits_per_pixel == 16 &&

        bits_per_pixel == vs->depth * 8 &&

        host_big_endian_flag == big_endian_flag &&

        red_max == 31 && green_max == 63 && blue_max == 31 &&

        red_shift == 11 && green_shift == 5 && blue_shift == 0) {

        vs->depth = 2;

        vs->write_pixels = vnc_write_pixels_copy;

        vs->send_hextile_tile = send_hextile_tile_16;

    } else

    if (bits_per_pixel == 8 &&

        bits_per_pixel == vs->depth * 8 &&

        red_max == 7 && green_max == 7 && blue_max == 3 &&

        red_shift == 5 && green_shift == 2 && blue_shift == 0) {

        vs->depth = 1;

        vs->write_pixels = vnc_write_pixels_copy;

        vs->send_hextile_tile = send_hextile_tile_8;

    } else

    {

        /* generic and slower case */

        if (bits_per_pixel != 8 &&

            bits_per_pixel != 16 &&

            bits_per_pixel != 32)

            goto fail;

        if (vs->depth == 4) {

            vs->send_hextile_tile = send_hextile_tile_generic_32;

        } else if (vs->depth == 2) {

           vs->send_hextile_tile = send_hextile_tile_generic_16;

        } else {

            vs->send_hextile_tile = send_hextile_tile_generic_8;

        }

        vs->pix_big_endian = big_endian_flag;

        vs->write_pixels = vnc_write_pixels_generic;

    }

    vs->client_red_shift = red_shift;

    vs->client_red_max = red_max;

    vs->client_green_shift = green_shift;

    vs->client_green_max = green_max;

    vs->client_blue_shift = blue_shift;

    vs->client_blue_max = blue_max;

    vs->pix_bpp = bits_per_pixel / 8;

    vga_hw_invalidate();

    vga_hw_update();

}


static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
                                   size_t size)
{
    int64_t len;
    if (!bdrv_is_inserted(bs))
        return -ENOMEDIUM;
    if (bs->growable)
        return 0;
    len = bdrv_getlength(bs);
    if (offset < 0)
    if ((offset > len) || (len - offset < size))
    return 0;


static void net_socket_accept(void *opaque)

{

    NetSocketListenState *s = opaque;

    NetSocketState *s1;

    struct sockaddr_in saddr;

    socklen_t len;

    int fd;

    for(;;) {

        len = sizeof(saddr);

        fd = qemu_accept(s->fd, (struct sockaddr *)&saddr, &len);

        if (fd < 0 && errno != EINTR) {

            return;

        } else if (fd >= 0) {

            break;

        }

    }

    s1 = net_socket_fd_init(s->vlan, s->model, s->name, fd, 1);

    if (!s1) {

        closesocket(fd);

    } else {

        snprintf(s1->nc.info_str, sizeof(s1->nc.info_str),

                 "socket: connection from %s:%d",

                 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));

    }

}


static void svq3_luma_dc_dequant_idct_c(int16_t *output, int16_t *input, int qp)

{

    const int qmul = svq3_dequant_coeff[qp];

#define stride 16

    int i;

    int temp[16];

    static const uint8_t x_offset[4] = { 0, 1 * stride, 4 * stride, 5 * stride };

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

        const int z0 = 13 * (input[4 * i + 0] +      input[4 * i + 2]);

        const int z1 = 13 * (input[4 * i + 0] -      input[4 * i + 2]);

        const int z2 =  7 *  input[4 * i + 1] - 17 * input[4 * i + 3];

        const int z3 = 17 *  input[4 * i + 1] +  7 * input[4 * i + 3];

        temp[4 * i + 0] = z0 + z3;

        temp[4 * i + 1] = z1 + z2;

        temp[4 * i + 2] = z1 - z2;

        temp[4 * i + 3] = z0 - z3;

    }

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

        const int offset = x_offset[i];

        const int z0     = 13 * (temp[4 * 0 + i] +      temp[4 * 2 + i]);

        const int z1     = 13 * (temp[4 * 0 + i] -      temp[4 * 2 + i]);

        const int z2     =  7 *  temp[4 * 1 + i] - 17 * temp[4 * 3 + i];

        const int z3     = 17 *  temp[4 * 1 + i] +  7 * temp[4 * 3 + i];

        output[stride *  0 + offset] = (z0 + z3) * qmul + 0x80000 >> 20;

        output[stride *  2 + offset] = (z1 + z2) * qmul + 0x80000 >> 20;

        output[stride *  8 + offset] = (z1 - z2) * qmul + 0x80000 >> 20;

        output[stride * 10 + offset] = (z0 - z3) * qmul + 0x80000 >> 20;

    }

}


static av_cold int adpcm_encode_init(AVCodecContext *avctx)

{

    ADPCMEncodeContext *s = avctx->priv_data;

    uint8_t *extradata;

    int i;

    if (avctx->channels > 2)

        return -1; /* only stereo or mono =) */

    if (avctx->trellis && (unsigned)avctx->trellis > 16U) {

        av_log(avctx, AV_LOG_ERROR, "invalid trellis size\n");

        return -1;

    }

    if (avctx->trellis) {

        int frontier  = 1 << avctx->trellis;

        int max_paths =  frontier * FREEZE_INTERVAL;

        FF_ALLOC_OR_GOTO(avctx, s->paths,

                         max_paths * sizeof(*s->paths), error);

        FF_ALLOC_OR_GOTO(avctx, s->node_buf,

                         2 * frontier * sizeof(*s->node_buf),  error);

        FF_ALLOC_OR_GOTO(avctx, s->nodep_buf,

                         2 * frontier * sizeof(*s->nodep_buf), error);

        FF_ALLOC_OR_GOTO(avctx, s->trellis_hash,

                         65536 * sizeof(*s->trellis_hash), error);

    }

    avctx->bits_per_coded_sample = av_get_bits_per_sample(avctx->codec->id);

    switch (avctx->codec->id) {

    case CODEC_ID_ADPCM_IMA_WAV:

        /* each 16 bits sample gives one nibble

           and we have 4 bytes per channel overhead */

        avctx->frame_size = (BLKSIZE - 4 * avctx->channels) * 8 /

                            (4 * avctx->channels) + 1;

        /* seems frame_size isn't taken into account...

           have to buffer the samples :-( */

        avctx->block_align = BLKSIZE;

        break;

    case CODEC_ID_ADPCM_IMA_QT:

        avctx->frame_size  = 64;

        avctx->block_align = 34 * avctx->channels;

        break;

    case CODEC_ID_ADPCM_MS:

        /* each 16 bits sample gives one nibble

           and we have 7 bytes per channel overhead */

        avctx->frame_size = (BLKSIZE - 7 * avctx->channels) * 2 /

                             avctx->channels + 2;

        avctx->block_align    = BLKSIZE;

        avctx->extradata_size = 32;

        extradata = avctx->extradata = av_malloc(avctx->extradata_size);

        if (!extradata)

            return AVERROR(ENOMEM);

        bytestream_put_le16(&extradata, avctx->frame_size);

        bytestream_put_le16(&extradata, 7); /* wNumCoef */

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

            bytestream_put_le16(&extradata, ff_adpcm_AdaptCoeff1[i] * 4);

            bytestream_put_le16(&extradata, ff_adpcm_AdaptCoeff2[i] * 4);

        }

        break;

    case CODEC_ID_ADPCM_YAMAHA:

        avctx->frame_size  = BLKSIZE * avctx->channels;

        avctx->block_align = BLKSIZE;

        break;

    case CODEC_ID_ADPCM_SWF:

        if (avctx->sample_rate != 11025 &&

            avctx->sample_rate != 22050 &&

            avctx->sample_rate != 44100) {

            av_log(avctx, AV_LOG_ERROR, "Sample rate must be 11025, "

                   "22050 or 44100\n");

            goto error;

        }

        avctx->frame_size = 512 * (avctx->sample_rate / 11025);

        break;

    default:

        goto error;

    }

    avctx->coded_frame = avcodec_alloc_frame();

    return 0;

error:

    av_freep(&s->paths);

    av_freep(&s->node_buf);

    av_freep(&s->nodep_buf);

    av_freep(&s->trellis_hash);

    return -1;

}


int ff_h264_slice_context_init(H264Context *h, H264SliceContext *sl)

{

    ERContext *er = &sl->er;

    int mb_array_size = h->mb_height * h->mb_stride;

    int y_size  = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);

    int c_size  = h->mb_stride * (h->mb_height + 1);

    int yc_size = y_size + 2   * c_size;

    int x, y, i;

    sl->ref_cache[0][scan8[5]  + 1] =

    sl->ref_cache[0][scan8[7]  + 1] =

    sl->ref_cache[0][scan8[13] + 1] =

    sl->ref_cache[1][scan8[5]  + 1] =

    sl->ref_cache[1][scan8[7]  + 1] =

    sl->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;

    if (sl != h->slice_ctx) {

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

    } else

    if (CONFIG_ERROR_RESILIENCE) {

        /* init ER */

        er->avctx          = h->avctx;

        er->decode_mb      = h264_er_decode_mb;

        er->opaque         = h;

        er->quarter_sample = 1;

        er->mb_num      = h->mb_num;

        er->mb_width    = h->mb_width;

        er->mb_height   = h->mb_height;

        er->mb_stride   = h->mb_stride;

        er->b8_stride   = h->mb_width * 2 + 1;

        // error resilience code looks cleaner with this

        FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy,

                          (h->mb_num + 1) * sizeof(int), fail);

        for (y = 0; y < h->mb_height; y++)

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

                er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;

        er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *

                                                      h->mb_stride + h->mb_width;

        FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,

                          mb_array_size * sizeof(uint8_t), fail);

        FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer,

                         h->mb_height * h->mb_stride, fail);

        FF_ALLOCZ_OR_GOTO(h->avctx, sl->dc_val_base,

                          yc_size * sizeof(int16_t), fail);

        er->dc_val[0] = sl->dc_val_base + h->mb_width * 2 + 2;

        er->dc_val[1] = sl->dc_val_base + y_size + h->mb_stride + 1;

        er->dc_val[2] = er->dc_val[1] + c_size;

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

            sl->dc_val_base[i] = 1024;

    }

    return 0;

fail:

    return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us

}


static void test_visitor_in_alternate_number(TestInputVisitorData *data,

                                             const void *unused)

{

    Visitor *v;

    Error *err = NULL;

    AltStrBool *asb;

    AltStrNum *asn;

    AltNumStr *ans;

    AltStrInt *asi;

    AltIntNum *ain;

    AltNumInt *ani;

    /* Parsing an int */

    v = visitor_input_test_init(data, "42");

    visit_type_AltStrBool(v, &asb, NULL, &err);

    error_free_or_abort(&err);

    qapi_free_AltStrBool(asb);

    /* FIXME: Order of alternate should not affect semantics; asn should

     * parse the same as ans */

    v = visitor_input_test_init(data, "42");

    visit_type_AltStrNum(v, &asn, NULL, &err);

    /* FIXME g_assert_cmpint(asn->type, == ALT_STR_NUM_KIND_N); */

    /* FIXME g_assert_cmpfloat(asn->u.n, ==, 42); */

    error_free_or_abort(&err);

    qapi_free_AltStrNum(asn);

    v = visitor_input_test_init(data, "42");

    visit_type_AltNumStr(v, &ans, NULL, &error_abort);

    g_assert_cmpint(ans->type, ==, ALT_NUM_STR_KIND_N);

    g_assert_cmpfloat(ans->u.n, ==, 42);

    qapi_free_AltNumStr(ans);

    v = visitor_input_test_init(data, "42");

    visit_type_AltStrInt(v, &asi, NULL, &error_abort);

    g_assert_cmpint(asi->type, ==, ALT_STR_INT_KIND_I);

    g_assert_cmpint(asi->u.i, ==, 42);

    qapi_free_AltStrInt(asi);

    v = visitor_input_test_init(data, "42");

    visit_type_AltIntNum(v, &ain, NULL, &error_abort);

    g_assert_cmpint(ain->type, ==, ALT_INT_NUM_KIND_I);

    g_assert_cmpint(ain->u.i, ==, 42);

    qapi_free_AltIntNum(ain);

    v = visitor_input_test_init(data, "42");

    visit_type_AltNumInt(v, &ani, NULL, &error_abort);

    g_assert_cmpint(ani->type, ==, ALT_NUM_INT_KIND_I);

    g_assert_cmpint(ani->u.i, ==, 42);

    qapi_free_AltNumInt(ani);

    /* Parsing a double */

    v = visitor_input_test_init(data, "42.5");

    visit_type_AltStrBool(v, &asb, NULL, &err);

    error_free_or_abort(&err);

    qapi_free_AltStrBool(asb);

    v = visitor_input_test_init(data, "42.5");

    visit_type_AltStrNum(v, &asn, NULL, &error_abort);

    g_assert_cmpint(asn->type, ==, ALT_STR_NUM_KIND_N);

    g_assert_cmpfloat(asn->u.n, ==, 42.5);

    qapi_free_AltStrNum(asn);

    v = visitor_input_test_init(data, "42.5");

    visit_type_AltNumStr(v, &ans, NULL, &error_abort);

    g_assert_cmpint(ans->type, ==, ALT_NUM_STR_KIND_N);

    g_assert_cmpfloat(ans->u.n, ==, 42.5);

    qapi_free_AltNumStr(ans);

    v = visitor_input_test_init(data, "42.5");

    visit_type_AltStrInt(v, &asi, NULL, &err);

    error_free_or_abort(&err);

    qapi_free_AltStrInt(asi);

    v = visitor_input_test_init(data, "42.5");

    visit_type_AltIntNum(v, &ain, NULL, &error_abort);

    g_assert_cmpint(ain->type, ==, ALT_INT_NUM_KIND_N);

    g_assert_cmpfloat(ain->u.n, ==, 42.5);

    qapi_free_AltIntNum(ain);

    v = visitor_input_test_init(data, "42.5");

    visit_type_AltNumInt(v, &ani, NULL, &error_abort);

    g_assert_cmpint(ani->type, ==, ALT_NUM_INT_KIND_N);

    g_assert_cmpfloat(ani->u.n, ==, 42.5);

    qapi_free_AltNumInt(ani);

}


static int coroutine_fn iscsi_co_writev(BlockDriverState *bs,

                                        int64_t sector_num, int nb_sectors,

                                        QEMUIOVector *iov)

{

    IscsiLun *iscsilun = bs->opaque;

    struct IscsiTask iTask;

    uint64_t lba;

    uint32_t num_sectors;

    uint8_t *data = NULL;

    uint8_t *buf = NULL;

    if (!is_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {

        return -EINVAL;

    }

    lba = sector_qemu2lun(sector_num, iscsilun);

    num_sectors = sector_qemu2lun(nb_sectors, iscsilun);

#if !defined(LIBISCSI_FEATURE_IOVECTOR)

    /* if the iovec only contains one buffer we can pass it directly */

    if (iov->niov == 1) {

        data = iov->iov[0].iov_base;

    } else {

        size_t size = MIN(nb_sectors * BDRV_SECTOR_SIZE, iov->size);

        buf = g_malloc(size);

        qemu_iovec_to_buf(iov, 0, buf, size);

        data = buf;

    }

#endif

    iscsi_co_init_iscsitask(iscsilun, &iTask);

retry:

    if (iscsilun->use_16_for_rw) {

        iTask.task = iscsi_write16_task(iscsilun->iscsi, iscsilun->lun, lba,

                                        data, num_sectors * iscsilun->block_size,

                                        iscsilun->block_size, 0, 0, 0, 0, 0,

                                        iscsi_co_generic_cb, &iTask);

    } else {

        iTask.task = iscsi_write10_task(iscsilun->iscsi, iscsilun->lun, lba,

                                        data, num_sectors * iscsilun->block_size,

                                        iscsilun->block_size, 0, 0, 0, 0, 0,

                                        iscsi_co_generic_cb, &iTask);

    }

    if (iTask.task == NULL) {

        g_free(buf);

        return -ENOMEM;

    }

#if defined(LIBISCSI_FEATURE_IOVECTOR)

    scsi_task_set_iov_out(iTask.task, (struct scsi_iovec *) iov->iov,

                          iov->niov);

#endif

    while (!iTask.complete) {

        iscsi_set_events(iscsilun);

        qemu_coroutine_yield();

    }

    if (iTask.task != NULL) {

        scsi_free_scsi_task(iTask.task);

        iTask.task = NULL;

    }

    if (iTask.do_retry) {

        iTask.complete = 0;

        goto retry;

    }

    g_free(buf);

    if (iTask.status != SCSI_STATUS_GOOD) {

        return -EIO;

    }

    iscsi_allocationmap_set(iscsilun, sector_num, nb_sectors);

    return 0;

}


static void add_sel_entry(IPMIBmcSim *ibs,

                          uint8_t *cmd, unsigned int cmd_len,

                          uint8_t *rsp, unsigned int *rsp_len,

                          unsigned int max_rsp_len)

{

    IPMI_CHECK_CMD_LEN(18);

    if (sel_add_event(ibs, cmd + 2)) {

        rsp[2] = IPMI_CC_OUT_OF_SPACE;

        return;

    }

    /* sel_add_event fills in the record number. */

    IPMI_ADD_RSP_DATA(cmd[2]);

    IPMI_ADD_RSP_DATA(cmd[3]);

}


static void vmdk_free_last_extent(BlockDriverState *bs)

{

    BDRVVmdkState *s = bs->opaque;

    if (s->num_extents == 0) {

        return;

    }

    s->num_extents--;

    s->extents = g_realloc(s->extents, s->num_extents * sizeof(VmdkExtent));

}


static int libschroedinger_encode_frame(AVCodecContext *avctx, AVPacket *pkt,

                                        const AVFrame *frame, int *got_packet)

{

    int enc_size = 0;

    SchroEncoderParams *p_schro_params = avctx->priv_data;

    SchroEncoder *encoder = p_schro_params->encoder;

    struct FFSchroEncodedFrame *p_frame_output = NULL;

    int go = 1;

    SchroBuffer *enc_buf;

    int presentation_frame;

    int parse_code;

    int last_frame_in_sequence = 0;

    int pkt_size, ret;

    if (!frame) {

        /* Push end of sequence if not already signalled. */

        if (!p_schro_params->eos_signalled) {

            schro_encoder_end_of_stream(encoder);

            p_schro_params->eos_signalled = 1;

        }

    } else {

        /* Allocate frame data to schro input buffer. */

        SchroFrame *in_frame = libschroedinger_frame_from_data(avctx, frame);

        if (!in_frame)

            return AVERROR(ENOMEM);

        /* Load next frame. */

        schro_encoder_push_frame(encoder, in_frame);

    }

    if (p_schro_params->eos_pulled)

        go = 0;

    /* Now check to see if we have any output from the encoder. */

    while (go) {

        int err;

        SchroStateEnum state;

        state = schro_encoder_wait(encoder);

        switch (state) {

        case SCHRO_STATE_HAVE_BUFFER:

        case SCHRO_STATE_END_OF_STREAM:

            enc_buf = schro_encoder_pull(encoder, &presentation_frame);

            if (enc_buf->length <= 0)

                return AVERROR_BUG;

            parse_code = enc_buf->data[4];

            /* All non-frame data is prepended to actual frame data to

             * be able to set the pts correctly. So we don't write data

             * to the frame output queue until we actually have a frame

             */

            if ((err = av_reallocp(&p_schro_params->enc_buf,

                                   p_schro_params->enc_buf_size +

                                   enc_buf->length)) < 0) {

                p_schro_params->enc_buf_size = 0;

                return err;

            }

            memcpy(p_schro_params->enc_buf + p_schro_params->enc_buf_size,

                   enc_buf->data, enc_buf->length);

            p_schro_params->enc_buf_size += enc_buf->length;

            if (state == SCHRO_STATE_END_OF_STREAM) {

                p_schro_params->eos_pulled = 1;

                go = 0;

            }

            if (!SCHRO_PARSE_CODE_IS_PICTURE(parse_code)) {

                schro_buffer_unref(enc_buf);

                break;

            }

            /* Create output frame. */

            p_frame_output = av_mallocz(sizeof(FFSchroEncodedFrame));

            if (!p_frame_output)

                return AVERROR(ENOMEM);

            /* Set output data. */

            p_frame_output->size     = p_schro_params->enc_buf_size;

            p_frame_output->p_encbuf = p_schro_params->enc_buf;

            if (SCHRO_PARSE_CODE_IS_INTRA(parse_code) &&

                SCHRO_PARSE_CODE_IS_REFERENCE(parse_code))

                p_frame_output->key_frame = 1;

            /* Parse the coded frame number from the bitstream. Bytes 14

             * through 17 represent the frame number. */

            p_frame_output->frame_num = AV_RB32(enc_buf->data + 13);

            ff_schro_queue_push_back(&p_schro_params->enc_frame_queue,

                                     p_frame_output);

            p_schro_params->enc_buf_size = 0;

            p_schro_params->enc_buf      = NULL;

            schro_buffer_unref(enc_buf);

            break;

        case SCHRO_STATE_NEED_FRAME:

            go = 0;

            break;

        case SCHRO_STATE_AGAIN:

            break;

        default:

            av_log(avctx, AV_LOG_ERROR, "Unknown Schro Encoder state\n");

            return -1;

        }

    }

    /* Copy 'next' frame in queue. */

    if (p_schro_params->enc_frame_queue.size == 1 &&

        p_schro_params->eos_pulled)

        last_frame_in_sequence = 1;

    p_frame_output = ff_schro_queue_pop(&p_schro_params->enc_frame_queue);

    if (!p_frame_output)

        return 0;

    pkt_size = p_frame_output->size;

    if (last_frame_in_sequence && p_schro_params->enc_buf_size > 0)

        pkt_size += p_schro_params->enc_buf_size;

    if ((ret = ff_alloc_packet2(avctx, pkt, pkt_size, 0)) < 0)

        goto error;

    memcpy(pkt->data, p_frame_output->p_encbuf, p_frame_output->size);

#if FF_API_CODED_FRAME

FF_DISABLE_DEPRECATION_WARNINGS

    avctx->coded_frame->key_frame = p_frame_output->key_frame;

    avctx->coded_frame->pts = p_frame_output->frame_num;

FF_ENABLE_DEPRECATION_WARNINGS

#endif

    /* Use the frame number of the encoded frame as the pts. It is OK to

     * do so since Dirac is a constant frame rate codec. It expects input

     * to be of constant frame rate. */

    pkt->pts = p_frame_output->frame_num;

    pkt->dts = p_schro_params->dts++;

    enc_size = p_frame_output->size;

    /* Append the end of sequence information to the last frame in the

     * sequence. */

    if (last_frame_in_sequence && p_schro_params->enc_buf_size > 0) {

        memcpy(pkt->data + enc_size, p_schro_params->enc_buf,

               p_schro_params->enc_buf_size);

        enc_size += p_schro_params->enc_buf_size;

        av_freep(&p_schro_params->enc_buf);

        p_schro_params->enc_buf_size = 0;

    }

    if (p_frame_output->key_frame)

        pkt->flags |= AV_PKT_FLAG_KEY;

    *got_packet = 1;

error:

    /* free frame */

    libschroedinger_free_frame(p_frame_output);

    return ret;

}


static int qcow2_write(BlockDriverState *bs, int64_t sector_num,

                       const uint8_t *buf, int nb_sectors)

{

    Coroutine *co;

    AioContext *aio_context = bdrv_get_aio_context(bs);

    Qcow2WriteCo data = {

        .bs         = bs,

        .sector_num = sector_num,

        .buf        = buf,

        .nb_sectors = nb_sectors,

        .ret        = -EINPROGRESS,

    };

    co = qemu_coroutine_create(qcow2_write_co_entry);

    qemu_coroutine_enter(co, &data);

    while (data.ret == -EINPROGRESS) {

        aio_poll(aio_context, true);

    }

    return data.ret;

}


static void virtio_scsi_hotplug(HotplugHandler *hotplug_dev, DeviceState *dev,

                                Error **errp)

{

    VirtIODevice *vdev = VIRTIO_DEVICE(hotplug_dev);

    VirtIOSCSI *s = VIRTIO_SCSI(vdev);

    SCSIDevice *sd = SCSI_DEVICE(dev);

    if (s->ctx && !s->dataplane_disabled) {

        VirtIOSCSIBlkChangeNotifier *insert_notifier, *remove_notifier;

        if (blk_op_is_blocked(sd->conf.blk, BLOCK_OP_TYPE_DATAPLANE, errp)) {

            return;

        }

        blk_op_block_all(sd->conf.blk, s->blocker);

        aio_context_acquire(s->ctx);

        blk_set_aio_context(sd->conf.blk, s->ctx);

        aio_context_release(s->ctx);

        insert_notifier = g_new0(VirtIOSCSIBlkChangeNotifier, 1);

        insert_notifier->n.notify = virtio_scsi_blk_insert_notifier;

        insert_notifier->s = s;

        insert_notifier->sd = sd;

        blk_add_insert_bs_notifier(sd->conf.blk, &insert_notifier->n);

        QTAILQ_INSERT_TAIL(&s->insert_notifiers, insert_notifier, next);

        remove_notifier = g_new0(VirtIOSCSIBlkChangeNotifier, 1);

        remove_notifier->n.notify = virtio_scsi_blk_remove_notifier;

        remove_notifier->s = s;

        remove_notifier->sd = sd;

        blk_add_remove_bs_notifier(sd->conf.blk, &remove_notifier->n);

        QTAILQ_INSERT_TAIL(&s->remove_notifiers, remove_notifier, next);

    }

    if (virtio_vdev_has_feature(vdev, VIRTIO_SCSI_F_HOTPLUG)) {

        virtio_scsi_push_event(s, sd,

                               VIRTIO_SCSI_T_TRANSPORT_RESET,

                               VIRTIO_SCSI_EVT_RESET_RESCAN);

    }

}