static av_always_inline void emulated_edge_mc(uint8_t *buf, const uint8_t *src,

                                              int linesize,

                                              int block_w, int block_h,

                                              int src_x, int src_y,

                                              int w, int h,

                                              emu_edge_core_func *core_fn)

{

    int start_y, start_x, end_y, end_x, src_y_add = 0;

    if (src_y >= h) {

        src_y_add = h - 1 - src_y;

        src_y     = h - 1;

    } else if (src_y <= -block_h) {

        src_y_add = 1 - block_h - src_y;

        src_y     = 1 - block_h;

    }

    if (src_x >= w) {

        src   += w - 1 - src_x;

        src_x  = w - 1;

    } else if (src_x <= -block_w) {

        src   += 1 - block_w - src_x;

        src_x  = 1 - block_w;

    }

    start_y = FFMAX(0, -src_y);

    start_x = FFMAX(0, -src_x);

    end_y   = FFMIN(block_h, h-src_y);

    end_x   = FFMIN(block_w, w-src_x);

    av_assert2(start_x < end_x && block_w > 0);

    av_assert2(start_y < end_y && block_h > 0);

    // fill in the to-be-copied part plus all above/below

    src += (src_y_add + start_y) * linesize + start_x;

    buf += start_x;

    core_fn(buf, src, linesize, start_y, end_y,

            block_h, start_x, end_x, block_w);

}


static av_cold int init_bundles(BinkContext *c)

{

    int bw, bh, blocks;

    int i;

    bw = (c->avctx->width  + 7) >> 3;

    bh = (c->avctx->height + 7) >> 3;

    blocks = bw * bh;

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

        c->bundle[i].data = av_malloc(blocks * 64);

        if (!c->bundle[i].data)

            return AVERROR(ENOMEM);

        c->bundle[i].data_end = c->bundle[i].data + blocks * 64;

    }

    return 0;

}


static void quorum_vote(QuorumAIOCB *acb)

{

    bool quorum = true;

    int i, j, ret;

    QuorumVoteValue hash;

    BDRVQuorumState *s = acb->common.bs->opaque;

    QuorumVoteVersion *winner;

    if (quorum_has_too_much_io_failed(acb)) {

        return;

    }

    /* get the index of the first successful read */

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

        if (!acb->qcrs[i].ret) {

            break;

        }

    }

    assert(i < s->num_children);

    /* compare this read with all other successful reads stopping at quorum

     * failure

     */

    for (j = i + 1; j < s->num_children; j++) {

        if (acb->qcrs[j].ret) {

            continue;

        }

        quorum = quorum_compare(acb, &acb->qcrs[i].qiov, &acb->qcrs[j].qiov);

        if (!quorum) {

            break;

       }

    }

    /* Every successful read agrees */

    if (quorum) {

        quorum_copy_qiov(acb->qiov, &acb->qcrs[i].qiov);

        return;

    }

    /* compute hashes for each successful read, also store indexes */

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

        if (acb->qcrs[i].ret) {

            continue;

        }

        ret = quorum_compute_hash(acb, i, &hash);

        /* if ever the hash computation failed */

        if (ret < 0) {

            acb->vote_ret = ret;

            goto free_exit;

        }

        quorum_count_vote(&acb->votes, &hash, i);

    }

    /* vote to select the most represented version */

    winner = quorum_get_vote_winner(&acb->votes);

    /* if the winner count is smaller than threshold the read fails */

    if (winner->vote_count < s->threshold) {

        quorum_report_failure(acb);

        acb->vote_ret = -EIO;

        goto free_exit;

    }

    /* we have a winner: copy it */

    quorum_copy_qiov(acb->qiov, &acb->qcrs[winner->index].qiov);

    /* some versions are bad print them */

    quorum_report_bad_versions(s, acb, &winner->value);

free_exit:

    /* free lists */

    quorum_free_vote_list(&acb->votes);

}


static void stellaris_init(const char *kernel_filename, const char *cpu_model,

                           stellaris_board_info *board)

{

    static const int uart_irq[] = {5, 6, 33, 34};

    static const int timer_irq[] = {19, 21, 23, 35};

    static const uint32_t gpio_addr[7] =

      { 0x40004000, 0x40005000, 0x40006000, 0x40007000,

        0x40024000, 0x40025000, 0x40026000};

    static const int gpio_irq[7] = {0, 1, 2, 3, 4, 30, 31};

    qemu_irq *pic;

    DeviceState *gpio_dev[7];

    qemu_irq gpio_in[7][8];

    qemu_irq gpio_out[7][8];

    qemu_irq adc;

    int sram_size;

    int flash_size;

    I2CBus *i2c;

    DeviceState *dev;

    int i;

    int j;

    MemoryRegion *sram = g_new(MemoryRegion, 1);

    MemoryRegion *flash = g_new(MemoryRegion, 1);

    MemoryRegion *system_memory = get_system_memory();

    flash_size = (((board->dc0 & 0xffff) + 1) << 1) * 1024;

    sram_size = ((board->dc0 >> 18) + 1) * 1024;

    /* Flash programming is done via the SCU, so pretend it is ROM.  */

    memory_region_init_ram(flash, NULL, "stellaris.flash", flash_size,

                           &error_abort);

    vmstate_register_ram_global(flash);

    memory_region_set_readonly(flash, true);

    memory_region_add_subregion(system_memory, 0, flash);

    memory_region_init_ram(sram, NULL, "stellaris.sram", sram_size,

                           &error_abort);

    vmstate_register_ram_global(sram);

    memory_region_add_subregion(system_memory, 0x20000000, sram);

    pic = armv7m_init(system_memory, flash_size, NUM_IRQ_LINES,

                      kernel_filename, cpu_model);

    if (board->dc1 & (1 << 16)) {

        dev = sysbus_create_varargs(TYPE_STELLARIS_ADC, 0x40038000,

                                    pic[14], pic[15], pic[16], pic[17], NULL);

        adc = qdev_get_gpio_in(dev, 0);

    } else {

        adc = NULL;

    }

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

        if (board->dc2 & (0x10000 << i)) {

            dev = sysbus_create_simple(TYPE_STELLARIS_GPTM,

                                       0x40030000 + i * 0x1000,

                                       pic[timer_irq[i]]);

            /* TODO: This is incorrect, but we get away with it because

               the ADC output is only ever pulsed.  */

            qdev_connect_gpio_out(dev, 0, adc);

        }

    }

    stellaris_sys_init(0x400fe000, pic[28], board, nd_table[0].macaddr.a);

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

        if (board->dc4 & (1 << i)) {

            gpio_dev[i] = sysbus_create_simple("pl061_luminary", gpio_addr[i],

                                               pic[gpio_irq[i]]);

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

                gpio_in[i][j] = qdev_get_gpio_in(gpio_dev[i], j);

                gpio_out[i][j] = NULL;

            }

        }

    }

    if (board->dc2 & (1 << 12)) {

        dev = sysbus_create_simple(TYPE_STELLARIS_I2C, 0x40020000, pic[8]);

        i2c = (I2CBus *)qdev_get_child_bus(dev, "i2c");

        if (board->peripherals & BP_OLED_I2C) {

            i2c_create_slave(i2c, "ssd0303", 0x3d);

        }

    }

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

        if (board->dc2 & (1 << i)) {

            sysbus_create_simple("pl011_luminary", 0x4000c000 + i * 0x1000,

                                 pic[uart_irq[i]]);

        }

    }

    if (board->dc2 & (1 << 4)) {

        dev = sysbus_create_simple("pl022", 0x40008000, pic[7]);

        if (board->peripherals & BP_OLED_SSI) {

            void *bus;

            DeviceState *sddev;

            DeviceState *ssddev;

            /* Some boards have both an OLED controller and SD card connected to

             * the same SSI port, with the SD card chip select connected to a

             * GPIO pin.  Technically the OLED chip select is connected to the

             * SSI Fss pin.  We do not bother emulating that as both devices

             * should never be selected simultaneously, and our OLED controller

             * ignores stray 0xff commands that occur when deselecting the SD

             * card.

             */

            bus = qdev_get_child_bus(dev, "ssi");

            sddev = ssi_create_slave(bus, "ssi-sd");

            ssddev = ssi_create_slave(bus, "ssd0323");

            gpio_out[GPIO_D][0] = qemu_irq_split(

                    qdev_get_gpio_in_named(sddev, SSI_GPIO_CS, 0),

                    qdev_get_gpio_in_named(ssddev, SSI_GPIO_CS, 0));

            gpio_out[GPIO_C][7] = qdev_get_gpio_in(ssddev, 0);

            /* Make sure the select pin is high.  */

            qemu_irq_raise(gpio_out[GPIO_D][0]);

        }

    }

    if (board->dc4 & (1 << 28)) {

        DeviceState *enet;

        qemu_check_nic_model(&nd_table[0], "stellaris");

        enet = qdev_create(NULL, "stellaris_enet");

        qdev_set_nic_properties(enet, &nd_table[0]);

        qdev_init_nofail(enet);

        sysbus_mmio_map(SYS_BUS_DEVICE(enet), 0, 0x40048000);

        sysbus_connect_irq(SYS_BUS_DEVICE(enet), 0, pic[42]);

    }

    if (board->peripherals & BP_GAMEPAD) {

        qemu_irq gpad_irq[5];

        static const int gpad_keycode[5] = { 0xc8, 0xd0, 0xcb, 0xcd, 0x1d };

        gpad_irq[0] = qemu_irq_invert(gpio_in[GPIO_E][0]); /* up */

        gpad_irq[1] = qemu_irq_invert(gpio_in[GPIO_E][1]); /* down */

        gpad_irq[2] = qemu_irq_invert(gpio_in[GPIO_E][2]); /* left */

        gpad_irq[3] = qemu_irq_invert(gpio_in[GPIO_E][3]); /* right */

        gpad_irq[4] = qemu_irq_invert(gpio_in[GPIO_F][1]); /* select */

        stellaris_gamepad_init(5, gpad_irq, gpad_keycode);

    }

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

        if (board->dc4 & (1 << i)) {

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

                if (gpio_out[i][j]) {

                    qdev_connect_gpio_out(gpio_dev[i], j, gpio_out[i][j]);

                }

            }

        }

    }

}


void cpu_exec_init(CPUState *env)

{

    CPUState **penv;

    int cpu_index;

    if (!code_gen_ptr) {

        code_gen_ptr = code_gen_buffer;

        page_init();

        io_mem_init();

    }

    env->next_cpu = NULL;

    penv = &first_cpu;

    cpu_index = 0;

    while (*penv != NULL) {

        penv = (CPUState **)&(*penv)->next_cpu;

        cpu_index++;

    }

    env->cpu_index = cpu_index;

    *penv = env;

}


static inline void RENAME(yuv422ptoyuy2)(const uint8_t *ysrc, const uint8_t *usrc, const uint8_t *vsrc, uint8_t *dst,

	long width, long height,

	long lumStride, long chromStride, long dstStride)

{

	RENAME(yuvPlanartoyuy2)(ysrc, usrc, vsrc, dst, width, height, lumStride, chromStride, dstStride, 1);

}


static inline bool handler_is_async(const mon_cmd_t *cmd)

{

    return cmd->flags & MONITOR_CMD_ASYNC;

}


static int vqa_decode_init(AVCodecContext *avctx)

{

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

    unsigned char *vqa_header;

    int i, j, codebook_index;;

    s->avctx = avctx;

    avctx->pix_fmt = PIX_FMT_PAL8;

    avctx->has_b_frames = 0;

    dsputil_init(&s->dsp, avctx);

    /* make sure the extradata made it */

    if (s->avctx->extradata_size != VQA_HEADER_SIZE) {

        av_log(s->avctx, AV_LOG_ERROR, "  VQA video: expected extradata size of %d\n", VQA_HEADER_SIZE);

    /* load up the VQA parameters from the header */

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

    s->vqa_version = vqa_header[0];

    s->width = LE_16(&vqa_header[6]);

    s->height = LE_16(&vqa_header[8]);

    s->vector_width = vqa_header[10];

    s->vector_height = vqa_header[11];

    s->partial_count = s->partial_countdown = vqa_header[13];

    /* the vector dimensions have to meet very stringent requirements */

    if ((s->vector_width != 4) ||

        ((s->vector_height != 2) && (s->vector_height != 4))) {

        /* return without further initialization */

    /* allocate codebooks */

    s->codebook_size = MAX_CODEBOOK_SIZE;

    s->codebook = av_malloc(s->codebook_size);

    s->next_codebook_buffer = av_malloc(s->codebook_size);

    /* initialize the solid-color vectors */

    if (s->vector_height == 4) {

        codebook_index = 0xFF00 * 16;

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

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

                s->codebook[codebook_index++] = i;

    } else {

        codebook_index = 0xF00 * 8;

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

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

                s->codebook[codebook_index++] = i;

    s->next_codebook_buffer_index = 0;

    /* allocate decode buffer */

    s->decode_buffer_size = (s->width / s->vector_width) *

        (s->height / s->vector_height) * 2;

    s->decode_buffer = av_malloc(s->decode_buffer_size);

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

    return 0;


static int open_output_file(OptionsContext *o, const char *filename)

{

    AVFormatContext *oc;

    int i, j, err;

    AVOutputFormat *file_oformat;

    OutputFile *of;

    OutputStream *ost;

    InputStream  *ist;

    AVDictionary *unused_opts = NULL;

    AVDictionaryEntry *e = NULL;

    if (configure_complex_filters() < 0) {

        av_log(NULL, AV_LOG_FATAL, "Error configuring filters.\n");

        exit_program(1);

    }

    if (o->stop_time != INT64_MAX && o->recording_time != INT64_MAX) {

        o->stop_time = INT64_MAX;

        av_log(NULL, AV_LOG_WARNING, "-t and -to cannot be used together; using -t.\n");

    }

    if (o->stop_time != INT64_MAX && o->recording_time == INT64_MAX) {

        int64_t start_time = o->start_time == AV_NOPTS_VALUE ? 0 : o->start_time;

        if (o->stop_time <= start_time) {

            av_log(NULL, AV_LOG_WARNING, "-to value smaller than -ss; ignoring -to.\n");

            o->stop_time = INT64_MAX;

        } else {

            o->recording_time = o->stop_time - start_time;

        }

    }

    GROW_ARRAY(output_files, nb_output_files);

    of = av_mallocz(sizeof(*of));

    if (!of)

        exit_program(1);

    output_files[nb_output_files - 1] = of;

    of->ost_index      = nb_output_streams;

    of->recording_time = o->recording_time;

    of->start_time     = o->start_time;

    of->limit_filesize = o->limit_filesize;

    of->shortest       = o->shortest;

    av_dict_copy(&of->opts, o->g->format_opts, 0);

    if (!strcmp(filename, "-"))

        filename = "pipe:";

    err = avformat_alloc_output_context2(&oc, NULL, o->format, filename);

    if (!oc) {

        print_error(filename, err);

        exit_program(1);

    }

    of->ctx = oc;

    if (o->recording_time != INT64_MAX)

        oc->duration = o->recording_time;

    file_oformat= oc->oformat;

    oc->interrupt_callback = int_cb;

    /* create streams for all unlabeled output pads */

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

        FilterGraph *fg = filtergraphs[i];

        for (j = 0; j < fg->nb_outputs; j++) {

            OutputFilter *ofilter = fg->outputs[j];

            if (!ofilter->out_tmp || ofilter->out_tmp->name)

                continue;

            switch (avfilter_pad_get_type(ofilter->out_tmp->filter_ctx->output_pads,

                                          ofilter->out_tmp->pad_idx)) {

            case AVMEDIA_TYPE_VIDEO:    o->video_disable    = 1; break;

            case AVMEDIA_TYPE_AUDIO:    o->audio_disable    = 1; break;

            case AVMEDIA_TYPE_SUBTITLE: o->subtitle_disable = 1; break;

            }

            init_output_filter(ofilter, o, oc);

        }

    }

    /* ffserver seeking with date=... needs a date reference */

    if (!strcmp(file_oformat->name, "ffm") &&

        av_strstart(filename, "http:", NULL)) {

        int err = parse_option(o, "metadata", "creation_time=now", options);

        if (err < 0) {

            print_error(filename, err);

            exit_program(1);

        }

    }

    if (!strcmp(file_oformat->name, "ffm") && !override_ffserver &&

        av_strstart(filename, "http:", NULL)) {

        int j;

        /* special case for files sent to ffserver: we get the stream

           parameters from ffserver */

        int err = read_ffserver_streams(o, oc, filename);

        if (err < 0) {

            print_error(filename, err);

            exit_program(1);

        }

        for(j = nb_output_streams - oc->nb_streams; j < nb_output_streams; j++) {

            ost = output_streams[j];

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

                ist = input_streams[i];

                if(ist->st->codec->codec_type == ost->st->codec->codec_type){

                    ost->sync_ist= ist;

                    ost->source_index= i;

                    if(ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO) ost->avfilter = av_strdup("anull");

                    if(ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) ost->avfilter = av_strdup("null");

                    ist->discard = 0;

                    ist->st->discard = AVDISCARD_NONE;

                    break;

                }

            }

            if(!ost->sync_ist){

                av_log(NULL, AV_LOG_FATAL, "Missing %s stream which is required by this ffm\n", av_get_media_type_string(ost->st->codec->codec_type));

                exit_program(1);

            }

        }

    } else if (!o->nb_stream_maps) {

        char *subtitle_codec_name = NULL;

        /* pick the "best" stream of each type */

        /* video: highest resolution */

        if (!o->video_disable && oc->oformat->video_codec != AV_CODEC_ID_NONE) {

            int area = 0, idx = -1;

            int qcr = avformat_query_codec(oc->oformat, oc->oformat->video_codec, 0);

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

                int new_area;

                ist = input_streams[i];

                new_area = ist->st->codec->width * ist->st->codec->height;

                if((qcr!=MKTAG('A', 'P', 'I', 'C')) && (ist->st->disposition & AV_DISPOSITION_ATTACHED_PIC))

                    new_area = 1;

                if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&

                    new_area > area) {

                    if((qcr==MKTAG('A', 'P', 'I', 'C')) && !(ist->st->disposition & AV_DISPOSITION_ATTACHED_PIC))

                        continue;

                    area = new_area;

                    idx = i;

                }

            }

            if (idx >= 0)

                new_video_stream(o, oc, idx);

        }

        /* audio: most channels */

        if (!o->audio_disable && oc->oformat->audio_codec != AV_CODEC_ID_NONE) {

            int channels = 0, idx = -1;

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

                ist = input_streams[i];

                if (ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&

                    ist->st->codec->channels > channels) {

                    channels = ist->st->codec->channels;

                    idx = i;

                }

            }

            if (idx >= 0)

                new_audio_stream(o, oc, idx);

        }

        /* subtitles: pick first */

        MATCH_PER_TYPE_OPT(codec_names, str, subtitle_codec_name, oc, "s");

        if (!o->subtitle_disable && (oc->oformat->subtitle_codec != AV_CODEC_ID_NONE || subtitle_codec_name)) {

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

                if (input_streams[i]->st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {

                    new_subtitle_stream(o, oc, i);

                    break;

                }

        }

        /* do something with data? */

    } else {

        for (i = 0; i < o->nb_stream_maps; i++) {

            StreamMap *map = &o->stream_maps[i];

            if (map->disabled)

                continue;

            if (map->linklabel) {

                FilterGraph *fg;

                OutputFilter *ofilter = NULL;

                int j, k;

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

                    fg = filtergraphs[j];

                    for (k = 0; k < fg->nb_outputs; k++) {

                        AVFilterInOut *out = fg->outputs[k]->out_tmp;

                        if (out && !strcmp(out->name, map->linklabel)) {

                            ofilter = fg->outputs[k];

                            goto loop_end;

                        }

                    }

                }

loop_end:

                if (!ofilter) {

                    av_log(NULL, AV_LOG_FATAL, "Output with label '%s' does not exist "

                           "in any defined filter graph, or was already used elsewhere.\n", map->linklabel);

                    exit_program(1);

                }

                init_output_filter(ofilter, o, oc);

            } else {

                int src_idx = input_files[map->file_index]->ist_index + map->stream_index;

                ist = input_streams[input_files[map->file_index]->ist_index + map->stream_index];

                if(o->subtitle_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE)

                    continue;

                if(o->   audio_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)

                    continue;

                if(o->   video_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO)

                    continue;

                if(o->    data_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_DATA)

                    continue;

                switch (ist->st->codec->codec_type) {

                case AVMEDIA_TYPE_VIDEO:      ost = new_video_stream     (o, oc, src_idx); break;

                case AVMEDIA_TYPE_AUDIO:      ost = new_audio_stream     (o, oc, src_idx); break;

                case AVMEDIA_TYPE_SUBTITLE:   ost = new_subtitle_stream  (o, oc, src_idx); break;

                case AVMEDIA_TYPE_DATA:       ost = new_data_stream      (o, oc, src_idx); break;

                case AVMEDIA_TYPE_ATTACHMENT: ost = new_attachment_stream(o, oc, src_idx); break;

                default:

                    av_log(NULL, AV_LOG_FATAL, "Cannot map stream #%d:%d - unsupported type.\n",

                           map->file_index, map->stream_index);

                    exit_program(1);

                }

            }

        }

    }

    /* handle attached files */

    for (i = 0; i < o->nb_attachments; i++) {

        AVIOContext *pb;

        uint8_t *attachment;

        const char *p;

        int64_t len;

        if ((err = avio_open2(&pb, o->attachments[i], AVIO_FLAG_READ, &int_cb, NULL)) < 0) {

            av_log(NULL, AV_LOG_FATAL, "Could not open attachment file %s.\n",

                   o->attachments[i]);

            exit_program(1);

        }

        if ((len = avio_size(pb)) <= 0) {

            av_log(NULL, AV_LOG_FATAL, "Could not get size of the attachment %s.\n",

                   o->attachments[i]);

            exit_program(1);

        }

        if (!(attachment = av_malloc(len))) {

            av_log(NULL, AV_LOG_FATAL, "Attachment %s too large to fit into memory.\n",

                   o->attachments[i]);

            exit_program(1);

        }

        avio_read(pb, attachment, len);

        ost = new_attachment_stream(o, oc, -1);

        ost->stream_copy               = 0;

        ost->attachment_filename       = o->attachments[i];

        ost->finished                  = 1;

        ost->st->codec->extradata      = attachment;

        ost->st->codec->extradata_size = len;

        p = strrchr(o->attachments[i], '/');

        av_dict_set(&ost->st->metadata, "filename", (p && *p) ? p + 1 : o->attachments[i], AV_DICT_DONT_OVERWRITE);

        avio_close(pb);

    }

    for (i = nb_output_streams - oc->nb_streams; i < nb_output_streams; i++) { //for all streams of this output file

        AVDictionaryEntry *e;

        ost = output_streams[i];

        if ((ost->stream_copy || ost->attachment_filename)

            && (e = av_dict_get(o->g->codec_opts, "flags", NULL, AV_DICT_IGNORE_SUFFIX))

            && (!e->key[5] || check_stream_specifier(oc, ost->st, e->key+6)))

            if (av_opt_set(ost->st->codec, "flags", e->value, 0) < 0)

                exit_program(1);

    }

    /* check if all codec options have been used */

    unused_opts = strip_specifiers(o->g->codec_opts);

    for (i = of->ost_index; i < nb_output_streams; i++) {

        e = NULL;

        while ((e = av_dict_get(output_streams[i]->opts, "", e,

                                AV_DICT_IGNORE_SUFFIX)))

            av_dict_set(&unused_opts, e->key, NULL, 0);

    }

    e = NULL;

    while ((e = av_dict_get(unused_opts, "", e, AV_DICT_IGNORE_SUFFIX))) {

        const AVClass *class = avcodec_get_class();

        const AVOption *option = av_opt_find(&class, e->key, NULL, 0,

                                             AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ);

        if (!option)

            continue;

        if (!(option->flags & AV_OPT_FLAG_ENCODING_PARAM)) {

            av_log(NULL, AV_LOG_ERROR, "Codec AVOption %s (%s) specified for "

                   "output file #%d (%s) is not an encoding option.\n", e->key,

                   option->help ? option->help : "", nb_output_files - 1,

                   filename);

            exit_program(1);

        }

        // gop_timecode is injected by generic code but not always used

        if (!strcmp(e->key, "gop_timecode"))

            continue;

        av_log(NULL, AV_LOG_WARNING, "Codec AVOption %s (%s) specified for "

               "output file #%d (%s) has not been used for any stream. The most "

               "likely reason is either wrong type (e.g. a video option with "

               "no video streams) or that it is a private option of some encoder "

               "which was not actually used for any stream.\n", e->key,

               option->help ? option->help : "", nb_output_files - 1, filename);

    }

    av_dict_free(&unused_opts);

    /* check filename in case of an image number is expected */

    if (oc->oformat->flags & AVFMT_NEEDNUMBER) {

        if (!av_filename_number_test(oc->filename)) {

            print_error(oc->filename, AVERROR(EINVAL));

            exit_program(1);

        }

    }

    if (!(oc->oformat->flags & AVFMT_NOFILE)) {

        /* test if it already exists to avoid losing precious files */

        assert_file_overwrite(filename);

        /* open the file */

        if ((err = avio_open2(&oc->pb, filename, AVIO_FLAG_WRITE,

                              &oc->interrupt_callback,

                              &of->opts)) < 0) {

            print_error(filename, err);

            exit_program(1);

        }

    } else if (strcmp(oc->oformat->name, "image2")==0 && !av_filename_number_test(filename))

        assert_file_overwrite(filename);

    if (o->mux_preload) {

        uint8_t buf[64];

        snprintf(buf, sizeof(buf), "%d", (int)(o->mux_preload*AV_TIME_BASE));

        av_dict_set(&of->opts, "preload", buf, 0);

    }

    oc->max_delay = (int)(o->mux_max_delay * AV_TIME_BASE);

    /* copy metadata */

    for (i = 0; i < o->nb_metadata_map; i++) {

        char *p;

        int in_file_index = strtol(o->metadata_map[i].u.str, &p, 0);

        if (in_file_index >= nb_input_files) {

            av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d while processing metadata maps\n", in_file_index);

            exit_program(1);

        }

        copy_metadata(o->metadata_map[i].specifier, *p ? p + 1 : p, oc,

                      in_file_index >= 0 ?

                      input_files[in_file_index]->ctx : NULL, o);

    }

    /* copy chapters */

    if (o->chapters_input_file >= nb_input_files) {

        if (o->chapters_input_file == INT_MAX) {

            /* copy chapters from the first input file that has them*/

            o->chapters_input_file = -1;

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

                if (input_files[i]->ctx->nb_chapters) {

                    o->chapters_input_file = i;

                    break;

                }

        } else {

            av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d in chapter mapping.\n",

                   o->chapters_input_file);

            exit_program(1);

        }

    }

    if (o->chapters_input_file >= 0)

        copy_chapters(input_files[o->chapters_input_file], of,

                      !o->metadata_chapters_manual);

    /* copy global metadata by default */

    if (!o->metadata_global_manual && nb_input_files){

        av_dict_copy(&oc->metadata, input_files[0]->ctx->metadata,

                     AV_DICT_DONT_OVERWRITE);

        if(o->recording_time != INT64_MAX)

            av_dict_set(&oc->metadata, "duration", NULL, 0);

        av_dict_set(&oc->metadata, "creation_time", NULL, 0);

    }

    if (!o->metadata_streams_manual)

        for (i = of->ost_index; i < nb_output_streams; i++) {

            InputStream *ist;

            if (output_streams[i]->source_index < 0)         /* this is true e.g. for attached files */

                continue;

            ist = input_streams[output_streams[i]->source_index];

            av_dict_copy(&output_streams[i]->st->metadata, ist->st->metadata, AV_DICT_DONT_OVERWRITE);

        }

    /* process manually set metadata */

    for (i = 0; i < o->nb_metadata; i++) {

        AVDictionary **m;

        char type, *val;

        const char *stream_spec;

        int index = 0, j, ret = 0;

        val = strchr(o->metadata[i].u.str, '=');

        if (!val) {

            av_log(NULL, AV_LOG_FATAL, "No '=' character in metadata string %s.\n",

                   o->metadata[i].u.str);

            exit_program(1);

        }

        *val++ = 0;

        parse_meta_type(o->metadata[i].specifier, &type, &index, &stream_spec);

        if (type == 's') {

            for (j = 0; j < oc->nb_streams; j++) {

                if ((ret = check_stream_specifier(oc, oc->streams[j], stream_spec)) > 0) {

                    av_dict_set(&oc->streams[j]->metadata, o->metadata[i].u.str, *val ? val : NULL, 0);

                } else if (ret < 0)

                    exit_program(1);

            }

        }

        else {

            switch (type) {

            case 'g':

                m = &oc->metadata;

                break;

            case 'c':

                if (index < 0 || index >= oc->nb_chapters) {

                    av_log(NULL, AV_LOG_FATAL, "Invalid chapter index %d in metadata specifier.\n", index);

                    exit_program(1);

                }

                m = &oc->chapters[index]->metadata;

                break;

            default:

                av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", o->metadata[i].specifier);

                exit_program(1);

            }

            av_dict_set(m, o->metadata[i].u.str, *val ? val : NULL, 0);

        }

    }

    return 0;

}


static bool logic_imm_decode_wmask(uint64_t *result, unsigned int immn,

                                   unsigned int imms, unsigned int immr)

{

    uint64_t mask;

    unsigned e, levels, s, r;

    int len;

    assert(immn < 2 && imms < 64 && immr < 64);

    /* The bit patterns we create here are 64 bit patterns which

     * are vectors of identical elements of size e = 2, 4, 8, 16, 32 or

     * 64 bits each. Each element contains the same value: a run

     * of between 1 and e-1 non-zero bits, rotated within the

     * element by between 0 and e-1 bits.

     *

     * The element size and run length are encoded into immn (1 bit)

     * and imms (6 bits) as follows:

     * 64 bit elements: immn = 1, imms = <length of run - 1>

     * 32 bit elements: immn = 0, imms = 0 : <length of run - 1>

     * 16 bit elements: immn = 0, imms = 10 : <length of run - 1>

     *  8 bit elements: immn = 0, imms = 110 : <length of run - 1>

     *  4 bit elements: immn = 0, imms = 1110 : <length of run - 1>

     *  2 bit elements: immn = 0, imms = 11110 : <length of run - 1>

     * Notice that immn = 0, imms = 11111x is the only combination

     * not covered by one of the above options; this is reserved.

     * Further, <length of run - 1> all-ones is a reserved pattern.

     *

     * In all cases the rotation is by immr % e (and immr is 6 bits).

     */

    /* First determine the element size */

    len = 31 - clz32((immn << 6) | (~imms & 0x3f));

    if (len < 1) {

        /* This is the immn == 0, imms == 0x11111x case */

        return false;

    }

    e = 1 << len;

    levels = e - 1;

    s = imms & levels;

    r = immr & levels;

    if (s == levels) {

        /* <length of run - 1> mustn't be all-ones. */

        return false;

    }

    /* Create the value of one element: s+1 set bits rotated

     * by r within the element (which is e bits wide)...

     */

    mask = bitmask64(s + 1);

    mask = (mask >> r) | (mask << (e - r));

    /* ...then replicate the element over the whole 64 bit value */

    mask = bitfield_replicate(mask, e);

    *result = mask;

    return true;

}


static int add_candidate_ref(HEVCContext *s, RefPicList *list,

                             int poc, int ref_flag)

{

    HEVCFrame *ref = find_ref_idx(s, poc);

    if (ref == s->ref)

        return AVERROR_INVALIDDATA;

    if (!ref) {

        ref = generate_missing_ref(s, poc);

        if (!ref)

            return AVERROR(ENOMEM);

    }

    list->list[list->nb_refs] = ref->poc;

    list->ref[list->nb_refs]  = ref;

    list->nb_refs++;

    mark_ref(ref, ref_flag);

    return 0;

}


static inline void t_gen_mov_preg_TN(DisasContext *dc, int r, TCGv tn)

{

    if (r < 0 || r > 15) {

        fprintf(stderr, "wrong register write $p%d\n", r);

    }

    if (r == PR_BZ || r == PR_WZ || r == PR_DZ) {

        return;

    } else if (r == PR_SRS) {

        tcg_gen_andi_tl(cpu_PR[r], tn, 3);

    } else {

        if (r == PR_PID) {

            gen_helper_tlb_flush_pid(cpu_env, tn);

        }

        if (dc->tb_flags & S_FLAG && r == PR_SPC) {

            gen_helper_spc_write(cpu_env, tn);

        } else if (r == PR_CCS) {

            dc->cpustate_changed = 1;

        }

        tcg_gen_mov_tl(cpu_PR[r], tn);

    }

}


static int vorbis_parse_id_hdr(vorbis_context *vc){

    GetBitContext *gb=&vc->gb;

    uint_fast8_t bl0, bl1;

    if ((get_bits(gb, 8)!='v') || (get_bits(gb, 8)!='o') ||

    (get_bits(gb, 8)!='r') || (get_bits(gb, 8)!='b') ||

    (get_bits(gb, 8)!='i') || (get_bits(gb, 8)!='s')) {

        av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis id header packet corrupt (no vorbis signature). \n");

        return 1;

    }

    vc->version=get_bits_long(gb, 32);    //FIXME check 0

    vc->audio_channels=get_bits(gb, 8);   //FIXME check >0

    vc->audio_samplerate=get_bits_long(gb, 32);   //FIXME check >0

    vc->bitrate_maximum=get_bits_long(gb, 32);

    vc->bitrate_nominal=get_bits_long(gb, 32);

    vc->bitrate_minimum=get_bits_long(gb, 32);

    bl0=get_bits(gb, 4);

    bl1=get_bits(gb, 4);

    vc->blocksize[0]=(1<<bl0);

    vc->blocksize[1]=(1<<bl1);

    if (bl0>13 || bl0<6 || bl1>13 || bl1<6 || bl1<bl0) {

        av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis id header packet corrupt (illegal blocksize). \n");

        return 3;

    }

    // output format int16

    if (vc->blocksize[1]/2 * vc->audio_channels * 2 >

                                             AVCODEC_MAX_AUDIO_FRAME_SIZE) {

        av_log(vc->avccontext, AV_LOG_ERROR, "Vorbis channel count makes "

               "output packets too large.\n");

        return 4;

    }

    vc->win[0]=ff_vorbis_vwin[bl0-6];

    vc->win[1]=ff_vorbis_vwin[bl1-6];

    if(vc->exp_bias){

        int i, j;

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

            float *win = av_malloc(vc->blocksize[j]/2 * sizeof(float));

            for(i=0; i<vc->blocksize[j]/2; i++)

                win[i] = vc->win[j][i] * (1<<15);

            vc->win[j] = win;

        }

    }

    if ((get_bits1(gb)) == 0) {

        av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis id header packet corrupt (framing flag not set). \n");

        return 2;

    }

    vc->channel_residues= av_malloc((vc->blocksize[1]/2)*vc->audio_channels * sizeof(float));

    vc->channel_floors  = av_malloc((vc->blocksize[1]/2)*vc->audio_channels * sizeof(float));

    vc->saved           = av_mallocz((vc->blocksize[1]/2)*vc->audio_channels * sizeof(float));

    vc->ret             = av_malloc((vc->blocksize[1]/2)*vc->audio_channels * sizeof(float));

    vc->buf             = av_malloc( vc->blocksize[1]                       * sizeof(float));

    vc->buf_tmp         = av_malloc( vc->blocksize[1]                       * sizeof(float));

    vc->previous_window=0;

    ff_mdct_init(&vc->mdct[0], bl0, 1);

    ff_mdct_init(&vc->mdct[1], bl1, 1);

    AV_DEBUG(" vorbis version %d \n audio_channels %d \n audio_samplerate %d \n bitrate_max %d \n bitrate_nom %d \n bitrate_min %d \n blk_0 %d blk_1 %d \n ",

            vc->version, vc->audio_channels, vc->audio_samplerate, vc->bitrate_maximum, vc->bitrate_nominal, vc->bitrate_minimum, vc->blocksize[0], vc->blocksize[1]);

/*

    BLK=vc->blocksize[0];

    for(i=0;i<BLK/2;++i) {

        vc->win[0][i]=sin(0.5*3.14159265358*(sin(((float)i+0.5)/(float)BLK*3.14159265358))*(sin(((float)i+0.5)/(float)BLK*3.14159265358)));

    }

*/

    return 0;

}


void ff_avg_h264_qpel4_mc31_msa(uint8_t *dst, const uint8_t *src,

                                ptrdiff_t stride)

{

    avc_luma_hv_qrt_and_aver_dst_4x4_msa(src - 2,

                                         src - (stride * 2) +

                                         sizeof(uint8_t), stride, dst, stride);

}


static int net_vhost_user_init(NetClientState *peer, const char *device,

                               const char *name, CharDriverState *chr,

                               int queues)

{

    NetClientState *nc;

    VhostUserState *s;

    int i;

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

        nc = qemu_new_net_client(&net_vhost_user_info, peer, device, name);

        snprintf(nc->info_str, sizeof(nc->info_str), "vhost-user%d to %s",

                 i, chr->label);

        nc->queue_index = i;

        s = DO_UPCAST(VhostUserState, nc, nc);

        s->chr = chr;

    }

    qemu_chr_add_handlers(chr, NULL, NULL, net_vhost_user_event, (void*)name);

    return 0;

}


static int flv_probe(AVProbeData *p)

{

    const uint8_t *d;

    if (p->buf_size < 6)

        return 0;

    d = p->buf;

    if (d[0] == 'F' && d[1] == 'L' && d[2] == 'V' && d[3] < 5 && d[5]==0) {

        return AVPROBE_SCORE_MAX;

    }

    return 0;

}


static void scsi_read_data(SCSIDevice *d, uint32_t tag)

{

    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, d);

    SCSIDiskReq *r;

    r = scsi_find_request(s, tag);

    if (!r) {

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

        /* ??? This is the wrong error.  */

        scsi_command_complete(r, CHECK_CONDITION, HARDWARE_ERROR);

        return;

    }

    /* No data transfer may already be in progress */

    assert(r->req.aiocb == NULL);

    scsi_read_request(r);

}


static void opt_output_file(void *optctx, const char *filename)

{

    OptionsContext *o = optctx;

    AVFormatContext *oc;

    int i, err;

    AVOutputFormat *file_oformat;

    OutputStream *ost;

    InputStream  *ist;

    if (!strcmp(filename, "-"))

        filename = "pipe:";

    oc = avformat_alloc_context();

    if (!oc) {

        print_error(filename, AVERROR(ENOMEM));

        exit_program(1);

    }

    if (last_asked_format) {

        file_oformat = av_guess_format(last_asked_format, NULL, NULL);

        if (!file_oformat) {

            fprintf(stderr, "Requested output format '%s' is not a suitable output format\n", last_asked_format);

            exit_program(1);

        }

        last_asked_format = NULL;

    } else {

        file_oformat = av_guess_format(NULL, filename, NULL);

        if (!file_oformat) {

            fprintf(stderr, "Unable to find a suitable output format for '%s'\n",

                    filename);

            exit_program(1);

        }

    }

    oc->oformat = file_oformat;

    av_strlcpy(oc->filename, filename, sizeof(oc->filename));

    if (!strcmp(file_oformat->name, "ffm") &&

        av_strstart(filename, "http:", NULL)) {

        /* special case for files sent to avserver: we get the stream

           parameters from avserver */

        int err = read_avserver_streams(oc, filename);

        if (err < 0) {

            print_error(filename, err);

            exit_program(1);

        }

    } else if (!o->nb_stream_maps) {

        /* pick the "best" stream of each type */

#define NEW_STREAM(type, index)\

        if (index >= 0) {\

            ost = new_ ## type ## _stream(oc);\

            ost->source_index = index;\

            ost->sync_ist     = &input_streams[index];\

            input_streams[index].discard = 0;\

        }

        /* video: highest resolution */

        if (!video_disable && oc->oformat->video_codec != CODEC_ID_NONE) {

            int area = 0, idx = -1;

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

                ist = &input_streams[i];

                if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&

                    ist->st->codec->width * ist->st->codec->height > area) {

                    area = ist->st->codec->width * ist->st->codec->height;

                    idx = i;

                }

            }

            NEW_STREAM(video, idx);

        }

        /* audio: most channels */

        if (!audio_disable && oc->oformat->audio_codec != CODEC_ID_NONE) {

            int channels = 0, idx = -1;

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

                ist = &input_streams[i];

                if (ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&

                    ist->st->codec->channels > channels) {

                    channels = ist->st->codec->channels;

                    idx = i;

                }

            }

            NEW_STREAM(audio, idx);

        }

        /* subtitles: pick first */

        if (!subtitle_disable && oc->oformat->subtitle_codec != CODEC_ID_NONE) {

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

                if (input_streams[i].st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {

                    NEW_STREAM(subtitle, i);

                    break;

                }

        }

        /* do something with data? */

    } else {

        for (i = 0; i < o->nb_stream_maps; i++) {

            StreamMap *map = &o->stream_maps[i];

            if (map->disabled)

                continue;

            ist = &input_streams[input_files[map->file_index].ist_index + map->stream_index];

            switch (ist->st->codec->codec_type) {

            case AVMEDIA_TYPE_VIDEO:    ost = new_video_stream(oc);    break;

            case AVMEDIA_TYPE_AUDIO:    ost = new_audio_stream(oc);    break;

            case AVMEDIA_TYPE_SUBTITLE: ost = new_subtitle_stream(oc); break;

            case AVMEDIA_TYPE_DATA:     ost = new_data_stream(oc);     break;

            default:

                av_log(NULL, AV_LOG_ERROR, "Cannot map stream #%d.%d - unsupported type.\n",

                       map->file_index, map->stream_index);

                exit_program(1);

            }

            ost->source_index = input_files[map->file_index].ist_index + map->stream_index;

            ost->sync_ist = &input_streams[input_files[map->sync_file_index].ist_index +

                                           map->sync_stream_index];

            ist->discard = 0;

        }

    }

    av_dict_copy(&oc->metadata, metadata, 0);

    av_dict_free(&metadata);

    output_files = grow_array(output_files, sizeof(*output_files), &nb_output_files, nb_output_files + 1);

    output_files[nb_output_files - 1].ctx       = oc;

    output_files[nb_output_files - 1].ost_index = nb_output_streams - oc->nb_streams;

    output_files[nb_output_files - 1].recording_time = o->recording_time;

    output_files[nb_output_files - 1].start_time     = o->start_time;

    output_files[nb_output_files - 1].limit_filesize = limit_filesize;

    av_dict_copy(&output_files[nb_output_files - 1].opts, format_opts, 0);

    /* check filename in case of an image number is expected */

    if (oc->oformat->flags & AVFMT_NEEDNUMBER) {

        if (!av_filename_number_test(oc->filename)) {

            print_error(oc->filename, AVERROR(EINVAL));

            exit_program(1);

        }

    }

    if (!(oc->oformat->flags & AVFMT_NOFILE)) {

        /* test if it already exists to avoid loosing precious files */

        if (!file_overwrite &&

            (strchr(filename, ':') == NULL ||

             filename[1] == ':' ||

             av_strstart(filename, "file:", NULL))) {

            if (avio_check(filename, 0) == 0) {

                if (!using_stdin) {

                    fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);

                    fflush(stderr);

                    if (!read_yesno()) {

                        fprintf(stderr, "Not overwriting - exiting\n");

                        exit_program(1);

                    }

                }

                else {

                    fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);

                    exit_program(1);

                }

            }

        }

        /* open the file */

        if ((err = avio_open(&oc->pb, filename, AVIO_FLAG_WRITE)) < 0) {

            print_error(filename, err);

            exit_program(1);

        }

    }

    oc->preload= (int)(mux_preload*AV_TIME_BASE);

    oc->max_delay= (int)(mux_max_delay*AV_TIME_BASE);

    oc->flags |= AVFMT_FLAG_NONBLOCK;

    /* copy chapters */

    if (chapters_input_file >= nb_input_files) {

        if (chapters_input_file == INT_MAX) {

            /* copy chapters from the first input file that has them*/

            chapters_input_file = -1;

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

                if (input_files[i].ctx->nb_chapters) {

                    chapters_input_file = i;

                    break;

                }

        } else {

            av_log(NULL, AV_LOG_ERROR, "Invalid input file index %d in chapter mapping.\n",

                   chapters_input_file);

            exit_program(1);

        }

    }

    if (chapters_input_file >= 0)

        copy_chapters(&input_files[chapters_input_file], &output_files[nb_output_files - 1]);

    /* copy metadata */

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

        AVFormatContext *files[2];

        AVDictionary    **meta[2];

        int j;

#define METADATA_CHECK_INDEX(index, nb_elems, desc)\

        if ((index) < 0 || (index) >= (nb_elems)) {\

            av_log(NULL, AV_LOG_ERROR, "Invalid %s index %d while processing metadata maps\n",\

                     (desc), (index));\

            exit_program(1);\

        }

        int in_file_index = meta_data_maps[i][1].file;

        if (in_file_index < 0)

            continue;

        METADATA_CHECK_INDEX(in_file_index, nb_input_files, "input file")

        files[0] = oc;

        files[1] = input_files[in_file_index].ctx;

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

            MetadataMap *map = &meta_data_maps[i][j];

            switch (map->type) {

            case 'g':

                meta[j] = &files[j]->metadata;

                break;

            case 's':

                METADATA_CHECK_INDEX(map->index, files[j]->nb_streams, "stream")

                meta[j] = &files[j]->streams[map->index]->metadata;

                break;

            case 'c':

                METADATA_CHECK_INDEX(map->index, files[j]->nb_chapters, "chapter")

                meta[j] = &files[j]->chapters[map->index]->metadata;

                break;

            case 'p':

                METADATA_CHECK_INDEX(map->index, files[j]->nb_programs, "program")

                meta[j] = &files[j]->programs[map->index]->metadata;

                break;

            }

        }

        av_dict_copy(meta[0], *meta[1], AV_DICT_DONT_OVERWRITE);

    }

    /* copy global metadata by default */

    if (metadata_global_autocopy && nb_input_files)

        av_dict_copy(&oc->metadata, input_files[0].ctx->metadata,

                     AV_DICT_DONT_OVERWRITE);

    if (metadata_streams_autocopy)

        for (i = output_files[nb_output_files - 1].ost_index; i < nb_output_streams; i++) {

            InputStream *ist = &input_streams[output_streams[i].source_index];

            av_dict_copy(&output_streams[i].st->metadata, ist->st->metadata, AV_DICT_DONT_OVERWRITE);

        }

    frame_rate    = (AVRational){0, 0};

    frame_width   = 0;

    frame_height  = 0;

    audio_sample_rate = 0;

    audio_channels    = 0;

    audio_sample_fmt  = AV_SAMPLE_FMT_NONE;

    chapters_input_file = INT_MAX;

    limit_filesize = UINT64_MAX;

    av_freep(&meta_data_maps);

    nb_meta_data_maps = 0;

    metadata_global_autocopy   = 1;

    metadata_streams_autocopy  = 1;

    metadata_chapters_autocopy = 1;

    av_freep(&streamid_map);

    nb_streamid_map = 0;

    av_dict_free(&codec_names);

    av_freep(&forced_key_frames);

    reset_options(o);

}


static int spawn_thread(void)

{

    pthread_attr_t attr;

    int ret;

    cur_threads++;

    idle_threads++;

    pthread_attr_init(&attr);

    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

    ret = pthread_create(&thread_id, &attr, aio_thread, NULL);

    pthread_attr_destroy(&attr);

    return ret;

}


static int read_gab2_sub(AVStream *st, AVPacket *pkt)

{

    if (pkt->size >= 7 &&

        !strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data + 5) == 2) {

        uint8_t desc[256];

        int score      = AVPROBE_SCORE_EXTENSION, ret;

        AVIStream *ast = st->priv_data;

        AVInputFormat *sub_demuxer;

        AVRational time_base;

        AVIOContext *pb = avio_alloc_context(pkt->data + 7,

                                             pkt->size - 7,

                                             0, NULL, NULL, NULL, NULL);

        AVProbeData pd;

        unsigned int desc_len = avio_rl32(pb);

        if (desc_len > pb->buf_end - pb->buf_ptr)

            goto error;

        ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));

        avio_skip(pb, desc_len - ret);

        if (*desc)

            av_dict_set(&st->metadata, "title", desc, 0);

        avio_rl16(pb);   /* flags? */

        avio_rl32(pb);   /* data size */

        pd = (AVProbeData) { .buf      = pb->buf_ptr,

                             .buf_size = pb->buf_end - pb->buf_ptr };

        if (!(sub_demuxer = av_probe_input_format2(&pd, 1, &score)))

            goto error;

        if (!(ast->sub_ctx = avformat_alloc_context()))

            goto error;

        ast->sub_ctx->pb = pb;

        if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) {

            ff_read_packet(ast->sub_ctx, &ast->sub_pkt);

            *st->codec = *ast->sub_ctx->streams[0]->codec;

            ast->sub_ctx->streams[0]->codec->extradata = NULL;

            time_base = ast->sub_ctx->streams[0]->time_base;

            avpriv_set_pts_info(st, 64, time_base.num, time_base.den);

        }

        ast->sub_buffer = pkt->data;

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

        return 1;

error:

        av_freep(&pb);

    }

    return 0;

}


bool machine_iommu(MachineState *machine)

{

    return machine->iommu;

}


static int disas_cp15_insn(CPUState *env, DisasContext *s, uint32_t insn)

{

    uint32_t rd;

    TCGv tmp, tmp2;

    /* M profile cores use memory mapped registers instead of cp15.  */

    if (arm_feature(env, ARM_FEATURE_M))

	return 1;

    if ((insn & (1 << 25)) == 0) {

        if (insn & (1 << 20)) {

            /* mrrc */

            return 1;

        }

        /* mcrr.  Used for block cache operations, so implement as no-op.  */

        return 0;

    }

    if ((insn & (1 << 4)) == 0) {

        /* cdp */

        return 1;

    }

    if (IS_USER(s) && !cp15_user_ok(insn)) {

        return 1;

    }

    if ((insn & 0x0fff0fff) == 0x0e070f90

        || (insn & 0x0fff0fff) == 0x0e070f58) {

        /* Wait for interrupt.  */

        gen_set_pc_im(s->pc);

        s->is_jmp = DISAS_WFI;

        return 0;

    }

    rd = (insn >> 12) & 0xf;

    if (cp15_tls_load_store(env, s, insn, rd))

        return 0;

    tmp2 = tcg_const_i32(insn);

    if (insn & ARM_CP_RW_BIT) {

        tmp = new_tmp();

        gen_helper_get_cp15(tmp, cpu_env, tmp2);

        /* If the destination register is r15 then sets condition codes.  */

        if (rd != 15)

            store_reg(s, rd, tmp);

        else

            dead_tmp(tmp);

    } else {

        tmp = load_reg(s, rd);

        gen_helper_set_cp15(cpu_env, tmp2, tmp);

        dead_tmp(tmp);

        /* Normally we would always end the TB here, but Linux

         * arch/arm/mach-pxa/sleep.S expects two instructions following

         * an MMU enable to execute from cache.  Imitate this behaviour.  */

        if (!arm_feature(env, ARM_FEATURE_XSCALE) ||

                (insn & 0x0fff0fff) != 0x0e010f10)

            gen_lookup_tb(s);

    }

    tcg_temp_free_i32(tmp2);

    return 0;

}


static CharDriverState *vc_init(const char *id, ChardevBackend *backend,

                                ChardevReturn *ret, Error **errp)

{

    return vc_handler(backend->u.vc, errp);

}


USBDevice *usb_host_device_open(const char *devname)

{

    int fd = -1, ret;

    USBHostDevice *dev = NULL;

    struct usbdevfs_connectinfo ci;

    char buf[1024];

    int bus_num, addr;

    char product_name[PRODUCT_NAME_SZ];

    dev = qemu_mallocz(sizeof(USBHostDevice));

    if (!dev)

        goto fail;

#ifdef DEBUG_ISOCH

    printf("usb_host_device_open %s\n", devname);

#endif

    if (usb_host_find_device(&bus_num, &addr,

                             product_name, sizeof(product_name),

                             devname) < 0)

        return NULL;

    snprintf(buf, sizeof(buf), USBDEVFS_PATH "/%03d/%03d",

             bus_num, addr);

    fd = open(buf, O_RDWR | O_NONBLOCK);

    if (fd < 0) {

        perror(buf);

        return NULL;

    }

    /* read the device description */

    dev->descr_len = read(fd, dev->descr, sizeof(dev->descr));

    if (dev->descr_len <= 0) {

        perror("usb_host_device_open: reading device data failed");

        goto fail;

    }

#ifdef DEBUG

    {

        int x;

        printf("=== begin dumping device descriptor data ===\n");

        for (x = 0; x < dev->descr_len; x++)

            printf("%02x ", dev->descr[x]);

        printf("\n=== end dumping device descriptor data ===\n");

    }

#endif

    dev->fd = fd;

    dev->configuration = 1;

    /* XXX - do something about initial configuration */

    if (!usb_host_update_interfaces(dev, 1))

        goto fail;

    ret = ioctl(fd, USBDEVFS_CONNECTINFO, &ci);

    if (ret < 0) {

        perror("usb_host_device_open: USBDEVFS_CONNECTINFO");

        goto fail;

    }

#ifdef DEBUG

    printf("host USB device %d.%d grabbed\n", bus_num, addr);

#endif

    ret = usb_linux_update_endp_table(dev);

    if (ret)

        goto fail;

    if (ci.slow)

        dev->dev.speed = USB_SPEED_LOW;

    else

        dev->dev.speed = USB_SPEED_HIGH;

    dev->dev.handle_packet = usb_generic_handle_packet;

    dev->dev.handle_reset = usb_host_handle_reset;

    dev->dev.handle_control = usb_host_handle_control;

    dev->dev.handle_data = usb_host_handle_data;

    dev->dev.handle_destroy = usb_host_handle_destroy;

    if (product_name[0] == '\0')

        snprintf(dev->dev.devname, sizeof(dev->dev.devname),

                 "host:%s", devname);

    else

        pstrcpy(dev->dev.devname, sizeof(dev->dev.devname),

                product_name);

#ifdef USE_ASYNCIO

    /* set up the signal handlers */

    sigemptyset(&sigact.sa_mask);

    sigact.sa_sigaction = isoch_done;

    sigact.sa_flags = SA_SIGINFO;

    sigact.sa_restorer = 0;

    ret = sigaction(SIG_ISOCOMPLETE, &sigact, NULL);

    if (ret < 0) {

        perror("usb_host_device_open: sigaction failed");

        goto fail;

    }

    if (pipe(dev->pipe_fds) < 0) {

        perror("usb_host_device_open: pipe creation failed");

        goto fail;

    }

    fcntl(dev->pipe_fds[0], F_SETFL, O_NONBLOCK | O_ASYNC);

    fcntl(dev->pipe_fds[1], F_SETFL, O_NONBLOCK);

    qemu_set_fd_handler(dev->pipe_fds[0], urb_completion_pipe_read, NULL, dev);

#endif

    dev->urbs_ready = 0;

    return (USBDevice *)dev;

fail:

    if (dev)

        qemu_free(dev);

    close(fd);

    return NULL;

}


uint64_t helper_frsp(CPUPPCState *env, uint64_t arg)

{

    CPU_DoubleU farg;

    float32 f32;

    farg.ll = arg;

    if (unlikely(float64_is_signaling_nan(farg.d))) {

        /* sNaN square root */

        fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXSNAN);

    }

    f32 = float64_to_float32(farg.d, &env->fp_status);

    farg.d = float32_to_float64(f32, &env->fp_status);

    return farg.ll;

}


int gen_new_label(void)

{

    TCGContext *s = &tcg_ctx;

    int idx;

    TCGLabel *l;

    if (s->nb_labels >= TCG_MAX_LABELS)

        tcg_abort();

    idx = s->nb_labels++;

    l = &s->labels[idx];

    l->has_value = 0;

    l->u.first_reloc = NULL;

    return idx;

}


void bdrv_round_to_clusters(BlockDriverState *bs,

                            int64_t sector_num, int nb_sectors,

                            int64_t *cluster_sector_num,

                            int *cluster_nb_sectors)

{

    BlockDriverInfo bdi;

    if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {

        *cluster_sector_num = sector_num;

        *cluster_nb_sectors = nb_sectors;

    } else {

        int64_t c = bdi.cluster_size / BDRV_SECTOR_SIZE;

        *cluster_sector_num = QEMU_ALIGN_DOWN(sector_num, c);

        *cluster_nb_sectors = QEMU_ALIGN_UP(sector_num - *cluster_sector_num +

                                            nb_sectors, c);

    }

}


void tlb_reset_dirty(CPUState *cpu, ram_addr_t start1, ram_addr_t length)

{

    CPUArchState *env;

    int mmu_idx;

    assert_cpu_is_self(cpu);

    env = cpu->env_ptr;

    for (mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) {

        unsigned int i;

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

            tlb_reset_dirty_range(&env->tlb_table[mmu_idx][i],

                                  start1, length);

        }

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

            tlb_reset_dirty_range(&env->tlb_v_table[mmu_idx][i],

                                  start1, length);

        }

    }

}


blkdebug_co_preadv(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
                   QEMUIOVector *qiov, int flags)
{
    BDRVBlkdebugState *s = bs->opaque;
    BlkdebugRule *rule = NULL;
    QSIMPLEQ_FOREACH(rule, &s->active_rules, active_next) {
        uint64_t inject_offset = rule->options.inject.offset;
        if (inject_offset == -1 ||
            (inject_offset >= offset && inject_offset < offset + bytes))
        {
            break;
    if (rule && rule->options.inject.error) {
        return inject_error(bs, rule);
    return bdrv_co_preadv(bs->file, offset, bytes, qiov, flags);


static int idreg_init1(SysBusDevice *dev)

{

    IDRegState *s = MACIO_ID_REGISTER(dev);

    memory_region_init_ram(&s->mem, OBJECT(s),

                           "sun4m.idreg", sizeof(idreg_data), &error_abort);

    vmstate_register_ram_global(&s->mem);

    memory_region_set_readonly(&s->mem, true);

    sysbus_init_mmio(dev, &s->mem);

    return 0;

}


static inline void tcg_out_ld_ptr(TCGContext *s, int ret,

                                  tcg_target_long arg)

{

#if defined(__sparc_v9__) && !defined(__sparc_v8plus__)

    if (arg != (arg & 0xffffffff))

        fprintf(stderr, "unimplemented %s with offset %ld\n", __func__, arg);

    if (arg != (arg & 0xfff))

        tcg_out32(s, SETHI | INSN_RD(ret) | (((uint32_t)arg & 0xfffffc00) >> 10));

    tcg_out32(s, LDX | INSN_RD(ret) | INSN_RS1(ret) |

              INSN_IMM13(arg & 0x3ff));

#else

    tcg_out_ld_raw(s, ret, arg);

#endif

}


int xen_config_dev_blk(DriveInfo *disk)

{

    char fe[256], be[256];

    int vdev = 202 * 256 + 16 * disk->unit;

    int cdrom = disk->bdrv->type == BDRV_TYPE_CDROM;

    const char *devtype = cdrom ? "cdrom" : "disk";

    const char *mode    = cdrom ? "r"     : "w";

    snprintf(disk->bdrv->device_name, sizeof(disk->bdrv->device_name),

	     "xvd%c", 'a' + disk->unit);

    xen_be_printf(NULL, 1, "config disk %d [%s]: %s\n",

                  disk->unit, disk->bdrv->device_name, disk->bdrv->filename);

    xen_config_dev_dirs("vbd", "qdisk", vdev, fe, be, sizeof(fe));

    /* frontend */

    xenstore_write_int(fe, "virtual-device",  vdev);

    xenstore_write_str(fe, "device-type",     devtype);

    /* backend */

    xenstore_write_str(be, "dev",             disk->bdrv->device_name);

    xenstore_write_str(be, "type",            "file");

    xenstore_write_str(be, "params",          disk->bdrv->filename);

    xenstore_write_str(be, "mode",            mode);

    /* common stuff */

    return xen_config_dev_all(fe, be);

}


static inline void gen_intermediate_code_internal(OpenRISCCPU *cpu,

                                                  TranslationBlock *tb,

                                                  int search_pc)

{

    CPUState *cs = CPU(cpu);

    struct DisasContext ctx, *dc = &ctx;

    uint16_t *gen_opc_end;

    uint32_t pc_start;

    int j, k;

    uint32_t next_page_start;

    int num_insns;

    int max_insns;

    pc_start = tb->pc;

    dc->tb = tb;

    gen_opc_end = tcg_ctx.gen_opc_buf + OPC_MAX_SIZE;

    dc->is_jmp = DISAS_NEXT;

    dc->ppc = pc_start;

    dc->pc = pc_start;

    dc->flags = cpu->env.cpucfgr;

    dc->mem_idx = cpu_mmu_index(&cpu->env);

    dc->synced_flags = dc->tb_flags = tb->flags;

    dc->delayed_branch = !!(dc->tb_flags & D_FLAG);

    dc->singlestep_enabled = cs->singlestep_enabled;

    if (qemu_loglevel_mask(CPU_LOG_TB_IN_ASM)) {

        qemu_log("-----------------------------------------\n");

        log_cpu_state(CPU(cpu), 0);

    }

    next_page_start = (pc_start & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE;

    k = -1;

    num_insns = 0;

    max_insns = tb->cflags & CF_COUNT_MASK;

    if (max_insns == 0) {

        max_insns = CF_COUNT_MASK;

    }

    gen_tb_start();

    do {

        check_breakpoint(cpu, dc);

        if (search_pc) {

            j = tcg_ctx.gen_opc_ptr - tcg_ctx.gen_opc_buf;

            if (k < j) {

                k++;

                while (k < j) {

                    tcg_ctx.gen_opc_instr_start[k++] = 0;

                }

            }

            tcg_ctx.gen_opc_pc[k] = dc->pc;

            tcg_ctx.gen_opc_instr_start[k] = 1;

            tcg_ctx.gen_opc_icount[k] = num_insns;

        }

        if (unlikely(qemu_loglevel_mask(CPU_LOG_TB_OP | CPU_LOG_TB_OP_OPT))) {

            tcg_gen_debug_insn_start(dc->pc);

        }

        if (num_insns + 1 == max_insns && (tb->cflags & CF_LAST_IO)) {

            gen_io_start();

        }

        dc->ppc = dc->pc - 4;

        dc->npc = dc->pc + 4;

        tcg_gen_movi_tl(cpu_ppc, dc->ppc);

        tcg_gen_movi_tl(cpu_npc, dc->npc);

        disas_openrisc_insn(dc, cpu);

        dc->pc = dc->npc;

        num_insns++;

        /* delay slot */

        if (dc->delayed_branch) {

            dc->delayed_branch--;

            if (!dc->delayed_branch) {

                dc->tb_flags &= ~D_FLAG;

                gen_sync_flags(dc);

                tcg_gen_mov_tl(cpu_pc, jmp_pc);

                tcg_gen_mov_tl(cpu_npc, jmp_pc);

                tcg_gen_movi_tl(jmp_pc, 0);

                tcg_gen_exit_tb(0);

                dc->is_jmp = DISAS_JUMP;

                break;

            }

        }

    } while (!dc->is_jmp

             && tcg_ctx.gen_opc_ptr < gen_opc_end

             && !cs->singlestep_enabled

             && !singlestep

             && (dc->pc < next_page_start)

             && num_insns < max_insns);

    if (tb->cflags & CF_LAST_IO) {

        gen_io_end();

    }

    if (dc->is_jmp == DISAS_NEXT) {

        dc->is_jmp = DISAS_UPDATE;

        tcg_gen_movi_tl(cpu_pc, dc->pc);

    }

    if (unlikely(cs->singlestep_enabled)) {

        if (dc->is_jmp == DISAS_NEXT) {

            tcg_gen_movi_tl(cpu_pc, dc->pc);

        }

        gen_exception(dc, EXCP_DEBUG);

    } else {

        switch (dc->is_jmp) {

        case DISAS_NEXT:

            gen_goto_tb(dc, 0, dc->pc);

            break;

        default:

        case DISAS_JUMP:

            break;

        case DISAS_UPDATE:

            /* indicate that the hash table must be used

               to find the next TB */

            tcg_gen_exit_tb(0);

            break;

        case DISAS_TB_JUMP:

            /* nothing more to generate */

            break;

        }

    }

    gen_tb_end(tb, num_insns);

    *tcg_ctx.gen_opc_ptr = INDEX_op_end;

    if (search_pc) {

        j = tcg_ctx.gen_opc_ptr - tcg_ctx.gen_opc_buf;

        k++;

        while (k <= j) {

            tcg_ctx.gen_opc_instr_start[k++] = 0;

        }

    } else {

        tb->size = dc->pc - pc_start;

        tb->icount = num_insns;

    }

#ifdef DEBUG_DISAS

    if (qemu_loglevel_mask(CPU_LOG_TB_IN_ASM)) {

        qemu_log("\n");

        log_target_disas(&cpu->env, pc_start, dc->pc - pc_start, 0);

        qemu_log("\nisize=%d osize=%td\n",

            dc->pc - pc_start, tcg_ctx.gen_opc_ptr -

            tcg_ctx.gen_opc_buf);

    }

#endif

}


static void pci_ivshmem_realize(PCIDevice *dev, Error **errp)

{

    IVShmemState *s = IVSHMEM(dev);

    Error *err = NULL;

    uint8_t *pci_conf;

    uint8_t attr = PCI_BASE_ADDRESS_SPACE_MEMORY |

        PCI_BASE_ADDRESS_MEM_PREFETCH;

    if (!!s->server_chr + !!s->shmobj + !!s->hostmem != 1) {

        error_setg(errp,

                   "You must specify either 'shm', 'chardev' or 'x-memdev'");

        return;

    }

    if (s->hostmem) {

        MemoryRegion *mr;

        if (s->sizearg) {

            g_warning("size argument ignored with hostmem");

        }

        mr = host_memory_backend_get_memory(s->hostmem, &error_abort);

        s->ivshmem_size = memory_region_size(mr);

    } else if (s->sizearg == NULL) {

        s->ivshmem_size = 4 << 20; /* 4 MB default */

    } else {

        char *end;

        int64_t size = qemu_strtosz(s->sizearg, &end);

        if (size < 0 || *end != '\0' || !is_power_of_2(size)) {

            error_setg(errp, "Invalid size %s", s->sizearg);

            return;

        }

        s->ivshmem_size = size;

    }

    /* IRQFD requires MSI */

    if (ivshmem_has_feature(s, IVSHMEM_IOEVENTFD) &&

        !ivshmem_has_feature(s, IVSHMEM_MSI)) {

        error_setg(errp, "ioeventfd/irqfd requires MSI");

        return;

    }

    /* check that role is reasonable */

    if (s->role) {

        if (strncmp(s->role, "peer", 5) == 0) {

            s->role_val = IVSHMEM_PEER;

        } else if (strncmp(s->role, "master", 7) == 0) {

            s->role_val = IVSHMEM_MASTER;

        } else {

            error_setg(errp, "'role' must be 'peer' or 'master'");

            return;

        }

    } else {

        s->role_val = IVSHMEM_MASTER; /* default */

    }

    pci_conf = dev->config;

    pci_conf[PCI_COMMAND] = PCI_COMMAND_IO | PCI_COMMAND_MEMORY;

    /*

     * Note: we don't use INTx with IVSHMEM_MSI at all, so this is a

     * bald-faced lie then.  But it's a backwards compatible lie.

     */

    pci_config_set_interrupt_pin(pci_conf, 1);

    memory_region_init_io(&s->ivshmem_mmio, OBJECT(s), &ivshmem_mmio_ops, s,

                          "ivshmem-mmio", IVSHMEM_REG_BAR_SIZE);

    /* region for registers*/

    pci_register_bar(dev, 0, PCI_BASE_ADDRESS_SPACE_MEMORY,

                     &s->ivshmem_mmio);

    memory_region_init(&s->bar, OBJECT(s), "ivshmem-bar2-container", s->ivshmem_size);

    if (s->ivshmem_64bit) {

        attr |= PCI_BASE_ADDRESS_MEM_TYPE_64;

    }

    if (s->hostmem != NULL) {

        MemoryRegion *mr;

        IVSHMEM_DPRINTF("using hostmem\n");

        mr = host_memory_backend_get_memory(MEMORY_BACKEND(s->hostmem),

                                            &error_abort);

        vmstate_register_ram(mr, DEVICE(s));

        memory_region_add_subregion(&s->bar, 0, mr);

        pci_register_bar(PCI_DEVICE(s), 2, attr, &s->bar);

    } else if (s->server_chr != NULL) {

        /* FIXME do not rely on what chr drivers put into filename */

        if (strncmp(s->server_chr->filename, "unix:", 5)) {

            error_setg(errp, "chardev is not a unix client socket");

            return;

        }

        /* if we get a UNIX socket as the parameter we will talk

         * to the ivshmem server to receive the memory region */

        IVSHMEM_DPRINTF("using shared memory server (socket = %s)\n",

                        s->server_chr->filename);

        if (ivshmem_setup_interrupts(s) < 0) {

            error_setg(errp, "failed to initialize interrupts");

            return;

        }

        /* we allocate enough space for 16 peers and grow as needed */

        resize_peers(s, 16);

        s->vm_id = -1;

        pci_register_bar(dev, 2, attr, &s->bar);

        qemu_chr_add_handlers(s->server_chr, ivshmem_can_receive,

                              ivshmem_check_version, NULL, s);

    } else {

        /* just map the file immediately, we're not using a server */

        int fd;

        IVSHMEM_DPRINTF("using shm_open (shm object = %s)\n", s->shmobj);

        /* try opening with O_EXCL and if it succeeds zero the memory

         * by truncating to 0 */

        if ((fd = shm_open(s->shmobj, O_CREAT|O_RDWR|O_EXCL,

                        S_IRWXU|S_IRWXG|S_IRWXO)) > 0) {

           /* truncate file to length PCI device's memory */

            if (ftruncate(fd, s->ivshmem_size) != 0) {

                error_report("could not truncate shared file");

            }

        } else if ((fd = shm_open(s->shmobj, O_CREAT|O_RDWR,

                        S_IRWXU|S_IRWXG|S_IRWXO)) < 0) {

            error_setg(errp, "could not open shared file");

            return;

        }

        if (check_shm_size(s, fd, errp) == -1) {

            return;

        }

        create_shared_memory_BAR(s, fd, attr, &err);

        if (err) {

            error_propagate(errp, err);

            return;

        }

    }

    fifo8_create(&s->incoming_fifo, sizeof(int64_t));

    if (s->role_val == IVSHMEM_PEER) {

        error_setg(&s->migration_blocker,

                   "Migration is disabled when using feature 'peer mode' in device 'ivshmem'");

        migrate_add_blocker(s->migration_blocker);

    }

}


int print_insn_lm32(bfd_vma memaddr, struct disassemble_info *info)

{

    fprintf_function fprintf_fn = info->fprintf_func;

    void *stream = info->stream;

    int rc;

    uint8_t insn[4];

    const Lm32OpcodeInfo *opc_info;

    uint32_t op;

    const char *args_fmt;

    rc = info->read_memory_func(memaddr, insn, 4, info);

    if (rc != 0) {

        info->memory_error_func(rc, memaddr, info);

        return -1;

    }

    fprintf_fn(stream, "%02x %02x %02x %02x    ",

            insn[0], insn[1], insn[2], insn[3]);

    op = bfd_getb32(insn);

    opc_info = find_opcode_info(op);

    if (opc_info) {

        fprintf_fn(stream, "%-8s ", opc_info->name);

        args_fmt = opc_info->args_fmt;

        while (args_fmt && *args_fmt) {

            if (*args_fmt == '%') {

                switch (*(++args_fmt)) {

                case '0': {

                    uint8_t r0;

                    const char *r0_name;

                    r0 = (op >> 21) & 0x1f;

                    r0_name = find_reg_info(r0)->name;

                    fprintf_fn(stream, "%s", r0_name);

                    break;

                }

                case '1': {

                    uint8_t r1;

                    const char *r1_name;

                    r1 = (op >> 16) & 0x1f;

                    r1_name = find_reg_info(r1)->name;

                    fprintf_fn(stream, "%s", r1_name);

                    break;

                }

                case '2': {

                    uint8_t r2;

                    const char *r2_name;

                    r2 = (op >> 11) & 0x1f;

                    r2_name = find_reg_info(r2)->name;

                    fprintf_fn(stream, "%s", r2_name);

                    break;

                }

                case 'c': {

                    uint8_t csr;

                    const char *csr_name;

                    csr = (op >> 21) & 0x1f;

                    csr_name = find_csr_info(csr)->name;

                    if (csr_name) {

                        fprintf_fn(stream, "%s", csr_name);

                    } else {

                        fprintf_fn(stream, "0x%x", csr);

                    }

                    break;

                }

                case 'u': {

                    uint16_t u16;

                    u16 = op & 0xffff;

                    fprintf_fn(stream, "0x%x", u16);

                    break;

                }

                case 's': {

                    int16_t s16;

                    s16 = (int16_t)(op & 0xffff);

                    fprintf_fn(stream, "%d", s16);

                    break;

                }

                case 'r': {

                    uint32_t rela;

                    rela = memaddr + (((int16_t)(op & 0xffff)) << 2);

                    fprintf_fn(stream, "%x", rela);

                    break;

                }

                case 'R': {

                    uint32_t rela;

                    int32_t imm26;

                    imm26 = (int32_t)((op & 0x3ffffff) << 6) >> 4;

                    rela = memaddr + imm26;

                    fprintf_fn(stream, "%x", rela);

                    break;

                }

                case 'h': {

                    uint8_t u5;

                    u5 = (op & 0x1f);

                    fprintf_fn(stream, "%d", u5);

                    break;

                }

                default:

                    break;

                }

            } else {

                fprintf_fn(stream, "%c", *args_fmt);

            }

            args_fmt++;

        }

    } else {

        fprintf_fn(stream, ".word 0x%x", op);

    }

    return 4;

}


static int get_coc(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c,

                   uint8_t *properties)

{

    int compno;

    if (s->buf_end - s->buf < 2)

        return AVERROR(EINVAL);

    compno = bytestream_get_byte(&s->buf);

    c      += compno;

    c->csty = bytestream_get_byte(&s->buf);

    get_cox(s, c);

    properties[compno] |= HAD_COC;

    return 0;

}


static void curses_setup(void)

{

    int i, colour_default[8] = {

        COLOR_BLACK, COLOR_BLUE, COLOR_GREEN, COLOR_CYAN,

        COLOR_RED, COLOR_MAGENTA, COLOR_YELLOW, COLOR_WHITE,

    };

    /* input as raw as possible, let everything be interpreted

     * by the guest system */

    initscr(); noecho(); intrflush(stdscr, FALSE);

    nodelay(stdscr, TRUE); nonl(); keypad(stdscr, TRUE);

    start_color(); raw(); scrollok(stdscr, FALSE);

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

        init_pair(i, colour_default[i & 7], colour_default[i >> 3]);

}


static inline void RENAME(hyscale)(uint16_t *dst, int dstWidth, uint8_t *src, int srcW, int xInc)

{

#ifdef HAVE_MMX

	// use the new MMX scaler if th mmx2 cant be used (its faster than the x86asm one)

    if(sws_flags != SWS_FAST_BILINEAR || (!canMMX2BeUsed))

#else

    if(sws_flags != SWS_FAST_BILINEAR)

#endif

    {

    	RENAME(hScale)(dst, dstWidth, src, srcW, xInc, hLumFilter, hLumFilterPos, hLumFilterSize);

    }

    else // Fast Bilinear upscale / crap downscale

    {

#ifdef ARCH_X86

#ifdef HAVE_MMX2

	int i;

	if(canMMX2BeUsed)

	{

		asm volatile(

			"pxor %%mm7, %%mm7		\n\t"

			"pxor %%mm2, %%mm2		\n\t" // 2*xalpha

			"movd %5, %%mm6			\n\t" // xInc&0xFFFF

			"punpcklwd %%mm6, %%mm6		\n\t"

			"punpcklwd %%mm6, %%mm6		\n\t"

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

			"psllq $16, %%mm2		\n\t"

			"paddw %%mm6, %%mm2		\n\t"

			"psllq $16, %%mm2		\n\t"

			"paddw %%mm6, %%mm2		\n\t"

			"psllq $16, %%mm2		\n\t" //0,t,2t,3t		t=xInc&0xFF

			"movq %%mm2, "MANGLE(temp0)"	\n\t"

			"movd %4, %%mm6			\n\t" //(xInc*4)&0xFFFF

			"punpcklwd %%mm6, %%mm6		\n\t"

			"punpcklwd %%mm6, %%mm6		\n\t"

			"xorl %%eax, %%eax		\n\t" // i

			"movl %0, %%esi			\n\t" // src

			"movl %1, %%edi			\n\t" // buf1

			"movl %3, %%edx			\n\t" // (xInc*4)>>16

			"xorl %%ecx, %%ecx		\n\t"

			"xorl %%ebx, %%ebx		\n\t"

			"movw %4, %%bx			\n\t" // (xInc*4)&0xFFFF

#define FUNNY_Y_CODE \

			PREFETCH" 1024(%%esi)		\n\t"\

			PREFETCH" 1056(%%esi)		\n\t"\

			PREFETCH" 1088(%%esi)		\n\t"\

			"call "MANGLE(funnyYCode)"	\n\t"\

			"movq "MANGLE(temp0)", %%mm2	\n\t"\

			"xorl %%ecx, %%ecx		\n\t"

FUNNY_Y_CODE

FUNNY_Y_CODE

FUNNY_Y_CODE

FUNNY_Y_CODE

FUNNY_Y_CODE

FUNNY_Y_CODE

FUNNY_Y_CODE

FUNNY_Y_CODE

			:: "m" (src), "m" (dst), "m" (dstWidth), "m" ((xInc*4)>>16),

			"m" ((xInc*4)&0xFFFF), "m" (xInc&0xFFFF)

			: "%eax", "%ebx", "%ecx", "%edx", "%esi", "%edi"

		);

		for(i=dstWidth-1; (i*xInc)>>16 >=srcW-1; i--) dst[i] = src[srcW-1]*128;

	}

	else

	{

#endif

	//NO MMX just normal asm ...

	asm volatile(

		"xorl %%eax, %%eax		\n\t" // i

		"xorl %%ebx, %%ebx		\n\t" // xx

		"xorl %%ecx, %%ecx		\n\t" // 2*xalpha

		".balign 16			\n\t"

		"1:				\n\t"

		"movzbl  (%0, %%ebx), %%edi	\n\t" //src[xx]

		"movzbl 1(%0, %%ebx), %%esi	\n\t" //src[xx+1]

		"subl %%edi, %%esi		\n\t" //src[xx+1] - src[xx]

		"imull %%ecx, %%esi		\n\t" //(src[xx+1] - src[xx])*2*xalpha

		"shll $16, %%edi		\n\t"

		"addl %%edi, %%esi		\n\t" //src[xx+1]*2*xalpha + src[xx]*(1-2*xalpha)

		"movl %1, %%edi			\n\t"

		"shrl $9, %%esi			\n\t"

		"movw %%si, (%%edi, %%eax, 2)	\n\t"

		"addw %4, %%cx			\n\t" //2*xalpha += xInc&0xFF

		"adcl %3, %%ebx			\n\t" //xx+= xInc>>8 + carry

		"movzbl (%0, %%ebx), %%edi	\n\t" //src[xx]

		"movzbl 1(%0, %%ebx), %%esi	\n\t" //src[xx+1]

		"subl %%edi, %%esi		\n\t" //src[xx+1] - src[xx]

		"imull %%ecx, %%esi		\n\t" //(src[xx+1] - src[xx])*2*xalpha

		"shll $16, %%edi		\n\t"

		"addl %%edi, %%esi		\n\t" //src[xx+1]*2*xalpha + src[xx]*(1-2*xalpha)

		"movl %1, %%edi			\n\t"

		"shrl $9, %%esi			\n\t"

		"movw %%si, 2(%%edi, %%eax, 2)	\n\t"

		"addw %4, %%cx			\n\t" //2*xalpha += xInc&0xFF

		"adcl %3, %%ebx			\n\t" //xx+= xInc>>8 + carry

		"addl $2, %%eax			\n\t"

		"cmpl %2, %%eax			\n\t"

		" jb 1b				\n\t"

		:: "r" (src), "m" (dst), "m" (dstWidth), "m" (xInc>>16), "m" (xInc&0xFFFF)

		: "%eax", "%ebx", "%ecx", "%edi", "%esi"

		);

#ifdef HAVE_MMX2

	} //if MMX2 cant be used

#endif

#else

	int i;

	unsigned int xpos=0;

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

	{

		register unsigned int xx=xpos>>16;

		register unsigned int xalpha=(xpos&0xFFFF)>>9;

		dst[i]= (src[xx]<<7) + (src[xx+1] - src[xx])*xalpha;

		xpos+=xInc;

	}

#endif

    }

}


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

{

    uint16_t *v = pv;

    uint16_t v2;

    qemu_get_be16s(f, &v2);

    if (*v == v2) {

        return 0;

    }

    return -EINVAL;

}


static int h264_handle_packet(AVFormatContext *ctx, PayloadContext *data,

                              AVStream *st, AVPacket *pkt, uint32_t *timestamp,

                              const uint8_t *buf, int len, uint16_t seq,

                              int flags)

{

    uint8_t nal;

    uint8_t type;

    int result = 0;

    if (!len) {

        av_log(ctx, AV_LOG_ERROR, "Empty H264 RTP packet\n");

        return AVERROR_INVALIDDATA;

    }

    nal  = buf[0];

    type = nal & 0x1f;

    assert(data);

    assert(buf);

    /* Simplify the case (these are all the nal types used internally by

     * the h264 codec). */

    if (type >= 1 && type <= 23)

        type = 1;

    switch (type) {

    case 0:                    // undefined, but pass them through

    case 1:

        av_new_packet(pkt, len + sizeof(start_sequence));

        memcpy(pkt->data, start_sequence, sizeof(start_sequence));

        memcpy(pkt->data + sizeof(start_sequence), buf, len);

        COUNT_NAL_TYPE(data, nal);

        break;

    case 24:                   // STAP-A (one packet, multiple nals)

        // consume the STAP-A NAL

        buf++;

        len--;

        // first we are going to figure out the total size

        {

            int pass         = 0;

            int total_length = 0;

            uint8_t *dst     = NULL;

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

                const uint8_t *src = buf;

                int src_len        = len;

                while (src_len > 2) {

                    uint16_t nal_size = AV_RB16(src);

                    // consume the length of the aggregate

                    src     += 2;

                    src_len -= 2;

                    if (nal_size <= src_len) {

                        if (pass == 0) {

                            // counting

                            total_length += sizeof(start_sequence) + nal_size;

                        } else {

                            // copying

                            assert(dst);

                            memcpy(dst, start_sequence, sizeof(start_sequence));

                            dst += sizeof(start_sequence);

                            memcpy(dst, src, nal_size);

                            COUNT_NAL_TYPE(data, *src);

                            dst += nal_size;

                        }

                    } else {

                        av_log(ctx, AV_LOG_ERROR,

                               "nal size exceeds length: %d %d\n", nal_size, src_len);

                    }

                    // eat what we handled

                    src     += nal_size;

                    src_len -= nal_size;

                    if (src_len < 0)

                        av_log(ctx, AV_LOG_ERROR,

                               "Consumed more bytes than we got! (%d)\n", src_len);

                }

                if (pass == 0) {

                    /* now we know the total size of the packet (with the

                     * start sequences added) */

                    av_new_packet(pkt, total_length);

                    dst = pkt->data;

                } else {

                    assert(dst - pkt->data == total_length);

                }

            }

        }

        break;

    case 25:                   // STAP-B

    case 26:                   // MTAP-16

    case 27:                   // MTAP-24

    case 29:                   // FU-B

        av_log(ctx, AV_LOG_ERROR,

               "Unhandled type (%d) (See RFC for implementation details\n",

               type);

        result = AVERROR(ENOSYS);

        break;

    case 28:                   // FU-A (fragmented nal)

        buf++;

        len--;                 // skip the fu_indicator

        if (len > 1) {

            // these are the same as above, we just redo them here for clarity

            uint8_t fu_indicator      = nal;

            uint8_t fu_header         = *buf;

            uint8_t start_bit         = fu_header >> 7;

            uint8_t av_unused end_bit = (fu_header & 0x40) >> 6;

            uint8_t nal_type          = fu_header & 0x1f;

            uint8_t reconstructed_nal;

            // Reconstruct this packet's true nal; only the data follows.

            /* The original nal forbidden bit and NRI are stored in this

             * packet's nal. */

            reconstructed_nal  = fu_indicator & 0xe0;

            reconstructed_nal |= nal_type;

            // skip the fu_header

            buf++;

            len--;

            if (start_bit)

                COUNT_NAL_TYPE(data, nal_type);

            if (start_bit) {

                /* copy in the start sequence, and the reconstructed nal */

                av_new_packet(pkt, sizeof(start_sequence) + sizeof(nal) + len);

                memcpy(pkt->data, start_sequence, sizeof(start_sequence));

                pkt->data[sizeof(start_sequence)] = reconstructed_nal;

                memcpy(pkt->data + sizeof(start_sequence) + sizeof(nal), buf, len);

            } else {

                av_new_packet(pkt, len);

                memcpy(pkt->data, buf, len);

            }

        } else {

            av_log(ctx, AV_LOG_ERROR, "Too short data for FU-A H264 RTP packet\n");

            result = AVERROR_INVALIDDATA;

        }

        break;

    case 30:                   // undefined

    case 31:                   // undefined

    default:

        av_log(ctx, AV_LOG_ERROR, "Undefined type (%d)\n", type);

        result = AVERROR_INVALIDDATA;

        break;

    }

    pkt->stream_index = st->index;

    return result;

}


void bdrv_refresh_filename(BlockDriverState *bs)

{

    BlockDriver *drv = bs->drv;

    QDict *opts;

    if (!drv) {

        return;

    }

    /* This BDS's file name will most probably depend on its file's name, so

     * refresh that first */

    if (bs->file) {

        bdrv_refresh_filename(bs->file->bs);

    }

    if (drv->bdrv_refresh_filename) {

        /* Obsolete information is of no use here, so drop the old file name

         * information before refreshing it */

        bs->exact_filename[0] = '\0';

        if (bs->full_open_options) {

            QDECREF(bs->full_open_options);

            bs->full_open_options = NULL;

        }

        drv->bdrv_refresh_filename(bs);

    } else if (bs->file) {

        /* Try to reconstruct valid information from the underlying file */

        bool has_open_options;

        bs->exact_filename[0] = '\0';

        if (bs->full_open_options) {

            QDECREF(bs->full_open_options);

            bs->full_open_options = NULL;

        }

        opts = qdict_new();

        has_open_options = append_open_options(opts, bs);

        /* If no specific options have been given for this BDS, the filename of

         * the underlying file should suffice for this one as well */

        if (bs->file->bs->exact_filename[0] && !has_open_options) {

            strcpy(bs->exact_filename, bs->file->bs->exact_filename);

        }

        /* Reconstructing the full options QDict is simple for most format block

         * drivers, as long as the full options are known for the underlying

         * file BDS. The full options QDict of that file BDS should somehow

         * contain a representation of the filename, therefore the following

         * suffices without querying the (exact_)filename of this BDS. */

        if (bs->file->bs->full_open_options) {

            qdict_put_obj(opts, "driver",

                          QOBJECT(qstring_from_str(drv->format_name)));

            QINCREF(bs->file->bs->full_open_options);

            qdict_put_obj(opts, "file",

                          QOBJECT(bs->file->bs->full_open_options));

            bs->full_open_options = opts;

        } else {

            QDECREF(opts);

        }

    } else if (!bs->full_open_options && qdict_size(bs->options)) {

        /* There is no underlying file BDS (at least referenced by BDS.file),

         * so the full options QDict should be equal to the options given

         * specifically for this block device when it was opened (plus the

         * driver specification).

         * Because those options don't change, there is no need to update

         * full_open_options when it's already set. */

        opts = qdict_new();

        append_open_options(opts, bs);

        qdict_put_obj(opts, "driver",

                      QOBJECT(qstring_from_str(drv->format_name)));

        if (bs->exact_filename[0]) {

            /* This may not work for all block protocol drivers (some may

             * require this filename to be parsed), but we have to find some

             * default solution here, so just include it. If some block driver

             * does not support pure options without any filename at all or

             * needs some special format of the options QDict, it needs to

             * implement the driver-specific bdrv_refresh_filename() function.

             */

            qdict_put_obj(opts, "filename",

                          QOBJECT(qstring_from_str(bs->exact_filename)));

        }

        bs->full_open_options = opts;

    }

    if (bs->exact_filename[0]) {

        pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);

    } else if (bs->full_open_options) {

        QString *json = qobject_to_json(QOBJECT(bs->full_open_options));

        snprintf(bs->filename, sizeof(bs->filename), "json:%s",

                 qstring_get_str(json));

        QDECREF(json);

    }

}


static inline bool cpu_handle_exception(CPUState *cpu, int *ret)

{

    if (cpu->exception_index >= 0) {

        if (cpu->exception_index >= EXCP_INTERRUPT) {

            /* exit request from the cpu execution loop */

            *ret = cpu->exception_index;

            if (*ret == EXCP_DEBUG) {

                cpu_handle_debug_exception(cpu);

            }

            cpu->exception_index = -1;

            return true;

        } else {

#if defined(CONFIG_USER_ONLY)

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

               which will be handled outside the cpu execution

               loop */

#if defined(TARGET_I386)

            CPUClass *cc = CPU_GET_CLASS(cpu);

            cc->do_interrupt(cpu);

#endif

            *ret = cpu->exception_index;

            cpu->exception_index = -1;

            return true;

#else

            if (replay_exception()) {

                CPUClass *cc = CPU_GET_CLASS(cpu);

                qemu_mutex_lock_iothread();

                cc->do_interrupt(cpu);

                qemu_mutex_unlock_iothread();

                cpu->exception_index = -1;

            } else if (!replay_has_interrupt()) {

                /* give a chance to iothread in replay mode */

                *ret = EXCP_INTERRUPT;

                return true;

            }

#endif

        }

#ifndef CONFIG_USER_ONLY

    } else if (replay_has_exception()

               && cpu->icount_decr.u16.low + cpu->icount_extra == 0) {

        /* try to cause an exception pending in the log */

        cpu_exec_nocache(cpu, 1, tb_find(cpu, NULL, 0), true);

        *ret = -1;

        return true;

#endif

    }

    return false;

}


void ff_dnxhdenc_init_x86(DNXHDEncContext *ctx)

{

#if HAVE_INLINE_ASM

    if (av_get_cpu_flags() & AV_CPU_FLAG_SSE2) {

        if (ctx->cid_table->bit_depth == 8)

            ctx->get_pixels_8x4_sym = get_pixels_8x4_sym_sse2;

    }

#endif /* HAVE_INLINE_ASM */

}


uint64_t helper_fdiv(CPUPPCState *env, uint64_t arg1, uint64_t arg2)

{

    CPU_DoubleU farg1, farg2;

    farg1.ll = arg1;

    farg2.ll = arg2;

    if (unlikely(float64_is_infinity(farg1.d) &&

                 float64_is_infinity(farg2.d))) {

        /* Division of infinity by infinity */

        farg1.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXIDI);

    } else if (unlikely(float64_is_zero(farg1.d) && float64_is_zero(farg2.d))) {

        /* Division of zero by zero */

        farg1.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXZDZ);

    } else {

        if (unlikely(float64_is_signaling_nan(farg1.d) ||

                     float64_is_signaling_nan(farg2.d))) {

            /* sNaN division */

            fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXSNAN);

        }

        farg1.d = float64_div(farg1.d, farg2.d, &env->fp_status);

    }

    return farg1.ll;

}


static void test_io_channel_ipv4(bool async)

{

    SocketAddress *listen_addr = g_new0(SocketAddress, 1);

    SocketAddress *connect_addr = g_new0(SocketAddress, 1);

    listen_addr->type = SOCKET_ADDRESS_KIND_INET;

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

    listen_addr->u.inet->host = g_strdup("0.0.0.0");

    listen_addr->u.inet->port = NULL; /* Auto-select */

    connect_addr->type = SOCKET_ADDRESS_KIND_INET;

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

    connect_addr->u.inet->host = g_strdup("127.0.0.1");

    connect_addr->u.inet->port = NULL; /* Filled in later */

    test_io_channel(async, listen_addr, connect_addr);

    qapi_free_SocketAddress(listen_addr);

    qapi_free_SocketAddress(connect_addr);

}