static void rpza_decode_stream(RpzaContext *s)

{

    int width = s->avctx->width;

    int stride = s->frame.linesize[0] / 2;

    int row_inc = stride - 4;

    int stream_ptr = 0;

    int chunk_size;

    unsigned char opcode;

    int n_blocks;

    unsigned short colorA = 0, colorB;

    unsigned short color4[4];

    unsigned char index, idx;

    unsigned short ta, tb;

    unsigned short *pixels = (unsigned short *)s->frame.data[0];

    int row_ptr = 0;

    int pixel_ptr = 0;

    int block_ptr;

    int pixel_x, pixel_y;

    int total_blocks;

    /* First byte is always 0xe1. Warn if it's different */

    if (s->buf[stream_ptr] != 0xe1)

        av_log(s->avctx, AV_LOG_ERROR, "First chunk byte is 0x%02x instead of 0xe1\n",

            s->buf[stream_ptr]);

    /* Get chunk size, ingnoring first byte */

    chunk_size = AV_RB32(&s->buf[stream_ptr]) & 0x00FFFFFF;

    stream_ptr += 4;

    /* If length mismatch use size from MOV file and try to decode anyway */

    if (chunk_size != s->size)

        av_log(s->avctx, AV_LOG_ERROR, "MOV chunk size != encoded chunk size; using MOV chunk size\n");

    chunk_size = s->size;

    /* Number of 4x4 blocks in frame. */

    total_blocks = ((s->avctx->width + 3) / 4) * ((s->avctx->height + 3) / 4);

    /* Process chunk data */

    while (stream_ptr < chunk_size) {

        opcode = s->buf[stream_ptr++]; /* Get opcode */

        n_blocks = (opcode & 0x1f) + 1; /* Extract block counter from opcode */

        /* If opcode MSbit is 0, we need more data to decide what to do */

        if ((opcode & 0x80) == 0) {

            colorA = (opcode << 8) | (s->buf[stream_ptr++]);

            opcode = 0;

            if ((s->buf[stream_ptr] & 0x80) != 0) {

                /* Must behave as opcode 110xxxxx, using colorA computed

                 * above. Use fake opcode 0x20 to enter switch block at

                 * the right place */

                opcode = 0x20;

                n_blocks = 1;

            }

        }

        switch (opcode & 0xe0) {

        /* Skip blocks */

        case 0x80:

            while (n_blocks--) {

              ADVANCE_BLOCK();

            }

            break;

        /* Fill blocks with one color */

        case 0xa0:

            colorA = AV_RB16 (&s->buf[stream_ptr]);

            stream_ptr += 2;

            while (n_blocks--) {

                block_ptr = row_ptr + pixel_ptr;

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

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

                        pixels[block_ptr] = colorA;

                        block_ptr++;

                    }

                    block_ptr += row_inc;

                }

                ADVANCE_BLOCK();

            }

            break;

        /* Fill blocks with 4 colors */

        case 0xc0:

            colorA = AV_RB16 (&s->buf[stream_ptr]);

            stream_ptr += 2;

        case 0x20:

            colorB = AV_RB16 (&s->buf[stream_ptr]);

            stream_ptr += 2;

            /* sort out the colors */

            color4[0] = colorB;

            color4[1] = 0;

            color4[2] = 0;

            color4[3] = colorA;

            /* red components */

            ta = (colorA >> 10) & 0x1F;

            tb = (colorB >> 10) & 0x1F;

            color4[1] |= ((11 * ta + 21 * tb) >> 5) << 10;

            color4[2] |= ((21 * ta + 11 * tb) >> 5) << 10;

            /* green components */

            ta = (colorA >> 5) & 0x1F;

            tb = (colorB >> 5) & 0x1F;

            color4[1] |= ((11 * ta + 21 * tb) >> 5) << 5;

            color4[2] |= ((21 * ta + 11 * tb) >> 5) << 5;

            /* blue components */

            ta = colorA & 0x1F;

            tb = colorB & 0x1F;

            color4[1] |= ((11 * ta + 21 * tb) >> 5);

            color4[2] |= ((21 * ta + 11 * tb) >> 5);

            if (s->size - stream_ptr < n_blocks * 4)

                return;

            while (n_blocks--) {

                block_ptr = row_ptr + pixel_ptr;

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

                    index = s->buf[stream_ptr++];

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

                        idx = (index >> (2 * (3 - pixel_x))) & 0x03;

                        pixels[block_ptr] = color4[idx];

                        block_ptr++;

                    }

                    block_ptr += row_inc;

                }

                ADVANCE_BLOCK();

            }

            break;

        /* Fill block with 16 colors */

        case 0x00:

            if (s->size - stream_ptr < 16)

                return;

            block_ptr = row_ptr + pixel_ptr;

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

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

                    /* We already have color of upper left pixel */

                    if ((pixel_y != 0) || (pixel_x !=0)) {

                        colorA = AV_RB16 (&s->buf[stream_ptr]);

                        stream_ptr += 2;

                    }

                    pixels[block_ptr] = colorA;

                    block_ptr++;

                }

                block_ptr += row_inc;

            }

            ADVANCE_BLOCK();

            break;

        /* Unknown opcode */

        default:

            av_log(s->avctx, AV_LOG_ERROR, "Unknown opcode %d in rpza chunk."

                 " Skip remaining %d bytes of chunk data.\n", opcode,

                 chunk_size - stream_ptr);

            return;

        } /* Opcode switch */

    }

}


int usb_device_attach(USBDevice *dev)

{

    USBBus *bus = usb_bus_from_device(dev);

    if (bus->nfree == 1 && dev->port_path == NULL) {

        /* Create a new hub and chain it on

           (unless a physical port location is specified). */

        usb_create_simple(bus, "usb-hub");

    }

    return do_attach(dev);

}


static void cpu_debug_handler(CPUState *env)

{

    gdb_set_stop_cpu(env);

    qemu_system_debug_request();

}


static uint16_t qpci_spapr_io_readw(QPCIBus *bus, void *addr)

{

    QPCIBusSPAPR *s = container_of(bus, QPCIBusSPAPR, bus);

    uint64_t port = (uintptr_t)addr;

    uint16_t v;

    if (port < s->pio.size) {

        v = readw(s->pio_cpu_base + port);

    } else {

        v = readw(s->mmio_cpu_base + port);

    }

    return bswap16(v);

}


static int ast_read_header(AVFormatContext *s)

{

    int codec;

    AVStream *st;

    st = avformat_new_stream(s, NULL);

    if (!st)

        return AVERROR(ENOMEM);

    avio_skip(s->pb, 8);

    codec = avio_rb16(s->pb);

    switch (codec) {

    case 1:

        st->codec->codec_id = AV_CODEC_ID_PCM_S16BE_PLANAR;

        break;

    default:

        av_log(s, AV_LOG_ERROR, "unsupported codec %d\n", codec);

    }

    avio_skip(s->pb, 2);

    st->codec->codec_type = AVMEDIA_TYPE_AUDIO;

    st->codec->channels = avio_rb16(s->pb);

    if (!st->codec->channels)

        return AVERROR_INVALIDDATA;

    if (st->codec->channels == 2)

        st->codec->channel_layout = AV_CH_LAYOUT_STEREO;

    else if (st->codec->channels == 4)

        st->codec->channel_layout = AV_CH_LAYOUT_4POINT0;

    avio_skip(s->pb, 2);

    st->codec->sample_rate = avio_rb32(s->pb);

    if (st->codec->sample_rate <= 0)

        return AVERROR_INVALIDDATA;

    st->start_time         = 0;

    st->duration           = avio_rb32(s->pb);

    avio_skip(s->pb, 40);

    avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);

    return 0;

}


static av_cold int vsink_init(AVFilterContext *ctx, void *opaque)

{

    BufferSinkContext *buf = ctx->priv;

    AVBufferSinkParams *params = opaque;

    if (params && params->pixel_fmts) {

        const int *pixel_fmts = params->pixel_fmts;

        buf->pixel_fmts = ff_copy_int_list(pixel_fmts);

        if (!buf->pixel_fmts)

            return AVERROR(ENOMEM);

    }

    return common_init(ctx);

}


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

                            int *got_frame_ptr, AVPacket *avpkt)

{

    AACContext *ac = avctx->priv_data;

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    GetBitContext gb;

    int buf_consumed;

    int buf_offset;

    int err;

    int new_extradata_size;

    const uint8_t *new_extradata = av_packet_get_side_data(avpkt,

                                       AV_PKT_DATA_NEW_EXTRADATA,

                                       &new_extradata_size);

    int jp_dualmono_size;

    const uint8_t *jp_dualmono   = av_packet_get_side_data(avpkt,

                                       AV_PKT_DATA_JP_DUALMONO,

                                       &jp_dualmono_size);

    if (new_extradata && 0) {

        av_free(avctx->extradata);

        avctx->extradata = av_mallocz(new_extradata_size +

                                      AV_INPUT_BUFFER_PADDING_SIZE);

        if (!avctx->extradata)

            return AVERROR(ENOMEM);

        avctx->extradata_size = new_extradata_size;

        memcpy(avctx->extradata, new_extradata, new_extradata_size);

        push_output_configuration(ac);

        if (decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,

                                         avctx->extradata,

                                         avctx->extradata_size*8, 1) < 0) {

            pop_output_configuration(ac);

            return AVERROR_INVALIDDATA;

        }

    }

    ac->dmono_mode = 0;

    if (jp_dualmono && jp_dualmono_size > 0)

        ac->dmono_mode =  1 + *jp_dualmono;

    if (ac->force_dmono_mode >= 0)

        ac->dmono_mode = ac->force_dmono_mode;

    if (INT_MAX / 8 <= buf_size)

        return AVERROR_INVALIDDATA;

    if ((err = init_get_bits8(&gb, buf, buf_size)) < 0)

        return err;

    switch (ac->oc[1].m4ac.object_type) {

    case AOT_ER_AAC_LC:

    case AOT_ER_AAC_LTP:

    case AOT_ER_AAC_LD:

    case AOT_ER_AAC_ELD:

        err = aac_decode_er_frame(avctx, data, got_frame_ptr, &gb);

        break;

    default:

        err = aac_decode_frame_int(avctx, data, got_frame_ptr, &gb, avpkt);

    }

    if (err < 0)

        return err;

    buf_consumed = (get_bits_count(&gb) + 7) >> 3;

    for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)

        if (buf[buf_offset])

            break;

    return buf_size > buf_offset ? buf_consumed : buf_size;

}


static void init_proc_book3s_64(CPUPPCState *env, int version)

{

    gen_spr_ne_601(env);

    gen_tbl(env);

    gen_spr_book3s_altivec(env);

    gen_spr_book3s_pmu_sup(env);

    gen_spr_book3s_pmu_user(env);

    gen_spr_book3s_common(env);

    switch (version) {

    case BOOK3S_CPU_970:

    case BOOK3S_CPU_POWER5PLUS:

        gen_spr_970_hid(env);

        gen_spr_970_hior(env);

        gen_low_BATs(env);

        gen_spr_970_pmu_sup(env);

        gen_spr_970_pmu_user(env);

        break;

    case BOOK3S_CPU_POWER7:

    case BOOK3S_CPU_POWER8:

        gen_spr_book3s_ids(env);

        gen_spr_amr(env, version >= BOOK3S_CPU_POWER8);

        gen_spr_book3s_purr(env);

        env->ci_large_pages = true;

        break;

    default:

        g_assert_not_reached();

    }

    if (version >= BOOK3S_CPU_POWER5PLUS) {

        gen_spr_power5p_common(env);

        gen_spr_power5p_lpar(env);

        gen_spr_power5p_ear(env);

    } else {

        gen_spr_970_lpar(env);

    }

    if (version == BOOK3S_CPU_970) {

        gen_spr_970_dbg(env);

    }

    if (version >= BOOK3S_CPU_POWER6) {

        gen_spr_power6_common(env);

        gen_spr_power6_dbg(env);

    }

    if (version == BOOK3S_CPU_POWER7) {

        gen_spr_power7_book4(env);

    }

    if (version >= BOOK3S_CPU_POWER8) {

        gen_spr_power8_tce_address_control(env);

        gen_spr_power8_ids(env);

        gen_spr_power8_ebb(env);

        gen_spr_power8_fscr(env);

        gen_spr_power8_pmu_sup(env);

        gen_spr_power8_pmu_user(env);

        gen_spr_power8_tm(env);

        gen_spr_power8_pspb(env);

        gen_spr_vtb(env);

        gen_spr_power8_ic(env);

        gen_spr_power8_book4(env);

    }

    if (version < BOOK3S_CPU_POWER8) {

        gen_spr_book3s_dbg(env);

    } else {

        gen_spr_book3s_207_dbg(env);

    }

#if !defined(CONFIG_USER_ONLY)

    switch (version) {

    case BOOK3S_CPU_970:

    case BOOK3S_CPU_POWER5PLUS:

        env->slb_nr = 64;

        break;

    case BOOK3S_CPU_POWER7:

    case BOOK3S_CPU_POWER8:

    default:

        env->slb_nr = 32;

        break;

    }

#endif

    /* Allocate hardware IRQ controller */

    switch (version) {

    case BOOK3S_CPU_970:

    case BOOK3S_CPU_POWER5PLUS:

        init_excp_970(env);

        ppc970_irq_init(ppc_env_get_cpu(env));

        break;

    case BOOK3S_CPU_POWER7:

    case BOOK3S_CPU_POWER8:

        init_excp_POWER7(env);

        ppcPOWER7_irq_init(ppc_env_get_cpu(env));

        break;

    default:

        g_assert_not_reached();

    }

    env->dcache_line_size = 128;

    env->icache_line_size = 128;

}


static void virtio_host_initfn(Object *obj)

{

    VirtIOInputHostPCI *dev = VIRTIO_INPUT_HOST_PCI(obj);

    virtio_instance_init_common(obj, &dev->vdev, sizeof(dev->vdev),

                                TYPE_VIRTIO_INPUT_HOST);

}


int qcow2_update_snapshot_refcount(BlockDriverState *bs,

    int64_t l1_table_offset, int l1_size, int addend)

{

    BDRVQcowState *s = bs->opaque;

    uint64_t *l1_table, *l2_table, l2_offset, offset, l1_size2, l1_allocated;

    int64_t old_offset, old_l2_offset;

    int i, j, l1_modified = 0, nb_csectors, refcount;

    int ret;

    l2_table = NULL;

    l1_table = NULL;

    l1_size2 = l1_size * sizeof(uint64_t);

    /* WARNING: qcow2_snapshot_goto relies on this function not using the

     * l1_table_offset when it is the current s->l1_table_offset! Be careful

     * when changing this! */

    if (l1_table_offset != s->l1_table_offset) {

        l1_table = g_malloc0(align_offset(l1_size2, 512));

        l1_allocated = 1;

        ret = bdrv_pread(bs->file, l1_table_offset, l1_table, l1_size2);

        if (ret < 0) {

            goto fail;

        }

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

            be64_to_cpus(&l1_table[i]);

    } else {

        assert(l1_size == s->l1_size);

        l1_table = s->l1_table;

        l1_allocated = 0;

    }

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

        l2_offset = l1_table[i];

        if (l2_offset) {

            old_l2_offset = l2_offset;

            l2_offset &= L1E_OFFSET_MASK;

            ret = qcow2_cache_get(bs, s->l2_table_cache, l2_offset,

                (void**) &l2_table);

            if (ret < 0) {

                goto fail;

            }

            for(j = 0; j < s->l2_size; j++) {

                offset = be64_to_cpu(l2_table[j]);

                if (offset != 0) {

                    old_offset = offset;

                    offset &= ~QCOW_OFLAG_COPIED;

                    if (offset & QCOW_OFLAG_COMPRESSED) {

                        nb_csectors = ((offset >> s->csize_shift) &

                                       s->csize_mask) + 1;

                        if (addend != 0) {

                            int ret;

                            ret = update_refcount(bs,

                                (offset & s->cluster_offset_mask) & ~511,

                                nb_csectors * 512, addend);

                            if (ret < 0) {

                                goto fail;

                            }

                        }

                        /* compressed clusters are never modified */

                        refcount = 2;

                    } else {

                        uint64_t cluster_index = (offset & L2E_OFFSET_MASK) >> s->cluster_bits;

                        if (addend != 0) {

                            refcount = update_cluster_refcount(bs, cluster_index, addend);

                        } else {

                            refcount = get_refcount(bs, cluster_index);

                        }

                        if (refcount < 0) {

                            ret = refcount;

                            goto fail;

                        }

                    }

                    if (refcount == 1) {

                        offset |= QCOW_OFLAG_COPIED;

                    }

                    if (offset != old_offset) {

                        if (addend > 0) {

                            qcow2_cache_set_dependency(bs, s->l2_table_cache,

                                s->refcount_block_cache);

                        }

                        l2_table[j] = cpu_to_be64(offset);

                        qcow2_cache_entry_mark_dirty(s->l2_table_cache, l2_table);

                    }

                }

            }

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

            if (ret < 0) {

                goto fail;

            }

            if (addend != 0) {

                refcount = update_cluster_refcount(bs, l2_offset >> s->cluster_bits, addend);

            } else {

                refcount = get_refcount(bs, l2_offset >> s->cluster_bits);

            }

            if (refcount < 0) {

                ret = refcount;

                goto fail;

            } else if (refcount == 1) {

                l2_offset |= QCOW_OFLAG_COPIED;

            }

            if (l2_offset != old_l2_offset) {

                l1_table[i] = l2_offset;

                l1_modified = 1;

            }

        }

    }

    ret = bdrv_flush(bs);

fail:

    if (l2_table) {

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

    }

    /* Update L1 only if it isn't deleted anyway (addend = -1) */

    if (addend >= 0 && l1_modified) {

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

            cpu_to_be64s(&l1_table[i]);

        if (bdrv_pwrite_sync(bs->file, l1_table_offset, l1_table,

                        l1_size2) < 0)

            goto fail;

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

            be64_to_cpus(&l1_table[i]);

    }

    if (l1_allocated)

        g_free(l1_table);

    return ret;

}


int ff_dirac_golomb_read_32bit(DiracGolombLUT *lut_ctx, const uint8_t *buf,
                               int bytes, uint8_t *_dst, int coeffs)
{
    int i, b, c_idx = 0;
    int32_t *dst = (int32_t *)_dst;
    DiracGolombLUT *future[4], *l = &lut_ctx[2*LUT_SIZE + buf[0]];
    INIT_RESIDUE(res);
    for (b = 1; b <= bytes; b++) {
        future[0] = &lut_ctx[buf[b]];
        future[1] = future[0] + 1*LUT_SIZE;
        future[2] = future[0] + 2*LUT_SIZE;
        future[3] = future[0] + 3*LUT_SIZE;
        if ((c_idx + 1) > coeffs)
            return c_idx;
        /* res_bits is a hint for better branch prediction */
        if (res_bits && l->sign) {
            int32_t coeff = 1;
            APPEND_RESIDUE(res, l->preamble);
            for (i = 0; i < (res_bits >> 1) - 1; i++) {
                coeff <<= 1;
                coeff |= (res >> (RSIZE_BITS - 2*i - 2)) & 1;
            }
            dst[c_idx++] = l->sign * (coeff - 1);
        }
        memcpy(&dst[c_idx], l->ready, LUT_BITS*sizeof(int32_t));
        c_idx += l->ready_num;
        APPEND_RESIDUE(res, l->leftover);
        l = future[l->need_s ? 3 : !res_bits ? 2 : res_bits & 1];
    }
    return c_idx;
}


static uint32_t syborg_virtio_readl(void *opaque, target_phys_addr_t offset)

{

    SyborgVirtIOProxy *s = opaque;

    VirtIODevice *vdev = s->vdev;

    uint32_t ret;

    DPRINTF("readl 0x%x\n", (int)offset);

    if (offset >= SYBORG_VIRTIO_CONFIG) {

        return virtio_config_readl(vdev, offset - SYBORG_VIRTIO_CONFIG);

    }

    switch(offset >> 2) {

    case SYBORG_VIRTIO_ID:

        ret = SYBORG_ID_VIRTIO;

        break;

    case SYBORG_VIRTIO_DEVTYPE:

        ret = s->id;

        break;

    case SYBORG_VIRTIO_HOST_FEATURES:

        ret = vdev->get_features(vdev);

        ret |= (1 << VIRTIO_F_NOTIFY_ON_EMPTY);

        break;

    case SYBORG_VIRTIO_GUEST_FEATURES:

        ret = vdev->features;

        break;

    case SYBORG_VIRTIO_QUEUE_BASE:

        ret = virtio_queue_get_addr(vdev, vdev->queue_sel);

        break;

    case SYBORG_VIRTIO_QUEUE_NUM:

        ret = virtio_queue_get_num(vdev, vdev->queue_sel);

        break;

    case SYBORG_VIRTIO_QUEUE_SEL:

        ret = vdev->queue_sel;

        break;

    case SYBORG_VIRTIO_STATUS:

        ret = vdev->status;

        break;

    case SYBORG_VIRTIO_INT_ENABLE:

        ret = s->int_enable;

        break;

    case SYBORG_VIRTIO_INT_STATUS:

        ret = vdev->isr;

        break;

    default:

        BADF("Bad read offset 0x%x\n", (int)offset);

        return 0;

    }

    return ret;

}


static int nfs_file_create(const char *url, QemuOpts *opts, Error **errp)

{

    int ret = 0;

    int64_t total_size = 0;

    NFSClient *client = g_new0(NFSClient, 1);

    QDict *options = NULL;

    client->aio_context = qemu_get_aio_context();

    /* Read out options */

    total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),

                          BDRV_SECTOR_SIZE);

    options = qdict_new();

    ret = nfs_parse_uri(url, options, errp);

    if (ret < 0) {

        goto out;

    }

    ret = nfs_client_open(client, options, O_CREAT, errp, 0);

    if (ret < 0) {

        goto out;

    }

    ret = nfs_ftruncate(client->context, client->fh, total_size);

    nfs_client_close(client);

out:

    g_free(client);

    return ret;

}


int setenv(const char *name, const char *value, int overwrite)
{
    int result = 0;
    if (overwrite || !getenv(name)) {
        size_t length = strlen(name) + strlen(value) + 2;
        char *string = g_malloc(length);
        snprintf(string, length, "%s=%s", name, value);
        result = putenv(string);
    }
    return result;
}


static void clone_tables(H264Context *dst, H264Context *src){

    dst->intra4x4_pred_mode       = src->intra4x4_pred_mode;

    dst->non_zero_count           = src->non_zero_count;

    dst->slice_table              = src->slice_table;

    dst->cbp_table                = src->cbp_table;

    dst->mb2b_xy                  = src->mb2b_xy;

    dst->mb2b8_xy                 = src->mb2b8_xy;

    dst->chroma_pred_mode_table   = src->chroma_pred_mode_table;

    dst->mvd_table[0]             = src->mvd_table[0];

    dst->mvd_table[1]             = src->mvd_table[1];

    dst->direct_table             = src->direct_table;

    if(!dst->dequant4_coeff[0])

        init_dequant_tables(dst);

    dst->s.obmc_scratchpad = NULL;

    ff_h264_pred_init(&dst->hpc, src->s.codec_id);

    dst->dequant_coeff_pps= -1;

}


static void adb_kbd_reset(DeviceState *dev)

{

    ADBDevice *d = ADB_DEVICE(dev);

    KBDState *s = ADB_KEYBOARD(dev);

    d->handler = 1;

    d->devaddr = ADB_DEVID_KEYBOARD;

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

    s->rptr = 0;

    s->wptr = 0;

    s->count = 0;

}


static int mjpeg_decode_scan(MJpegDecodeContext *s, int nb_components, int Ah, int Al,

                             const uint8_t *mb_bitmask, const AVFrame *reference){

    int i, mb_x, mb_y;

    uint8_t* data[MAX_COMPONENTS];

    const uint8_t *reference_data[MAX_COMPONENTS];

    int linesize[MAX_COMPONENTS];

    GetBitContext mb_bitmask_gb;

    if (mb_bitmask) {

        init_get_bits(&mb_bitmask_gb, mb_bitmask, s->mb_width*s->mb_height);

    if(s->flipped && s->avctx->flags & CODEC_FLAG_EMU_EDGE) {

        av_log(s->avctx, AV_LOG_ERROR, "Can not flip image with CODEC_FLAG_EMU_EDGE set!\n");

        s->flipped = 0;

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

        int c = s->comp_index[i];

        data[c] = s->picture_ptr->data[c];

        reference_data[c] = reference ? reference->data[c] : NULL;

        linesize[c]=s->linesize[c];

        s->coefs_finished[c] |= 1;

        if(s->flipped) {

            //picture should be flipped upside-down for this codec

            int offset = (linesize[c] * (s->v_scount[i] * (8 * s->mb_height -((s->height/s->v_max)&7)) - 1 ));

            data[c] += offset;

            reference_data[c] += offset;

            linesize[c] *= -1;

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

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

            const int copy_mb = mb_bitmask && !get_bits1(&mb_bitmask_gb);

            if (s->restart_interval && !s->restart_count)

                s->restart_count = s->restart_interval;

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

                uint8_t *ptr;

                int n, h, v, x, y, c, j;

                int block_offset;

                n = s->nb_blocks[i];

                c = s->comp_index[i];

                h = s->h_scount[i];

                v = s->v_scount[i];

                x = 0;

                y = 0;

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

                    block_offset = (((linesize[c] * (v * mb_y + y) * 8) +

                                     (h * mb_x + x) * 8) >> s->avctx->lowres);

                    if(s->interlaced && s->bottom_field)

                        block_offset += linesize[c] >> 1;

                    ptr = data[c] + block_offset;

                    if(!s->progressive) {

                        if (copy_mb) {

                            mjpeg_copy_block(ptr, reference_data[c] + block_offset, linesize[c], s->avctx->lowres);

                        } else {

                        s->dsp.clear_block(s->block);

                        if(decode_block(s, s->block, i,

                                     s->dc_index[i], s->ac_index[i],

                                     s->quant_matrixes[ s->quant_index[c] ]) < 0) {

                            av_log(s->avctx, AV_LOG_ERROR, "error y=%d x=%d\n", mb_y, mb_x);

                        s->dsp.idct_put(ptr, linesize[c], s->block);

                    } else {

                        int block_idx = s->block_stride[c] * (v * mb_y + y) + (h * mb_x + x);

                        DCTELEM *block = s->blocks[c][block_idx];

                        if(Ah)

                            block[0] += get_bits1(&s->gb) * s->quant_matrixes[ s->quant_index[c] ][0] << Al;

                        else if(decode_dc_progressive(s, block, i, s->dc_index[i], s->quant_matrixes[ s->quant_index[c] ], Al) < 0) {

                            av_log(s->avctx, AV_LOG_ERROR, "error y=%d x=%d\n", mb_y, mb_x);

//                    av_log(s->avctx, AV_LOG_DEBUG, "mb: %d %d processed\n", mb_y, mb_x);

//av_log(NULL, AV_LOG_DEBUG, "%d %d %d %d %d %d %d %d \n", mb_x, mb_y, x, y, c, s->bottom_field, (v * mb_y + y) * 8, (h * mb_x + x) * 8);

                    if (++x == h) {

                        x = 0;

                        y++;

            if (s->restart_interval && !--s->restart_count) {

                align_get_bits(&s->gb);

                skip_bits(&s->gb, 16); /* skip RSTn */

                for (i=0; i<nb_components; i++) /* reset dc */

                    s->last_dc[i] = 1024;

    return 0;


static int flv_data_packet(AVFormatContext *s, AVPacket *pkt,

                           int64_t dts, int64_t next)

{

    AVIOContext *pb = s->pb;

    AVStream *st    = NULL;

    char buf[20];

    int ret = AVERROR_INVALIDDATA;

    int i, length = -1;

    switch (avio_r8(pb)) {

    case AMF_DATA_TYPE_MIXEDARRAY:

        avio_seek(pb, 4, SEEK_CUR);

    case AMF_DATA_TYPE_OBJECT:

        break;

    default:

        goto skip;

    }

    while ((ret = amf_get_string(pb, buf, sizeof(buf))) > 0) {

        AMFDataType type = avio_r8(pb);

        if (type == AMF_DATA_TYPE_STRING && !strcmp(buf, "text")) {

            length = avio_rb16(pb);

            ret    = av_get_packet(pb, pkt, length);

            if (ret < 0)

                goto skip;

            else

                break;

        } else {

            if ((ret = amf_skip_tag(pb, type)) < 0)

                goto skip;

        }

    }

    if (length < 0) {

        ret = AVERROR_INVALIDDATA;

        goto skip;

    }

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

        st = s->streams[i];

        if (st->codec->codec_type == AVMEDIA_TYPE_DATA)

            break;

    }

    if (i == s->nb_streams) {

        st = create_stream(s, AVMEDIA_TYPE_DATA);

        if (!st)

            return AVERROR_INVALIDDATA;

        st->codec->codec_id = AV_CODEC_ID_TEXT;

    }

    pkt->dts  = dts;

    pkt->pts  = dts;

    pkt->size = ret;

    pkt->stream_index = st->index;

    pkt->flags       |= AV_PKT_FLAG_KEY;

skip:

    avio_seek(s->pb, next + 4, SEEK_SET);

    return ret;

}


void ff_h264_write_back_intra_pred_mode(H264Context *h){

    int8_t *mode= h->intra4x4_pred_mode + h->mb2br_xy[h->mb_xy];

    AV_COPY32(mode, h->intra4x4_pred_mode_cache + 4 + 8*4);

    mode[4]= h->intra4x4_pred_mode_cache[7+8*3];

    mode[5]= h->intra4x4_pred_mode_cache[7+8*2];

    mode[6]= h->intra4x4_pred_mode_cache[7+8*1];

}


static int noise(AVBitStreamFilterContext *bsfc, AVCodecContext *avctx, const char *args,
                     uint8_t **poutbuf, int *poutbuf_size,
                     const uint8_t *buf, int buf_size, int keyframe){
    unsigned int *state= bsfc->priv_data;
    int amount= args ? atoi(args) : (*state % 10001+1);
    int i;
    *poutbuf= av_malloc(buf_size + FF_INPUT_BUFFER_PADDING_SIZE);
    memcpy(*poutbuf, buf, buf_size + FF_INPUT_BUFFER_PADDING_SIZE);
    for(i=0; i<buf_size; i++){
        (*state) += (*poutbuf)[i] + 1;
        if(*state % amount == 0)
            (*poutbuf)[i] = *state;
    }
    return 1;
}


static int mjpeg_decode_scan(MJpegDecodeContext *s, int nb_components, int Ah, int Al,

                             const uint8_t *mb_bitmask, const AVFrame *reference){

    int i, mb_x, mb_y;

    uint8_t* data[MAX_COMPONENTS];

    const uint8_t *reference_data[MAX_COMPONENTS];

    int linesize[MAX_COMPONENTS];

    GetBitContext mb_bitmask_gb;

    if (mb_bitmask) {

        init_get_bits(&mb_bitmask_gb, mb_bitmask, s->mb_width*s->mb_height);

    }

    if(s->flipped && s->avctx->flags & CODEC_FLAG_EMU_EDGE) {

        av_log(s->avctx, AV_LOG_ERROR, "Can not flip image with CODEC_FLAG_EMU_EDGE set!\n");

        s->flipped = 0;

    }

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

        int c = s->comp_index[i];

        data[c] = s->picture_ptr->data[c];

        reference_data[c] = reference ? reference->data[c] : NULL;

        linesize[c]=s->linesize[c];

        s->coefs_finished[c] |= 1;

        if(s->flipped) {

            //picture should be flipped upside-down for this codec

            int offset = (linesize[c] * (s->v_scount[i] * (8 * s->mb_height -((s->height/s->v_max)&7)) - 1 ));

            data[c] += offset;

            reference_data[c] += offset;

            linesize[c] *= -1;

        }

    }

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

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

            const int copy_mb = mb_bitmask && !get_bits1(&mb_bitmask_gb);

            if (s->restart_interval && !s->restart_count)

                s->restart_count = s->restart_interval;

            if(get_bits_count(&s->gb)>s->gb.size_in_bits){

                av_log(s->avctx, AV_LOG_ERROR, "overread %d\n", get_bits_count(&s->gb) - s->gb.size_in_bits);

                return -1;

            }

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

                uint8_t *ptr;

                int n, h, v, x, y, c, j;

                int block_offset;

                n = s->nb_blocks[i];

                c = s->comp_index[i];

                h = s->h_scount[i];

                v = s->v_scount[i];

                x = 0;

                y = 0;

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

                    block_offset = (((linesize[c] * (v * mb_y + y) * 8) +

                                     (h * mb_x + x) * 8) >> s->avctx->lowres);

                    if(s->interlaced && s->bottom_field)

                        block_offset += linesize[c] >> 1;

                    ptr = data[c] + block_offset;

                    if(!s->progressive) {

                        if (copy_mb) {

                            mjpeg_copy_block(ptr, reference_data[c] + block_offset, linesize[c], s->avctx->lowres);

                        } else {

                        s->dsp.clear_block(s->block);

                        if(decode_block(s, s->block, i,

                                     s->dc_index[i], s->ac_index[i],

                                     s->quant_matrixes[ s->quant_index[c] ]) < 0) {

                            av_log(s->avctx, AV_LOG_ERROR, "error y=%d x=%d\n", mb_y, mb_x);

                            return -1;

                        }

                        s->dsp.idct_put(ptr, linesize[c], s->block);

                        }

                    } else {

                        int block_idx = s->block_stride[c] * (v * mb_y + y) + (h * mb_x + x);

                        DCTELEM *block = s->blocks[c][block_idx];

                        if(Ah)

                            block[0] += get_bits1(&s->gb) * s->quant_matrixes[ s->quant_index[c] ][0] << Al;

                        else if(decode_dc_progressive(s, block, i, s->dc_index[i], s->quant_matrixes[ s->quant_index[c] ], Al) < 0) {

                            av_log(s->avctx, AV_LOG_ERROR, "error y=%d x=%d\n", mb_y, mb_x);

                            return -1;

                        }

                    }

//                    av_log(s->avctx, AV_LOG_DEBUG, "mb: %d %d processed\n", mb_y, mb_x);

//av_log(NULL, AV_LOG_DEBUG, "%d %d %d %d %d %d %d %d \n", mb_x, mb_y, x, y, c, s->bottom_field, (v * mb_y + y) * 8, (h * mb_x + x) * 8);

                    if (++x == h) {

                        x = 0;

                        y++;

                    }

                }

            }

            if (s->restart_interval && show_bits(&s->gb, 8) == 0xFF){ /* skip RSTn */

                --s->restart_count;

                align_get_bits(&s->gb);

                while(show_bits(&s->gb, 8) == 0xFF)

                    skip_bits(&s->gb, 8);

                skip_bits(&s->gb, 8);

                for (i=0; i<nb_components; i++) /* reset dc */

                    s->last_dc[i] = 1024;

            }

        }

    }

    return 0;

}


static void qcow2_invalidate_cache(BlockDriverState *bs)
{
    BDRVQcowState *s = bs->opaque;
    int flags = s->flags;
    AES_KEY aes_encrypt_key;
    AES_KEY aes_decrypt_key;
    uint32_t crypt_method = 0;
    QDict *options;
    /*
     * Backing files are read-only which makes all of their metadata immutable,
     * that means we don't have to worry about reopening them here.
     */
    if (s->crypt_method) {
        crypt_method = s->crypt_method;
        memcpy(&aes_encrypt_key, &s->aes_encrypt_key, sizeof(aes_encrypt_key));
        memcpy(&aes_decrypt_key, &s->aes_decrypt_key, sizeof(aes_decrypt_key));
    }
    qcow2_close(bs);
    options = qdict_new();
    qdict_put(options, QCOW2_OPT_LAZY_REFCOUNTS,
              qbool_from_int(s->use_lazy_refcounts));
    memset(s, 0, sizeof(BDRVQcowState));
    qcow2_open(bs, options, flags, NULL);
    QDECREF(options);
    if (crypt_method) {
        s->crypt_method = crypt_method;
        memcpy(&s->aes_encrypt_key, &aes_encrypt_key, sizeof(aes_encrypt_key));
        memcpy(&s->aes_decrypt_key, &aes_decrypt_key, sizeof(aes_decrypt_key));
    }
}


static av_cold int avui_encode_init(AVCodecContext *avctx)

{

    avctx->coded_frame = av_frame_alloc();

    if (avctx->width != 720 || avctx->height != 486 && avctx->height != 576) {

        av_log(avctx, AV_LOG_ERROR, "Only 720x486 and 720x576 are supported.\n");

        return AVERROR(EINVAL);

    }

    if (!avctx->coded_frame) {

        av_log(avctx, AV_LOG_ERROR, "Could not allocate frame.\n");

        return AVERROR(ENOMEM);

    }

    if (!(avctx->extradata = av_mallocz(24 + FF_INPUT_BUFFER_PADDING_SIZE)))

        return AVERROR(ENOMEM);

    avctx->extradata_size = 24;

    memcpy(avctx->extradata, "\0\0\0\x18""APRGAPRG0001", 16);

    if (avctx->field_order > AV_FIELD_PROGRESSIVE) {

        avctx->extradata[19] = 2;

    } else {

        avctx->extradata[19] = 1;

    }

    return 0;

}


void acpi_pm1_evt_write_sts(ACPIREGS *ar, uint16_t val)

{

    uint16_t pm1_sts = acpi_pm1_evt_get_sts(ar, ar->tmr.overflow_time);

    if (pm1_sts & val & ACPI_BITMASK_TIMER_STATUS) {

        /* if TMRSTS is reset, then compute the new overflow time */

        acpi_pm_tmr_calc_overflow_time(ar);

    }

    ar->pm1.evt.sts &= ~val;

}


static int decode_frame(AVCodecContext * avctx, void *data, int *got_frame_ptr,

                        AVPacket *avpkt)

{

    const uint8_t *buf  = avpkt->data;

    int buf_size        = avpkt->size;

    MPADecodeContext *s = avctx->priv_data;

    uint32_t header;

    int ret;

    if (buf_size < HEADER_SIZE)

        return AVERROR_INVALIDDATA;

    header = AV_RB32(buf);

    if (ff_mpa_check_header(header) < 0) {

        av_log(avctx, AV_LOG_ERROR, "Header missing\n");

        return AVERROR_INVALIDDATA;

    }

    if (avpriv_mpegaudio_decode_header((MPADecodeHeader *)s, header) == 1) {

        /* free format: prepare to compute frame size */

        s->frame_size = -1;

        return AVERROR_INVALIDDATA;

    }

    /* update codec info */

    avctx->channels       = s->nb_channels;

    avctx->channel_layout = s->nb_channels == 1 ? AV_CH_LAYOUT_MONO : AV_CH_LAYOUT_STEREO;

    if (!avctx->bit_rate)

        avctx->bit_rate = s->bit_rate;

    s->frame = data;

    ret = mp_decode_frame(s, NULL, buf, buf_size);

    if (ret >= 0) {

        s->frame->nb_samples = avctx->frame_size;

        *got_frame_ptr       = 1;

        avctx->sample_rate   = s->sample_rate;

        //FIXME maybe move the other codec info stuff from above here too

    } else {

        av_log(avctx, AV_LOG_ERROR, "Error while decoding MPEG audio frame.\n");

        /* Only return an error if the bad frame makes up the whole packet or

         * the error is related to buffer management.

         * If there is more data in the packet, just consume the bad frame

         * instead of returning an error, which would discard the whole

         * packet. */

        *got_frame_ptr = 0;

        if (buf_size == avpkt->size || ret != AVERROR_INVALIDDATA)

            return ret;

    }

    s->frame_size = 0;

    return buf_size;

}


int attribute_align_arg avcodec_open2(AVCodecContext *avctx, AVCodec *codec, AVDictionary **options)

{

    int ret = 0;

    AVDictionary *tmp = NULL;

    if (avcodec_is_open(avctx))

        return 0;

    if ((!codec && !avctx->codec)) {

        av_log(avctx, AV_LOG_ERROR, "No codec provided to avcodec_open2().\n");

        return AVERROR(EINVAL);

    }

    if ((codec && avctx->codec && codec != avctx->codec)) {

        av_log(avctx, AV_LOG_ERROR, "This AVCodecContext was allocated for %s, "

               "but %s passed to avcodec_open2().\n", avctx->codec->name, codec->name);

        return AVERROR(EINVAL);

    }

    if (!codec)

        codec = avctx->codec;

    if (avctx->extradata_size < 0 || avctx->extradata_size >= FF_MAX_EXTRADATA_SIZE)

        return AVERROR(EINVAL);

    if (options)

        av_dict_copy(&tmp, *options, 0);

    /* If there is a user-supplied mutex locking routine, call it. */

    if (ff_lockmgr_cb) {

        if ((*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))

            return -1;

    }

    entangled_thread_counter++;

    if(entangled_thread_counter != 1){

        av_log(avctx, AV_LOG_ERROR, "insufficient thread locking around avcodec_open/close()\n");

        ret = -1;

        goto end;

    }

    avctx->internal = av_mallocz(sizeof(AVCodecInternal));

    if (!avctx->internal) {

        ret = AVERROR(ENOMEM);

        goto end;

    }

    if (codec->priv_data_size > 0) {

      if(!avctx->priv_data){

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

        if (!avctx->priv_data) {

            ret = AVERROR(ENOMEM);

            goto end;

        }

        if (codec->priv_class) {

            *(const AVClass**)avctx->priv_data= codec->priv_class;

            av_opt_set_defaults(avctx->priv_data);

        }

      }

      if (codec->priv_class && (ret = av_opt_set_dict(avctx->priv_data, &tmp)) < 0)

          goto free_and_end;

    } else {

        avctx->priv_data = NULL;

    }

    if ((ret = av_opt_set_dict(avctx, &tmp)) < 0)

        goto free_and_end;

    if (codec->capabilities & CODEC_CAP_EXPERIMENTAL)

        if (avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {

            av_log(avctx, AV_LOG_ERROR, "Codec is experimental but experimental codecs are not enabled, try -strict -2\n");

            ret = -1;

            goto free_and_end;

        }

    //We only call avcodec_set_dimensions() for non h264 codecs so as not to overwrite previously setup dimensions

    if(!( avctx->coded_width && avctx->coded_height && avctx->width && avctx->height && avctx->codec_id == CODEC_ID_H264)){

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

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

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

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

    }

    if ((avctx->coded_width || avctx->coded_height || avctx->width || avctx->height)

        && (  av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx) < 0

           || av_image_check_size(avctx->width,       avctx->height,       0, avctx) < 0)) {

        av_log(avctx, AV_LOG_WARNING, "ignoring invalid width/height values\n");

        avcodec_set_dimensions(avctx, 0, 0);

    }

    /* if the decoder init function was already called previously,

       free the already allocated subtitle_header before overwriting it */

    if (av_codec_is_decoder(codec))

        av_freep(&avctx->subtitle_header);

#define SANE_NB_CHANNELS 128U

    if (avctx->channels > SANE_NB_CHANNELS) {

        ret = AVERROR(EINVAL);

        goto free_and_end;

    }

    avctx->codec = codec;

    if ((avctx->codec_type == AVMEDIA_TYPE_UNKNOWN || avctx->codec_type == codec->type) &&

        avctx->codec_id == CODEC_ID_NONE) {

        avctx->codec_type = codec->type;

        avctx->codec_id   = codec->id;

    }

    if (avctx->codec_id != codec->id || (avctx->codec_type != codec->type

                           && avctx->codec_type != AVMEDIA_TYPE_ATTACHMENT)) {

        av_log(avctx, AV_LOG_ERROR, "codec type or id mismatches\n");

        ret = AVERROR(EINVAL);

        goto free_and_end;

    }

    avctx->frame_number = 0;

    if (avctx->codec_type == AVMEDIA_TYPE_AUDIO &&

        (!avctx->time_base.num || !avctx->time_base.den)) {

        avctx->time_base.num = 1;

        avctx->time_base.den = avctx->sample_rate;

    }

    if (!HAVE_THREADS)

        av_log(avctx, AV_LOG_WARNING, "Warning: not compiled with thread support, using thread emulation\n");

    if (HAVE_THREADS && !avctx->thread_opaque) {

        ret = ff_thread_init(avctx);

        if (ret < 0) {

            goto free_and_end;

        }

    }

    if (!HAVE_THREADS && !(codec->capabilities & CODEC_CAP_AUTO_THREADS))

        avctx->thread_count = 1;

    if (avctx->codec->max_lowres < avctx->lowres || avctx->lowres < 0) {

        av_log(avctx, AV_LOG_ERROR, "The maximum value for lowres supported by the decoder is %d\n",

               avctx->codec->max_lowres);

        ret = AVERROR(EINVAL);

        goto free_and_end;

    }

    if (av_codec_is_encoder(avctx->codec)) {

        int i;

        if (avctx->codec->sample_fmts) {

            for (i = 0; avctx->codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; i++)

                if (avctx->sample_fmt == avctx->codec->sample_fmts[i])

                    break;

            if (avctx->codec->sample_fmts[i] == AV_SAMPLE_FMT_NONE) {

                av_log(avctx, AV_LOG_ERROR, "Specified sample_fmt is not supported.\n");

                ret = AVERROR(EINVAL);

                goto free_and_end;

            }

        }

        if (avctx->codec->pix_fmts) {

            for (i = 0; avctx->codec->pix_fmts[i] != PIX_FMT_NONE; i++)

                if (avctx->pix_fmt == avctx->codec->pix_fmts[i])

                    break;

            if (avctx->codec->pix_fmts[i] == PIX_FMT_NONE

                && !((avctx->codec_id == CODEC_ID_MJPEG || avctx->codec_id == CODEC_ID_LJPEG)

                     && avctx->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL)) {

                av_log(avctx, AV_LOG_ERROR, "Specified pix_fmt is not supported\n");

                ret = AVERROR(EINVAL);

                goto free_and_end;

            }

        }

        if (avctx->codec->supported_samplerates) {

            for (i = 0; avctx->codec->supported_samplerates[i] != 0; i++)

                if (avctx->sample_rate == avctx->codec->supported_samplerates[i])

                    break;

            if (avctx->codec->supported_samplerates[i] == 0) {

                av_log(avctx, AV_LOG_ERROR, "Specified sample_rate is not supported\n");

                ret = AVERROR(EINVAL);

                goto free_and_end;

            }

        }

        if (avctx->codec->channel_layouts) {

            if (!avctx->channel_layout) {

                av_log(avctx, AV_LOG_WARNING, "channel_layout not specified\n");

            } else {

                for (i = 0; avctx->codec->channel_layouts[i] != 0; i++)

                    if (avctx->channel_layout == avctx->codec->channel_layouts[i])

                        break;

                if (avctx->codec->channel_layouts[i] == 0) {

                    av_log(avctx, AV_LOG_ERROR, "Specified channel_layout is not supported\n");

                    ret = AVERROR(EINVAL);

                    goto free_and_end;

                }

            }

        }

        if (avctx->channel_layout && avctx->channels) {

            if (av_get_channel_layout_nb_channels(avctx->channel_layout) != avctx->channels) {

                av_log(avctx, AV_LOG_ERROR, "channel layout does not match number of channels\n");

                ret = AVERROR(EINVAL);

                goto free_and_end;

            }

        } else if (avctx->channel_layout) {

            avctx->channels = av_get_channel_layout_nb_channels(avctx->channel_layout);

        }

    }

    avctx->pts_correction_num_faulty_pts =

    avctx->pts_correction_num_faulty_dts = 0;

    avctx->pts_correction_last_pts =

    avctx->pts_correction_last_dts = INT64_MIN;

    if(avctx->codec->init && !(avctx->active_thread_type&FF_THREAD_FRAME)){

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

        if (ret < 0) {

            goto free_and_end;

        }

    }

    ret=0;

    if (av_codec_is_decoder(avctx->codec)) {

        if (!avctx->bit_rate)

            avctx->bit_rate = get_bit_rate(avctx);

        /* validate channel layout from the decoder */

        if (avctx->channel_layout &&

            av_get_channel_layout_nb_channels(avctx->channel_layout) != avctx->channels) {

            av_log(avctx, AV_LOG_WARNING, "channel layout does not match number of channels\n");

            avctx->channel_layout = 0;

        }

    }

end:

    entangled_thread_counter--;

    /* Release any user-supplied mutex. */

    if (ff_lockmgr_cb) {

        (*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE);

    }

    if (options) {

        av_dict_free(options);

        *options = tmp;

    }

    return ret;

free_and_end:

    av_dict_free(&tmp);

    av_freep(&avctx->priv_data);

    av_freep(&avctx->internal);

    avctx->codec= NULL;

    goto end;

}


static int get_transform_coeffs1(uint8_t *exps, uint8_t *bap, float chcoeff,

        float *coeffs, int start, int end, int dith_flag, GetBitContext *gb,

        dither_state *state)

{

    int16_t mantissa;

    int i;

    int gcode;

    mant_group l3_grp, l5_grp, l11_grp;

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

        l3_grp.gcodes[i] = l5_grp.gcodes[i] = l11_grp.gcodes[i] = -1;

    l3_grp.gcptr = l5_grp.gcptr = 3;

    l11_grp.gcptr = 2;

    i = 0;

    while (i < start)

        coeffs[i++] = 0;

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

        switch (bap[i]) {

            case 0:

                if (!dith_flag) {

                    coeffs[i] = 0;

                    continue;

                }

                else {

                    mantissa = dither_int16(state);

                    coeffs[i] = to_float(exps[i], mantissa) * chcoeff;

                    continue;

                }

            case 1:

                if (l3_grp.gcptr > 2) {

                    gcode = get_bits(gb, 5);

                    if (gcode > 26)

                        return -1;

                    l3_grp.gcodes[0] = gcode / 9;

                    l3_grp.gcodes[1] = (gcode % 9) / 3;

                    l3_grp.gcodes[2] = (gcode % 9) % 3;

                    l3_grp.gcptr = 0;

                }

                mantissa = l3_q_tab[l3_grp.gcodes[l3_grp.gcptr++]];

                coeffs[i] = to_float(exps[i], mantissa) * chcoeff;

                continue;

            case 2:

                if (l5_grp.gcptr > 2) {

                    gcode = get_bits(gb, 7);

                    if (gcode > 124)

                        return -1;

                    l5_grp.gcodes[0] = gcode / 25;

                    l5_grp.gcodes[1] = (gcode % 25) / 5;

                    l5_grp.gcodes[2] = (gcode % 25) % 5;

                    l5_grp.gcptr = 0;

                }

                mantissa = l5_q_tab[l5_grp.gcodes[l5_grp.gcptr++]];

                coeffs[i] = to_float(exps[i], mantissa) * chcoeff;

                continue;

            case 3:

                mantissa = get_bits(gb, 3);

                if (mantissa > 6)

                    return -1;

                mantissa = l7_q_tab[mantissa];

                coeffs[i] = to_float(exps[i], mantissa);

                continue;

            case 4:

                if (l11_grp.gcptr > 1) {

                    gcode = get_bits(gb, 7);

                    if (gcode > 120)

                        return -1;

                    l11_grp.gcodes[0] = gcode / 11;

                    l11_grp.gcodes[1] = gcode % 11;

                }

                mantissa = l11_q_tab[l11_grp.gcodes[l11_grp.gcptr++]];

                coeffs[i] = to_float(exps[i], mantissa) * chcoeff;

                continue;

            case 5:

                mantissa = get_bits(gb, 4);

                if (mantissa > 14)

                    return -1;

                mantissa = l15_q_tab[mantissa];

                coeffs[i] = to_float(exps[i], mantissa) * chcoeff;

                continue;

            default:

                mantissa = get_bits(gb, qntztab[bap[i]]) << (16 - qntztab[bap[i]]);

                coeffs[i] = to_float(exps[i], mantissa) * chcoeff;

                continue;

        }

    }

    i = end;

    while (i < 256)

        coeffs[i++] = 0;

    return 0;

}


static int usb_host_update_interfaces(USBHostDevice *dev, int configuration)

{

    int dev_descr_len, config_descr_len;

    int interface, nb_interfaces, nb_configurations;

    int ret, i;

    if (configuration == 0) /* address state - ignore */

        return 1;

    i = 0;

    dev_descr_len = dev->descr[0];

    if (dev_descr_len > dev->descr_len)

        goto fail;

    nb_configurations = dev->descr[17];

    i += dev_descr_len;

    while (i < dev->descr_len) {

#ifdef DEBUG

        printf("i is %d, descr_len is %d, dl %d, dt %d\n", i, dev->descr_len,

               dev->descr[i], dev->descr[i+1]);

#endif

        if (dev->descr[i+1] != USB_DT_CONFIG) {

            i += dev->descr[i];

            continue;

        }

        config_descr_len = dev->descr[i];

        if (configuration == dev->descr[i + 5])

            break;

        i += config_descr_len;

    }

    if (i >= dev->descr_len) {

        printf("usb_host: error - device has no matching configuration\n");

        goto fail;

    }

    nb_interfaces = dev->descr[i + 4];

#ifdef USBDEVFS_DISCONNECT

    /* earlier Linux 2.4 do not support that */

    {

        struct usbdevfs_ioctl ctrl;

        for (interface = 0; interface < nb_interfaces; interface++) {

            ctrl.ioctl_code = USBDEVFS_DISCONNECT;

            ctrl.ifno = interface;

            ret = ioctl(dev->fd, USBDEVFS_IOCTL, &ctrl);

            if (ret < 0 && errno != ENODATA) {

                perror("USBDEVFS_DISCONNECT");

                goto fail;

            }

        }

    }

#endif

    /* XXX: only grab if all interfaces are free */

    for (interface = 0; interface < nb_interfaces; interface++) {

        ret = ioctl(dev->fd, USBDEVFS_CLAIMINTERFACE, &interface);

        if (ret < 0) {

            if (errno == EBUSY) {

                fprintf(stderr,

                        "usb_host: warning - device already grabbed\n");

            } else {

                perror("USBDEVFS_CLAIMINTERFACE");

            }

        fail:

            return 0;

        }

    }

#ifdef DEBUG

    printf("usb_host: %d interfaces claimed for configuration %d\n",

           nb_interfaces, configuration);

#endif

    return 1;

}


static int get_block_status(BlockDriverState *bs, int64_t offset,

                            int64_t bytes, MapEntry *e)

{

    int64_t ret;

    int depth;

    BlockDriverState *file;

    bool has_offset;

    int nb_sectors = bytes >> BDRV_SECTOR_BITS;

    assert(bytes < INT_MAX);

    /* As an optimization, we could cache the current range of unallocated

     * clusters in each file of the chain, and avoid querying the same

     * range repeatedly.

     */

    depth = 0;

    for (;;) {

        ret = bdrv_get_block_status(bs, offset >> BDRV_SECTOR_BITS, nb_sectors,

                                    &nb_sectors, &file);

        if (ret < 0) {

            return ret;

        }

        assert(nb_sectors);

        if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {

            break;

        }

        bs = backing_bs(bs);

        if (bs == NULL) {

            ret = 0;

            break;

        }

        depth++;

    }

    has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);

    *e = (MapEntry) {

        .start = offset,

        .length = nb_sectors * BDRV_SECTOR_SIZE,

        .data = !!(ret & BDRV_BLOCK_DATA),

        .zero = !!(ret & BDRV_BLOCK_ZERO),

        .offset = ret & BDRV_BLOCK_OFFSET_MASK,

        .has_offset = has_offset,

        .depth = depth,

        .has_filename = file && has_offset,

        .filename = file && has_offset ? file->filename : NULL,

    };

    return 0;

}


static void *colo_compare_thread(void *opaque)

{

    CompareState *s = opaque;

    GSource *timeout_source;

    s->worker_context = g_main_context_new();

    qemu_chr_fe_set_handlers(&s->chr_pri_in, compare_chr_can_read,

                             compare_pri_chr_in, NULL, NULL,

                             s, s->worker_context, true);

    qemu_chr_fe_set_handlers(&s->chr_sec_in, compare_chr_can_read,

                             compare_sec_chr_in, NULL, NULL,

                             s, s->worker_context, true);

    s->compare_loop = g_main_loop_new(s->worker_context, FALSE);

    /* To kick any packets that the secondary doesn't match */

    timeout_source = g_timeout_source_new(REGULAR_PACKET_CHECK_MS);

    g_source_set_callback(timeout_source,

                          (GSourceFunc)check_old_packet_regular, s, NULL);

    g_source_attach(timeout_source, s->worker_context);

    g_main_loop_run(s->compare_loop);

    g_source_unref(timeout_source);

    g_main_loop_unref(s->compare_loop);

    g_main_context_unref(s->worker_context);

    return NULL;

}


static int find_image_format(BlockDriverState *bs, const char *filename,

                             BlockDriver **pdrv, Error **errp)

{

    BlockDriver *drv;

    uint8_t buf[BLOCK_PROBE_BUF_SIZE];

    int ret = 0;

    /* Return the raw BlockDriver * to scsi-generic devices or empty drives */

    if (bs->sg || !bdrv_is_inserted(bs) || bdrv_getlength(bs) == 0) {

        *pdrv = &bdrv_raw;

        return ret;

    }

    ret = bdrv_pread(bs, 0, buf, sizeof(buf));

    if (ret < 0) {

        error_setg_errno(errp, -ret, "Could not read image for determining its "

                         "format");

        *pdrv = NULL;

        return ret;

    }

    drv = bdrv_probe_all(buf, ret, filename);

    if (!drv) {

        error_setg(errp, "Could not determine image format: No compatible "

                   "driver found");

        ret = -ENOENT;

    }

    *pdrv = drv;

    return ret;

}


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

{

    write_image_header(s);

    avio_write(s->pb, pkt->data, pkt->size);

    return 0;

}


static void uart_parameters_setup(UartState *s)

{

    QEMUSerialSetParams ssp;

    unsigned int baud_rate, packet_size;

    baud_rate = (s->r[R_MR] & UART_MR_CLKS) ?

            UART_INPUT_CLK / 8 : UART_INPUT_CLK;

    ssp.speed = baud_rate / (s->r[R_BRGR] * (s->r[R_BDIV] + 1));

    packet_size = 1;

    switch (s->r[R_MR] & UART_MR_PAR) {

    case UART_PARITY_EVEN:

        ssp.parity = 'E';

        packet_size++;

        break;

    case UART_PARITY_ODD:

        ssp.parity = 'O';

        packet_size++;

        break;

    default:

        ssp.parity = 'N';

        break;

    }

    switch (s->r[R_MR] & UART_MR_CHRL) {

    case UART_DATA_BITS_6:

        ssp.data_bits = 6;

        break;

    case UART_DATA_BITS_7:

        ssp.data_bits = 7;

        break;

    default:

        ssp.data_bits = 8;

        break;

    }

    switch (s->r[R_MR] & UART_MR_NBSTOP) {

    case UART_STOP_BITS_1:

        ssp.stop_bits = 1;

        break;

    default:

        ssp.stop_bits = 2;

        break;

    }

    packet_size += ssp.data_bits + ssp.stop_bits;

    s->char_tx_time = (get_ticks_per_sec() / ssp.speed) * packet_size;

    qemu_chr_fe_ioctl(s->chr, CHR_IOCTL_SERIAL_SET_PARAMS, &ssp);

}


eth_read(void *opaque, target_phys_addr_t addr, unsigned int size)

{

	struct fs_eth *eth = opaque;

	uint32_t r = 0;

	addr >>= 2;

	switch (addr) {

		case R_STAT:

			r = eth->mdio_bus.mdio & 1;

			break;

	default:

		r = eth->regs[addr];

		D(printf ("%s %x\n", __func__, addr * 4));

		break;

	}

	return r;

}


int vnc_display_open(DisplayState *ds, const char *display)

{

    VncState *vs = ds ? (VncState *)ds->opaque : vnc_state;

    const char *options;

    int password = 0;

    int reverse = 0;

    int to_port = 0;

#ifdef CONFIG_VNC_TLS

    int tls = 0, x509 = 0;

#endif

    vnc_display_close(ds);

    if (strcmp(display, "none") == 0)

	return 0;

    if (!(vs->display = strdup(display)))

	return -1;

    options = display;

    while ((options = strchr(options, ','))) {

	options++;

	if (strncmp(options, "password", 8) == 0) {

	    password = 1; /* Require password auth */

	} else if (strncmp(options, "reverse", 7) == 0) {

	    reverse = 1;

	} else if (strncmp(options, "to=", 3) == 0) {

            to_port = atoi(options+3) + 5900;

#ifdef CONFIG_VNC_TLS

	} else if (strncmp(options, "tls", 3) == 0) {

	    tls = 1; /* Require TLS */

	} else if (strncmp(options, "x509", 4) == 0) {

	    char *start, *end;

	    x509 = 1; /* Require x509 certificates */

	    if (strncmp(options, "x509verify", 10) == 0)

	        vs->x509verify = 1; /* ...and verify client certs */

	    /* Now check for 'x509=/some/path' postfix

	     * and use that to setup x509 certificate/key paths */

	    start = strchr(options, '=');

	    end = strchr(options, ',');

	    if (start && (!end || (start < end))) {

		int len = end ? end-(start+1) : strlen(start+1);

		char *path = qemu_malloc(len+1);

                pstrcpy(path, len, start + 1);

		path[len] = '\0';

		VNC_DEBUG("Trying certificate path '%s'\n", path);

		if (vnc_set_x509_credential_dir(vs, path) < 0) {

		    fprintf(stderr, "Failed to find x509 certificates/keys in %s\n", path);

		    qemu_free(path);

		    qemu_free(vs->display);

		    vs->display = NULL;

		    return -1;

		}

		qemu_free(path);

	    } else {

		fprintf(stderr, "No certificate path provided\n");

		qemu_free(vs->display);

		vs->display = NULL;

		return -1;

	    }

#endif

	}

    }

    if (password) {

#ifdef CONFIG_VNC_TLS

	if (tls) {

	    vs->auth = VNC_AUTH_VENCRYPT;

	    if (x509) {

		VNC_DEBUG("Initializing VNC server with x509 password auth\n");

		vs->subauth = VNC_AUTH_VENCRYPT_X509VNC;

	    } else {

		VNC_DEBUG("Initializing VNC server with TLS password auth\n");

		vs->subauth = VNC_AUTH_VENCRYPT_TLSVNC;

	    }

	} else {

#endif

	    VNC_DEBUG("Initializing VNC server with password auth\n");

	    vs->auth = VNC_AUTH_VNC;

#ifdef CONFIG_VNC_TLS

	    vs->subauth = VNC_AUTH_INVALID;

	}

#endif

    } else {

#ifdef CONFIG_VNC_TLS

	if (tls) {

	    vs->auth = VNC_AUTH_VENCRYPT;

	    if (x509) {

		VNC_DEBUG("Initializing VNC server with x509 no auth\n");

		vs->subauth = VNC_AUTH_VENCRYPT_X509NONE;

	    } else {

		VNC_DEBUG("Initializing VNC server with TLS no auth\n");

		vs->subauth = VNC_AUTH_VENCRYPT_TLSNONE;

	    }

	} else {

#endif

	    VNC_DEBUG("Initializing VNC server with no auth\n");

	    vs->auth = VNC_AUTH_NONE;

#ifdef CONFIG_VNC_TLS

	    vs->subauth = VNC_AUTH_INVALID;

	}

#endif

    }

    if (reverse) {

        /* connect to viewer */

        if (strncmp(display, "unix:", 5) == 0)

            vs->lsock = unix_connect(display+5);

        else

            vs->lsock = inet_connect(display, SOCK_STREAM);

        if (-1 == vs->lsock) {

            free(vs->display);

            vs->display = NULL;

            return -1;

        } else {

            vs->csock = vs->lsock;

            vs->lsock = -1;

            vnc_connect(vs);

        }

        return 0;

    } else {

        /* listen for connects */

        char *dpy;

        dpy = qemu_malloc(256);

        if (strncmp(display, "unix:", 5) == 0) {

            strcpy(dpy, "unix:");

            vs->lsock = unix_listen(display, dpy+5, 256-5);

        } else {

            vs->lsock = inet_listen(display, dpy, 256, SOCK_STREAM, 5900);

        }

        if (-1 == vs->lsock) {

            free(dpy);

        } else {

            free(vs->display);

            vs->display = dpy;

        }

    }

    return qemu_set_fd_handler2(vs->lsock, vnc_listen_poll, vnc_listen_read, NULL, vs);

}


static void nabm_writeb (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_LVI:

    case PO_LVI:

    case MC_LVI:

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

        if ((r->cr & CR_RPBM) && (r->sr & SR_DCH)) {

            r->sr &= ~(SR_DCH | SR_CELV);

            r->civ = r->piv;

            r->piv = (r->piv + 1) % 32;

            fetch_bd (s, r);

        }

        r->lvi = val % 32;

        dolog ("LVI[%d] <- %#x\n", GET_BM (index), val);

        break;

    case PI_CR:

    case PO_CR:

    case MC_CR:

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

        if (val & CR_RR) {

            reset_bm_regs (s, r);

        }

        else {

            r->cr = val & CR_VALID_MASK;

            if (!(r->cr & CR_RPBM)) {

                voice_set_active (s, r - s->bm_regs, 0);

                r->sr |= SR_DCH;

            }

            else {

                r->civ = r->piv;

                r->piv = (r->piv + 1) % 32;

                fetch_bd (s, r);

                r->sr &= ~SR_DCH;

                voice_set_active (s, r - s->bm_regs, 1);

            }

        }

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

        break;

    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 writeb %#x <- %#x\n", addr, val);

        break;

    }

}


void helper_xssubqp(CPUPPCState *env, uint32_t opcode)

{

    ppc_vsr_t xt, xa, xb;

    float_status tstat;

    getVSR(rA(opcode) + 32, &xa, env);

    getVSR(rB(opcode) + 32, &xb, env);

    getVSR(rD(opcode) + 32, &xt, env);

    helper_reset_fpstatus(env);

    if (unlikely(Rc(opcode) != 0)) {

        /* TODO: Support xssubqp after round-to-odd is implemented */

        abort();

    }

    tstat = env->fp_status;

    set_float_exception_flags(0, &tstat);

    xt.f128 = float128_sub(xa.f128, xb.f128, &tstat);

    env->fp_status.float_exception_flags |= tstat.float_exception_flags;

    if (unlikely(tstat.float_exception_flags & float_flag_invalid)) {

        if (float128_is_infinity(xa.f128) && float128_is_infinity(xb.f128)) {

            float_invalid_op_excp(env, POWERPC_EXCP_FP_VXISI, 1);

        } else if (float128_is_signaling_nan(xa.f128, &tstat) ||

                   float128_is_signaling_nan(xb.f128, &tstat)) {

            float_invalid_op_excp(env, POWERPC_EXCP_FP_VXSNAN, 1);

        }

    }

    helper_compute_fprf_float128(env, xt.f128);

    putVSR(rD(opcode) + 32, &xt, env);

    float_check_status(env);

}


void acpi_pm1_cnt_init(ACPIREGS *ar, MemoryRegion *parent)

{

    ar->wakeup.notify = acpi_notify_wakeup;

    qemu_register_wakeup_notifier(&ar->wakeup);

    memory_region_init_io(&ar->pm1.cnt.io, &acpi_pm_cnt_ops, ar, "acpi-cnt", 2);

    memory_region_add_subregion(parent, 4, &ar->pm1.cnt.io);

}


static void vfio_probe_nvidia_bar0_quirk(VFIOPCIDevice *vdev, int nr)

{

    VFIOQuirk *quirk;

    VFIOConfigMirrorQuirk *mirror;

    if (!vfio_pci_is(vdev, PCI_VENDOR_ID_NVIDIA, PCI_ANY_ID) ||

        !vfio_is_vga(vdev) || nr != 0) {

        return;

    }

    quirk = g_malloc0(sizeof(*quirk));

    mirror = quirk->data = g_malloc0(sizeof(*mirror));

    mirror->mem = quirk->mem = g_new0(MemoryRegion, 1);

    quirk->nr_mem = 1;

    mirror->vdev = vdev;

    mirror->offset = 0x88000;

    mirror->bar = nr;

    memory_region_init_io(mirror->mem, OBJECT(vdev),

                          &vfio_nvidia_mirror_quirk, mirror,

                          "vfio-nvidia-bar0-88000-mirror-quirk",

                          PCIE_CONFIG_SPACE_SIZE);

    memory_region_add_subregion_overlap(&vdev->bars[nr].region.mem,

                                        mirror->offset, mirror->mem, 1);

    QLIST_INSERT_HEAD(&vdev->bars[nr].quirks, quirk, next);

    /* The 0x1800 offset mirror only seems to get used by legacy VGA */

    if (vdev->has_vga) {

        quirk = g_malloc0(sizeof(*quirk));

        mirror = quirk->data = g_malloc0(sizeof(*mirror));

        mirror->mem = quirk->mem = g_new0(MemoryRegion, 1);

        quirk->nr_mem = 1;

        mirror->vdev = vdev;

        mirror->offset = 0x1800;

        mirror->bar = nr;

        memory_region_init_io(mirror->mem, OBJECT(vdev),

                              &vfio_nvidia_mirror_quirk, mirror,

                              "vfio-nvidia-bar0-1800-mirror-quirk",

                              PCI_CONFIG_SPACE_SIZE);

        memory_region_add_subregion_overlap(&vdev->bars[nr].region.mem,

                                            mirror->offset, mirror->mem, 1);

        QLIST_INSERT_HEAD(&vdev->bars[nr].quirks, quirk, next);

    }

    trace_vfio_quirk_nvidia_bar0_probe(vdev->vbasedev.name);

}


static int mkv_write_tag_targets(AVFormatContext *s,

                                 unsigned int elementid, unsigned int uid,

                                 ebml_master *tags, ebml_master* tag)

{

    AVIOContext *pb;

    MatroskaMuxContext *mkv = s->priv_data;

    ebml_master targets;

    int ret;

    if (!tags->pos) {

        ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TAGS, avio_tell(s->pb));

        if (ret < 0) return ret;

        start_ebml_master_crc32(s->pb, &mkv->tags_bc, tags, MATROSKA_ID_TAGS, 0);

    }

    pb = mkv->tags_bc;

    *tag     = start_ebml_master(pb, MATROSKA_ID_TAG,       0);

    targets = start_ebml_master(pb, MATROSKA_ID_TAGTARGETS, 0);

    if (elementid)

        put_ebml_uint(pb, elementid, uid);

    end_ebml_master(pb, targets);

    return 0;

}


static int v9fs_synth_symlink(FsContext *fs_ctx, const char *oldpath,

                              V9fsPath *newpath, const char *buf, FsCred *credp)

{

    errno = EPERM;

    return -1;

}


static uint32_t virtio_ioport_read(void *opaque, uint32_t addr)

{

    VirtIODevice *vdev = to_virtio_device(opaque);

    uint32_t ret = 0xFFFFFFFF;

    addr -= vdev->addr;

    switch (addr) {

    case VIRTIO_PCI_HOST_FEATURES:

        ret = vdev->get_features(vdev);

        ret |= (1 << VIRTIO_F_NOTIFY_ON_EMPTY);

        break;

    case VIRTIO_PCI_GUEST_FEATURES:

        ret = vdev->features;

        break;

    case VIRTIO_PCI_QUEUE_PFN:

        ret = vdev->vq[vdev->queue_sel].pfn;

        break;

    case VIRTIO_PCI_QUEUE_NUM:

        ret = vdev->vq[vdev->queue_sel].vring.num;

        break;

    case VIRTIO_PCI_QUEUE_SEL:

        ret = vdev->queue_sel;

        break;

    case VIRTIO_PCI_STATUS:

        ret = vdev->status;

        break;

    case VIRTIO_PCI_ISR:

        /* reading from the ISR also clears it. */

        ret = vdev->isr;

        vdev->isr = 0;

        virtio_update_irq(vdev);

        break;

    default:

        break;

    }

    return ret;

}


static void sb16_realizefn (DeviceState *dev, Error **errp)

{

    ISADevice *isadev = ISA_DEVICE (dev);

    SB16State *s = SB16 (dev);

    IsaDmaClass *k;

    isa_init_irq (isadev, &s->pic, s->irq);

    s->mixer_regs[0x80] = magic_of_irq (s->irq);

    s->mixer_regs[0x81] = (1 << s->dma) | (1 << s->hdma);

    s->mixer_regs[0x82] = 2 << 5;

    s->csp_regs[5] = 1;

    s->csp_regs[9] = 0xf8;

    reset_mixer (s);

    s->aux_ts = timer_new_ns(QEMU_CLOCK_VIRTUAL, aux_timer, s);

    if (!s->aux_ts) {

        dolog ("warning: Could not create auxiliary timer\n");

    }

    isa_register_portio_list (isadev, s->port, sb16_ioport_list, s, "sb16");

    s->isa_hdma = isa_get_dma(isa_bus_from_device(isadev), s->hdma);

    k = ISADMA_GET_CLASS(s->isa_hdma);

    k->register_channel(s->isa_hdma, s->hdma, SB_read_DMA, s);

    s->isa_dma = isa_get_dma(isa_bus_from_device(isadev), s->dma);

    k = ISADMA_GET_CLASS(s->isa_dma);

    k->register_channel(s->isa_dma, s->dma, SB_read_DMA, s);

    s->can_write = 1;

    AUD_register_card ("sb16", &s->card);

}


static int slavio_misc_init1(SysBusDevice *sbd)

{

    DeviceState *dev = DEVICE(sbd);

    MiscState *s = SLAVIO_MISC(dev);

    sysbus_init_irq(sbd, &s->irq);

    sysbus_init_irq(sbd, &s->fdc_tc);

    /* 8 bit registers */

    /* Slavio control */

    memory_region_init_io(&s->cfg_iomem, OBJECT(s), &slavio_cfg_mem_ops, s,

                          "configuration", MISC_SIZE);

    sysbus_init_mmio(sbd, &s->cfg_iomem);

    /* Diagnostics */

    memory_region_init_io(&s->diag_iomem, OBJECT(s), &slavio_diag_mem_ops, s,

                          "diagnostic", MISC_SIZE);

    sysbus_init_mmio(sbd, &s->diag_iomem);

    /* Modem control */

    memory_region_init_io(&s->mdm_iomem, OBJECT(s), &slavio_mdm_mem_ops, s,

                          "modem", MISC_SIZE);

    sysbus_init_mmio(sbd, &s->mdm_iomem);

    /* 16 bit registers */

    /* ss600mp diag LEDs */

    memory_region_init_io(&s->led_iomem, OBJECT(s), &slavio_led_mem_ops, s,

                          "leds", MISC_SIZE);

    sysbus_init_mmio(sbd, &s->led_iomem);

    /* 32 bit registers */

    /* System control */

    memory_region_init_io(&s->sysctrl_iomem, OBJECT(s), &slavio_sysctrl_mem_ops, s,

                          "system-control", MISC_SIZE);

    sysbus_init_mmio(sbd, &s->sysctrl_iomem);

    /* AUX 1 (Misc System Functions) */

    memory_region_init_io(&s->aux1_iomem, OBJECT(s), &slavio_aux1_mem_ops, s,

                          "misc-system-functions", MISC_SIZE);

    sysbus_init_mmio(sbd, &s->aux1_iomem);

    /* AUX 2 (Software Powerdown Control) */

    memory_region_init_io(&s->aux2_iomem, OBJECT(s), &slavio_aux2_mem_ops, s,

                          "software-powerdown-control", MISC_SIZE);

    sysbus_init_mmio(sbd, &s->aux2_iomem);

    qdev_init_gpio_in(dev, slavio_set_power_fail, 1);

    return 0;

}


static QIOChannelSocket *nbd_establish_connection(SocketAddress *saddr,

                                                  Error **errp)

{

    QIOChannelSocket *sioc;

    Error *local_err = NULL;

    sioc = qio_channel_socket_new();

    qio_channel_set_name(QIO_CHANNEL(sioc), "nbd-client");

    qio_channel_socket_connect_sync(sioc,

                                    saddr,

                                    &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        return NULL;

    }

    qio_channel_set_delay(QIO_CHANNEL(sioc), false);

    return sioc;

}


static void formant_postfilter(G723_1_Context *p, int16_t *lpc, int16_t *buf)

{

    int16_t filter_coef[2][LPC_ORDER], *buf_ptr;

    int filter_signal[LPC_ORDER + FRAME_LEN], *signal_ptr;

    int i, j, k;

    memcpy(buf, p->fir_mem, LPC_ORDER * sizeof(*buf));

    memcpy(filter_signal, p->iir_mem, LPC_ORDER * sizeof(*filter_signal));

    for (i = LPC_ORDER, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++) {

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

            filter_coef[0][k] = (-lpc[k] * postfilter_tbl[0][k] +

                                 (1 << 14)) >> 15;

            filter_coef[1][k] = (-lpc[k] * postfilter_tbl[1][k] +

                                 (1 << 14)) >> 15;

        }

        iir_filter(filter_coef[0], filter_coef[1], buf + i,

                   filter_signal + i);

        lpc += LPC_ORDER;

    }

    memcpy(p->fir_mem, buf + FRAME_LEN, LPC_ORDER * sizeof(*p->fir_mem));

    memcpy(p->iir_mem, filter_signal + FRAME_LEN,

           LPC_ORDER * sizeof(*p->iir_mem));

    buf_ptr    = buf + LPC_ORDER;

    signal_ptr = filter_signal + LPC_ORDER;

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

        int16_t temp_vector[SUBFRAME_LEN];

        int temp;

        int auto_corr[2];

        int scale, energy;

        /* Normalize */

        memcpy(temp_vector, buf_ptr, SUBFRAME_LEN * sizeof(*temp_vector));

        scale = scale_vector(temp_vector, SUBFRAME_LEN);

        /* Compute auto correlation coefficients */

        auto_corr[0] = dot_product(temp_vector, temp_vector + 1,

                                   SUBFRAME_LEN - 1, 1);

        auto_corr[1] = dot_product(temp_vector, temp_vector, SUBFRAME_LEN, 1);

        /* Compute reflection coefficient */

        temp = auto_corr[1] >> 16;

        if (temp) {

            temp = (auto_corr[0] >> 2) / temp;

        }

        p->reflection_coef = (3 * p->reflection_coef + temp + 2) >> 2;

        temp = -p->reflection_coef >> 1 & ~3;

        /* Compensation filter */

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

            buf_ptr[j] = av_clipl_int32(signal_ptr[j] +

                                        ((signal_ptr[j - 1] >> 16) *

                                         temp << 1)) >> 16;

        }

        /* Compute normalized signal energy */

        temp = 2 * scale + 4;

        if (temp < 0) {

            energy = av_clipl_int32((int64_t)auto_corr[1] << -temp);

        } else

            energy = auto_corr[1] >> temp;

        gain_scale(p, buf_ptr, energy);

        buf_ptr    += SUBFRAME_LEN;

        signal_ptr += SUBFRAME_LEN;

    }

}


int attribute_align_arg avresample_convert(AVAudioResampleContext *avr,

                                           uint8_t **output, int out_plane_size,

                                           int out_samples, uint8_t **input,

                                           int in_plane_size, int in_samples)

{

    AudioData input_buffer;

    AudioData output_buffer;

    AudioData *current_buffer;

    int ret, direct_output;

    /* reset internal buffers */

    if (avr->in_buffer) {

        avr->in_buffer->nb_samples = 0;

        ff_audio_data_set_channels(avr->in_buffer,

                                   avr->in_buffer->allocated_channels);

    }

    if (avr->resample_out_buffer) {

        avr->resample_out_buffer->nb_samples = 0;

        ff_audio_data_set_channels(avr->resample_out_buffer,

                                   avr->resample_out_buffer->allocated_channels);

    }

    if (avr->out_buffer) {

        avr->out_buffer->nb_samples = 0;

        ff_audio_data_set_channels(avr->out_buffer,

                                   avr->out_buffer->allocated_channels);

    }

    av_dlog(avr, "[start conversion]\n");

    /* initialize output_buffer with output data */

    direct_output = output && av_audio_fifo_size(avr->out_fifo) == 0;

    if (output) {

        ret = ff_audio_data_init(&output_buffer, output, out_plane_size,

                                 avr->out_channels, out_samples,

                                 avr->out_sample_fmt, 0, "output");

        if (ret < 0)

            return ret;

        output_buffer.nb_samples = 0;

    }

    if (input) {

        /* initialize input_buffer with input data */

        ret = ff_audio_data_init(&input_buffer, input, in_plane_size,

                                 avr->in_channels, in_samples,

                                 avr->in_sample_fmt, 1, "input");

        if (ret < 0)

            return ret;

        current_buffer = &input_buffer;

        if (avr->upmix_needed && !avr->in_convert_needed && !avr->resample_needed &&

            !avr->out_convert_needed && direct_output && out_samples >= in_samples) {

            /* in some rare cases we can copy input to output and upmix

               directly in the output buffer */

            av_dlog(avr, "[copy] %s to output\n", current_buffer->name);

            ret = ff_audio_data_copy(&output_buffer, current_buffer,

                                     avr->remap_point == REMAP_OUT_COPY ?

                                     &avr->ch_map_info : NULL);

            if (ret < 0)

                return ret;

            current_buffer = &output_buffer;

        } else if (avr->remap_point == REMAP_OUT_COPY &&

                   (!direct_output || out_samples < in_samples)) {

            /* if remapping channels during output copy, we may need to

             * use an intermediate buffer in order to remap before adding

             * samples to the output fifo */

            av_dlog(avr, "[copy] %s to out_buffer\n", current_buffer->name);

            ret = ff_audio_data_copy(avr->out_buffer, current_buffer,

                                     &avr->ch_map_info);

            if (ret < 0)

                return ret;

            current_buffer = avr->out_buffer;

        } else if (avr->in_copy_needed || avr->in_convert_needed) {

            /* if needed, copy or convert input to in_buffer, and downmix if

               applicable */

            if (avr->in_convert_needed) {

                ret = ff_audio_data_realloc(avr->in_buffer,

                                            current_buffer->nb_samples);

                if (ret < 0)

                    return ret;

                av_dlog(avr, "[convert] %s to in_buffer\n", current_buffer->name);

                ret = ff_audio_convert(avr->ac_in, avr->in_buffer,

                                       current_buffer);

                if (ret < 0)

                    return ret;

            } else {

                av_dlog(avr, "[copy] %s to in_buffer\n", current_buffer->name);

                ret = ff_audio_data_copy(avr->in_buffer, current_buffer,

                                         avr->remap_point == REMAP_IN_COPY ?

                                         &avr->ch_map_info : NULL);

                if (ret < 0)

                    return ret;

            }

            ff_audio_data_set_channels(avr->in_buffer, avr->in_channels);

            if (avr->downmix_needed) {

                av_dlog(avr, "[downmix] in_buffer\n");

                ret = ff_audio_mix(avr->am, avr->in_buffer);

                if (ret < 0)

                    return ret;

            }

            current_buffer = avr->in_buffer;

        }

    } else {

        /* flush resampling buffer and/or output FIFO if input is NULL */

        if (!avr->resample_needed)

            return handle_buffered_output(avr, output ? &output_buffer : NULL,

                                          NULL);

        current_buffer = NULL;

    }

    if (avr->resample_needed) {

        AudioData *resample_out;

        if (!avr->out_convert_needed && direct_output && out_samples > 0)

            resample_out = &output_buffer;

        else

            resample_out = avr->resample_out_buffer;

        av_dlog(avr, "[resample] %s to %s\n", current_buffer->name,

                resample_out->name);

        ret = ff_audio_resample(avr->resample, resample_out,

                                current_buffer);

        if (ret < 0)

            return ret;

        /* if resampling did not produce any samples, just return 0 */

        if (resample_out->nb_samples == 0) {

            av_dlog(avr, "[end conversion]\n");

            return 0;

        }

        current_buffer = resample_out;

    }

    if (avr->upmix_needed) {

        av_dlog(avr, "[upmix] %s\n", current_buffer->name);

        ret = ff_audio_mix(avr->am, current_buffer);

        if (ret < 0)

            return ret;

    }

    /* if we resampled or upmixed directly to output, return here */

    if (current_buffer == &output_buffer) {

        av_dlog(avr, "[end conversion]\n");

        return current_buffer->nb_samples;

    }

    if (avr->out_convert_needed) {

        if (direct_output && out_samples >= current_buffer->nb_samples) {

            /* convert directly to output */

            av_dlog(avr, "[convert] %s to output\n", current_buffer->name);

            ret = ff_audio_convert(avr->ac_out, &output_buffer, current_buffer);

            if (ret < 0)

                return ret;

            av_dlog(avr, "[end conversion]\n");

            return output_buffer.nb_samples;

        } else {

            ret = ff_audio_data_realloc(avr->out_buffer,

                                        current_buffer->nb_samples);

            if (ret < 0)

                return ret;

            av_dlog(avr, "[convert] %s to out_buffer\n", current_buffer->name);

            ret = ff_audio_convert(avr->ac_out, avr->out_buffer,

                                   current_buffer);

            if (ret < 0)

                return ret;

            current_buffer = avr->out_buffer;

        }

    }

    return handle_buffered_output(avr, output ? &output_buffer : NULL,

                                  current_buffer);

}


static int ogg_read_header(AVFormatContext *avfcontext, AVFormatParameters *ap)

{

    OggContext *context = avfcontext->priv_data;

    ogg_packet op ;

    char *buf ;

    ogg_page og ;

    AVStream *ast ;

    AVCodecContext *codec;

    uint8_t *p;

    int i;

    ogg_sync_init(&context->oy) ;

    buf = ogg_sync_buffer(&context->oy, DECODER_BUFFER_SIZE) ;

    if(get_buffer(&avfcontext->pb, buf, DECODER_BUFFER_SIZE) <= 0)

	return AVERROR_IO ;

    ogg_sync_wrote(&context->oy, DECODER_BUFFER_SIZE) ;

    ogg_sync_pageout(&context->oy, &og) ;

    ogg_stream_init(&context->os, ogg_page_serialno(&og)) ;

    ogg_stream_pagein(&context->os, &og) ;

    /* currently only one vorbis stream supported */

    ast = av_new_stream(avfcontext, 0) ;

    if(!ast)

	return AVERROR_NOMEM ;

    av_set_pts_info(ast, 60, 1, AV_TIME_BASE);

    codec= &ast->codec;

    codec->codec_type = CODEC_TYPE_AUDIO;

    codec->codec_id = CODEC_ID_VORBIS;

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

        if(next_packet(avfcontext, &op)){

        }

        codec->extradata_size+= 2 + op.bytes;

        codec->extradata= av_realloc(codec->extradata, codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);

        p= codec->extradata + codec->extradata_size - 2 - op.bytes;

        *(p++)= op.bytes>>8;

        *(p++)= op.bytes&0xFF;

        memcpy(p, op.packet, op.bytes);

    }

    return 0 ;

}


static inline int tcg_temp_new_internal(TCGType type, int temp_local)
{
    TCGContext *s = &tcg_ctx;
    TCGTemp *ts;
    int idx, k;
    k = type;
    if (temp_local)
        k += TCG_TYPE_COUNT;
    idx = s->first_free_temp[k];
    if (idx != -1) {
        /* There is already an available temp with the
           right type */
        ts = &s->temps[idx];
        s->first_free_temp[k] = ts->next_free_temp;
        ts->temp_allocated = 1;
        assert(ts->temp_local == temp_local);
    } else {
        idx = s->nb_temps;
#if TCG_TARGET_REG_BITS == 32
        if (type == TCG_TYPE_I64) {
            tcg_temp_alloc(s, s->nb_temps + 2);
            ts = &s->temps[s->nb_temps];
            ts->base_type = type;
            ts->type = TCG_TYPE_I32;
            ts->temp_allocated = 1;
            ts->temp_local = temp_local;
            ts->name = NULL;
            ts++;
            ts->base_type = TCG_TYPE_I32;
            ts->type = TCG_TYPE_I32;
            ts->temp_allocated = 1;
            ts->temp_local = temp_local;
            ts->name = NULL;
            s->nb_temps += 2;
        } else
        {
            tcg_temp_alloc(s, s->nb_temps + 1);
            ts = &s->temps[s->nb_temps];
            ts->base_type = type;
            ts->type = type;
            ts->temp_allocated = 1;
            ts->temp_local = temp_local;
            ts->name = NULL;
            s->nb_temps++;
        }
    }
    return idx;
}


static int vp56_size_changed(VP56Context *s)
{
    AVCodecContext *avctx = s->avctx;
    int stride = s->frames[VP56_FRAME_CURRENT]->linesize[0];
    int i;
    s->plane_width[0]  = s->plane_width[3]  = avctx->coded_width;
    s->plane_width[1]  = s->plane_width[2]  = avctx->coded_width/2;
    s->plane_height[0] = s->plane_height[3] = avctx->coded_height;
    s->plane_height[1] = s->plane_height[2] = avctx->coded_height/2;
    for (i=0; i<4; i++)
        s->stride[i] = s->flip * s->frames[VP56_FRAME_CURRENT]->linesize[i];
    s->mb_width  = (avctx->coded_width +15) / 16;
    s->mb_height = (avctx->coded_height+15) / 16;
    if (s->mb_width > 1000 || s->mb_height > 1000) {
        ff_set_dimensions(avctx, 0, 0);
        av_log(avctx, AV_LOG_ERROR, "picture too big\n");
        return AVERROR_INVALIDDATA;
    }
    av_reallocp_array(&s->above_blocks, 4*s->mb_width+6,
                      sizeof(*s->above_blocks));
    av_reallocp_array(&s->macroblocks, s->mb_width*s->mb_height,
                      sizeof(*s->macroblocks));
    av_free(s->edge_emu_buffer_alloc);
    s->edge_emu_buffer_alloc = av_malloc(16*stride);
    s->edge_emu_buffer = s->edge_emu_buffer_alloc;
    if (!s->above_blocks || !s->macroblocks || !s->edge_emu_buffer_alloc)
        return AVERROR(ENOMEM);
    if (s->flip < 0)
        s->edge_emu_buffer += 15 * stride;
    if (s->alpha_context)
        return vp56_size_changed(s->alpha_context);
    return 0;
}


static void rtsp_cmd_teardown(HTTPContext *c, const char *url, RTSPHeader *h)

{

    HTTPContext *rtp_c;

    rtp_c = find_rtp_session_with_url(url, h->session_id);

    if (!rtp_c) {

        rtsp_reply_error(c, RTSP_STATUS_SESSION);

        return;

    }

    /* abort the session */

    close_connection(rtp_c);

    /* now everything is OK, so we can send the connection parameters */

    rtsp_reply_header(c, RTSP_STATUS_OK);

    /* session ID */

    url_fprintf(c->pb, "Session: %s\r\n", rtp_c->session_id);

    url_fprintf(c->pb, "\r\n");

}


static CharDriverState *qemu_chr_open_win_path(const char *filename)

{

    CharDriverState *chr;

    WinCharState *s;

    chr = qemu_chr_alloc();

    s = g_malloc0(sizeof(WinCharState));

    chr->opaque = s;

    chr->chr_write = win_chr_write;

    chr->chr_close = win_chr_close;

    if (win_chr_init(chr, filename) < 0) {

        g_free(s);

        g_free(chr);

        return NULL;

    }

    return chr;

}


static av_cold int twin_decode_init(AVCodecContext *avctx)

{

    int ret;

    TwinContext *tctx = avctx->priv_data;

    int isampf, ibps;

    tctx->avctx       = avctx;

    avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;

    if (!avctx->extradata || avctx->extradata_size < 12) {

        av_log(avctx, AV_LOG_ERROR, "Missing or incomplete extradata\n");

        return AVERROR_INVALIDDATA;

    }

    avctx->channels = AV_RB32(avctx->extradata    ) + 1;

    avctx->bit_rate = AV_RB32(avctx->extradata + 4) * 1000;

    isampf          = AV_RB32(avctx->extradata + 8);

    switch (isampf) {

    case 44: avctx->sample_rate = 44100;         break;

    case 22: avctx->sample_rate = 22050;         break;

    case 11: avctx->sample_rate = 11025;         break;

    default: avctx->sample_rate = isampf * 1000; break;

    }

    if (avctx->channels > CHANNELS_MAX) {

        av_log(avctx, AV_LOG_ERROR, "Unsupported number of channels: %i\n",

               avctx->channels);

        return -1;

    }

    ibps = avctx->bit_rate / (1000 * avctx->channels);

    switch ((isampf << 8) +  ibps) {

    case (8 <<8) +  8: tctx->mtab = &mode_08_08; break;

    case (11<<8) +  8: tctx->mtab = &mode_11_08; break;

    case (11<<8) + 10: tctx->mtab = &mode_11_10; break;

    case (16<<8) + 16: tctx->mtab = &mode_16_16; break;

    case (22<<8) + 20: tctx->mtab = &mode_22_20; break;

    case (22<<8) + 24: tctx->mtab = &mode_22_24; break;

    case (22<<8) + 32: tctx->mtab = &mode_22_32; break;

    case (44<<8) + 40: tctx->mtab = &mode_44_40; break;

    case (44<<8) + 48: tctx->mtab = &mode_44_48; break;

    default:

        av_log(avctx, AV_LOG_ERROR, "This version does not support %d kHz - %d kbit/s/ch mode.\n", isampf, isampf);

        return -1;

    }

    ff_dsputil_init(&tctx->dsp, avctx);

    avpriv_float_dsp_init(&tctx->fdsp, avctx->flags & CODEC_FLAG_BITEXACT);

    if ((ret = init_mdct_win(tctx))) {

        av_log(avctx, AV_LOG_ERROR, "Error initializing MDCT\n");

        twin_decode_close(avctx);

        return ret;

    }

    init_bitstream_params(tctx);

    memset_float(tctx->bark_hist[0][0], 0.1, FF_ARRAY_ELEMS(tctx->bark_hist));

    avcodec_get_frame_defaults(&tctx->frame);

    avctx->coded_frame = &tctx->frame;

    return 0;

}


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

{

    int64_t offset = avio_tell(pb) + atom.size, pts, timestamp;

    uint8_t version;

    unsigned i, j, track_id, item_count;

    AVStream *st = NULL;

    AVStream *ref_st = NULL;

    MOVStreamContext *sc, *ref_sc = NULL;

    AVRational timescale;

    version = avio_r8(pb);

    if (version > 1) {

        avpriv_request_sample(c->fc, "sidx version %u", version);

        return 0;

    }

    avio_rb24(pb); // flags

    track_id = avio_rb32(pb); // Reference ID

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

        if (c->fc->streams[i]->id == track_id) {

            st = c->fc->streams[i];

            break;

        }

    }

    if (!st) {

        av_log(c->fc, AV_LOG_WARNING, "could not find corresponding track id %d\n", track_id);

        return 0;

    }

    sc = st->priv_data;

    timescale = av_make_q(1, avio_rb32(pb));

    if (timescale.den <= 0) {

        av_log(c->fc, AV_LOG_ERROR, "Invalid sidx timescale 1/%d\n", timescale.den);

        return AVERROR_INVALIDDATA;

    }

    if (version == 0) {

        pts = avio_rb32(pb);

        offset += avio_rb32(pb);

    } else {

        pts = avio_rb64(pb);

        offset += avio_rb64(pb);

    }

    avio_rb16(pb); // reserved

    item_count = avio_rb16(pb);

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

        int index;

        MOVFragmentStreamInfo * frag_stream_info;

        uint32_t size = avio_rb32(pb);

        uint32_t duration = avio_rb32(pb);

        if (size & 0x80000000) {

            avpriv_request_sample(c->fc, "sidx reference_type 1");

            return AVERROR_PATCHWELCOME;

        }

        avio_rb32(pb); // sap_flags

        timestamp = av_rescale_q(pts, st->time_base, timescale);

        index = update_frag_index(c, offset);

        frag_stream_info = get_frag_stream_info(&c->frag_index, index, track_id);

        if (frag_stream_info)

            frag_stream_info->sidx_pts = timestamp;

        offset += size;

        pts += duration;

    }

    st->duration = sc->track_end = pts;

    sc->has_sidx = 1;

    if (offset == avio_size(pb)) {

        // Find first entry in fragment index that came from an sidx.

        // This will pretty much always be the first entry.

        for (i = 0; i < c->frag_index.nb_items; i++) {

            MOVFragmentIndexItem * item = &c->frag_index.item[i];

            for (j = 0; ref_st == NULL && j < item->nb_stream_info; j++) {

                MOVFragmentStreamInfo * si;

                si = &item->stream_info[j];

                if (si->sidx_pts != AV_NOPTS_VALUE) {

                    ref_st = c->fc->streams[i];

                    ref_sc = ref_st->priv_data;

                    break;

                }

            }

        }

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

            st = c->fc->streams[i];

            sc = st->priv_data;

            if (!sc->has_sidx) {

                st->duration = sc->track_end = av_rescale(ref_st->duration, sc->time_scale, ref_sc->time_scale);

            }

        }

        c->frag_index.complete = 1;

    }

    return 0;

}


static void shix_init(MachineState *machine)

{

    const char *cpu_model = machine->cpu_model;

    int ret;

    SuperHCPU *cpu;

    struct SH7750State *s;

    MemoryRegion *sysmem = get_system_memory();

    MemoryRegion *rom = g_new(MemoryRegion, 1);

    MemoryRegion *sdram = g_new(MemoryRegion, 2);

    if (!cpu_model)

        cpu_model = "any";

    cpu = SUPERH_CPU(cpu_generic_init(TYPE_SUPERH_CPU, cpu_model));

    if (cpu == NULL) {

        fprintf(stderr, "Unable to find CPU definition\n");

        exit(1);

    }

    /* Allocate memory space */

    memory_region_init_ram(rom, NULL, "shix.rom", 0x4000, &error_fatal);

    memory_region_set_readonly(rom, true);

    memory_region_add_subregion(sysmem, 0x00000000, rom);

    memory_region_init_ram(&sdram[0], NULL, "shix.sdram1", 0x01000000,

                           &error_fatal);

    memory_region_add_subregion(sysmem, 0x08000000, &sdram[0]);

    memory_region_init_ram(&sdram[1], NULL, "shix.sdram2", 0x01000000,

                           &error_fatal);

    memory_region_add_subregion(sysmem, 0x0c000000, &sdram[1]);

    /* Load BIOS in 0 (and access it through P2, 0xA0000000) */

    if (bios_name == NULL)

        bios_name = BIOS_FILENAME;

    ret = load_image_targphys(bios_name, 0, 0x4000);

    if (ret < 0 && !qtest_enabled()) {

        error_report("Could not load SHIX bios '%s'", bios_name);

        exit(1);

    }

    /* Register peripherals */

    s = sh7750_init(cpu, sysmem);

    /* XXXXX Check success */

    tc58128_init(s, "shix_linux_nand.bin", NULL);

}


static inline void gen_addr_imm_index (DisasContext *ctx)

{

    target_long simm = SIMM(ctx->opcode);

    if (rA(ctx->opcode) == 0) {

        gen_op_set_T0(simm);

    } else {

        gen_op_load_gpr_T0(rA(ctx->opcode));

        if (likely(simm != 0))

            gen_op_addi(simm);

    }

}


void qmp_guest_suspend_ram(Error **errp)

{

    Error *local_err = NULL;

    GuestSuspendMode *mode = g_malloc(sizeof(GuestSuspendMode));

    *mode = GUEST_SUSPEND_MODE_RAM;

    check_suspend_mode(*mode, &local_err);

    acquire_privilege(SE_SHUTDOWN_NAME, &local_err);

    execute_async(do_suspend, mode, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        g_free(mode);

    }

}


void ff_hevc_cabac_init(HEVCContext *s, int ctb_addr_ts)

{

    if (ctb_addr_ts == s->ps.pps->ctb_addr_rs_to_ts[s->sh.slice_ctb_addr_rs]) {

        cabac_init_decoder(s);

        if (s->sh.dependent_slice_segment_flag == 0 ||

            (s->ps.pps->tiles_enabled_flag &&

             s->ps.pps->tile_id[ctb_addr_ts] != s->ps.pps->tile_id[ctb_addr_ts - 1]))

            cabac_init_state(s);

        if (!s->sh.first_slice_in_pic_flag &&

            s->ps.pps->entropy_coding_sync_enabled_flag) {

            if (ctb_addr_ts % s->ps.sps->ctb_width == 0) {

                if (s->ps.sps->ctb_width == 1)

                    cabac_init_state(s);

                else if (s->sh.dependent_slice_segment_flag == 1)

                    load_states(s);

            }

        }

    } else {

        if (s->ps.pps->tiles_enabled_flag &&

            s->ps.pps->tile_id[ctb_addr_ts] != s->ps.pps->tile_id[ctb_addr_ts - 1]) {

            if (s->threads_number == 1)

                cabac_reinit(s->HEVClc);

            else

                cabac_init_decoder(s);

            cabac_init_state(s);

        }

        if (s->ps.pps->entropy_coding_sync_enabled_flag) {

            if (ctb_addr_ts % s->ps.sps->ctb_width == 0) {

                get_cabac_terminate(&s->HEVClc->cc);

                if (s->threads_number == 1)

                    cabac_reinit(s->HEVClc);

                else

                    cabac_init_decoder(s);

                if (s->ps.sps->ctb_width == 1)

                    cabac_init_state(s);

                else

                    load_states(s);

            }

        }

    }

}


void lance_init(NICInfo *nd, target_phys_addr_t leaddr, void *dma_opaque,

                qemu_irq irq, qemu_irq *reset)

{

    PCNetState *d;

    int lance_io_memory;

    qemu_check_nic_model(nd, "lance");

    d = qemu_mallocz(sizeof(PCNetState));

    lance_io_memory =

        cpu_register_io_memory(0, lance_mem_read, lance_mem_write, d);

    d->dma_opaque = dma_opaque;

    *reset = *qemu_allocate_irqs(parent_lance_reset, d, 1);

    cpu_register_physical_memory(leaddr, 4, lance_io_memory);

    d->irq = irq;

    d->phys_mem_read = ledma_memory_read;

    d->phys_mem_write = ledma_memory_write;

    pcnet_common_init(d, nd);

}


static inline TCGv gen_load(DisasContext * s, int opsize, TCGv addr, int sign)

{

    TCGv tmp;

    int index = IS_USER(s);

    s->is_mem = 1;

    tmp = tcg_temp_new_i32();

    switch(opsize) {

    case OS_BYTE:

        if (sign)

            tcg_gen_qemu_ld8s(tmp, addr, index);

        else

            tcg_gen_qemu_ld8u(tmp, addr, index);

        break;

    case OS_WORD:

        if (sign)

            tcg_gen_qemu_ld16s(tmp, addr, index);

        else

            tcg_gen_qemu_ld16u(tmp, addr, index);

        break;

    case OS_LONG:

    case OS_SINGLE:

        tcg_gen_qemu_ld32u(tmp, addr, index);

        break;

    default:

        qemu_assert(0, "bad load size");

    }

    gen_throws_exception = gen_last_qop;

    return tmp;

}