void commit_start(BlockDriverState *bs, BlockDriverState *base,

                  BlockDriverState *top, int64_t speed,

                  BlockdevOnError on_error, BlockDriverCompletionFunc *cb,

                  void *opaque, Error **errp)

{

    CommitBlockJob *s;

    BlockReopenQueue *reopen_queue = NULL;

    int orig_overlay_flags;

    int orig_base_flags;

    BlockDriverState *overlay_bs;

    Error *local_err = NULL;

    if ((on_error == BLOCKDEV_ON_ERROR_STOP ||

         on_error == BLOCKDEV_ON_ERROR_ENOSPC) &&

        !bdrv_iostatus_is_enabled(bs)) {

        error_set(errp, QERR_INVALID_PARAMETER_COMBINATION);

        return;

    }

    /* Once we support top == active layer, remove this check */

    if (top == bs) {

        error_setg(errp,

                   "Top image as the active layer is currently unsupported");

        return;

    }

    if (top == base) {

        error_setg(errp, "Invalid files for merge: top and base are the same");

        return;

    }

    /* top and base may be valid, but let's make sure that base is reachable

     * from top */

    if (bdrv_find_backing_image(top, base->filename) != base) {

        error_setg(errp,

                   "Base (%s) is not reachable from top (%s)",

                   base->filename, top->filename);

        return;

    }

    overlay_bs = bdrv_find_overlay(bs, top);

    if (overlay_bs == NULL) {

        error_setg(errp, "Could not find overlay image for %s:", top->filename);

        return;

    }

    orig_base_flags    = bdrv_get_flags(base);

    orig_overlay_flags = bdrv_get_flags(overlay_bs);

    /* convert base & overlay_bs to r/w, if necessary */

    if (!(orig_base_flags & BDRV_O_RDWR)) {

        reopen_queue = bdrv_reopen_queue(reopen_queue, base,

                                         orig_base_flags | BDRV_O_RDWR);

    }

    if (!(orig_overlay_flags & BDRV_O_RDWR)) {

        reopen_queue = bdrv_reopen_queue(reopen_queue, overlay_bs,

                                         orig_overlay_flags | BDRV_O_RDWR);

    }

    if (reopen_queue) {

        bdrv_reopen_multiple(reopen_queue, &local_err);

        if (local_err != NULL) {

            error_propagate(errp, local_err);

            return;

        }

    }

    s = block_job_create(&commit_job_type, bs, speed, cb, opaque, errp);

    if (!s) {

        return;

    }

    s->base   = base;

    s->top    = top;

    s->active = bs;

    s->base_flags          = orig_base_flags;

    s->orig_overlay_flags  = orig_overlay_flags;

    s->on_error = on_error;

    s->common.co = qemu_coroutine_create(commit_run);

    trace_commit_start(bs, base, top, s, s->common.co, opaque);

    qemu_coroutine_enter(s->common.co, s);

}


static void check_guest_output(const testdef_t *test, int fd)

{

    bool output_ok = false;

    int i, nbr, pos = 0;

    char ch;

    /* Poll serial output... Wait at most 60 seconds */

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

        while ((nbr = read(fd, &ch, 1)) == 1) {

            if (ch == test->expect[pos]) {

                pos += 1;

                if (test->expect[pos] == '\0') {

                    /* We've reached the end of the expected string! */

                    output_ok = true;

                    goto done;

                }

            } else {

                pos = 0;

            }

        }

        g_assert(nbr >= 0);

        g_usleep(10000);

    }

done:

    g_assert(output_ok);

}


static void do_subtitle_out(AVFormatContext *s,

                            AVOutputStream *ost,

                            AVInputStream *ist,

                            AVSubtitle *sub,

                            int64_t pts)

{

    static uint8_t *subtitle_out = NULL;

    int subtitle_out_max_size = 65536;

    int subtitle_out_size, nb, i;

    AVCodecContext *enc;

    AVPacket pkt;

    if (pts == AV_NOPTS_VALUE) {

        fprintf(stderr, "Subtitle packets must have a pts\n");

        if (exit_on_error)

        return;

    enc = ost->st->codec;

    if (!subtitle_out) {

        subtitle_out = av_malloc(subtitle_out_max_size);

    /* Note: DVB subtitle need one packet to draw them and one other

       packet to clear them */

    /* XXX: signal it in the codec context ? */

    if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)

        nb = 2;

    else

        nb = 1;

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

        sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q);

        subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,

                                                    subtitle_out_max_size, sub);

        av_init_packet(&pkt);

        pkt.stream_index = ost->index;

        pkt.data = subtitle_out;

        pkt.size = subtitle_out_size;

        pkt.pts = av_rescale_q(pts, ist->st->time_base, ost->st->time_base);

        if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {

            /* XXX: the pts correction is handled here. Maybe handling

               it in the codec would be better */

            if (i == 0)

                pkt.pts += 90 * sub->start_display_time;

            else

                pkt.pts += 90 * sub->end_display_time;

        write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);


static int handle_sw_breakpoint(S390CPU *cpu, struct kvm_run *run)

{

    CPUS390XState *env = &cpu->env;

    unsigned long pc;

    cpu_synchronize_state(CPU(cpu));

    pc = env->psw.addr - 4;

    if (kvm_find_sw_breakpoint(CPU(cpu), pc)) {

        env->psw.addr = pc;

        return EXCP_DEBUG;

    }

    return -ENOENT;

}


static void vhost_dev_sync_region(struct vhost_dev *dev,

                                  MemoryRegionSection *section,

                                  uint64_t mfirst, uint64_t mlast,

                                  uint64_t rfirst, uint64_t rlast)

{

    uint64_t start = MAX(mfirst, rfirst);

    uint64_t end = MIN(mlast, rlast);

    vhost_log_chunk_t *from = dev->log + start / VHOST_LOG_CHUNK;

    vhost_log_chunk_t *to = dev->log + end / VHOST_LOG_CHUNK + 1;

    uint64_t addr = (start / VHOST_LOG_CHUNK) * VHOST_LOG_CHUNK;

    if (end < start) {

        return;

    }

    assert(end / VHOST_LOG_CHUNK < dev->log_size);

    assert(start / VHOST_LOG_CHUNK < dev->log_size);

    for (;from < to; ++from) {

        vhost_log_chunk_t log;

        int bit;

        /* We first check with non-atomic: much cheaper,

         * and we expect non-dirty to be the common case. */

        if (!*from) {

            addr += VHOST_LOG_CHUNK;

            continue;

        }

        /* Data must be read atomically. We don't really

         * need the barrier semantics of __sync

         * builtins, but it's easier to use them than

         * roll our own. */

        log = __sync_fetch_and_and(from, 0);

        while ((bit = sizeof(log) > sizeof(int) ?

                ffsll(log) : ffs(log))) {

            ram_addr_t ram_addr;

            bit -= 1;

            ram_addr = section->offset_within_region + bit * VHOST_LOG_PAGE;

            memory_region_set_dirty(section->mr, ram_addr, VHOST_LOG_PAGE);

            log &= ~(0x1ull << bit);

        }

        addr += VHOST_LOG_CHUNK;

    }

}


int nbd_client_co_pdiscard(BlockDriverState *bs, int64_t offset, int count)

{

    NBDClientSession *client = nbd_get_client_session(bs);

    NBDRequest request = {

        .type = NBD_CMD_TRIM,

        .from = offset,

        .len = count,

    };

    NBDReply reply;

    ssize_t ret;

    if (!(client->nbdflags & NBD_FLAG_SEND_TRIM)) {

        return 0;

    }

    nbd_coroutine_start(client, &request);

    ret = nbd_co_send_request(bs, &request, NULL);

    if (ret < 0) {

        reply.error = -ret;

    } else {

        nbd_co_receive_reply(client, &request, &reply, NULL);

    }

    nbd_coroutine_end(bs, &request);

    return -reply.error;

}


int qcow2_check_refcounts(BlockDriverState *bs)

{

    BDRVQcowState *s = bs->opaque;

    int64_t size;

    int nb_clusters, refcount1, refcount2, i;

    QCowSnapshot *sn;

    uint16_t *refcount_table;

    int ret, errors = 0;

    size = bdrv_getlength(bs->file);

    nb_clusters = size_to_clusters(s, size);

    refcount_table = qemu_mallocz(nb_clusters * sizeof(uint16_t));

    /* header */

    errors += inc_refcounts(bs, refcount_table, nb_clusters,

                  0, s->cluster_size);

    /* current L1 table */

    ret = check_refcounts_l1(bs, refcount_table, nb_clusters,

                       s->l1_table_offset, s->l1_size, 1);

    if (ret < 0) {

        return ret;

    }

    errors += ret;

    /* snapshots */

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

        sn = s->snapshots + i;

        check_refcounts_l1(bs, refcount_table, nb_clusters,

                           sn->l1_table_offset, sn->l1_size, 0);

    }

    errors += inc_refcounts(bs, refcount_table, nb_clusters,

                  s->snapshots_offset, s->snapshots_size);

    /* refcount data */

    errors += inc_refcounts(bs, refcount_table, nb_clusters,

                  s->refcount_table_offset,

                  s->refcount_table_size * sizeof(uint64_t));

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

        int64_t offset;

        offset = s->refcount_table[i];

        /* Refcount blocks are cluster aligned */

        if (offset & (s->cluster_size - 1)) {

            fprintf(stderr, "ERROR refcount block %d is not "

                "cluster aligned; refcount table entry corrupted\n", i);

            errors++;

        }

        if (offset != 0) {

            errors += inc_refcounts(bs, refcount_table, nb_clusters,

                          offset, s->cluster_size);

            if (refcount_table[offset / s->cluster_size] != 1) {

                fprintf(stderr, "ERROR refcount block %d refcount=%d\n",

                    i, refcount_table[offset / s->cluster_size]);

            }

        }

    }

    /* compare ref counts */

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

        refcount1 = get_refcount(bs, i);

        if (refcount1 < 0) {

            fprintf(stderr, "Can't get refcount for cluster %d: %s\n",

                i, strerror(-refcount1));

        }

        refcount2 = refcount_table[i];

        if (refcount1 != refcount2) {

            fprintf(stderr, "ERROR cluster %d refcount=%d reference=%d\n",

                   i, refcount1, refcount2);

            errors++;

        }

    }

    qemu_free(refcount_table);

    return errors;

}


static int caf_write_trailer(AVFormatContext *s)

{

    AVIOContext *pb = s->pb;

    AVCodecContext *enc = s->streams[0]->codec;

    if (pb->seekable) {

        CAFContext *caf = s->priv_data;

        int64_t file_size = avio_tell(pb);

        avio_seek(pb, caf->data, SEEK_SET);

        avio_wb64(pb, file_size - caf->data - 8);

        avio_seek(pb, file_size, SEEK_SET);

        if (!enc->block_align) {

            ffio_wfourcc(pb, "pakt");

            avio_wb64(pb, caf->size_entries_used + 24);

            avio_wb64(pb, caf->packets); ///< mNumberPackets

            avio_wb64(pb, caf->packets * samples_per_packet(enc->codec_id, enc->channels)); ///< mNumberValidFrames

            avio_wb32(pb, 0); ///< mPrimingFrames

            avio_wb32(pb, 0); ///< mRemainderFrames

            avio_write(pb, caf->pkt_sizes, caf->size_entries_used);

            av_freep(&caf->pkt_sizes);

            caf->size_buffer_size = 0;

        }

        avio_flush(pb);

    }

    return 0;

}


static void init_proc_970GX (CPUPPCState *env)

{

    gen_spr_ne_601(env);

    gen_spr_7xx(env);

    /* Time base */

    gen_tbl(env);

    /* Hardware implementation registers */

    /* XXX : not implemented */

    spr_register(env, SPR_HID0, "HID0",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_clear,

                 0x60000000);

    /* XXX : not implemented */

    spr_register(env, SPR_HID1, "HID1",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_750_HID2, "HID2",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_970_HID5, "HID5",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

#if defined(CONFIG_USER_ONLY)

                 0x00000080

#else

                 0x00000000

#endif

                 );

    /* Memory management */

    /* XXX: not correct */

    gen_low_BATs(env);

#if 0 // TODO

    env->slb_nr = 32;

#endif

    init_excp_970(env);

    env->dcache_line_size = 128;

    env->icache_line_size = 128;

    /* Allocate hardware IRQ controller */

    ppc970_irq_init(env);

}


static int find_marker(const uint8_t **pbuf_ptr, const uint8_t *buf_end)

{

    const uint8_t *buf_ptr;

    unsigned int v, v2;

    int val;

    int skipped = 0;

    buf_ptr = *pbuf_ptr;

    while (buf_ptr < buf_end) {

        v  = *buf_ptr++;

        v2 = *buf_ptr;

        if ((v == 0xff) && (v2 >= 0xc0) && (v2 <= 0xfe) && buf_ptr < buf_end) {

            val = *buf_ptr++;

            goto found;

        }

        skipped++;

    }

    val = -1;

found:

    av_dlog(NULL, "find_marker skipped %d bytes\n", skipped);

    *pbuf_ptr = buf_ptr;

    return val;

}


static int cavs_decode_frame(AVCodecContext * avctx,void *data, int *data_size,

                             AVPacket *avpkt) {

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    AVSContext *h = avctx->priv_data;

    MpegEncContext *s = &h->s;

    int input_size;

    const uint8_t *buf_end;

    const uint8_t *buf_ptr;

    AVFrame *picture = data;

    uint32_t stc = -1;

    s->avctx = avctx;

    if (buf_size == 0) {

        if (!s->low_delay && h->DPB[0].f.data[0]) {

            *data_size = sizeof(AVPicture);

            *picture = *(AVFrame *) &h->DPB[0];

        }

        return 0;

    }

    buf_ptr = buf;

    buf_end = buf + buf_size;

    for(;;) {

        buf_ptr = ff_find_start_code(buf_ptr,buf_end, &stc);

        if(stc & 0xFFFFFE00)

            return FFMAX(0, buf_ptr - buf - s->parse_context.last_index);

        input_size = (buf_end - buf_ptr)*8;

        switch(stc) {

        case CAVS_START_CODE:

            init_get_bits(&s->gb, buf_ptr, input_size);

            decode_seq_header(h);

            break;

        case PIC_I_START_CODE:

            if(!h->got_keyframe) {

                if(h->DPB[0].f.data[0])

                    avctx->release_buffer(avctx, (AVFrame *)&h->DPB[0]);

                if(h->DPB[1].f.data[0])

                    avctx->release_buffer(avctx, (AVFrame *)&h->DPB[1]);

                h->got_keyframe = 1;

            }

        case PIC_PB_START_CODE:

            *data_size = 0;

            if(!h->got_keyframe)

                break;

            init_get_bits(&s->gb, buf_ptr, input_size);

            h->stc = stc;

            if(decode_pic(h))

                break;

            *data_size = sizeof(AVPicture);

            if(h->pic_type != AV_PICTURE_TYPE_B) {

                if(h->DPB[1].f.data[0]) {

                    *picture = *(AVFrame *) &h->DPB[1];

                } else {

                    *data_size = 0;

                }

            } else

                *picture = *(AVFrame *) &h->picture;

            break;

        case EXT_START_CODE:

            //mpeg_decode_extension(avctx,buf_ptr, input_size);

            break;

        case USER_START_CODE:

            //mpeg_decode_user_data(avctx,buf_ptr, input_size);

            break;

        default:

            if (stc <= SLICE_MAX_START_CODE) {

                init_get_bits(&s->gb, buf_ptr, input_size);

                decode_slice_header(h, &s->gb);

            }

            break;

        }

    }

}


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

{

    PCIDevice *s = container_of(pv, PCIDevice, config);

    uint8_t config[size];

    int i;

    qemu_get_buffer(f, config, size);

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

        if ((config[i] ^ s->config[i]) & s->cmask[i] & ~s->wmask[i])

            return -EINVAL;

    memcpy(s->config, config, size);

    pci_update_mappings(s);

    return 0;

}


static void update_md5_sum(FlacEncodeContext *s, const int16_t *samples)

{

#if HAVE_BIGENDIAN

    int i;

    for (i = 0; i < s->frame.blocksize * s->channels; i++) {

        int16_t smp = av_le2ne16(samples[i]);

        av_md5_update(s->md5ctx, (uint8_t *)&smp, 2);

    }

#else

    av_md5_update(s->md5ctx, (const uint8_t *)samples, s->frame.blocksize*s->channels*2);

#endif

}


static int cuvid_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt)

{

    CuvidContext *ctx = avctx->priv_data;

    AVHWDeviceContext *device_ctx = (AVHWDeviceContext*)ctx->hwdevice->data;

    AVCUDADeviceContext *device_hwctx = device_ctx->hwctx;

    CUcontext dummy, cuda_ctx = device_hwctx->cuda_ctx;

    AVFrame *frame = data;

    CUVIDSOURCEDATAPACKET cupkt;

    AVPacket filter_packet = { 0 };

    AVPacket filtered_packet = { 0 };

    CUdeviceptr mapped_frame = 0;

    int ret = 0, eret = 0;

    if (ctx->bsf && avpkt->size) {

        if ((ret = av_packet_ref(&filter_packet, avpkt)) < 0) {

            av_log(avctx, AV_LOG_ERROR, "av_packet_ref failed\n");

            return ret;

        }

        if ((ret = av_bsf_send_packet(ctx->bsf, &filter_packet)) < 0) {

            av_log(avctx, AV_LOG_ERROR, "av_bsf_send_packet failed\n");

            av_packet_unref(&filter_packet);

            return ret;

        }

        if ((ret = av_bsf_receive_packet(ctx->bsf, &filtered_packet)) < 0) {

            av_log(avctx, AV_LOG_ERROR, "av_bsf_receive_packet failed\n");

            return ret;

        }

        avpkt = &filtered_packet;

    }

    ret = CHECK_CU(cuCtxPushCurrent(cuda_ctx));

    if (ret < 0) {

        av_packet_unref(&filtered_packet);

        return ret;

    }

    memset(&cupkt, 0, sizeof(cupkt));

    if (avpkt->size) {

        cupkt.payload_size = avpkt->size;

        cupkt.payload = avpkt->data;

        if (avpkt->pts != AV_NOPTS_VALUE) {

            cupkt.flags = CUVID_PKT_TIMESTAMP;

            cupkt.timestamp = av_rescale_q(avpkt->pts, avctx->pkt_timebase, (AVRational){1, 10000000});

        }

    } else {

        cupkt.flags = CUVID_PKT_ENDOFSTREAM;

    }

    ret = CHECK_CU(cuvidParseVideoData(ctx->cuparser, &cupkt));

    av_packet_unref(&filtered_packet);

    if (ret < 0) {

        if (ctx->internal_error)

            ret = ctx->internal_error;

        goto error;

    }

    if (av_fifo_size(ctx->frame_queue)) {

        CUVIDPARSERDISPINFO dispinfo;

        CUVIDPROCPARAMS params;

        unsigned int pitch = 0;

        int offset = 0;

        int i;

        av_fifo_generic_read(ctx->frame_queue, &dispinfo, sizeof(CUVIDPARSERDISPINFO), NULL);

        memset(&params, 0, sizeof(params));

        params.progressive_frame = dispinfo.progressive_frame;

        params.second_field = 0;

        params.top_field_first = dispinfo.top_field_first;

        ret = CHECK_CU(cuvidMapVideoFrame(ctx->cudecoder, dispinfo.picture_index, &mapped_frame, &pitch, &params));

        if (ret < 0)

            goto error;

        if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {

            ret = av_hwframe_get_buffer(ctx->hwframe, frame, 0);

            if (ret < 0) {

                av_log(avctx, AV_LOG_ERROR, "av_hwframe_get_buffer failed\n");

                goto error;

            }

            ret = ff_decode_frame_props(avctx, frame);

            if (ret < 0) {

                av_log(avctx, AV_LOG_ERROR, "ff_decode_frame_props failed\n");

                goto error;

            }

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

                CUDA_MEMCPY2D cpy = {

                    .srcMemoryType = CU_MEMORYTYPE_DEVICE,

                    .dstMemoryType = CU_MEMORYTYPE_DEVICE,

                    .srcDevice     = mapped_frame,

                    .dstDevice     = (CUdeviceptr)frame->data[i],

                    .srcPitch      = pitch,

                    .dstPitch      = frame->linesize[i],

                    .srcY          = offset,

                    .WidthInBytes  = FFMIN(pitch, frame->linesize[i]),

                    .Height        = avctx->coded_height >> (i ? 1 : 0),

                };

                ret = CHECK_CU(cuMemcpy2D(&cpy));

                if (ret < 0)

                    goto error;

                offset += avctx->coded_height;

            }

        } else if (avctx->pix_fmt == AV_PIX_FMT_NV12) {

            AVFrame *tmp_frame = av_frame_alloc();

            if (!tmp_frame) {

                av_log(avctx, AV_LOG_ERROR, "av_frame_alloc failed\n");

                ret = AVERROR(ENOMEM);

                goto error;

            }

            tmp_frame->format        = AV_PIX_FMT_CUDA;

            tmp_frame->hw_frames_ctx = av_buffer_ref(ctx->hwframe);

            tmp_frame->data[0]       = (uint8_t*)mapped_frame;

            tmp_frame->linesize[0]   = pitch;

            tmp_frame->data[1]       = (uint8_t*)(mapped_frame + avctx->coded_height * pitch);

            tmp_frame->linesize[1]   = pitch;

            tmp_frame->width         = avctx->width;

            tmp_frame->height        = avctx->height;

            ret = ff_get_buffer(avctx, frame, 0);

            if (ret < 0) {

                av_log(avctx, AV_LOG_ERROR, "ff_get_buffer failed\n");

                av_frame_free(&tmp_frame);

                goto error;

            }

            ret = av_hwframe_transfer_data(frame, tmp_frame, 0);

            if (ret) {

                av_log(avctx, AV_LOG_ERROR, "av_hwframe_transfer_data failed\n");

                av_frame_free(&tmp_frame);

                goto error;

            }

            av_frame_free(&tmp_frame);

        } else {

            ret = AVERROR_BUG;

            goto error;

        }

        frame->width = avctx->width;

        frame->height = avctx->height;

        frame->pts = av_rescale_q(dispinfo.timestamp, (AVRational){1, 10000000}, avctx->pkt_timebase);

        /* CUVIDs opaque reordering breaks the internal pkt logic.

         * So set pkt_pts and clear all the other pkt_ fields.

         */

        frame->pkt_pts = frame->pts;

        av_frame_set_pkt_pos(frame, -1);

        av_frame_set_pkt_duration(frame, 0);

        av_frame_set_pkt_size(frame, -1);

        frame->interlaced_frame = !dispinfo.progressive_frame;

        if (!dispinfo.progressive_frame)

            frame->top_field_first = dispinfo.top_field_first;

        *got_frame = 1;

    } else {

        *got_frame = 0;

    }

error:

    if (mapped_frame)

        eret = CHECK_CU(cuvidUnmapVideoFrame(ctx->cudecoder, mapped_frame));

    eret = CHECK_CU(cuCtxPopCurrent(&dummy));

    if (eret < 0)

        return eret;

    else

        return ret;

}


static void intra_predict_mad_cow_dc_0lt_8x8_msa(uint8_t *src, int32_t stride)

{

    uint8_t lp_cnt;

    uint32_t src0, src1, src2 = 0, src3;

    uint32_t out0, out1, out2, out3;

    v16u8 src_top;

    v8u16 add;

    v4u32 sum;

    src_top = LD_UB(src - stride);

    add = __msa_hadd_u_h(src_top, src_top);

    sum = __msa_hadd_u_w(add, add);

    src0 = __msa_copy_u_w((v4i32) sum, 0);

    src1 = __msa_copy_u_w((v4i32) sum, 1);

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

        src2 += src[(4 + lp_cnt) * stride - 1];

    }

    src0 = (src0 + 2) >> 2;

    src3 = (src1 + src2 + 4) >> 3;

    src1 = (src1 + 2) >> 2;

    src2 = (src2 + 2) >> 2;

    out0 = src0 * 0x01010101;

    out1 = src1 * 0x01010101;

    out2 = src2 * 0x01010101;

    out3 = src3 * 0x01010101;

    for (lp_cnt = 4; lp_cnt--;) {

        SW(out0, src);

        SW(out1, src + 4);

        SW(out2, src + stride * 4);

        SW(out3, src + stride * 4 + 4);

        src += stride;

    }

}


static int img_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)

{

    VideoDemuxData *s1 = s->priv_data;

    if (timestamp < 0 || timestamp > s1->img_last - s1->img_first)

        return -1;

    s1->img_number = timestamp + s1->img_first;

    return 0;

}


static int read_filter_params(MLPDecodeContext *m, GetBitContext *gbp,

                              unsigned int channel, unsigned int filter)

{

    FilterParams *fp = &m->channel_params[channel].filter_params[filter];

    const int max_order = filter ? MAX_IIR_ORDER : MAX_FIR_ORDER;

    const char fchar = filter ? 'I' : 'F';

    int i, order;

    // Filter is 0 for FIR, 1 for IIR.

    assert(filter < 2);

    m->filter_changed[channel][filter]++;

    order = get_bits(gbp, 4);

    if (order > max_order) {

        av_log(m->avctx, AV_LOG_ERROR,

               "%cIR filter order %d is greater than maximum %d.\n",

               fchar, order, max_order);

        return -1;

    }

    fp->order = order;

    if (order > 0) {

        int coeff_bits, coeff_shift;

        fp->shift = get_bits(gbp, 4);

        coeff_bits  = get_bits(gbp, 5);

        coeff_shift = get_bits(gbp, 3);

        if (coeff_bits < 1 || coeff_bits > 16) {

            av_log(m->avctx, AV_LOG_ERROR,

                   "%cIR filter coeff_bits must be between 1 and 16.\n",

                   fchar);

            return -1;

        }

        if (coeff_bits + coeff_shift > 16) {

            av_log(m->avctx, AV_LOG_ERROR,

                   "Sum of coeff_bits and coeff_shift for %cIR filter must be 16 or less.\n",

                   fchar);

            return -1;

        }

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

            fp->coeff[i] = get_sbits(gbp, coeff_bits) << coeff_shift;

        if (get_bits1(gbp)) {

            int state_bits, state_shift;

            if (filter == FIR) {

                av_log(m->avctx, AV_LOG_ERROR,

                       "FIR filter has state data specified.\n");

                return -1;

            }

            state_bits  = get_bits(gbp, 4);

            state_shift = get_bits(gbp, 4);

            /* TODO: Check validity of state data. */

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

                fp->state[i] = get_sbits(gbp, state_bits) << state_shift;

        }

    }

    return 0;

}


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

{

    AVStream *st;

    MOVStreamContext *sc;

    int size;

    int32_t yaw, pitch, roll;

    size_t l = 0, t = 0, r = 0, b = 0;

    size_t padding = 0;

    uint32_t tag;

    enum AVSphericalProjection projection;

    if (c->fc->nb_streams < 1)

        return 0;

    st = c->fc->streams[c->fc->nb_streams - 1];

    sc = st->priv_data;

    if (atom.size < 8) {

        av_log(c->fc, AV_LOG_ERROR, "Empty spherical video box\n");

        return AVERROR_INVALIDDATA;

    }

    size = avio_rb32(pb);

    if (size <= 12 || size > atom.size)

        return AVERROR_INVALIDDATA;

    tag = avio_rl32(pb);

    if (tag != MKTAG('s','v','h','d')) {

        av_log(c->fc, AV_LOG_ERROR, "Missing spherical video header\n");

        return 0;

    }

    avio_skip(pb, 4); /*  version + flags */

    avio_skip(pb, size - 12); /* metadata_source */

    size = avio_rb32(pb);

    if (size > atom.size)

        return AVERROR_INVALIDDATA;

    tag = avio_rl32(pb);

    if (tag != MKTAG('p','r','o','j')) {

        av_log(c->fc, AV_LOG_ERROR, "Missing projection box\n");

        return 0;

    }

    size = avio_rb32(pb);

    if (size > atom.size)

        return AVERROR_INVALIDDATA;

    tag = avio_rl32(pb);

    if (tag != MKTAG('p','r','h','d')) {

        av_log(c->fc, AV_LOG_ERROR, "Missing projection header box\n");

        return 0;

    }

    avio_skip(pb, 4); /*  version + flags */

    /* 16.16 fixed point */

    yaw   = avio_rb32(pb);

    pitch = avio_rb32(pb);

    roll  = avio_rb32(pb);

    size = avio_rb32(pb);

    if (size > atom.size)

        return AVERROR_INVALIDDATA;

    tag = avio_rl32(pb);

    avio_skip(pb, 4); /*  version + flags */

    switch (tag) {

    case MKTAG('c','b','m','p'):

        projection = AV_SPHERICAL_CUBEMAP;

        padding = avio_rb32(pb);

        break;

    case MKTAG('e','q','u','i'):

        t = avio_rb32(pb);

        b = avio_rb32(pb);

        l = avio_rb32(pb);

        r = avio_rb32(pb);

        if (b >= UINT_MAX - t || r >= UINT_MAX - l) {

            av_log(c->fc, AV_LOG_ERROR,

                   "Invalid bounding rectangle coordinates %"SIZE_SPECIFIER","

                   "%"SIZE_SPECIFIER",%"SIZE_SPECIFIER",%"SIZE_SPECIFIER"\n",

                   l, t, r, b);

            return AVERROR_INVALIDDATA;

        }

        if (l || t || r || b)

            projection = AV_SPHERICAL_EQUIRECTANGULAR_TILE;

        else

            projection = AV_SPHERICAL_EQUIRECTANGULAR;

        break;

    default:

        av_log(c->fc, AV_LOG_ERROR, "Unknown projection type\n");

        return 0;

    }

    sc->spherical = av_spherical_alloc(&sc->spherical_size);

    if (!sc->spherical)

        return AVERROR(ENOMEM);

    sc->spherical->projection = projection;

    sc->spherical->yaw   = yaw;

    sc->spherical->pitch = pitch;

    sc->spherical->roll  = roll;

    sc->spherical->padding = padding;

    sc->spherical->bound_left   = l;

    sc->spherical->bound_top    = t;

    sc->spherical->bound_right  = r;

    sc->spherical->bound_bottom = b;

    return 0;

}


struct tm *brktimegm(time_t secs, struct tm *tm)

{

    int days, y, ny, m;

    int md[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

    days = secs / 86400;

    secs %= 86400;

    tm->tm_hour = secs / 3600;

    tm->tm_min = (secs % 3600) / 60;

    tm->tm_sec =  secs % 60;

    /* oh well, may be someone some day will invent a formula for this stuff */

    y = 1970; /* start "guessing" */

    while (days >= (ISLEAP(y)?366:365)) {

        ny = (y + days/366);

        days -= (ny - y) * 365 + LEAPS_COUNT(ny - 1) - LEAPS_COUNT(y - 1);

        y = ny;

    }

    md[1] = ISLEAP(y)?29:28;

    for (m=0; days >= md[m]; m++)

         days -= md[m];

    tm->tm_year = y;  /* unlike gmtime_r we store complete year here */

    tm->tm_mon = m+1; /* unlike gmtime_r tm_mon is from 1 to 12 */

    tm->tm_mday = days+1;

    return tm;

}


static int dnxhd_decode_macroblock(const DNXHDContext *ctx, RowContext *row,

                                   AVFrame *frame, int x, int y)

{

    int shift1 = ctx->bit_depth >= 10;

    int dct_linesize_luma   = frame->linesize[0];

    int dct_linesize_chroma = frame->linesize[1];

    uint8_t *dest_y, *dest_u, *dest_v;

    int dct_y_offset, dct_x_offset;

    int qscale, i, act;

    int interlaced_mb = 0;

    if (ctx->mbaff) {

        interlaced_mb = get_bits1(&row->gb);

        qscale = get_bits(&row->gb, 10);

    } else {

        qscale = get_bits(&row->gb, 11);

    }

    act = get_bits1(&row->gb);

    if (act) {

        static int warned = 0;

        if (!warned) {

            warned = 1;

            av_log(ctx->avctx, AV_LOG_ERROR,

                   "Unsupported adaptive color transform, patch welcome.\n");

        }

    }

    if (qscale != row->last_qscale) {

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

            row->luma_scale[i]   = qscale * ctx->cid_table->luma_weight[i];

            row->chroma_scale[i] = qscale * ctx->cid_table->chroma_weight[i];

        }

        row->last_qscale = qscale;

    }

    for (i = 0; i < 8 + 4 * ctx->is_444; i++) {

        if (ctx->decode_dct_block(ctx, row, i) < 0)

            return AVERROR_INVALIDDATA;

    }

    if (frame->interlaced_frame) {

        dct_linesize_luma   <<= 1;

        dct_linesize_chroma <<= 1;

    }

    dest_y = frame->data[0] + ((y * dct_linesize_luma)   << 4) + (x << (4 + shift1));

    dest_u = frame->data[1] + ((y * dct_linesize_chroma) << 4) + (x << (3 + shift1 + ctx->is_444));

    dest_v = frame->data[2] + ((y * dct_linesize_chroma) << 4) + (x << (3 + shift1 + ctx->is_444));

    if (frame->interlaced_frame && ctx->cur_field) {

        dest_y += frame->linesize[0];

        dest_u += frame->linesize[1];

        dest_v += frame->linesize[2];

    }

    if (interlaced_mb) {

        dct_linesize_luma   <<= 1;

        dct_linesize_chroma <<= 1;

    }

    dct_y_offset = interlaced_mb ? frame->linesize[0] : (dct_linesize_luma << 3);

    dct_x_offset = 8 << shift1;

    if (!ctx->is_444) {

        ctx->idsp.idct_put(dest_y,                               dct_linesize_luma, row->blocks[0]);

        ctx->idsp.idct_put(dest_y + dct_x_offset,                dct_linesize_luma, row->blocks[1]);

        ctx->idsp.idct_put(dest_y + dct_y_offset,                dct_linesize_luma, row->blocks[4]);

        ctx->idsp.idct_put(dest_y + dct_y_offset + dct_x_offset, dct_linesize_luma, row->blocks[5]);

        if (!(ctx->avctx->flags & AV_CODEC_FLAG_GRAY)) {

            dct_y_offset = interlaced_mb ? frame->linesize[1] : (dct_linesize_chroma << 3);

            ctx->idsp.idct_put(dest_u,                dct_linesize_chroma, row->blocks[2]);

            ctx->idsp.idct_put(dest_v,                dct_linesize_chroma, row->blocks[3]);

            ctx->idsp.idct_put(dest_u + dct_y_offset, dct_linesize_chroma, row->blocks[6]);

            ctx->idsp.idct_put(dest_v + dct_y_offset, dct_linesize_chroma, row->blocks[7]);

        }

    } else {

        ctx->idsp.idct_put(dest_y,                               dct_linesize_luma, row->blocks[0]);

        ctx->idsp.idct_put(dest_y + dct_x_offset,                dct_linesize_luma, row->blocks[1]);

        ctx->idsp.idct_put(dest_y + dct_y_offset,                dct_linesize_luma, row->blocks[6]);

        ctx->idsp.idct_put(dest_y + dct_y_offset + dct_x_offset, dct_linesize_luma, row->blocks[7]);

        if (!(ctx->avctx->flags & AV_CODEC_FLAG_GRAY)) {

            dct_y_offset = interlaced_mb ? frame->linesize[1] : (dct_linesize_chroma << 3);

            ctx->idsp.idct_put(dest_u,                               dct_linesize_chroma, row->blocks[2]);

            ctx->idsp.idct_put(dest_u + dct_x_offset,                dct_linesize_chroma, row->blocks[3]);

            ctx->idsp.idct_put(dest_u + dct_y_offset,                dct_linesize_chroma, row->blocks[8]);

            ctx->idsp.idct_put(dest_u + dct_y_offset + dct_x_offset, dct_linesize_chroma, row->blocks[9]);

            ctx->idsp.idct_put(dest_v,                               dct_linesize_chroma, row->blocks[4]);

            ctx->idsp.idct_put(dest_v + dct_x_offset,                dct_linesize_chroma, row->blocks[5]);

            ctx->idsp.idct_put(dest_v + dct_y_offset,                dct_linesize_chroma, row->blocks[10]);

            ctx->idsp.idct_put(dest_v + dct_y_offset + dct_x_offset, dct_linesize_chroma, row->blocks[11]);

        }

    }

    return 0;

}


static int get_audio_flags(AVCodecContext *enc){

    int flags = (enc->bits_per_coded_sample == 16) ? FLV_SAMPLESSIZE_16BIT : FLV_SAMPLESSIZE_8BIT;

    if (enc->codec_id == CODEC_ID_AAC) // specs force these parameters

        return FLV_CODECID_AAC | FLV_SAMPLERATE_44100HZ | FLV_SAMPLESSIZE_16BIT | FLV_STEREO;

    else if (enc->codec_id == CODEC_ID_SPEEX) {

        if (enc->sample_rate != 16000) {

            av_log(enc, AV_LOG_ERROR, "flv only supports wideband (16kHz) Speex audio\n");

            return -1;

        }

        if (enc->channels != 1) {

            av_log(enc, AV_LOG_ERROR, "flv only supports mono Speex audio\n");

            return -1;

        }

        if (enc->frame_size / 320 > 8) {

            av_log(enc, AV_LOG_WARNING, "Warning: Speex stream has more than "

                                        "8 frames per packet. Adobe Flash "

                                        "Player cannot handle this!\n");

        }

        return FLV_CODECID_SPEEX | FLV_SAMPLERATE_11025HZ | FLV_SAMPLESSIZE_16BIT;

    } else {

    switch (enc->sample_rate) {

        case    44100:

            flags |= FLV_SAMPLERATE_44100HZ;

            break;

        case    22050:

            flags |= FLV_SAMPLERATE_22050HZ;

            break;

        case    11025:

            flags |= FLV_SAMPLERATE_11025HZ;

            break;

        case     8000: //nellymoser only

        case     5512: //not mp3

            if(enc->codec_id != CODEC_ID_MP3){

                flags |= FLV_SAMPLERATE_SPECIAL;

                break;

            }

        default:

            av_log(enc, AV_LOG_ERROR, "flv does not support that sample rate, choose from (44100, 22050, 11025).\n");

            return -1;

    }

    }

    if (enc->channels > 1) {

        flags |= FLV_STEREO;

    }

    switch(enc->codec_id){

    case CODEC_ID_MP3:

        flags |= FLV_CODECID_MP3    | FLV_SAMPLESSIZE_16BIT;

        break;

    case CODEC_ID_PCM_U8:

        flags |= FLV_CODECID_PCM    | FLV_SAMPLESSIZE_8BIT;

        break;

    case CODEC_ID_PCM_S16BE:

        flags |= FLV_CODECID_PCM    | FLV_SAMPLESSIZE_16BIT;

        break;

    case CODEC_ID_PCM_S16LE:

        flags |= FLV_CODECID_PCM_LE | FLV_SAMPLESSIZE_16BIT;

        break;

    case CODEC_ID_ADPCM_SWF:

        flags |= FLV_CODECID_ADPCM | FLV_SAMPLESSIZE_16BIT;

        break;

    case CODEC_ID_NELLYMOSER:

        if (enc->sample_rate == 8000) {

            flags |= FLV_CODECID_NELLYMOSER_8KHZ_MONO | FLV_SAMPLESSIZE_16BIT;

        } else {

            flags |= FLV_CODECID_NELLYMOSER | FLV_SAMPLESSIZE_16BIT;

        }

        break;

    case 0:

        flags |= enc->codec_tag<<4;

        break;

    default:

        av_log(enc, AV_LOG_ERROR, "codec not compatible with flv\n");

        return -1;

    }

    return flags;

}


static int init_output_stream_encode(OutputStream *ost)

{

    InputStream *ist = get_input_stream(ost);

    AVCodecContext *enc_ctx = ost->enc_ctx;

    AVCodecContext *dec_ctx = NULL;

    AVFormatContext *oc = output_files[ost->file_index]->ctx;

    int j, ret;

    set_encoder_id(output_files[ost->file_index], ost);

    if (ist) {

        ost->st->disposition          = ist->st->disposition;

        dec_ctx = ist->dec_ctx;

        enc_ctx->chroma_sample_location = dec_ctx->chroma_sample_location;

    } else {

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

            AVStream *st = oc->streams[j];

            if (st != ost->st && st->codecpar->codec_type == ost->st->codecpar->codec_type)

                break;

        }

        if (j == oc->nb_streams)

            if (ost->st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO ||

                ost->st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)

                ost->st->disposition = AV_DISPOSITION_DEFAULT;

    }

    if ((enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||

         enc_ctx->codec_type == AVMEDIA_TYPE_AUDIO) &&

         filtergraph_is_simple(ost->filter->graph)) {

            FilterGraph *fg = ost->filter->graph;

            if (configure_filtergraph(fg)) {

                av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");

                exit_program(1);

            }

    }

    if (enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO) {

        if (!ost->frame_rate.num)

            ost->frame_rate = av_buffersink_get_frame_rate(ost->filter->filter);

        if (ist && !ost->frame_rate.num)

            ost->frame_rate = ist->framerate;

        if (ist && !ost->frame_rate.num)

            ost->frame_rate = ist->st->r_frame_rate;

        if (ist && !ost->frame_rate.num) {

            ost->frame_rate = (AVRational){25, 1};

            av_log(NULL, AV_LOG_WARNING,

                   "No information "

                   "about the input framerate is available. Falling "

                   "back to a default value of 25fps for output stream #%d:%d. Use the -r option "

                   "if you want a different framerate.\n",

                   ost->file_index, ost->index);

        }

//      ost->frame_rate = ist->st->avg_frame_rate.num ? ist->st->avg_frame_rate : (AVRational){25, 1};

        if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {

            int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);

            ost->frame_rate = ost->enc->supported_framerates[idx];

        }

        // reduce frame rate for mpeg4 to be within the spec limits

        if (enc_ctx->codec_id == AV_CODEC_ID_MPEG4) {

            av_reduce(&ost->frame_rate.num, &ost->frame_rate.den,

                      ost->frame_rate.num, ost->frame_rate.den, 65535);

        }

    }

    switch (enc_ctx->codec_type) {

    case AVMEDIA_TYPE_AUDIO:

        enc_ctx->sample_fmt     = av_buffersink_get_format(ost->filter->filter);

        if (dec_ctx)

            enc_ctx->bits_per_raw_sample = FFMIN(dec_ctx->bits_per_raw_sample,

                                                 av_get_bytes_per_sample(enc_ctx->sample_fmt) << 3);

        enc_ctx->sample_rate    = av_buffersink_get_sample_rate(ost->filter->filter);

        enc_ctx->channel_layout = av_buffersink_get_channel_layout(ost->filter->filter);

        enc_ctx->channels       = av_buffersink_get_channels(ost->filter->filter);

        enc_ctx->time_base      = (AVRational){ 1, enc_ctx->sample_rate };

        break;

    case AVMEDIA_TYPE_VIDEO:

        enc_ctx->time_base = av_inv_q(ost->frame_rate);

        if (!(enc_ctx->time_base.num && enc_ctx->time_base.den))

            enc_ctx->time_base = av_buffersink_get_time_base(ost->filter->filter);

        if (   av_q2d(enc_ctx->time_base) < 0.001 && video_sync_method != VSYNC_PASSTHROUGH

           && (video_sync_method == VSYNC_CFR || video_sync_method == VSYNC_VSCFR || (video_sync_method == VSYNC_AUTO && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){

            av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not efficiently supporting it.\n"

                                       "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");

        }

        for (j = 0; j < ost->forced_kf_count; j++)

            ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],

                                                 AV_TIME_BASE_Q,

                                                 enc_ctx->time_base);

        enc_ctx->width  = av_buffersink_get_w(ost->filter->filter);

        enc_ctx->height = av_buffersink_get_h(ost->filter->filter);

        enc_ctx->sample_aspect_ratio = ost->st->sample_aspect_ratio =

            ost->frame_aspect_ratio.num ? // overridden by the -aspect cli option

            av_mul_q(ost->frame_aspect_ratio, (AVRational){ enc_ctx->height, enc_ctx->width }) :

            av_buffersink_get_sample_aspect_ratio(ost->filter->filter);

        if (!strncmp(ost->enc->name, "libx264", 7) &&

            enc_ctx->pix_fmt == AV_PIX_FMT_NONE &&

            av_buffersink_get_format(ost->filter->filter) != AV_PIX_FMT_YUV420P)

            av_log(NULL, AV_LOG_WARNING,

                   "No pixel format specified, %s for H.264 encoding chosen.\n"

                   "Use -pix_fmt yuv420p for compatibility with outdated media players.\n",

                   av_get_pix_fmt_name(av_buffersink_get_format(ost->filter->filter)));

        if (!strncmp(ost->enc->name, "mpeg2video", 10) &&

            enc_ctx->pix_fmt == AV_PIX_FMT_NONE &&

            av_buffersink_get_format(ost->filter->filter) != AV_PIX_FMT_YUV420P)

            av_log(NULL, AV_LOG_WARNING,

                   "No pixel format specified, %s for MPEG-2 encoding chosen.\n"

                   "Use -pix_fmt yuv420p for compatibility with outdated media players.\n",

                   av_get_pix_fmt_name(av_buffersink_get_format(ost->filter->filter)));

        enc_ctx->pix_fmt = av_buffersink_get_format(ost->filter->filter);

        if (dec_ctx)

            enc_ctx->bits_per_raw_sample = FFMIN(dec_ctx->bits_per_raw_sample,

                                                 av_pix_fmt_desc_get(enc_ctx->pix_fmt)->comp[0].depth);

        ost->st->avg_frame_rate = ost->frame_rate;

        if (!dec_ctx ||

            enc_ctx->width   != dec_ctx->width  ||

            enc_ctx->height  != dec_ctx->height ||

            enc_ctx->pix_fmt != dec_ctx->pix_fmt) {

            enc_ctx->bits_per_raw_sample = frame_bits_per_raw_sample;

        }

        if (ost->forced_keyframes) {

            if (!strncmp(ost->forced_keyframes, "expr:", 5)) {

                ret = av_expr_parse(&ost->forced_keyframes_pexpr, ost->forced_keyframes+5,

                                    forced_keyframes_const_names, NULL, NULL, NULL, NULL, 0, NULL);

                if (ret < 0) {

                    av_log(NULL, AV_LOG_ERROR,

                           "Invalid force_key_frames expression '%s'\n", ost->forced_keyframes+5);

                    return ret;

                }

                ost->forced_keyframes_expr_const_values[FKF_N] = 0;

                ost->forced_keyframes_expr_const_values[FKF_N_FORCED] = 0;

                ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N] = NAN;

                ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T] = NAN;

            // Don't parse the 'forced_keyframes' in case of 'keep-source-keyframes',

            // parse it only for static kf timings

            } else if(strncmp(ost->forced_keyframes, "source", 6)) {

                parse_forced_key_frames(ost->forced_keyframes, ost, ost->enc_ctx);

            }

        }

        break;

    case AVMEDIA_TYPE_SUBTITLE:

        enc_ctx->time_base = (AVRational){1, 1000};

        if (!enc_ctx->width) {

            enc_ctx->width     = input_streams[ost->source_index]->st->codecpar->width;

            enc_ctx->height    = input_streams[ost->source_index]->st->codecpar->height;

        }

        break;

    case AVMEDIA_TYPE_DATA:

        break;

    default:

        abort();

        break;

    }

    return 0;

}


int avio_put_str16le(AVIOContext *s, const char *str)

{

    const uint8_t *q = str;

    int ret = 0;

    while (*q) {

        uint32_t ch;

        uint16_t tmp;

        GET_UTF8(ch, *q++, break;)

        PUT_UTF16(ch, tmp, avio_wl16(s, tmp); ret += 2;)

    }

    avio_wl16(s, 0);

    ret += 2;

    return ret;

}


void init_get_bits(GetBitContext *s,

                   UINT8 *buffer, int buffer_size)

{

    s->buffer= buffer;

    s->size= buffer_size;

    s->buffer_end= buffer + buffer_size;

#ifdef ALT_BITSTREAM_READER

    s->index=0;

#elif defined LIBMPEG2_BITSTREAM_READER

    s->buffer_ptr = buffer;

    s->bit_count = 16;

    s->cache = 0;

#elif defined A32_BITSTREAM_READER

    s->buffer_ptr = (uint32_t*)buffer;

    s->bit_count = 32;

    s->cache0 = 0;

    s->cache1 = 0;

#endif

    {

        OPEN_READER(re, s)

        UPDATE_CACHE(re, s)

//        UPDATE_CACHE(re, s)

        CLOSE_READER(re, s)

    }

#ifdef A32_BITSTREAM_READER

    s->cache1 = 0;

#endif

}


static int sdp_parse_rtpmap(AVCodecContext *codec, RTSPStream *rtsp_st, int payload_type, const char *p)

{

    char buf[256];

    int i;

    AVCodec *c;

    const char *c_name;

    /* Loop into AVRtpDynamicPayloadTypes[] and AVRtpPayloadTypes[] and

       see if we can handle this kind of payload */

    get_word_sep(buf, sizeof(buf), "/", &p);

    if (payload_type >= RTP_PT_PRIVATE) {

        RTPDynamicProtocolHandler *handler= RTPFirstDynamicPayloadHandler;

        while(handler) {

            if (!strcasecmp(buf, handler->enc_name) && (codec->codec_type == handler->codec_type)) {

                codec->codec_id = handler->codec_id;

                rtsp_st->dynamic_handler= handler;

                if(handler->open) {

                    rtsp_st->dynamic_protocol_context= handler->open();

                }

                break;

            }

            handler= handler->next;

        }

    } else {

        /* We are in a standard case ( from http://www.iana.org/assignments/rtp-parameters) */

        /* search into AVRtpPayloadTypes[] */

        codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);

    }

    c = avcodec_find_decoder(codec->codec_id);

    if (c && c->name)

        c_name = c->name;

    else

        c_name = (char *)NULL;

    if (c_name) {

        get_word_sep(buf, sizeof(buf), "/", &p);

        i = atoi(buf);

        switch (codec->codec_type) {

            case CODEC_TYPE_AUDIO:

                av_log(codec, AV_LOG_DEBUG, " audio codec set to : %s\n", c_name);

                codec->sample_rate = RTSP_DEFAULT_AUDIO_SAMPLERATE;

                codec->channels = RTSP_DEFAULT_NB_AUDIO_CHANNELS;

                if (i > 0) {

                    codec->sample_rate = i;

                    get_word_sep(buf, sizeof(buf), "/", &p);

                    i = atoi(buf);

                    if (i > 0)

                        codec->channels = i;

                    // TODO: there is a bug here; if it is a mono stream, and less than 22000Hz, faad upconverts to stereo and twice the

                    //  frequency.  No problem, but the sample rate is being set here by the sdp line.  Upcoming patch forthcoming. (rdm)

                }

                av_log(codec, AV_LOG_DEBUG, " audio samplerate set to : %i\n", codec->sample_rate);

                av_log(codec, AV_LOG_DEBUG, " audio channels set to : %i\n", codec->channels);

                break;

            case CODEC_TYPE_VIDEO:

                av_log(codec, AV_LOG_DEBUG, " video codec set to : %s\n", c_name);

                break;

            default:

                break;

        }

        return 0;

    }

    return -1;

}


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

{

    VirtIODevice *vdev = VIRTIO_DEVICE(dev);

    VirtIONet *n = VIRTIO_NET(dev);

    NetClientState *nc;

    int i;

    virtio_init(vdev, "virtio-net", VIRTIO_ID_NET, n->config_size);

    n->max_queues = MAX(n->nic_conf.peers.queues, 1);

    n->vqs = g_malloc0(sizeof(VirtIONetQueue) * n->max_queues);

    n->vqs[0].rx_vq = virtio_add_queue(vdev, 256, virtio_net_handle_rx);

    n->curr_queues = 1;

    n->vqs[0].n = n;

    n->tx_timeout = n->net_conf.txtimer;

    if (n->net_conf.tx && strcmp(n->net_conf.tx, "timer")

                       && strcmp(n->net_conf.tx, "bh")) {

        error_report("virtio-net: "

                     "Unknown option tx=%s, valid options: \"timer\" \"bh\"",

                     n->net_conf.tx);

        error_report("Defaulting to \"bh\"");

    if (n->net_conf.tx && !strcmp(n->net_conf.tx, "timer")) {

        n->vqs[0].tx_vq = virtio_add_queue(vdev, 256,

                                           virtio_net_handle_tx_timer);

        n->vqs[0].tx_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, virtio_net_tx_timer,

                                               &n->vqs[0]);

    } else {

        n->vqs[0].tx_vq = virtio_add_queue(vdev, 256,

                                           virtio_net_handle_tx_bh);

        n->vqs[0].tx_bh = qemu_bh_new(virtio_net_tx_bh, &n->vqs[0]);

    n->ctrl_vq = virtio_add_queue(vdev, 64, virtio_net_handle_ctrl);

    qemu_macaddr_default_if_unset(&n->nic_conf.macaddr);

    memcpy(&n->mac[0], &n->nic_conf.macaddr, sizeof(n->mac));

    n->status = VIRTIO_NET_S_LINK_UP;

    n->announce_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL,

                                     virtio_net_announce_timer, n);

    if (n->netclient_type) {

        /*

         * Happen when virtio_net_set_netclient_name has been called.

         */

        n->nic = qemu_new_nic(&net_virtio_info, &n->nic_conf,

                              n->netclient_type, n->netclient_name, n);

    } else {

        n->nic = qemu_new_nic(&net_virtio_info, &n->nic_conf,

                              object_get_typename(OBJECT(dev)), dev->id, n);

    peer_test_vnet_hdr(n);

    if (peer_has_vnet_hdr(n)) {

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

            qemu_using_vnet_hdr(qemu_get_subqueue(n->nic, i)->peer, true);

        n->host_hdr_len = sizeof(struct virtio_net_hdr);

    } else {

        n->host_hdr_len = 0;

    qemu_format_nic_info_str(qemu_get_queue(n->nic), n->nic_conf.macaddr.a);

    n->vqs[0].tx_waiting = 0;

    n->tx_burst = n->net_conf.txburst;

    virtio_net_set_mrg_rx_bufs(n, 0);

    n->promisc = 1; /* for compatibility */

    n->mac_table.macs = g_malloc0(MAC_TABLE_ENTRIES * ETH_ALEN);

    n->vlans = g_malloc0(MAX_VLAN >> 3);

    nc = qemu_get_queue(n->nic);

    nc->rxfilter_notify_enabled = 1;

    n->qdev = dev;

    register_savevm(dev, "virtio-net", -1, VIRTIO_NET_VM_VERSION,

                    virtio_net_save, virtio_net_load, n);


static int avi_read_seek(AVFormatContext *s, int stream_index,

                         int64_t timestamp, int flags)

{

    AVIContext *avi = s->priv_data;

    AVStream *st;

    int i, index;

    int64_t pos, pos_min;

    AVIStream *ast;

    /* Does not matter which stream is requested dv in avi has the

     * stream information in the first video stream.

     */

    if (avi->dv_demux)

        stream_index = 0;

    if (!avi->index_loaded) {

        /* we only load the index on demand */

        avi_load_index(s);

        avi->index_loaded |= 1;

    }

    av_assert0(stream_index >= 0);

    st    = s->streams[stream_index];

    ast   = st->priv_data;

    index = av_index_search_timestamp(st,

                                      timestamp * FFMAX(ast->sample_size, 1),

                                      flags);

    if (index < 0) {

        if (st->nb_index_entries > 0)

            av_log(s, AV_LOG_DEBUG, "Failed to find timestamp %"PRId64 " in index %"PRId64 " .. %"PRId64 "\n",

                   timestamp * FFMAX(ast->sample_size, 1),

                   st->index_entries[0].timestamp,

                   st->index_entries[st->nb_index_entries - 1].timestamp);

        return AVERROR_INVALIDDATA;

    }

    /* find the position */

    pos       = st->index_entries[index].pos;

    timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);

    av_log(s, AV_LOG_TRACE, "XX %"PRId64" %d %"PRId64"\n",

            timestamp, index, st->index_entries[index].timestamp);

    if (CONFIG_DV_DEMUXER && avi->dv_demux) {

        /* One and only one real stream for DV in AVI, and it has video  */

        /* offsets. Calling with other stream indexes should have failed */

        /* the av_index_search_timestamp call above.                     */

        if (avio_seek(s->pb, pos, SEEK_SET) < 0)

            return -1;

        /* Feed the DV video stream version of the timestamp to the */

        /* DV demux so it can synthesize correct timestamps.        */

        ff_dv_offset_reset(avi->dv_demux, timestamp);

        avi->stream_index = -1;

        return 0;

    }

    pos_min = pos;

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

        AVStream *st2   = s->streams[i];

        AVIStream *ast2 = st2->priv_data;

        ast2->packet_size =

        ast2->remaining   = 0;

        if (ast2->sub_ctx) {

            seek_subtitle(st, st2, timestamp);

            continue;

        }

        if (st2->nb_index_entries <= 0)

            continue;

//        av_assert1(st2->codecpar->block_align);

        av_assert0(fabs(av_q2d(st2->time_base) - ast2->scale / (double)ast2->rate) < av_q2d(st2->time_base) * 0.00000001);

        index = av_index_search_timestamp(st2,

                                          av_rescale_q(timestamp,

                                                       st->time_base,

                                                       st2->time_base) *

                                          FFMAX(ast2->sample_size, 1),

                                          flags |

                                          AVSEEK_FLAG_BACKWARD |

                                          (st2->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0));

        if (index < 0)

            index = 0;

        ast2->seek_pos = st2->index_entries[index].pos;

        pos_min = FFMIN(pos_min,ast2->seek_pos);

    }

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

        AVStream *st2 = s->streams[i];

        AVIStream *ast2 = st2->priv_data;

        if (ast2->sub_ctx || st2->nb_index_entries <= 0)

            continue;

        index = av_index_search_timestamp(

                st2,

                av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),

                flags | AVSEEK_FLAG_BACKWARD | (st2->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0));

        if (index < 0)

            index = 0;

        while (!avi->non_interleaved && index>0 && st2->index_entries[index-1].pos >= pos_min)

            index--;

        ast2->frame_offset = st2->index_entries[index].timestamp;

    }

    /* do the seek */

    if (avio_seek(s->pb, pos_min, SEEK_SET) < 0) {

        av_log(s, AV_LOG_ERROR, "Seek failed\n");

        return -1;

    }

    avi->stream_index = -1;

    avi->dts_max      = INT_MIN;

    return 0;

}


void ff_aac_coder_init_mips(AACEncContext *c) {

#if HAVE_INLINE_ASM

    AACCoefficientsEncoder *e = c->coder;

    int option = c->options.aac_coder;

    if (option == 2) {

        e->quantize_and_encode_band = quantize_and_encode_band_mips;

        e->encode_window_bands_info = codebook_trellis_rate;

#if HAVE_MIPSFPU

        e->search_for_quantizers    = search_for_quantizers_twoloop;

#endif /* HAVE_MIPSFPU */

    }

#if HAVE_MIPSFPU

    e->search_for_ms            = search_for_ms_mips;

#endif /* HAVE_MIPSFPU */

#endif /* HAVE_INLINE_ASM */

}


static void gen_wsr_ps(DisasContext *dc, uint32_t sr, TCGv_i32 v)

{

    uint32_t mask = PS_WOE | PS_CALLINC | PS_OWB |

        PS_UM | PS_EXCM | PS_INTLEVEL;

    if (option_enabled(dc, XTENSA_OPTION_MMU)) {

        mask |= PS_RING;

    }

    tcg_gen_andi_i32(cpu_SR[sr], v, mask);

    /* This can change mmu index, so exit tb */

    gen_jumpi(dc, dc->next_pc, -1);

}


uint64_t HELPER(neon_abdl_s32)(uint32_t a, uint32_t b)

{

    uint64_t tmp;

    uint64_t result;

    DO_ABD(result, a, b, int16_t);

    DO_ABD(tmp, a >> 16, b >> 16, int16_t);

    return result | (tmp << 32);

}


static int get_cox(J2kDecoderContext *s, J2kCodingStyle *c)

{

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

        return AVERROR(EINVAL);

          c->nreslevels = bytestream_get_byte(&s->buf) + 1; // num of resolution levels - 1

     c->log2_cblk_width = bytestream_get_byte(&s->buf) + 2; // cblk width

    c->log2_cblk_height = bytestream_get_byte(&s->buf) + 2; // cblk height

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

    if (c->cblk_style != 0){ // cblk style

        av_log(s->avctx, AV_LOG_WARNING, "extra cblk styles %X\n", c->cblk_style);

    }

    c->transform = bytestream_get_byte(&s->buf); // transformation

    if (c->csty & J2K_CSTY_PREC) {

        int i;

        for (i = 0; i < c->nreslevels; i++)

            bytestream_get_byte(&s->buf);

    }

    return 0;

}


QFloat *qobject_to_qfloat(const QObject *obj)

{

    if (qobject_type(obj) != QTYPE_QFLOAT)

        return NULL;

    return container_of(obj, QFloat, base);

}


void HELPER(divu)(CPUM68KState *env, uint32_t word)

{

    uint32_t num;

    uint32_t den;

    uint32_t quot;

    uint32_t rem;

    num = env->div1;

    den = env->div2;

    /* ??? This needs to make sure the throwing location is accurate.  */

    if (den == 0) {

        raise_exception(env, EXCP_DIV0);

    }

    quot = num / den;

    rem = num % den;

    env->cc_v = (word && quot > 0xffff ? -1 : 0);

    env->cc_z = quot;

    env->cc_n = quot;

    env->cc_c = 0;

    env->div1 = quot;

    env->div2 = rem;

}


void cpu_dump_state(CPUState *env, FILE *f,

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

                    int flags)

{

    int i, x;

    cpu_fprintf(f, "pc: " TARGET_FMT_lx "  npc: " TARGET_FMT_lx "\n", env->pc,

                env->npc);

    cpu_fprintf(f, "General Registers:\n");

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

        cpu_fprintf(f, "%%g%c: " TARGET_FMT_lx "\t", i + '0', env->gregs[i]);

    cpu_fprintf(f, "\n");

    for (; i < 8; i++)

        cpu_fprintf(f, "%%g%c: " TARGET_FMT_lx "\t", i + '0', env->gregs[i]);

    cpu_fprintf(f, "\nCurrent Register Window:\n");

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

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

            cpu_fprintf(f, "%%%c%d: " TARGET_FMT_lx "\t",

                    (x == 0 ? 'o' : (x == 1 ? 'l' : 'i')), i,

                    env->regwptr[i + x * 8]);

        cpu_fprintf(f, "\n");

        for (; i < 8; i++)

            cpu_fprintf(f, "%%%c%d: " TARGET_FMT_lx "\t",

                    (x == 0 ? 'o' : x == 1 ? 'l' : 'i'), i,

                    env->regwptr[i + x * 8]);

        cpu_fprintf(f, "\n");

    }

    cpu_fprintf(f, "\nFloating Point Registers:\n");

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

        if ((i & 3) == 0)

            cpu_fprintf(f, "%%f%02d:", i);

        cpu_fprintf(f, " %016lf", env->fpr[i]);

        if ((i & 3) == 3)

            cpu_fprintf(f, "\n");

    }

#ifdef TARGET_SPARC64

    cpu_fprintf(f, "pstate: 0x%08x ccr: 0x%02x asi: 0x%02x tl: %d fprs: %d\n",

                env->pstate, GET_CCR(env), env->asi, env->tl, env->fprs);

    cpu_fprintf(f, "cansave: %d canrestore: %d otherwin: %d wstate %d "

                "cleanwin %d cwp %d\n",

                env->cansave, env->canrestore, env->otherwin, env->wstate,

                env->cleanwin, env->nwindows - 1 - env->cwp);

#else

    cpu_fprintf(f, "psr: 0x%08x -> %c%c%c%c %c%c%c wim: 0x%08x\n",

                GET_PSR(env), GET_FLAG(PSR_ZERO, 'Z'), GET_FLAG(PSR_OVF, 'V'),

                GET_FLAG(PSR_NEG, 'N'), GET_FLAG(PSR_CARRY, 'C'),

                env->psrs?'S':'-', env->psrps?'P':'-',

                env->psret?'E':'-', env->wim);

#endif

    cpu_fprintf(f, "fsr: 0x%08x\n", GET_FSR32(env));

}


static uint16_t nvme_set_feature(NvmeCtrl *n, NvmeCmd *cmd, NvmeRequest *req)

{

    uint32_t dw10 = le32_to_cpu(cmd->cdw10);

    uint32_t dw11 = le32_to_cpu(cmd->cdw11);

    switch (dw10) {

    case NVME_VOLATILE_WRITE_CACHE:

        blk_set_enable_write_cache(n->conf.blk, dw11 & 1);

        break;

    case NVME_NUMBER_OF_QUEUES:

        req->cqe.result =

            cpu_to_le32((n->num_queues - 1) | ((n->num_queues - 1) << 16));

        break;

    default:

        return NVME_INVALID_FIELD | NVME_DNR;

    }

    return NVME_SUCCESS;

}


static int flic_decode_frame_8BPP(AVCodecContext *avctx,

                                  void *data, int *got_frame,

                                  const uint8_t *buf, int buf_size)

{

    FlicDecodeContext *s = avctx->priv_data;

    GetByteContext g2;

    int pixel_ptr;

    int palette_ptr;

    unsigned char palette_idx1;

    unsigned char palette_idx2;

    unsigned int frame_size;

    int num_chunks;

    unsigned int chunk_size;

    int chunk_type;

    int i, j, ret;

    int color_packets;

    int color_changes;

    int color_shift;

    unsigned char r, g, b;

    int lines;

    int compressed_lines;

    int starting_line;

    signed short line_packets;

    int y_ptr;

    int byte_run;

    int pixel_skip;

    int pixel_countdown;

    unsigned char *pixels;

    unsigned int pixel_limit;

    bytestream2_init(&g2, buf, buf_size);

    if ((ret = ff_reget_buffer(avctx, s->frame)) < 0)

        return ret;

    pixels = s->frame->data[0];

    pixel_limit = s->avctx->height * s->frame->linesize[0];

    if (buf_size < 16 || buf_size > INT_MAX - (3 * 256 + AV_INPUT_BUFFER_PADDING_SIZE))

    frame_size = bytestream2_get_le32(&g2);

    if (frame_size > buf_size)

        frame_size = buf_size;

    bytestream2_skip(&g2, 2); /* skip the magic number */

    num_chunks = bytestream2_get_le16(&g2);

    bytestream2_skip(&g2, 8);  /* skip padding */

    if (frame_size < 16)

    frame_size -= 16;

    /* iterate through the chunks */

    while ((frame_size >= 6) && (num_chunks > 0) &&

            bytestream2_get_bytes_left(&g2) >= 4) {

        int stream_ptr_after_chunk;

        chunk_size = bytestream2_get_le32(&g2);

        if (chunk_size > frame_size) {

            av_log(avctx, AV_LOG_WARNING,

                   "Invalid chunk_size = %u > frame_size = %u\n", chunk_size, frame_size);

            chunk_size = frame_size;

        }

        stream_ptr_after_chunk = bytestream2_tell(&g2) - 4 + chunk_size;

        chunk_type = bytestream2_get_le16(&g2);

        switch (chunk_type) {

        case FLI_256_COLOR:

        case FLI_COLOR:

            /* check special case: If this file is from the Magic Carpet

             * game and uses 6-bit colors even though it reports 256-color

             * chunks in a 0xAF12-type file (fli_type is set to 0xAF13 during

             * initialization) */

            if ((chunk_type == FLI_256_COLOR) && (s->fli_type != FLC_MAGIC_CARPET_SYNTHETIC_TYPE_CODE))

                color_shift = 0;

            else

                color_shift = 2;

            /* set up the palette */

            color_packets = bytestream2_get_le16(&g2);

            palette_ptr = 0;

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

                /* first byte is how many colors to skip */

                palette_ptr += bytestream2_get_byte(&g2);

                /* next byte indicates how many entries to change */

                color_changes = bytestream2_get_byte(&g2);

                /* if there are 0 color changes, there are actually 256 */

                if (color_changes == 0)

                    color_changes = 256;

                if (bytestream2_tell(&g2) + color_changes * 3 > stream_ptr_after_chunk)

                    break;

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

                    unsigned int entry;

                    /* wrap around, for good measure */

                    if ((unsigned)palette_ptr >= 256)

                        palette_ptr = 0;

                    r = bytestream2_get_byte(&g2) << color_shift;

                    g = bytestream2_get_byte(&g2) << color_shift;

                    b = bytestream2_get_byte(&g2) << color_shift;

                    entry = 0xFFU << 24 | r << 16 | g << 8 | b;

                    if (color_shift == 2)

                        entry |= entry >> 6 & 0x30303;

                    if (s->palette[palette_ptr] != entry)

                        s->new_palette = 1;

                    s->palette[palette_ptr++] = entry;

                }

            }

            break;

        case FLI_DELTA:

            y_ptr = 0;

            compressed_lines = bytestream2_get_le16(&g2);

            while (compressed_lines > 0) {

                if (bytestream2_tell(&g2) + 2 > stream_ptr_after_chunk)

                    break;

                if (y_ptr > pixel_limit)

                line_packets = bytestream2_get_le16(&g2);

                if ((line_packets & 0xC000) == 0xC000) {

                    // line skip opcode

                    line_packets = -line_packets;

                    if (line_packets > s->avctx->height)

                    y_ptr += line_packets * s->frame->linesize[0];

                } else if ((line_packets & 0xC000) == 0x4000) {

                    av_log(avctx, AV_LOG_ERROR, "Undefined opcode (%x) in DELTA_FLI\n", line_packets);

                } else if ((line_packets & 0xC000) == 0x8000) {

                    // "last byte" opcode

                    pixel_ptr= y_ptr + s->frame->linesize[0] - 1;

                    CHECK_PIXEL_PTR(0);

                    pixels[pixel_ptr] = line_packets & 0xff;

                } else {

                    compressed_lines--;

                    pixel_ptr = y_ptr;

                    CHECK_PIXEL_PTR(0);

                    pixel_countdown = s->avctx->width;

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

                        if (bytestream2_tell(&g2) + 2 > stream_ptr_after_chunk)

                            break;

                        /* account for the skip bytes */

                        pixel_skip = bytestream2_get_byte(&g2);

                        pixel_ptr += pixel_skip;

                        pixel_countdown -= pixel_skip;

                        byte_run = sign_extend(bytestream2_get_byte(&g2), 8);

                        if (byte_run < 0) {

                            byte_run = -byte_run;

                            palette_idx1 = bytestream2_get_byte(&g2);

                            palette_idx2 = bytestream2_get_byte(&g2);

                            CHECK_PIXEL_PTR(byte_run * 2);

                            for (j = 0; j < byte_run; j++, pixel_countdown -= 2) {

                                pixels[pixel_ptr++] = palette_idx1;

                                pixels[pixel_ptr++] = palette_idx2;

                            }

                        } else {

                            CHECK_PIXEL_PTR(byte_run * 2);

                            if (bytestream2_tell(&g2) + byte_run * 2 > stream_ptr_after_chunk)

                                break;

                            for (j = 0; j < byte_run * 2; j++, pixel_countdown--) {

                                pixels[pixel_ptr++] = bytestream2_get_byte(&g2);

                            }

                        }

                    }

                    y_ptr += s->frame->linesize[0];

                }

            }

            break;

        case FLI_LC:

            /* line compressed */

            starting_line = bytestream2_get_le16(&g2);

            y_ptr = 0;

            y_ptr += starting_line * s->frame->linesize[0];

            compressed_lines = bytestream2_get_le16(&g2);

            while (compressed_lines > 0) {

                pixel_ptr = y_ptr;

                CHECK_PIXEL_PTR(0);

                pixel_countdown = s->avctx->width;

                if (bytestream2_tell(&g2) + 1 > stream_ptr_after_chunk)

                    break;

                line_packets = bytestream2_get_byte(&g2);

                if (line_packets > 0) {

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

                        /* account for the skip bytes */

                        if (bytestream2_tell(&g2) + 1 > stream_ptr_after_chunk)

                            break;

                        pixel_skip = bytestream2_get_byte(&g2);

                        pixel_ptr += pixel_skip;

                        pixel_countdown -= pixel_skip;

                        byte_run = sign_extend(bytestream2_get_byte(&g2),8);

                        if (byte_run > 0) {

                            CHECK_PIXEL_PTR(byte_run);

                            if (bytestream2_tell(&g2) + byte_run > stream_ptr_after_chunk)

                                break;

                            for (j = 0; j < byte_run; j++, pixel_countdown--) {

                                pixels[pixel_ptr++] = bytestream2_get_byte(&g2);

                            }

                        } else if (byte_run < 0) {

                            byte_run = -byte_run;

                            palette_idx1 = bytestream2_get_byte(&g2);

                            CHECK_PIXEL_PTR(byte_run);

                            for (j = 0; j < byte_run; j++, pixel_countdown--) {

                                pixels[pixel_ptr++] = palette_idx1;

                            }

                        }

                    }

                }

                y_ptr += s->frame->linesize[0];

                compressed_lines--;

            }

            break;

        case FLI_BLACK:

            /* set the whole frame to color 0 (which is usually black) */

            memset(pixels, 0,

                s->frame->linesize[0] * s->avctx->height);

            break;

        case FLI_BRUN:

            /* Byte run compression: This chunk type only occurs in the first

             * FLI frame and it will update the entire frame. */

            y_ptr = 0;

            for (lines = 0; lines < s->avctx->height; lines++) {

                pixel_ptr = y_ptr;

                /* disregard the line packets; instead, iterate through all

                 * pixels on a row */

                 bytestream2_skip(&g2, 1);

                pixel_countdown = s->avctx->width;

                while (pixel_countdown > 0) {

                    if (bytestream2_tell(&g2) + 1 > stream_ptr_after_chunk)

                        break;

                    byte_run = sign_extend(bytestream2_get_byte(&g2), 8);

                    if (!byte_run) {

                        av_log(avctx, AV_LOG_ERROR, "Invalid byte run value.\n");

                    }

                    if (byte_run > 0) {

                        palette_idx1 = bytestream2_get_byte(&g2);

                        CHECK_PIXEL_PTR(byte_run);

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

                            pixels[pixel_ptr++] = palette_idx1;

                            pixel_countdown--;

                            if (pixel_countdown < 0)

                                av_log(avctx, AV_LOG_ERROR, "pixel_countdown < 0 (%d) at line %d\n",

                                       pixel_countdown, lines);

                        }

                    } else {  /* copy bytes if byte_run < 0 */

                        byte_run = -byte_run;

                        CHECK_PIXEL_PTR(byte_run);

                        if (bytestream2_tell(&g2) + byte_run > stream_ptr_after_chunk)

                            break;

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

                            pixels[pixel_ptr++] = bytestream2_get_byte(&g2);

                            pixel_countdown--;

                            if (pixel_countdown < 0)

                                av_log(avctx, AV_LOG_ERROR, "pixel_countdown < 0 (%d) at line %d\n",

                                       pixel_countdown, lines);

                        }

                    }

                }

                y_ptr += s->frame->linesize[0];

            }

            break;

        case FLI_COPY:

            /* copy the chunk (uncompressed frame) */

            if (chunk_size - 6 != FFALIGN(s->avctx->width, 4) * s->avctx->height) {

                av_log(avctx, AV_LOG_ERROR, "In chunk FLI_COPY : source data (%d bytes) " \

                       "has incorrect size, skipping chunk\n", chunk_size - 6);

                bytestream2_skip(&g2, chunk_size - 6);

            } else {

                for (y_ptr = 0; y_ptr < s->frame->linesize[0] * s->avctx->height;

                     y_ptr += s->frame->linesize[0]) {

                    bytestream2_get_buffer(&g2, &pixels[y_ptr],

                                           s->avctx->width);

                    if (s->avctx->width & 3)

                        bytestream2_skip(&g2, 4 - (s->avctx->width & 3));

                }

            }

            break;

        case FLI_MINI:

            /* some sort of a thumbnail? disregard this chunk... */

            break;

        default:

            av_log(avctx, AV_LOG_ERROR, "Unrecognized chunk type: %d\n", chunk_type);

            break;

        }

        if (stream_ptr_after_chunk - bytestream2_tell(&g2) >= 0) {

            bytestream2_skip(&g2, stream_ptr_after_chunk - bytestream2_tell(&g2));

        } else {

            av_log(avctx, AV_LOG_ERROR, "Chunk overread\n");

            break;

        }

        frame_size -= chunk_size;

        num_chunks--;

    }

    /* by the end of the chunk, the stream ptr should equal the frame

     * size (minus 1 or 2, possibly); if it doesn't, issue a warning */

    if (bytestream2_get_bytes_left(&g2) > 2)

        av_log(avctx, AV_LOG_ERROR, "Processed FLI chunk where chunk size = %d " \

               "and final chunk ptr = %d\n", buf_size,

               buf_size - bytestream2_get_bytes_left(&g2));

    /* make the palette available on the way out */

    memcpy(s->frame->data[1], s->palette, AVPALETTE_SIZE);

    if (s->new_palette) {

        s->frame->palette_has_changed = 1;

        s->new_palette = 0;

    }

    if ((ret = av_frame_ref(data, s->frame)) < 0)

        return ret;

    *got_frame = 1;

    return buf_size;

}


static int pci_read_devaddr(Monitor *mon, const char *addr,

                            int *busp, unsigned *slotp)

{

    int dom;

    /* strip legacy tag */

    if (!strncmp(addr, "pci_addr=", 9)) {

        addr += 9;

    }

    if (pci_parse_devaddr(addr, &dom, busp, slotp, NULL)) {

        monitor_printf(mon, "Invalid pci address\n");

        return -1;

    }

    if (dom != 0) {

        monitor_printf(mon, "Multiple PCI domains not supported, use device_add\n");

        return -1;

    }

    return 0;

}


static void write_streaminfo(FlacEncodeContext *s, uint8_t *header)

{

    PutBitContext pb;

    memset(header, 0, FLAC_STREAMINFO_SIZE);

    init_put_bits(&pb, header, FLAC_STREAMINFO_SIZE);

    /* streaminfo metadata block */

    put_bits(&pb, 16, s->avctx->frame_size);

    put_bits(&pb, 16, s->avctx->frame_size);

    put_bits(&pb, 24, 0);

    put_bits(&pb, 24, s->max_framesize);

    put_bits(&pb, 20, s->samplerate);

    put_bits(&pb, 3, s->channels-1);

    put_bits(&pb, 5, 15);       /* bits per sample - 1 */

    /* write 36-bit sample count in 2 put_bits() calls */

    put_bits(&pb, 24, (s->sample_count & 0xFFFFFF000LL) >> 12);

    put_bits(&pb, 12,  s->sample_count & 0x000000FFFLL);

    flush_put_bits(&pb);

    /* MD5 signature = 0 */

}


static void slavio_check_interrupts(SLAVIO_INTCTLState *s, int set_irqs)

{

    uint32_t pending = s->intregm_pending, pil_pending;

    unsigned int i, j;

    pending &= ~s->intregm_disabled;

    trace_slavio_check_interrupts(pending, s->intregm_disabled);

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

        pil_pending = 0;

        /* If we are the current interrupt target, get hard interrupts */

        if (pending && !(s->intregm_disabled & MASTER_DISABLE) &&

            (i == s->target_cpu)) {

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

                if ((pending & (1 << j)) && intbit_to_level[j]) {

                    pil_pending |= 1 << intbit_to_level[j];

                }

            }

        }

        /* Calculate current pending hard interrupts for display */

        s->slaves[i].intreg_pending &= CPU_SOFTIRQ_MASK | CPU_IRQ_INT15_IN |

            CPU_IRQ_TIMER_IN;

        if (i == s->target_cpu) {

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

                if ((s->intregm_pending & (1 << j)) && intbit_to_level[j]) {

                    s->slaves[i].intreg_pending |= 1 << intbit_to_level[j];

                }

            }

        }

        /* Level 15 and CPU timer interrupts are only masked when

           the MASTER_DISABLE bit is set */

        if (!(s->intregm_disabled & MASTER_DISABLE)) {

            pil_pending |= s->slaves[i].intreg_pending &

                (CPU_IRQ_INT15_IN | CPU_IRQ_TIMER_IN);

        }

        /* Add soft interrupts */

        pil_pending |= (s->slaves[i].intreg_pending & CPU_SOFTIRQ_MASK) >> 16;

        if (set_irqs) {

            for (j = MAX_PILS; j > 0; j--) {

                if (pil_pending & (1 << j)) {

                    if (!(s->slaves[i].irl_out & (1 << j))) {

                        qemu_irq_raise(s->cpu_irqs[i][j]);

                    }

                } else {

                    if (s->slaves[i].irl_out & (1 << j)) {

                        qemu_irq_lower(s->cpu_irqs[i][j]);

                    }

                }

            }

        }

        s->slaves[i].irl_out = pil_pending;

    }

}


static struct ioreq *ioreq_start(struct XenBlkDev *blkdev)

{

    struct ioreq *ioreq = NULL;

    if (QLIST_EMPTY(&blkdev->freelist)) {

        if (blkdev->requests_total >= max_requests) {

            goto out;

        }

        /* allocate new struct */

        ioreq = g_malloc0(sizeof(*ioreq));

        ioreq->blkdev = blkdev;

        blkdev->requests_total++;

        qemu_iovec_init(&ioreq->v, BLKIF_MAX_SEGMENTS_PER_REQUEST);

    } else {

        /* get one from freelist */

        ioreq = QLIST_FIRST(&blkdev->freelist);

        QLIST_REMOVE(ioreq, list);

        qemu_iovec_reset(&ioreq->v);

    }

    QLIST_INSERT_HEAD(&blkdev->inflight, ioreq, list);

    blkdev->requests_inflight++;

out:

    return ioreq;

}


static void dequantize_slice_buffered(SnowContext *s, slice_buffer * sb, SubBand *b, IDWTELEM *src, int stride, int start_y, int end_y){

    const int w= b->width;

    const int qlog= av_clip(s->qlog + b->qlog, 0, QROOT*16);

    const int qmul= ff_qexp[qlog&(QROOT-1)]<<(qlog>>QSHIFT);

    const int qadd= (s->qbias*qmul)>>QBIAS_SHIFT;

    int x,y;

    if(s->qlog == LOSSLESS_QLOG) return;

    for(y=start_y; y<end_y; y++){

//        DWTELEM * line = slice_buffer_get_line_from_address(sb, src + (y * stride));

        IDWTELEM * line = slice_buffer_get_line(sb, (y * b->stride_line) + b->buf_y_offset) + b->buf_x_offset;

        for(x=0; x<w; x++){

            int i= line[x];

            if(i<0){

                line[x]= -((-i*qmul + qadd)>>(QEXPSHIFT)); //FIXME try different bias

            }else if(i>0){

                line[x]=  (( i*qmul + qadd)>>(QEXPSHIFT));

            }

        }

    }

}


static int kvm_irqchip_create(MachineState *machine, KVMState *s)

{

    int ret;

    if (!machine_kernel_irqchip_allowed(machine) ||

        (!kvm_check_extension(s, KVM_CAP_IRQCHIP) &&

         (kvm_vm_enable_cap(s, KVM_CAP_S390_IRQCHIP, 0) < 0))) {

        return 0;

    }

    /* First probe and see if there's a arch-specific hook to create the

     * in-kernel irqchip for us */

    ret = kvm_arch_irqchip_create(s);

    if (ret < 0) {

        return ret;

    } else if (ret == 0) {

        ret = kvm_vm_ioctl(s, KVM_CREATE_IRQCHIP);

        if (ret < 0) {

            fprintf(stderr, "Create kernel irqchip failed\n");

            return ret;

        }

    }

    kvm_kernel_irqchip = true;

    /* If we have an in-kernel IRQ chip then we must have asynchronous

     * interrupt delivery (though the reverse is not necessarily true)

     */

    kvm_async_interrupts_allowed = true;

    kvm_halt_in_kernel_allowed = true;

    kvm_init_irq_routing(s);

    return 0;

}


static void qemu_clock_init(QEMUClockType type)
{
    QEMUClock *clock = qemu_clock_ptr(type);
    clock->type = type;
    clock->enabled = true;
    clock->last = INT64_MIN;
    QLIST_INIT(&clock->timerlists);
    notifier_list_init(&clock->reset_notifiers);
    main_loop_tlg.tl[type] = timerlist_new(type, NULL, NULL);
}


static void gen_mfdcr(DisasContext *ctx)

{

#if defined(CONFIG_USER_ONLY)

    gen_inval_exception(ctx, POWERPC_EXCP_PRIV_REG);

#else

    TCGv dcrn;

    if (unlikely(ctx->pr)) {

        gen_inval_exception(ctx, POWERPC_EXCP_PRIV_REG);

        return;

    }

    /* NIP cannot be restored if the memory exception comes from an helper */

    gen_update_nip(ctx, ctx->nip - 4);

    dcrn = tcg_const_tl(SPR(ctx->opcode));

    gen_helper_load_dcr(cpu_gpr[rD(ctx->opcode)], cpu_env, dcrn);

    tcg_temp_free(dcrn);

#endif

}


static int wav_write_header(AVFormatContext *s)

{

    WAVContext *wav = s->priv_data;

    AVIOContext *pb = s->pb;

    int64_t fmt, fact;

    ffio_wfourcc(pb, "RIFF");

    avio_wl32(pb, 0); /* file length */

    ffio_wfourcc(pb, "WAVE");

    /* format header */

    fmt = ff_start_tag(pb, "fmt ");

    if (ff_put_wav_header(pb, s->streams[0]->codec) < 0) {

        av_log(s, AV_LOG_ERROR, "%s codec not supported in WAVE format\n",

               s->streams[0]->codec->codec ? s->streams[0]->codec->codec->name : "NONE");

        av_free(wav);

        return -1;

    }

    ff_end_tag(pb, fmt);

    if (s->streams[0]->codec->codec_tag != 0x01 /* hence for all other than PCM */

        && s->pb->seekable) {

        fact = ff_start_tag(pb, "fact");

        avio_wl32(pb, 0);

        ff_end_tag(pb, fact);

    }

    av_set_pts_info(s->streams[0], 64, 1, s->streams[0]->codec->sample_rate);

    wav->maxpts = wav->last_duration = 0;

    wav->minpts = INT64_MAX;

    /* data header */

    wav->data = ff_start_tag(pb, "data");

    avio_flush(pb);

    return 0;

}


void ff_llviddsp_init_x86(LLVidDSPContext *c)

{

    int cpu_flags = av_get_cpu_flags();

#if HAVE_INLINE_ASM && HAVE_7REGS && ARCH_X86_32

    if (cpu_flags & AV_CPU_FLAG_CMOV)

        c->add_median_pred = add_median_pred_cmov;

#endif

    if (ARCH_X86_32 && EXTERNAL_MMX(cpu_flags)) {

        c->add_bytes = ff_add_bytes_mmx;

    }

    if (ARCH_X86_32 && EXTERNAL_MMXEXT(cpu_flags)) {

        /* slower than cmov version on AMD */

        if (!(cpu_flags & AV_CPU_FLAG_3DNOW))

            c->add_median_pred = ff_add_median_pred_mmxext;

    }

    if (EXTERNAL_SSE2(cpu_flags)) {

        c->add_bytes       = ff_add_bytes_sse2;

        c->add_median_pred = ff_add_median_pred_sse2;

    }

    if (EXTERNAL_SSSE3(cpu_flags)) {

        c->add_left_pred = ff_add_left_pred_ssse3;

        c->add_left_pred_int16 = ff_add_left_pred_int16_ssse3;

        c->add_gradient_pred   = ff_add_gradient_pred_ssse3;

    }

    if (EXTERNAL_SSSE3_FAST(cpu_flags)) {

        c->add_left_pred = ff_add_left_pred_unaligned_ssse3;

    }

    if (EXTERNAL_SSE4(cpu_flags)) {

        c->add_left_pred_int16 = ff_add_left_pred_int16_sse4;

    }

    if (EXTERNAL_AVX2_FAST(cpu_flags)) {

        c->add_bytes       = ff_add_bytes_avx2;

        c->add_left_pred   = ff_add_left_pred_unaligned_avx2;

        c->add_gradient_pred = ff_add_gradient_pred_avx2;

    }

}


static av_cold int libgsm_init(AVCodecContext *avctx) {

    if (avctx->channels > 1) {

        av_log(avctx, AV_LOG_ERROR, "Mono required for GSM, got %d channels\n",

               avctx->channels);

        return -1;

    }

    if(avctx->codec->decode){

        if(!avctx->channels)

            avctx->channels= 1;

        if(!avctx->sample_rate)

            avctx->sample_rate= 8000;

        avctx->sample_fmt = AV_SAMPLE_FMT_S16;

    }else{

        if (avctx->sample_rate != 8000) {

            av_log(avctx, AV_LOG_ERROR, "Sample rate 8000Hz required for GSM, got %dHz\n",

                avctx->sample_rate);

            if(avctx->strict_std_compliance > FF_COMPLIANCE_UNOFFICIAL)

                return -1;

        }

        if (avctx->bit_rate != 13000 /* Official */ &&

            avctx->bit_rate != 13200 /* Very common */ &&

            avctx->bit_rate != 0 /* Unknown; a.o. mov does not set bitrate when decoding */ ) {

            av_log(avctx, AV_LOG_ERROR, "Bitrate 13000bps required for GSM, got %dbps\n",

                avctx->bit_rate);

            if(avctx->strict_std_compliance > FF_COMPLIANCE_UNOFFICIAL)

                return -1;

        }

    }

    avctx->priv_data = gsm_create();

    switch(avctx->codec_id) {

    case CODEC_ID_GSM:

        avctx->frame_size = GSM_FRAME_SIZE;

        avctx->block_align = GSM_BLOCK_SIZE;

        break;

    case CODEC_ID_GSM_MS: {

        int one = 1;

        gsm_option(avctx->priv_data, GSM_OPT_WAV49, &one);

        avctx->frame_size = 2*GSM_FRAME_SIZE;

        avctx->block_align = GSM_MS_BLOCK_SIZE;

        }

    }

    avctx->coded_frame= avcodec_alloc_frame();

    avctx->coded_frame->key_frame= 1;

    return 0;

}


static int h261_decode_frame(AVCodecContext *avctx,

                             void *data, int *data_size,

                             uint8_t *buf, int buf_size)

{

    H261Context *h= avctx->priv_data;

    MpegEncContext *s = &h->s;

    int ret;

    AVFrame *pict = data;

#ifdef DEBUG

    printf("*****frame %d size=%d\n", avctx->frame_number, buf_size);

    printf("bytes=%x %x %x %x\n", buf[0], buf[1], buf[2], buf[3]);

#endif

    s->flags= avctx->flags;

    s->flags2= avctx->flags2;

    /* no supplementary picture */

    if (buf_size == 0) {

        return 0;

    }

    h->gob_start_code_skipped=0;

retry:

    init_get_bits(&s->gb, buf, buf_size*8);

    if(!s->context_initialized){

        if (MPV_common_init(s) < 0) //we need the idct permutaton for reading a custom matrix

            return -1;

    }

    //we need to set current_picture_ptr before reading the header, otherwise we cant store anyting im there

    if(s->current_picture_ptr==NULL || s->current_picture_ptr->data[0]){

        int i= ff_find_unused_picture(s, 0);

        s->current_picture_ptr= &s->picture[i];

    }

    ret = h261_decode_picture_header(h);

    /* skip if the header was thrashed */

    if (ret < 0){

        av_log(s->avctx, AV_LOG_ERROR, "header damaged\n");

        return -1;

    }

    if (s->width != avctx->coded_width || s->height != avctx->coded_height){

        ParseContext pc= s->parse_context; //FIXME move these demuxng hack to avformat

        s->parse_context.buffer=0;

        MPV_common_end(s);

        s->parse_context= pc;

    }

    if (!s->context_initialized) {

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

        goto retry;

    }

    // for hurry_up==5

    s->current_picture.pict_type= s->pict_type;

    s->current_picture.key_frame= s->pict_type == I_TYPE;

    /* skip everything if we are in a hurry>=5 */

    if(avctx->hurry_up>=5) return get_consumed_bytes(s, buf_size);

    if(MPV_frame_start(s, avctx) < 0)

        return -1;

    ff_er_frame_start(s);

    /* decode each macroblock */

    s->mb_x=0;

    s->mb_y=0;

    while(h->gob_number < (s->mb_height==18 ? 12 : 5)){

        if(ff_h261_resync(h)<0)

            break;

        h261_decode_gob(h);

    }

    MPV_frame_end(s);

assert(s->current_picture.pict_type == s->current_picture_ptr->pict_type);

assert(s->current_picture.pict_type == s->pict_type);

    *pict= *(AVFrame*)s->current_picture_ptr;

    ff_print_debug_info(s, pict);

    /* Return the Picture timestamp as the frame number */

    /* we substract 1 because it is added on utils.c    */

    avctx->frame_number = s->picture_number - 1;

    *data_size = sizeof(AVFrame);

    return get_consumed_bytes(s, buf_size);

}


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

{

    AVStream *st;

    MOVStreamContext *sc;

    int64_t ret;

    uint8_t uuid[16];

    static const uint8_t uuid_isml_manifest[] = {

        0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,

        0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66

    };

    static const uint8_t uuid_xmp[] = {

        0xbe, 0x7a, 0xcf, 0xcb, 0x97, 0xa9, 0x42, 0xe8,

        0x9c, 0x71, 0x99, 0x94, 0x91, 0xe3, 0xaf, 0xac

    };

    static const uint8_t uuid_spherical[] = {

        0xff, 0xcc, 0x82, 0x63, 0xf8, 0x55, 0x4a, 0x93,

        0x88, 0x14, 0x58, 0x7a, 0x02, 0x52, 0x1f, 0xdd,

    };

    if (atom.size < sizeof(uuid) || atom.size == INT64_MAX)

        return AVERROR_INVALIDDATA;

    if (c->fc->nb_streams < 1)

        return 0;

    st = c->fc->streams[c->fc->nb_streams - 1];

    sc = st->priv_data;

    ret = avio_read(pb, uuid, sizeof(uuid));

    if (ret < 0) {

        return ret;

    } else if (ret != sizeof(uuid)) {

        return AVERROR_INVALIDDATA;

    }

    if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) {

        uint8_t *buffer, *ptr;

        char *endptr;

        size_t len = atom.size - sizeof(uuid);

        if (len < 4) {

            return AVERROR_INVALIDDATA;

        }

        ret = avio_skip(pb, 4); // zeroes

        len -= 4;

        buffer = av_mallocz(len + 1);

        if (!buffer) {

            return AVERROR(ENOMEM);

        }

        ret = avio_read(pb, buffer, len);

        if (ret < 0) {

            av_free(buffer);

            return ret;

        } else if (ret != len) {

            av_free(buffer);

            return AVERROR_INVALIDDATA;

        }

        ptr = buffer;

        while ((ptr = av_stristr(ptr, "systemBitrate=\""))) {

            ptr += sizeof("systemBitrate=\"") - 1;

            c->bitrates_count++;

            c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates));

            if (!c->bitrates) {

                c->bitrates_count = 0;

                av_free(buffer);

                return AVERROR(ENOMEM);

            }

            errno = 0;

            ret = strtol(ptr, &endptr, 10);

            if (ret < 0 || errno || *endptr != '"') {

                c->bitrates[c->bitrates_count - 1] = 0;

            } else {

                c->bitrates[c->bitrates_count - 1] = ret;

            }

        }

        av_free(buffer);

    } else if (!memcmp(uuid, uuid_xmp, sizeof(uuid))) {

        uint8_t *buffer;

        size_t len = atom.size - sizeof(uuid);

        if (c->export_xmp) {

            buffer = av_mallocz(len + 1);

            if (!buffer) {

                return AVERROR(ENOMEM);

            }

            ret = avio_read(pb, buffer, len);

            if (ret < 0) {

                av_free(buffer);

                return ret;

            } else if (ret != len) {

                av_free(buffer);

                return AVERROR_INVALIDDATA;

            }

            buffer[len] = '\0';

            av_dict_set(&c->fc->metadata, "xmp", buffer, 0);

            av_free(buffer);

        } else {

            // skip all uuid atom, which makes it fast for long uuid-xmp file

            ret = avio_skip(pb, len);

            if (ret < 0)

                return ret;

        }

    } else if (!memcmp(uuid, uuid_spherical, sizeof(uuid))) {

        size_t len = atom.size - sizeof(uuid);

        ret = mov_parse_uuid_spherical(sc, pb, len);

        if (ret < 0)

            return ret;

        if (!sc->spherical)

            av_log(c->fc, AV_LOG_WARNING, "Invalid spherical metadata found\n");    }

    return 0;

}


uint64_t HELPER(neon_abdl_u16)(uint32_t a, uint32_t b)

{

    uint64_t tmp;

    uint64_t result;

    DO_ABD(result, a, b, uint8_t);

    DO_ABD(tmp, a >> 8, b >> 8, uint8_t);

    result |= tmp << 16;

    DO_ABD(tmp, a >> 16, b >> 16, uint8_t);

    result |= tmp << 32;

    DO_ABD(tmp, a >> 24, b >> 24, uint8_t);

    result |= tmp << 48;

    return result;

}


static int ipvideo_decode_block_opcode_0xA(IpvideoContext *s, AVFrame *frame)
{
    int x, y;
    unsigned char P[8];
    int flags = 0;
    bytestream2_get_buffer(&s->stream_ptr, P, 4);
    /* 4-color encoding for each 4x4 quadrant, or 4-color encoding on
     * either top and bottom or left and right halves */
    if (P[0] <= P[1]) {
        /* 4-color encoding for each quadrant; need 32 bytes */
        for (y = 0; y < 16; y++) {
            // new values for each 4x4 block
            if (!(y & 3)) {
                if (y) bytestream2_get_buffer(&s->stream_ptr, P, 4);
                flags = bytestream2_get_le32(&s->stream_ptr);
            for (x = 0; x < 4; x++, flags >>= 2)
                *s->pixel_ptr++ = P[flags & 0x03];
            s->pixel_ptr += s->stride - 4;
            // switch to right half
            if (y == 7) s->pixel_ptr -= 8 * s->stride - 4;
    } else {
        // vertical split?
        int vert;
        uint64_t flags = bytestream2_get_le64(&s->stream_ptr);
        bytestream2_get_buffer(&s->stream_ptr, P + 4, 4);
        vert = P[4] <= P[5];
        /* 4-color encoding for either left and right or top and bottom
         * halves */
        for (y = 0; y < 16; y++) {
            for (x = 0; x < 4; x++, flags >>= 2)
                *s->pixel_ptr++ = P[flags & 0x03];
            if (vert) {
                s->pixel_ptr += s->stride - 4;
                // switch to right half
                if (y == 7) s->pixel_ptr -= 8 * s->stride - 4;
            } else if (y & 1) s->pixel_ptr += s->line_inc;
            // load values for second half
            if (y == 7) {
                memcpy(P, P + 4, 4);
                flags = bytestream2_get_le64(&s->stream_ptr);
    /* report success */
    return 0;


static av_cold int truemotion1_decode_init(AVCodecContext *avctx)

{

    TrueMotion1Context *s = avctx->priv_data;

    s->avctx = avctx;

    // FIXME: it may change ?

//    if (avctx->bits_per_sample == 24)

//        avctx->pix_fmt = AV_PIX_FMT_RGB24;

//    else

//        avctx->pix_fmt = AV_PIX_FMT_RGB555;

    s->frame = av_frame_alloc();

    if (!s->frame)

        return AVERROR(ENOMEM);

    /* there is a vertical predictor for each pixel in a line; each vertical

     * predictor is 0 to start with */

    av_fast_malloc(&s->vert_pred, &s->vert_pred_size, s->avctx->width * sizeof(unsigned int));

    if (!s->vert_pred)

        return AVERROR(ENOMEM);

    return 0;

}


static uint32_t suov32(CPUTriCoreState *env, int64_t arg)

{

    uint32_t ret;

    int64_t max_pos = UINT32_MAX;

    if (arg > max_pos) {

        env->PSW_USB_V = (1 << 31);

        env->PSW_USB_SV = (1 << 31);

        ret = (target_ulong)max_pos;

    } else {

        if (arg < 0) {

            env->PSW_USB_V = (1 << 31);

            env->PSW_USB_SV = (1 << 31);

            ret = 0;

        } else {

            env->PSW_USB_V = 0;

            ret = (target_ulong)arg;

        }

     }

    env->PSW_USB_AV = arg ^ arg * 2u;

    env->PSW_USB_SAV |= env->PSW_USB_AV;

    return ret;

}