static always_inline int get_segment (CPUState *env, mmu_ctx_t *ctx,

                                      target_ulong eaddr, int rw, int type)

{

    target_phys_addr_t sdr, hash, mask, sdr_mask, htab_mask;

    target_ulong sr, vsid, vsid_mask, pgidx, page_mask;

#if defined(TARGET_PPC64)

    int attr;

#endif

    int ds, vsid_sh, sdr_sh, pr;

    int ret, ret2;

    pr = msr_pr;

#if defined(TARGET_PPC64)

    if (env->mmu_model == POWERPC_MMU_64B) {

#if defined (DEBUG_MMU)

        if (loglevel != 0) {

            fprintf(logfile, "Check SLBs\n");

        }

#endif

        ret = slb_lookup(env, eaddr, &vsid, &page_mask, &attr);

        if (ret < 0)

            return ret;

        ctx->key = ((attr & 0x40) && (pr != 0)) ||

            ((attr & 0x80) && (pr == 0)) ? 1 : 0;

        ds = 0;

        ctx->nx = attr & 0x20 ? 1 : 0;

        vsid_mask = 0x00003FFFFFFFFF80ULL;

        vsid_sh = 7;

        sdr_sh = 18;

        sdr_mask = 0x3FF80;

    } else

#endif /* defined(TARGET_PPC64) */

    {

        sr = env->sr[eaddr >> 28];

        page_mask = 0x0FFFFFFF;

        ctx->key = (((sr & 0x20000000) && (pr != 0)) ||

                    ((sr & 0x40000000) && (pr == 0))) ? 1 : 0;

        ds = sr & 0x80000000 ? 1 : 0;

        ctx->nx = sr & 0x10000000 ? 1 : 0;

        vsid = sr & 0x00FFFFFF;

        vsid_mask = 0x01FFFFC0;

        vsid_sh = 6;

        sdr_sh = 16;

        sdr_mask = 0xFFC0;

#if defined (DEBUG_MMU)

        if (loglevel != 0) {

            fprintf(logfile, "Check segment v=0x" ADDRX " %d 0x" ADDRX

                    " nip=0x" ADDRX " lr=0x" ADDRX

                    " ir=%d dr=%d pr=%d %d t=%d\n",

                    eaddr, (int)(eaddr >> 28), sr, env->nip,

                    env->lr, (int)msr_ir, (int)msr_dr, pr != 0 ? 1 : 0,

                    rw, type);

        }

#endif

    }

#if defined (DEBUG_MMU)

    if (loglevel != 0) {

        fprintf(logfile, "pte segment: key=%d ds %d nx %d vsid " ADDRX "\n",

                ctx->key, ds, ctx->nx, vsid);

    }

#endif

    ret = -1;

    if (!ds) {

        /* Check if instruction fetch is allowed, if needed */

        if (type != ACCESS_CODE || ctx->nx == 0) {

            /* Page address translation */

            /* Primary table address */

            sdr = env->sdr1;

            pgidx = (eaddr & page_mask) >> TARGET_PAGE_BITS;

#if defined(TARGET_PPC64)

            if (env->mmu_model == POWERPC_MMU_64B) {

                htab_mask = 0x0FFFFFFF >> (28 - (sdr & 0x1F));

                /* XXX: this is false for 1 TB segments */

                hash = ((vsid ^ pgidx) << vsid_sh) & vsid_mask;

            } else

#endif

            {

                htab_mask = sdr & 0x000001FF;

                hash = ((vsid ^ pgidx) << vsid_sh) & vsid_mask;

            }

            mask = (htab_mask << sdr_sh) | sdr_mask;

#if defined (DEBUG_MMU)

            if (loglevel != 0) {

                fprintf(logfile, "sdr " PADDRX " sh %d hash " PADDRX " mask "

                        PADDRX " " ADDRX "\n", sdr, sdr_sh, hash, mask,

                        page_mask);

            }

#endif

            ctx->pg_addr[0] = get_pgaddr(sdr, sdr_sh, hash, mask);

            /* Secondary table address */

            hash = (~hash) & vsid_mask;

#if defined (DEBUG_MMU)

            if (loglevel != 0) {

                fprintf(logfile, "sdr " PADDRX " sh %d hash " PADDRX " mask "

                        PADDRX "\n", sdr, sdr_sh, hash, mask);

            }

#endif

            ctx->pg_addr[1] = get_pgaddr(sdr, sdr_sh, hash, mask);

#if defined(TARGET_PPC64)

            if (env->mmu_model == POWERPC_MMU_64B) {

                /* Only 5 bits of the page index are used in the AVPN */

                ctx->ptem = (vsid << 12) | ((pgidx >> 4) & 0x0F80);

            } else

#endif

            {

                ctx->ptem = (vsid << 7) | (pgidx >> 10);

            }

            /* Initialize real address with an invalid value */

            ctx->raddr = (target_ulong)-1;

            if (unlikely(env->mmu_model == POWERPC_MMU_SOFT_6xx ||

                         env->mmu_model == POWERPC_MMU_SOFT_74xx)) {

                /* Software TLB search */

                ret = ppc6xx_tlb_check(env, ctx, eaddr, rw, type);

            } else {

#if defined (DEBUG_MMU)

                if (loglevel != 0) {

                    fprintf(logfile, "0 sdr1=0x" PADDRX " vsid=0x%06x "

                            "api=0x%04x hash=0x%07x pg_addr=0x" PADDRX "\n",

                            sdr, (uint32_t)vsid, (uint32_t)pgidx,

                            (uint32_t)hash, ctx->pg_addr[0]);

                }

#endif

                /* Primary table lookup */

                ret = find_pte(env, ctx, 0, rw, type);

                if (ret < 0) {

                    /* Secondary table lookup */

#if defined (DEBUG_MMU)

                    if (eaddr != 0xEFFFFFFF && loglevel != 0) {

                        fprintf(logfile,

                                "1 sdr1=0x" PADDRX " vsid=0x%06x api=0x%04x "

                                "hash=0x%05x pg_addr=0x" PADDRX "\n",

                                sdr, (uint32_t)vsid, (uint32_t)pgidx,

                                (uint32_t)hash, ctx->pg_addr[1]);

                    }

#endif

                    ret2 = find_pte(env, ctx, 1, rw, type);

                    if (ret2 != -1)

                        ret = ret2;

                }

            }

#if defined (DUMP_PAGE_TABLES)

            if (loglevel != 0) {

                target_phys_addr_t curaddr;

                uint32_t a0, a1, a2, a3;

                fprintf(logfile,

                        "Page table: " PADDRX " len " PADDRX "\n",

                        sdr, mask + 0x80);

                for (curaddr = sdr; curaddr < (sdr + mask + 0x80);

                     curaddr += 16) {

                    a0 = ldl_phys(curaddr);

                    a1 = ldl_phys(curaddr + 4);

                    a2 = ldl_phys(curaddr + 8);

                    a3 = ldl_phys(curaddr + 12);

                    if (a0 != 0 || a1 != 0 || a2 != 0 || a3 != 0) {

                        fprintf(logfile,

                                PADDRX ": %08x %08x %08x %08x\n",

                                curaddr, a0, a1, a2, a3);

                    }

                }

            }

#endif

        } else {

#if defined (DEBUG_MMU)

            if (loglevel != 0)

                fprintf(logfile, "No access allowed\n");

#endif

            ret = -3;

        }

    } else {

#if defined (DEBUG_MMU)

        if (loglevel != 0)

            fprintf(logfile, "direct store...\n");

#endif

        /* Direct-store segment : absolutely *BUGGY* for now */

        switch (type) {

        case ACCESS_INT:

            /* Integer load/store : only access allowed */

            break;

        case ACCESS_CODE:

            /* No code fetch is allowed in direct-store areas */

            return -4;

        case ACCESS_FLOAT:

            /* Floating point load/store */

            return -4;

        case ACCESS_RES:

            /* lwarx, ldarx or srwcx. */

            return -4;

        case ACCESS_CACHE:

            /* dcba, dcbt, dcbtst, dcbf, dcbi, dcbst, dcbz, or icbi */

            /* Should make the instruction do no-op.

             * As it already do no-op, it's quite easy :-)

             */

            ctx->raddr = eaddr;

            return 0;

        case ACCESS_EXT:

            /* eciwx or ecowx */

            return -4;

        default:

            if (logfile) {

                fprintf(logfile, "ERROR: instruction should not need "

                        "address translation\n");

            }

            return -4;

        }

        if ((rw == 1 || ctx->key != 1) && (rw == 0 || ctx->key != 0)) {

            ctx->raddr = eaddr;

            ret = 2;

        } else {

            ret = -2;

        }

    }

    return ret;

}


AVFilterBufferRef *avfilter_get_audio_buffer_ref_from_frame(const AVFrame *frame,

                                                            int perms)

{

    AVFilterBufferRef *samplesref =

        avfilter_get_audio_buffer_ref_from_arrays((uint8_t **)frame->data, frame->linesize[0], perms,

                                                  frame->nb_samples, frame->format,

                                                  av_frame_get_channel_layout(frame));

    if (!samplesref)

        return NULL;

    if (avfilter_copy_frame_props(samplesref, frame) < 0) {

        samplesref->buf->data[0] = NULL;

        avfilter_unref_bufferp(&samplesref);

    }

    return samplesref;

}


int ff_wmv2_decode_secondary_picture_header(MpegEncContext *s)

{

    Wmv2Context *const w = (Wmv2Context *) s;

    if (s->pict_type == AV_PICTURE_TYPE_I) {

        if (w->j_type_bit)

            w->j_type = get_bits1(&s->gb);

        else

            w->j_type = 0; // FIXME check

        if (!w->j_type) {

            if (w->per_mb_rl_bit)

                s->per_mb_rl_table = get_bits1(&s->gb);

            else

                s->per_mb_rl_table = 0;

            if (!s->per_mb_rl_table) {

                s->rl_chroma_table_index = decode012(&s->gb);

                s->rl_table_index        = decode012(&s->gb);

            }

            s->dc_table_index = get_bits1(&s->gb);

        }

        s->inter_intra_pred = 0;

        s->no_rounding      = 1;

        if (s->avctx->debug & FF_DEBUG_PICT_INFO) {

            av_log(s->avctx, AV_LOG_DEBUG,

                   "qscale:%d rlc:%d rl:%d dc:%d mbrl:%d j_type:%d \n",

                   s->qscale, s->rl_chroma_table_index, s->rl_table_index,

                   s->dc_table_index, s->per_mb_rl_table, w->j_type);

        }

    } else {

        int cbp_index;

        w->j_type = 0;

        parse_mb_skip(w);

        cbp_index = decode012(&s->gb);

        w->cbp_table_index = wmv2_get_cbp_table_index(s, cbp_index);

        if (w->mspel_bit)

            s->mspel = get_bits1(&s->gb);

        else

            s->mspel = 0; // FIXME check

        if (w->abt_flag) {

            w->per_mb_abt = get_bits1(&s->gb) ^ 1;

            if (!w->per_mb_abt)

                w->abt_type = decode012(&s->gb);

        }

        if (w->per_mb_rl_bit)

            s->per_mb_rl_table = get_bits1(&s->gb);

        else

            s->per_mb_rl_table = 0;

        if (!s->per_mb_rl_table) {

            s->rl_table_index        = decode012(&s->gb);

            s->rl_chroma_table_index = s->rl_table_index;

        }

        s->dc_table_index   = get_bits1(&s->gb);

        s->mv_table_index   = get_bits1(&s->gb);

        s->inter_intra_pred = 0; // (s->width * s->height < 320 * 240 && s->bit_rate <= II_BITRATE);

        s->no_rounding     ^= 1;

        if (s->avctx->debug & FF_DEBUG_PICT_INFO) {

            av_log(s->avctx, AV_LOG_DEBUG,

                   "rl:%d rlc:%d dc:%d mv:%d mbrl:%d qp:%d mspel:%d "

                   "per_mb_abt:%d abt_type:%d cbp:%d ii:%d\n",

                   s->rl_table_index, s->rl_chroma_table_index,

                   s->dc_table_index, s->mv_table_index,

                   s->per_mb_rl_table, s->qscale, s->mspel,

                   w->per_mb_abt, w->abt_type, w->cbp_table_index,

                   s->inter_intra_pred);

        }

    }

    s->esc3_level_length = 0;

    s->esc3_run_length   = 0;

    s->picture_number++; // FIXME ?

    if (w->j_type) {

        ff_intrax8_decode_picture(&w->x8, &s->current_picture,

                                  &s->gb, &s->mb_x, &s->mb_y,

                                  2 * s->qscale, (s->qscale - 1) | 1,

                                  s->loop_filter, s->low_delay);

        ff_er_add_slice(&w->s.er, 0, 0,

                        (w->s.mb_x >> 1) - 1, (w->s.mb_y >> 1) - 1,

                        ER_MB_END);

        return 1;

    }

    return 0;

}


static void vp8_decode_flush_impl(AVCodecContext *avctx, int force, int is_close)

{

    VP8Context *s = avctx->priv_data;

    int i;

    if (!avctx->is_copy || force) {

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

            if (s->frames[i].data[0])

                vp8_release_frame(s, &s->frames[i], is_close);

    }

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

    free_buffers(s);

    s->maps_are_invalid = 1;

}


static CharDriverState *qemu_chr_open_stdio(QemuOpts *opts)

{

    CharDriverState *chr;

    if (stdio_nb_clients >= STDIO_MAX_CLIENTS) {

    if (stdio_nb_clients == 0) {

        old_fd0_flags = fcntl(0, F_GETFL);

        tcgetattr (0, &oldtty);

        fcntl(0, F_SETFL, O_NONBLOCK);

        atexit(term_exit);

    chr = qemu_chr_open_fd(0, 1);

    chr->chr_close = qemu_chr_close_stdio;

    chr->chr_set_echo = qemu_chr_set_echo_stdio;

    qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);

    stdio_nb_clients++;

    stdio_allow_signal = qemu_opt_get_bool(opts, "signal",

                                           display_type != DT_NOGRAPHIC);

    qemu_chr_fe_set_echo(chr, false);

    return chr;


static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, uint8_t *buf, int buf_size)

{

	LclContext * const c = (LclContext *)avctx->priv_data;

	unsigned char *encoded = (unsigned char *)buf;

    int pixel_ptr;

    int row, col;

    unsigned char *outptr;

    unsigned int width = avctx->width; // Real image width

    unsigned int height = avctx->height; // Real image height

    unsigned int mszh_dlen;

    unsigned char yq, y1q, uq, vq;

    int uqvq;

    unsigned int mthread_inlen, mthread_outlen;

#ifdef CONFIG_ZLIB

    int zret; // Zlib return code

#endif

    int len = buf_size;

	/* no supplementary picture */

	if (buf_size == 0)

		return 0;

	if(c->pic.data[0])

		avctx->release_buffer(avctx, &c->pic);

	c->pic.reference = 0;

	c->pic.buffer_hints = FF_BUFFER_HINTS_VALID;

	if(avctx->get_buffer(avctx, &c->pic) < 0){

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

		return -1;

	}

    outptr = c->pic.data[0]; // Output image pointer

    /* Decompress frame */

    switch (avctx->codec_id) {

        case CODEC_ID_MSZH:

            switch (c->compression) {

                case COMP_MSZH:

                    if (c->flags & FLAG_MULTITHREAD) {

                        mthread_inlen = *((unsigned int*)encoded);

                        mthread_outlen = *((unsigned int*)(encoded+4));

                        mszh_dlen = mszh_decomp(encoded + 8, mthread_inlen, c->decomp_buf);

                        if (mthread_outlen != mszh_dlen) {

                            av_log(avctx, AV_LOG_ERROR, "Mthread1 decoded size differs (%d != %d)\n",

                                   mthread_outlen, mszh_dlen);

                        }

                        mszh_dlen = mszh_decomp(encoded + 8 + mthread_inlen, len - mthread_inlen,

                                                c->decomp_buf + mthread_outlen);

                        if ((c->decomp_size - mthread_outlen) != mszh_dlen) {

                            av_log(avctx, AV_LOG_ERROR, "Mthread2 decoded size differs (%d != %d)\n",

                                   c->decomp_size - mthread_outlen, mszh_dlen);

                        }

                        encoded = c->decomp_buf;

                        len = c->decomp_size;

                    } else {

                        mszh_dlen = mszh_decomp(encoded, len, c->decomp_buf);

                        if (c->decomp_size != mszh_dlen) {

                            av_log(avctx, AV_LOG_ERROR, "Decoded size differs (%d != %d)\n",

                                   c->decomp_size, mszh_dlen);

                        }

                        encoded = c->decomp_buf;

                        len = mszh_dlen;

                    }

                    break;

                case COMP_MSZH_NOCOMP:

                    break;

                default:

                    av_log(avctx, AV_LOG_ERROR, "BUG! Unknown MSZH compression in frame decoder.\n");

                    return -1;

            }

            break;

        case CODEC_ID_ZLIB:

#ifdef CONFIG_ZLIB

            /* Using the original dll with normal compression (-1) and RGB format

             * gives a file with ZLIB fourcc, but frame is really uncompressed.

             * To be sure that's true check also frame size */

            if ((c->compression == COMP_ZLIB_NORMAL) && (c->imgtype == IMGTYPE_RGB24) &&

               (len == width * height * 3))

                break;

            zret = inflateReset(&(c->zstream));

            if (zret != Z_OK) {

                av_log(avctx, AV_LOG_ERROR, "Inflate reset error: %d\n", zret);

                return -1;

            }

            if (c->flags & FLAG_MULTITHREAD) {

                mthread_inlen = *((unsigned int*)encoded);

                mthread_outlen = *((unsigned int*)(encoded+4));

                c->zstream.next_in = encoded + 8;

                c->zstream.avail_in = mthread_inlen;

                c->zstream.next_out = c->decomp_buf;

                c->zstream.avail_out = mthread_outlen;

                zret = inflate(&(c->zstream), Z_FINISH);

                if ((zret != Z_OK) && (zret != Z_STREAM_END)) {

                    av_log(avctx, AV_LOG_ERROR, "Mthread1 inflate error: %d\n", zret);

                    return -1;

                }

                if (mthread_outlen != (unsigned int)(c->zstream.total_out)) {

                    av_log(avctx, AV_LOG_ERROR, "Mthread1 decoded size differs (%u != %lu)\n",

                           mthread_outlen, c->zstream.total_out);

                }

                zret = inflateReset(&(c->zstream));

                if (zret != Z_OK) {

                    av_log(avctx, AV_LOG_ERROR, "Mthread2 inflate reset error: %d\n", zret);

                    return -1;

                }

                c->zstream.next_in = encoded + 8 + mthread_inlen;

                c->zstream.avail_in = len - mthread_inlen;

                c->zstream.next_out = c->decomp_buf + mthread_outlen;

                c->zstream.avail_out = mthread_outlen;

                zret = inflate(&(c->zstream), Z_FINISH);

                if ((zret != Z_OK) && (zret != Z_STREAM_END)) {

                    av_log(avctx, AV_LOG_ERROR, "Mthread2 inflate error: %d\n", zret);

                    return -1;

                }

                if ((c->decomp_size - mthread_outlen) != (unsigned int)(c->zstream.total_out)) {

                    av_log(avctx, AV_LOG_ERROR, "Mthread2 decoded size differs (%d != %lu)\n",

                           c->decomp_size - mthread_outlen, c->zstream.total_out);

                }

            } else {

                c->zstream.next_in = encoded;

                c->zstream.avail_in = len;

                c->zstream.next_out = c->decomp_buf;

                c->zstream.avail_out = c->decomp_size;

                zret = inflate(&(c->zstream), Z_FINISH);

                if ((zret != Z_OK) && (zret != Z_STREAM_END)) {

                    av_log(avctx, AV_LOG_ERROR, "Inflate error: %d\n", zret);

                    return -1;

                }

                if (c->decomp_size != (unsigned int)(c->zstream.total_out)) {

                    av_log(avctx, AV_LOG_ERROR, "Decoded size differs (%d != %lu)\n",

                           c->decomp_size, c->zstream.total_out);

                }

            }

            encoded = c->decomp_buf;

            len = c->decomp_size;;

#else

            av_log(avctx, AV_LOG_ERROR, "BUG! Zlib support not compiled in frame decoder.\n");

            return -1;

#endif

            break;

        default:

            av_log(avctx, AV_LOG_ERROR, "BUG! Unknown codec in frame decoder compression switch.\n");

            return -1;

    }

    /* Apply PNG filter */

    if ((avctx->codec_id == CODEC_ID_ZLIB) && (c->flags & FLAG_PNGFILTER)) {

        switch (c->imgtype) {

            case IMGTYPE_YUV111:

            case IMGTYPE_RGB24:

                for (row = 0; row < height; row++) {

                    pixel_ptr = row * width * 3;

                    yq = encoded[pixel_ptr++];

                    uqvq = encoded[pixel_ptr++];

              	  uqvq+=(encoded[pixel_ptr++] << 8);

                    for (col = 1; col < width; col++) {

                        encoded[pixel_ptr] = yq -= encoded[pixel_ptr];

                        uqvq -= (encoded[pixel_ptr+1] | (encoded[pixel_ptr+2]<<8));

                        encoded[pixel_ptr+1] = (uqvq) & 0xff;

                        encoded[pixel_ptr+2] = ((uqvq)>>8) & 0xff;

                        pixel_ptr += 3;

                    }

                }

                break;

            case IMGTYPE_YUV422:

                for (row = 0; row < height; row++) {

                    pixel_ptr = row * width * 2;

                    yq = uq = vq =0;

                    for (col = 0; col < width/4; col++) {

                        encoded[pixel_ptr] = yq -= encoded[pixel_ptr];

                        encoded[pixel_ptr+1] = yq -= encoded[pixel_ptr+1];

                        encoded[pixel_ptr+2] = yq -= encoded[pixel_ptr+2];

                        encoded[pixel_ptr+3] = yq -= encoded[pixel_ptr+3];

                        encoded[pixel_ptr+4] = uq -= encoded[pixel_ptr+4];

                        encoded[pixel_ptr+5] = uq -= encoded[pixel_ptr+5];

                        encoded[pixel_ptr+6] = vq -= encoded[pixel_ptr+6];

                        encoded[pixel_ptr+7] = vq -= encoded[pixel_ptr+7];

                        pixel_ptr += 8;

                    }

                }

                break;

            case IMGTYPE_YUV411:

                for (row = 0; row < height; row++) {

                    pixel_ptr = row * width / 2 * 3;

                    yq = uq = vq =0;

                    for (col = 0; col < width/4; col++) {

                        encoded[pixel_ptr] = yq -= encoded[pixel_ptr];

                        encoded[pixel_ptr+1] = yq -= encoded[pixel_ptr+1];

                        encoded[pixel_ptr+2] = yq -= encoded[pixel_ptr+2];

                        encoded[pixel_ptr+3] = yq -= encoded[pixel_ptr+3];

                        encoded[pixel_ptr+4] = uq -= encoded[pixel_ptr+4];

                        encoded[pixel_ptr+5] = vq -= encoded[pixel_ptr+5];

                        pixel_ptr += 6;

                    }

                }

                break;

            case IMGTYPE_YUV211:

                for (row = 0; row < height; row++) {

                    pixel_ptr = row * width * 2;

                    yq = uq = vq =0;

                    for (col = 0; col < width/2; col++) {

                        encoded[pixel_ptr] = yq -= encoded[pixel_ptr];

                        encoded[pixel_ptr+1] = yq -= encoded[pixel_ptr+1];

                        encoded[pixel_ptr+2] = uq -= encoded[pixel_ptr+2];

                        encoded[pixel_ptr+3] = vq -= encoded[pixel_ptr+3];

                        pixel_ptr += 4;

                    }

                }

                break;

            case IMGTYPE_YUV420:

                for (row = 0; row < height/2; row++) {

                    pixel_ptr = row * width * 3;

                    yq = y1q = uq = vq =0;

                    for (col = 0; col < width/2; col++) {

                        encoded[pixel_ptr] = yq -= encoded[pixel_ptr];

                        encoded[pixel_ptr+1] = yq -= encoded[pixel_ptr+1];

                        encoded[pixel_ptr+2] = y1q -= encoded[pixel_ptr+2];

                        encoded[pixel_ptr+3] = y1q -= encoded[pixel_ptr+3];

                        encoded[pixel_ptr+4] = uq -= encoded[pixel_ptr+4];

                        encoded[pixel_ptr+5] = vq -= encoded[pixel_ptr+5];

                        pixel_ptr += 6;

                    }

                }

                break;

            default:

                av_log(avctx, AV_LOG_ERROR, "BUG! Unknown imagetype in pngfilter switch.\n");

                return -1;

        }

    }

    /* Convert colorspace */

    switch (c->imgtype) {

        case IMGTYPE_YUV111:

            for (row = height - 1; row >= 0; row--) {

                pixel_ptr = row * c->pic.linesize[0];

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

                    outptr[pixel_ptr++] = get_b(encoded[0], encoded[1]);

                    outptr[pixel_ptr++] = get_g(encoded[0], encoded[1], encoded[2]);

                    outptr[pixel_ptr++] = get_r(encoded[0], encoded[2]);

                    encoded += 3;

                }

            }

            break;

        case IMGTYPE_YUV422:

            for (row = height - 1; row >= 0; row--) {

                pixel_ptr = row * c->pic.linesize[0];

                for (col = 0; col < width/4; col++) {

                    outptr[pixel_ptr++] = get_b(encoded[0], encoded[4]);

                    outptr[pixel_ptr++] = get_g(encoded[0], encoded[4], encoded[6]);

                    outptr[pixel_ptr++] = get_r(encoded[0], encoded[6]);

                    outptr[pixel_ptr++] = get_b(encoded[1], encoded[4]);

                    outptr[pixel_ptr++] = get_g(encoded[1], encoded[4], encoded[6]);

                    outptr[pixel_ptr++] = get_r(encoded[1], encoded[6]);

                    outptr[pixel_ptr++] = get_b(encoded[2], encoded[5]);

                    outptr[pixel_ptr++] = get_g(encoded[2], encoded[5], encoded[7]);

                    outptr[pixel_ptr++] = get_r(encoded[2], encoded[7]);

                    outptr[pixel_ptr++] = get_b(encoded[3], encoded[5]);

                    outptr[pixel_ptr++] = get_g(encoded[3], encoded[5], encoded[7]);

                    outptr[pixel_ptr++] = get_r(encoded[3], encoded[7]);

                    encoded += 8;

                }

            }

            break;

        case IMGTYPE_RGB24:

            for (row = height - 1; row >= 0; row--) {

                pixel_ptr = row * c->pic.linesize[0];

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

                    outptr[pixel_ptr++] = encoded[0];

                    outptr[pixel_ptr++] = encoded[1];

                    outptr[pixel_ptr++] = encoded[2];

                    encoded += 3;

                }

            }

            break;

        case IMGTYPE_YUV411:

            for (row = height - 1; row >= 0; row--) {

                pixel_ptr = row * c->pic.linesize[0];

                for (col = 0; col < width/4; col++) {

                    outptr[pixel_ptr++] = get_b(encoded[0], encoded[4]);

                    outptr[pixel_ptr++] = get_g(encoded[0], encoded[4], encoded[5]);

                    outptr[pixel_ptr++] = get_r(encoded[0], encoded[5]);

                    outptr[pixel_ptr++] = get_b(encoded[1], encoded[4]);

                    outptr[pixel_ptr++] = get_g(encoded[1], encoded[4], encoded[5]);

                    outptr[pixel_ptr++] = get_r(encoded[1], encoded[5]);

                    outptr[pixel_ptr++] = get_b(encoded[2], encoded[4]);

                    outptr[pixel_ptr++] = get_g(encoded[2], encoded[4], encoded[5]);

                    outptr[pixel_ptr++] = get_r(encoded[2], encoded[5]);

                    outptr[pixel_ptr++] = get_b(encoded[3], encoded[4]);

                    outptr[pixel_ptr++] = get_g(encoded[3], encoded[4], encoded[5]);

                    outptr[pixel_ptr++] = get_r(encoded[3], encoded[5]);

                    encoded += 6;

                }

            }

            break;

        case IMGTYPE_YUV211:

            for (row = height - 1; row >= 0; row--) {

                pixel_ptr = row * c->pic.linesize[0];

                for (col = 0; col < width/2; col++) {

                    outptr[pixel_ptr++] = get_b(encoded[0], encoded[2]);

                    outptr[pixel_ptr++] = get_g(encoded[0], encoded[2], encoded[3]);

                    outptr[pixel_ptr++] = get_r(encoded[0], encoded[3]);

                    outptr[pixel_ptr++] = get_b(encoded[1], encoded[2]);

                    outptr[pixel_ptr++] = get_g(encoded[1], encoded[2], encoded[3]);

                    outptr[pixel_ptr++] = get_r(encoded[1], encoded[3]);

                    encoded += 4;

                }

            }

            break;

        case IMGTYPE_YUV420:

            for (row = height / 2 - 1; row >= 0; row--) {

                pixel_ptr = 2 * row * c->pic.linesize[0];

                for (col = 0; col < width/2; col++) {

                    outptr[pixel_ptr] = get_b(encoded[0], encoded[4]);

                    outptr[pixel_ptr+1] = get_g(encoded[0], encoded[4], encoded[5]);

                    outptr[pixel_ptr+2] = get_r(encoded[0], encoded[5]);

                    outptr[pixel_ptr+3] = get_b(encoded[1], encoded[4]);

                    outptr[pixel_ptr+4] = get_g(encoded[1], encoded[4], encoded[5]);

                    outptr[pixel_ptr+5] = get_r(encoded[1], encoded[5]);

                    outptr[pixel_ptr-c->pic.linesize[0]] = get_b(encoded[2], encoded[4]);

                    outptr[pixel_ptr-c->pic.linesize[0]+1] = get_g(encoded[2], encoded[4], encoded[5]);

                    outptr[pixel_ptr-c->pic.linesize[0]+2] = get_r(encoded[2], encoded[5]);

                    outptr[pixel_ptr-c->pic.linesize[0]+3] = get_b(encoded[3], encoded[4]);

                    outptr[pixel_ptr-c->pic.linesize[0]+4] = get_g(encoded[3], encoded[4], encoded[5]);

                    outptr[pixel_ptr-c->pic.linesize[0]+5] = get_r(encoded[3], encoded[5]);

                    pixel_ptr += 6;

                    encoded += 6;

                }

            }

            break;

        default:

            av_log(avctx, AV_LOG_ERROR, "BUG! Unknown imagetype in image decoder.\n");

            return -1;

    }

    *data_size = sizeof(AVFrame);

    *(AVFrame*)data = c->pic;

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

    return buf_size;

}


static int ram_save_host_page(RAMState *rs, PageSearchStatus *pss,

                              bool last_stage)

{

    int tmppages, pages = 0;

    size_t pagesize_bits =

        qemu_ram_pagesize(pss->block) >> TARGET_PAGE_BITS;

    do {

        tmppages = ram_save_target_page(rs, pss, last_stage);

        if (tmppages < 0) {

            return tmppages;

        }

        pages += tmppages;

        pss->page++;

    } while (pss->page & (pagesize_bits - 1));

    /* The offset we leave with is the last one we looked at */

    pss->page--;

    return pages;

}


static int qemu_rdma_exchange_recv(RDMAContext *rdma, RDMAControlHeader *head,

                                int expecting)

{

    RDMAControlHeader ready = {

                                .len = 0,

                                .type = RDMA_CONTROL_READY,

                                .repeat = 1,

                              };

    int ret;

    /*

     * Inform the source that we're ready to receive a message.

     */

    ret = qemu_rdma_post_send_control(rdma, NULL, &ready);

    if (ret < 0) {

        fprintf(stderr, "Failed to send control buffer!\n");

        return ret;

    }

    /*

     * Block and wait for the message.

     */

    ret = qemu_rdma_exchange_get_response(rdma, head,

                                          expecting, RDMA_WRID_READY);

    if (ret < 0) {

        return ret;

    }

    qemu_rdma_move_header(rdma, RDMA_WRID_READY, head);

    /*

     * Post a new RECV work request to replace the one we just consumed.

     */

    ret = qemu_rdma_post_recv_control(rdma, RDMA_WRID_READY);

    if (ret) {

        fprintf(stderr, "rdma migration: error posting second control recv!");

        return ret;

    }

    return 0;

}


static int qxl_track_command(PCIQXLDevice *qxl, struct QXLCommandExt *ext)

{

    switch (le32_to_cpu(ext->cmd.type)) {

    case QXL_CMD_SURFACE:

    {

        QXLSurfaceCmd *cmd = qxl_phys2virt(qxl, ext->cmd.data, ext->group_id);

        if (!cmd) {

        uint32_t id = le32_to_cpu(cmd->surface_id);

        if (id >= qxl->ssd.num_surfaces) {

            qxl_set_guest_bug(qxl, "QXL_CMD_SURFACE id %d >= %d", id,

                              qxl->ssd.num_surfaces);

        qemu_mutex_lock(&qxl->track_lock);

        if (cmd->type == QXL_SURFACE_CMD_CREATE) {

            qxl->guest_surfaces.cmds[id] = ext->cmd.data;

            qxl->guest_surfaces.count++;

            if (qxl->guest_surfaces.max < qxl->guest_surfaces.count)

                qxl->guest_surfaces.max = qxl->guest_surfaces.count;

        if (cmd->type == QXL_SURFACE_CMD_DESTROY) {

            qxl->guest_surfaces.cmds[id] = 0;

            qxl->guest_surfaces.count--;

        qemu_mutex_unlock(&qxl->track_lock);

        break;

    case QXL_CMD_CURSOR:

    {

        QXLCursorCmd *cmd = qxl_phys2virt(qxl, ext->cmd.data, ext->group_id);

        if (!cmd) {

        if (cmd->type == QXL_CURSOR_SET) {

            qemu_mutex_lock(&qxl->track_lock);

            qxl->guest_cursor = ext->cmd.data;

            qemu_mutex_unlock(&qxl->track_lock);

        break;

    return 0;


int tcp_fconnect(struct socket *so)

{

  Slirp *slirp = so->slirp;

  int ret=0;

  DEBUG_CALL("tcp_fconnect");

  DEBUG_ARG("so = %lx", (long )so);

  if( (ret=so->s=socket(AF_INET,SOCK_STREAM,0)) >= 0) {

    int opt, s=so->s;

    struct sockaddr_in addr;

    fd_nonblock(s);

    opt = 1;

    setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(char *)&opt,sizeof(opt ));

    opt = 1;

    setsockopt(s,SOL_SOCKET,SO_OOBINLINE,(char *)&opt,sizeof(opt ));

    addr.sin_family = AF_INET;

    if ((so->so_faddr.s_addr & slirp->vnetwork_mask.s_addr) ==

        slirp->vnetwork_addr.s_addr) {

      /* It's an alias */

      if (so->so_faddr.s_addr == slirp->vnameserver_addr.s_addr) {

	if (get_dns_addr(&addr.sin_addr) < 0)

	  addr.sin_addr = loopback_addr;

      } else {

	addr.sin_addr = loopback_addr;

      }

    } else

      addr.sin_addr = so->so_faddr;

    addr.sin_port = so->so_fport;

    DEBUG_MISC((dfd, " connect()ing, addr.sin_port=%d, "

		"addr.sin_addr.s_addr=%.16s\n",

		ntohs(addr.sin_port), inet_ntoa(addr.sin_addr)));

    /* We don't care what port we get */

    ret = connect(s,(struct sockaddr *)&addr,sizeof (addr));

    /*

     * If it's not in progress, it failed, so we just return 0,

     * without clearing SS_NOFDREF

     */

    soisfconnecting(so);

  }

  return(ret);

}


static void cloop_close(BlockDriverState *bs)

{

    BDRVCloopState *s = bs->opaque;

    if (s->n_blocks > 0) {

        g_free(s->offsets);

    }

    g_free(s->compressed_block);

    g_free(s->uncompressed_block);

    inflateEnd(&s->zstream);

}


PROTO4(_pack_2ch_)

PROTO4(_pack_6ch_)

PROTO4(_pack_8ch_)

PROTO4(_unpack_2ch_)

PROTO4(_unpack_6ch_)

av_cold void swri_audio_convert_init_x86(struct AudioConvert *ac,

                                 enum AVSampleFormat out_fmt,

                                 enum AVSampleFormat in_fmt,

                                 int channels){

    int mm_flags = av_get_cpu_flags();

    ac->simd_f= NULL;

//FIXME add memcpy case

#define MULTI_CAPS_FUNC(flag, cap) \

    if (EXTERNAL_##flag(mm_flags)) {\

        if(   out_fmt == AV_SAMPLE_FMT_S32  && in_fmt == AV_SAMPLE_FMT_S16 || out_fmt == AV_SAMPLE_FMT_S32P && in_fmt == AV_SAMPLE_FMT_S16P)\

            ac->simd_f =  ff_int16_to_int32_a_ ## cap;\

        if(   out_fmt == AV_SAMPLE_FMT_S16  && in_fmt == AV_SAMPLE_FMT_S32 || out_fmt == AV_SAMPLE_FMT_S16P && in_fmt == AV_SAMPLE_FMT_S32P)\

            ac->simd_f =  ff_int32_to_int16_a_ ## cap;\

    }

MULTI_CAPS_FUNC(MMX, mmx)

MULTI_CAPS_FUNC(SSE2, sse2)

    if(EXTERNAL_MMX(mm_flags)) {

        if(channels == 6) {

            if(   out_fmt == AV_SAMPLE_FMT_FLT  && in_fmt == AV_SAMPLE_FMT_FLTP || out_fmt == AV_SAMPLE_FMT_S32 && in_fmt == AV_SAMPLE_FMT_S32P)

                ac->simd_f =  ff_pack_6ch_float_to_float_a_mmx;

        }

    }

    if(EXTERNAL_SSE(mm_flags)) {

        if(channels == 6) {

            if(   out_fmt == AV_SAMPLE_FMT_FLT  && in_fmt == AV_SAMPLE_FMT_FLTP || out_fmt == AV_SAMPLE_FMT_S32 && in_fmt == AV_SAMPLE_FMT_S32P)

                ac->simd_f =  ff_pack_6ch_float_to_float_a_sse;

            if(   out_fmt == AV_SAMPLE_FMT_FLTP  && in_fmt == AV_SAMPLE_FMT_FLT || out_fmt == AV_SAMPLE_FMT_S32P && in_fmt == AV_SAMPLE_FMT_S32)

                ac->simd_f =  ff_unpack_6ch_float_to_float_a_sse;

        }

    }

    if(EXTERNAL_SSE2(mm_flags)) {

        if(   out_fmt == AV_SAMPLE_FMT_FLT  && in_fmt == AV_SAMPLE_FMT_S32 || out_fmt == AV_SAMPLE_FMT_FLTP && in_fmt == AV_SAMPLE_FMT_S32P)

            ac->simd_f =  ff_int32_to_float_a_sse2;

        if(   out_fmt == AV_SAMPLE_FMT_FLT  && in_fmt == AV_SAMPLE_FMT_S16 || out_fmt == AV_SAMPLE_FMT_FLTP && in_fmt == AV_SAMPLE_FMT_S16P)

            ac->simd_f =  ff_int16_to_float_a_sse2;

        if(   out_fmt == AV_SAMPLE_FMT_S32  && in_fmt == AV_SAMPLE_FMT_FLT || out_fmt == AV_SAMPLE_FMT_S32P && in_fmt == AV_SAMPLE_FMT_FLTP)

            ac->simd_f =  ff_float_to_int32_a_sse2;

        if(   out_fmt == AV_SAMPLE_FMT_S16  && in_fmt == AV_SAMPLE_FMT_FLT || out_fmt == AV_SAMPLE_FMT_S16P && in_fmt == AV_SAMPLE_FMT_FLTP)

            ac->simd_f =  ff_float_to_int16_a_sse2;

        if(channels == 2) {

            if(   out_fmt == AV_SAMPLE_FMT_FLT  && in_fmt == AV_SAMPLE_FMT_FLTP || out_fmt == AV_SAMPLE_FMT_S32 && in_fmt == AV_SAMPLE_FMT_S32P)

                ac->simd_f =  ff_pack_2ch_int32_to_int32_a_sse2;

            if(   out_fmt == AV_SAMPLE_FMT_S16  && in_fmt == AV_SAMPLE_FMT_S16P)

                ac->simd_f =  ff_pack_2ch_int16_to_int16_a_sse2;

            if(   out_fmt == AV_SAMPLE_FMT_S32  && in_fmt == AV_SAMPLE_FMT_S16P)

                ac->simd_f =  ff_pack_2ch_int16_to_int32_a_sse2;

            if(   out_fmt == AV_SAMPLE_FMT_S16  && in_fmt == AV_SAMPLE_FMT_S32P)

                ac->simd_f =  ff_pack_2ch_int32_to_int16_a_sse2;

            if(   out_fmt == AV_SAMPLE_FMT_FLTP  && in_fmt == AV_SAMPLE_FMT_FLT || out_fmt == AV_SAMPLE_FMT_S32P && in_fmt == AV_SAMPLE_FMT_S32)

                ac->simd_f =  ff_unpack_2ch_int32_to_int32_a_sse2;

            if(   out_fmt == AV_SAMPLE_FMT_S16P  && in_fmt == AV_SAMPLE_FMT_S16)

                ac->simd_f =  ff_unpack_2ch_int16_to_int16_a_sse2;

            if(   out_fmt == AV_SAMPLE_FMT_S32P  && in_fmt == AV_SAMPLE_FMT_S16)

                ac->simd_f =  ff_unpack_2ch_int16_to_int32_a_sse2;

            if(   out_fmt == AV_SAMPLE_FMT_S16P  && in_fmt == AV_SAMPLE_FMT_S32)

                ac->simd_f =  ff_unpack_2ch_int32_to_int16_a_sse2;

            if(   out_fmt == AV_SAMPLE_FMT_FLT  && in_fmt == AV_SAMPLE_FMT_S32P)

                ac->simd_f =  ff_pack_2ch_int32_to_float_a_sse2;

            if(   out_fmt == AV_SAMPLE_FMT_S32  && in_fmt == AV_SAMPLE_FMT_FLTP)

                ac->simd_f =  ff_pack_2ch_float_to_int32_a_sse2;

            if(   out_fmt == AV_SAMPLE_FMT_FLT  && in_fmt == AV_SAMPLE_FMT_S16P)

                ac->simd_f =  ff_pack_2ch_int16_to_float_a_sse2;

            if(   out_fmt == AV_SAMPLE_FMT_S16  && in_fmt == AV_SAMPLE_FMT_FLTP)

                ac->simd_f =  ff_pack_2ch_float_to_int16_a_sse2;

            if(   out_fmt == AV_SAMPLE_FMT_FLTP  && in_fmt == AV_SAMPLE_FMT_S32)

                ac->simd_f =  ff_unpack_2ch_int32_to_float_a_sse2;

            if(   out_fmt == AV_SAMPLE_FMT_S32P  && in_fmt == AV_SAMPLE_FMT_FLT)

                ac->simd_f =  ff_unpack_2ch_float_to_int32_a_sse2;

            if(   out_fmt == AV_SAMPLE_FMT_FLTP  && in_fmt == AV_SAMPLE_FMT_S16)

                ac->simd_f =  ff_unpack_2ch_int16_to_float_a_sse2;

            if(   out_fmt == AV_SAMPLE_FMT_S16P  && in_fmt == AV_SAMPLE_FMT_FLT)

                ac->simd_f =  ff_unpack_2ch_float_to_int16_a_sse2;

        }

        if(channels == 6) {

            if(   out_fmt == AV_SAMPLE_FMT_FLT  && in_fmt == AV_SAMPLE_FMT_S32P)

                ac->simd_f =  ff_pack_6ch_int32_to_float_a_sse2;

            if(   out_fmt == AV_SAMPLE_FMT_S32  && in_fmt == AV_SAMPLE_FMT_FLTP)

                ac->simd_f =  ff_pack_6ch_float_to_int32_a_sse2;

            if(   out_fmt == AV_SAMPLE_FMT_FLTP  && in_fmt == AV_SAMPLE_FMT_S32)

                ac->simd_f =  ff_unpack_6ch_int32_to_float_a_sse2;

            if(   out_fmt == AV_SAMPLE_FMT_S32P  && in_fmt == AV_SAMPLE_FMT_FLT)

                ac->simd_f =  ff_unpack_6ch_float_to_int32_a_sse2;

        }

        if(channels == 8) {

            if(   out_fmt == AV_SAMPLE_FMT_FLT  && in_fmt == AV_SAMPLE_FMT_FLTP || out_fmt == AV_SAMPLE_FMT_S32 && in_fmt == AV_SAMPLE_FMT_S32P)

                ac->simd_f =  ff_pack_8ch_float_to_float_a_sse2;

            if(   out_fmt == AV_SAMPLE_FMT_FLT  && in_fmt == AV_SAMPLE_FMT_S32P)

                ac->simd_f =  ff_pack_8ch_int32_to_float_a_sse2;

            if(   out_fmt == AV_SAMPLE_FMT_S32  && in_fmt == AV_SAMPLE_FMT_FLTP)

                ac->simd_f =  ff_pack_8ch_float_to_int32_a_sse2;

        }

    }

    if(EXTERNAL_SSSE3(mm_flags)) {

        if(channels == 2) {

            if(   out_fmt == AV_SAMPLE_FMT_S16P  && in_fmt == AV_SAMPLE_FMT_S16)

                ac->simd_f =  ff_unpack_2ch_int16_to_int16_a_ssse3;

            if(   out_fmt == AV_SAMPLE_FMT_S32P  && in_fmt == AV_SAMPLE_FMT_S16)

                ac->simd_f =  ff_unpack_2ch_int16_to_int32_a_ssse3;

            if(   out_fmt == AV_SAMPLE_FMT_FLTP  && in_fmt == AV_SAMPLE_FMT_S16)

                ac->simd_f =  ff_unpack_2ch_int16_to_float_a_ssse3;

        }

    }

    if(EXTERNAL_AVX(mm_flags)) {

        if(   out_fmt == AV_SAMPLE_FMT_FLT  && in_fmt == AV_SAMPLE_FMT_S32 || out_fmt == AV_SAMPLE_FMT_FLTP && in_fmt == AV_SAMPLE_FMT_S32P)

            ac->simd_f =  ff_int32_to_float_a_avx;

        if(channels == 6) {

            if(   out_fmt == AV_SAMPLE_FMT_FLT  && in_fmt == AV_SAMPLE_FMT_FLTP || out_fmt == AV_SAMPLE_FMT_S32 && in_fmt == AV_SAMPLE_FMT_S32P)

                ac->simd_f =  ff_pack_6ch_float_to_float_a_avx;

            if(   out_fmt == AV_SAMPLE_FMT_FLT  && in_fmt == AV_SAMPLE_FMT_S32P)

                ac->simd_f =  ff_pack_6ch_int32_to_float_a_avx;

            if(   out_fmt == AV_SAMPLE_FMT_S32  && in_fmt == AV_SAMPLE_FMT_FLTP)

                ac->simd_f =  ff_pack_6ch_float_to_int32_a_avx;

            if(   out_fmt == AV_SAMPLE_FMT_FLTP  && in_fmt == AV_SAMPLE_FMT_FLT || out_fmt == AV_SAMPLE_FMT_S32P && in_fmt == AV_SAMPLE_FMT_S32)

                ac->simd_f =  ff_unpack_6ch_float_to_float_a_avx;

            if(   out_fmt == AV_SAMPLE_FMT_FLTP  && in_fmt == AV_SAMPLE_FMT_S32)

                ac->simd_f =  ff_unpack_6ch_int32_to_float_a_avx;

            if(   out_fmt == AV_SAMPLE_FMT_S32P  && in_fmt == AV_SAMPLE_FMT_FLT)

                ac->simd_f =  ff_unpack_6ch_float_to_int32_a_avx;

        }

        if(channels == 8) {

            if(   out_fmt == AV_SAMPLE_FMT_FLT  && in_fmt == AV_SAMPLE_FMT_FLTP || out_fmt == AV_SAMPLE_FMT_S32 && in_fmt == AV_SAMPLE_FMT_S32P)

                ac->simd_f =  ff_pack_8ch_float_to_float_a_avx;

            if(   out_fmt == AV_SAMPLE_FMT_FLT  && in_fmt == AV_SAMPLE_FMT_S32P)

                ac->simd_f =  ff_pack_8ch_int32_to_float_a_avx;

            if(   out_fmt == AV_SAMPLE_FMT_S32  && in_fmt == AV_SAMPLE_FMT_FLTP)

                ac->simd_f =  ff_pack_8ch_float_to_int32_a_avx;

        }

    }

    if(EXTERNAL_AVX2(mm_flags)) {

        if(   out_fmt == AV_SAMPLE_FMT_S32  && in_fmt == AV_SAMPLE_FMT_FLT || out_fmt == AV_SAMPLE_FMT_S32P && in_fmt == AV_SAMPLE_FMT_FLTP)

            ac->simd_f =  ff_float_to_int32_a_avx2;

    }

}


int ff_unlock_avcodec(const AVCodec *codec)

{

    _Bool exp = 1;

    if (codec->caps_internal & FF_CODEC_CAP_INIT_THREADSAFE || !codec->init)

        return 0;

    av_assert0(atomic_compare_exchange_strong(&ff_avcodec_locked, &exp, 0));

    atomic_fetch_add(&entangled_thread_counter, -1);

    if (lockmgr_cb) {

        if ((*lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE))

            return -1;

    }

    return 0;

}


static int ivi_decode_coded_blocks(GetBitContext *gb, IVIBandDesc *band,

                                   ivi_mc_func mc, int mv_x, int mv_y,

                                   int *prev_dc, int is_intra, int mc_type,

                                   uint32_t quant, int offs,

                                   AVCodecContext *avctx)

{

    const uint16_t *base_tab  = is_intra ? band->intra_base : band->inter_base;

    RVMapDesc *rvmap = band->rv_map;

    uint8_t col_flags[8];

    int32_t trvec[64];

    uint32_t sym = 0, lo, hi, q;

    int pos, run, val;

    int blk_size   = band->blk_size;

    int num_coeffs = blk_size * blk_size;

    int col_mask   = blk_size - 1;

    int scan_pos   = -1;

    int min_size   = band->pitch * (band->transform_size - 1) +

                     band->transform_size;

    int buf_size   = band->pitch * band->aheight - offs;

    if (min_size > buf_size)

        return AVERROR_INVALIDDATA;

    if (!band->scan) {

        av_log(avctx, AV_LOG_ERROR, "Scan pattern is not set.\n");

        return AVERROR_INVALIDDATA;

    }

    /* zero transform vector */

    memset(trvec, 0, num_coeffs * sizeof(trvec[0]));

    /* zero column flags */

    memset(col_flags, 0, sizeof(col_flags));

    while (scan_pos <= num_coeffs) {

        sym = get_vlc2(gb, band->blk_vlc.tab->table,

                       IVI_VLC_BITS, 1);

        if (sym == rvmap->eob_sym)

            break; /* End of block */

        /* Escape - run/val explicitly coded using 3 vlc codes */

        if (sym == rvmap->esc_sym) {

            run = get_vlc2(gb, band->blk_vlc.tab->table, IVI_VLC_BITS, 1) + 1;

            lo  = get_vlc2(gb, band->blk_vlc.tab->table, IVI_VLC_BITS, 1);

            hi  = get_vlc2(gb, band->blk_vlc.tab->table, IVI_VLC_BITS, 1);

            /* merge them and convert into signed val */

            val = IVI_TOSIGNED((hi << 6) | lo);

        } else {

            if (sym >= 256U) {

                av_log(avctx, AV_LOG_ERROR, "Invalid sym encountered: %d.\n", sym);

                return AVERROR_INVALIDDATA;

            }

            run = rvmap->runtab[sym];

            val = rvmap->valtab[sym];

        }

        /* de-zigzag and dequantize */

        scan_pos += run;

        if (scan_pos >= num_coeffs || scan_pos < 0)

            break;

        pos = band->scan[scan_pos];

        if (!val)

            av_dlog(avctx, "Val = 0 encountered!\n");

        q = (base_tab[pos] * quant) >> 9;

        if (q > 1)

            val = val * q + FFSIGN(val) * (((q ^ 1) - 1) >> 1);

        trvec[pos] = val;

        /* track columns containing non-zero coeffs */

        col_flags[pos & col_mask] |= !!val;

    }

    if (scan_pos < 0 || scan_pos >= num_coeffs && sym != rvmap->eob_sym)

        return AVERROR_INVALIDDATA; /* corrupt block data */

    /* undoing DC coeff prediction for intra-blocks */

    if (is_intra && band->is_2d_trans) {

        *prev_dc     += trvec[0];

        trvec[0]      = *prev_dc;

        col_flags[0] |= !!*prev_dc;

    }

    /* apply inverse transform */

    band->inv_transform(trvec, band->buf + offs,

                        band->pitch, col_flags);

    /* apply motion compensation */

    if (!is_intra)

        return ivi_mc(mc, band->buf, band->ref_buf, offs, mv_x, mv_y,

                      band->pitch, mc_type);

    return 0;

}


static void continue_send(IPMIBmcExtern *ibe)

{

    if (ibe->outlen == 0) {

        goto check_reset;

    }

 send:

    ibe->outpos += qemu_chr_fe_write(ibe->chr, ibe->outbuf + ibe->outpos,

                                     ibe->outlen - ibe->outpos);

    if (ibe->outpos < ibe->outlen) {

        /* Not fully transmitted, try again in a 10ms */

        timer_mod_ns(ibe->extern_timer,

                     qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + 10000000);

    } else {

        /* Sent */

        ibe->outlen = 0;

        ibe->outpos = 0;

        if (!ibe->sending_cmd) {

            ibe->waiting_rsp = true;

        } else {

            ibe->sending_cmd = false;

        }

    check_reset:

        if (ibe->connected && ibe->send_reset) {

            /* Send the reset */

            ibe->outbuf[0] = VM_CMD_RESET;

            ibe->outbuf[1] = VM_CMD_CHAR;

            ibe->outlen = 2;

            ibe->outpos = 0;

            ibe->send_reset = false;

            ibe->sending_cmd = true;

            goto send;

        }

        if (ibe->waiting_rsp) {

            /* Make sure we get a response within 4 seconds. */

            timer_mod_ns(ibe->extern_timer,

                         qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + 4000000000ULL);

        }

    }

    return;

}


static void sdhci_do_adma(SDHCIState *s)

{

    unsigned int n, begin, length;

    const uint16_t block_size = s->blksize & 0x0fff;

    ADMADescr dscr;

    int i;

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

        s->admaerr &= ~SDHC_ADMAERR_LENGTH_MISMATCH;

        get_adma_description(s, &dscr);

        DPRINT_L2("ADMA loop: addr=" TARGET_FMT_plx ", len=%d, attr=%x\n",

                dscr.addr, dscr.length, dscr.attr);

        if ((dscr.attr & SDHC_ADMA_ATTR_VALID) == 0) {

            /* Indicate that error occurred in ST_FDS state */

            s->admaerr &= ~SDHC_ADMAERR_STATE_MASK;

            s->admaerr |= SDHC_ADMAERR_STATE_ST_FDS;

            /* Generate ADMA error interrupt */

            if (s->errintstsen & SDHC_EISEN_ADMAERR) {

                s->errintsts |= SDHC_EIS_ADMAERR;

                s->norintsts |= SDHC_NIS_ERR;

            }

            sdhci_update_irq(s);

            return;

        }

        length = dscr.length ? dscr.length : 65536;

        switch (dscr.attr & SDHC_ADMA_ATTR_ACT_MASK) {

        case SDHC_ADMA_ATTR_ACT_TRAN:  /* data transfer */

            if (s->trnmod & SDHC_TRNS_READ) {

                while (length) {

                    if (s->data_count == 0) {

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

                            s->fifo_buffer[n] = sdbus_read_data(&s->sdbus);

                        }

                    }

                    begin = s->data_count;

                    if ((length + begin) < block_size) {

                        s->data_count = length + begin;

                        length = 0;

                     } else {

                        s->data_count = block_size;

                        length -= block_size - begin;

                    }

                    dma_memory_write(&address_space_memory, dscr.addr,

                                     &s->fifo_buffer[begin],

                                     s->data_count - begin);

                    dscr.addr += s->data_count - begin;

                    if (s->data_count == block_size) {

                        s->data_count = 0;

                        if (s->trnmod & SDHC_TRNS_BLK_CNT_EN) {

                            s->blkcnt--;

                            if (s->blkcnt == 0) {

                                break;

                            }

                        }

                    }

                }

            } else {

                while (length) {

                    begin = s->data_count;

                    if ((length + begin) < block_size) {

                        s->data_count = length + begin;

                        length = 0;

                     } else {

                        s->data_count = block_size;

                        length -= block_size - begin;

                    }

                    dma_memory_read(&address_space_memory, dscr.addr,

                                    &s->fifo_buffer[begin],

                                    s->data_count - begin);

                    dscr.addr += s->data_count - begin;

                    if (s->data_count == block_size) {

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

                            sdbus_write_data(&s->sdbus, s->fifo_buffer[n]);

                        }

                        s->data_count = 0;

                        if (s->trnmod & SDHC_TRNS_BLK_CNT_EN) {

                            s->blkcnt--;

                            if (s->blkcnt == 0) {

                                break;

                            }

                        }

                    }

                }

            }

            s->admasysaddr += dscr.incr;

            break;

        case SDHC_ADMA_ATTR_ACT_LINK:   /* link to next descriptor table */

            s->admasysaddr = dscr.addr;

            DPRINT_L1("ADMA link: admasysaddr=0x%" PRIx64 "\n",

                      s->admasysaddr);

            break;

        default:

            s->admasysaddr += dscr.incr;

            break;

        }

        if (dscr.attr & SDHC_ADMA_ATTR_INT) {

            DPRINT_L1("ADMA interrupt: admasysaddr=0x%" PRIx64 "\n",

                      s->admasysaddr);

            if (s->norintstsen & SDHC_NISEN_DMA) {

                s->norintsts |= SDHC_NIS_DMA;

            }

            sdhci_update_irq(s);

        }

        /* ADMA transfer terminates if blkcnt == 0 or by END attribute */

        if (((s->trnmod & SDHC_TRNS_BLK_CNT_EN) &&

                    (s->blkcnt == 0)) || (dscr.attr & SDHC_ADMA_ATTR_END)) {

            DPRINT_L2("ADMA transfer completed\n");

            if (length || ((dscr.attr & SDHC_ADMA_ATTR_END) &&

                (s->trnmod & SDHC_TRNS_BLK_CNT_EN) &&

                s->blkcnt != 0)) {

                ERRPRINT("SD/MMC host ADMA length mismatch\n");

                s->admaerr |= SDHC_ADMAERR_LENGTH_MISMATCH |

                        SDHC_ADMAERR_STATE_ST_TFR;

                if (s->errintstsen & SDHC_EISEN_ADMAERR) {

                    ERRPRINT("Set ADMA error flag\n");

                    s->errintsts |= SDHC_EIS_ADMAERR;

                    s->norintsts |= SDHC_NIS_ERR;

                }

                sdhci_update_irq(s);

            }

            sdhci_end_transfer(s);

            return;

        }

    }

    /* we have unfinished business - reschedule to continue ADMA */

    timer_mod(s->transfer_timer,

                   qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + SDHC_TRANSFER_DELAY);

}


static int copy_sectors(BlockDriverState *bs, uint64_t start_sect,

                        uint64_t cluster_offset, int n_start, int n_end)

{

    BDRVQcowState *s = bs->opaque;

    int n, ret;

    void *buf;

    /*

     * If this is the last cluster and it is only partially used, we must only

     * copy until the end of the image, or bdrv_check_request will fail for the

     * bdrv_read/write calls below.

     */

    if (start_sect + n_end > bs->total_sectors) {

        n_end = bs->total_sectors - start_sect;

    }

    n = n_end - n_start;

    if (n <= 0) {

        return 0;

    }

    buf = qemu_blockalign(bs, n * BDRV_SECTOR_SIZE);

    BLKDBG_EVENT(bs->file, BLKDBG_COW_READ);

    ret = bdrv_read(bs, start_sect + n_start, buf, n);

    if (ret < 0) {

        goto out;

    }

    if (s->crypt_method) {

        qcow2_encrypt_sectors(s, start_sect + n_start,

                        buf, buf, n, 1,

                        &s->aes_encrypt_key);

    }

    BLKDBG_EVENT(bs->file, BLKDBG_COW_WRITE);

    ret = bdrv_write(bs->file, (cluster_offset >> 9) + n_start, buf, n);

    if (ret < 0) {

        goto out;

    }

    ret = 0;

out:

    qemu_vfree(buf);

    return ret;

}


void arm_cpu_do_transaction_failed(CPUState *cs, hwaddr physaddr,

                                   vaddr addr, unsigned size,

                                   MMUAccessType access_type,

                                   int mmu_idx, MemTxAttrs attrs,

                                   MemTxResult response, uintptr_t retaddr)

{

    ARMCPU *cpu = ARM_CPU(cs);

    ARMMMUFaultInfo fi = {};

    /* now we have a real cpu fault */

    cpu_restore_state(cs, retaddr);

    /* The EA bit in syndromes and fault status registers is an

     * IMPDEF classification of external aborts. ARM implementations

     * usually use this to indicate AXI bus Decode error (0) or

     * Slave error (1); in QEMU we follow that.

     */

    fi.ea = (response != MEMTX_DECODE_ERROR);

    fi.type = ARMFault_SyncExternal;

    deliver_fault(cpu, addr, access_type, mmu_idx, &fi);

}


static int truemotion1_decode_header(TrueMotion1Context *s)
{
    int i, ret;
    int width_shift = 0;
    int new_pix_fmt;
    struct frame_header header;
    uint8_t header_buffer[128] = { 0 };  /* logical maximum size of the header */
    const uint8_t *sel_vector_table;
    header.header_size = ((s->buf[0] >> 5) | (s->buf[0] << 3)) & 0x7f;
    if (s->buf[0] < 0x10)
    {
        av_log(s->avctx, AV_LOG_ERROR, "invalid header size (%d)\n", s->buf[0]);
    /* unscramble the header bytes with a XOR operation */
    for (i = 1; i < header.header_size; i++)
        header_buffer[i - 1] = s->buf[i] ^ s->buf[i + 1];
    header.compression = header_buffer[0];
    header.deltaset = header_buffer[1];
    header.vectable = header_buffer[2];
    header.ysize = AV_RL16(&header_buffer[3]);
    header.xsize = AV_RL16(&header_buffer[5]);
    header.checksum = AV_RL16(&header_buffer[7]);
    header.version = header_buffer[9];
    header.header_type = header_buffer[10];
    header.flags = header_buffer[11];
    header.control = header_buffer[12];
    /* Version 2 */
    if (header.version >= 2)
    {
        if (header.header_type > 3)
        {
            av_log(s->avctx, AV_LOG_ERROR, "invalid header type (%d)\n", header.header_type);
        } else if ((header.header_type == 2) || (header.header_type == 3)) {
            s->flags = header.flags;
            if (!(s->flags & FLAG_INTERFRAME))
                s->flags |= FLAG_KEYFRAME;
        } else
            s->flags = FLAG_KEYFRAME;
    } else /* Version 1 */
        s->flags = FLAG_KEYFRAME;
    if (s->flags & FLAG_SPRITE) {
        avpriv_request_sample(s->avctx, "Frame with sprite");
        /* FIXME header.width, height, xoffset and yoffset aren't initialized */
        return AVERROR_PATCHWELCOME;
    } else {
        s->w = header.xsize;
        s->h = header.ysize;
        if (header.header_type < 2) {
            if ((s->w < 213) && (s->h >= 176))
            {
                s->flags |= FLAG_INTERPOLATED;
                avpriv_request_sample(s->avctx, "Interpolated frame");
    if (header.compression >= 17) {
        av_log(s->avctx, AV_LOG_ERROR, "invalid compression type (%d)\n", header.compression);
    if ((header.deltaset != s->last_deltaset) ||
        (header.vectable != s->last_vectable))
        select_delta_tables(s, header.deltaset);
    if ((header.compression & 1) && header.header_type)
        sel_vector_table = pc_tbl2;
    else {
        if (header.vectable > 0 && header.vectable < 4)
            sel_vector_table = tables[header.vectable - 1];
        else {
            av_log(s->avctx, AV_LOG_ERROR, "invalid vector table id (%d)\n", header.vectable);
    if (compression_types[header.compression].algorithm == ALGO_RGB24H) {
        new_pix_fmt = AV_PIX_FMT_RGB32;
        width_shift = 1;
    } else
        new_pix_fmt = AV_PIX_FMT_RGB555; // RGB565 is supported as well
    s->w >>= width_shift;
    if (s->w != s->avctx->width || s->h != s->avctx->height ||
        new_pix_fmt != s->avctx->pix_fmt) {
        av_frame_unref(s->frame);
        s->avctx->sample_aspect_ratio = (AVRational){ 1 << width_shift, 1 };
        s->avctx->pix_fmt = new_pix_fmt;
        if ((ret = ff_set_dimensions(s->avctx, s->w, s->h)) < 0)
            return ret;
        av_fast_malloc(&s->vert_pred, &s->vert_pred_size, s->avctx->width * sizeof(unsigned int));
    /* There is 1 change bit per 4 pixels, so each change byte represents
     * 32 pixels; divide width by 4 to obtain the number of change bits and
     * then round up to the nearest byte. */
    s->mb_change_bits_row_size = ((s->avctx->width >> (2 - width_shift)) + 7) >> 3;
    if ((header.deltaset != s->last_deltaset) || (header.vectable != s->last_vectable))
    {
        if (compression_types[header.compression].algorithm == ALGO_RGB24H)
            gen_vector_table24(s, sel_vector_table);
        else
        if (s->avctx->pix_fmt == AV_PIX_FMT_RGB555)
            gen_vector_table15(s, sel_vector_table);
        else
            gen_vector_table16(s, sel_vector_table);
    /* set up pointers to the other key data chunks */
    s->mb_change_bits = s->buf + header.header_size;
    if (s->flags & FLAG_KEYFRAME) {
        /* no change bits specified for a keyframe; only index bytes */
        s->index_stream = s->mb_change_bits;
    } else {
        /* one change bit per 4x4 block */
        s->index_stream = s->mb_change_bits +
            (s->mb_change_bits_row_size * (s->avctx->height >> 2));
    s->index_stream_size = s->size - (s->index_stream - s->buf);
    s->last_deltaset = header.deltaset;
    s->last_vectable = header.vectable;
    s->compression = header.compression;
    s->block_width = compression_types[header.compression].block_width;
    s->block_height = compression_types[header.compression].block_height;
    s->block_type = compression_types[header.compression].block_type;
    if (s->avctx->debug & FF_DEBUG_PICT_INFO)
        av_log(s->avctx, AV_LOG_INFO, "tables: %d / %d c:%d %dx%d t:%d %s%s%s%s\n",
            s->last_deltaset, s->last_vectable, s->compression, s->block_width,
            s->block_height, s->block_type,
            s->flags & FLAG_KEYFRAME ? " KEY" : "",
            s->flags & FLAG_INTERFRAME ? " INTER" : "",
            s->flags & FLAG_SPRITE ? " SPRITE" : "",
            s->flags & FLAG_INTERPOLATED ? " INTERPOL" : "");
    return header.header_size;


static av_always_inline void RENAME(decode_line)(FFV1Context *s, int w,

                                                 TYPE *sample[2],

                                                 int plane_index, int bits)

{

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

    RangeCoder *const c   = &s->c;

    int x;

    int run_count = 0;

    int run_mode  = 0;

    int run_index = s->run_index;

    if (s->slice_coding_mode == 1) {

        int i;

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

            int v = 0;

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

                uint8_t state = 128;

                v += v + get_rac(c, &state);

            }

            sample[1][x] = v;

        }

        return;

    }

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

        int diff, context, sign;

        context = RENAME(get_context)(p, sample[1] + x, sample[0] + x, sample[1] + x);

        if (context < 0) {

            context = -context;

            sign    = 1;

        } else

            sign = 0;

        av_assert2(context < p->context_count);

        if (s->ac != AC_GOLOMB_RICE) {

            diff = get_symbol_inline(c, p->state[context], 1);

        } else {

            if (context == 0 && run_mode == 0)

                run_mode = 1;

            if (run_mode) {

                if (run_count == 0 && run_mode == 1) {

                    if (get_bits1(&s->gb)) {

                        run_count = 1 << ff_log2_run[run_index];

                        if (x + run_count <= w)

                            run_index++;

                    } else {

                        if (ff_log2_run[run_index])

                            run_count = get_bits(&s->gb, ff_log2_run[run_index]);

                        else

                            run_count = 0;

                        if (run_index)

                            run_index--;

                        run_mode = 2;

                    }

                }

                run_count--;

                if (run_count < 0) {

                    run_mode  = 0;

                    run_count = 0;

                    diff      = get_vlc_symbol(&s->gb, &p->vlc_state[context],

                                               bits);

                    if (diff >= 0)

                        diff++;

                } else

                    diff = 0;

            } else

                diff = get_vlc_symbol(&s->gb, &p->vlc_state[context], bits);

            ff_dlog(s->avctx, "count:%d index:%d, mode:%d, x:%d pos:%d\n",

                    run_count, run_index, run_mode, x, get_bits_count(&s->gb));

        }

        if (sign)

            diff = -diff;

        sample[1][x] = av_mod_uintp2(RENAME(predict)(sample[1] + x, sample[0] + x) + (SUINT)diff, bits);

    }

    s->run_index = run_index;

}


static int bochs_open(BlockDriverState *bs, int flags)

{

    BDRVBochsState *s = bs->opaque;

    int i;

    struct bochs_header bochs;

    struct bochs_header_v1 header_v1;

    bs->read_only = 1; // no write support yet

    if (bdrv_pread(bs->file, 0, &bochs, sizeof(bochs)) != sizeof(bochs)) {

        goto fail;

    }

    if (strcmp(bochs.magic, HEADER_MAGIC) ||

        strcmp(bochs.type, REDOLOG_TYPE) ||

        strcmp(bochs.subtype, GROWING_TYPE) ||

	((le32_to_cpu(bochs.version) != HEADER_VERSION) &&

	(le32_to_cpu(bochs.version) != HEADER_V1))) {

        return -EMEDIUMTYPE;

    }

    if (le32_to_cpu(bochs.version) == HEADER_V1) {

      memcpy(&header_v1, &bochs, sizeof(bochs));

      bs->total_sectors = le64_to_cpu(header_v1.extra.redolog.disk) / 512;

    } else {

      bs->total_sectors = le64_to_cpu(bochs.extra.redolog.disk) / 512;

    }

    s->catalog_size = le32_to_cpu(bochs.extra.redolog.catalog);

    s->catalog_bitmap = g_malloc(s->catalog_size * 4);

    if (bdrv_pread(bs->file, le32_to_cpu(bochs.header), s->catalog_bitmap,

                   s->catalog_size * 4) != s->catalog_size * 4)

	goto fail;

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

	le32_to_cpus(&s->catalog_bitmap[i]);

    s->data_offset = le32_to_cpu(bochs.header) + (s->catalog_size * 4);

    s->bitmap_blocks = 1 + (le32_to_cpu(bochs.extra.redolog.bitmap) - 1) / 512;

    s->extent_blocks = 1 + (le32_to_cpu(bochs.extra.redolog.extent) - 1) / 512;

    s->extent_size = le32_to_cpu(bochs.extra.redolog.extent);

    qemu_co_mutex_init(&s->lock);

    return 0;

 fail:

    return -1;

}


static void set_alarm (m48t59_t *NVRAM, struct tm *tm)

{

    NVRAM->alarm = mktime(tm);

    if (NVRAM->alrm_timer != NULL) {

        qemu_del_timer(NVRAM->alrm_timer);

	NVRAM->alrm_timer = NULL;

    }

    if (NVRAM->alarm - time(NULL) > 0)

	qemu_mod_timer(NVRAM->alrm_timer, NVRAM->alarm * 1000);

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    PCIHostBridgeClass *hc = PCI_HOST_BRIDGE_CLASS(klass);

    hc->root_bus_path = i440fx_pcihost_root_bus_path;

    dc->realize = i440fx_pcihost_realize;

    dc->fw_name = "pci";

    dc->props = i440fx_props;

}


static void init_parse_context(OptionParseContext *octx,

                               const OptionGroupDef *groups, int nb_groups)

{

    static const OptionGroupDef global_group = { "global" };

    int i;

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

    octx->nb_groups = nb_groups;

    octx->groups    = av_mallocz(sizeof(*octx->groups) * octx->nb_groups);

    if (!octx->groups)

        exit(1);

    for (i = 0; i < octx->nb_groups; i++)

        octx->groups[i].group_def = &groups[i];

    octx->global_opts.group_def = &global_group;

    octx->global_opts.arg       = "";

    init_opts();

}


int ff_mov_read_chan(AVFormatContext *s, AVStream *st, int64_t size)

{

    AVIOContext *pb = s->pb;

    uint32_t layout_tag, bitmap, num_descr, label_mask;

    int i;

    if (size < 12)

        return AVERROR_INVALIDDATA;

    layout_tag = avio_rb32(pb);

    bitmap     = avio_rb32(pb);

    num_descr  = avio_rb32(pb);

    av_dlog(s, "chan: layout=%u bitmap=%u num_descr=%u\n",

            layout_tag, bitmap, num_descr);

    if (size < 12ULL + num_descr * 20ULL)

        return 0;

    label_mask = 0;

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

        uint32_t label;

        label     = avio_rb32(pb);          // mChannelLabel

        avio_rb32(pb);                      // mChannelFlags

        avio_rl32(pb);                      // mCoordinates[0]

        avio_rl32(pb);                      // mCoordinates[1]

        avio_rl32(pb);                      // mCoordinates[2]

        if (layout_tag == 0) {

            uint32_t mask_incr = mov_get_channel_label(label);

            if (mask_incr == 0) {

                label_mask = 0;

                break;

            }

            label_mask |= mask_incr;

        }

    }

    if (layout_tag == 0)

            st->codec->channel_layout = label_mask;

    else

        st->codec->channel_layout = ff_mov_get_channel_layout(layout_tag, bitmap);

    return 0;

}


void microblaze_load_kernel(MicroBlazeCPU *cpu, hwaddr ddr_base,

                            uint32_t ramsize,

                            const char *initrd_filename,

                            const char *dtb_filename,

                            void (*machine_cpu_reset)(MicroBlazeCPU *))

{

    QemuOpts *machine_opts;

    const char *kernel_filename;

    const char *kernel_cmdline;

    const char *dtb_arg;

    machine_opts = qemu_get_machine_opts();

    kernel_filename = qemu_opt_get(machine_opts, "kernel");

    kernel_cmdline = qemu_opt_get(machine_opts, "append");

    dtb_arg = qemu_opt_get(machine_opts, "dtb");

    if (dtb_arg) { /* Preference a -dtb argument */

        dtb_filename = dtb_arg;

    } else { /* default to pcbios dtb as passed by machine_init */

        dtb_filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, dtb_filename);

    }

    boot_info.machine_cpu_reset = machine_cpu_reset;

    qemu_register_reset(main_cpu_reset, cpu);

    if (kernel_filename) {

        int kernel_size;

        uint64_t entry, low, high;

        uint32_t base32;

        int big_endian = 0;

#ifdef TARGET_WORDS_BIGENDIAN

        big_endian = 1;

#endif

        /* Boots a kernel elf binary.  */

        kernel_size = load_elf(kernel_filename, NULL, NULL,

                               &entry, &low, &high,

                               big_endian, ELF_MACHINE, 0);

        base32 = entry;

        if (base32 == 0xc0000000) {

            kernel_size = load_elf(kernel_filename, translate_kernel_address,

                                   NULL, &entry, NULL, NULL,

                                   big_endian, ELF_MACHINE, 0);

        }

        /* Always boot into physical ram.  */

        boot_info.bootstrap_pc = ddr_base + (entry & 0x0fffffff);

        /* If it wasn't an ELF image, try an u-boot image.  */

        if (kernel_size < 0) {

            hwaddr uentry, loadaddr;

            kernel_size = load_uimage(kernel_filename, &uentry, &loadaddr, 0);

            boot_info.bootstrap_pc = uentry;

            high = (loadaddr + kernel_size + 3) & ~3;

        }

        /* Not an ELF image nor an u-boot image, try a RAW image.  */

        if (kernel_size < 0) {

            kernel_size = load_image_targphys(kernel_filename, ddr_base,

                                              ram_size);

            boot_info.bootstrap_pc = ddr_base;

            high = (ddr_base + kernel_size + 3) & ~3;

        }

        if (initrd_filename) {

            int initrd_size;

            uint32_t initrd_offset;

            high = ROUND_UP(high + kernel_size, 4);

            boot_info.initrd_start = high;

            initrd_offset = boot_info.initrd_start - ddr_base;

            initrd_size = load_ramdisk(initrd_filename,

                                       boot_info.initrd_start,

                                       ram_size - initrd_offset);

            if (initrd_size < 0) {

                initrd_size = load_image_targphys(initrd_filename,

                                                  boot_info.initrd_start,

                                                  ram_size - initrd_offset);

            }

            if (initrd_size < 0) {

                error_report("qemu: could not load initrd '%s'\n",

                             initrd_filename);

                exit(EXIT_FAILURE);

            }

            boot_info.initrd_end = boot_info.initrd_start + initrd_size;

            high = ROUND_UP(high + initrd_size, 4);

        }

        boot_info.cmdline = high + 4096;

        if (kernel_cmdline && strlen(kernel_cmdline)) {

            pstrcpy_targphys("cmdline", boot_info.cmdline, 256, kernel_cmdline);

        }

        /* Provide a device-tree.  */

        boot_info.fdt = boot_info.cmdline + 4096;

        microblaze_load_dtb(boot_info.fdt, ram_size,

                            boot_info.initrd_start,

                            boot_info.initrd_end,

                            kernel_cmdline,

                            dtb_filename);

    }

}


static int kvm_ppc_register_host_cpu_type(void)

{

    TypeInfo type_info = {

        .name = TYPE_HOST_POWERPC_CPU,

        .class_init = kvmppc_host_cpu_class_init,

    };

    PowerPCCPUClass *pvr_pcc;

    DeviceClass *dc;

    int i;

    pvr_pcc = kvm_ppc_get_host_cpu_class();

    if (pvr_pcc == NULL) {

        return -1;

    }

    type_info.parent = object_class_get_name(OBJECT_CLASS(pvr_pcc));

    type_register(&type_info);

#if defined(TARGET_PPC64)

    type_info.name = g_strdup_printf("%s-"TYPE_SPAPR_CPU_CORE, "host");

    type_info.parent = TYPE_SPAPR_CPU_CORE,

    type_info.instance_size = sizeof(sPAPRCPUCore);

    type_info.instance_init = NULL;

    type_info.class_init = spapr_cpu_core_class_init;

    type_info.class_data = (void *) "host";

    type_register(&type_info);

    g_free((void *)type_info.name);

#endif

    /*

     * Update generic CPU family class alias (e.g. on a POWER8NVL host,

     * we want "POWER8" to be a "family" alias that points to the current

     * host CPU type, too)

     */

    dc = DEVICE_CLASS(ppc_cpu_get_family_class(pvr_pcc));

    for (i = 0; ppc_cpu_aliases[i].alias != NULL; i++) {

        if (strcmp(ppc_cpu_aliases[i].alias, dc->desc) == 0) {

            ObjectClass *oc = OBJECT_CLASS(pvr_pcc);

            char *suffix;

            ppc_cpu_aliases[i].model = g_strdup(object_class_get_name(oc));

            suffix = strstr(ppc_cpu_aliases[i].model, "-"TYPE_POWERPC_CPU);

            if (suffix) {

                *suffix = 0;

            }

            ppc_cpu_aliases[i].oc = oc;

            break;

        }

    }

    return 0;

}


static int av_encode(AVFormatContext **output_files,
                     int nb_output_files,
                     AVFormatContext **input_files,
                     int nb_input_files,
                     AVStreamMap *stream_maps, int nb_stream_maps)
{
    int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0, pts_set;
    AVFormatContext *is, *os;
    AVCodecContext *codec, *icodec;
    AVOutputStream *ost, **ost_table = NULL;
    AVInputStream *ist, **ist_table = NULL;
    AVInputFile *file_table;
    AVFormatContext *stream_no_data;
    int key;
    file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
    if (!file_table)
        goto fail;
    /* input stream init */
    j = 0;
    for(i=0;i<nb_input_files;i++) {
        is = input_files[i];
        file_table[i].ist_index = j;
        file_table[i].nb_streams = is->nb_streams;
        j += is->nb_streams;
    nb_istreams = j;
    ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
    if (!ist_table)
        goto fail;
    for(i=0;i<nb_istreams;i++) {
        ist = av_mallocz(sizeof(AVInputStream));
        if (!ist)
            goto fail;
        ist_table[i] = ist;
    j = 0;
    for(i=0;i<nb_input_files;i++) {
        is = input_files[i];
        for(k=0;k<is->nb_streams;k++) {
            ist = ist_table[j++];
            ist->st = is->streams[k];
            ist->file_index = i;
            ist->index = k;
            ist->discard = 1; /* the stream is discarded by default
                                 (changed later) */
            if (ist->st->codec.rate_emu) {
                ist->start = av_gettime();
                ist->frame = 0;
    /* output stream init */
    nb_ostreams = 0;
    for(i=0;i<nb_output_files;i++) {
        os = output_files[i];
        nb_ostreams += os->nb_streams;
    if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
        fprintf(stderr, "Number of stream maps must match number of output streams\n");
    /* Sanity check the mapping args -- do the input files & streams exist? */
    for(i=0;i<nb_stream_maps;i++) {
        int fi = stream_maps[i].file_index;
        int si = stream_maps[i].stream_index;
        if (fi < 0 || fi > nb_input_files - 1 ||
            si < 0 || si > file_table[fi].nb_streams - 1) {
            fprintf(stderr,"Could not find input stream #%d.%d\n", fi, si);
    ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
    if (!ost_table)
        goto fail;
    for(i=0;i<nb_ostreams;i++) {
        ost = av_mallocz(sizeof(AVOutputStream));
        if (!ost)
            goto fail;
        ost_table[i] = ost;
    n = 0;
    for(k=0;k<nb_output_files;k++) {
        os = output_files[k];
        for(i=0;i<os->nb_streams;i++) {
            int found;
            ost = ost_table[n++];
            ost->file_index = k;
            ost->index = i;
            ost->st = os->streams[i];
            if (nb_stream_maps > 0) {
                ost->source_index = file_table[stream_maps[n-1].file_index].ist_index +
                    stream_maps[n-1].stream_index;
            } else {
                /* get corresponding input stream index : we select the first one with the right type */
                found = 0;
                for(j=0;j<nb_istreams;j++) {
                    ist = ist_table[j];
                    if (ist->discard &&
                        ist->st->codec.codec_type == ost->st->codec.codec_type) {
                        ost->source_index = j;
                        found = 1;
                if (!found) {
                    /* try again and reuse existing stream */
                    for(j=0;j<nb_istreams;j++) {
                        ist = ist_table[j];
                        if (ist->st->codec.codec_type == ost->st->codec.codec_type) {
                            ost->source_index = j;
                            found = 1;
                    if (!found) {
                        fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
            ist = ist_table[ost->source_index];
            ist->discard = 0;
    /* for each output stream, we compute the right encoding parameters */
    for(i=0;i<nb_ostreams;i++) {
        ost = ost_table[i];
        ist = ist_table[ost->source_index];
        codec = &ost->st->codec;
        icodec = &ist->st->codec;
        if (ost->st->stream_copy) {
            /* if stream_copy is selected, no need to decode or encode */
            codec->codec_id = icodec->codec_id;
            codec->codec_type = icodec->codec_type;
            codec->codec_tag = icodec->codec_tag;
            codec->bit_rate = icodec->bit_rate;
            switch(codec->codec_type) {
            case CODEC_TYPE_AUDIO:
                codec->sample_rate = icodec->sample_rate;
                codec->channels = icodec->channels;
                break;
            case CODEC_TYPE_VIDEO:
                codec->frame_rate = icodec->frame_rate;
                codec->frame_rate_base = icodec->frame_rate_base;
                codec->width = icodec->width;
                codec->height = icodec->height;
                break;
            default:
                av_abort();
        } else {
            switch(codec->codec_type) {
            case CODEC_TYPE_AUDIO:
                if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
                    goto fail;
                if (codec->channels == icodec->channels &&
                    codec->sample_rate == icodec->sample_rate) {
                    ost->audio_resample = 0;
                } else {
                    if (codec->channels != icodec->channels &&
                        icodec->codec_id == CODEC_ID_AC3) {
                        /* Special case for 5:1 AC3 input */
                        /* and mono or stereo output      */
                        /* Request specific number of channels */
                        icodec->channels = codec->channels;
                        if (codec->sample_rate == icodec->sample_rate)
                            ost->audio_resample = 0;
                        else {
                            ost->audio_resample = 1;
                            ost->resample = audio_resample_init(codec->channels, icodec->channels,
                                                        codec->sample_rate,
                                                        icodec->sample_rate);
                        /* Request specific number of channels */
                        icodec->channels = codec->channels;
                    } else {
                        ost->audio_resample = 1;
                        ost->resample = audio_resample_init(codec->channels, icodec->channels,
                                                        codec->sample_rate,
                                                        icodec->sample_rate);
                ist->decoding_needed = 1;
                ost->encoding_needed = 1;
                break;
            case CODEC_TYPE_VIDEO:
                if (codec->width == icodec->width &&
                    codec->height == icodec->height &&
                    frame_topBand == 0 &&
                    frame_bottomBand == 0 &&
                    frame_leftBand == 0 &&
                    frame_rightBand == 0)
                {
                    ost->video_resample = 0;
                    ost->video_crop = 0;
                } else if ((codec->width == icodec->width -
                                (frame_leftBand + frame_rightBand)) &&
                        (codec->height == icodec->height -
                                (frame_topBand  + frame_bottomBand)))
                {
                    ost->video_resample = 0;
                    ost->video_crop = 1;
                    ost->topBand = frame_topBand;
                    ost->leftBand = frame_leftBand;
                } else {
                    uint8_t *buf;
                    ost->video_resample = 1;
                    ost->video_crop = 0; // cropping is handled as part of resample
                    buf = av_malloc((codec->width * codec->height * 3) / 2);
                    if (!buf)
                        goto fail;
                    ost->pict_tmp.data[0] = buf;
                    ost->pict_tmp.data[1] = ost->pict_tmp.data[0] + (codec->width * codec->height);
                    ost->pict_tmp.data[2] = ost->pict_tmp.data[1] + (codec->width * codec->height) / 4;
                    ost->pict_tmp.linesize[0] = codec->width;
                    ost->pict_tmp.linesize[1] = codec->width / 2;
                    ost->pict_tmp.linesize[2] = codec->width / 2;
                    ost->img_resample_ctx = img_resample_full_init(
                                      ost->st->codec.width, ost->st->codec.height,
                                      ist->st->codec.width, ist->st->codec.height,
                                      frame_topBand, frame_bottomBand,
                                      frame_leftBand, frame_rightBand);
                ost->encoding_needed = 1;
                ist->decoding_needed = 1;
                break;
            default:
                av_abort();
            /* two pass mode */
            if (ost->encoding_needed &&
                (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
                char logfilename[1024];
                FILE *f;
                int size;
                char *logbuffer;
                snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
                         pass_logfilename ?
                         pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
                if (codec->flags & CODEC_FLAG_PASS1) {
                    f = fopen(logfilename, "w");
                    if (!f) {
                        perror(logfilename);
                    ost->logfile = f;
                } else {
                    /* read the log file */
                    f = fopen(logfilename, "r");
                    if (!f) {
                        perror(logfilename);
                    fseek(f, 0, SEEK_END);
                    size = ftell(f);
                    fseek(f, 0, SEEK_SET);
                    logbuffer = av_malloc(size + 1);
                    if (!logbuffer) {
                        fprintf(stderr, "Could not allocate log buffer\n");
                    fread(logbuffer, 1, size, f);
                    fclose(f);
                    logbuffer[size] = '\0';
                    codec->stats_in = logbuffer;
    /* dump the file output parameters - cannot be done before in case
       of stream copy */
    for(i=0;i<nb_output_files;i++) {
        dump_format(output_files[i], i, output_files[i]->filename, 1);
    /* dump the stream mapping */
    fprintf(stderr, "Stream mapping:\n");
    for(i=0;i<nb_ostreams;i++) {
        ost = ost_table[i];
        fprintf(stderr, "  Stream #%d.%d -> #%d.%d\n",
                ist_table[ost->source_index]->file_index,
                ist_table[ost->source_index]->index,
                ost->file_index,
                ost->index);
    /* open each encoder */
    for(i=0;i<nb_ostreams;i++) {
        ost = ost_table[i];
        if (ost->encoding_needed) {
            AVCodec *codec;
            codec = avcodec_find_encoder(ost->st->codec.codec_id);
            if (!codec) {
                fprintf(stderr, "Unsupported codec for output stream #%d.%d\n",
            if (avcodec_open(&ost->st->codec, codec) < 0) {
                fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n",
    /* open each decoder */
    for(i=0;i<nb_istreams;i++) {
        ist = ist_table[i];
        if (ist->decoding_needed) {
            AVCodec *codec;
            codec = avcodec_find_decoder(ist->st->codec.codec_id);
            if (!codec) {
                fprintf(stderr, "Unsupported codec (id=%d) for input stream #%d.%d\n",
                        ist->st->codec.codec_id, ist->file_index, ist->index);
            if (avcodec_open(&ist->st->codec, codec) < 0) {
                fprintf(stderr, "Error while opening codec for input stream #%d.%d\n",
                        ist->file_index, ist->index);
            //if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO)
            //    ist->st->codec.flags |= CODEC_FLAG_REPEAT_FIELD;
            ist->frame_decoded = 1;
    /* init pts */
    for(i=0;i<nb_istreams;i++) {
        ist = ist_table[i];
    /* compute buffer size max (should use a complete heuristic) */
    for(i=0;i<nb_input_files;i++) {
        file_table[i].buffer_size_max = 2048;
    /* open files and write file headers */
    for(i=0;i<nb_output_files;i++) {
        os = output_files[i];
        if (av_write_header(os) < 0) {
            fprintf(stderr, "Could not write header for output file #%d (incorrect codec paramters ?)\n", i);
            ret = -EINVAL;
            goto fail;
#ifndef CONFIG_WIN32
    if (!do_play) {
        fprintf(stderr, "Press [q] to stop encoding\n");
    } else {
        fprintf(stderr, "Press [q] to stop playing\n");
#endif
    term_init();
    stream_no_data = 0;
    key = -1;
    for(;;) {
        int file_index, ist_index;
        AVPacket pkt;
        uint8_t *ptr;
        int len;
        uint8_t *data_buf;
        int data_size, got_picture;
        AVPicture picture;
        short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
        void *buffer_to_free;
        double pts_min;
    redo:
        /* if 'q' pressed, exits */
        if (key) {
            /* read_key() returns 0 on EOF */
            key = read_key();
            if (key == 'q')
                break;
        /* select the stream that we must read now by looking at the
           smallest output pts */
        file_index = -1;
        pts_min = 1e10;
        for(i=0;i<nb_ostreams;i++) {
            double pts;
            ost = ost_table[i];
            os = output_files[ost->file_index];
            ist = ist_table[ost->source_index];
            pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
            if (!file_table[ist->file_index].eof_reached &&
                pts < pts_min) {
                pts_min = pts;
                file_index = ist->file_index;
        /* if none, if is finished */
        if (file_index < 0) {
            break;
        /* finish if recording time exhausted */
        if (recording_time > 0 && pts_min >= (recording_time / 1000000.0))
            break;
        /* read a packet from it and output it in the fifo */
        is = input_files[file_index];
        if (av_read_packet(is, &pkt) < 0) {
            file_table[file_index].eof_reached = 1;
            continue;
        if (!pkt.size) {
            stream_no_data = is;
        } else {
            stream_no_data = 0;
        if (do_hex_dump) {
            printf("stream #%d, size=%d:\n", pkt.stream_index, pkt.size);
            av_hex_dump(pkt.data, pkt.size);
        /* the following test is needed in case new streams appear
           dynamically in stream : we ignore them */
        if (pkt.stream_index >= file_table[file_index].nb_streams)
            goto discard_packet;
        ist_index = file_table[file_index].ist_index + pkt.stream_index;
        ist = ist_table[ist_index];
        if (ist->discard)
            goto discard_packet;
        // printf("read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);
        len = pkt.size;
        ptr = pkt.data;
        pts_set = 0;
        while (len > 0) {
            int64_t ipts;
            ipts = AV_NOPTS_VALUE;
            /* decode the packet if needed */
            data_buf = NULL; /* fail safe */
            data_size = 0;
            if (ist->decoding_needed) {
                /* NOTE1: we only take into account the PTS if a new
                   frame has begun (MPEG semantics) */
                /* NOTE2: even if the fraction is not initialized,
                   av_frac_set can be used to set the integer part */
                if (ist->frame_decoded &&
                    pkt.pts != AV_NOPTS_VALUE &&
                    !pts_set) {
                    ipts = pkt.pts;
                    ist->frame_decoded = 0;
                    pts_set = 1;
                switch(ist->st->codec.codec_type) {
                case CODEC_TYPE_AUDIO:
                    /* XXX: could avoid copy if PCM 16 bits with same
                       endianness as CPU */
                    ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,
                                               ptr, len);
                    if (ret < 0)
                        goto fail_decode;
                    /* Some bug in mpeg audio decoder gives */
                    /* data_size < 0, it seems they are overflows */
                    if (data_size <= 0) {
                        /* no audio frame */
                        ptr += ret;
                        len -= ret;
                        continue;
                    data_buf = (uint8_t *)samples;
                    break;
                case CODEC_TYPE_VIDEO:
                    {
                        AVFrame big_picture;
                        data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;
                        ret = avcodec_decode_video(&ist->st->codec,
                                                   &big_picture, &got_picture, ptr, len);
                        picture= *(AVPicture*)&big_picture;
                        ist->st->quality= big_picture.quality;
                        if (ret < 0) {
                        fail_decode:
                            fprintf(stderr, "Error while decoding stream #%d.%d\n",
                                    ist->file_index, ist->index);
                            av_free_packet(&pkt);
                            goto redo;
                        if (!got_picture) {
                            /* no picture yet */
                            ptr += ret;
                            len -= ret;
                            continue;
                    break;
                default:
                    goto fail_decode;
            } else {
                data_buf = ptr;
                data_size = len;
                ret = len;
            ptr += ret;
            len -= ret;
            buffer_to_free = 0;
            if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO) {
                pre_process_video_frame(ist, &picture, &buffer_to_free);
            ist->frame_decoded = 1;
            /* frame rate emulation */
            if (ist->st->codec.rate_emu) {
                int64_t pts = av_rescale((int64_t) ist->frame * ist->st->codec.frame_rate_base, 1000000, ist->st->codec.frame_rate);
                int64_t now = av_gettime() - ist->start;
                if (pts > now)
                    usleep(pts - now);
                ist->frame++;
#if 0
            /* mpeg PTS deordering : if it is a P or I frame, the PTS
               is the one of the next displayed one */
            /* XXX: add mpeg4 too ? */
            if (ist->st->codec.codec_id == CODEC_ID_MPEG1VIDEO) {
                if (ist->st->codec.pict_type != B_TYPE) {
                    int64_t tmp;
                    tmp = ist->last_ip_pts;
                    ist->last_ip_pts  = ist->frac_pts.val;
                    ist->frac_pts.val = tmp;
#endif
            /* transcode raw format, encode packets and output them */
            for(i=0;i<nb_ostreams;i++) {
                int frame_size;
                ost = ost_table[i];
                if (ost->source_index == ist_index) {
                    os = output_files[ost->file_index];
                    if (ipts != AV_NOPTS_VALUE) {
#if 0
                        printf("%d: got pts=%f %f\n",
                               i, pkt.pts / 90000.0,
                               (ipts - ost->st->pts.val) / 90000.0);
#endif
                        /* set the input output pts pairs */
                        ost->sync_ipts = (double)ipts * is->pts_num /
                            is->pts_den;
                        /* XXX: take into account the various fifos,
                           in particular for audio */
                        ost->sync_opts = ost->st->pts.val;
                        //printf("ipts=%lld sync_ipts=%f sync_opts=%lld pts.val=%lld pkt.pts=%lld\n", ipts, ost->sync_ipts, ost->sync_opts, ost->st->pts.val, pkt.pts);
                    } else {
                        //printf("pts.val=%lld\n", ost->st->pts.val);
                        ost->sync_ipts = AV_NOPTS_VALUE;
                    if (ost->encoding_needed) {
                        switch(ost->st->codec.codec_type) {
                        case CODEC_TYPE_AUDIO:
                            do_audio_out(os, ost, ist, data_buf, data_size);
                            break;
                        case CODEC_TYPE_VIDEO:
                            /* find an audio stream for synchro */
                            {
                                int i;
                                AVOutputStream *audio_sync, *ost1;
                                audio_sync = NULL;
                                for(i=0;i<nb_ostreams;i++) {
                                    ost1 = ost_table[i];
                                    if (ost1->file_index == ost->file_index &&
                                        ost1->st->codec.codec_type == CODEC_TYPE_AUDIO) {
                                        audio_sync = ost1;
                                        break;
                                do_video_out(os, ost, ist, &picture, &frame_size, audio_sync);
                                if (do_vstats && frame_size)
                                    do_video_stats(os, ost, frame_size);
                            break;
                        default:
                            av_abort();
                    } else {
                        AVFrame avframe;
                        /* no reencoding needed : output the packet directly */
                        /* force the input stream PTS */
                        memset(&avframe, 0, sizeof(AVFrame));
                        ost->st->codec.coded_frame= &avframe;
			avframe.key_frame = pkt.flags & PKT_FLAG_KEY;
                        av_write_frame(os, ost->index, data_buf, data_size);
			ost->st->codec.frame_number++;
			ost->frame_number++;
            av_free(buffer_to_free);
            ipts = AV_NOPTS_VALUE;
    discard_packet:
        av_free_packet(&pkt);
        /* dump report by using the output first video and audio streams */
        print_report(output_files, ost_table, nb_ostreams, 0);
    term_exit();
    /* dump report by using the first video and audio streams */
    print_report(output_files, ost_table, nb_ostreams, 1);
    /* close each encoder */
    for(i=0;i<nb_ostreams;i++) {
        ost = ost_table[i];
        if (ost->encoding_needed) {
            av_freep(&ost->st->codec.stats_in);
            avcodec_close(&ost->st->codec);
    /* close each decoder */
    for(i=0;i<nb_istreams;i++) {
        ist = ist_table[i];
        if (ist->decoding_needed) {
            avcodec_close(&ist->st->codec);
    /* write the trailer if needed and close file */
    for(i=0;i<nb_output_files;i++) {
        os = output_files[i];
        av_write_trailer(os);
    /* finished ! */
    ret = 0;
 fail1:
    av_free(file_table);
    if (ist_table) {
        for(i=0;i<nb_istreams;i++) {
            ist = ist_table[i];
            av_free(ist);
        av_free(ist_table);
    if (ost_table) {
        for(i=0;i<nb_ostreams;i++) {
            ost = ost_table[i];
            if (ost) {
                if (ost->logfile) {
                    fclose(ost->logfile);
                    ost->logfile = NULL;
                fifo_free(&ost->fifo); /* works even if fifo is not
                                          initialized but set to zero */
                av_free(ost->pict_tmp.data[0]);
                if (ost->video_resample)
                    img_resample_close(ost->img_resample_ctx);
                if (ost->audio_resample)
                    audio_resample_close(ost->resample);
                av_free(ost);
        av_free(ost_table);
    return ret;
 fail:
    ret = -ENOMEM;
    goto fail1;


static void RENAME(mix8to2)(SAMPLE **out, const SAMPLE **in, COEFF *coeffp, integer len){

    int i;

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

        INTER t = in[2][i]*coeffp[0*8+2] + in[3][i]*coeffp[0*8+3];

        out[0][i] = R(t + in[0][i]*(INTER)coeffp[0*8+0] + in[4][i]*(INTER)coeffp[0*8+4] + in[6][i]*(INTER)coeffp[0*8+6]);

        out[1][i] = R(t + in[1][i]*(INTER)coeffp[1*8+1] + in[5][i]*(INTER)coeffp[1*8+5] + in[7][i]*(INTER)coeffp[1*8+7]);

    }

}