static int rebuild_refcount_structure(BlockDriverState *bs,

                                      BdrvCheckResult *res,

                                      uint16_t **refcount_table,

                                      int64_t *nb_clusters)

{

    BDRVQcowState *s = bs->opaque;

    int64_t first_free_cluster = 0, reftable_offset = -1, cluster = 0;

    int64_t refblock_offset, refblock_start, refblock_index;

    uint32_t reftable_size = 0;

    uint64_t *on_disk_reftable = NULL;

    uint16_t *on_disk_refblock;

    int i, ret = 0;

    struct {

        uint64_t reftable_offset;

        uint32_t reftable_clusters;

    } QEMU_PACKED reftable_offset_and_clusters;

    qcow2_cache_empty(bs, s->refcount_block_cache);

write_refblocks:

    for (; cluster < *nb_clusters; cluster++) {

        if (!(*refcount_table)[cluster]) {

            continue;

        }

        refblock_index = cluster >> s->refcount_block_bits;

        refblock_start = refblock_index << s->refcount_block_bits;

        /* Don't allocate a cluster in a refblock already written to disk */

        if (first_free_cluster < refblock_start) {

            first_free_cluster = refblock_start;

        }

        refblock_offset = alloc_clusters_imrt(bs, 1, refcount_table,

                                              nb_clusters, &first_free_cluster);

        if (refblock_offset < 0) {

            fprintf(stderr, "ERROR allocating refblock: %s\n",

                    strerror(-refblock_offset));

            res->check_errors++;

            ret = refblock_offset;

            goto fail;

        }

        if (reftable_size <= refblock_index) {

            uint32_t old_reftable_size = reftable_size;

            uint64_t *new_on_disk_reftable;

            reftable_size = ROUND_UP((refblock_index + 1) * sizeof(uint64_t),

                                     s->cluster_size) / sizeof(uint64_t);

            new_on_disk_reftable = g_try_realloc(on_disk_reftable,

                                                 reftable_size *

                                                 sizeof(uint64_t));

            if (!new_on_disk_reftable) {

                res->check_errors++;

                ret = -ENOMEM;

                goto fail;

            }

            on_disk_reftable = new_on_disk_reftable;

            memset(on_disk_reftable + old_reftable_size, 0,

                   (reftable_size - old_reftable_size) * sizeof(uint64_t));

            /* The offset we have for the reftable is now no longer valid;

             * this will leak that range, but we can easily fix that by running

             * a leak-fixing check after this rebuild operation */

            reftable_offset = -1;

        }

        on_disk_reftable[refblock_index] = refblock_offset;

        /* If this is apparently the last refblock (for now), try to squeeze the

         * reftable in */

        if (refblock_index == (*nb_clusters - 1) >> s->refcount_block_bits &&

            reftable_offset < 0)

        {

            uint64_t reftable_clusters = size_to_clusters(s, reftable_size *

                                                          sizeof(uint64_t));

            reftable_offset = alloc_clusters_imrt(bs, reftable_clusters,

                                                  refcount_table, nb_clusters,

                                                  &first_free_cluster);

            if (reftable_offset < 0) {

                fprintf(stderr, "ERROR allocating reftable: %s\n",

                        strerror(-reftable_offset));

                res->check_errors++;

                ret = reftable_offset;

                goto fail;

            }

        }

        ret = qcow2_pre_write_overlap_check(bs, 0, refblock_offset,

                                            s->cluster_size);

        if (ret < 0) {

            fprintf(stderr, "ERROR writing refblock: %s\n", strerror(-ret));

            goto fail;

        }

        on_disk_refblock = qemu_blockalign0(bs->file, s->cluster_size);

        for (i = 0; i < s->refcount_block_size &&

                    refblock_start + i < *nb_clusters; i++)

        {

            on_disk_refblock[i] =

                cpu_to_be16((*refcount_table)[refblock_start + i]);

        }

        ret = bdrv_write(bs->file, refblock_offset / BDRV_SECTOR_SIZE,

                         (void *)on_disk_refblock, s->cluster_sectors);

        qemu_vfree(on_disk_refblock);

        if (ret < 0) {

            fprintf(stderr, "ERROR writing refblock: %s\n", strerror(-ret));

            goto fail;

        }

        /* Go to the end of this refblock */

        cluster = refblock_start + s->refcount_block_size - 1;

    }

    if (reftable_offset < 0) {

        uint64_t post_refblock_start, reftable_clusters;

        post_refblock_start = ROUND_UP(*nb_clusters, s->refcount_block_size);

        reftable_clusters = size_to_clusters(s,

                                             reftable_size * sizeof(uint64_t));

        /* Not pretty but simple */

        if (first_free_cluster < post_refblock_start) {

            first_free_cluster = post_refblock_start;

        }

        reftable_offset = alloc_clusters_imrt(bs, reftable_clusters,

                                              refcount_table, nb_clusters,

                                              &first_free_cluster);

        if (reftable_offset < 0) {

            fprintf(stderr, "ERROR allocating reftable: %s\n",

                    strerror(-reftable_offset));

            res->check_errors++;

            ret = reftable_offset;

            goto fail;

        }

        goto write_refblocks;

    }

    assert(on_disk_reftable);

    for (refblock_index = 0; refblock_index < reftable_size; refblock_index++) {

        cpu_to_be64s(&on_disk_reftable[refblock_index]);

    }

    ret = qcow2_pre_write_overlap_check(bs, 0, reftable_offset,

                                        reftable_size * sizeof(uint64_t));

    if (ret < 0) {

        fprintf(stderr, "ERROR writing reftable: %s\n", strerror(-ret));

        goto fail;

    }

    assert(reftable_size < INT_MAX / sizeof(uint64_t));

    ret = bdrv_pwrite(bs->file, reftable_offset, on_disk_reftable,

                      reftable_size * sizeof(uint64_t));

    if (ret < 0) {

        fprintf(stderr, "ERROR writing reftable: %s\n", strerror(-ret));

        goto fail;

    }

    /* Enter new reftable into the image header */

    cpu_to_be64w(&reftable_offset_and_clusters.reftable_offset,

                 reftable_offset);

    cpu_to_be32w(&reftable_offset_and_clusters.reftable_clusters,

                 size_to_clusters(s, reftable_size * sizeof(uint64_t)));

    ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader,

                                              refcount_table_offset),

                           &reftable_offset_and_clusters,

                           sizeof(reftable_offset_and_clusters));

    if (ret < 0) {

        fprintf(stderr, "ERROR setting reftable: %s\n", strerror(-ret));

        goto fail;

    }

    for (refblock_index = 0; refblock_index < reftable_size; refblock_index++) {

        be64_to_cpus(&on_disk_reftable[refblock_index]);

    }

    s->refcount_table = on_disk_reftable;

    s->refcount_table_offset = reftable_offset;

    s->refcount_table_size = reftable_size;

    return 0;

fail:

    g_free(on_disk_reftable);

    return ret;

}


static void vp8_idct_dc_add4uv_c(uint8_t *dst, int16_t block[4][16],

                                 ptrdiff_t stride)

{

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

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

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

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

}


static void fw_cfg_mem_class_init(ObjectClass *klass, void *data)

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    dc->realize = fw_cfg_mem_realize;

    dc->props = fw_cfg_mem_properties;

}


int xen_pt_msix_init(XenPCIPassthroughState *s, uint32_t base)

{

    uint8_t id = 0;

    uint16_t control = 0;

    uint32_t table_off = 0;

    int i, total_entries, bar_index;

    XenHostPCIDevice *hd = &s->real_device;

    PCIDevice *d = &s->dev;

    int fd = -1;

    XenPTMSIX *msix = NULL;

    int rc = 0;

    rc = xen_host_pci_get_byte(hd, base + PCI_CAP_LIST_ID, &id);

    if (rc) {

        return rc;

    }

    if (id != PCI_CAP_ID_MSIX) {

        XEN_PT_ERR(d, "Invalid id %#x base %#x\n", id, base);

        return -1;

    }

    xen_host_pci_get_word(hd, base + PCI_MSIX_FLAGS, &control);

    total_entries = control & PCI_MSIX_FLAGS_QSIZE;

    total_entries += 1;

    s->msix = g_malloc0(sizeof (XenPTMSIX)

                        + total_entries * sizeof (XenPTMSIXEntry));

    msix = s->msix;

    msix->total_entries = total_entries;

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

        msix->msix_entry[i].pirq = XEN_PT_UNASSIGNED_PIRQ;

    }

    memory_region_init_io(&msix->mmio, OBJECT(s), &pci_msix_ops,

                          s, "xen-pci-pt-msix",

                          (total_entries * PCI_MSIX_ENTRY_SIZE

                           + XC_PAGE_SIZE - 1)

                          & XC_PAGE_MASK);

    xen_host_pci_get_long(hd, base + PCI_MSIX_TABLE, &table_off);

    bar_index = msix->bar_index = table_off & PCI_MSIX_FLAGS_BIRMASK;

    table_off = table_off & ~PCI_MSIX_FLAGS_BIRMASK;

    msix->table_base = s->real_device.io_regions[bar_index].base_addr;

    XEN_PT_LOG(d, "get MSI-X table BAR base 0x%"PRIx64"\n", msix->table_base);

    fd = open("/dev/mem", O_RDWR);

    if (fd == -1) {

        rc = -errno;

        XEN_PT_ERR(d, "Can't open /dev/mem: %s\n", strerror(errno));

        goto error_out;

    }

    XEN_PT_LOG(d, "table_off = %#x, total_entries = %d\n",

               table_off, total_entries);

    msix->table_offset_adjust = table_off & 0x0fff;

    msix->phys_iomem_base =

        mmap(NULL,

             total_entries * PCI_MSIX_ENTRY_SIZE + msix->table_offset_adjust,

             PROT_READ,

             MAP_SHARED | MAP_LOCKED,

             fd,

             msix->table_base + table_off - msix->table_offset_adjust);

    close(fd);

    if (msix->phys_iomem_base == MAP_FAILED) {

        rc = -errno;

        XEN_PT_ERR(d, "Can't map physical MSI-X table: %s\n", strerror(errno));

        goto error_out;

    }

    msix->phys_iomem_base = (char *)msix->phys_iomem_base

        + msix->table_offset_adjust;

    XEN_PT_LOG(d, "mapping physical MSI-X table to %p\n",

               msix->phys_iomem_base);

    memory_region_add_subregion_overlap(&s->bar[bar_index], table_off,

                                        &msix->mmio,

                                        2); /* Priority: pci default + 1 */

    return 0;

error_out:

    g_free(s->msix);

    s->msix = NULL;

    return rc;

}


static int64_t archipelago_volume_info(BDRVArchipelagoState *s)

{

    uint64_t size;

    int ret, targetlen;

    struct xseg_request *req;

    struct xseg_reply_info *xinfo;

    AIORequestData *reqdata = g_malloc(sizeof(AIORequestData));

    const char *volname = s->volname;

    targetlen = strlen(volname);

    req = xseg_get_request(s->xseg, s->srcport, s->mportno, X_ALLOC);

    if (!req) {

        archipelagolog("Cannot get XSEG request\n");

        goto err_exit2;

    }

    ret = xseg_prep_request(s->xseg, req, targetlen,

                            sizeof(struct xseg_reply_info));

    if (ret < 0) {

        archipelagolog("Cannot prepare XSEG request\n");

        goto err_exit;

    }

    char *target = xseg_get_target(s->xseg, req);

    if (!target) {

        archipelagolog("Cannot get XSEG target\n");

        goto err_exit;

    }

    memcpy(target, volname, targetlen);

    req->size = req->datalen;

    req->offset = 0;

    req->op = X_INFO;

    reqdata->op = ARCHIP_OP_VOLINFO;

    reqdata->volname = volname;

    xseg_set_req_data(s->xseg, req, reqdata);

    xport p = xseg_submit(s->xseg, req, s->srcport, X_ALLOC);

    if (p == NoPort) {

        archipelagolog("Cannot submit XSEG request\n");

        goto err_exit;

    }

    xseg_signal(s->xseg, p);

    qemu_mutex_lock(&s->archip_mutex);

    while (!s->is_signaled) {

        qemu_cond_wait(&s->archip_cond, &s->archip_mutex);

    }

    s->is_signaled = false;

    qemu_mutex_unlock(&s->archip_mutex);

    xinfo = (struct xseg_reply_info *) xseg_get_data(s->xseg, req);

    size = xinfo->size;

    xseg_put_request(s->xseg, req, s->srcport);

    g_free(reqdata);

    s->size = size;

    return size;

err_exit:

    xseg_put_request(s->xseg, req, s->srcport);

err_exit2:

    g_free(reqdata);

    return -EIO;

}


static void openpic_set_irq(void *opaque, int n_IRQ, int level)

{

    OpenPICState *opp = opaque;

    IRQSource *src;

    src = &opp->src[n_IRQ];

    DPRINTF("openpic: set irq %d = %d ipvp=%08x\n",

            n_IRQ, level, src->ipvp);

    if (src->ipvp & IPVP_SENSE_MASK) {

        /* level-sensitive irq */

        src->pending = level;

        if (!level) {

            src->ipvp &= ~IPVP_ACTIVITY_MASK;

        }

    } else {

        /* edge-sensitive irq */

        if (level) {

            src->pending = 1;

        }

    }

    openpic_update_irq(opp, n_IRQ);

}


static int libschroedinger_decode_frame(AVCodecContext *avctx,

                                        void *data, int *got_frame,

                                        AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    int64_t pts  = avpkt->pts;

    SchroTag *tag;

    SchroDecoderParams *p_schro_params = avctx->priv_data;

    SchroDecoder *decoder = p_schro_params->decoder;

    SchroBuffer *enc_buf;

    SchroFrame* frame;

    AVFrame *avframe = data;

    int state;

    int go = 1;

    int outer = 1;

    SchroParseUnitContext parse_ctx;

    LibSchroFrameContext *framewithpts = NULL;

    int ret;

    *got_frame = 0;

    parse_context_init(&parse_ctx, buf, buf_size);

    if (!buf_size) {

        if (!p_schro_params->eos_signalled) {

            state = schro_decoder_push_end_of_stream(decoder);

            p_schro_params->eos_signalled = 1;

        }

    }

    /* Loop through all the individual parse units in the input buffer */

    do {

        if ((enc_buf = find_next_parse_unit(&parse_ctx))) {

            /* Set Schrotag with the pts to be recovered after decoding*/

            enc_buf->tag = schro_tag_new(av_malloc(sizeof(int64_t)), av_free);

            if (!enc_buf->tag->value) {

                av_log(avctx, AV_LOG_ERROR, "Unable to allocate SchroTag\n");

                return AVERROR(ENOMEM);

            }

            AV_WN(64, enc_buf->tag->value, pts);

            /* Push buffer into decoder. */

            if (SCHRO_PARSE_CODE_IS_PICTURE(enc_buf->data[4]) &&

                SCHRO_PARSE_CODE_NUM_REFS(enc_buf->data[4]) > 0)

                avctx->has_b_frames = 1;

            state = schro_decoder_push(decoder, enc_buf);

            if (state == SCHRO_DECODER_FIRST_ACCESS_UNIT)

                libschroedinger_handle_first_access_unit(avctx);

            go = 1;

        } else

            outer = 0;

        while (go) {

            /* Parse data and process result. */

            state = schro_decoder_wait(decoder);

            switch (state) {

            case SCHRO_DECODER_FIRST_ACCESS_UNIT:

                libschroedinger_handle_first_access_unit(avctx);

                break;

            case SCHRO_DECODER_NEED_BITS:

                /* Need more input data - stop iterating over what we have. */

                go = 0;

                break;

            case SCHRO_DECODER_NEED_FRAME:

                /* Decoder needs a frame - create one and push it in. */

                frame = ff_create_schro_frame(avctx,

                                              p_schro_params->frame_format);

                if (!frame)

                    return AVERROR(ENOMEM);

                schro_decoder_add_output_picture(decoder, frame);

                break;

            case SCHRO_DECODER_OK:

                /* Pull a frame out of the decoder. */

                tag   = schro_decoder_get_picture_tag(decoder);

                frame = schro_decoder_pull(decoder);

                if (frame) {

                    /* Add relation between schroframe and pts. */

                    framewithpts = av_malloc(sizeof(LibSchroFrameContext));

                    if (!framewithpts) {

                        av_log(avctx, AV_LOG_ERROR, "Unable to allocate FrameWithPts\n");

                        return AVERROR(ENOMEM);

                    }

                    framewithpts->frame = frame;

                    framewithpts->pts   = AV_RN64(tag->value);

                    ff_schro_queue_push_back(&p_schro_params->dec_frame_queue,

                                             framewithpts);

                }

                break;

            case SCHRO_DECODER_EOS:

                go = 0;

                p_schro_params->eos_pulled = 1;

                schro_decoder_reset(decoder);

                outer = 0;

                break;

            case SCHRO_DECODER_ERROR:

                return -1;

                break;

            }

        }

    } while (outer);

    /* Grab next frame to be returned from the top of the queue. */

    framewithpts = ff_schro_queue_pop(&p_schro_params->dec_frame_queue);

    if (framewithpts && framewithpts->frame && framewithpts->frame->components[0].stride) {

        if ((ret = ff_get_buffer(avctx, avframe, 0)) < 0) {

            goto end;

        }

        memcpy(avframe->data[0],

               framewithpts->frame->components[0].data,

               framewithpts->frame->components[0].length);

        memcpy(avframe->data[1],

               framewithpts->frame->components[1].data,

               framewithpts->frame->components[1].length);

        memcpy(avframe->data[2],

               framewithpts->frame->components[2].data,

               framewithpts->frame->components[2].length);

        /* Fill frame with current buffer data from Schroedinger. */

        avframe->pts = framewithpts->pts;

#if FF_API_PKT_PTS

FF_DISABLE_DEPRECATION_WARNINGS

        avframe->pkt_pts = avframe->pts;

FF_ENABLE_DEPRECATION_WARNINGS

#endif

        avframe->linesize[0] = framewithpts->frame->components[0].stride;

        avframe->linesize[1] = framewithpts->frame->components[1].stride;

        avframe->linesize[2] = framewithpts->frame->components[2].stride;

        *got_frame      = 1;

    } else {

        data       = NULL;

        *got_frame = 0;

    }

    ret = buf_size;

end:

    /* Now free the frame resources. */

    if (framewithpts && framewithpts->frame)

        libschroedinger_decode_frame_free(framewithpts->frame);

    av_freep(&framewithpts);

    return ret;

}


static void qemu_tcg_wait_io_event(CPUState *cpu)

{

    while (all_cpu_threads_idle()) {

        stop_tcg_kick_timer();

        qemu_cond_wait(cpu->halt_cond, &qemu_global_mutex);

    }

    start_tcg_kick_timer();

    CPU_FOREACH(cpu) {

        qemu_wait_io_event_common(cpu);

    }

}


TCGOp *tcg_op_insert_after(TCGContext *s, TCGOp *old_op,

                           TCGOpcode opc, int nargs)

{

    int oi = s->gen_next_op_idx;

    int prev = old_op - s->gen_op_buf;

    int next = old_op->next;

    TCGOp *new_op;

    tcg_debug_assert(oi < OPC_BUF_SIZE);

    s->gen_next_op_idx = oi + 1;

    new_op = &s->gen_op_buf[oi];

    *new_op = (TCGOp){

        .opc = opc,

        .prev = prev,

        .next = next

    };

    s->gen_op_buf[next].prev = oi;

    old_op->next = oi;

    return new_op;

}


static inline bool check_lba_range(SCSIDiskState *s,

                                   uint64_t sector_num, uint32_t nb_sectors)

{

    /*

     * The first line tests that no overflow happens when computing the last

     * sector.  The second line tests that the last accessed sector is in

     * range.

     */

    return (sector_num <= sector_num + nb_sectors &&

            sector_num + nb_sectors - 1 <= s->qdev.max_lba);

}


static av_cold int rv30_decode_init(AVCodecContext *avctx)

{

    RV34DecContext *r = avctx->priv_data;

    int ret;

    r->rv30 = 1;

    if ((ret = ff_rv34_decode_init(avctx)) < 0)

        return ret;

    if(avctx->extradata_size < 2){

        av_log(avctx, AV_LOG_ERROR, "Extradata is too small.\n");

        return -1;

    }

    r->rpr = (avctx->extradata[1] & 7) >> 1;

    r->rpr = FFMIN(r->rpr + 1, 3);

    if(avctx->extradata_size - 8 < (r->rpr - 1) * 2){

        av_log(avctx, AV_LOG_ERROR, "Insufficient extradata - need at least %d bytes, got %d\n",

               6 + r->rpr * 2, avctx->extradata_size);

        return AVERROR(EINVAL);

    }

    r->parse_slice_header = rv30_parse_slice_header;

    r->decode_intra_types = rv30_decode_intra_types;

    r->decode_mb_info     = rv30_decode_mb_info;

    r->loop_filter        = rv30_loop_filter;

    r->luma_dc_quant_i = rv30_luma_dc_quant;

    r->luma_dc_quant_p = rv30_luma_dc_quant;

    return 0;

}


static int jpeg2000_decode_packets_po_iteration(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile,

                                             int RSpoc, int CSpoc,

                                             int LYEpoc, int REpoc, int CEpoc,

                                             int Ppoc)

{

    int ret = 0;

    int layno, reslevelno, compno, precno, ok_reslevel;

    int x, y;

    int tp_index = 0;

    int step_x, step_y;

    switch (Ppoc) {

    case JPEG2000_PGOD_RLCP:

        av_log(s->avctx, AV_LOG_DEBUG, "Progression order RLCP\n");

        ok_reslevel = 1;

        for (reslevelno = RSpoc; ok_reslevel && reslevelno < REpoc; reslevelno++) {

            ok_reslevel = 0;

            for (layno = 0; layno < LYEpoc; layno++) {

                for (compno = CSpoc; compno < CEpoc; compno++) {

                    Jpeg2000CodingStyle *codsty = tile->codsty + compno;

                    Jpeg2000QuantStyle *qntsty  = tile->qntsty + compno;

                    if (reslevelno < codsty->nreslevels) {

                        Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel +

                                                reslevelno;

                        ok_reslevel = 1;

                        for (precno = 0; precno < rlevel->num_precincts_x * rlevel->num_precincts_y; precno++)

                            if ((ret = jpeg2000_decode_packet(s, tile, &tp_index,

                                                              codsty, rlevel,

                                                              precno, layno,

                                                              qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),

                                                              qntsty->nguardbits)) < 0)

                                return ret;

                    }

                }

            }

        }

        break;

    case JPEG2000_PGOD_LRCP:

        av_log(s->avctx, AV_LOG_DEBUG, "Progression order LRCP\n");

        for (layno = 0; layno < LYEpoc; layno++) {

            ok_reslevel = 1;

            for (reslevelno = RSpoc; ok_reslevel && reslevelno < REpoc; reslevelno++) {

                ok_reslevel = 0;

                for (compno = CSpoc; compno < CEpoc; compno++) {

                    Jpeg2000CodingStyle *codsty = tile->codsty + compno;

                    Jpeg2000QuantStyle *qntsty  = tile->qntsty + compno;

                    if (reslevelno < codsty->nreslevels) {

                        Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel +

                                                reslevelno;

                        ok_reslevel = 1;

                        for (precno = 0; precno < rlevel->num_precincts_x * rlevel->num_precincts_y; precno++)

                            if ((ret = jpeg2000_decode_packet(s, tile, &tp_index,

                                                              codsty, rlevel,

                                                              precno, layno,

                                                              qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),

                                                              qntsty->nguardbits)) < 0)

                                return ret;

                    }

                }

            }

        }

        break;

    case JPEG2000_PGOD_CPRL:

        av_log(s->avctx, AV_LOG_DEBUG, "Progression order CPRL\n");

        for (compno = CSpoc; compno < CEpoc; compno++) {

            Jpeg2000Component *comp     = tile->comp + compno;

            Jpeg2000CodingStyle *codsty = tile->codsty + compno;

            Jpeg2000QuantStyle *qntsty  = tile->qntsty + compno;

            step_x = 32;

            step_y = 32;

            for (reslevelno = RSpoc; reslevelno < FFMIN(codsty->nreslevels, REpoc); reslevelno++) {

                uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r

                Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;

                step_x = FFMIN(step_x, rlevel->log2_prec_width  + reducedresno);

                step_y = FFMIN(step_y, rlevel->log2_prec_height + reducedresno);

            }

            step_x = 1<<step_x;

            step_y = 1<<step_y;

            for (y = tile->coord[1][0]; y < tile->coord[1][1]; y = (y/step_y + 1)*step_y) {

                for (x = tile->coord[0][0]; x < tile->coord[0][1]; x = (x/step_x + 1)*step_x) {

                    for (reslevelno = RSpoc; reslevelno < FFMIN(codsty->nreslevels, REpoc); reslevelno++) {

                        unsigned prcx, prcy;

                        uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r

                        Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;

                        int xc = x / s->cdx[compno];

                        int yc = y / s->cdy[compno];

                        if (yc % (1 << (rlevel->log2_prec_height + reducedresno)) && y != tile->coord[1][0]) //FIXME this is a subset of the check

                            continue;

                        if (xc % (1 << (rlevel->log2_prec_width + reducedresno)) && x != tile->coord[0][0]) //FIXME this is a subset of the check

                            continue;

                        // check if a precinct exists

                        prcx   = ff_jpeg2000_ceildivpow2(xc, reducedresno) >> rlevel->log2_prec_width;

                        prcy   = ff_jpeg2000_ceildivpow2(yc, reducedresno) >> rlevel->log2_prec_height;

                        prcx  -= ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], reducedresno) >> rlevel->log2_prec_width;

                        prcy  -= ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], reducedresno) >> rlevel->log2_prec_height;

                        precno = prcx + rlevel->num_precincts_x * prcy;

                        if (prcx >= rlevel->num_precincts_x || prcy >= rlevel->num_precincts_y) {

                            av_log(s->avctx, AV_LOG_WARNING, "prc %d %d outside limits %d %d\n",

                                   prcx, prcy, rlevel->num_precincts_x, rlevel->num_precincts_y);

                            continue;

                        }

                        for (layno = 0; layno < LYEpoc; layno++) {

                            if ((ret = jpeg2000_decode_packet(s, tile, &tp_index, codsty, rlevel,

                                                              precno, layno,

                                                              qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),

                                                              qntsty->nguardbits)) < 0)

                                return ret;

                        }

                    }

                }

            }

        }

        break;

    case JPEG2000_PGOD_RPCL:

        av_log(s->avctx, AV_LOG_WARNING, "Progression order RPCL\n");

        ok_reslevel = 1;

        for (reslevelno = RSpoc; ok_reslevel && reslevelno < REpoc; reslevelno++) {

            ok_reslevel = 0;

            step_x = 30;

            step_y = 30;

            for (compno = CSpoc; compno < CEpoc; compno++) {

                Jpeg2000Component *comp     = tile->comp + compno;

                Jpeg2000CodingStyle *codsty = tile->codsty + compno;

                if (reslevelno < codsty->nreslevels) {

                    uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r

                    Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;

                    step_x = FFMIN(step_x, rlevel->log2_prec_width  + reducedresno);

                    step_y = FFMIN(step_y, rlevel->log2_prec_height + reducedresno);

                }

            }

            step_x = 1<<step_x;

            step_y = 1<<step_y;

            for (y = tile->coord[1][0]; y < tile->coord[1][1]; y = (y/step_y + 1)*step_y) {

                for (x = tile->coord[0][0]; x < tile->coord[0][1]; x = (x/step_x + 1)*step_x) {

                    for (compno = CSpoc; compno < CEpoc; compno++) {

                        Jpeg2000Component *comp     = tile->comp + compno;

                        Jpeg2000CodingStyle *codsty = tile->codsty + compno;

                        Jpeg2000QuantStyle *qntsty  = tile->qntsty + compno;

                        uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r

                        Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;

                        unsigned prcx, prcy;

                        int xc = x / s->cdx[compno];

                        int yc = y / s->cdy[compno];

                        if (reslevelno >= codsty->nreslevels)

                            continue;

                        if (yc % (1 << (rlevel->log2_prec_height + reducedresno)) && y != tile->coord[1][0]) //FIXME this is a subset of the check

                            continue;

                        if (xc % (1 << (rlevel->log2_prec_width + reducedresno)) && x != tile->coord[0][0]) //FIXME this is a subset of the check

                            continue;

                        // check if a precinct exists

                        prcx   = ff_jpeg2000_ceildivpow2(xc, reducedresno) >> rlevel->log2_prec_width;

                        prcy   = ff_jpeg2000_ceildivpow2(yc, reducedresno) >> rlevel->log2_prec_height;

                        prcx  -= ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], reducedresno) >> rlevel->log2_prec_width;

                        prcy  -= ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], reducedresno) >> rlevel->log2_prec_height;

                        precno = prcx + rlevel->num_precincts_x * prcy;

                        ok_reslevel = 1;

                        if (prcx >= rlevel->num_precincts_x || prcy >= rlevel->num_precincts_y) {

                            av_log(s->avctx, AV_LOG_WARNING, "prc %d %d outside limits %d %d\n",

                                   prcx, prcy, rlevel->num_precincts_x, rlevel->num_precincts_y);

                            continue;

                        }

                            for (layno = 0; layno < LYEpoc; layno++) {

                                if ((ret = jpeg2000_decode_packet(s, tile, &tp_index,

                                                                codsty, rlevel,

                                                                precno, layno,

                                                                qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),

                                                                qntsty->nguardbits)) < 0)

                                    return ret;

                            }

                    }

                }

            }

        }

        break;

    case JPEG2000_PGOD_PCRL:

        av_log(s->avctx, AV_LOG_WARNING, "Progression order PCRL\n");

        step_x = 32;

        step_y = 32;

        for (compno = CSpoc; compno < CEpoc; compno++) {

            Jpeg2000Component *comp     = tile->comp + compno;

            Jpeg2000CodingStyle *codsty = tile->codsty + compno;

            Jpeg2000QuantStyle *qntsty  = tile->qntsty + compno;

            for (reslevelno = RSpoc; reslevelno < FFMIN(codsty->nreslevels, REpoc); reslevelno++) {

                uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r

                Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;

                step_x = FFMIN(step_x, rlevel->log2_prec_width  + reducedresno);

                step_y = FFMIN(step_y, rlevel->log2_prec_height + reducedresno);

            }

        }

        step_x = 1<<step_x;

        step_y = 1<<step_y;

        for (y = tile->coord[1][0]; y < tile->coord[1][1]; y = (y/step_y + 1)*step_y) {

            for (x = tile->coord[0][0]; x < tile->coord[0][1]; x = (x/step_x + 1)*step_x) {

                for (compno = CSpoc; compno < CEpoc; compno++) {

                    Jpeg2000Component *comp     = tile->comp + compno;

                    Jpeg2000CodingStyle *codsty = tile->codsty + compno;

                    Jpeg2000QuantStyle *qntsty  = tile->qntsty + compno;

                    int xc = x / s->cdx[compno];

                    int yc = y / s->cdy[compno];

                    for (reslevelno = RSpoc; reslevelno < FFMIN(codsty->nreslevels, REpoc); reslevelno++) {

                        unsigned prcx, prcy;

                        uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r

                        Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;

                        if (yc % (1 << (rlevel->log2_prec_height + reducedresno)) && y != tile->coord[1][0]) //FIXME this is a subset of the check

                            continue;

                        if (xc % (1 << (rlevel->log2_prec_width + reducedresno)) && x != tile->coord[0][0]) //FIXME this is a subset of the check

                            continue;

                        // check if a precinct exists

                        prcx   = ff_jpeg2000_ceildivpow2(xc, reducedresno) >> rlevel->log2_prec_width;

                        prcy   = ff_jpeg2000_ceildivpow2(yc, reducedresno) >> rlevel->log2_prec_height;

                        prcx  -= ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], reducedresno) >> rlevel->log2_prec_width;

                        prcy  -= ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], reducedresno) >> rlevel->log2_prec_height;

                        precno = prcx + rlevel->num_precincts_x * prcy;

                        if (prcx >= rlevel->num_precincts_x || prcy >= rlevel->num_precincts_y) {

                            av_log(s->avctx, AV_LOG_WARNING, "prc %d %d outside limits %d %d\n",

                                   prcx, prcy, rlevel->num_precincts_x, rlevel->num_precincts_y);

                            continue;

                        }

                        for (layno = 0; layno < LYEpoc; layno++) {

                            if ((ret = jpeg2000_decode_packet(s, tile, &tp_index, codsty, rlevel,

                                                              precno, layno,

                                                              qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),

                                                              qntsty->nguardbits)) < 0)

                                return ret;

                        }

                    }

                }

            }

        }

        break;

    default:

        break;

    }

    return ret;

}


static av_cold int vmdaudio_decode_init(AVCodecContext *avctx)

{

    VmdAudioContext *s = avctx->priv_data;

    if (avctx->channels < 1 || avctx->channels > 2) {

        av_log(avctx, AV_LOG_ERROR, "invalid number of channels\n");

        return AVERROR(EINVAL);

    }

    if (avctx->block_align < 1) {

        av_log(avctx, AV_LOG_ERROR, "invalid block align\n");

        return AVERROR(EINVAL);

    }

    avctx->channel_layout = avctx->channels == 1 ? AV_CH_LAYOUT_MONO :

                                                   AV_CH_LAYOUT_STEREO;

    if (avctx->bits_per_coded_sample == 16)

        avctx->sample_fmt = AV_SAMPLE_FMT_S16;

    else

        avctx->sample_fmt = AV_SAMPLE_FMT_U8;

    s->out_bps = av_get_bytes_per_sample(avctx->sample_fmt);

    s->chunk_size = avctx->block_align + avctx->channels * (s->out_bps == 2);

    avcodec_get_frame_defaults(&s->frame);

    avctx->coded_frame = &s->frame;

    av_log(avctx, AV_LOG_DEBUG, "%d channels, %d bits/sample, "

           "block align = %d, sample rate = %d\n",

           avctx->channels, avctx->bits_per_coded_sample, avctx->block_align,

           avctx->sample_rate);

    return 0;

}


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

                                int *got_frame, AVPacket *avpkt)

{

    const uint8_t *buf       = avpkt->data;

    const uint8_t *buf_end   = avpkt->data + avpkt->size;

    AVFrame * const p        = data;

    unsigned int w, h, depth, type, maptype, maplength, stride, x, y, len, alen;

    uint8_t *ptr, *ptr2 = NULL;

    const uint8_t *bufstart = buf;

    int ret;

    if (avpkt->size < 32)

        return AVERROR_INVALIDDATA;

    if (AV_RB32(buf) != RAS_MAGIC) {

        av_log(avctx, AV_LOG_ERROR, "this is not sunras encoded data\n");

        return AVERROR_INVALIDDATA;

    }

    w         = AV_RB32(buf + 4);

    h         = AV_RB32(buf + 8);

    depth     = AV_RB32(buf + 12);

    type      = AV_RB32(buf + 20);

    maptype   = AV_RB32(buf + 24);

    maplength = AV_RB32(buf + 28);

    buf      += 32;

    if (type == RT_EXPERIMENTAL) {

        avpriv_request_sample(avctx, "TIFF/IFF/EXPERIMENTAL (compression) type");

        return AVERROR_PATCHWELCOME;

    }

    if (type > RT_FORMAT_IFF) {

        av_log(avctx, AV_LOG_ERROR, "invalid (compression) type\n");

        return AVERROR_INVALIDDATA;

    }

    if (maptype == RMT_RAW) {

        avpriv_request_sample(avctx, "Unknown colormap type");

        return AVERROR_PATCHWELCOME;

    }

    if (maptype > RMT_RAW) {

        av_log(avctx, AV_LOG_ERROR, "invalid colormap type\n");

        return AVERROR_INVALIDDATA;

    }

    if (type == RT_FORMAT_TIFF || type == RT_FORMAT_IFF) {

        av_log(avctx, AV_LOG_ERROR, "unsupported (compression) type\n");

        return -1;

    }

    switch (depth) {

        case 1:

            avctx->pix_fmt = maplength ? AV_PIX_FMT_PAL8 : AV_PIX_FMT_MONOWHITE;

            break;

        case 4:

            avctx->pix_fmt = maplength ? AV_PIX_FMT_PAL8 : AV_PIX_FMT_NONE;

            break;

        case 8:

            avctx->pix_fmt = maplength ? AV_PIX_FMT_PAL8 : AV_PIX_FMT_GRAY8;

            break;

        case 24:

            avctx->pix_fmt = (type == RT_FORMAT_RGB) ? AV_PIX_FMT_RGB24 : AV_PIX_FMT_BGR24;

            break;

        case 32:

            avctx->pix_fmt = (type == RT_FORMAT_RGB) ? AV_PIX_FMT_0RGB : AV_PIX_FMT_0BGR;

            break;

        default:

            av_log(avctx, AV_LOG_ERROR, "invalid depth\n");

            return AVERROR_INVALIDDATA;

    }

    ret = ff_set_dimensions(avctx, w, h);

    if (ret < 0)

        return ret;

    if ((ret = ff_get_buffer(avctx, p, 0)) < 0)

        return ret;

    p->pict_type = AV_PICTURE_TYPE_I;

    if (buf_end - buf < maplength)

        return AVERROR_INVALIDDATA;

    if (depth > 8 && maplength) {

        av_log(avctx, AV_LOG_WARNING, "useless colormap found or file is corrupted, trying to recover\n");

    } else if (maplength) {

        unsigned int len = maplength / 3;

        if (maplength % 3 || maplength > 768) {

            av_log(avctx, AV_LOG_WARNING, "invalid colormap length\n");

            return AVERROR_INVALIDDATA;

        }

        ptr = p->data[1];

        for (x = 0; x < len; x++, ptr += 4)

            *(uint32_t *)ptr = (0xFFU<<24) + (buf[x]<<16) + (buf[len+x]<<8) + buf[len+len+x];

    }

    buf += maplength;

    if (maplength && depth < 8) {

        ptr = ptr2 = av_malloc_array((w + 15), h);

        if (!ptr)

            return AVERROR(ENOMEM);

        stride = (w + 15 >> 3) * depth;

    } else {

    ptr    = p->data[0];

    stride = p->linesize[0];

    }

    /* scanlines are aligned on 16 bit boundaries */

    len  = (depth * w + 7) >> 3;

    alen = len + (len & 1);

    if (type == RT_BYTE_ENCODED) {

        int value, run;

        uint8_t *end = ptr + h * stride;

        x = 0;

        while (ptr != end && buf < buf_end) {

            run = 1;

            if (buf_end - buf < 1)

                return AVERROR_INVALIDDATA;

            if ((value = *buf++) == RLE_TRIGGER) {

                run = *buf++ + 1;

                if (run != 1)

                    value = *buf++;

            }

            while (run--) {

                if (x < len)

                    ptr[x] = value;

                if (++x >= alen) {

                    x = 0;

                    ptr += stride;

                    if (ptr == end)

                        break;

                }

            }

        }

    } else {

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

            if (buf_end - buf < len)

                break;

            memcpy(ptr, buf, len);

            ptr += stride;

            buf += alen;

        }

    }

    if (avctx->pix_fmt == AV_PIX_FMT_PAL8 && depth < 8) {

        uint8_t *ptr_free = ptr2;

        ptr = p->data[0];

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

            for (x = 0; x < (w + 7 >> 3) * depth; x++) {

                if (depth == 1) {

                    ptr[8*x]   = ptr2[x] >> 7;

                    ptr[8*x+1] = ptr2[x] >> 6 & 1;

                    ptr[8*x+2] = ptr2[x] >> 5 & 1;

                    ptr[8*x+3] = ptr2[x] >> 4 & 1;

                    ptr[8*x+4] = ptr2[x] >> 3 & 1;

                    ptr[8*x+5] = ptr2[x] >> 2 & 1;

                    ptr[8*x+6] = ptr2[x] >> 1 & 1;

                    ptr[8*x+7] = ptr2[x]      & 1;

                } else {

                    ptr[2*x]   = ptr2[x] >> 4;

                    ptr[2*x+1] = ptr2[x] & 0xF;

                }

            }

            ptr  += p->linesize[0];

            ptr2 += (w + 15 >> 3) * depth;

        }

        av_freep(&ptr_free);

    }

    *got_frame = 1;

    return buf - bufstart;

}


static int xan_decode_frame(AVCodecContext *avctx,

                            void *data, int *data_size,

                            AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int ret, buf_size = avpkt->size;

    XanContext *s = avctx->priv_data;

    if (avctx->codec->id == CODEC_ID_XAN_WC3) {

        const uint8_t *buf_end = buf + buf_size;

        int tag = 0;

        while (buf_end - buf > 8 && tag != VGA__TAG) {

            unsigned *tmpptr;

            uint32_t new_pal;

            int size;

            int i;

            tag  = bytestream_get_le32(&buf);

            size = bytestream_get_be32(&buf);

            size = FFMIN(size, buf_end - buf);

            switch (tag) {

            case PALT_TAG:

                if (size < PALETTE_SIZE)

                    return AVERROR_INVALIDDATA;

                if (s->palettes_count >= PALETTES_MAX)

                    return AVERROR_INVALIDDATA;

                tmpptr = av_realloc(s->palettes, (s->palettes_count + 1) * AVPALETTE_SIZE);

                if (!tmpptr)

                    return AVERROR(ENOMEM);

                s->palettes = tmpptr;

                tmpptr += s->palettes_count * AVPALETTE_COUNT;

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

#if RUNTIME_GAMMA

                    int r = gamma_corr(*buf++);

                    int g = gamma_corr(*buf++);

                    int b = gamma_corr(*buf++);

#else

                    int r = gamma_lookup[*buf++];

                    int g = gamma_lookup[*buf++];

                    int b = gamma_lookup[*buf++];

#endif

                    *tmpptr++ = (r << 16) | (g << 8) | b;

                }

                s->palettes_count++;

                break;

            case SHOT_TAG:

                if (size < 4)

                    return AVERROR_INVALIDDATA;

                new_pal = bytestream_get_le32(&buf);

                if (new_pal < s->palettes_count) {

                    s->cur_palette = new_pal;

                } else

                    av_log(avctx, AV_LOG_ERROR, "Invalid palette selected\n");

                break;

            case VGA__TAG:

                break;

            default:

                buf += size;

                break;

            }

        }

        buf_size = buf_end - buf;

    }

    if ((ret = avctx->get_buffer(avctx, &s->current_frame))) {

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

        return ret;

    }

    s->current_frame.reference = 3;

    if (!s->frame_size)

        s->frame_size = s->current_frame.linesize[0] * s->avctx->height;

    memcpy(s->current_frame.data[1], s->palettes + s->cur_palette * AVPALETTE_COUNT, AVPALETTE_SIZE);

    s->buf = buf;

    s->size = buf_size;

    xan_wc3_decode_frame(s);

    /* release the last frame if it is allocated */

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

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

    *data_size = sizeof(AVFrame);

    *(AVFrame*)data = s->current_frame;

    /* shuffle frames */

    FFSWAP(AVFrame, s->current_frame, s->last_frame);

    /* always report that the buffer was completely consumed */

    return buf_size;

}


av_cold int MPV_encode_init(AVCodecContext *avctx)

{

    MpegEncContext *s = avctx->priv_data;

    int i;

    int chroma_h_shift, chroma_v_shift;

    MPV_encode_defaults(s);

    switch (avctx->codec_id) {

    case CODEC_ID_MPEG2VIDEO:

        if(avctx->pix_fmt != PIX_FMT_YUV420P && avctx->pix_fmt != PIX_FMT_YUV422P){

            av_log(avctx, AV_LOG_ERROR, "only YUV420 and YUV422 are supported\n");

            return -1;

        }

        break;

    case CODEC_ID_LJPEG:

    case CODEC_ID_MJPEG:

        if(avctx->pix_fmt != PIX_FMT_YUVJ420P && avctx->pix_fmt != PIX_FMT_YUVJ422P && avctx->pix_fmt != PIX_FMT_RGB32 &&

           ((avctx->pix_fmt != PIX_FMT_YUV420P && avctx->pix_fmt != PIX_FMT_YUV422P) || avctx->strict_std_compliance>FF_COMPLIANCE_INOFFICIAL)){

            av_log(avctx, AV_LOG_ERROR, "colorspace not supported in jpeg\n");

            return -1;

        }

        break;

    default:

        if(avctx->pix_fmt != PIX_FMT_YUV420P){

            av_log(avctx, AV_LOG_ERROR, "only YUV420 is supported\n");

            return -1;

        }

    }

    switch (avctx->pix_fmt) {

    case PIX_FMT_YUVJ422P:

    case PIX_FMT_YUV422P:

        s->chroma_format = CHROMA_422;

        break;

    case PIX_FMT_YUVJ420P:

    case PIX_FMT_YUV420P:

    default:

        s->chroma_format = CHROMA_420;

        break;

    }

    s->bit_rate = avctx->bit_rate;

    s->width = avctx->width;

    s->height = avctx->height;

    if(avctx->gop_size > 600 && avctx->strict_std_compliance>FF_COMPLIANCE_EXPERIMENTAL){

        av_log(avctx, AV_LOG_ERROR, "Warning keyframe interval too large! reducing it ...\n");

        avctx->gop_size=600;

    }

    s->gop_size = avctx->gop_size;

    s->avctx = avctx;

    s->flags= avctx->flags;

    s->flags2= avctx->flags2;

    s->max_b_frames= avctx->max_b_frames;

    s->codec_id= avctx->codec->id;

    s->luma_elim_threshold  = avctx->luma_elim_threshold;

    s->chroma_elim_threshold= avctx->chroma_elim_threshold;

    s->strict_std_compliance= avctx->strict_std_compliance;

    s->data_partitioning= avctx->flags & CODEC_FLAG_PART;

    s->quarter_sample= (avctx->flags & CODEC_FLAG_QPEL)!=0;

    s->mpeg_quant= avctx->mpeg_quant;

    s->rtp_mode= !!avctx->rtp_payload_size;

    s->intra_dc_precision= avctx->intra_dc_precision;

    s->user_specified_pts = AV_NOPTS_VALUE;

    if (s->gop_size <= 1) {

        s->intra_only = 1;

        s->gop_size = 12;

    } else {

        s->intra_only = 0;

    }

    s->me_method = avctx->me_method;

    /* Fixed QSCALE */

    s->fixed_qscale = !!(avctx->flags & CODEC_FLAG_QSCALE);

    s->adaptive_quant= (   s->avctx->lumi_masking

                        || s->avctx->dark_masking

                        || s->avctx->temporal_cplx_masking

                        || s->avctx->spatial_cplx_masking

                        || s->avctx->p_masking

                        || s->avctx->border_masking

                        || (s->flags&CODEC_FLAG_QP_RD))

                       && !s->fixed_qscale;

    s->obmc= !!(s->flags & CODEC_FLAG_OBMC);

    s->loop_filter= !!(s->flags & CODEC_FLAG_LOOP_FILTER);

    s->alternate_scan= !!(s->flags & CODEC_FLAG_ALT_SCAN);

    s->intra_vlc_format= !!(s->flags2 & CODEC_FLAG2_INTRA_VLC);

    s->q_scale_type= !!(s->flags2 & CODEC_FLAG2_NON_LINEAR_QUANT);

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

        av_log(avctx, AV_LOG_ERROR, "a vbv buffer size is needed, for encoding with a maximum bitrate\n");

        return -1;

    }

    if(avctx->rc_min_rate && avctx->rc_max_rate != avctx->rc_min_rate){

        av_log(avctx, AV_LOG_INFO, "Warning min_rate > 0 but min_rate != max_rate isn't recommended!\n");

    }

    if(avctx->rc_min_rate && avctx->rc_min_rate > avctx->bit_rate){

        av_log(avctx, AV_LOG_ERROR, "bitrate below min bitrate\n");

        return -1;

    }

    if(avctx->rc_max_rate && avctx->rc_max_rate < avctx->bit_rate){

        av_log(avctx, AV_LOG_INFO, "bitrate above max bitrate\n");

        return -1;

    }

    if(avctx->rc_max_rate && avctx->rc_max_rate == avctx->bit_rate && avctx->rc_max_rate != avctx->rc_min_rate){

        av_log(avctx, AV_LOG_INFO, "impossible bitrate constraints, this will fail\n");

    }

    if(avctx->rc_buffer_size && avctx->bit_rate*av_q2d(avctx->time_base) > avctx->rc_buffer_size){

        av_log(avctx, AV_LOG_ERROR, "VBV buffer too small for bitrate\n");

        return -1;

    }

    if(avctx->bit_rate*av_q2d(avctx->time_base) > avctx->bit_rate_tolerance){

        av_log(avctx, AV_LOG_ERROR, "bitrate tolerance too small for bitrate\n");

        return -1;

    }

    if(   s->avctx->rc_max_rate && s->avctx->rc_min_rate == s->avctx->rc_max_rate

       && (s->codec_id == CODEC_ID_MPEG1VIDEO || s->codec_id == CODEC_ID_MPEG2VIDEO)

       && 90000LL * (avctx->rc_buffer_size-1) > s->avctx->rc_max_rate*0xFFFFLL){

        av_log(avctx, AV_LOG_INFO, "Warning vbv_delay will be set to 0xFFFF (=VBR) as the specified vbv buffer is too large for the given bitrate!\n");

    }

    if((s->flags & CODEC_FLAG_4MV) && s->codec_id != CODEC_ID_MPEG4

       && s->codec_id != CODEC_ID_H263 && s->codec_id != CODEC_ID_H263P && s->codec_id != CODEC_ID_FLV1){

        av_log(avctx, AV_LOG_ERROR, "4MV not supported by codec\n");

        return -1;

    }

    if(s->obmc && s->avctx->mb_decision != FF_MB_DECISION_SIMPLE){

        av_log(avctx, AV_LOG_ERROR, "OBMC is only supported with simple mb decision\n");

        return -1;

    }

    if(s->obmc && s->codec_id != CODEC_ID_H263 && s->codec_id != CODEC_ID_H263P){

        av_log(avctx, AV_LOG_ERROR, "OBMC is only supported with H263(+)\n");

        return -1;

    }

    if(s->quarter_sample && s->codec_id != CODEC_ID_MPEG4){

        av_log(avctx, AV_LOG_ERROR, "qpel not supported by codec\n");

        return -1;

    }

    if(s->data_partitioning && s->codec_id != CODEC_ID_MPEG4){

        av_log(avctx, AV_LOG_ERROR, "data partitioning not supported by codec\n");

        return -1;

    }

    if(s->max_b_frames && s->codec_id != CODEC_ID_MPEG4 && s->codec_id != CODEC_ID_MPEG1VIDEO && s->codec_id != CODEC_ID_MPEG2VIDEO){

        av_log(avctx, AV_LOG_ERROR, "b frames not supported by codec\n");

        return -1;

    }

    if((s->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME|CODEC_FLAG_ALT_SCAN))

       && s->codec_id != CODEC_ID_MPEG4 && s->codec_id != CODEC_ID_MPEG2VIDEO){

        av_log(avctx, AV_LOG_ERROR, "interlacing not supported by codec\n");

        return -1;

    }

    if(s->mpeg_quant && s->codec_id != CODEC_ID_MPEG4){ //FIXME mpeg2 uses that too

        av_log(avctx, AV_LOG_ERROR, "mpeg2 style quantization not supported by codec\n");

        return -1;

    }

    if((s->flags & CODEC_FLAG_CBP_RD) && !avctx->trellis){

        av_log(avctx, AV_LOG_ERROR, "CBP RD needs trellis quant\n");

        return -1;

    }

    if((s->flags & CODEC_FLAG_QP_RD) && s->avctx->mb_decision != FF_MB_DECISION_RD){

        av_log(avctx, AV_LOG_ERROR, "QP RD needs mbd=2\n");

        return -1;

    }

    if(s->avctx->scenechange_threshold < 1000000000 && (s->flags & CODEC_FLAG_CLOSED_GOP)){

        av_log(avctx, AV_LOG_ERROR, "closed gop with scene change detection are not supported yet, set threshold to 1000000000\n");

        return -1;

    }

    if((s->flags2 & CODEC_FLAG2_INTRA_VLC) && s->codec_id != CODEC_ID_MPEG2VIDEO){

        av_log(avctx, AV_LOG_ERROR, "intra vlc table not supported by codec\n");

        return -1;

    }

    if(s->flags & CODEC_FLAG_LOW_DELAY){

        if (s->codec_id != CODEC_ID_MPEG2VIDEO){

            av_log(avctx, AV_LOG_ERROR, "low delay forcing is only available for mpeg2\n");

            return -1;

        }

        if (s->max_b_frames != 0){

            av_log(avctx, AV_LOG_ERROR, "b frames cannot be used with low delay\n");

            return -1;

        }

    }

    if(s->q_scale_type == 1){

        if(s->codec_id != CODEC_ID_MPEG2VIDEO){

            av_log(avctx, AV_LOG_ERROR, "non linear quant is only available for mpeg2\n");

            return -1;

        }

        if(avctx->qmax > 12){

            av_log(avctx, AV_LOG_ERROR, "non linear quant only supports qmax <= 12 currently\n");

            return -1;

        }

    }

    if(s->avctx->thread_count > 1 && s->codec_id != CODEC_ID_MPEG4

       && s->codec_id != CODEC_ID_MPEG1VIDEO && s->codec_id != CODEC_ID_MPEG2VIDEO

       && (s->codec_id != CODEC_ID_H263P || !(s->flags & CODEC_FLAG_H263P_SLICE_STRUCT))){

        av_log(avctx, AV_LOG_ERROR, "multi threaded encoding not supported by codec\n");

        return -1;

    }

    if(s->avctx->thread_count < 1){

        av_log(avctx, AV_LOG_ERROR, "automatic thread number detection not supported by codec, patch welcome\n");

        return -1;

    }

    if(s->avctx->thread_count > 1)

        s->rtp_mode= 1;

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

        av_log(avctx, AV_LOG_ERROR, "framerate not set\n");

        return -1;

    }

    i= (INT_MAX/2+128)>>8;

    if(avctx->me_threshold >= i){

        av_log(avctx, AV_LOG_ERROR, "me_threshold too large, max is %d\n", i - 1);

        return -1;

    }

    if(avctx->mb_threshold >= i){

        av_log(avctx, AV_LOG_ERROR, "mb_threshold too large, max is %d\n", i - 1);

        return -1;

    }

    if(avctx->b_frame_strategy && (avctx->flags&CODEC_FLAG_PASS2)){

        av_log(avctx, AV_LOG_INFO, "notice: b_frame_strategy only affects the first pass\n");

        avctx->b_frame_strategy = 0;

    }

    i= av_gcd(avctx->time_base.den, avctx->time_base.num);

    if(i > 1){

        av_log(avctx, AV_LOG_INFO, "removing common factors from framerate\n");

        avctx->time_base.den /= i;

        avctx->time_base.num /= i;

//        return -1;

    }

    if(s->codec_id==CODEC_ID_MJPEG){

        s->intra_quant_bias= 1<<(QUANT_BIAS_SHIFT-1); //(a + x/2)/x

        s->inter_quant_bias= 0;

    }else if(s->mpeg_quant || s->codec_id==CODEC_ID_MPEG1VIDEO || s->codec_id==CODEC_ID_MPEG2VIDEO){

        s->intra_quant_bias= 3<<(QUANT_BIAS_SHIFT-3); //(a + x*3/8)/x

        s->inter_quant_bias= 0;

    }else{

        s->intra_quant_bias=0;

        s->inter_quant_bias=-(1<<(QUANT_BIAS_SHIFT-2)); //(a - x/4)/x

    }

    if(avctx->intra_quant_bias != FF_DEFAULT_QUANT_BIAS)

        s->intra_quant_bias= avctx->intra_quant_bias;

    if(avctx->inter_quant_bias != FF_DEFAULT_QUANT_BIAS)

        s->inter_quant_bias= avctx->inter_quant_bias;

    avcodec_get_chroma_sub_sample(avctx->pix_fmt, &chroma_h_shift, &chroma_v_shift);

    if(avctx->codec_id == CODEC_ID_MPEG4 && s->avctx->time_base.den > (1<<16)-1){

        av_log(avctx, AV_LOG_ERROR, "timebase not supported by mpeg 4 standard\n");

        return -1;

    }

    s->time_increment_bits = av_log2(s->avctx->time_base.den - 1) + 1;

    switch(avctx->codec->id) {

    case CODEC_ID_MPEG1VIDEO:

        s->out_format = FMT_MPEG1;

        s->low_delay= !!(s->flags & CODEC_FLAG_LOW_DELAY);

        avctx->delay= s->low_delay ? 0 : (s->max_b_frames + 1);

        break;

    case CODEC_ID_MPEG2VIDEO:

        s->out_format = FMT_MPEG1;

        s->low_delay= !!(s->flags & CODEC_FLAG_LOW_DELAY);

        avctx->delay= s->low_delay ? 0 : (s->max_b_frames + 1);

        s->rtp_mode= 1;

        break;

    case CODEC_ID_LJPEG:

    case CODEC_ID_MJPEG:

        s->out_format = FMT_MJPEG;

        s->intra_only = 1; /* force intra only for jpeg */

        if(avctx->codec->id == CODEC_ID_MJPEG || avctx->pix_fmt != PIX_FMT_BGRA){

        s->mjpeg_vsample[0] = 2;

        s->mjpeg_vsample[1] = 2>>chroma_v_shift;

        s->mjpeg_vsample[2] = 2>>chroma_v_shift;

        s->mjpeg_hsample[0] = 2;

        s->mjpeg_hsample[1] = 2>>chroma_h_shift;

        s->mjpeg_hsample[2] = 2>>chroma_h_shift;

        }else{

            s->mjpeg_vsample[0] = s->mjpeg_hsample[0] =

            s->mjpeg_vsample[1] = s->mjpeg_hsample[1] =

            s->mjpeg_vsample[2] = s->mjpeg_hsample[2] = 1;

        }

        if (!(CONFIG_MJPEG_ENCODER || CONFIG_LJPEG_ENCODER)

            || ff_mjpeg_encode_init(s) < 0)

            return -1;

        avctx->delay=0;

        s->low_delay=1;

        break;

    case CODEC_ID_H261:

        if (!CONFIG_H261_ENCODER)  return -1;

        if (ff_h261_get_picture_format(s->width, s->height) < 0) {

            av_log(avctx, AV_LOG_ERROR, "The specified picture size of %dx%d is not valid for the H.261 codec.\nValid sizes are 176x144, 352x288\n", s->width, s->height);

            return -1;

        }

        s->out_format = FMT_H261;

        avctx->delay=0;

        s->low_delay=1;

        break;

    case CODEC_ID_H263:

        if (!CONFIG_H263_ENCODER)  return -1;

        if (h263_get_picture_format(s->width, s->height) == 7) {

            av_log(avctx, AV_LOG_INFO, "The specified picture size of %dx%d is not valid for the H.263 codec.\nValid sizes are 128x96, 176x144, 352x288, 704x576, and 1408x1152. Try H.263+.\n", s->width, s->height);

            return -1;

        }

        s->out_format = FMT_H263;

        s->obmc= (avctx->flags & CODEC_FLAG_OBMC) ? 1:0;

        avctx->delay=0;

        s->low_delay=1;

        break;

    case CODEC_ID_H263P:

        s->out_format = FMT_H263;

        s->h263_plus = 1;

        /* Fx */

        s->umvplus = (avctx->flags & CODEC_FLAG_H263P_UMV) ? 1:0;

        s->h263_aic= (avctx->flags & CODEC_FLAG_AC_PRED) ? 1:0;

        s->modified_quant= s->h263_aic;

        s->alt_inter_vlc= (avctx->flags & CODEC_FLAG_H263P_AIV) ? 1:0;

        s->obmc= (avctx->flags & CODEC_FLAG_OBMC) ? 1:0;

        s->loop_filter= (avctx->flags & CODEC_FLAG_LOOP_FILTER) ? 1:0;

        s->unrestricted_mv= s->obmc || s->loop_filter || s->umvplus;

        s->h263_slice_structured= (s->flags & CODEC_FLAG_H263P_SLICE_STRUCT) ? 1:0;

        /* /Fx */

        /* These are just to be sure */

        avctx->delay=0;

        s->low_delay=1;

        break;

    case CODEC_ID_FLV1:

        s->out_format = FMT_H263;

        s->h263_flv = 2; /* format = 1; 11-bit codes */

        s->unrestricted_mv = 1;

        s->rtp_mode=0; /* don't allow GOB */

        avctx->delay=0;

        s->low_delay=1;

        break;

    case CODEC_ID_RV10:

        s->out_format = FMT_H263;

        avctx->delay=0;

        s->low_delay=1;

        break;

    case CODEC_ID_RV20:

        s->out_format = FMT_H263;

        avctx->delay=0;

        s->low_delay=1;

        s->modified_quant=1;

        s->h263_aic=1;

        s->h263_plus=1;

        s->loop_filter=1;

        s->unrestricted_mv= s->obmc || s->loop_filter || s->umvplus;

        break;

    case CODEC_ID_MPEG4:

        s->out_format = FMT_H263;

        s->h263_pred = 1;

        s->unrestricted_mv = 1;

        s->low_delay= s->max_b_frames ? 0 : 1;

        avctx->delay= s->low_delay ? 0 : (s->max_b_frames + 1);

        break;

    case CODEC_ID_MSMPEG4V1:

        s->out_format = FMT_H263;

        s->h263_msmpeg4 = 1;

        s->h263_pred = 1;

        s->unrestricted_mv = 1;

        s->msmpeg4_version= 1;

        avctx->delay=0;

        s->low_delay=1;

        break;

    case CODEC_ID_MSMPEG4V2:

        s->out_format = FMT_H263;

        s->h263_msmpeg4 = 1;

        s->h263_pred = 1;

        s->unrestricted_mv = 1;

        s->msmpeg4_version= 2;

        avctx->delay=0;

        s->low_delay=1;

        break;

    case CODEC_ID_MSMPEG4V3:

        s->out_format = FMT_H263;

        s->h263_msmpeg4 = 1;

        s->h263_pred = 1;

        s->unrestricted_mv = 1;

        s->msmpeg4_version= 3;

        s->flipflop_rounding=1;

        avctx->delay=0;

        s->low_delay=1;

        break;

    case CODEC_ID_WMV1:

        s->out_format = FMT_H263;

        s->h263_msmpeg4 = 1;

        s->h263_pred = 1;

        s->unrestricted_mv = 1;

        s->msmpeg4_version= 4;

        s->flipflop_rounding=1;

        avctx->delay=0;

        s->low_delay=1;

        break;

    case CODEC_ID_WMV2:

        s->out_format = FMT_H263;

        s->h263_msmpeg4 = 1;

        s->h263_pred = 1;

        s->unrestricted_mv = 1;

        s->msmpeg4_version= 5;

        s->flipflop_rounding=1;

        avctx->delay=0;

        s->low_delay=1;

        break;

    default:

        return -1;

    }

    avctx->has_b_frames= !s->low_delay;

    s->encoding = 1;

    s->progressive_frame=

    s->progressive_sequence= !(avctx->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME|CODEC_FLAG_ALT_SCAN));

    /* init */

    if (MPV_common_init(s) < 0)

        return -1;

    if(!s->dct_quantize)

        s->dct_quantize = dct_quantize_c;

    if(!s->denoise_dct)

        s->denoise_dct = denoise_dct_c;

    s->fast_dct_quantize = s->dct_quantize;

    if(avctx->trellis)

        s->dct_quantize = dct_quantize_trellis_c;

    if((CONFIG_H263P_ENCODER || CONFIG_RV20_ENCODER) && s->modified_quant)

        s->chroma_qscale_table= ff_h263_chroma_qscale_table;

    s->quant_precision=5;

    ff_set_cmp(&s->dsp, s->dsp.ildct_cmp, s->avctx->ildct_cmp);

    ff_set_cmp(&s->dsp, s->dsp.frame_skip_cmp, s->avctx->frame_skip_cmp);

    if (CONFIG_H261_ENCODER && s->out_format == FMT_H261)

        ff_h261_encode_init(s);

    if (CONFIG_ANY_H263_ENCODER && s->out_format == FMT_H263)

        h263_encode_init(s);

    if (CONFIG_MSMPEG4_ENCODER && s->msmpeg4_version)

        ff_msmpeg4_encode_init(s);

    if ((CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)

        && s->out_format == FMT_MPEG1)

        ff_mpeg1_encode_init(s);

    /* init q matrix */

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

        int j= s->dsp.idct_permutation[i];

        if(CONFIG_MPEG4_ENCODER && s->codec_id==CODEC_ID_MPEG4 && s->mpeg_quant){

            s->intra_matrix[j] = ff_mpeg4_default_intra_matrix[i];

            s->inter_matrix[j] = ff_mpeg4_default_non_intra_matrix[i];

        }else if(s->out_format == FMT_H263 || s->out_format == FMT_H261){

            s->intra_matrix[j] =

            s->inter_matrix[j] = ff_mpeg1_default_non_intra_matrix[i];

        }else

        { /* mpeg1/2 */

            s->intra_matrix[j] = ff_mpeg1_default_intra_matrix[i];

            s->inter_matrix[j] = ff_mpeg1_default_non_intra_matrix[i];

        }

        if(s->avctx->intra_matrix)

            s->intra_matrix[j] = s->avctx->intra_matrix[i];

        if(s->avctx->inter_matrix)

            s->inter_matrix[j] = s->avctx->inter_matrix[i];

    }

    /* precompute matrix */

    /* for mjpeg, we do include qscale in the matrix */

    if (s->out_format != FMT_MJPEG) {

        ff_convert_matrix(&s->dsp, s->q_intra_matrix, s->q_intra_matrix16,

                       s->intra_matrix, s->intra_quant_bias, avctx->qmin, 31, 1);

        ff_convert_matrix(&s->dsp, s->q_inter_matrix, s->q_inter_matrix16,

                       s->inter_matrix, s->inter_quant_bias, avctx->qmin, 31, 0);

    }

    if(ff_rate_control_init(s) < 0)

        return -1;

    return 0;

}


static void read_sbr_envelope(SpectralBandReplication *sbr, GetBitContext *gb,

                              SBRData *ch_data, int ch)

{

    int bits;

    int i, j, k;

    VLC_TYPE (*t_huff)[2], (*f_huff)[2];

    int t_lav, f_lav;

    const int delta = (ch == 1 && sbr->bs_coupling == 1) + 1;

    const int odd = sbr->n[1] & 1;

    if (sbr->bs_coupling && ch) {

        if (ch_data->bs_amp_res) {

            bits   = 5;

            t_huff = vlc_sbr[T_HUFFMAN_ENV_BAL_3_0DB].table;

            t_lav  = vlc_sbr_lav[T_HUFFMAN_ENV_BAL_3_0DB];

            f_huff = vlc_sbr[F_HUFFMAN_ENV_BAL_3_0DB].table;

            f_lav  = vlc_sbr_lav[F_HUFFMAN_ENV_BAL_3_0DB];

        } else {

            bits   = 6;

            t_huff = vlc_sbr[T_HUFFMAN_ENV_BAL_1_5DB].table;

            t_lav  = vlc_sbr_lav[T_HUFFMAN_ENV_BAL_1_5DB];

            f_huff = vlc_sbr[F_HUFFMAN_ENV_BAL_1_5DB].table;

            f_lav  = vlc_sbr_lav[F_HUFFMAN_ENV_BAL_1_5DB];

        }

    } else {

        if (ch_data->bs_amp_res) {

            bits   = 6;

            t_huff = vlc_sbr[T_HUFFMAN_ENV_3_0DB].table;

            t_lav  = vlc_sbr_lav[T_HUFFMAN_ENV_3_0DB];

            f_huff = vlc_sbr[F_HUFFMAN_ENV_3_0DB].table;

            f_lav  = vlc_sbr_lav[F_HUFFMAN_ENV_3_0DB];

        } else {

            bits   = 7;

            t_huff = vlc_sbr[T_HUFFMAN_ENV_1_5DB].table;

            t_lav  = vlc_sbr_lav[T_HUFFMAN_ENV_1_5DB];

            f_huff = vlc_sbr[F_HUFFMAN_ENV_1_5DB].table;

            f_lav  = vlc_sbr_lav[F_HUFFMAN_ENV_1_5DB];

        }

    }

    for (i = 0; i < ch_data->bs_num_env; i++) {

        if (ch_data->bs_df_env[i]) {

            // bs_freq_res[0] == bs_freq_res[bs_num_env] from prev frame

            if (ch_data->bs_freq_res[i + 1] == ch_data->bs_freq_res[i]) {

                for (j = 0; j < sbr->n[ch_data->bs_freq_res[i + 1]]; j++)

                    ch_data->env_facs_q[i + 1][j] = ch_data->env_facs_q[i][j] + delta * (get_vlc2(gb, t_huff, 9, 3) - t_lav);

            } else if (ch_data->bs_freq_res[i + 1]) {

                for (j = 0; j < sbr->n[ch_data->bs_freq_res[i + 1]]; j++) {

                    k = (j + odd) >> 1; // find k such that f_tablelow[k] <= f_tablehigh[j] < f_tablelow[k + 1]

                    ch_data->env_facs_q[i + 1][j] = ch_data->env_facs_q[i][k] + delta * (get_vlc2(gb, t_huff, 9, 3) - t_lav);

                }

            } else {

                for (j = 0; j < sbr->n[ch_data->bs_freq_res[i + 1]]; j++) {

                    k = j ? 2*j - odd : 0; // find k such that f_tablehigh[k] == f_tablelow[j]

                    ch_data->env_facs_q[i + 1][j] = ch_data->env_facs_q[i][k] + delta * (get_vlc2(gb, t_huff, 9, 3) - t_lav);

                }

            }

        } else {

            ch_data->env_facs_q[i + 1][0] = delta * get_bits(gb, bits); // bs_env_start_value_balance

            for (j = 1; j < sbr->n[ch_data->bs_freq_res[i + 1]]; j++)

                ch_data->env_facs_q[i + 1][j] = ch_data->env_facs_q[i + 1][j - 1] + delta * (get_vlc2(gb, f_huff, 9, 3) - f_lav);

        }

    }

    //assign 0th elements of env_facs_q from last elements

    memcpy(ch_data->env_facs_q[0], ch_data->env_facs_q[ch_data->bs_num_env],

           sizeof(ch_data->env_facs_q[0]));

}


static int pva_read_packet(AVFormatContext *s, AVPacket *pkt) {

    ByteIOContext *pb = s->pb;

    PVAContext *pvactx = s->priv_data;

    int ret, syncword, streamid, reserved, flags, length, pts_flag;

    int64_t pva_pts = AV_NOPTS_VALUE;

recover:

    syncword = get_be16(pb);

    streamid = get_byte(pb);

    get_byte(pb);               /* counter not used */

    reserved = get_byte(pb);

    flags    = get_byte(pb);

    length   = get_be16(pb);

    pts_flag = flags & 0x10;

    if (syncword != PVA_MAGIC) {

        av_log(s, AV_LOG_ERROR, "invalid syncword\n");

        return AVERROR(EIO);

    }

    if (streamid != PVA_VIDEO_PAYLOAD && streamid != PVA_AUDIO_PAYLOAD) {

        av_log(s, AV_LOG_ERROR, "invalid streamid\n");

        return AVERROR(EIO);

    }

    if (reserved != 0x55) {

        av_log(s, AV_LOG_WARNING, "expected reserved byte to be 0x55\n");

    }

    if (length > PVA_MAX_PAYLOAD_LENGTH) {

        av_log(s, AV_LOG_ERROR, "invalid payload length %u\n", length);

        return AVERROR(EIO);

    }

    if (streamid == PVA_VIDEO_PAYLOAD && pts_flag) {

        pva_pts = get_be32(pb);

        length -= 4;

    } else if (streamid == PVA_AUDIO_PAYLOAD) {

        /* PVA Audio Packets either start with a signaled PES packet or

         * are a continuation of the previous PES packet. New PES packets

         * always start at the beginning of a PVA Packet, never somewhere in

         * the middle. */

        if (!pvactx->continue_pes) {

            int pes_signal, pes_header_data_length, pes_packet_length,

                pes_flags;

            unsigned char pes_header_data[256];

            pes_signal             = get_be24(pb);

            get_byte(pb);

            pes_packet_length      = get_be16(pb);

            pes_flags              = get_be16(pb);

            pes_header_data_length = get_byte(pb);

            if (pes_signal != 1) {

                av_log(s, AV_LOG_WARNING, "expected signaled PES packet, "

                                          "trying to recover\n");

                url_fskip(pb, length - 9);

                goto recover;

            }

            get_buffer(pb, pes_header_data, pes_header_data_length);

            length -= 9 + pes_header_data_length;

            pes_packet_length -= 3 + pes_header_data_length;

            pvactx->continue_pes = pes_packet_length;

            if (pes_flags & 0x80 && (pes_header_data[0] & 0xf0) == 0x20)

                pva_pts = ff_parse_pes_pts(pes_header_data);

        }

        pvactx->continue_pes -= length;

        if (pvactx->continue_pes < 0) {

            av_log(s, AV_LOG_WARNING, "audio data corruption\n");

            pvactx->continue_pes = 0;

        }

    }

    if ((ret = av_get_packet(pb, pkt, length)) <= 0)

        return AVERROR(EIO);

    pkt->stream_index = streamid - 1;

    if (pva_pts != AV_NOPTS_VALUE)

        pkt->pts = pva_pts;

    return ret;

}


static int decode_blck(uint8_t *frame, int width, int height,

                       const uint8_t *src, const uint8_t *src_end)

{

    memset(frame, 0, width * height);

    return 0;

}


static CharDriverState *qmp_chardev_open_socket(const char *id,

                                                ChardevBackend *backend,

                                                ChardevReturn *ret,

                                                Error **errp)

{

    CharDriverState *chr;

    TCPCharDriver *s;

    ChardevSocket *sock = backend->u.socket;

    SocketAddress *addr = sock->addr;

    bool do_nodelay     = sock->has_nodelay ? sock->nodelay : false;

    bool is_listen      = sock->has_server  ? sock->server  : true;

    bool is_telnet      = sock->has_telnet  ? sock->telnet  : false;

    bool is_waitconnect = sock->has_wait    ? sock->wait    : false;

    int64_t reconnect   = sock->has_reconnect ? sock->reconnect : 0;

    ChardevCommon *common = qapi_ChardevSocket_base(backend->u.socket);

    chr = qemu_chr_alloc(common, errp);

    if (!chr) {

        return NULL;

    }

    s = g_new0(TCPCharDriver, 1);

    s->is_unix = addr->type == SOCKET_ADDRESS_KIND_UNIX;

    s->is_listen = is_listen;

    s->is_telnet = is_telnet;

    s->do_nodelay = do_nodelay;

    qapi_copy_SocketAddress(&s->addr, sock->addr);

    chr->opaque = s;

    chr->chr_write = tcp_chr_write;

    chr->chr_sync_read = tcp_chr_sync_read;

    chr->chr_close = tcp_chr_close;

    chr->get_msgfds = tcp_get_msgfds;

    chr->set_msgfds = tcp_set_msgfds;

    chr->chr_add_client = tcp_chr_add_client;

    chr->chr_add_watch = tcp_chr_add_watch;

    chr->chr_update_read_handler = tcp_chr_update_read_handler;

    /* be isn't opened until we get a connection */

    chr->explicit_be_open = true;

    chr->filename = SocketAddress_to_str("disconnected:",

                                         addr, is_listen, is_telnet);

    if (is_listen) {

        if (is_telnet) {

            s->do_telnetopt = 1;

        }

    } else if (reconnect > 0) {

        s->reconnect_time = reconnect;

    }

    if (s->reconnect_time) {

        socket_try_connect(chr);

    } else if (!qemu_chr_open_socket_fd(chr, errp)) {

        g_free(s);

        qemu_chr_free_common(chr);

        return NULL;

    }

    if (is_listen && is_waitconnect) {

        fprintf(stderr, "QEMU waiting for connection on: %s\n",

                chr->filename);

        tcp_chr_accept(QIO_CHANNEL(s->listen_ioc), G_IO_IN, chr);

        qio_channel_set_blocking(QIO_CHANNEL(s->listen_ioc), false, NULL);

    }

    return chr;

}


static void pci_vpb_class_init(ObjectClass *klass, void *data)

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    dc->realize = pci_vpb_realize;

    dc->reset = pci_vpb_reset;

    dc->vmsd = &pci_vpb_vmstate;

    dc->props = pci_vpb_properties;

}


static void gt64120_pci_mapping(GT64120State *s)

{

    /* Update IO mapping */

    if ((s->regs[GT_PCI0IOLD] & 0x7f) <= s->regs[GT_PCI0IOHD])

    {

      /* Unmap old IO address */

      if (s->PCI0IO_length)

      {

          memory_region_del_subregion(get_system_memory(), &s->PCI0IO_mem);

          memory_region_destroy(&s->PCI0IO_mem);

      }

      /* Map new IO address */

      s->PCI0IO_start = s->regs[GT_PCI0IOLD] << 21;

      s->PCI0IO_length = ((s->regs[GT_PCI0IOHD] + 1) - (s->regs[GT_PCI0IOLD] & 0x7f)) << 21;

      isa_mem_base = s->PCI0IO_start;

      isa_mmio_init(s->PCI0IO_start, s->PCI0IO_length);

    }

}


static void *qemu_dummy_cpu_thread_fn(void *arg)

{

#ifdef _WIN32

    fprintf(stderr, "qtest is not supported under Windows\n");

    exit(1);

#else

    CPUState *cpu = arg;

    sigset_t waitset;

    int r;

    rcu_register_thread();

    qemu_mutex_lock_iothread();

    qemu_thread_get_self(cpu->thread);

    cpu->thread_id = qemu_get_thread_id();

    cpu->can_do_io = 1;

    sigemptyset(&waitset);

    sigaddset(&waitset, SIG_IPI);

    /* signal CPU creation */

    cpu->created = true;

    qemu_cond_signal(&qemu_cpu_cond);

    current_cpu = cpu;

    while (1) {

        current_cpu = NULL;

        qemu_mutex_unlock_iothread();

        do {

            int sig;

            r = sigwait(&waitset, &sig);

        } while (r == -1 && (errno == EAGAIN || errno == EINTR));

        if (r == -1) {

            perror("sigwait");

            exit(1);

        }

        qemu_mutex_lock_iothread();

        current_cpu = cpu;

        qemu_wait_io_event_common(cpu);

    }

    return NULL;

#endif

}


void target_disas(FILE *out, CPUState *cpu, target_ulong code,

                  target_ulong size, int flags)

{

    CPUClass *cc = CPU_GET_CLASS(cpu);

    target_ulong pc;

    int count;

    CPUDebug s;

    INIT_DISASSEMBLE_INFO(s.info, out, fprintf);

    s.cpu = cpu;

    s.info.read_memory_func = target_read_memory;

    s.info.read_memory_inner_func = NULL;

    s.info.buffer_vma = code;

    s.info.buffer_length = size;

    s.info.print_address_func = generic_print_address;

#ifdef TARGET_WORDS_BIGENDIAN

    s.info.endian = BFD_ENDIAN_BIG;

#else

    s.info.endian = BFD_ENDIAN_LITTLE;

#endif

    if (cc->disas_set_info) {

        cc->disas_set_info(cpu, &s.info);

    }

#if defined(TARGET_I386)

    if (flags == 2) {

        s.info.mach = bfd_mach_x86_64;

    } else if (flags == 1) {

        s.info.mach = bfd_mach_i386_i8086;

    } else {

        s.info.mach = bfd_mach_i386_i386;

    }

    s.info.print_insn = print_insn_i386;

#elif defined(TARGET_PPC)

    if ((flags >> 16) & 1) {

        s.info.endian = BFD_ENDIAN_LITTLE;

    }

    if (flags & 0xFFFF) {

        /* If we have a precise definition of the instruction set, use it. */

        s.info.mach = flags & 0xFFFF;

    } else {

#ifdef TARGET_PPC64

        s.info.mach = bfd_mach_ppc64;

#else

        s.info.mach = bfd_mach_ppc;

#endif

    }

    s.info.disassembler_options = (char *)"any";

    s.info.print_insn = print_insn_ppc;

#endif

    if (s.info.print_insn == NULL) {

        s.info.print_insn = print_insn_od_target;

    }

    for (pc = code; size > 0; pc += count, size -= count) {

	fprintf(out, "0x" TARGET_FMT_lx ":  ", pc);

	count = s.info.print_insn(pc, &s.info);

#if 0

        {

            int i;

            uint8_t b;

            fprintf(out, " {");

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

                target_read_memory(pc + i, &b, 1, &s.info);

                fprintf(out, " %02x", b);

            }

            fprintf(out, " }");

        }

#endif

	fprintf(out, "\n");

	if (count < 0)

	    break;

        if (size < count) {

            fprintf(out,

                    "Disassembler disagrees with translator over instruction "

                    "decoding\n"

                    "Please report this to qemu-devel@nongnu.org\n");

            break;

        }

    }

}


static inline int decode_bytes(const uint8_t *inbuffer, uint8_t *out, int bytes)

{

    static const uint32_t tab[4] = {

        AV_BE2NE32C(0x37c511f2), AV_BE2NE32C(0xf237c511),

        AV_BE2NE32C(0x11f237c5), AV_BE2NE32C(0xc511f237),

    };

    int i, off;

    uint32_t c;

    const uint32_t *buf;

    uint32_t *obuf = (uint32_t *) out;

    /* FIXME: 64 bit platforms would be able to do 64 bits at a time.

     * I'm too lazy though, should be something like

     * for (i = 0; i < bitamount / 64; i++)

     *     (int64_t) out[i] = 0x37c511f237c511f2 ^ av_be2ne64(int64_t) in[i]);

     * Buffer alignment needs to be checked. */

    off = (intptr_t) inbuffer & 3;

    buf = (const uint32_t *) (inbuffer - off);

    c = tab[off];

    bytes += 3 + off;

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

        obuf[i] = c ^ buf[i];

    return off;

}


static void coroutine_fn v9fs_fix_fid_paths(V9fsPDU *pdu, V9fsPath *olddir,

                                            V9fsString *old_name,

                                            V9fsPath *newdir,

                                            V9fsString *new_name)

{

    V9fsFidState *tfidp;

    V9fsPath oldpath, newpath;

    V9fsState *s = pdu->s;

    v9fs_path_init(&oldpath);

    v9fs_path_init(&newpath);

    v9fs_co_name_to_path(pdu, olddir, old_name->data, &oldpath);

    v9fs_co_name_to_path(pdu, newdir, new_name->data, &newpath);

    /*

     * Fixup fid's pointing to the old name to

     * start pointing to the new name

     */

    for (tfidp = s->fid_list; tfidp; tfidp = tfidp->next) {

        if (v9fs_path_is_ancestor(&oldpath, &tfidp->path)) {

            /* replace the name */

            v9fs_fix_path(&tfidp->path, &newpath, strlen(oldpath.data));

        }

    }

    v9fs_path_free(&oldpath);

    v9fs_path_free(&newpath);

}


static inline void rv40_weak_loop_filter(uint8_t *src, const int step,

                                         const int filter_p1, const int filter_q1,

                                         const int alpha, const int beta,

                                         const int lim_p0q0,

                                         const int lim_q1, const int lim_p1,

                                         const int diff_p1p0, const int diff_q1q0,

                                         const int diff_p1p2, const int diff_q1q2)

{

    uint8_t *cm = ff_cropTbl + MAX_NEG_CROP;

    int t, u, diff;

    t = src[0*step] - src[-1*step];

    if(!t)

        return;

    u = (alpha * FFABS(t)) >> 7;

    if(u > 3 - (filter_p1 && filter_q1))

        return;

    t <<= 2;

    if(filter_p1 && filter_q1)

        t += src[-2*step] - src[1*step];

    diff = CLIP_SYMM((t + 4) >> 3, lim_p0q0);

    src[-1*step] = cm[src[-1*step] + diff];

    src[ 0*step] = cm[src[ 0*step] - diff];

    if(FFABS(diff_p1p2) <= beta && filter_p1){

        t = (diff_p1p0 + diff_p1p2 - diff) >> 1;

        src[-2*step] = cm[src[-2*step] - CLIP_SYMM(t, lim_p1)];

    }

    if(FFABS(diff_q1q2) <= beta && filter_q1){

        t = (diff_q1q0 + diff_q1q2 + diff) >> 1;

        src[ 1*step] = cm[src[ 1*step] - CLIP_SYMM(t, lim_q1)];

    }

}


static int fileTest(uint8_t *ref[4], int refStride[4], int w, int h, FILE *fp,

                    enum AVPixelFormat srcFormat_in,

                    enum AVPixelFormat dstFormat_in)

{

    char buf[256];

    while (fgets(buf, sizeof(buf), fp)) {

        struct Results r;

        enum AVPixelFormat srcFormat;

        char srcStr[12];

        int srcW, srcH;

        enum AVPixelFormat dstFormat;

        char dstStr[12];

        int dstW, dstH;

        int flags;

        int ret;

        ret = sscanf(buf,

                     " %12s %dx%d -> %12s %dx%d flags=%d CRC=%x"

                     " SSD=%"PRId64 ", %"PRId64 ", %"PRId64 ", %"PRId64 "\n",

                     srcStr, &srcW, &srcH, dstStr, &dstW, &dstH,

                     &flags, &r.crc, &r.ssdY, &r.ssdU, &r.ssdV, &r.ssdA);

        if (ret != 12) {

            srcStr[0] = dstStr[0] = 0;

            ret       = sscanf(buf, "%12s -> %12s\n", srcStr, dstStr);

        }

        srcFormat = av_get_pix_fmt(srcStr);

        dstFormat = av_get_pix_fmt(dstStr);

        if (srcFormat == AV_PIX_FMT_NONE || dstFormat == AV_PIX_FMT_NONE) {

            fprintf(stderr, "malformed input file\n");

            return -1;

        }

        if ((srcFormat_in != AV_PIX_FMT_NONE && srcFormat_in != srcFormat) ||

            (dstFormat_in != AV_PIX_FMT_NONE && dstFormat_in != dstFormat))

            continue;

        if (ret != 12) {

            printf("%s", buf);

            continue;

        }

        doTest(ref, refStride, w, h,

               srcFormat, dstFormat,

               srcW, srcH, dstW, dstH, flags,

               &r);

    }

    return 0;

}


static int dirac_decode_frame_internal(DiracContext *s)

{

    DWTContext d;

    int y, i, comp, dsty;

    if (s->low_delay) {

        /* [DIRAC_STD] 13.5.1 low_delay_transform_data() */

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

            Plane *p = &s->plane[comp];

            memset(p->idwt_buf, 0, p->idwt_stride * p->idwt_height * sizeof(IDWTELEM));

        }

        if (!s->zero_res)

            decode_lowdelay(s);

    }

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

        Plane *p       = &s->plane[comp];

        uint8_t *frame = s->current_picture->avframe->data[comp];

        /* FIXME: small resolutions */

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

            s->edge_emu_buffer[i] = s->edge_emu_buffer_base + i*FFALIGN(p->width, 16);

        if (!s->zero_res && !s->low_delay)

        {

            memset(p->idwt_buf, 0, p->idwt_stride * p->idwt_height * sizeof(IDWTELEM));

            decode_component(s, comp); /* [DIRAC_STD] 13.4.1 core_transform_data() */

        }

        if (ff_spatial_idwt_init2(&d, p->idwt_buf, p->idwt_width, p->idwt_height, p->idwt_stride,

                                  s->wavelet_idx+2, s->wavelet_depth, p->idwt_tmp))

            return -1;

        if (!s->num_refs) { /* intra */

            for (y = 0; y < p->height; y += 16) {

                ff_spatial_idwt_slice2(&d, y+16); /* decode */

                s->diracdsp.put_signed_rect_clamped(frame + y*p->stride, p->stride,

                                                    p->idwt_buf + y*p->idwt_stride, p->idwt_stride, p->width, 16);

            }

        } else { /* inter */

            int rowheight = p->ybsep*p->stride;

            select_dsp_funcs(s, p->width, p->height, p->xblen, p->yblen);

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

                interpolate_refplane(s, s->ref_pics[i], comp, p->width, p->height);

            memset(s->mctmp, 0, 4*p->yoffset*p->stride);

            dsty = -p->yoffset;

            for (y = 0; y < s->blheight; y++) {

                int h     = 0,

                    start = FFMAX(dsty, 0);

                uint16_t *mctmp    = s->mctmp + y*rowheight;

                DiracBlock *blocks = s->blmotion + y*s->blwidth;

                init_obmc_weights(s, p, y);

                if (y == s->blheight-1 || start+p->ybsep > p->height)

                    h = p->height - start;

                else

                    h = p->ybsep - (start - dsty);

                if (h < 0)

                    break;

                memset(mctmp+2*p->yoffset*p->stride, 0, 2*rowheight);

                mc_row(s, blocks, mctmp, comp, dsty);

                mctmp += (start - dsty)*p->stride + p->xoffset;

                ff_spatial_idwt_slice2(&d, start + h); /* decode */

                s->diracdsp.add_rect_clamped(frame + start*p->stride, mctmp, p->stride,

                                             p->idwt_buf + start*p->idwt_stride, p->idwt_stride, p->width, h);

                dsty += p->ybsep;

            }

        }

    }

    return 0;

}


void updateMMXDitherTables(SwsContext *c, int dstY, int lumBufIndex, int chrBufIndex,

                           int lastInLumBuf, int lastInChrBuf)

{

    const int dstH= c->dstH;

    const int flags= c->flags;

    int16_t **lumPixBuf= c->lumPixBuf;

    int16_t **chrUPixBuf= c->chrUPixBuf;

    int16_t **alpPixBuf= c->alpPixBuf;

    const int vLumBufSize= c->vLumBufSize;

    const int vChrBufSize= c->vChrBufSize;

    int32_t *vLumFilterPos= c->vLumFilterPos;

    int32_t *vChrFilterPos= c->vChrFilterPos;

    int16_t *vLumFilter= c->vLumFilter;

    int16_t *vChrFilter= c->vChrFilter;

    int32_t *lumMmxFilter= c->lumMmxFilter;

    int32_t *chrMmxFilter= c->chrMmxFilter;

    int32_t av_unused *alpMmxFilter= c->alpMmxFilter;

    const int vLumFilterSize= c->vLumFilterSize;

    const int vChrFilterSize= c->vChrFilterSize;

    const int chrDstY= dstY>>c->chrDstVSubSample;

    const int firstLumSrcY= vLumFilterPos[dstY]; //First line needed as input

    const int firstChrSrcY= vChrFilterPos[chrDstY]; //First line needed as input

    c->blueDither= ff_dither8[dstY&1];

    if (c->dstFormat == PIX_FMT_RGB555 || c->dstFormat == PIX_FMT_BGR555)

        c->greenDither= ff_dither8[dstY&1];

    else

        c->greenDither= ff_dither4[dstY&1];

    c->redDither= ff_dither8[(dstY+1)&1];

    if (dstY < dstH - 2) {

        const int16_t **lumSrcPtr= (const int16_t **)(void*) lumPixBuf + lumBufIndex + firstLumSrcY - lastInLumBuf + vLumBufSize;

        const int16_t **chrUSrcPtr= (const int16_t **)(void*) chrUPixBuf + chrBufIndex + firstChrSrcY - lastInChrBuf + vChrBufSize;

        const int16_t **alpSrcPtr= (CONFIG_SWSCALE_ALPHA && alpPixBuf) ? (const int16_t **)(void*) alpPixBuf + lumBufIndex + firstLumSrcY - lastInLumBuf + vLumBufSize : NULL;

        int i;

        if (firstLumSrcY < 0 || firstLumSrcY + vLumFilterSize > c->srcH) {

            const int16_t **tmpY = (const int16_t **) lumPixBuf + 2 * vLumBufSize;

            int neg = -firstLumSrcY, i, end = FFMIN(c->srcH - firstLumSrcY, vLumFilterSize);

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

                tmpY[i] = lumSrcPtr[neg];

            for (     ; i < end;            i++)

                tmpY[i] = lumSrcPtr[i];

            for (     ; i < vLumFilterSize; i++)

                tmpY[i] = tmpY[i-1];

            lumSrcPtr = tmpY;

            if (alpSrcPtr) {

                const int16_t **tmpA = (const int16_t **) alpPixBuf + 2 * vLumBufSize;

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

                    tmpA[i] = alpSrcPtr[neg];

                for (     ; i < end;            i++)

                    tmpA[i] = alpSrcPtr[i];

                for (     ; i < vLumFilterSize; i++)

                    tmpA[i] = tmpA[i - 1];

                alpSrcPtr = tmpA;

            }

        }

        if (firstChrSrcY < 0 || firstChrSrcY + vChrFilterSize > c->chrSrcH) {

            const int16_t **tmpU = (const int16_t **) chrUPixBuf + 2 * vChrBufSize;

            int neg = -firstChrSrcY, i, end = FFMIN(c->chrSrcH - firstChrSrcY, vChrFilterSize);

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

                tmpU[i] = chrUSrcPtr[neg];

            }

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

                tmpU[i] = chrUSrcPtr[i];

            }

            for (     ; i < vChrFilterSize; i++) {

                tmpU[i] = tmpU[i - 1];

            }

            chrUSrcPtr = tmpU;

        }

        if (flags & SWS_ACCURATE_RND) {

            int s= APCK_SIZE / 8;

            for (i=0; i<vLumFilterSize; i+=2) {

                *(const void**)&lumMmxFilter[s*i              ]= lumSrcPtr[i  ];

                *(const void**)&lumMmxFilter[s*i+APCK_PTR2/4  ]= lumSrcPtr[i+(vLumFilterSize>1)];

                lumMmxFilter[s*i+APCK_COEF/4  ]=

                lumMmxFilter[s*i+APCK_COEF/4+1]= vLumFilter[dstY*vLumFilterSize + i    ]

                + (vLumFilterSize>1 ? vLumFilter[dstY*vLumFilterSize + i + 1]<<16 : 0);

                if (CONFIG_SWSCALE_ALPHA && alpPixBuf) {

                    *(const void**)&alpMmxFilter[s*i              ]= alpSrcPtr[i  ];

                    *(const void**)&alpMmxFilter[s*i+APCK_PTR2/4  ]= alpSrcPtr[i+(vLumFilterSize>1)];

                    alpMmxFilter[s*i+APCK_COEF/4  ]=

                    alpMmxFilter[s*i+APCK_COEF/4+1]= lumMmxFilter[s*i+APCK_COEF/4  ];

                }

            }

            for (i=0; i<vChrFilterSize; i+=2) {

                *(const void**)&chrMmxFilter[s*i              ]= chrUSrcPtr[i  ];

                *(const void**)&chrMmxFilter[s*i+APCK_PTR2/4  ]= chrUSrcPtr[i+(vChrFilterSize>1)];

                chrMmxFilter[s*i+APCK_COEF/4  ]=

                chrMmxFilter[s*i+APCK_COEF/4+1]= vChrFilter[chrDstY*vChrFilterSize + i    ]

                + (vChrFilterSize>1 ? vChrFilter[chrDstY*vChrFilterSize + i + 1]<<16 : 0);

            }

        } else {

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

                *(const void**)&lumMmxFilter[4*i+0]= lumSrcPtr[i];

                lumMmxFilter[4*i+2]=

                lumMmxFilter[4*i+3]=

                ((uint16_t)vLumFilter[dstY*vLumFilterSize + i])*0x10001;

                if (CONFIG_SWSCALE_ALPHA && alpPixBuf) {

                    *(const void**)&alpMmxFilter[4*i+0]= alpSrcPtr[i];

                    alpMmxFilter[4*i+2]=

                    alpMmxFilter[4*i+3]= lumMmxFilter[4*i+2];

                }

            }

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

                *(const void**)&chrMmxFilter[4*i+0]= chrUSrcPtr[i];

                chrMmxFilter[4*i+2]=

                chrMmxFilter[4*i+3]=

                ((uint16_t)vChrFilter[chrDstY*vChrFilterSize + i])*0x10001;

            }

        }

    }

}


static inline void gen_outs(DisasContext *s, TCGMemOp ot)

{

    if (s->base.tb->cflags & CF_USE_ICOUNT) {

        gen_io_start();

    }

    gen_string_movl_A0_ESI(s);

    gen_op_ld_v(s, ot, cpu_T0, cpu_A0);

    tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_regs[R_EDX]);

    tcg_gen_andi_i32(cpu_tmp2_i32, cpu_tmp2_i32, 0xffff);

    tcg_gen_trunc_tl_i32(cpu_tmp3_i32, cpu_T0);

    gen_helper_out_func(ot, cpu_tmp2_i32, cpu_tmp3_i32);

    gen_op_movl_T0_Dshift(ot);

    gen_op_add_reg_T0(s->aflag, R_ESI);

    gen_bpt_io(s, cpu_tmp2_i32, ot);

    if (s->base.tb->cflags & CF_USE_ICOUNT) {

        gen_io_end();

    }

}


static av_cold int alloc_buffers(AVCodecContext *avctx, AACEncContext *s)

{

    FF_ALLOCZ_OR_GOTO(avctx, s->buffer.samples, 3 * 1024 * s->channels * sizeof(s->buffer.samples[0]), alloc_fail);

    FF_ALLOCZ_OR_GOTO(avctx, s->cpe, sizeof(ChannelElement) * s->chan_map[0], alloc_fail);

    FF_ALLOCZ_OR_GOTO(avctx, avctx->extradata, 5 + FF_INPUT_BUFFER_PADDING_SIZE, alloc_fail);

    for(int ch = 0; ch < s->channels; ch++)

        s->planar_samples[ch] = s->buffer.samples + 3 * 1024 * ch;

    return 0;

alloc_fail:

    return AVERROR(ENOMEM);

}


void ff_aac_update_ltp(AACEncContext *s, SingleChannelElement *sce)

{

    int i, j, lag;

    float corr, s0, s1, max_corr = 0.0f;

    float *samples = &s->planar_samples[s->cur_channel][1024];

    float *pred_signal = &sce->ltp_state[0];

    int samples_num = 2048;

    if (s->profile != FF_PROFILE_AAC_LTP)

        return;

    /* Calculate lag */

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

        s0 = s1 = 0.0f;

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

            if (j + 1024 < i)

                continue;

            s0 += samples[j]*pred_signal[j-i+1024];

            s1 += pred_signal[j-i+1024]*pred_signal[j-i+1024];

        }

        corr = s1 > 0.0f ? s0/sqrt(s1) : 0.0f;

        if (corr > max_corr) {

            max_corr = corr;

            lag = i;

        }

    }

    lag = av_clip_uintp2(lag, 11); /* 11 bits => 2^11 = 0->2047 */

    if (!lag) {

        sce->ics.ltp.lag = lag;

        return;

    }

    s0 = s1 = 0.0f;

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

        s0 += samples[i];

        s1 += pred_signal[i-lag+1024];

    }

    sce->ics.ltp.coef_idx = quant_array_idx(s0/s1, ltp_coef, 8);

    sce->ics.ltp.coef     = ltp_coef[sce->ics.ltp.coef_idx];

    /* Predict the new samples */

    if (lag < 1024)

        samples_num = lag + 1024;

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

        pred_signal[i+1024] = sce->ics.ltp.coef*pred_signal[i-lag+1024];

    memset(&pred_signal[samples_num], 0, (2048 - samples_num)*sizeof(float));

    sce->ics.ltp.lag = lag;

}


void ff_biweight_h264_pixels4_8_msa(uint8_t *dst, uint8_t *src,

                                    int stride, int height,

                                    int log2_denom, int weight_dst,

                                    int weight_src, int offset)

{

    avc_biwgt_4width_msa(src, stride,

                         dst, stride,

                         height, log2_denom,

                         weight_src, weight_dst, offset);

}


void clear_blocks_dcbz128_ppc(DCTELEM *blocks)

{

POWERPC_TBL_DECLARE(powerpc_clear_blocks_dcbz128, 1);

    register int misal = ((unsigned long)blocks & 0x0000007f);

    register int i = 0;

POWERPC_TBL_START_COUNT(powerpc_clear_blocks_dcbz128, 1);

#if 1

 if (misal) {

   // we could probably also optimize this case,

   // but there's not much point as the machines

   // aren't available yet (2003-06-26)

      memset(blocks, 0, sizeof(DCTELEM)*6*64);

    }

    else

      for ( ; i < sizeof(DCTELEM)*6*64 ; i += 128) {

	asm volatile("dcbzl %0,%1" : : "b" (blocks), "r" (i) : "memory");

      }

#else

    memset(blocks, 0, sizeof(DCTELEM)*6*64);

#endif

POWERPC_TBL_STOP_COUNT(powerpc_clear_blocks_dcbz128, 1);

}


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

{

    PowerPCCPUClass *pcc = POWERPC_CPU_CLASS(oc);

    CPUClass *cc = CPU_CLASS(oc);

    DeviceClass *dc = DEVICE_CLASS(oc);

    pcc->parent_realize = dc->realize;

    dc->realize = ppc_cpu_realizefn;

    dc->unrealize = ppc_cpu_unrealizefn;

    pcc->parent_reset = cc->reset;

    cc->reset = ppc_cpu_reset;

    cc->class_by_name = ppc_cpu_class_by_name;

    cc->do_interrupt = ppc_cpu_do_interrupt;

    cc->dump_state = ppc_cpu_dump_state;

    cc->dump_statistics = ppc_cpu_dump_statistics;

    cc->set_pc = ppc_cpu_set_pc;

    cc->gdb_read_register = ppc_cpu_gdb_read_register;

    cc->gdb_write_register = ppc_cpu_gdb_write_register;

#ifndef CONFIG_USER_ONLY

    cc->get_phys_page_debug = ppc_cpu_get_phys_page_debug;

    cc->vmsd = &vmstate_ppc_cpu;

    cc->gdb_num_core_regs = 71;

    cc->gdb_core_xml_file = "power64-core.xml";

#else

    cc->gdb_core_xml_file = "power-core.xml";

}


static CharDriverState *qmp_chardev_open_socket(ChardevSocket *sock,

                                                Error **errp)

{

    SocketAddress *addr = sock->addr;

    bool do_nodelay     = sock->has_nodelay ? sock->nodelay : false;

    bool is_listen      = sock->has_server  ? sock->server  : true;

    bool is_telnet      = sock->has_telnet  ? sock->telnet  : false;

    bool is_waitconnect = sock->has_wait    ? sock->wait    : false;

    int fd;

    if (is_listen) {

        fd = socket_listen(addr, errp);

    } else {

        fd = socket_connect(addr, errp, NULL, NULL);

    }

    if (error_is_set(errp)) {

        return NULL;

    }

    return qemu_chr_open_socket_fd(fd, do_nodelay, is_listen,

                                   is_telnet, is_waitconnect, errp);

}