int avfilter_graph_parse(AVFilterGraph *graph, const char *filters,

                         AVFilterInOut **open_inputs_ptr, AVFilterInOut **open_outputs_ptr,

                         void *log_ctx)

{

    int index = 0, ret = 0;

    char chr = 0;

    AVFilterInOut *curr_inputs = NULL;

    AVFilterInOut *open_inputs  = open_inputs_ptr  ? *open_inputs_ptr  : NULL;

    AVFilterInOut *open_outputs = open_outputs_ptr ? *open_outputs_ptr : NULL;

    do {

        AVFilterContext *filter;

        const char *filterchain = filters;

        filters += strspn(filters, WHITESPACES);

        if ((ret = parse_inputs(&filters, &curr_inputs, &open_outputs, log_ctx)) < 0)

            goto end;

        if ((ret = parse_filter(&filter, &filters, graph, index, log_ctx)) < 0)

            goto end;

        if (filter->input_count == 1 && !curr_inputs && !index) {

            /* First input pad, assume it is "[in]" if not specified */

            const char *tmp = "[in]";

            if ((ret = parse_inputs(&tmp, &curr_inputs, &open_outputs, log_ctx)) < 0)

                goto end;

        }

        if ((ret = link_filter_inouts(filter, &curr_inputs, &open_inputs, log_ctx)) < 0)

            goto end;

        if ((ret = parse_outputs(&filters, &curr_inputs, &open_inputs, &open_outputs,

                                 log_ctx)) < 0)

            goto end;

        filters += strspn(filters, WHITESPACES);

        chr = *filters++;

        if (chr == ';' && curr_inputs) {

            av_log(log_ctx, AV_LOG_ERROR,

                   "Invalid filterchain containing an unlabelled output pad: \"%s\"\n",

                   filterchain);

            ret = AVERROR(EINVAL);

            goto end;

        }

        index++;

    } while (chr == ',' || chr == ';');

    if (chr) {

        av_log(log_ctx, AV_LOG_ERROR,

               "Unable to parse graph description substring: \"%s\"\n",

               filters - 1);

        ret = AVERROR(EINVAL);

        goto end;

    }

    if (open_inputs && !strcmp(open_inputs->name, "out") && curr_inputs) {

        /* Last output pad, assume it is "[out]" if not specified */

        const char *tmp = "[out]";

        if ((ret = parse_outputs(&tmp, &curr_inputs, &open_inputs, &open_outputs,

                                 log_ctx)) < 0)

            goto end;

    }

end:

    /* clear open_in/outputs only if not passed as parameters */

    if (open_inputs_ptr) *open_inputs_ptr = open_inputs;

    else avfilter_inout_free(&open_inputs);

    if (open_outputs_ptr) *open_outputs_ptr = open_outputs;

    else avfilter_inout_free(&open_outputs);

    avfilter_inout_free(&curr_inputs);

    if (ret < 0) {

        for (; graph->filter_count > 0; graph->filter_count--)

            avfilter_free(graph->filters[graph->filter_count - 1]);

        av_freep(&graph->filters);

    }

    return ret;

}


static inline int vorbis_residue_decode(vorbis_context *vc, vorbis_residue *vr,

                                        unsigned ch,

                                        uint8_t *do_not_decode,

                                        float *vec, unsigned vlen)

{

    if (vr->type == 2)

        return vorbis_residue_decode_internal(vc, vr, ch, do_not_decode, vec, vlen, 2);

    else if (vr->type == 1)

        return vorbis_residue_decode_internal(vc, vr, ch, do_not_decode, vec, vlen, 1);

    else if (vr->type == 0)

        return vorbis_residue_decode_internal(vc, vr, ch, do_not_decode, vec, vlen, 0);

    else {

        av_log(vc->avccontext, AV_LOG_ERROR, " Invalid residue type while residue decode?! \n");

        return AVERROR_INVALIDDATA;

    }

}


static void common_end(FFV1Context *s){

    int i;

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

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

        av_freep(&p->state);

    }

}


static av_cold int ape_decode_close(AVCodecContext * avctx)

{

    APEContext *s = avctx->priv_data;

    int i;

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

        av_freep(&s->filterbuf[i]);

    av_freep(&s->data);

    return 0;

}


static int qemu_chr_open_file_out(QemuOpts *opts, CharDriverState **_chr)

{

    int fd_out;

    TFR(fd_out = qemu_open(qemu_opt_get(opts, "path"),

                      O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));

    if (fd_out < 0) {

        return -errno;

    }

    *_chr = qemu_chr_open_fd(-1, fd_out);

    return 0;

}


static int con_initialise(struct XenDevice *xendev)

{

    struct XenConsole *con = container_of(xendev, struct XenConsole, xendev);

    int limit;

    if (xenstore_read_int(con->console, "ring-ref", &con->ring_ref) == -1)

	return -1;

    if (xenstore_read_int(con->console, "port", &con->xendev.remote_port) == -1)

	return -1;

    if (xenstore_read_int(con->console, "limit", &limit) == 0)

	con->buffer.max_capacity = limit;

    if (!xendev->dev) {

        con->sring = xc_map_foreign_range(xen_xc, con->xendev.dom,

                                          XC_PAGE_SIZE,

                                          PROT_READ|PROT_WRITE,

                                          con->ring_ref);

    } else {

        con->sring = xengnttab_map_grant_ref(xendev->gnttabdev, con->xendev.dom,

                                             con->ring_ref,

                                             PROT_READ|PROT_WRITE);

    }

    if (!con->sring)

	return -1;

    xen_be_bind_evtchn(&con->xendev);

    if (con->chr) {

        if (qemu_chr_fe_claim(con->chr) == 0) {

            qemu_chr_add_handlers(con->chr, xencons_can_receive,

                                  xencons_receive, NULL, con);

        } else {

            xen_be_printf(xendev, 0,

                          "xen_console_init error chardev %s already used\n",

                          con->chr->label);

            con->chr = NULL;

        }

    }

    xen_be_printf(xendev, 1, "ring mfn %d, remote port %d, local port %d, limit %zd\n",

		  con->ring_ref,

		  con->xendev.remote_port,

		  con->xendev.local_port,

		  con->buffer.max_capacity);

    return 0;

}


static void writer_close(WriterContext **wctx)

{

    int i;

    if (!*wctx)

        return;

    if ((*wctx)->writer->uninit)

        (*wctx)->writer->uninit(*wctx);

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

        av_bprint_finalize(&(*wctx)->section_pbuf[i], NULL);

    if ((*wctx)->writer->priv_class)

        av_opt_free((*wctx)->priv);

    av_freep(&((*wctx)->priv));

    av_freep(wctx);

}


static int avi_read_tag(AVFormatContext *s, AVStream *st, uint32_t tag, uint32_t size)

{

    AVIOContext *pb = s->pb;

    char key[5] = {0}, *value;

    size += (size & 1);

    if (size == UINT_MAX)

        return -1;

    value = av_malloc(size+1);

    if (!value)

        return -1;

    avio_read(pb, value, size);

    value[size]=0;

    AV_WL32(key, tag);

    return av_dict_set(st ? &st->metadata : &s->metadata, key, value,

                            AV_DICT_DONT_STRDUP_VAL);

}


static void set_dirty_tracking(void)

{

    BlkMigDevState *bmds;

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

        bmds->dirty_bitmap = bdrv_create_dirty_bitmap(bmds->bs, BLOCK_SIZE);

    }

}


static inline void RENAME(nvXXtoUV)(uint8_t *dst1, uint8_t *dst2,

                                    const uint8_t *src, int width)

{

#if COMPILE_TEMPLATE_MMX

    __asm__ volatile(

        "movq "MANGLE(bm01010101)", %%mm4           \n\t"

        "mov                    %0, %%"REG_a"       \n\t"

        "1:                                         \n\t"

        "movq    (%1, %%"REG_a",2), %%mm0           \n\t"

        "movq   8(%1, %%"REG_a",2), %%mm1           \n\t"

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

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

        "pand                %%mm4, %%mm0           \n\t"

        "pand                %%mm4, %%mm1           \n\t"

        "psrlw                  $8, %%mm2           \n\t"

        "psrlw                  $8, %%mm3           \n\t"

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

        "packuswb            %%mm3, %%mm2           \n\t"

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

        "movq                %%mm2, (%3, %%"REG_a") \n\t"

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

        " js                    1b                  \n\t"

        : : "g" ((x86_reg)-width), "r" (src+width*2), "r" (dst1+width), "r" (dst2+width)

        : "%"REG_a

    );

#else

    int i;

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

        dst1[i] = src[2*i+0];

        dst2[i] = src[2*i+1];

    }

#endif

}


static int frame_copy_props(AVFrame *dst, const AVFrame *src, int force_copy)

{

    int i;

    dst->key_frame              = src->key_frame;

    dst->pict_type              = src->pict_type;

    dst->sample_aspect_ratio    = src->sample_aspect_ratio;

    dst->pts                    = src->pts;

    dst->repeat_pict            = src->repeat_pict;

    dst->interlaced_frame       = src->interlaced_frame;

    dst->top_field_first        = src->top_field_first;

    dst->palette_has_changed    = src->palette_has_changed;

    dst->sample_rate            = src->sample_rate;

    dst->opaque                 = src->opaque;

#if FF_API_PKT_PTS

FF_DISABLE_DEPRECATION_WARNINGS

    dst->pkt_pts                = src->pkt_pts;

FF_ENABLE_DEPRECATION_WARNINGS

#endif

    dst->pkt_dts                = src->pkt_dts;

    dst->pkt_pos                = src->pkt_pos;

    dst->pkt_size               = src->pkt_size;

    dst->pkt_duration           = src->pkt_duration;

    dst->reordered_opaque       = src->reordered_opaque;

    dst->quality                = src->quality;

    dst->best_effort_timestamp  = src->best_effort_timestamp;

    dst->coded_picture_number   = src->coded_picture_number;

    dst->display_picture_number = src->display_picture_number;

    dst->flags                  = src->flags;

    dst->decode_error_flags     = src->decode_error_flags;

    dst->color_primaries        = src->color_primaries;

    dst->color_trc              = src->color_trc;

    dst->colorspace             = src->colorspace;

    dst->color_range            = src->color_range;

    dst->chroma_location        = src->chroma_location;

    av_dict_copy(&dst->metadata, src->metadata, 0);

#if FF_API_ERROR_FRAME

FF_DISABLE_DEPRECATION_WARNINGS

    memcpy(dst->error, src->error, sizeof(dst->error));

FF_ENABLE_DEPRECATION_WARNINGS

#endif

    for (i = 0; i < src->nb_side_data; i++) {

        const AVFrameSideData *sd_src = src->side_data[i];

        AVFrameSideData *sd_dst;

        if (   sd_src->type == AV_FRAME_DATA_PANSCAN

            && (src->width != dst->width || src->height != dst->height))

            continue;

        if (force_copy) {

            sd_dst = av_frame_new_side_data(dst, sd_src->type,

                                            sd_src->size);

            if (!sd_dst) {

                wipe_side_data(dst);

                return AVERROR(ENOMEM);

            memcpy(sd_dst->data, sd_src->data, sd_src->size);

        } else {

            sd_dst = av_frame_new_side_data(dst, sd_src->type, 0);

            if (!sd_dst) {

                wipe_side_data(dst);

                return AVERROR(ENOMEM);

            if (sd_src->buf) {

            sd_dst->buf = av_buffer_ref(sd_src->buf);

            if (!sd_dst->buf) {

                wipe_side_data(dst);

                return AVERROR(ENOMEM);

            sd_dst->data = sd_dst->buf->data;

            sd_dst->size = sd_dst->buf->size;

        av_dict_copy(&sd_dst->metadata, sd_src->metadata, 0);

#if FF_API_FRAME_QP

FF_DISABLE_DEPRECATION_WARNINGS

    dst->qscale_table = NULL;

    dst->qstride      = 0;

    dst->qscale_type  = 0;

    av_buffer_unref(&dst->qp_table_buf);

    if (src->qp_table_buf) {

        dst->qp_table_buf = av_buffer_ref(src->qp_table_buf);

        if (dst->qp_table_buf) {

            dst->qscale_table = dst->qp_table_buf->data;

            dst->qstride      = src->qstride;

            dst->qscale_type  = src->qscale_type;

FF_ENABLE_DEPRECATION_WARNINGS

#endif

    return 0;


static int img_create(int argc, char **argv)

{

    int c, ret = 0;

    uint64_t img_size = -1;

    const char *fmt = "raw";

    const char *base_fmt = NULL;

    const char *filename;

    const char *base_filename = NULL;

    char *options = NULL;

    for(;;) {

        c = getopt(argc, argv, "F:b:f:he6o:");

        if (c == -1) {

            break;

        }

        switch(c) {

        case '?':

        case 'h':

            help();

            break;

        case 'F':

            base_fmt = optarg;

            break;

        case 'b':

            base_filename = optarg;

            break;

        case 'f':

            fmt = optarg;

            break;

        case 'e':

            error_report("option -e is deprecated, please use \'-o "

                  "encryption\' instead!");

            return 1;

        case '6':

            error_report("option -6 is deprecated, please use \'-o "

                  "compat6\' instead!");

            return 1;

        case 'o':

            options = optarg;

            break;

        }

    }

    /* Get the filename */

    if (optind >= argc) {

        help();

    }

    filename = argv[optind++];

    /* Get image size, if specified */

    if (optind < argc) {

        int64_t sval;

        char *end;

        sval = strtosz_suffix(argv[optind++], &end, STRTOSZ_DEFSUFFIX_B);

        if (sval < 0 || *end) {

            error_report("Invalid image size specified! You may use k, M, G or "

                  "T suffixes for ");

            error_report("kilobytes, megabytes, gigabytes and terabytes.");

            ret = -1;

            goto out;

        }

        img_size = (uint64_t)sval;

    }

    if (options && !strcmp(options, "?")) {

        ret = print_block_option_help(filename, fmt);

        goto out;

    }

    ret = bdrv_img_create(filename, fmt, base_filename, base_fmt,

                          options, img_size, BDRV_O_FLAGS);

out:

    if (ret) {

        return 1;

    }

    return 0;

}


static int kvm_sclp_service_call(S390CPU *cpu, struct kvm_run *run,

                                 uint16_t ipbh0)

{

    CPUS390XState *env = &cpu->env;

    uint64_t sccb;

    uint32_t code;

    int r = 0;

    cpu_synchronize_state(CPU(cpu));

    if (env->psw.mask & PSW_MASK_PSTATE) {

        enter_pgmcheck(cpu, PGM_PRIVILEGED);

        return 0;

    }

    sccb = env->regs[ipbh0 & 0xf];

    code = env->regs[(ipbh0 & 0xf0) >> 4];

    r = sclp_service_call(sccb, code);

    if (r < 0) {

        enter_pgmcheck(cpu, -r);

    }

    setcc(cpu, r);

    return 0;

}


static void libschroedinger_flush(AVCodecContext *avctx)

{

    /* Got a seek request. Free the decoded frames queue and then reset

     * the decoder */

    SchroDecoderParams *p_schro_params = avctx->priv_data;

    /* Free data in the output frame queue. */

    ff_schro_queue_free(&p_schro_params->dec_frame_queue,

                        libschroedinger_decode_frame_free);

    ff_schro_queue_init(&p_schro_params->dec_frame_queue);

    schro_decoder_reset(p_schro_params->decoder);

    p_schro_params->eos_pulled = 0;

    p_schro_params->eos_signalled = 0;

}


CFDataRef ff_videotoolbox_hvcc_extradata_create(AVCodecContext *avctx)

{

    HEVCContext *h = avctx->priv_data;

    const HEVCVPS *vps = (const HEVCVPS *)h->ps.vps_list[0]->data;

    const HEVCSPS *sps = (const HEVCSPS *)h->ps.sps_list[0]->data;

    int i, num_pps = 0;

    const HEVCPPS *pps = h->ps.pps;

    PTLCommon ptlc = vps->ptl.general_ptl;

    VUI vui = sps->vui;

    uint8_t parallelismType;

    CFDataRef data = NULL;

    uint8_t *p;

    int vt_extradata_size = 23 + 5 + vps->data_size + 5 + sps->data_size + 3;

    uint8_t *vt_extradata;

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

        if (h->ps.pps_list[i]) {

            const HEVCPPS *pps = (const HEVCPPS *)h->ps.pps_list[i]->data;

            vt_extradata_size += 2 + pps->data_size;

            num_pps++;

        }

    }

    vt_extradata = av_malloc(vt_extradata_size);

    if (!vt_extradata)

        return NULL;

    p = vt_extradata;

    /* unsigned int(8) configurationVersion = 1; */

    AV_W8(p + 0, 1);

    /*

     * unsigned int(2) general_profile_space;

     * unsigned int(1) general_tier_flag;

     * unsigned int(5) general_profile_idc;

     */

    AV_W8(p + 1, ptlc.profile_space << 6 |

                 ptlc.tier_flag     << 5 |

                 ptlc.profile_idc);

    /* unsigned int(32) general_profile_compatibility_flags; */

    memcpy(p + 2, ptlc.profile_compatibility_flag, 4);

    /* unsigned int(48) general_constraint_indicator_flags; */

    AV_W8(p + 6, ptlc.progressive_source_flag    << 7 |

                 ptlc.interlaced_source_flag     << 6 |

                 ptlc.non_packed_constraint_flag << 5 |

                 ptlc.frame_only_constraint_flag << 4);

    AV_W8(p + 7, 0);

    AV_WN32(p + 8, 0);

    /* unsigned int(8) general_level_idc; */

    AV_W8(p + 12, ptlc.level_idc);

    /*

     * bit(4) reserved = ‘1111’b;

     * unsigned int(12) min_spatial_segmentation_idc;

     */

    AV_W8(p + 13, 0xf0 | (vui.min_spatial_segmentation_idc >> 4));

    AV_W8(p + 14, vui.min_spatial_segmentation_idc & 0xff);

    /*

     * bit(6) reserved = ‘111111’b;

     * unsigned int(2) parallelismType;

     */

    if (!vui.min_spatial_segmentation_idc)

        parallelismType = 0;

    else if (pps->entropy_coding_sync_enabled_flag && pps->tiles_enabled_flag)

        parallelismType = 0;

    else if (pps->entropy_coding_sync_enabled_flag)

        parallelismType = 3;

    else if (pps->tiles_enabled_flag)

        parallelismType = 2;

    else

        parallelismType = 1;

    AV_W8(p + 15, 0xfc | parallelismType);

    /*

     * bit(6) reserved = ‘111111’b;

     * unsigned int(2) chromaFormat;

     */

    AV_W8(p + 16, sps->chroma_format_idc | 0xfc);

    /*

     * bit(5) reserved = ‘11111’b;

     * unsigned int(3) bitDepthLumaMinus8;

     */

    AV_W8(p + 17, (sps->bit_depth - 8) | 0xfc);

    /*

     * bit(5) reserved = ‘11111’b;

     * unsigned int(3) bitDepthChromaMinus8;

     */

    AV_W8(p + 18, (sps->bit_depth_chroma - 8) | 0xfc);

    /* bit(16) avgFrameRate; */

    AV_WB16(p + 19, 0);

    /*

     * bit(2) constantFrameRate;

     * bit(3) numTemporalLayers;

     * bit(1) temporalIdNested;

     * unsigned int(2) lengthSizeMinusOne;

     */

    AV_W8(p + 21, 0                             << 6 |

                  sps->max_sub_layers           << 3 |

                  sps->temporal_id_nesting_flag << 2 |

                  3);

    /* unsigned int(8) numOfArrays; */

    AV_W8(p + 22, 3);

    p += 23;

    /* vps */

    /*

     * bit(1) array_completeness;

     * unsigned int(1) reserved = 0;

     * unsigned int(6) NAL_unit_type;

     */

    AV_W8(p, 1 << 7 |

             HEVC_NAL_VPS & 0x3f);

    /* unsigned int(16) numNalus; */

    AV_WB16(p + 1, 1);

    /* unsigned int(16) nalUnitLength; */

    AV_WB16(p + 3, vps->data_size);

    /* bit(8*nalUnitLength) nalUnit; */

    memcpy(p + 5, vps->data, vps->data_size);

    p += 5 + vps->data_size;

    /* sps */

    AV_W8(p, 1 << 7 |

             HEVC_NAL_SPS & 0x3f);

    AV_WB16(p + 1, 1);

    AV_WB16(p + 3, sps->data_size);

    memcpy(p + 5, sps->data, sps->data_size);

    p += 5 + sps->data_size;

    /* pps */

    AV_W8(p, 1 << 7 |

             HEVC_NAL_PPS & 0x3f);

    AV_WB16(p + 1, num_pps);

    p += 3;

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

        if (h->ps.pps_list[i]) {

            const HEVCPPS *pps = (const HEVCPPS *)h->ps.pps_list[i]->data;

            AV_WB16(p, pps->data_size);

            memcpy(p + 2, pps->data, pps->data_size);

            p += 2 + pps->data_size;

        }

    }

    av_assert0(p - vt_extradata == vt_extradata_size);

    data = CFDataCreate(kCFAllocatorDefault, vt_extradata, vt_extradata_size);

    av_free(vt_extradata);

    return data;

}


static void xhci_kick_epctx(XHCIEPContext *epctx, unsigned int streamid)

{

    XHCIState *xhci = epctx->xhci;

    XHCIStreamContext *stctx = NULL;

    XHCITransfer *xfer;

    XHCIRing *ring;

    USBEndpoint *ep = NULL;

    uint64_t mfindex;

    unsigned int count = 0;

    int length;

    int i;

    trace_usb_xhci_ep_kick(epctx->slotid, epctx->epid, streamid);

    assert(!epctx->kick_active);

    /* If the device has been detached, but the guest has not noticed this

       yet the 2 above checks will succeed, but we must NOT continue */

    if (!xhci->slots[epctx->slotid - 1].uport ||

        !xhci->slots[epctx->slotid - 1].uport->dev ||

        !xhci->slots[epctx->slotid - 1].uport->dev->attached) {

        return;

    }

    if (epctx->retry) {

        XHCITransfer *xfer = epctx->retry;

        trace_usb_xhci_xfer_retry(xfer);

        assert(xfer->running_retry);

        if (xfer->timed_xfer) {

            /* time to kick the transfer? */

            mfindex = xhci_mfindex_get(xhci);

            xhci_check_intr_iso_kick(xhci, xfer, epctx, mfindex);

            if (xfer->running_retry) {

                return;

            }

            xfer->timed_xfer = 0;

            xfer->running_retry = 1;

        }

        if (xfer->iso_xfer) {

            /* retry iso transfer */

            if (xhci_setup_packet(xfer) < 0) {

                return;

            }

            usb_handle_packet(xfer->packet.ep->dev, &xfer->packet);

            assert(xfer->packet.status != USB_RET_NAK);

            xhci_try_complete_packet(xfer);

        } else {

            /* retry nak'ed transfer */

            if (xhci_setup_packet(xfer) < 0) {

                return;

            }

            usb_handle_packet(xfer->packet.ep->dev, &xfer->packet);

            if (xfer->packet.status == USB_RET_NAK) {

                return;

            }

            xhci_try_complete_packet(xfer);

        }

        assert(!xfer->running_retry);

        if (xfer->complete) {

            xhci_ep_free_xfer(epctx->retry);

        }

        epctx->retry = NULL;

    }

    if (epctx->state == EP_HALTED) {

        DPRINTF("xhci: ep halted, not running schedule\n");

        return;

    }

    if (epctx->nr_pstreams) {

        uint32_t err;

        stctx = xhci_find_stream(epctx, streamid, &err);

        if (stctx == NULL) {

            return;

        }

        ring = &stctx->ring;

        xhci_set_ep_state(xhci, epctx, stctx, EP_RUNNING);

    } else {

        ring = &epctx->ring;

        streamid = 0;

        xhci_set_ep_state(xhci, epctx, NULL, EP_RUNNING);

    }

    assert(ring->dequeue != 0);

    epctx->kick_active++;

    while (1) {

        length = xhci_ring_chain_length(xhci, ring);

        if (length <= 0) {

            break;

        }

        xfer = xhci_ep_alloc_xfer(epctx, length);

        if (xfer == NULL) {

            break;

        }

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

            TRBType type;

            type = xhci_ring_fetch(xhci, ring, &xfer->trbs[i], NULL);

            assert(type);

        }

        xfer->streamid = streamid;

        if (epctx->epid == 1) {

            xhci_fire_ctl_transfer(xhci, xfer);

        } else {

            xhci_fire_transfer(xhci, xfer, epctx);

        }

        if (xfer->complete) {

            xhci_ep_free_xfer(xfer);

            xfer = NULL;

        }

        if (epctx->state == EP_HALTED) {

            break;

        }

        if (xfer != NULL && xfer->running_retry) {

            DPRINTF("xhci: xfer nacked, stopping schedule\n");

            epctx->retry = xfer;

            break;

        }

        if (count++ > TRANSFER_LIMIT) {

            trace_usb_xhci_enforced_limit("transfers");

            break;

        }

    }

    /* update ring dequeue ptr */

    xhci_set_ep_state(xhci, epctx, stctx, epctx->state);

    epctx->kick_active--;

    ep = xhci_epid_to_usbep(epctx);

    if (ep) {

        usb_device_flush_ep_queue(ep->dev, ep);

    }

}


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

                         V9fsPath *dir_path, const char *name, FsCred *credp)

{

    int err = -1;

    int serrno = 0;

    char *newpath;

    V9fsString fullname;

    char *buffer;

    v9fs_string_init(&fullname);

    v9fs_string_sprintf(&fullname, "%s/%s", dir_path->data, name);

    newpath = fullname.data;

    /* Determine the security model */

    if (fs_ctx->export_flags & V9FS_SM_MAPPED) {

        int fd;

        ssize_t oldpath_size, write_size;

        buffer = rpath(fs_ctx, newpath);

        fd = open(buffer, O_CREAT|O_EXCL|O_RDWR|O_NOFOLLOW, SM_LOCAL_MODE_BITS);

        if (fd == -1) {

            g_free(buffer);

            err = fd;

            goto out;

        }

        /* Write the oldpath (target) to the file. */

        oldpath_size = strlen(oldpath);

        do {

            write_size = write(fd, (void *)oldpath, oldpath_size);

        } while (write_size == -1 && errno == EINTR);

        if (write_size != oldpath_size) {

            serrno = errno;

            close(fd);

            err = -1;

            goto err_end;

        }

        close(fd);

        /* Set cleint credentials in symlink's xattr */

        credp->fc_mode = credp->fc_mode|S_IFLNK;

        err = local_set_xattr(buffer, credp);

        if (err == -1) {

            serrno = errno;

            goto err_end;

        }

    } else if (fs_ctx->export_flags & V9FS_SM_MAPPED_FILE) {

        int fd;

        ssize_t oldpath_size, write_size;

        buffer = rpath(fs_ctx, newpath);

        fd = open(buffer, O_CREAT|O_EXCL|O_RDWR|O_NOFOLLOW, SM_LOCAL_MODE_BITS);

        if (fd == -1) {

            g_free(buffer);

            err = fd;

            goto out;

        }

        /* Write the oldpath (target) to the file. */

        oldpath_size = strlen(oldpath);

        do {

            write_size = write(fd, (void *)oldpath, oldpath_size);

        } while (write_size == -1 && errno == EINTR);

        if (write_size != oldpath_size) {

            serrno = errno;

            close(fd);

            err = -1;

            goto err_end;

        }

        close(fd);

        /* Set cleint credentials in symlink's xattr */

        credp->fc_mode = credp->fc_mode|S_IFLNK;

        err = local_set_mapped_file_attr(fs_ctx, newpath, credp);

        if (err == -1) {

            serrno = errno;

            goto err_end;

        }

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

               (fs_ctx->export_flags & V9FS_SM_NONE)) {

        buffer = rpath(fs_ctx, newpath);

        err = symlink(oldpath, buffer);

        if (err) {

            g_free(buffer);

            goto out;

        }

        err = lchown(buffer, credp->fc_uid, credp->fc_gid);

        if (err == -1) {

            /*

             * If we fail to change ownership and if we are

             * using security model none. Ignore the error

             */

            if ((fs_ctx->export_flags & V9FS_SEC_MASK) != V9FS_SM_NONE) {

                serrno = errno;

                goto err_end;

            } else

                err = 0;

        }

    }

    goto out;

err_end:

    remove(buffer);

    errno = serrno;

    g_free(buffer);

out:

    v9fs_string_free(&fullname);

    return err;

}


void OPPROTO op_405_check_satu (void)

{

    if (unlikely(T0 < T2)) {

        /* Saturate result */

        T0 = -1;

    }

    RETURN();

}


static void qemu_gluster_complete_aio(void *opaque)

{

    GlusterAIOCB *acb = (GlusterAIOCB *)opaque;

    qemu_bh_delete(acb->bh);

    acb->bh = NULL;

    qemu_coroutine_enter(acb->coroutine, NULL);

}


static void virtio_init_pci(VirtIOPCIProxy *proxy, VirtIODevice *vdev,

                            uint16_t vendor, uint16_t device,

                            uint16_t class_code, uint8_t pif)

{

    uint8_t *config;

    uint32_t size;

    proxy->vdev = vdev;

    config = proxy->pci_dev.config;

    pci_config_set_vendor_id(config, vendor);

    pci_config_set_device_id(config, device);

    config[0x08] = VIRTIO_PCI_ABI_VERSION;

    config[0x09] = pif;

    pci_config_set_class(config, class_code);

    config[PCI_HEADER_TYPE] = PCI_HEADER_TYPE_NORMAL;

    config[0x2c] = vendor & 0xFF;

    config[0x2d] = (vendor >> 8) & 0xFF;

    config[0x2e] = vdev->device_id & 0xFF;

    config[0x2f] = (vdev->device_id >> 8) & 0xFF;

    config[0x3d] = 1;

    if (vdev->nvectors && !msix_init(&proxy->pci_dev, vdev->nvectors, 1, 0,

                                     TARGET_PAGE_SIZE)) {

        pci_register_bar(&proxy->pci_dev, 1,

                         msix_bar_size(&proxy->pci_dev),

                         PCI_ADDRESS_SPACE_MEM,

                         msix_mmio_map);

    } else

        vdev->nvectors = 0;

    proxy->pci_dev.config_write = virtio_write_config;

    size = VIRTIO_PCI_REGION_SIZE(&proxy->pci_dev) + vdev->config_len;

    if (size & (size-1))

        size = 1 << qemu_fls(size);

    pci_register_bar(&proxy->pci_dev, 0, size, PCI_ADDRESS_SPACE_IO,

                           virtio_map);

    qemu_register_reset(virtio_pci_reset, proxy);

    virtio_bind_device(vdev, &virtio_pci_bindings, proxy);

}


static void disas_pc_rel_adr(DisasContext *s, uint32_t insn)

{

    unsigned int page, rd;

    uint64_t base;

    int64_t offset;

    page = extract32(insn, 31, 1);

    /* SignExtend(immhi:immlo) -> offset */

    offset = ((int64_t)sextract32(insn, 5, 19) << 2) | extract32(insn, 29, 2);

    rd = extract32(insn, 0, 5);

    base = s->pc - 4;

    if (page) {

        /* ADRP (page based) */

        base &= ~0xfff;

        offset <<= 12;

    }

    tcg_gen_movi_i64(cpu_reg(s, rd), base + offset);

}


ff_voc_get_packet(AVFormatContext *s, AVPacket *pkt, AVStream *st, int max_size)

{

    VocDecContext *voc = s->priv_data;

    AVCodecParameters *par = st->codecpar;

    AVIOContext *pb = s->pb;

    VocType type;

    int size, tmp_codec=-1;

    int sample_rate = 0;

    int channels = 1;

    int64_t duration;

    int ret;

    av_add_index_entry(st,

                       avio_tell(pb),

                       voc->pts,

                       voc->remaining_size,

                       0,

                       AVINDEX_KEYFRAME);

    while (!voc->remaining_size) {

        type = avio_r8(pb);

        if (type == VOC_TYPE_EOF)

            return AVERROR_EOF;

        voc->remaining_size = avio_rl24(pb);

        if (!voc->remaining_size) {

            if (!s->pb->seekable)

                return AVERROR(EIO);

            voc->remaining_size = avio_size(pb) - avio_tell(pb);

        }

        max_size -= 4;

        switch (type) {

        case VOC_TYPE_VOICE_DATA:

            if (!par->sample_rate) {

                par->sample_rate = 1000000 / (256 - avio_r8(pb));

                if (sample_rate)

                    par->sample_rate = sample_rate;

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

                par->channels = channels;

                par->bits_per_coded_sample = av_get_bits_per_sample(par->codec_id);

            } else

                avio_skip(pb, 1);

            tmp_codec = avio_r8(pb);

            voc->remaining_size -= 2;

            max_size -= 2;

            channels = 1;

            break;

        case VOC_TYPE_VOICE_DATA_CONT:

            break;

        case VOC_TYPE_EXTENDED:

            sample_rate = avio_rl16(pb);

            avio_r8(pb);

            channels = avio_r8(pb) + 1;

            sample_rate = 256000000 / (channels * (65536 - sample_rate));

            voc->remaining_size = 0;

            max_size -= 4;

            break;

        case VOC_TYPE_NEW_VOICE_DATA:

            if (!par->sample_rate) {

                par->sample_rate = avio_rl32(pb);

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

                par->bits_per_coded_sample = avio_r8(pb);

                par->channels = avio_r8(pb);

            } else

                avio_skip(pb, 6);

            tmp_codec = avio_rl16(pb);

            avio_skip(pb, 4);

            voc->remaining_size -= 12;

            max_size -= 12;

            break;

        default:

            avio_skip(pb, voc->remaining_size);

            max_size -= voc->remaining_size;

            voc->remaining_size = 0;

            break;

        }

    }

    if (par->sample_rate <= 0) {

        av_log(s, AV_LOG_ERROR, "Invalid sample rate %d\n", par->sample_rate);

        return AVERROR_INVALIDDATA;

    }

    if (tmp_codec >= 0) {

        tmp_codec = ff_codec_get_id(ff_voc_codec_tags, tmp_codec);

        if (par->codec_id == AV_CODEC_ID_NONE)

            par->codec_id = tmp_codec;

        else if (par->codec_id != tmp_codec)

            av_log(s, AV_LOG_WARNING, "Ignoring mid-stream change in audio codec\n");

        if (par->codec_id == AV_CODEC_ID_NONE) {

            if (s->audio_codec_id == AV_CODEC_ID_NONE) {

                av_log(s, AV_LOG_ERROR, "unknown codec tag\n");

                return AVERROR(EINVAL);

            }

            av_log(s, AV_LOG_WARNING, "unknown codec tag\n");

        }

    }

    par->bit_rate = par->sample_rate * par->channels * par->bits_per_coded_sample;

    if (max_size <= 0)

        max_size = 2048;

    size = FFMIN(voc->remaining_size, max_size);

    voc->remaining_size -= size;

    ret = av_get_packet(pb, pkt, size);

    pkt->dts = pkt->pts = voc->pts;

    duration = av_get_audio_frame_duration2(st->codecpar, size);

    if (duration > 0 && voc->pts != AV_NOPTS_VALUE)

        voc->pts += duration;

    else

        voc->pts = AV_NOPTS_VALUE;

    return ret;

}


void AcpiCpuHotplug_add(ACPIGPE *gpe, AcpiCpuHotplug *g, CPUState *cpu)

{

    CPUClass *k = CPU_GET_CLASS(cpu);

    int64_t cpu_id;

    *gpe->sts = *gpe->sts | ACPI_CPU_HOTPLUG_STATUS;

    cpu_id = k->get_arch_id(CPU(cpu));

    g->sts[cpu_id / 8] |= (1 << (cpu_id % 8));

}


static void fill_coding_method_array (sb_int8_array tone_level_idx, sb_int8_array tone_level_idx_temp,

                sb_int8_array coding_method, int nb_channels,

                int c, int superblocktype_2_3, int cm_table_select)

{

    int ch, sb, j;

    int tmp, acc, esp_40, comp;

    int add1, add2, add3, add4;

    int64_t multres;

    // This should never happen

    if (nb_channels <= 0)

        return;

    if (!superblocktype_2_3) {

        /* This case is untested, no samples available */

        SAMPLES_NEEDED

        for (ch = 0; ch < nb_channels; ch++)

            for (sb = 0; sb < 30; sb++) {

                for (j = 1; j < 64; j++) {

                    add1 = tone_level_idx[ch][sb][j] - 10;

                    if (add1 < 0)

                        add1 = 0;

                    add2 = add3 = add4 = 0;

                    if (sb > 1) {

                        add2 = tone_level_idx[ch][sb - 2][j] + tone_level_idx_offset_table[sb][0] - 6;

                        if (add2 < 0)

                            add2 = 0;

                    }

                    if (sb > 0) {

                        add3 = tone_level_idx[ch][sb - 1][j] + tone_level_idx_offset_table[sb][1] - 6;

                        if (add3 < 0)

                            add3 = 0;

                    }

                    if (sb < 29) {

                        add4 = tone_level_idx[ch][sb + 1][j] + tone_level_idx_offset_table[sb][3] - 6;

                        if (add4 < 0)

                            add4 = 0;

                    }

                    tmp = tone_level_idx[ch][sb][j + 1] * 2 - add4 - add3 - add2 - add1;

                    if (tmp < 0)

                        tmp = 0;

                    tone_level_idx_temp[ch][sb][j + 1] = tmp & 0xff;

                }

                tone_level_idx_temp[ch][sb][0] = tone_level_idx_temp[ch][sb][1];

            }

            acc = 0;

            for (ch = 0; ch < nb_channels; ch++)

                for (sb = 0; sb < 30; sb++)

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

                        acc += tone_level_idx_temp[ch][sb][j];

            if (acc)

                tmp = c * 256 / (acc & 0xffff);

            multres = 0x66666667 * (acc * 10);

            esp_40 = (multres >> 32) / 8 + ((multres & 0xffffffff) >> 31);

            for (ch = 0;  ch < nb_channels; ch++)

                for (sb = 0; sb < 30; sb++)

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

                        comp = tone_level_idx_temp[ch][sb][j]* esp_40 * 10;

                        if (comp < 0)

                            comp += 0xff;

                        comp /= 256; // signed shift

                        switch(sb) {

                            case 0:

                                if (comp < 30)

                                    comp = 30;

                                comp += 15;

                                break;

                            case 1:

                                if (comp < 24)

                                    comp = 24;

                                comp += 10;

                                break;

                            case 2:

                            case 3:

                            case 4:

                                if (comp < 16)

                                    comp = 16;

                        }

                        if (comp <= 5)

                            tmp = 0;

                        else if (comp <= 10)

                            tmp = 10;

                        else if (comp <= 16)

                            tmp = 16;

                        else if (comp <= 24)

                            tmp = -1;

                        else

                            tmp = 0;

                        coding_method[ch][sb][j] = ((tmp & 0xfffa) + 30 )& 0xff;

                    }

            for (sb = 0; sb < 30; sb++)

                fix_coding_method_array(sb, nb_channels, coding_method);

            for (ch = 0; ch < nb_channels; ch++)

                for (sb = 0; sb < 30; sb++)

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

                        if (sb >= 10) {

                            if (coding_method[ch][sb][j] < 10)

                                coding_method[ch][sb][j] = 10;

                        } else {

                            if (sb >= 2) {

                                if (coding_method[ch][sb][j] < 16)

                                    coding_method[ch][sb][j] = 16;

                            } else {

                                if (coding_method[ch][sb][j] < 30)

                                    coding_method[ch][sb][j] = 30;

                            }

                        }

    } else { // superblocktype_2_3 != 0

        for (ch = 0; ch < nb_channels; ch++)

            for (sb = 0; sb < 30; sb++)

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

                    coding_method[ch][sb][j] = coding_method_table[cm_table_select][sb];

    }

    return;

}


void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height,

                               int linesize_align[AV_NUM_DATA_POINTERS])

{

    int i;

    int w_align= 1;

    int h_align= 1;

    switch(s->pix_fmt){

    case PIX_FMT_YUV420P:

    case PIX_FMT_YUYV422:

    case PIX_FMT_UYVY422:

    case PIX_FMT_YUV422P:

    case PIX_FMT_YUV440P:

    case PIX_FMT_YUV444P:

    case PIX_FMT_GBRP:

    case PIX_FMT_GRAY8:

    case PIX_FMT_GRAY16BE:

    case PIX_FMT_GRAY16LE:

    case PIX_FMT_YUVJ420P:

    case PIX_FMT_YUVJ422P:

    case PIX_FMT_YUVJ440P:

    case PIX_FMT_YUVJ444P:

    case PIX_FMT_YUVA420P:

    case PIX_FMT_YUV420P9LE:

    case PIX_FMT_YUV420P9BE:

    case PIX_FMT_YUV420P10LE:

    case PIX_FMT_YUV420P10BE:

    case PIX_FMT_YUV422P9LE:

    case PIX_FMT_YUV422P9BE:

    case PIX_FMT_YUV422P10LE:

    case PIX_FMT_YUV422P10BE:

    case PIX_FMT_YUV444P9LE:

    case PIX_FMT_YUV444P9BE:

    case PIX_FMT_YUV444P10LE:

    case PIX_FMT_YUV444P10BE:

    case PIX_FMT_GBRP9LE:

    case PIX_FMT_GBRP9BE:

    case PIX_FMT_GBRP10LE:

    case PIX_FMT_GBRP10BE:

        w_align = 16; //FIXME assume 16 pixel per macroblock

        h_align = 16 * 2; // interlaced needs 2 macroblocks height

        break;

    case PIX_FMT_YUV411P:

    case PIX_FMT_UYYVYY411:

        w_align=32;

        h_align=8;

        break;

    case PIX_FMT_YUV410P:

        if(s->codec_id == CODEC_ID_SVQ1){

            w_align=64;

            h_align=64;

        }

    case PIX_FMT_RGB555:

        if(s->codec_id == CODEC_ID_RPZA){

            w_align=4;

            h_align=4;

        }

    case PIX_FMT_PAL8:

    case PIX_FMT_BGR8:

    case PIX_FMT_RGB8:

        if(s->codec_id == CODEC_ID_SMC){

            w_align=4;

            h_align=4;

        }

        break;

    case PIX_FMT_BGR24:

        if((s->codec_id == CODEC_ID_MSZH) || (s->codec_id == CODEC_ID_ZLIB)){

            w_align=4;

            h_align=4;

        }

        break;

    default:

        w_align= 1;

        h_align= 1;

        break;

    }

    *width = FFALIGN(*width , w_align);

    *height= FFALIGN(*height, h_align);

    if(s->codec_id == CODEC_ID_H264 || s->lowres)

        *height+=2; // some of the optimized chroma MC reads one line too much

                    // which is also done in mpeg decoders with lowres > 0

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

        linesize_align[i] = STRIDE_ALIGN;

//STRIDE_ALIGN is 8 for SSE* but this does not work for SVQ1 chroma planes

//we could change STRIDE_ALIGN to 16 for x86/sse but it would increase the

//picture size unneccessarily in some cases. The solution here is not

//pretty and better ideas are welcome!

#if HAVE_MMX

    if(s->codec_id == CODEC_ID_SVQ1 || s->codec_id == CODEC_ID_VP5 ||

       s->codec_id == CODEC_ID_VP6 || s->codec_id == CODEC_ID_VP6F ||

       s->codec_id == CODEC_ID_VP6A) {

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

            linesize_align[i] = 16;

    }

#endif

}


PPC_OP(addze)

{

    T1 = T0;

    T0 += xer_ca;

    if (T0 < T1) {

        xer_ca = 1;

    } else {

        xer_ca = 0;

    }

    RETURN();

}


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

{

    qemu_fseek(f, size, SEEK_CUR);

    return 0;

}


void hmp_savevm(Monitor *mon, const QDict *qdict)
{
    BlockDriverState *bs, *bs1;
    QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
    int ret;
    QEMUFile *f;
    int saved_vm_running;
    uint64_t vm_state_size;
    qemu_timeval tv;
    struct tm tm;
    const char *name = qdict_get_try_str(qdict, "name");
    Error *local_err = NULL;
    /* Verify if there is a device that doesn't support snapshots and is writable */
    bs = NULL;
    while ((bs = bdrv_next(bs))) {
        if (!bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
            continue;
        if (!bdrv_can_snapshot(bs)) {
            monitor_printf(mon, "Device '%s' is writable but does not support snapshots.\n",
                               bdrv_get_device_name(bs));
    bs = find_vmstate_bs();
    if (!bs) {
        monitor_printf(mon, "No block device can accept snapshots\n");
    saved_vm_running = runstate_is_running();
    vm_stop(RUN_STATE_SAVE_VM);
    memset(sn, 0, sizeof(*sn));
    /* fill auxiliary fields */
    qemu_gettimeofday(&tv);
    sn->date_sec = tv.tv_sec;
    sn->date_nsec = tv.tv_usec * 1000;
    sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
    if (name) {
        ret = bdrv_snapshot_find(bs, old_sn, name);
        if (ret >= 0) {
            pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
            pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
        } else {
            pstrcpy(sn->name, sizeof(sn->name), name);
    } else {
        /* cast below needed for OpenBSD where tv_sec is still 'long' */
        localtime_r((const time_t *)&tv.tv_sec, &tm);
        strftime(sn->name, sizeof(sn->name), "vm-%Y%m%d%H%M%S", &tm);
    /* Delete old snapshots of the same name */
    if (name && del_existing_snapshots(mon, name) < 0) {
        goto the_end;
    /* save the VM state */
    f = qemu_fopen_bdrv(bs, 1);
    if (!f) {
        monitor_printf(mon, "Could not open VM state file\n");
        goto the_end;
    ret = qemu_savevm_state(f, &local_err);
    vm_state_size = qemu_ftell(f);
    qemu_fclose(f);
    if (ret < 0) {
        monitor_printf(mon, "%s\n", error_get_pretty(local_err));
        error_free(local_err);
        goto the_end;
    /* create the snapshots */
    bs1 = NULL;
    while ((bs1 = bdrv_next(bs1))) {
        if (bdrv_can_snapshot(bs1)) {
            /* Write VM state size only to the image that contains the state */
            sn->vm_state_size = (bs == bs1 ? vm_state_size : 0);
            ret = bdrv_snapshot_create(bs1, sn);
            if (ret < 0) {
                monitor_printf(mon, "Error while creating snapshot on '%s'\n",
                               bdrv_get_device_name(bs1));
 the_end:
    if (saved_vm_running) {
        vm_start();


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

{

    SWFContext *swf = s->priv_data;

    AVIOContext *pb = s->pb;

    AVStream *vst = NULL, *ast = NULL, *st = 0;

    int tag, len, i, frame, v, res;

#if CONFIG_ZLIB

    if (swf->zpb)

        pb = swf->zpb;

#endif

    for(;;) {

        uint64_t pos = avio_tell(pb);

        tag = get_swf_tag(pb, &len);

        if (tag < 0)

            return tag;

        if (len < 0) {

            av_log(s, AV_LOG_ERROR, "invalid tag length: %d\n", len);

            return AVERROR_INVALIDDATA;

        }

        if (tag == TAG_VIDEOSTREAM) {

            int ch_id = avio_rl16(pb);

            len -= 2;

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

                st = s->streams[i];

                if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && st->id == ch_id)

                    goto skip;

            }

            avio_rl16(pb);

            avio_rl16(pb);

            avio_rl16(pb);

            avio_r8(pb);

            /* Check for FLV1 */

            vst = avformat_new_stream(s, NULL);

            if (!vst)

                return AVERROR(ENOMEM);

            vst->id = ch_id;

            vst->codec->codec_type = AVMEDIA_TYPE_VIDEO;

            vst->codec->codec_id = ff_codec_get_id(ff_swf_codec_tags, avio_r8(pb));

            avpriv_set_pts_info(vst, 16, 256, swf->frame_rate);

            len -= 8;

        } else if (tag == TAG_STREAMHEAD || tag == TAG_STREAMHEAD2) {

            /* streaming found */

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

                st = s->streams[i];

                if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && st->id == -1)

                    goto skip;

            }

            avio_r8(pb);

            v = avio_r8(pb);

            swf->samples_per_frame = avio_rl16(pb);

            ast = create_new_audio_stream(s, -1, v); /* -1 to avoid clash with video stream ch_id */

            if (!ast)

                return AVERROR(ENOMEM);

            len -= 4;

        } else if (tag == TAG_DEFINESOUND) {

            /* audio stream */

            int ch_id = avio_rl16(pb);

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

                st = s->streams[i];

                if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && st->id == ch_id)

                    goto skip;

            }

            // FIXME: The entire audio stream is stored in a single chunk/tag. Normally,

            // these are smaller audio streams in DEFINESOUND tags, but it's technically

            // possible they could be huge. Break it up into multiple packets if it's big.

            v = avio_r8(pb);

            ast = create_new_audio_stream(s, ch_id, v);

            if (!ast)

                return AVERROR(ENOMEM);

            ast->duration = avio_rl32(pb); // number of samples

            if (((v>>4) & 15) == 2) { // MP3 sound data record

                ast->skip_samples = avio_rl16(pb);

                len -= 2;

            }

            len -= 7;

            if ((res = av_get_packet(pb, pkt, len)) < 0)

                return res;

            pkt->pos = pos;

            pkt->stream_index = ast->index;

            return pkt->size;

        } else if (tag == TAG_VIDEOFRAME) {

            int ch_id = avio_rl16(pb);

            len -= 2;

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

                st = s->streams[i];

                if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && st->id == ch_id) {

                    frame = avio_rl16(pb);

                    len -= 2;

                    if (len <= 0)

                        goto skip;

                    if ((res = av_get_packet(pb, pkt, len)) < 0)

                        return res;

                    pkt->pos = pos;

                    pkt->pts = frame;

                    pkt->stream_index = st->index;

                    return pkt->size;

                }

            }

        } else if (tag == TAG_DEFINEBITSLOSSLESS || tag == TAG_DEFINEBITSLOSSLESS2) {

#if CONFIG_ZLIB

            long out_len;

            uint8_t *buf = NULL, *zbuf = NULL, *pal;

            uint32_t colormap[AVPALETTE_COUNT] = {0};

            const int alpha_bmp = tag == TAG_DEFINEBITSLOSSLESS2;

            const int colormapbpp = 3 + alpha_bmp;

            int linesize, colormapsize = 0;

            const int ch_id   = avio_rl16(pb);

            const int bmp_fmt = avio_r8(pb);

            const int width   = avio_rl16(pb);

            const int height  = avio_rl16(pb);

            len -= 2+1+2+2;

            switch (bmp_fmt) {

            case 3: // PAL-8

                linesize = width;

                colormapsize = avio_r8(pb) + 1;

                len--;

                break;

            case 4: // RGB15

                linesize = width * 2;

                break;

            case 5: // RGB24 (0RGB)

                linesize = width * 4;

                break;

            default:

                av_log(s, AV_LOG_ERROR, "invalid bitmap format %d, skipped\n", bmp_fmt);

                goto bitmap_end_skip;

            }

            linesize = FFALIGN(linesize, 4);

            if (av_image_check_size(width, height, 0, s) < 0 ||

                linesize >= INT_MAX / height ||

                linesize * height >= INT_MAX - colormapsize * colormapbpp) {

                av_log(s, AV_LOG_ERROR, "invalid frame size %dx%d\n", width, height);

                goto bitmap_end_skip;

            }

            out_len = colormapsize * colormapbpp + linesize * height;

            av_dlog(s, "bitmap: ch=%d fmt=%d %dx%d (linesize=%d) len=%d->%ld pal=%d\n",

                    ch_id, bmp_fmt, width, height, linesize, len, out_len, colormapsize);

            zbuf = av_malloc(len);

            buf  = av_malloc(out_len);

            if (!zbuf || !buf) {

                res = AVERROR(ENOMEM);

                goto bitmap_end;

            }

            len = avio_read(pb, zbuf, len);

            if (len < 0 || (res = uncompress(buf, &out_len, zbuf, len)) != Z_OK) {

                av_log(s, AV_LOG_WARNING, "Failed to uncompress one bitmap\n");

                goto bitmap_end_skip;

            }

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

                st = s->streams[i];

                if (st->codec->codec_id == AV_CODEC_ID_RAWVIDEO && st->id == -3)

                    break;

            }

            if (i == s->nb_streams) {

                vst = avformat_new_stream(s, NULL);

                if (!vst) {

                    res = AVERROR(ENOMEM);

                    goto bitmap_end;

                }

                vst->id = -3; /* -3 to avoid clash with video stream and audio stream */

                vst->codec->codec_type = AVMEDIA_TYPE_VIDEO;

                vst->codec->codec_id = AV_CODEC_ID_RAWVIDEO;

                avpriv_set_pts_info(vst, 64, 256, swf->frame_rate);

                st = vst;

            }

            st->codec->width  = width;

            st->codec->height = height;

            if ((res = av_new_packet(pkt, out_len - colormapsize * colormapbpp)) < 0)

                goto bitmap_end;

            pkt->pos = pos;

            pkt->stream_index = st->index;

            switch (bmp_fmt) {

            case 3:

                st->codec->pix_fmt = AV_PIX_FMT_PAL8;

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

                    if (alpha_bmp)  colormap[i] = buf[3]<<24 | AV_RB24(buf + 4*i);

                    else            colormap[i] = 0xffU <<24 | AV_RB24(buf + 3*i);

                pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);

                if (!pal) {

                    res = AVERROR(ENOMEM);

                    goto bitmap_end;

                }

                memcpy(pal, colormap, AVPALETTE_SIZE);

                break;

            case 4:

                st->codec->pix_fmt = AV_PIX_FMT_RGB555;

                break;

            case 5:

                st->codec->pix_fmt = alpha_bmp ? AV_PIX_FMT_ARGB : AV_PIX_FMT_0RGB;

                break;

            default:

                av_assert0(0);

            }

            if (linesize * height > pkt->size) {

                res = AVERROR_INVALIDDATA;

                goto bitmap_end;

            }

            memcpy(pkt->data, buf + colormapsize*colormapbpp, linesize * height);

            res = pkt->size;

bitmap_end:

            av_freep(&zbuf);

            av_freep(&buf);

            return res;

bitmap_end_skip:

            av_freep(&zbuf);

            av_freep(&buf);

#else

            av_log(s, AV_LOG_ERROR, "this file requires zlib support compiled in\n");

#endif

        } else if (tag == TAG_STREAMBLOCK) {

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

                st = s->streams[i];

                if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && st->id == -1) {

                    if (st->codec->codec_id == AV_CODEC_ID_MP3) {

                        avio_skip(pb, 4);

                        len -= 4;

                        if (len <= 0)

                            goto skip;

                        if ((res = av_get_packet(pb, pkt, len)) < 0)

                            return res;

                    } else { // ADPCM, PCM

                        if (len <= 0)

                            goto skip;

                        if ((res = av_get_packet(pb, pkt, len)) < 0)

                            return res;

                    }

                    pkt->pos          = pos;

                    pkt->stream_index = st->index;

                    return pkt->size;

                }

            }

        } else if (tag == TAG_JPEG2) {

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

                st = s->streams[i];

                if (st->codec->codec_id == AV_CODEC_ID_MJPEG && st->id == -2)

                    break;

            }

            if (i == s->nb_streams) {

                vst = avformat_new_stream(s, NULL);

                if (!vst)

                    return AVERROR(ENOMEM);

                vst->id = -2; /* -2 to avoid clash with video stream and audio stream */

                vst->codec->codec_type = AVMEDIA_TYPE_VIDEO;

                vst->codec->codec_id = AV_CODEC_ID_MJPEG;

                avpriv_set_pts_info(vst, 64, 256, swf->frame_rate);

                st = vst;

            }

            avio_rl16(pb); /* BITMAP_ID */

            len -= 2;

            if (len < 4)

                goto skip;

            if ((res = av_new_packet(pkt, len)) < 0)

                return res;

            if (avio_read(pb, pkt->data, 4) != 4) {

                av_free_packet(pkt);

                return AVERROR_INVALIDDATA;

            }

            if (AV_RB32(pkt->data) == 0xffd8ffd9 ||

                AV_RB32(pkt->data) == 0xffd9ffd8) {

                /* old SWF files containing SOI/EOI as data start */

                /* files created by swink have reversed tag */

                pkt->size -= 4;

                res = avio_read(pb, pkt->data, pkt->size);

            } else {

                res = avio_read(pb, pkt->data + 4, pkt->size - 4);

                if (res >= 0)

                    res += 4;

            }

            if (res != pkt->size) {

                if (res < 0) {

                    av_free_packet(pkt);

                    return res;

                }

                av_shrink_packet(pkt, res);

            }

            pkt->pos = pos;

            pkt->stream_index = st->index;

            return pkt->size;

        } else {

            av_log(s, AV_LOG_DEBUG, "Unknown tag: %d\n", tag);

        }

    skip:

        if(len<0)

            av_log(s, AV_LOG_WARNING, "Cliping len %d\n", len);

        len = FFMAX(0, len);

        avio_skip(pb, len);

    }

}


static int dvbsub_parse_region_segment(AVCodecContext *avctx,

                                       const uint8_t *buf, int buf_size)

{

    DVBSubContext *ctx = avctx->priv_data;

    const uint8_t *buf_end = buf + buf_size;

    int region_id, object_id;

    int av_unused version;

    DVBSubRegion *region;

    DVBSubObject *object;

    DVBSubObjectDisplay *display;

    int fill;

    int ret;

    if (buf_size < 10)

        return AVERROR_INVALIDDATA;

    region_id = *buf++;

    region = get_region(ctx, region_id);

    if (!region) {

        region = av_mallocz(sizeof(DVBSubRegion));

        if (!region)

            return AVERROR(ENOMEM);

        region->id = region_id;

        region->version = -1;

        region->next = ctx->region_list;

        ctx->region_list = region;

    version = ((*buf)>>4) & 15;

    fill = ((*buf++) >> 3) & 1;

    region->width = AV_RB16(buf);

    buf += 2;

    region->height = AV_RB16(buf);

    buf += 2;

    ret = av_image_check_size2(region->width, region->height, avctx->max_pixels, AV_PIX_FMT_PAL8, 0, avctx);

    if (ret < 0) {

        region->width= region->height= 0;

        return ret;

    if (region->width * region->height != region->buf_size) {

        av_free(region->pbuf);

        region->buf_size = region->width * region->height;

        region->pbuf = av_malloc(region->buf_size);

        if (!region->pbuf) {

            region->buf_size =

            region->width =

            region->height = 0;

            return AVERROR(ENOMEM);

        fill = 1;

        region->dirty = 0;

    region->depth = 1 << (((*buf++) >> 2) & 7);

    if(region->depth<2 || region->depth>8){

        av_log(avctx, AV_LOG_ERROR, "region depth %d is invalid\n", region->depth);

        region->depth= 4;

    region->clut = *buf++;

    if (region->depth == 8) {

        region->bgcolor = *buf++;

        buf += 1;

    } else {

        buf += 1;

        if (region->depth == 4)

            region->bgcolor = (((*buf++) >> 4) & 15);

        else

            region->bgcolor = (((*buf++) >> 2) & 3);

    ff_dlog(avctx, "Region %d, (%dx%d)\n", region_id, region->width, region->height);

    if (fill) {

        memset(region->pbuf, region->bgcolor, region->buf_size);

        ff_dlog(avctx, "Fill region (%d)\n", region->bgcolor);

    delete_region_display_list(ctx, region);

    while (buf + 5 < buf_end) {

        object_id = AV_RB16(buf);

        buf += 2;

        object = get_object(ctx, object_id);

        if (!object) {

            object = av_mallocz(sizeof(DVBSubObject));

            if (!object)

                return AVERROR(ENOMEM);

            object->id = object_id;

            object->next = ctx->object_list;

            ctx->object_list = object;

        object->type = (*buf) >> 6;

        display = av_mallocz(sizeof(DVBSubObjectDisplay));

        if (!display)

            return AVERROR(ENOMEM);

        display->object_id = object_id;

        display->region_id = region_id;

        display->x_pos = AV_RB16(buf) & 0xfff;

        buf += 2;

        display->y_pos = AV_RB16(buf) & 0xfff;

        buf += 2;

        if ((object->type == 1 || object->type == 2) && buf+1 < buf_end) {

            display->fgcolor = *buf++;

            display->bgcolor = *buf++;

        display->region_list_next = region->display_list;

        region->display_list = display;

        display->object_list_next = object->display_list;

        object->display_list = display;

    return 0;


int attribute_align_arg av_buffersink_get_frame_flags(AVFilterContext *ctx, AVFrame *frame, int flags)

{

    BufferSinkContext *buf = ctx->priv;

    AVFilterLink *inlink = ctx->inputs[0];

    int ret;

    AVFrame *cur_frame;

    /* no picref available, fetch it from the filterchain */

    if (!av_fifo_size(buf->fifo)) {

        if (flags & AV_BUFFERSINK_FLAG_NO_REQUEST)

            return AVERROR(EAGAIN);

        if ((ret = ff_request_frame(inlink)) < 0)

            return ret;

    }

    if (!av_fifo_size(buf->fifo))

        return AVERROR(EINVAL);

    if (flags & AV_BUFFERSINK_FLAG_PEEK) {

        cur_frame = *((AVFrame **)av_fifo_peek2(buf->fifo, 0));

        av_frame_ref(frame, cur_frame); /* TODO check failure */

    } else {

        av_fifo_generic_read(buf->fifo, &cur_frame, sizeof(cur_frame), NULL);

        av_frame_move_ref(frame, cur_frame);

        av_frame_free(&cur_frame);

    }

    return 0;

}


void hmp_pcie_aer_inject_error(Monitor *mon, const QDict *qdict)

{

    QObject *data;

    int devfn;

    if (do_pcie_aer_inject_error(mon, qdict, &data) < 0) {

        return;

    }

    qdict = qobject_to_qdict(data);

    assert(qdict);

    devfn = (int)qdict_get_int(qdict, "devfn");

    monitor_printf(mon, "OK id: %s root bus: %s, bus: %x devfn: %x.%x\n",

                   qdict_get_str(qdict, "id"),

                   qdict_get_str(qdict, "root_bus"),

                   (int) qdict_get_int(qdict, "bus"),

                   PCI_SLOT(devfn), PCI_FUNC(devfn));

}


static int ac3_eac3_probe(AVProbeData *p, enum CodecID expected_codec_id)

{

    int max_frames, first_frames = 0, frames;

    uint8_t *buf, *buf2, *end;

    AC3HeaderInfo hdr;

    GetBitContext gbc;

    enum CodecID codec_id = CODEC_ID_AC3;

    max_frames = 0;

    buf = p->buf;

    end = buf + p->buf_size;

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

        buf2 = buf;

        for(frames = 0; buf2 < end; frames++) {

            init_get_bits(&gbc, buf2, 54);

            if(avpriv_ac3_parse_header(&gbc, &hdr) < 0)

                break;

            if(buf2 + hdr.frame_size > end ||

               av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0, buf2 + 2, hdr.frame_size - 2))

                break;

            if (hdr.bitstream_id > 10)

                codec_id = CODEC_ID_EAC3;

            buf2 += hdr.frame_size;

        }

        max_frames = FFMAX(max_frames, frames);

        if(buf == p->buf)

            first_frames = frames;

    }

    if(codec_id != expected_codec_id) return 0;

    // keep this in sync with mp3 probe, both need to avoid

    // issues with MPEG-files!

    if   (first_frames>=4) return AVPROBE_SCORE_MAX/2+1;

    else if(max_frames>500)return AVPROBE_SCORE_MAX/2;

    else if(max_frames>=4) return AVPROBE_SCORE_MAX/4;

    else if(max_frames>=1) return 1;

    else                   return 0;

}


static int h263_probe(AVProbeData *p)

{

    int code;

    const uint8_t *d;

    if (p->buf_size < 6)

        return 0;

    d = p->buf;

    code = (d[0] << 14) | (d[1] << 6) | (d[2] >> 2);

    if (code == 0x20) {

        return 50;

    }

    return 0;

}


static int cinepak_decode_init(AVCodecContext *avctx)

{

    CinepakContext *s = avctx->priv_data;

    s->avctx = avctx;

    s->width = (avctx->width + 3) & ~3;

    s->height = (avctx->height + 3) & ~3;

    s->sega_film_skip_bytes = -1;  /* uninitialized state */

    // check for paletted data

    if ((avctx->palctrl == NULL) || (avctx->bits_per_sample == 40)) {

        s->palette_video = 0;

        avctx->pix_fmt = PIX_FMT_YUV420P;

    } else {

        s->palette_video = 1;

        avctx->pix_fmt = PIX_FMT_PAL8;

    }

    dsputil_init(&s->dsp, avctx);

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

    return 0;

}


static int mpegts_init(AVFormatContext *s)

{

    MpegTSWrite *ts = s->priv_data;

    MpegTSWriteStream *ts_st;

    MpegTSService *service;

    AVStream *st, *pcr_st = NULL;

    AVDictionaryEntry *title, *provider;

    int i, j;

    const char *service_name;

    const char *provider_name;

    int *pids;

    int ret;

    if (s->max_delay < 0) /* Not set by the caller */

        s->max_delay = 0;

    // round up to a whole number of TS packets

    ts->pes_payload_size = (ts->pes_payload_size + 14 + 183) / 184 * 184 - 14;

    ts->tsid = ts->transport_stream_id;

    ts->onid = ts->original_network_id;

    if (!s->nb_programs) {

        /* allocate a single DVB service */

        title = av_dict_get(s->metadata, "service_name", NULL, 0);

        if (!title)

            title = av_dict_get(s->metadata, "title", NULL, 0);

        service_name  = title ? title->value : DEFAULT_SERVICE_NAME;

        provider      = av_dict_get(s->metadata, "service_provider", NULL, 0);

        provider_name = provider ? provider->value : DEFAULT_PROVIDER_NAME;

        service       = mpegts_add_service(ts, ts->service_id,

                                           provider_name, service_name);

        if (!service)

            return AVERROR(ENOMEM);

        service->pmt.write_packet = section_write_packet;

        service->pmt.opaque       = s;

        service->pmt.cc           = 15;

        service->pmt.discontinuity= ts->flags & MPEGTS_FLAG_DISCONT;

    } else {

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

            AVProgram *program = s->programs[i];

            title = av_dict_get(program->metadata, "service_name", NULL, 0);

            if (!title)

                title = av_dict_get(program->metadata, "title", NULL, 0);

            service_name  = title ? title->value : DEFAULT_SERVICE_NAME;

            provider      = av_dict_get(program->metadata, "service_provider", NULL, 0);

            provider_name = provider ? provider->value : DEFAULT_PROVIDER_NAME;

            service       = mpegts_add_service(ts, program->id,

                                               provider_name, service_name);

            if (!service)

                return AVERROR(ENOMEM);

            service->pmt.write_packet = section_write_packet;

            service->pmt.opaque       = s;

            service->pmt.cc           = 15;

            service->pmt.discontinuity= ts->flags & MPEGTS_FLAG_DISCONT;

            service->program          = program;

        }

    }

    ts->pat.pid          = PAT_PID;

    /* Initialize at 15 so that it wraps and is equal to 0 for the

     * first packet we write. */

    ts->pat.cc           = 15;

    ts->pat.discontinuity= ts->flags & MPEGTS_FLAG_DISCONT;

    ts->pat.write_packet = section_write_packet;

    ts->pat.opaque       = s;

    ts->sdt.pid          = SDT_PID;

    ts->sdt.cc           = 15;

    ts->sdt.discontinuity= ts->flags & MPEGTS_FLAG_DISCONT;

    ts->sdt.write_packet = section_write_packet;

    ts->sdt.opaque       = s;

    pids = av_malloc_array(s->nb_streams, sizeof(*pids));

    if (!pids) {

        ret = AVERROR(ENOMEM);

        goto fail;

    }

    /* assign pids to each stream */

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

        AVProgram *program;

        st = s->streams[i];

        ts_st = av_mallocz(sizeof(MpegTSWriteStream));

        if (!ts_st) {

            ret = AVERROR(ENOMEM);

            goto fail;

        }

        st->priv_data = ts_st;

        ts_st->user_tb = st->time_base;

        avpriv_set_pts_info(st, 33, 1, 90000);

        ts_st->payload = av_mallocz(ts->pes_payload_size);

        if (!ts_st->payload) {

            ret = AVERROR(ENOMEM);

            goto fail;

        }

        program = av_find_program_from_stream(s, NULL, i);

        if (program) {

            for (j = 0; j < ts->nb_services; j++) {

                if (ts->services[j]->program == program) {

                    service = ts->services[j];

                    break;

                }

            }

        }

        ts_st->service = service;

        /* MPEG pid values < 16 are reserved. Applications which set st->id in

         * this range are assigned a calculated pid. */

        if (st->id < 16) {

            ts_st->pid = ts->start_pid + i;

        } else if (st->id < 0x1FFF) {

            ts_st->pid = st->id;

        } else {

            av_log(s, AV_LOG_ERROR,

                   "Invalid stream id %d, must be less than 8191\n", st->id);

            ret = AVERROR(EINVAL);

            goto fail;

        }

        if (ts_st->pid == service->pmt.pid) {

            av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);

            ret = AVERROR(EINVAL);

            goto fail;

        }

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

            if (pids[j] == ts_st->pid) {

                av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);

                ret = AVERROR(EINVAL);

                goto fail;

            }

        }

        pids[i]                = ts_st->pid;

        ts_st->payload_pts     = AV_NOPTS_VALUE;

        ts_st->payload_dts     = AV_NOPTS_VALUE;

        ts_st->first_pts_check = 1;

        ts_st->cc              = 15;

        /* update PCR pid by using the first video stream */

        if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&

            service->pcr_pid == 0x1fff) {

            service->pcr_pid = ts_st->pid;

            pcr_st           = st;

        }

        if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&

            st->codecpar->extradata_size > 0) {

            AVStream *ast;

            ts_st->amux = avformat_alloc_context();

            if (!ts_st->amux) {

                ret = AVERROR(ENOMEM);

                goto fail;

            }

            ts_st->amux->oformat =

                av_guess_format((ts->flags & MPEGTS_FLAG_AAC_LATM) ? "latm" : "adts",

                                NULL, NULL);

            if (!ts_st->amux->oformat) {

                ret = AVERROR(EINVAL);

                goto fail;

            }

            if (!(ast = avformat_new_stream(ts_st->amux, NULL))) {

                ret = AVERROR(ENOMEM);

                goto fail;

            }

            ret = avcodec_parameters_copy(ast->codecpar, st->codecpar);

            if (ret != 0)

                goto fail;

            ast->time_base = st->time_base;

            ret = avformat_write_header(ts_st->amux, NULL);

            if (ret < 0)

                goto fail;

        }

        if (st->codecpar->codec_id == AV_CODEC_ID_OPUS) {

            ts_st->opus_pending_trim_start = st->codecpar->initial_padding * 48000 / st->codecpar->sample_rate;

        }

    }

    av_freep(&pids);

    /* if no video stream, use the first stream as PCR */

    if (service->pcr_pid == 0x1fff && s->nb_streams > 0) {

        pcr_st           = s->streams[0];

        ts_st            = pcr_st->priv_data;

        service->pcr_pid = ts_st->pid;

    } else

        ts_st = pcr_st->priv_data;

    if (ts->mux_rate > 1) {

        service->pcr_packet_period = (int64_t)ts->mux_rate * ts->pcr_period /

                                     (TS_PACKET_SIZE * 8 * 1000);

        ts->sdt_packet_period      = (int64_t)ts->mux_rate * SDT_RETRANS_TIME /

                                     (TS_PACKET_SIZE * 8 * 1000);

        ts->pat_packet_period      = (int64_t)ts->mux_rate * PAT_RETRANS_TIME /

                                     (TS_PACKET_SIZE * 8 * 1000);

        if (ts->copyts < 1)

            ts->first_pcr = av_rescale(s->max_delay, PCR_TIME_BASE, AV_TIME_BASE);

    } else {

        /* Arbitrary values, PAT/PMT will also be written on video key frames */

        ts->sdt_packet_period = 200;

        ts->pat_packet_period = 40;

        if (pcr_st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {

            int frame_size = av_get_audio_frame_duration2(pcr_st->codecpar, 0);

            if (!frame_size) {

                av_log(s, AV_LOG_WARNING, "frame size not set\n");

                service->pcr_packet_period =

                    pcr_st->codecpar->sample_rate / (10 * 512);

            } else {

                service->pcr_packet_period =

                    pcr_st->codecpar->sample_rate / (10 * frame_size);

            }

        } else {

            // max delta PCR 0.1s

            // TODO: should be avg_frame_rate

            service->pcr_packet_period =

                ts_st->user_tb.den / (10 * ts_st->user_tb.num);

        }

        if (!service->pcr_packet_period)

            service->pcr_packet_period = 1;

    }

    ts->last_pat_ts = AV_NOPTS_VALUE;

    ts->last_sdt_ts = AV_NOPTS_VALUE;

    // The user specified a period, use only it

    if (ts->pat_period < INT_MAX/2) {

        ts->pat_packet_period = INT_MAX;

    }

    if (ts->sdt_period < INT_MAX/2) {

        ts->sdt_packet_period = INT_MAX;

    }

    // output a PCR as soon as possible

    service->pcr_packet_count = service->pcr_packet_period;

    ts->pat_packet_count      = ts->pat_packet_period - 1;

    ts->sdt_packet_count      = ts->sdt_packet_period - 1;

    if (ts->mux_rate == 1)

        av_log(s, AV_LOG_VERBOSE, "muxrate VBR, ");

    else

        av_log(s, AV_LOG_VERBOSE, "muxrate %d, ", ts->mux_rate);

    av_log(s, AV_LOG_VERBOSE,

           "pcr every %d pkts, sdt every %d, pat/pmt every %d pkts\n",

           service->pcr_packet_period,

           ts->sdt_packet_period, ts->pat_packet_period);

    if (ts->m2ts_mode == -1) {

        if (av_match_ext(s->filename, "m2ts")) {

            ts->m2ts_mode = 1;

        } else {

            ts->m2ts_mode = 0;

        }

    }

    return 0;

fail:

    av_freep(&pids);

    return ret;

}


static void rtsp_cmd_setup(HTTPContext *c, const char *url,

                           RTSPHeader *h)

{

    FFStream *stream;

    int stream_index, port;

    char buf[1024];

    char path1[1024];

    const char *path;

    HTTPContext *rtp_c;

    RTSPTransportField *th;

    struct sockaddr_in dest_addr;

    RTSPActionServerSetup setup;

    /* find which url is asked */

    url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);

    path = path1;

    if (*path == '/')

        path++;

    /* now check each stream */

    for(stream = first_stream; stream != NULL; stream = stream->next) {

        if (!stream->is_feed && !strcmp(stream->fmt->name, "rtp")) {

            /* accept aggregate filenames only if single stream */

            if (!strcmp(path, stream->filename)) {

                if (stream->nb_streams != 1) {

                    rtsp_reply_error(c, RTSP_STATUS_AGGREGATE);

                    return;

                }

                stream_index = 0;

                goto found;

            }

            for(stream_index = 0; stream_index < stream->nb_streams;

                stream_index++) {

                snprintf(buf, sizeof(buf), "%s/streamid=%d",

                         stream->filename, stream_index);

                if (!strcmp(path, buf))

                    goto found;

            }

        }

    }

    /* no stream found */

    rtsp_reply_error(c, RTSP_STATUS_SERVICE); /* XXX: right error ? */

    return;

 found:

    /* generate session id if needed */

    if (h->session_id[0] == '\0')

        snprintf(h->session_id, sizeof(h->session_id), "%08x%08x",

                 av_random(&random_state), av_random(&random_state));

    /* find rtp session, and create it if none found */

    rtp_c = find_rtp_session(h->session_id);

    if (!rtp_c) {

        /* always prefer UDP */

        th = find_transport(h, RTSP_PROTOCOL_RTP_UDP);

        if (!th) {

            th = find_transport(h, RTSP_PROTOCOL_RTP_TCP);

            if (!th) {

                rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);

                return;

            }

        }

        rtp_c = rtp_new_connection(&c->from_addr, stream, h->session_id,

                                   th->protocol);

        if (!rtp_c) {

            rtsp_reply_error(c, RTSP_STATUS_BANDWIDTH);

            return;

        }

        /* open input stream */

        if (open_input_stream(rtp_c, "") < 0) {

            rtsp_reply_error(c, RTSP_STATUS_INTERNAL);

            return;

        }

    }

    /* test if stream is OK (test needed because several SETUP needs

       to be done for a given file) */

    if (rtp_c->stream != stream) {

        rtsp_reply_error(c, RTSP_STATUS_SERVICE);

        return;

    }

    /* test if stream is already set up */

    if (rtp_c->rtp_ctx[stream_index]) {

        rtsp_reply_error(c, RTSP_STATUS_STATE);

        return;

    }

    /* check transport */

    th = find_transport(h, rtp_c->rtp_protocol);

    if (!th || (th->protocol == RTSP_PROTOCOL_RTP_UDP &&

                th->client_port_min <= 0)) {

        rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);

        return;

    }

    /* setup default options */

    setup.transport_option[0] = '\0';

    dest_addr = rtp_c->from_addr;

    dest_addr.sin_port = htons(th->client_port_min);

    /* setup stream */

    if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, c) < 0) {

        rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);

        return;

    }

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

    rtsp_reply_header(c, RTSP_STATUS_OK);

    /* session ID */

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

    switch(rtp_c->rtp_protocol) {

    case RTSP_PROTOCOL_RTP_UDP:

        port = rtp_get_local_port(rtp_c->rtp_handles[stream_index]);

        url_fprintf(c->pb, "Transport: RTP/AVP/UDP;unicast;"

                    "client_port=%d-%d;server_port=%d-%d",

                    th->client_port_min, th->client_port_min + 1,

                    port, port + 1);

        break;

    case RTSP_PROTOCOL_RTP_TCP:

        url_fprintf(c->pb, "Transport: RTP/AVP/TCP;interleaved=%d-%d",

                    stream_index * 2, stream_index * 2 + 1);

        break;

    default:

        break;

    }

    if (setup.transport_option[0] != '\0')

        url_fprintf(c->pb, ";%s", setup.transport_option);

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

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

}


void aio_set_fd_handler(AioContext *ctx,

                        int fd,

                        bool is_external,

                        IOHandler *io_read,

                        IOHandler *io_write,

                        AioPollFn *io_poll,

                        void *opaque)

{

    AioHandler *node;

    bool is_new = false;

    bool deleted = false;

    qemu_lockcnt_lock(&ctx->list_lock);

    node = find_aio_handler(ctx, fd);

    /* Are we deleting the fd handler? */

    if (!io_read && !io_write && !io_poll) {

        if (node == NULL) {

            qemu_lockcnt_unlock(&ctx->list_lock);

            return;

        }

        g_source_remove_poll(&ctx->source, &node->pfd);

        /* If the lock is held, just mark the node as deleted */

        if (qemu_lockcnt_count(&ctx->list_lock)) {

            node->deleted = 1;

            node->pfd.revents = 0;

        } else {

            /* Otherwise, delete it for real.  We can't just mark it as

             * deleted because deleted nodes are only cleaned up while

             * no one is walking the handlers list.

             */

            QLIST_REMOVE(node, node);

            deleted = true;

        }

        if (!node->io_poll) {

            ctx->poll_disable_cnt--;

        }

    } else {

        if (node == NULL) {

            /* Alloc and insert if it's not already there */

            node = g_new0(AioHandler, 1);

            node->pfd.fd = fd;

            QLIST_INSERT_HEAD_RCU(&ctx->aio_handlers, node, node);

            g_source_add_poll(&ctx->source, &node->pfd);

            is_new = true;

            ctx->poll_disable_cnt += !io_poll;

        } else {

            ctx->poll_disable_cnt += !io_poll - !node->io_poll;

        }

        /* Update handler with latest information */

        node->io_read = io_read;

        node->io_write = io_write;

        node->io_poll = io_poll;

        node->opaque = opaque;

        node->is_external = is_external;

        node->pfd.events = (io_read ? G_IO_IN | G_IO_HUP | G_IO_ERR : 0);

        node->pfd.events |= (io_write ? G_IO_OUT | G_IO_ERR : 0);

    }

    aio_epoll_update(ctx, node, is_new);

    qemu_lockcnt_unlock(&ctx->list_lock);

    aio_notify(ctx);

    if (deleted) {

        g_free(node);

    }

}


static int check_bits_for_superframe(GetBitContext *orig_gb,

                                     WMAVoiceContext *s)

{

    GetBitContext s_gb, *gb = &s_gb;

    int n, need_bits, bd_idx;

    const struct frame_type_desc *frame_desc;

    /* initialize a copy */

    init_get_bits(gb, orig_gb->buffer, orig_gb->size_in_bits);

    skip_bits_long(gb, get_bits_count(orig_gb));

    av_assert1(get_bits_left(gb) == get_bits_left(orig_gb));

    /* superframe header */

    if (get_bits_left(gb) < 14)

        return 1;

    if (!get_bits1(gb))

        return AVERROR(ENOSYS);           // WMAPro-in-WMAVoice superframe

    if (get_bits1(gb)) skip_bits(gb, 12); // number of  samples in superframe

    if (s->has_residual_lsps) {           // residual LSPs (for all frames)

        if (get_bits_left(gb) < s->sframe_lsp_bitsize)

            return 1;

        skip_bits_long(gb, s->sframe_lsp_bitsize);

    }

    /* frames */

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

        int aw_idx_is_ext = 0;

        if (!s->has_residual_lsps) {     // independent LSPs (per-frame)

           if (get_bits_left(gb) < s->frame_lsp_bitsize) return 1;

           skip_bits_long(gb, s->frame_lsp_bitsize);

        }

        bd_idx = s->vbm_tree[get_vlc2(gb, frame_type_vlc.table, 6, 3)];

        if (bd_idx < 0)

            return AVERROR_INVALIDDATA; // invalid frame type VLC code

        frame_desc = &frame_descs[bd_idx];

        if (frame_desc->acb_type == ACB_TYPE_ASYMMETRIC) {

            if (get_bits_left(gb) < s->pitch_nbits)

                return 1;

            skip_bits_long(gb, s->pitch_nbits);

        }

        if (frame_desc->fcb_type == FCB_TYPE_SILENCE) {

            skip_bits(gb, 8);

        } else if (frame_desc->fcb_type == FCB_TYPE_AW_PULSES) {

            int tmp = get_bits(gb, 6);

            if (tmp >= 0x36) {

                skip_bits(gb, 2);

                aw_idx_is_ext = 1;

            }

        }

        /* blocks */

        if (frame_desc->acb_type == ACB_TYPE_HAMMING) {

            need_bits = s->block_pitch_nbits +

                (frame_desc->n_blocks - 1) * s->block_delta_pitch_nbits;

        } else if (frame_desc->fcb_type == FCB_TYPE_AW_PULSES) {

            need_bits = 2 * !aw_idx_is_ext;

        } else

            need_bits = 0;

        need_bits += frame_desc->frame_size;

        if (get_bits_left(gb) < need_bits)

            return 1;

        skip_bits_long(gb, need_bits);

    }

    return 0;

}


static void h263_v_loop_filter_mmx(uint8_t *src, int stride, int qscale)

{

    if (CONFIG_H263_DECODER || CONFIG_H263_ENCODER) {

        const int strength = ff_h263_loop_filter_strength[qscale];

        __asm__ volatile (

            H263_LOOP_FILTER

            "movq %%mm3, %1             \n\t"

            "movq %%mm4, %2             \n\t"

            "movq %%mm5, %0             \n\t"

            "movq %%mm6, %3             \n\t"

            : "+m"(*(uint64_t*)(src - 2 * stride)),

              "+m"(*(uint64_t*)(src - 1 * stride)),

              "+m"(*(uint64_t*)(src + 0 * stride)),

              "+m"(*(uint64_t*)(src + 1 * stride))

            : "g"(2 * strength), "m"(ff_pb_FC)

            );

    }

}


static int64_t *concat_channels_lists(const int64_t *layouts, const int *counts)

{

    int nb_layouts = 0, nb_counts = 0, i;

    int64_t *list;

    if (layouts)

        for (; layouts[nb_layouts] != -1; nb_layouts++);

    if (counts)

        for (; counts[nb_counts] != -1; nb_counts++);

    if (nb_counts > INT_MAX - 1 - nb_layouts)

        return NULL;

    if (!(list = av_calloc(nb_layouts + nb_counts + 1, sizeof(*list))))

        return NULL;

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

        list[i] = layouts[i];

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

        list[nb_layouts + i] = FF_COUNT2LAYOUT(counts[i]);

    list[nb_layouts + nb_counts] = -1;

    return list;

}


static void vnc_qmp_event(VncState *vs, QAPIEvent event)

{

    VncServerInfo *si;

    if (!vs->info) {

        return;

    }

    g_assert(vs->info->base);

    si = vnc_server_info_get(vs->vd);

    if (!si) {

        return;

    }

    switch (event) {

    case QAPI_EVENT_VNC_CONNECTED:

        qapi_event_send_vnc_connected(si, vs->info->base, &error_abort);

        break;

    case QAPI_EVENT_VNC_INITIALIZED:

        qapi_event_send_vnc_initialized(si, vs->info, &error_abort);

        break;

    case QAPI_EVENT_VNC_DISCONNECTED:

        qapi_event_send_vnc_disconnected(si, vs->info, &error_abort);

        break;

    default:

        break;

    }

    qapi_free_VncServerInfo(si);

}


void dump_exec_info(FILE *f,

                    int (*cpu_fprintf)(FILE *f, const char *fmt, ...))

{

    int i, target_code_size, max_target_code_size;

    int direct_jmp_count, direct_jmp2_count, cross_page;

    TranslationBlock *tb;

    target_code_size = 0;

    max_target_code_size = 0;

    cross_page = 0;

    direct_jmp_count = 0;

    direct_jmp2_count = 0;

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

        tb = &tbs[i];

        target_code_size += tb->size;

        if (tb->size > max_target_code_size)

            max_target_code_size = tb->size;

        if (tb->page_addr[1] != -1)

            cross_page++;

        if (tb->tb_next_offset[0] != 0xffff) {

            direct_jmp_count++;

            if (tb->tb_next_offset[1] != 0xffff) {

                direct_jmp2_count++;

            }

        }

    }

    /* XXX: avoid using doubles ? */

    cpu_fprintf(f, "Translation buffer state:\n");

    cpu_fprintf(f, "gen code size       %ld/%ld\n",

                code_gen_ptr - code_gen_buffer, code_gen_buffer_max_size);

    cpu_fprintf(f, "TB count            %d/%d\n",

                nb_tbs, code_gen_max_blocks);

    cpu_fprintf(f, "TB avg target size  %d max=%d bytes\n",

                nb_tbs ? target_code_size / nb_tbs : 0,

                max_target_code_size);

    cpu_fprintf(f, "TB avg host size    %d bytes (expansion ratio: %0.1f)\n",

                nb_tbs ? (code_gen_ptr - code_gen_buffer) / nb_tbs : 0,

                target_code_size ? (double) (code_gen_ptr - code_gen_buffer) / target_code_size : 0);

    cpu_fprintf(f, "cross page TB count %d (%d%%)\n",

            cross_page,

            nb_tbs ? (cross_page * 100) / nb_tbs : 0);

    cpu_fprintf(f, "direct jump count   %d (%d%%) (2 jumps=%d %d%%)\n",

                direct_jmp_count,

                nb_tbs ? (direct_jmp_count * 100) / nb_tbs : 0,

                direct_jmp2_count,

                nb_tbs ? (direct_jmp2_count * 100) / nb_tbs : 0);

    cpu_fprintf(f, "\nStatistics:\n");

    cpu_fprintf(f, "TB flush count      %d\n", tb_flush_count);

    cpu_fprintf(f, "TB invalidate count %d\n", tb_phys_invalidate_count);

    cpu_fprintf(f, "TLB flush count     %d\n", tlb_flush_count);

    tcg_dump_info(f, cpu_fprintf);

}


static void ac3_downmix(AC3DecodeContext *s)

{

    int i, j;

    float v0, v1;

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

        v0 = v1 = 0.0f;

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

            v0 += s->output[j][i] * s->downmix_coeffs[j][0];

            v1 += s->output[j][i] * s->downmix_coeffs[j][1];

        }

        v0 /= s->downmix_coeff_sum[0];

        v1 /= s->downmix_coeff_sum[1];

        if(s->output_mode == AC3_CHMODE_MONO) {

            s->output[0][i] = (v0 + v1) * LEVEL_MINUS_3DB;

        } else if(s->output_mode == AC3_CHMODE_STEREO) {

            s->output[0][i] = v0;

            s->output[1][i] = v1;

        }

    }

}


static void virtio_net_set_features(VirtIODevice *vdev, uint64_t features)

{

    VirtIONet *n = VIRTIO_NET(vdev);

    int i;

    virtio_net_set_multiqueue(n,

                              __virtio_has_feature(features, VIRTIO_NET_F_MQ));

    virtio_net_set_mrg_rx_bufs(n,

                               __virtio_has_feature(features,

                                                    VIRTIO_NET_F_MRG_RXBUF),

                               __virtio_has_feature(features,

                                                    VIRTIO_F_VERSION_1));

    if (n->has_vnet_hdr) {

        n->curr_guest_offloads =

            virtio_net_guest_offloads_by_features(features);

        virtio_net_apply_guest_offloads(n);

    }

    for (i = 0;  i < n->max_queues; i++) {

        NetClientState *nc = qemu_get_subqueue(n->nic, i);

        if (!get_vhost_net(nc->peer)) {

            continue;

        }

        vhost_net_ack_features(get_vhost_net(nc->peer), features);

    }

    if (__virtio_has_feature(features, VIRTIO_NET_F_CTRL_VLAN)) {

        memset(n->vlans, 0, MAX_VLAN >> 3);

    } else {

        memset(n->vlans, 0xff, MAX_VLAN >> 3);

    }

}


int postcopy_ram_enable_notify(MigrationIncomingState *mis)

{

    /* Open the fd for the kernel to give us userfaults */

    mis->userfault_fd = syscall(__NR_userfaultfd, O_CLOEXEC | O_NONBLOCK);

    if (mis->userfault_fd == -1) {

        error_report("%s: Failed to open userfault fd: %s", __func__,

                     strerror(errno));

        return -1;

    }

    /*

     * Although the host check already tested the API, we need to

     * do the check again as an ABI handshake on the new fd.

     */

    if (!ufd_version_check(mis->userfault_fd)) {

        return -1;

    }

    /* Now an eventfd we use to tell the fault-thread to quit */

    mis->userfault_quit_fd = eventfd(0, EFD_CLOEXEC);

    if (mis->userfault_quit_fd == -1) {

        error_report("%s: Opening userfault_quit_fd: %s", __func__,

                     strerror(errno));

        close(mis->userfault_fd);

        return -1;

    }

    qemu_sem_init(&mis->fault_thread_sem, 0);

    qemu_thread_create(&mis->fault_thread, "postcopy/fault",

                       postcopy_ram_fault_thread, mis, QEMU_THREAD_JOINABLE);

    qemu_sem_wait(&mis->fault_thread_sem);

    qemu_sem_destroy(&mis->fault_thread_sem);

    mis->have_fault_thread = true;

    /* Mark so that we get notified of accesses to unwritten areas */

    if (qemu_ram_foreach_block(ram_block_enable_notify, mis)) {

        return -1;

    }

    /*

     * Ballooning can mark pages as absent while we're postcopying

     * that would cause false userfaults.

     */

    qemu_balloon_inhibit(true);

    trace_postcopy_ram_enable_notify();

    return 0;

}


void qio_dns_resolver_lookup_async(QIODNSResolver *resolver,

                                   SocketAddress *addr,

                                   QIOTaskFunc func,

                                   gpointer opaque,

                                   GDestroyNotify notify)

{

    QIOTask *task;

    struct QIODNSResolverLookupData *data =

        g_new0(struct QIODNSResolverLookupData, 1);

    data->addr = QAPI_CLONE(SocketAddress, addr);

    task = qio_task_new(OBJECT(resolver), func, opaque, notify);

    qio_task_run_in_thread(task,

                           qio_dns_resolver_lookup_worker,

                           data,

                           qio_dns_resolver_lookup_data_free);

}


static void vhost_iommu_region_add(MemoryListener *listener,

                                   MemoryRegionSection *section)

{

    struct vhost_dev *dev = container_of(listener, struct vhost_dev,

                                         iommu_listener);

    struct vhost_iommu *iommu;

    if (!memory_region_is_iommu(section->mr)) {

        return;

    }

    iommu = g_malloc0(sizeof(*iommu));

    iommu->n.notify = vhost_iommu_unmap_notify;

    iommu->n.notifier_flags = IOMMU_NOTIFIER_UNMAP;

    iommu->mr = section->mr;

    iommu->iommu_offset = section->offset_within_address_space -

                          section->offset_within_region;

    iommu->hdev = dev;

    memory_region_register_iommu_notifier(section->mr, &iommu->n);

    QLIST_INSERT_HEAD(&dev->iommu_list, iommu, iommu_next);

    /* TODO: can replay help performance here? */

}


static void arm_timer_write(void *opaque, target_phys_addr_t offset,

                            uint32_t value)

{

    arm_timer_state *s = (arm_timer_state *)opaque;

    int freq;

    switch (offset >> 2) {

    case 0: /* TimerLoad */

        s->limit = value;

        arm_timer_recalibrate(s, 1);

        break;

    case 1: /* TimerValue */

        /* ??? Linux seems to want to write to this readonly register.

           Ignore it.  */

        break;

    case 2: /* TimerControl */

        if (s->control & TIMER_CTRL_ENABLE) {

            /* Pause the timer if it is running.  This may cause some

               inaccuracy dure to rounding, but avoids a whole lot of other

               messyness.  */

            ptimer_stop(s->timer);

        }

        s->control = value;

        freq = s->freq;

        /* ??? Need to recalculate expiry time after changing divisor.  */

        switch ((value >> 2) & 3) {

        case 1: freq >>= 4; break;

        case 2: freq >>= 8; break;

        }

        arm_timer_recalibrate(s, 0);

        ptimer_set_freq(s->timer, freq);

        if (s->control & TIMER_CTRL_ENABLE) {

            /* Restart the timer if still enabled.  */

            ptimer_run(s->timer, (s->control & TIMER_CTRL_ONESHOT) != 0);

        }

        break;

    case 3: /* TimerIntClr */

        s->int_level = 0;

        break;

    case 6: /* TimerBGLoad */

        s->limit = value;

        arm_timer_recalibrate(s, 0);

        break;

    default:

        hw_error("arm_timer_write: Bad offset %x\n", (int)offset);

    }

    arm_timer_update(s);

}


static void qed_plug_allocating_write_reqs(BDRVQEDState *s)

{

    assert(!s->allocating_write_reqs_plugged);

    s->allocating_write_reqs_plugged = true;

}


static inline void t_gen_swapr(TCGv d, TCGv s)

{

	struct {

		int shift; /* LSL when positive, LSR when negative.  */

		uint32_t mask;

	} bitrev [] = {

		{7, 0x80808080},

		{5, 0x40404040},

		{3, 0x20202020},

		{1, 0x10101010},

		{-1, 0x08080808},

		{-3, 0x04040404},

		{-5, 0x02020202},

		{-7, 0x01010101}

	};

	int i;

	TCGv t, org_s;

	/* d and s refer the same object.  */

	t = tcg_temp_new(TCG_TYPE_TL);

	org_s = tcg_temp_new(TCG_TYPE_TL);

	tcg_gen_mov_tl(org_s, s);

	tcg_gen_shli_tl(t, org_s,  bitrev[0].shift);

	tcg_gen_andi_tl(d, t,  bitrev[0].mask);

	for (i = 1; i < sizeof bitrev / sizeof bitrev[0]; i++) {

		if (bitrev[i].shift >= 0) {

			tcg_gen_shli_tl(t, org_s,  bitrev[i].shift);

		} else {

			tcg_gen_shri_tl(t, org_s,  -bitrev[i].shift);

		}

		tcg_gen_andi_tl(t, t,  bitrev[i].mask);

		tcg_gen_or_tl(d, d, t);

	}

	tcg_temp_free(t);

	tcg_temp_free(org_s);

}