int ff_mjpeg_decode_frame(AVCodecContext *avctx, void *data, int *got_frame,

                          AVPacket *avpkt)

{

    AVFrame     *frame = data;

    const uint8_t *buf = avpkt->data;

    int buf_size       = avpkt->size;

    MJpegDecodeContext *s = avctx->priv_data;

    const uint8_t *buf_end, *buf_ptr;

    const uint8_t *unescaped_buf_ptr;

    int hshift, vshift;

    int unescaped_buf_size;

    int start_code;

    int i, index;

    int ret = 0;

    int is16bit;

    av_dict_free(&s->exif_metadata);

    av_freep(&s->stereo3d);

    s->adobe_transform = -1;

    buf_ptr = buf;

    buf_end = buf + buf_size;

    while (buf_ptr < buf_end) {

        /* find start next marker */

        start_code = ff_mjpeg_find_marker(s, &buf_ptr, buf_end,

                                          &unescaped_buf_ptr,

                                          &unescaped_buf_size);

        /* EOF */

        if (start_code < 0) {

            break;

        } else if (unescaped_buf_size > INT_MAX / 8) {

            av_log(avctx, AV_LOG_ERROR,

                   "MJPEG packet 0x%x too big (%d/%d), corrupt data?\n",

                   start_code, unescaped_buf_size, buf_size);

            return AVERROR_INVALIDDATA;

        }

        av_log(avctx, AV_LOG_DEBUG, "marker=%x avail_size_in_buf=%"PTRDIFF_SPECIFIER"\n",

               start_code, buf_end - buf_ptr);

        ret = init_get_bits8(&s->gb, unescaped_buf_ptr, unescaped_buf_size);

        if (ret < 0) {

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

            goto fail;

        }

        s->start_code = start_code;

        if (s->avctx->debug & FF_DEBUG_STARTCODE)

            av_log(avctx, AV_LOG_DEBUG, "startcode: %X\n", start_code);

        /* process markers */

        if (start_code >= 0xd0 && start_code <= 0xd7)

            av_log(avctx, AV_LOG_DEBUG,

                   "restart marker: %d\n", start_code & 0x0f);

            /* APP fields */

        else if (start_code >= APP0 && start_code <= APP15)

            mjpeg_decode_app(s);

            /* Comment */

        else if (start_code == COM)

            mjpeg_decode_com(s);

        ret = -1;

        if (!CONFIG_JPEGLS_DECODER &&

            (start_code == SOF48 || start_code == LSE)) {

            av_log(avctx, AV_LOG_ERROR, "JPEG-LS support not enabled.\n");

            return AVERROR(ENOSYS);

        }

        if (avctx->skip_frame == AVDISCARD_ALL) {

            switch(start_code) {

            case SOF0:

            case SOF1:

            case SOF2:

            case SOF3:

            case SOF48:

            case SOI:

            case SOS:

            case EOI:

                break;

            default:

                goto skip;

            }

        }

        switch (start_code) {

        case SOI:

            s->restart_interval = 0;

            s->restart_count    = 0;

            /* nothing to do on SOI */

            break;

        case DQT:

            ff_mjpeg_decode_dqt(s);

            break;

        case DHT:

            if ((ret = ff_mjpeg_decode_dht(s)) < 0) {

                av_log(avctx, AV_LOG_ERROR, "huffman table decode error\n");

                goto fail;

            }

            break;

        case SOF0:

        case SOF1:

            s->lossless    = 0;

            s->ls          = 0;

            s->progressive = 0;

            if ((ret = ff_mjpeg_decode_sof(s)) < 0)

                goto fail;

            break;

        case SOF2:

            s->lossless    = 0;

            s->ls          = 0;

            s->progressive = 1;

            if ((ret = ff_mjpeg_decode_sof(s)) < 0)

                goto fail;

            break;

        case SOF3:

            s->avctx->properties |= FF_CODEC_PROPERTY_LOSSLESS;

            s->lossless    = 1;

            s->ls          = 0;

            s->progressive = 0;

            if ((ret = ff_mjpeg_decode_sof(s)) < 0)

                goto fail;

            break;

        case SOF48:

            s->avctx->properties |= FF_CODEC_PROPERTY_LOSSLESS;

            s->lossless    = 1;

            s->ls          = 1;

            s->progressive = 0;

            if ((ret = ff_mjpeg_decode_sof(s)) < 0)

                goto fail;

            break;

        case LSE:

            if (!CONFIG_JPEGLS_DECODER ||

                (ret = ff_jpegls_decode_lse(s)) < 0)

                goto fail;

            break;

        case EOI:

eoi_parser:

            s->cur_scan = 0;

            if (!s->got_picture) {

                av_log(avctx, AV_LOG_WARNING,

                       "Found EOI before any SOF, ignoring\n");

                break;

            }

            if (s->interlaced) {

                s->bottom_field ^= 1;

                /* if not bottom field, do not output image yet */

                if (s->bottom_field == !s->interlace_polarity)

                    break;

            }

            if (avctx->skip_frame == AVDISCARD_ALL) {

                s->got_picture = 0;

                goto the_end_no_picture;

            }

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

                return ret;

            *got_frame = 1;

            s->got_picture = 0;

            if (!s->lossless) {

                int qp = FFMAX3(s->qscale[0],

                                s->qscale[1],

                                s->qscale[2]);

                int qpw = (s->width + 15) / 16;

                AVBufferRef *qp_table_buf = av_buffer_alloc(qpw);

                if (qp_table_buf) {

                    memset(qp_table_buf->data, qp, qpw);

                    av_frame_set_qp_table(data, qp_table_buf, 0, FF_QSCALE_TYPE_MPEG1);

                }

                if(avctx->debug & FF_DEBUG_QP)

                    av_log(avctx, AV_LOG_DEBUG, "QP: %d\n", qp);

            }

            goto the_end;

        case SOS:

            s->cur_scan++;

            if (avctx->skip_frame == AVDISCARD_ALL)

                break;

            if ((ret = ff_mjpeg_decode_sos(s, NULL, 0, NULL)) < 0 &&

                (avctx->err_recognition & AV_EF_EXPLODE))

                goto fail;

            break;

        case DRI:

            mjpeg_decode_dri(s);

            break;

        case SOF5:

        case SOF6:

        case SOF7:

        case SOF9:

        case SOF10:

        case SOF11:

        case SOF13:

        case SOF14:

        case SOF15:

        case JPG:

            av_log(avctx, AV_LOG_ERROR,

                   "mjpeg: unsupported coding type (%x)\n", start_code);

            break;

        }

skip:

        /* eof process start code */

        buf_ptr += (get_bits_count(&s->gb) + 7) / 8;

        av_log(avctx, AV_LOG_DEBUG,

               "marker parser used %d bytes (%d bits)\n",

               (get_bits_count(&s->gb) + 7) / 8, get_bits_count(&s->gb));

    }

    if (s->got_picture && s->cur_scan) {

        av_log(avctx, AV_LOG_WARNING, "EOI missing, emulating\n");

        goto eoi_parser;

    }

    av_log(avctx, AV_LOG_FATAL, "No JPEG data found in image\n");

    return AVERROR_INVALIDDATA;

fail:

    s->got_picture = 0;

    return ret;

the_end:

    is16bit = av_pix_fmt_desc_get(s->avctx->pix_fmt)->comp[0].step > 1;

    if (AV_RB32(s->upscale_h)) {

        int p;

        av_assert0(avctx->pix_fmt == AV_PIX_FMT_YUVJ444P ||

                   avctx->pix_fmt == AV_PIX_FMT_YUV444P  ||

                   avctx->pix_fmt == AV_PIX_FMT_YUVJ440P ||

                   avctx->pix_fmt == AV_PIX_FMT_YUV440P  ||

                   avctx->pix_fmt == AV_PIX_FMT_YUVA444P ||

                   avctx->pix_fmt == AV_PIX_FMT_YUVJ420P ||

                   avctx->pix_fmt == AV_PIX_FMT_YUV420P  ||

                   avctx->pix_fmt == AV_PIX_FMT_YUV420P16||

                   avctx->pix_fmt == AV_PIX_FMT_YUVA420P  ||

                   avctx->pix_fmt == AV_PIX_FMT_YUVA420P16||

                   avctx->pix_fmt == AV_PIX_FMT_GBRP     ||

                   avctx->pix_fmt == AV_PIX_FMT_GBRAP

                  );

        avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &hshift, &vshift);

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

            uint8_t *line = s->picture_ptr->data[p];

            int w = s->width;

            int h = s->height;

            if (!s->upscale_h[p])

                continue;

            if (p==1 || p==2) {

                w = AV_CEIL_RSHIFT(w, hshift);

                h = AV_CEIL_RSHIFT(h, vshift);

            }

            if (s->upscale_v[p])

                h = (h+1)>>1;

            av_assert0(w > 0);

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

                if (s->upscale_h[p] == 1) {

                    if (is16bit) ((uint16_t*)line)[w - 1] = ((uint16_t*)line)[(w - 1) / 2];

                    else                      line[w - 1] = line[(w - 1) / 2];

                    for (index = w - 2; index > 0; index--) {

                        if (is16bit)

                            ((uint16_t*)line)[index] = (((uint16_t*)line)[index / 2] + ((uint16_t*)line)[(index + 1) / 2]) >> 1;

                        else

                            line[index] = (line[index / 2] + line[(index + 1) / 2]) >> 1;

                    }

                } else if (s->upscale_h[p] == 2) {

                    if (is16bit) {

                        ((uint16_t*)line)[w - 1] = ((uint16_t*)line)[(w - 1) / 3];

                        if (w > 1)

                            ((uint16_t*)line)[w - 2] = ((uint16_t*)line)[w - 1];

                    } else {

                        line[w - 1] = line[(w - 1) / 3];

                        if (w > 1)

                            line[w - 2] = line[w - 1];

                    }

                    for (index = w - 3; index > 0; index--) {

                        line[index] = (line[index / 3] + line[(index + 1) / 3] + line[(index + 2) / 3] + 1) / 3;

                    }

                }

                line += s->linesize[p];

            }

        }

    }

    if (AV_RB32(s->upscale_v)) {

        int p;

        av_assert0(avctx->pix_fmt == AV_PIX_FMT_YUVJ444P ||

                   avctx->pix_fmt == AV_PIX_FMT_YUV444P  ||

                   avctx->pix_fmt == AV_PIX_FMT_YUVJ422P ||

                   avctx->pix_fmt == AV_PIX_FMT_YUV422P  ||

                   avctx->pix_fmt == AV_PIX_FMT_YUVJ420P ||

                   avctx->pix_fmt == AV_PIX_FMT_YUV420P  ||

                   avctx->pix_fmt == AV_PIX_FMT_YUV440P  ||

                   avctx->pix_fmt == AV_PIX_FMT_YUVJ440P ||

                   avctx->pix_fmt == AV_PIX_FMT_YUVA444P ||

                   avctx->pix_fmt == AV_PIX_FMT_YUVA420P  ||

                   avctx->pix_fmt == AV_PIX_FMT_YUVA420P16||

                   avctx->pix_fmt == AV_PIX_FMT_GBRP     ||

                   avctx->pix_fmt == AV_PIX_FMT_GBRAP

                   );

        avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &hshift, &vshift);

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

            uint8_t *dst;

            int w = s->width;

            int h = s->height;

            if (!s->upscale_v[p])

                continue;

            if (p==1 || p==2) {

                w = AV_CEIL_RSHIFT(w, hshift);

                h = AV_CEIL_RSHIFT(h, vshift);

            }

            dst = &((uint8_t *)s->picture_ptr->data[p])[(h - 1) * s->linesize[p]];

            for (i = h - 1; i; i--) {

                uint8_t *src1 = &((uint8_t *)s->picture_ptr->data[p])[i / 2 * s->linesize[p]];

                uint8_t *src2 = &((uint8_t *)s->picture_ptr->data[p])[(i + 1) / 2 * s->linesize[p]];

                if (src1 == src2 || i == h - 1) {

                    memcpy(dst, src1, w);

                } else {

                    for (index = 0; index < w; index++)

                        dst[index] = (src1[index] + src2[index]) >> 1;

                }

                dst -= s->linesize[p];

            }

        }

    }

    if (s->flipped) {

        int j;

        avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &hshift, &vshift);

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

            uint8_t *dst = s->picture_ptr->data[index];

            int w = s->picture_ptr->width;

            int h = s->picture_ptr->height;

            if(index && index<3){

                w = AV_CEIL_RSHIFT(w, hshift);

                h = AV_CEIL_RSHIFT(h, vshift);

            }

            if(dst){

                uint8_t *dst2 = dst + s->picture_ptr->linesize[index]*(h-1);

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

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

                        FFSWAP(int, dst[j], dst2[j]);

                    dst  += s->picture_ptr->linesize[index];

                    dst2 -= s->picture_ptr->linesize[index];

                }

            }

        }

    }

    if (s->adobe_transform == 0 && s->avctx->pix_fmt == AV_PIX_FMT_GBRAP) {

        int w = s->picture_ptr->width;

        int h = s->picture_ptr->height;

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

            int j;

            uint8_t *dst[4];

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

                dst[index] =   s->picture_ptr->data[index]

                             + s->picture_ptr->linesize[index]*i;

            }

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

                int k = dst[3][j];

                int r = dst[0][j] * k;

                int g = dst[1][j] * k;

                int b = dst[2][j] * k;

                dst[0][j] = g*257 >> 16;

                dst[1][j] = b*257 >> 16;

                dst[2][j] = r*257 >> 16;

                dst[3][j] = 255;

            }

        }

    }

    if (s->adobe_transform == 2 && s->avctx->pix_fmt == AV_PIX_FMT_YUVA444P) {

        int w = s->picture_ptr->width;

        int h = s->picture_ptr->height;

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

            int j;

            uint8_t *dst[4];

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

                dst[index] =   s->picture_ptr->data[index]

                             + s->picture_ptr->linesize[index]*i;

            }

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

                int k = dst[3][j];

                int r = (255 - dst[0][j]) * k;

                int g = (128 - dst[1][j]) * k;

                int b = (128 - dst[2][j]) * k;

                dst[0][j] = r*257 >> 16;

                dst[1][j] = (g*257 >> 16) + 128;

                dst[2][j] = (b*257 >> 16) + 128;

                dst[3][j] = 255;

            }

        }

    }

    if (s->stereo3d) {

        AVStereo3D *stereo = av_stereo3d_create_side_data(data);

        if (stereo) {

            stereo->type  = s->stereo3d->type;

            stereo->flags = s->stereo3d->flags;

        }

        av_freep(&s->stereo3d);

    }

    av_dict_copy(avpriv_frame_get_metadatap(data), s->exif_metadata, 0);

    av_dict_free(&s->exif_metadata);

the_end_no_picture:

    av_log(avctx, AV_LOG_DEBUG, "decode frame unused %"PTRDIFF_SPECIFIER" bytes\n",

           buf_end - buf_ptr);

//  return buf_end - buf_ptr;

    return buf_ptr - buf;

}


static void a15_daughterboard_init(const VexpressMachineState *vms,

                                   ram_addr_t ram_size,

                                   const char *cpu_model,

                                   qemu_irq *pic)

{

    MemoryRegion *sysmem = get_system_memory();

    MemoryRegion *ram = g_new(MemoryRegion, 1);

    MemoryRegion *sram = g_new(MemoryRegion, 1);

    if (!cpu_model) {

        cpu_model = "cortex-a15";

    }

    {

        /* We have to use a separate 64 bit variable here to avoid the gcc

         * "comparison is always false due to limited range of data type"

         * warning if we are on a host where ram_addr_t is 32 bits.

         */

        uint64_t rsz = ram_size;

        if (rsz > (30ULL * 1024 * 1024 * 1024)) {

            fprintf(stderr, "vexpress-a15: cannot model more than 30GB RAM\n");

            exit(1);

        }

    }

    memory_region_allocate_system_memory(ram, NULL, "vexpress.highmem",

                                         ram_size);

    /* RAM is from 0x80000000 upwards; there is no low-memory alias for it. */

    memory_region_add_subregion(sysmem, 0x80000000, ram);

    /* 0x2c000000 A15MPCore private memory region (GIC) */

    init_cpus(cpu_model, "a15mpcore_priv", 0x2c000000, pic, vms->secure);

    /* A15 daughterboard peripherals: */

    /* 0x20000000: CoreSight interfaces: not modelled */

    /* 0x2a000000: PL301 AXI interconnect: not modelled */

    /* 0x2a420000: SCC: not modelled */

    /* 0x2a430000: system counter: not modelled */

    /* 0x2b000000: HDLCD controller: not modelled */

    /* 0x2b060000: SP805 watchdog: not modelled */

    /* 0x2b0a0000: PL341 dynamic memory controller: not modelled */

    /* 0x2e000000: system SRAM */

    memory_region_init_ram(sram, NULL, "vexpress.a15sram", 0x10000,

                           &error_abort);

    vmstate_register_ram_global(sram);

    memory_region_add_subregion(sysmem, 0x2e000000, sram);

    /* 0x7ffb0000: DMA330 DMA controller: not modelled */

    /* 0x7ffd0000: PL354 static memory controller: not modelled */

}


static void dec_sl(DisasContext *dc)

{

    if (dc->format == OP_FMT_RI) {

        LOG_DIS("sli r%d, r%d, %d\n", dc->r1, dc->r0, dc->imm5);

    } else {

        LOG_DIS("sl r%d, r%d, r%d\n", dc->r2, dc->r0, dc->r1);

    }

    if (!(dc->env->features & LM32_FEATURE_SHIFT)) {

        cpu_abort(dc->env, "hardware shifter is not available\n");

    }

    if (dc->format == OP_FMT_RI) {

        tcg_gen_shli_tl(cpu_R[dc->r1], cpu_R[dc->r0], dc->imm5);

    } else {

        TCGv t0 = tcg_temp_new();

        tcg_gen_andi_tl(t0, cpu_R[dc->r1], 0x1f);

        tcg_gen_shl_tl(cpu_R[dc->r2], cpu_R[dc->r0], t0);

        tcg_temp_free(t0);

    }

}


void qemu_iovec_init(QEMUIOVector *qiov, int alloc_hint)

{

    qiov->iov = g_malloc(alloc_hint * sizeof(struct iovec));

    qiov->niov = 0;

    qiov->nalloc = alloc_hint;

    qiov->size = 0;

}


static int vp3_update_thread_context(AVCodecContext *dst, const AVCodecContext *src)

{

    Vp3DecodeContext *s = dst->priv_data, *s1 = src->priv_data;

    int qps_changed = 0, i, err;

#define copy_fields(to, from, start_field, end_field) memcpy(&to->start_field, &from->start_field, (char*)&to->end_field - (char*)&to->start_field)

    if (!s1->current_frame.data[0]

        ||s->width != s1->width

        ||s->height!= s1->height) {

        if (s != s1)

            copy_fields(s, s1, golden_frame, current_frame);

        return -1;

    }

    if (s != s1) {

        // init tables if the first frame hasn't been decoded

        if (!s->current_frame.data[0]) {

            int y_fragment_count, c_fragment_count;

            s->avctx = dst;

            err = allocate_tables(dst);

            if (err)

                return err;

            y_fragment_count = s->fragment_width[0] * s->fragment_height[0];

            c_fragment_count = s->fragment_width[1] * s->fragment_height[1];

            memcpy(s->motion_val[0], s1->motion_val[0], y_fragment_count * sizeof(*s->motion_val[0]));

            memcpy(s->motion_val[1], s1->motion_val[1], c_fragment_count * sizeof(*s->motion_val[1]));

        }

        // copy previous frame data

        copy_fields(s, s1, golden_frame, dsp);

        // copy qscale data if necessary

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

            if (s->qps[i] != s1->qps[1]) {

                qps_changed = 1;

                memcpy(&s->qmat[i], &s1->qmat[i], sizeof(s->qmat[i]));

            }

        }

        if (s->qps[0] != s1->qps[0])

            memcpy(&s->bounding_values_array, &s1->bounding_values_array, sizeof(s->bounding_values_array));

        if (qps_changed)

            copy_fields(s, s1, qps, superblock_count);

#undef copy_fields

    }

    update_frames(dst);

    return 0;

}


static int write_reftable_entry(BlockDriverState *bs, int rt_index)

{

    BDRVQcowState *s = bs->opaque;

    uint64_t buf[RT_ENTRIES_PER_SECTOR];

    int rt_start_index;

    int i, ret;

    rt_start_index = rt_index & ~(RT_ENTRIES_PER_SECTOR - 1);

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

        buf[i] = cpu_to_be64(s->refcount_table[rt_start_index + i]);

    }

    ret = qcow2_pre_write_overlap_check(bs,

            QCOW2_OL_DEFAULT & ~QCOW2_OL_REFCOUNT_TABLE,

            s->refcount_table_offset + rt_start_index * sizeof(uint64_t),

            sizeof(buf));

    if (ret < 0) {

        return ret;

    }

    BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE);

    ret = bdrv_pwrite_sync(bs->file, s->refcount_table_offset +

            rt_start_index * sizeof(uint64_t), buf, sizeof(buf));

    if (ret < 0) {

        return ret;

    }

    return 0;

}


void ff_init_elbg(int *points, int dim, int numpoints, int *codebook,

                  int numCB, int max_steps, int *closest_cb,

                  AVLFG *rand_state)

{

    int i, k;

    if (numpoints > 24*numCB) {

        /* ELBG is very costly for a big number of points. So if we have a lot

           of them, get a good initial codebook to save on iterations       */

        int *temp_points = av_malloc(dim*(numpoints/8)*sizeof(int));

        for (i=0; i<numpoints/8; i++) {

            k = (i*BIG_PRIME) % numpoints;

            memcpy(temp_points + i*dim, points + k*dim, dim*sizeof(int));

        }

        ff_init_elbg(temp_points, dim, numpoints/8, codebook, numCB, 2*max_steps, closest_cb, rand_state);

        ff_do_elbg(temp_points, dim, numpoints/8, codebook, numCB, 2*max_steps, closest_cb, rand_state);

        av_free(temp_points);

    } else  // If not, initialize the codebook with random positions

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

            memcpy(codebook + i*dim, points + ((i*BIG_PRIME)%numpoints)*dim,

                   dim*sizeof(int));

}


av_cold void ff_lpc_init_x86(LPCContext *c)

{

#if HAVE_SSE2_INLINE

    int cpu_flags = av_get_cpu_flags();

    if (INLINE_SSE2(cpu_flags) && (cpu_flags & AV_CPU_FLAG_SSE2SLOW)) {

        c->lpc_apply_welch_window = lpc_apply_welch_window_sse2;

        c->lpc_compute_autocorr   = lpc_compute_autocorr_sse2;

    }

#endif /* HAVE_SSE2_INLINE */

}


int ff_pcm_read_packet(AVFormatContext *s, AVPacket *pkt)

{

    int ret, size;

    size= RAW_SAMPLES*s->streams[0]->codec->block_align;

    if (size <= 0)

        return AVERROR(EINVAL);

    ret= av_get_packet(s->pb, pkt, size);

    pkt->flags &= ~AV_PKT_FLAG_CORRUPT;

    pkt->stream_index = 0;

    if (ret < 0)

        return ret;

    return ret;

}


static int decode_cabac_mb_skip( H264Context *h, int mb_x, int mb_y ) {

    MpegEncContext * const s = &h->s;

    int mba_xy, mbb_xy;

    int ctx = 0;

    if(FRAME_MBAFF){ //FIXME merge with the stuff in fill_caches?

        int mb_xy = mb_x + (mb_y&~1)*s->mb_stride;

        mba_xy = mb_xy - 1;

        if( (mb_y&1)

            && h->slice_table[mba_xy] == h->slice_num

            && MB_FIELD == !!IS_INTERLACED( s->current_picture.mb_type[mba_xy] ) )

            mba_xy += s->mb_stride;

        if( MB_FIELD ){

            mbb_xy = mb_xy - s->mb_stride;

            if( !(mb_y&1)

                && h->slice_table[mbb_xy] == h->slice_num

                && IS_INTERLACED( s->current_picture.mb_type[mbb_xy] ) )

                mbb_xy -= s->mb_stride;

        }else

            mbb_xy = mb_x + (mb_y-1)*s->mb_stride;

    }else{

        int mb_xy = mb_x + mb_y*s->mb_stride;

        mba_xy = mb_xy - 1;

        mbb_xy = mb_xy - s->mb_stride;

    }

    if( h->slice_table[mba_xy] == h->slice_num && !IS_SKIP( s->current_picture.mb_type[mba_xy] ))

        ctx++;

    if( h->slice_table[mbb_xy] == h->slice_num && !IS_SKIP( s->current_picture.mb_type[mbb_xy] ))

        ctx++;

    if( h->slice_type == B_TYPE )

        ctx += 13;

    return get_cabac( &h->cabac, &h->cabac_state[11+ctx] );

}


static int handle_packets(AVFormatContext *s, int nb_packets)

{

    MpegTSContext *ts = s->priv_data;

    ByteIOContext *pb = &s->pb;

    uint8_t packet[TS_FEC_PACKET_SIZE];

    int packet_num, len;

    ts->stop_parse = 0;

    packet_num = 0;

    for(;;) {

        if (ts->stop_parse)

            break;

        packet_num++;

        if (nb_packets != 0 && packet_num >= nb_packets)

            break;

        len = get_buffer(pb, packet, ts->raw_packet_size);

        if (len != ts->raw_packet_size)

            return AVERROR_IO;

        /* check paquet sync byte */

        /* XXX: accept to resync ? */

        if (packet[0] != 0x47)

            return AVERROR_INVALIDDATA;

        handle_packet(s, packet);

    }

    return 0;

}


QTestState *qtest_init(const char *extra_args)

{

    QTestState *s;

    int sock, qmpsock, i;

    gchar *socket_path;

    gchar *qmp_socket_path;

    gchar *command;

    const char *qemu_binary;

    struct sigaction sigact;

    qemu_binary = getenv("QTEST_QEMU_BINARY");

    g_assert(qemu_binary != NULL);

    s = g_malloc(sizeof(*s));

    socket_path = g_strdup_printf("/tmp/qtest-%d.sock", getpid());

    qmp_socket_path = g_strdup_printf("/tmp/qtest-%d.qmp", getpid());

    sock = init_socket(socket_path);

    qmpsock = init_socket(qmp_socket_path);

    /* Catch SIGABRT to clean up on g_assert() failure */

    sigact = (struct sigaction){

        .sa_handler = sigabrt_handler,

        .sa_flags = SA_RESETHAND,

    };

    sigemptyset(&sigact.sa_mask);

    sigaction(SIGABRT, &sigact, &s->sigact_old);

    s->qemu_pid = fork();

    if (s->qemu_pid == 0) {

        command = g_strdup_printf("exec %s "

                                  "-qtest unix:%s,nowait "

                                  "-qtest-log /dev/null "

                                  "-qmp unix:%s,nowait "

                                  "-machine accel=qtest "

                                  "-display none "

                                  "%s", qemu_binary, socket_path,

                                  qmp_socket_path,

                                  extra_args ?: "");

        execlp("/bin/sh", "sh", "-c", command, NULL);

        exit(1);

    }

    s->fd = socket_accept(sock);

    s->qmp_fd = socket_accept(qmpsock);

    unlink(socket_path);

    unlink(qmp_socket_path);

    g_free(socket_path);

    g_free(qmp_socket_path);

    s->rx = g_string_new("");

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

        s->irq_level[i] = false;

    }

    /* Read the QMP greeting and then do the handshake */

    qtest_qmp_discard_response(s, "");

    qtest_qmp_discard_response(s, "{ 'execute': 'qmp_capabilities' }");

    if (getenv("QTEST_STOP")) {

        kill(s->qemu_pid, SIGSTOP);

    }

    return s;

}


static void qxl_init_ramsize(PCIQXLDevice *qxl)

{

    /* vga mode framebuffer / primary surface (bar 0, first part) */

    if (qxl->vgamem_size_mb < 8) {

        qxl->vgamem_size_mb = 8;

    qxl->vgamem_size = qxl->vgamem_size_mb * 1024 * 1024;

    /* vga ram (bar 0, total) */

    if (qxl->ram_size_mb != -1) {

        qxl->vga.vram_size = qxl->ram_size_mb * 1024 * 1024;

    if (qxl->vga.vram_size < qxl->vgamem_size * 2) {

        qxl->vga.vram_size = qxl->vgamem_size * 2;

    /* vram32 (surfaces, 32bit, bar 1) */

    if (qxl->vram32_size_mb != -1) {

        qxl->vram32_size = qxl->vram32_size_mb * 1024 * 1024;

    if (qxl->vram32_size < 4096) {

        qxl->vram32_size = 4096;

    /* vram (surfaces, 64bit, bar 4+5) */

    if (qxl->vram_size_mb != -1) {

        qxl->vram_size = qxl->vram_size_mb * 1024 * 1024;

    if (qxl->vram_size < qxl->vram32_size) {

        qxl->vram_size = qxl->vram32_size;

    if (qxl->revision == 1) {

        qxl->vram32_size = 4096;

        qxl->vram_size = 4096;

    qxl->vgamem_size = msb_mask(qxl->vgamem_size * 2 - 1);

    qxl->vga.vram_size = msb_mask(qxl->vga.vram_size * 2 - 1);

    qxl->vram32_size = msb_mask(qxl->vram32_size * 2 - 1);

    qxl->vram_size = msb_mask(qxl->vram_size * 2 - 1);


static int decode_packet(J2kDecoderContext *s, J2kCodingStyle *codsty, J2kResLevel *rlevel, int precno,

                         int layno, uint8_t *expn, int numgbits)

{

    int bandno, cblkny, cblknx, cblkno, ret;

    if (!(ret = get_bits(s, 1))){

        j2k_flush(s);

        return 0;

    } else if (ret < 0)

        return ret;

    for (bandno = 0; bandno < rlevel->nbands; bandno++){

        J2kBand *band = rlevel->band + bandno;

        J2kPrec *prec = band->prec + precno;

        int pos = 0;

        if (band->coord[0][0] == band->coord[0][1]

        ||  band->coord[1][0] == band->coord[1][1])

            continue;

        for (cblkny = prec->yi0; cblkny < prec->yi1; cblkny++)

            for(cblknx = prec->xi0, cblkno = cblkny * band->cblknx + cblknx; cblknx < prec->xi1; cblknx++, cblkno++, pos++){

                J2kCblk *cblk = band->cblk + cblkno;

                int incl, newpasses, llen;

                if (cblk->npasses)

                    incl = get_bits(s, 1);

                else

                    incl = tag_tree_decode(s, prec->cblkincl + pos, layno+1) == layno;

                if (!incl)

                    continue;

                else if (incl < 0)

                    return incl;

                if (!cblk->npasses)

                    cblk->nonzerobits = expn[bandno] + numgbits - 1 - tag_tree_decode(s, prec->zerobits + pos, 100);

                if ((newpasses = getnpasses(s)) < 0)

                    return newpasses;

                if ((llen = getlblockinc(s)) < 0)

                    return llen;

                cblk->lblock += llen;

                if ((ret = get_bits(s, av_log2(newpasses) + cblk->lblock)) < 0)

                    return ret;

                cblk->lengthinc = ret;

                cblk->npasses += newpasses;

            }

    }

    j2k_flush(s);

    if (codsty->csty & J2K_CSTY_EPH) {

        if (AV_RB16(s->buf) == J2K_EPH) {

            s->buf += 2;

        } else {

            av_log(s->avctx, AV_LOG_ERROR, "EPH marker not found.\n");

        }

    }

    for (bandno = 0; bandno < rlevel->nbands; bandno++){

        J2kBand *band = rlevel->band + bandno;

        int yi, cblknw = band->prec[precno].xi1 - band->prec[precno].xi0;

        for (yi = band->prec[precno].yi0; yi < band->prec[precno].yi1; yi++){

            int xi;

            for (xi = band->prec[precno].xi0; xi < band->prec[precno].xi1; xi++){

                J2kCblk *cblk = band->cblk + yi * cblknw + xi;

                if (s->buf_end - s->buf < cblk->lengthinc)

                    return AVERROR(EINVAL);

                bytestream_get_buffer(&s->buf, cblk->data, cblk->lengthinc);

                cblk->length += cblk->lengthinc;

                cblk->lengthinc = 0;

            }

        }

    }

    return 0;

}


static SoftFloat sbr_sum_square_c(int (*x)[2], int n)

{

    SoftFloat ret;

    uint64_t accu = 0, round;

    int i, nz;

    unsigned u;

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

        // Larger values are inavlid and could cause overflows of accu.

        av_assert2(FFABS(x[i + 0][0]) >> 29 == 0);

        accu += (int64_t)x[i + 0][0] * x[i + 0][0];

        av_assert2(FFABS(x[i + 0][1]) >> 29 == 0);

        accu += (int64_t)x[i + 0][1] * x[i + 0][1];

        av_assert2(FFABS(x[i + 1][0]) >> 29 == 0);

        accu += (int64_t)x[i + 1][0] * x[i + 1][0];

        av_assert2(FFABS(x[i + 1][1]) >> 29 == 0);

        accu += (int64_t)x[i + 1][1] * x[i + 1][1];

    }

    u = accu >> 32;

    if (u == 0) {

        nz = 1;

    } else {

        nz = -1;

        while (u < 0x80000000U) {

            u <<= 1;

            nz++;

        }

        nz = 32 - nz;

    }

    round = 1ULL << (nz-1);

    u = ((accu + round) >> nz);

    u >>= 1;

    ret = av_int2sf(u, 15 - nz);

    return ret;

}


int kvm_log_stop(target_phys_addr_t phys_addr, target_phys_addr_t end_addr)

{

        return kvm_dirty_pages_log_change(phys_addr, end_addr,

                                          0,

                                          KVM_MEM_LOG_DIRTY_PAGES);

}


int qemu_strtoll(const char *nptr, const char **endptr, int base,

                 int64_t *result)

{

    char *p;

    int err = 0;

    if (!nptr) {

        if (endptr) {

            *endptr = nptr;

        }

        err = -EINVAL;

    } else {

        errno = 0;

        *result = strtoll(nptr, &p, base);

        err = check_strtox_error(endptr, p, errno);

    }

    return err;

}


static int sofalizer_convolute(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)

{

    SOFAlizerContext *s = ctx->priv;

    ThreadData *td = arg;

    AVFrame *in = td->in, *out = td->out;

    int offset = jobnr;

    int *write = &td->write[jobnr];

    const int *const delay = td->delay[jobnr];

    const float *const ir = td->ir[jobnr];

    int *n_clippings = &td->n_clippings[jobnr];

    float *ringbuffer = td->ringbuffer[jobnr];

    float *temp_src = td->temp_src[jobnr];

    const int n_samples = s->sofa.n_samples; /* length of one IR */

    const float *src = (const float *)in->data[0]; /* get pointer to audio input buffer */

    float *dst = (float *)out->data[0]; /* get pointer to audio output buffer */

    const int in_channels = s->n_conv; /* number of input channels */

    /* ring buffer length is: longest IR plus max. delay -> next power of 2 */

    const int buffer_length = s->buffer_length;

    /* -1 for AND instead of MODULO (applied to powers of 2): */

    const uint32_t modulo = (uint32_t)buffer_length - 1;

    float *buffer[16]; /* holds ringbuffer for each input channel */

    int wr = *write;

    int read;

    int i, l;

    dst += offset;

    for (l = 0; l < in_channels; l++) {

        /* get starting address of ringbuffer for each input channel */

        buffer[l] = ringbuffer + l * buffer_length;

    }

    for (i = 0; i < in->nb_samples; i++) {

        const float *temp_ir = ir; /* using same set of IRs for each sample */

        *dst = 0;

        for (l = 0; l < in_channels; l++) {

            /* write current input sample to ringbuffer (for each channel) */

            *(buffer[l] + wr) = src[l];

        }

        /* loop goes through all channels to be convolved */

        for (l = 0; l < in_channels; l++) {

            const float *const bptr = buffer[l];

            if (l == s->lfe_channel) {

                /* LFE is an input channel but requires no convolution */

                /* apply gain to LFE signal and add to output buffer */

                *dst += *(buffer[s->lfe_channel] + wr) * s->gain_lfe;

                temp_ir += n_samples;

                continue;

            }

            /* current read position in ringbuffer: input sample write position

             * - delay for l-th ch. + diff. betw. IR length and buffer length

             * (mod buffer length) */

            read = (wr - *(delay + l) - (n_samples - 1) + buffer_length) & modulo;

            if (read + n_samples < buffer_length) {

                memcpy(temp_src, bptr + read, n_samples * sizeof(*temp_src));

            } else {

                int len = FFMIN(n_samples - (read % n_samples), buffer_length - read);

                memcpy(temp_src, bptr + read, len * sizeof(*temp_src));

                memcpy(temp_src + len, bptr, (n_samples - len) * sizeof(*temp_src));

            }

            /* multiply signal and IR, and add up the results */

            dst[0] += s->fdsp->scalarproduct_float(temp_ir, temp_src, n_samples);

            temp_ir += n_samples;

        }

        /* clippings counter */

        if (fabs(*dst) > 1)

            *n_clippings += 1;

        /* move output buffer pointer by +2 to get to next sample of processed channel: */

        dst += 2;

        src += in_channels;

        wr   = (wr + 1) & modulo; /* update ringbuffer write position */

    }

    *write = wr; /* remember write position in ringbuffer for next call */

    return 0;

}


int ff_htmlmarkup_to_ass(void *log_ctx, AVBPrint *dst, const char *in)

{

    char *param, buffer[128], tmp[128];

    int len, tag_close, sptr = 1, line_start = 1, an = 0, end = 0;

    SrtStack stack[16];

    int closing_brace_missing = 0;

    stack[0].tag[0] = 0;

    strcpy(stack[0].param[PARAM_SIZE],  "{\\fs}");

    strcpy(stack[0].param[PARAM_COLOR], "{\\c}");

    strcpy(stack[0].param[PARAM_FACE],  "{\\fn}");

    for (; !end && *in; in++) {

        switch (*in) {

        case '\r':

            break;

        case '\n':

            if (line_start) {

                end = 1;

                break;

            }

            rstrip_spaces_buf(dst);

            av_bprintf(dst, "\\N");

            line_start = 1;

            break;

        case ' ':

            if (!line_start)

                av_bprint_chars(dst, *in, 1);

            break;

        case '{':

            handle_open_brace(dst, &in, &an, &closing_brace_missing);

            break;

        case '<':

            tag_close = in[1] == '/';

            len = 0;

            if (sscanf(in+tag_close+1, "%127[^>]>%n", buffer, &len) >= 1 && len > 0) {

                const char *tagname = buffer;

                while (*tagname == ' ')

                    tagname++;

                if ((param = strchr(tagname, ' ')))

                    *param++ = 0;

                if ((!tag_close && sptr < FF_ARRAY_ELEMS(stack)) ||

                    ( tag_close && sptr > 0 && !av_strcasecmp(stack[sptr-1].tag, tagname))) {

                    int i, j, unknown = 0;

                    in += len + tag_close;

                    if (!tag_close)

                        memset(stack+sptr, 0, sizeof(*stack));

                    if (!av_strcasecmp(tagname, "font")) {

                        if (tag_close) {

                            for (i=PARAM_NUMBER-1; i>=0; i--)

                                if (stack[sptr-1].param[i][0])

                                    for (j=sptr-2; j>=0; j--)

                                        if (stack[j].param[i][0]) {

                                            av_bprintf(dst, "%s", stack[j].param[i]);

                                            break;

                                        }

                        } else {

                            while (param) {

                                if (!av_strncasecmp(param, "size=", 5)) {

                                    unsigned font_size;

                                    param += 5 + (param[5] == '"');

                                    if (sscanf(param, "%u", &font_size) == 1) {

                                        snprintf(stack[sptr].param[PARAM_SIZE],

                                             sizeof(stack[0].param[PARAM_SIZE]),

                                             "{\\fs%u}", font_size);

                                    }

                                } else if (!av_strncasecmp(param, "color=", 6)) {

                                    param += 6 + (param[6] == '"');

                                    snprintf(stack[sptr].param[PARAM_COLOR],

                                         sizeof(stack[0].param[PARAM_COLOR]),

                                         "{\\c&H%X&}",

                                         html_color_parse(log_ctx, param));

                                } else if (!av_strncasecmp(param, "face=", 5)) {

                                    param += 5 + (param[5] == '"');

                                    len = strcspn(param,

                                                  param[-1] == '"' ? "\"" :" ");

                                    av_strlcpy(tmp, param,

                                               FFMIN(sizeof(tmp), len+1));

                                    param += len;

                                    snprintf(stack[sptr].param[PARAM_FACE],

                                             sizeof(stack[0].param[PARAM_FACE]),

                                             "{\\fn%s}", tmp);

                                }

                                if ((param = strchr(param, ' ')))

                                    param++;

                            }

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

                                if (stack[sptr].param[i][0])

                                    av_bprintf(dst, "%s", stack[sptr].param[i]);

                        }

                    } else if (tagname[0] && !tagname[1] && av_stristr("bisu", tagname)) {

                        av_bprintf(dst, "{\\%c%d}", (char)av_tolower(tagname[0]), !tag_close);

                    } else if (!av_strcasecmp(tagname, "br")) {

                        av_bprintf(dst, "\\N");

                    } else {

                        unknown = 1;

                        snprintf(tmp, sizeof(tmp), "</%s>", tagname);

                    }

                    if (tag_close) {

                        sptr--;

                    } else if (unknown && !strstr(in, tmp)) {

                        in -= len + tag_close;

                        av_bprint_chars(dst, *in, 1);

                    } else

                        av_strlcpy(stack[sptr++].tag, tagname,

                                   sizeof(stack[0].tag));

                    break;

                }

            }

        default:

            av_bprint_chars(dst, *in, 1);

            break;

        }

        if (*in != ' ' && *in != '\r' && *in != '\n')

            line_start = 0;

    }

    if (!av_bprint_is_complete(dst))

        return AVERROR(ENOMEM);

    while (dst->len >= 2 && !strncmp(&dst->str[dst->len - 2], "\\N", 2))

        dst->len -= 2;

    dst->str[dst->len] = 0;

    rstrip_spaces_buf(dst);

    return 0;

}


void qemu_mutex_destroy(QemuMutex *mutex)

{

    assert(mutex->owner == 0);

    DeleteCriticalSection(&mutex->lock);

}


static int usb_host_handle_iso_data(USBHostDevice *s, USBPacket *p, int in)

{

    AsyncURB *aurb;

    int i, j, ret, max_packet_size, offset, len = 0;

    max_packet_size = get_max_packet_size(s, p->devep);

    if (max_packet_size == 0)

        return USB_RET_NAK;

    aurb = get_iso_urb(s, p->devep);

    if (!aurb) {

        aurb = usb_host_alloc_iso(s, p->devep, in);

    }

    i = get_iso_urb_idx(s, p->devep);

    j = aurb[i].iso_frame_idx;

    if (j >= 0 && j < ISO_FRAME_DESC_PER_URB) {

        if (in) {

            /* Check urb status  */

            if (aurb[i].urb.status) {

                len = urb_status_to_usb_ret(aurb[i].urb.status);

                /* Move to the next urb */

                aurb[i].iso_frame_idx = ISO_FRAME_DESC_PER_URB - 1;

            /* Check frame status */

            } else if (aurb[i].urb.iso_frame_desc[j].status) {

                len = urb_status_to_usb_ret(

                                        aurb[i].urb.iso_frame_desc[j].status);

            /* Check the frame fits */

            } else if (aurb[i].urb.iso_frame_desc[j].actual_length > p->len) {

                printf("husb: received iso data is larger then packet\n");

                len = USB_RET_NAK;

            /* All good copy data over */

            } else {

                len = aurb[i].urb.iso_frame_desc[j].actual_length;

                memcpy(p->data,

                       aurb[i].urb.buffer +

                           j * aurb[i].urb.iso_frame_desc[0].length,

                       len);

            }

        } else {

            len = p->len;

            offset = (j == 0) ? 0 : get_iso_buffer_used(s, p->devep);

            /* Check the frame fits */

            if (len > max_packet_size) {

                printf("husb: send iso data is larger then max packet size\n");

                return USB_RET_NAK;

            }

            /* All good copy data over */

            memcpy(aurb[i].urb.buffer + offset, p->data, len);

            aurb[i].urb.iso_frame_desc[j].length = len;

            offset += len;

            set_iso_buffer_used(s, p->devep, offset);

            /* Start the stream once we have buffered enough data */

            if (!is_iso_started(s, p->devep) && i == 1 && j == 8) {

                set_iso_started(s, p->devep);

            }

        }

        aurb[i].iso_frame_idx++;

        if (aurb[i].iso_frame_idx == ISO_FRAME_DESC_PER_URB) {

            i = (i + 1) % s->iso_urb_count;

            set_iso_urb_idx(s, p->devep, i);

        }

    } else {

        if (in) {

            set_iso_started(s, p->devep);

        } else {

            DPRINTF("hubs: iso out error no free buffer, dropping packet\n");

        }

    }

    if (is_iso_started(s, p->devep)) {

        /* (Re)-submit all fully consumed / filled urbs */

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

            if (aurb[i].iso_frame_idx == ISO_FRAME_DESC_PER_URB) {

                ret = ioctl(s->fd, USBDEVFS_SUBMITURB, &aurb[i]);

                if (ret < 0) {

                    printf("husb error submitting iso urb %d: %d\n", i, errno);

                    if (!in || len == 0) {

                        switch(errno) {

                        case ETIMEDOUT:

                            len = USB_RET_NAK;

                            break;

                        case EPIPE:

                        default:

                            len = USB_RET_STALL;

                        }

                    }

                    break;

                }

                aurb[i].iso_frame_idx = -1;

                change_iso_inflight(s, p->devep, +1);

            }

        }

    }

    return len;

}


static void pcie_pci_bridge_realize(PCIDevice *d, Error **errp)

{

    PCIBridge *br = PCI_BRIDGE(d);

    PCIEPCIBridge *pcie_br = PCIE_PCI_BRIDGE_DEV(d);

    int rc, pos;

    pci_bridge_initfn(d, TYPE_PCI_BUS);

    d->config[PCI_INTERRUPT_PIN] = 0x1;

    memory_region_init(&pcie_br->shpc_bar, OBJECT(d), "shpc-bar",

                       shpc_bar_size(d));

    rc = shpc_init(d, &br->sec_bus, &pcie_br->shpc_bar, 0, errp);

    if (rc) {

        goto error;

    }

    rc = pcie_cap_init(d, 0, PCI_EXP_TYPE_PCI_BRIDGE, 0, errp);

    if (rc < 0) {

        goto cap_error;

    }

    pos = pci_add_capability(d, PCI_CAP_ID_PM, 0, PCI_PM_SIZEOF, errp);

    if (pos < 0) {

        goto pm_error;

    }

    d->exp.pm_cap = pos;

    pci_set_word(d->config + pos + PCI_PM_PMC, 0x3);

    pcie_cap_arifwd_init(d);

    pcie_cap_deverr_init(d);

    rc = pcie_aer_init(d, PCI_ERR_VER, 0x100, PCI_ERR_SIZEOF, errp);

    if (rc < 0) {

        goto aer_error;

    }

    if (pcie_br->msi != ON_OFF_AUTO_OFF) {

        rc = msi_init(d, 0, 1, true, true, errp);

        if (rc < 0) {

            goto msi_error;

        }

    }

    pci_register_bar(d, 0, PCI_BASE_ADDRESS_SPACE_MEMORY |

                     PCI_BASE_ADDRESS_MEM_TYPE_64, &pcie_br->shpc_bar);

    return;

msi_error:

    pcie_aer_exit(d);

aer_error:

pm_error:

    pcie_cap_exit(d);

cap_error:

    shpc_free(d);

error:

    pci_bridge_exitfn(d);

}


static int qcrypto_cipher_init_aes(QCryptoCipher *cipher,

                                   const uint8_t *key, size_t nkey,

                                   Error **errp)

{

    QCryptoCipherBuiltin *ctxt;

    if (cipher->mode != QCRYPTO_CIPHER_MODE_CBC &&

        cipher->mode != QCRYPTO_CIPHER_MODE_ECB) {

        error_setg(errp, "Unsupported cipher mode %d", cipher->mode);

        return -1;

    }

    ctxt = g_new0(QCryptoCipherBuiltin, 1);

    if (AES_set_encrypt_key(key, nkey * 8, &ctxt->state.aes.encrypt_key) != 0) {

        error_setg(errp, "Failed to set encryption key");

        goto error;

    }

    if (AES_set_decrypt_key(key, nkey * 8, &ctxt->state.aes.decrypt_key) != 0) {

        error_setg(errp, "Failed to set decryption key");

        goto error;

    }

    ctxt->free = qcrypto_cipher_free_aes;

    ctxt->setiv = qcrypto_cipher_setiv_aes;

    ctxt->encrypt = qcrypto_cipher_encrypt_aes;

    ctxt->decrypt = qcrypto_cipher_decrypt_aes;

    cipher->opaque = ctxt;

    return 0;

 error:

    g_free(ctxt);

    return -1;

}


static int mxf_read_partition_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid)

{

    MXFContext *mxf = arg;

    MXFPartition *partition;

    UID op;

    uint64_t footer_partition;

    if (mxf->partitions_count+1 >= UINT_MAX / sizeof(*mxf->partitions))

        return AVERROR(ENOMEM);

    mxf->partitions = av_realloc(mxf->partitions, (mxf->partitions_count + 1) * sizeof(*mxf->partitions));

    if (!mxf->partitions)

        return AVERROR(ENOMEM);

    if (mxf->parsing_backward) {

        /* insert the new partition pack in the middle

         * this makes the entries in mxf->partitions sorted by offset */

        memmove(&mxf->partitions[mxf->last_forward_partition+1],

                &mxf->partitions[mxf->last_forward_partition],

                (mxf->partitions_count - mxf->last_forward_partition)*sizeof(*mxf->partitions));

        partition = mxf->current_partition = &mxf->partitions[mxf->last_forward_partition];

    } else {

        mxf->last_forward_partition++;

        partition = mxf->current_partition = &mxf->partitions[mxf->partitions_count];

    }

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

    mxf->partitions_count++;

    switch(uid[13]) {

    case 2:

        partition->type = Header;

        break;

    case 3:

        partition->type = BodyPartition;

        break;

    case 4:

        partition->type = Footer;

        break;

    default:

        av_log(mxf->fc, AV_LOG_ERROR, "unknown partition type %i\n", uid[13]);

        return AVERROR_INVALIDDATA;

    }

    /* consider both footers to be closed (there is only Footer and CompleteFooter) */

    partition->closed = partition->type == Footer || !(uid[14] & 1);

    partition->complete = uid[14] > 2;

    avio_skip(pb, 8);

    partition->this_partition = avio_rb64(pb);

    partition->previous_partition = avio_rb64(pb);

    footer_partition = avio_rb64(pb);

    avio_skip(pb, 16);

    partition->index_sid = avio_rb32(pb);

    avio_skip(pb, 8);

    partition->body_sid = avio_rb32(pb);

    avio_read(pb, op, sizeof(UID));

    /* some files don'thave FooterPartition set in every partition */

    if (footer_partition) {

        if (mxf->footer_partition && mxf->footer_partition != footer_partition) {

            av_log(mxf->fc, AV_LOG_ERROR, "inconsistent FooterPartition value: %li != %li\n",

                   mxf->footer_partition, footer_partition);

        } else {

            mxf->footer_partition = footer_partition;

        }

    }

    av_dlog(mxf->fc, "PartitionPack: ThisPartition = 0x%lx, PreviousPartition = 0x%lx, "

            "FooterPartition = 0x%lx, IndexSID = %i, BodySID = %i\n",

            partition->this_partition,

            partition->previous_partition, footer_partition,

            partition->index_sid, partition->body_sid);

    if      (op[12] == 1 && op[13] == 1) mxf->op = OP1a;

    else if (op[12] == 1 && op[13] == 2) mxf->op = OP1b;

    else if (op[12] == 1 && op[13] == 3) mxf->op = OP1c;

    else if (op[12] == 2 && op[13] == 1) mxf->op = OP2a;

    else if (op[12] == 2 && op[13] == 2) mxf->op = OP2b;

    else if (op[12] == 2 && op[13] == 3) mxf->op = OP2c;

    else if (op[12] == 3 && op[13] == 1) mxf->op = OP3a;

    else if (op[12] == 3 && op[13] == 2) mxf->op = OP3b;

    else if (op[12] == 3 && op[13] == 3) mxf->op = OP3c;

    else if (op[12] == 0x10)             mxf->op = OPAtom;

    else

        av_log(mxf->fc, AV_LOG_ERROR, "unknown operational pattern: %02xh %02xh\n", op[12], op[13]);

    return 0;

}


static uint64_t getSSD(uint8_t *src1, uint8_t *src2, int stride1, int stride2, int w, int h){

	int x,y;

	uint64_t ssd=0;

//printf("%d %d\n", w, h);

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

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

			int d= src1[x + y*stride1] - src2[x + y*stride2];

			ssd+= d*d;

//printf("%d", abs(src1[x + y*stride1] - src2[x + y*stride2])/26 );

		}

//printf("\n");

	}

	return ssd;

}


static inline void test_server_connect(TestServer *server)

{

    test_server_create_chr(server, ",reconnect=1");

}


static int put_system_header(AVFormatContext *ctx, uint8_t *buf,int only_for_stream_id)

{

    MpegMuxContext *s = ctx->priv_data;

    int size, i, private_stream_coded, id;

    PutBitContext pb;

    init_put_bits(&pb, buf, 128);

    put_bits(&pb, 32, SYSTEM_HEADER_START_CODE);

    put_bits(&pb, 16, 0);

    put_bits(&pb, 1, 1);

    put_bits(&pb, 22, s->mux_rate); /* maximum bit rate of the multiplexed stream */

    put_bits(&pb, 1, 1); /* marker */

    if (s->is_vcd && only_for_stream_id==VIDEO_ID) {

        /* This header applies only to the video stream (see VCD standard p. IV-7)*/

        put_bits(&pb, 6, 0);

    } else

        put_bits(&pb, 6, s->audio_bound);

    if (s->is_vcd) {

        /* see VCD standard, p. IV-7*/

        put_bits(&pb, 1, 0);

        put_bits(&pb, 1, 1);

    } else {

        put_bits(&pb, 1, 0); /* variable bitrate*/

        put_bits(&pb, 1, 0); /* non constrainted bit stream */

    }

    if (s->is_vcd || s->is_dvd) {

        /* see VCD standard p IV-7 */

        put_bits(&pb, 1, 1); /* audio locked */

        put_bits(&pb, 1, 1); /* video locked */

    } else {

        put_bits(&pb, 1, 0); /* audio locked */

        put_bits(&pb, 1, 0); /* video locked */

    }

    put_bits(&pb, 1, 1); /* marker */

    if (s->is_vcd && only_for_stream_id==AUDIO_ID) {

        /* This header applies only to the audio stream (see VCD standard p. IV-7)*/

        put_bits(&pb, 5, 0);

    } else

        put_bits(&pb, 5, s->video_bound);

    if (s->is_dvd) {

        put_bits(&pb, 1, 0);    /* packet_rate_restriction_flag */

        put_bits(&pb, 7, 0x7f); /* reserved byte */

    } else

        put_bits(&pb, 8, 0xff); /* reserved byte */

    /* DVD-Video Stream_bound entries

    id (0xB9) video, maximum P-STD for stream 0xE0. (P-STD_buffer_bound_scale = 1)

    id (0xB8) audio, maximum P-STD for any MPEG audio (0xC0 to 0xC7) streams. If there are none set to 4096 (32x128). (P-STD_buffer_bound_scale = 0)

    id (0xBD) private stream 1 (audio other than MPEG and subpictures). (P-STD_buffer_bound_scale = 1)

    id (0xBF) private stream 2, NAV packs, set to 2x1024. */

    if (s->is_dvd) {

        int P_STD_max_video = 0;

        int P_STD_max_mpeg_audio = 0;

        int P_STD_max_mpeg_PS1 = 0;

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

            StreamInfo *stream = ctx->streams[i]->priv_data;

            id = stream->id;

            if (id == 0xbd && stream->max_buffer_size > P_STD_max_mpeg_PS1) {

                P_STD_max_mpeg_PS1 = stream->max_buffer_size;

            } else if (id >= 0xc0 && id <= 0xc7 && stream->max_buffer_size > P_STD_max_mpeg_audio) {

                P_STD_max_mpeg_audio = stream->max_buffer_size;

            } else if (id == 0xe0 && stream->max_buffer_size > P_STD_max_video) {

                P_STD_max_video = stream->max_buffer_size;

            }

        }

        /* video */

        put_bits(&pb, 8, 0xb9); /* stream ID */

        put_bits(&pb, 2, 3);

        put_bits(&pb, 1, 1);

        put_bits(&pb, 13, P_STD_max_video / 1024);

        /* audio */

        if (P_STD_max_mpeg_audio == 0)

            P_STD_max_mpeg_audio = 4096;

        put_bits(&pb, 8, 0xb8); /* stream ID */

        put_bits(&pb, 2, 3);

        put_bits(&pb, 1, 0);

        put_bits(&pb, 13, P_STD_max_mpeg_audio / 128);

        /* private stream 1 */

        put_bits(&pb, 8, 0xbd); /* stream ID */

        put_bits(&pb, 2, 3);

        put_bits(&pb, 1, 0);

        put_bits(&pb, 13, P_STD_max_mpeg_PS1 / 128);

        /* private stream 2 */

        put_bits(&pb, 8, 0xbf); /* stream ID */

        put_bits(&pb, 2, 3);

        put_bits(&pb, 1, 1);

        put_bits(&pb, 13, 2);

    }

    else {

        /* audio stream info */

        private_stream_coded = 0;

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

            StreamInfo *stream = ctx->streams[i]->priv_data;

            /* For VCDs, only include the stream info for the stream

            that the pack which contains this system belongs to.

            (see VCD standard p. IV-7) */

            if ( !s->is_vcd || stream->id==only_for_stream_id

                || only_for_stream_id==0) {

                id = stream->id;

                if (id < 0xc0) {

                    /* special case for private streams (AC-3 uses that) */

                    if (private_stream_coded)

                        continue;

                    private_stream_coded = 1;

                    id = 0xbd;

                }

                put_bits(&pb, 8, id); /* stream ID */

                put_bits(&pb, 2, 3);

                if (id < 0xe0) {

                    /* audio */

                    put_bits(&pb, 1, 0);

                    put_bits(&pb, 13, stream->max_buffer_size / 128);

                } else {

                    /* video */

                    put_bits(&pb, 1, 1);

                    put_bits(&pb, 13, stream->max_buffer_size / 1024);

                }

            }

        }

    }

    flush_put_bits(&pb);

    size = put_bits_ptr(&pb) - pb.buf;

    /* patch packet size */

    buf[4] = (size - 6) >> 8;

    buf[5] = (size - 6) & 0xff;

    return size;

}


static int standard_decode_i_mbs(VC9Context *v)

{

    int x, y, ac_pred, cbpcy;

    /* Select ttmb table depending on pq */

    if (v->pq < 5) v->ttmb_vlc = &vc9_ttmb_vlc[0];

    else if (v->pq < 13) v->ttmb_vlc = &vc9_ttmb_vlc[1];

    else v->ttmb_vlc = &vc9_ttmb_vlc[2];

    for (y=0; y<v->height_mb; y++)

    {

        for (x=0; x<v->width_mb; x++)

        {

            cbpcy = get_vlc2(&v->gb, vc9_cbpcy_i_vlc.table,

                             VC9_CBPCY_I_VLC_BITS, 2);

            ac_pred = get_bits(&v->gb, 1);

            //Decode blocks from that mb wrt cbpcy

        }

    }

    return 0;

}


static void ff_h264_idct8_dc_add_mmx2(uint8_t *dst, int16_t *block, int stride)

{

    int dc = (block[0] + 32) >> 6;

    int y;

    __asm__ volatile(

        "movd          %0, %%mm0 \n\t"

        "pshufw $0, %%mm0, %%mm0 \n\t"

        "pxor       %%mm1, %%mm1 \n\t"

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

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

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

        ::"r"(dc)

    );

    for(y=2; y--; dst += 4*stride){

    __asm__ volatile(

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

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

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

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

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

        "paddusb    %%mm0, %%mm3 \n\t"

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

        "paddusb    %%mm0, %%mm5 \n\t"

        "psubusb    %%mm1, %%mm2 \n\t"

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

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

        "psubusb    %%mm1, %%mm5 \n\t"

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

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

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

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

        :"+m"(*(uint64_t*)(dst+0*stride)),

         "+m"(*(uint64_t*)(dst+1*stride)),

         "+m"(*(uint64_t*)(dst+2*stride)),

         "+m"(*(uint64_t*)(dst+3*stride))

    );

    }

}


static int movie_get_frame(AVFilterLink *outlink)

{

    MovieContext *movie = outlink->src->priv;

    AVPacket pkt;

    int ret, frame_decoded;

    AVStream *st = movie->format_ctx->streams[movie->stream_index];

    if (movie->is_done == 1)

        return 0;

    while ((ret = av_read_frame(movie->format_ctx, &pkt)) >= 0) {

        // Is this a packet from the video stream?

        if (pkt.stream_index == movie->stream_index) {

            avcodec_decode_video2(movie->codec_ctx, movie->frame, &frame_decoded, &pkt);

            if (frame_decoded) {

                /* FIXME: avoid the memcpy */

                movie->picref = avfilter_get_video_buffer(outlink, AV_PERM_WRITE | AV_PERM_PRESERVE |

                                                          AV_PERM_REUSE2, outlink->w, outlink->h);

                av_image_copy(movie->picref->data, movie->picref->linesize,

                              (void*)movie->frame->data,  movie->frame->linesize,

                              movie->picref->format, outlink->w, outlink->h);

                avfilter_copy_frame_props(movie->picref, movie->frame);

                /* FIXME: use a PTS correction mechanism as that in

                 * ffplay.c when some API will be available for that */

                /* use pkt_dts if pkt_pts is not available */

                movie->picref->pts = movie->frame->pkt_pts == AV_NOPTS_VALUE ?

                    movie->frame->pkt_dts : movie->frame->pkt_pts;

                if (!movie->frame->sample_aspect_ratio.num)

                    movie->picref->video->sample_aspect_ratio = st->sample_aspect_ratio;

                av_dlog(outlink->src,

                        "movie_get_frame(): file:'%s' pts:%"PRId64" time:%lf pos:%"PRId64" aspect:%d/%d\n",

                        movie->file_name, movie->picref->pts,

                        (double)movie->picref->pts * av_q2d(st->time_base),

                        movie->picref->pos,

                        movie->picref->video->sample_aspect_ratio.num,

                        movie->picref->video->sample_aspect_ratio.den);

                // We got it. Free the packet since we are returning

                av_free_packet(&pkt);

                return 0;

            }

        }

        // Free the packet that was allocated by av_read_frame

        av_free_packet(&pkt);

    }

    // On multi-frame source we should stop the mixing process when

    // the movie source does not have more frames

    if (ret == AVERROR_EOF)

        movie->is_done = 1;

    return ret;

}


static void do_io_interrupt(CPUS390XState *env)

{

    S390CPU *cpu = s390_env_get_cpu(env);

    LowCore *lowcore;

    IOIntQueue *q;

    uint8_t isc;

    int disable = 1;

    int found = 0;

    if (!(env->psw.mask & PSW_MASK_IO)) {

        cpu_abort(CPU(cpu), "I/O int w/o I/O mask\n");

    }

    for (isc = 0; isc < ARRAY_SIZE(env->io_index); isc++) {

        uint64_t isc_bits;

        if (env->io_index[isc] < 0) {

            continue;

        }

        if (env->io_index[isc] > MAX_IO_QUEUE) {

            cpu_abort(CPU(cpu), "I/O queue overrun for isc %d: %d\n",

                      isc, env->io_index[isc]);

        }

        q = &env->io_queue[env->io_index[isc]][isc];

        isc_bits = ISC_TO_ISC_BITS(IO_INT_WORD_ISC(q->word));

        if (!(env->cregs[6] & isc_bits)) {

            disable = 0;

            continue;

        }

        if (!found) {

            uint64_t mask, addr;

            found = 1;

            lowcore = cpu_map_lowcore(env);

            lowcore->subchannel_id = cpu_to_be16(q->id);

            lowcore->subchannel_nr = cpu_to_be16(q->nr);

            lowcore->io_int_parm = cpu_to_be32(q->parm);

            lowcore->io_int_word = cpu_to_be32(q->word);

            lowcore->io_old_psw.mask = cpu_to_be64(get_psw_mask(env));

            lowcore->io_old_psw.addr = cpu_to_be64(env->psw.addr);

            mask = be64_to_cpu(lowcore->io_new_psw.mask);

            addr = be64_to_cpu(lowcore->io_new_psw.addr);

            cpu_unmap_lowcore(lowcore);

            env->io_index[isc]--;

            DPRINTF("%s: %" PRIx64 " %" PRIx64 "\n", __func__,

                    env->psw.mask, env->psw.addr);

            load_psw(env, mask, addr);

        }

        if (env->io_index[isc] >= 0) {

            disable = 0;

        }

        continue;

    }

    if (disable) {

        env->pending_int &= ~INTERRUPT_IO;

    }

}


static int rtp_new_av_stream(HTTPContext *c,

                             int stream_index, struct sockaddr_in *dest_addr,

                             HTTPContext *rtsp_c)

{

    AVFormatContext *ctx;

    AVStream *st;

    char *ipaddr;

    URLContext *h = NULL;

    uint8_t *dummy_buf;

    int max_packet_size;

    /* now we can open the relevant output stream */

    ctx = avformat_alloc_context();

    if (!ctx)

        return -1;

    ctx->oformat = av_guess_format("rtp", NULL, NULL);

    st = av_mallocz(sizeof(AVStream));

    if (!st)

        goto fail;

    st->codec= avcodec_alloc_context();

    ctx->nb_streams = 1;

    ctx->streams[0] = st;

    if (!c->stream->feed ||

        c->stream->feed == c->stream)

        memcpy(st, c->stream->streams[stream_index], sizeof(AVStream));

    else

        memcpy(st,

               c->stream->feed->streams[c->stream->feed_streams[stream_index]],

               sizeof(AVStream));

    st->priv_data = NULL;

    /* build destination RTP address */

    ipaddr = inet_ntoa(dest_addr->sin_addr);

    switch(c->rtp_protocol) {

    case RTSP_LOWER_TRANSPORT_UDP:

    case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:

        /* RTP/UDP case */

        /* XXX: also pass as parameter to function ? */

        if (c->stream->is_multicast) {

            int ttl;

            ttl = c->stream->multicast_ttl;

            if (!ttl)

                ttl = 16;

            snprintf(ctx->filename, sizeof(ctx->filename),

                     "rtp://%s:%d?multicast=1&ttl=%d",

                     ipaddr, ntohs(dest_addr->sin_port), ttl);

        } else {

            snprintf(ctx->filename, sizeof(ctx->filename),

                     "rtp://%s:%d", ipaddr, ntohs(dest_addr->sin_port));

        }

        if (url_open(&h, ctx->filename, URL_WRONLY) < 0)

            goto fail;

        c->rtp_handles[stream_index] = h;

        max_packet_size = url_get_max_packet_size(h);

        break;

    case RTSP_LOWER_TRANSPORT_TCP:

        /* RTP/TCP case */

        c->rtsp_c = rtsp_c;

        max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;

        break;

    default:

        goto fail;

    }

    http_log("%s:%d - - \"PLAY %s/streamid=%d %s\"\n",

             ipaddr, ntohs(dest_addr->sin_port),

             c->stream->filename, stream_index, c->protocol);

    /* normally, no packets should be output here, but the packet size may be checked */

    if (url_open_dyn_packet_buf(&ctx->pb, max_packet_size) < 0) {

        /* XXX: close stream */

        goto fail;

    }

    av_set_parameters(ctx, NULL);

    if (av_write_header(ctx) < 0) {

    fail:

        if (h)

            url_close(h);

        av_free(ctx);

        return -1;

    }

    url_close_dyn_buf(ctx->pb, &dummy_buf);

    av_free(dummy_buf);

    c->rtp_ctx[stream_index] = ctx;

    return 0;

}


void unix_start_outgoing_migration(MigrationState *s, const char *path, Error **errp)

{

    unix_nonblocking_connect(path, unix_wait_for_connect, s, errp);

}


static void *mptsas_load_request(QEMUFile *f, SCSIRequest *sreq)

{

    SCSIBus *bus = sreq->bus;

    MPTSASState *s = container_of(bus, MPTSASState, bus);

    PCIDevice *pci = PCI_DEVICE(s);

    MPTSASRequest *req;

    int i, n;

    req = g_new(MPTSASRequest, 1);

    qemu_get_buffer(f, (unsigned char *)&req->scsi_io, sizeof(req->scsi_io));

    n = qemu_get_be32(f);

    /* TODO: add a way for SCSIBusInfo's load_request to fail,

     * and fail migration instead of asserting here.

     * When we do, we might be able to re-enable NDEBUG below.

     */

#ifdef NDEBUG

#error building with NDEBUG is not supported

#endif

    assert(n >= 0);

    pci_dma_sglist_init(&req->qsg, pci, n);

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

        uint64_t base = qemu_get_be64(f);

        uint64_t len = qemu_get_be64(f);

        qemu_sglist_add(&req->qsg, base, len);

    }

    scsi_req_ref(sreq);

    req->sreq = sreq;

    req->dev = s;

    return req;

}


static int dvbsub_parse_clut_segment(AVCodecContext *avctx,

                                     const uint8_t *buf, int buf_size)

{

    DVBSubContext *ctx = avctx->priv_data;

    const uint8_t *buf_end = buf + buf_size;

    int i, clut_id;

    int version;

    DVBSubCLUT *clut;

    int entry_id, depth , full_range;

    int y, cr, cb, alpha;

    int r, g, b, r_add, g_add, b_add;

    ff_dlog(avctx, "DVB clut packet:\n");

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

        ff_dlog(avctx, "%02x ", buf[i]);

        if (i % 16 == 15)

            ff_dlog(avctx, "\n");

    }

    if (i % 16)

        ff_dlog(avctx, "\n");

    clut_id = *buf++;

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

    buf += 1;

    clut = get_clut(ctx, clut_id);

    if (!clut) {

        clut = av_malloc(sizeof(DVBSubCLUT));

        if (!clut)

            return AVERROR(ENOMEM);

        memcpy(clut, &default_clut, sizeof(DVBSubCLUT));

        clut->id = clut_id;

        clut->version = -1;

        clut->next = ctx->clut_list;

        ctx->clut_list = clut;

    }

    if (clut->version != version) {

    clut->version = version;

    while (buf + 4 < buf_end) {

        entry_id = *buf++;

        depth = (*buf) & 0xe0;

        if (depth == 0) {

            av_log(avctx, AV_LOG_ERROR, "Invalid clut depth 0x%x!\n", *buf);

        }

        full_range = (*buf++) & 1;

        if (full_range) {

            y = *buf++;

            cr = *buf++;

            cb = *buf++;

            alpha = *buf++;

        } else {

            y = buf[0] & 0xfc;

            cr = (((buf[0] & 3) << 2) | ((buf[1] >> 6) & 3)) << 4;

            cb = (buf[1] << 2) & 0xf0;

            alpha = (buf[1] << 6) & 0xc0;

            buf += 2;

        }

        if (y == 0)

            alpha = 0xff;

        YUV_TO_RGB1_CCIR(cb, cr);

        YUV_TO_RGB2_CCIR(r, g, b, y);

        ff_dlog(avctx, "clut %d := (%d,%d,%d,%d)\n", entry_id, r, g, b, alpha);

        if (!!(depth & 0x80) + !!(depth & 0x40) + !!(depth & 0x20) > 1) {

            ff_dlog(avctx, "More than one bit level marked: %x\n", depth);

            if (avctx->strict_std_compliance > FF_COMPLIANCE_NORMAL)

                return AVERROR_INVALIDDATA;

        }

        if (depth & 0x80)

            clut->clut4[entry_id] = RGBA(r,g,b,255 - alpha);

        else if (depth & 0x40)

            clut->clut16[entry_id] = RGBA(r,g,b,255 - alpha);

        else if (depth & 0x20)

            clut->clut256[entry_id] = RGBA(r,g,b,255 - alpha);

    }

    }

    return 0;

}


VLANClientState *qemu_new_vlan_client(VLANState *vlan,

                                      IOReadHandler *fd_read, void *opaque)

{

    VLANClientState *vc, **pvc;

    vc = qemu_mallocz(sizeof(VLANClientState));

    if (!vc)

        return NULL;

    vc->fd_read = fd_read;

    vc->opaque = opaque;

    vc->vlan = vlan;

    vc->next = NULL;

    pvc = &vlan->first_client;

    while (*pvc != NULL)

        pvc = &(*pvc)->next;

    *pvc = vc;

    return vc;

}


static void unterminated_escape(void)

{

    QObject *obj = qobject_from_json("\"abc\\\"", NULL);

    g_assert(obj == NULL);

}


struct omap_gpmc_s *omap_gpmc_init(struct omap_mpu_state_s *mpu,

                                   hwaddr base,

                                   qemu_irq irq, qemu_irq drq)

{

    int cs;

    struct omap_gpmc_s *s = (struct omap_gpmc_s *)

            g_malloc0(sizeof(struct omap_gpmc_s));

    memory_region_init_io(&s->iomem, NULL, &omap_gpmc_ops, s, "omap-gpmc", 0x1000);

    memory_region_add_subregion(get_system_memory(), base, &s->iomem);

    s->irq = irq;

    s->drq = drq;

    s->accept_256 = cpu_is_omap3630(mpu);

    s->revision = cpu_class_omap3(mpu) ? 0x50 : 0x20;

    s->lastirq = 0;

    omap_gpmc_reset(s);

    /* We have to register a different IO memory handler for each

     * chip select region in case a NAND device is mapped there. We

     * make the region the worst-case size of 256MB and rely on the

     * container memory region in cs_map to chop it down to the actual

     * guest-requested size.

     */

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

        memory_region_init_io(&s->cs_file[cs].nandiomem, NULL,

                              &omap_nand_ops,

                              &s->cs_file[cs],

                              "omap-nand",

                              256 * 1024 * 1024);

    }

    memory_region_init_io(&s->prefetch.iomem, NULL, &omap_prefetch_ops, s,

                          "omap-gpmc-prefetch", 256 * 1024 * 1024);

    return s;

}


bool trace_backend_init(const char *events, const char *file)

{

    GThread *thread;

    if (!g_thread_supported()) {

        g_thread_init(NULL);

    }

    trace_available_cond = g_cond_new();

    trace_empty_cond = g_cond_new();

    thread = trace_thread_create(writeout_thread);

    if (!thread) {

        fprintf(stderr, "warning: unable to initialize simple trace backend\n");

        return false;

    }

    atexit(st_flush_trace_buffer);

    trace_backend_init_events(events);

    st_set_trace_file(file);

    return true;

}


static inline void vc1_pred_mv_intfr(VC1Context *v, int n, int dmv_x, int dmv_y,

                                     int mvn, int r_x, int r_y, uint8_t* is_intra)

{

    MpegEncContext *s = &v->s;

    int xy, wrap, off = 0;

    int A[2], B[2], C[2];

    int px, py;

    int a_valid = 0, b_valid = 0, c_valid = 0;

    int field_a, field_b, field_c; // 0: same, 1: opposit

    int total_valid, num_samefield, num_oppfield;

    int pos_c, pos_b, n_adj;

    wrap = s->b8_stride;

    xy = s->block_index[n];

    if (s->mb_intra) {

        s->mv[0][n][0] = s->current_picture.f.motion_val[0][xy][0] = 0;

        s->mv[0][n][1] = s->current_picture.f.motion_val[0][xy][1] = 0;

        s->current_picture.f.motion_val[1][xy][0] = 0;

        s->current_picture.f.motion_val[1][xy][1] = 0;

        if (mvn == 1) { /* duplicate motion data for 1-MV block */

            s->current_picture.f.motion_val[0][xy + 1][0]        = 0;

            s->current_picture.f.motion_val[0][xy + 1][1]        = 0;

            s->current_picture.f.motion_val[0][xy + wrap][0]     = 0;

            s->current_picture.f.motion_val[0][xy + wrap][1]     = 0;

            s->current_picture.f.motion_val[0][xy + wrap + 1][0] = 0;

            s->current_picture.f.motion_val[0][xy + wrap + 1][1] = 0;

            v->luma_mv[s->mb_x][0] = v->luma_mv[s->mb_x][1] = 0;

            s->current_picture.f.motion_val[1][xy + 1][0]        = 0;

            s->current_picture.f.motion_val[1][xy + 1][1]        = 0;

            s->current_picture.f.motion_val[1][xy + wrap][0]     = 0;

            s->current_picture.f.motion_val[1][xy + wrap][1]     = 0;

            s->current_picture.f.motion_val[1][xy + wrap + 1][0] = 0;

            s->current_picture.f.motion_val[1][xy + wrap + 1][1] = 0;

        }

        return;

    }

    off = ((n == 0) || (n == 1)) ? 1 : -1;

    /* predict A */

    if (s->mb_x || (n == 1) || (n == 3)) {

        if ((v->blk_mv_type[xy]) // current block (MB) has a field MV

            || (!v->blk_mv_type[xy] && !v->blk_mv_type[xy - 1])) { // or both have frame MV

            A[0] = s->current_picture.f.motion_val[0][xy - 1][0];

            A[1] = s->current_picture.f.motion_val[0][xy - 1][1];

            a_valid = 1;

        } else { // current block has frame mv and cand. has field MV (so average)

            A[0] = (s->current_picture.f.motion_val[0][xy - 1][0]

                    + s->current_picture.f.motion_val[0][xy - 1 + off * wrap][0] + 1) >> 1;

            A[1] = (s->current_picture.f.motion_val[0][xy - 1][1]

                    + s->current_picture.f.motion_val[0][xy - 1 + off * wrap][1] + 1) >> 1;

            a_valid = 1;

        }

        if (!(n & 1) && v->is_intra[s->mb_x - 1]) {

            a_valid = 0;

            A[0] = A[1] = 0;

        }

    } else

        A[0] = A[1] = 0;

    /* Predict B and C */

    B[0] = B[1] = C[0] = C[1] = 0;

    if (n == 0 || n == 1 || v->blk_mv_type[xy]) {

        if (!s->first_slice_line) {

            if (!v->is_intra[s->mb_x - s->mb_stride]) {

                b_valid = 1;

                n_adj   = n | 2;

                pos_b   = s->block_index[n_adj] - 2 * wrap;

                if (v->blk_mv_type[pos_b] && v->blk_mv_type[xy]) {

                    n_adj = (n & 2) | (n & 1);

                }

                B[0] = s->current_picture.f.motion_val[0][s->block_index[n_adj] - 2 * wrap][0];

                B[1] = s->current_picture.f.motion_val[0][s->block_index[n_adj] - 2 * wrap][1];

                if (v->blk_mv_type[pos_b] && !v->blk_mv_type[xy]) {

                    B[0] = (B[0] + s->current_picture.f.motion_val[0][s->block_index[n_adj ^ 2] - 2 * wrap][0] + 1) >> 1;

                    B[1] = (B[1] + s->current_picture.f.motion_val[0][s->block_index[n_adj ^ 2] - 2 * wrap][1] + 1) >> 1;

                }

            }

            if (s->mb_width > 1) {

                if (!v->is_intra[s->mb_x - s->mb_stride + 1]) {

                    c_valid = 1;

                    n_adj   = 2;

                    pos_c   = s->block_index[2] - 2 * wrap + 2;

                    if (v->blk_mv_type[pos_c] && v->blk_mv_type[xy]) {

                        n_adj = n & 2;

                    }

                    C[0] = s->current_picture.f.motion_val[0][s->block_index[n_adj] - 2 * wrap + 2][0];

                    C[1] = s->current_picture.f.motion_val[0][s->block_index[n_adj] - 2 * wrap + 2][1];

                    if (v->blk_mv_type[pos_c] && !v->blk_mv_type[xy]) {

                        C[0] = (1 + C[0] + (s->current_picture.f.motion_val[0][s->block_index[n_adj ^ 2] - 2 * wrap + 2][0])) >> 1;

                        C[1] = (1 + C[1] + (s->current_picture.f.motion_val[0][s->block_index[n_adj ^ 2] - 2 * wrap + 2][1])) >> 1;

                    }

                    if (s->mb_x == s->mb_width - 1) {

                        if (!v->is_intra[s->mb_x - s->mb_stride - 1]) {

                            c_valid = 1;

                            n_adj   = 3;

                            pos_c   = s->block_index[3] - 2 * wrap - 2;

                            if (v->blk_mv_type[pos_c] && v->blk_mv_type[xy]) {

                                n_adj = n | 1;

                            }

                            C[0] = s->current_picture.f.motion_val[0][s->block_index[n_adj] - 2 * wrap - 2][0];

                            C[1] = s->current_picture.f.motion_val[0][s->block_index[n_adj] - 2 * wrap - 2][1];

                            if (v->blk_mv_type[pos_c] && !v->blk_mv_type[xy]) {

                                C[0] = (1 + C[0] + s->current_picture.f.motion_val[0][s->block_index[1] - 2 * wrap - 2][0]) >> 1;

                                C[1] = (1 + C[1] + s->current_picture.f.motion_val[0][s->block_index[1] - 2 * wrap - 2][1]) >> 1;

                            }

                        } else

                            c_valid = 0;

                    }

                }

            }

        }

    } else {

        pos_b   = s->block_index[1];

        b_valid = 1;

        B[0]    = s->current_picture.f.motion_val[0][pos_b][0];

        B[1]    = s->current_picture.f.motion_val[0][pos_b][1];

        pos_c   = s->block_index[0];

        c_valid = 1;

        C[0]    = s->current_picture.f.motion_val[0][pos_c][0];

        C[1]    = s->current_picture.f.motion_val[0][pos_c][1];

    }

    total_valid = a_valid + b_valid + c_valid;

    // check if predictor A is out of bounds

    if (!s->mb_x && !(n == 1 || n == 3)) {

        A[0] = A[1] = 0;

    }

    // check if predictor B is out of bounds

    if ((s->first_slice_line && v->blk_mv_type[xy]) || (s->first_slice_line && !(n & 2))) {

        B[0] = B[1] = C[0] = C[1] = 0;

    }

    if (!v->blk_mv_type[xy]) {

        if (s->mb_width == 1) {

            px = B[0];

            py = B[1];

        } else {

            if (total_valid >= 2) {

                px = mid_pred(A[0], B[0], C[0]);

                py = mid_pred(A[1], B[1], C[1]);

            } else if (total_valid) {

                if (a_valid) { px = A[0]; py = A[1]; }

                if (b_valid) { px = B[0]; py = B[1]; }

                if (c_valid) { px = C[0]; py = C[1]; }

            } else

                px = py = 0;

        }

    } else {

        if (a_valid)

            field_a = (A[1] & 4) ? 1 : 0;

        else

            field_a = 0;

        if (b_valid)

            field_b = (B[1] & 4) ? 1 : 0;

        else

            field_b = 0;

        if (c_valid)

            field_c = (C[1] & 4) ? 1 : 0;

        else

            field_c = 0;

        num_oppfield  = field_a + field_b + field_c;

        num_samefield = total_valid - num_oppfield;

        if (total_valid == 3) {

            if ((num_samefield == 3) || (num_oppfield == 3)) {

                px = mid_pred(A[0], B[0], C[0]);

                py = mid_pred(A[1], B[1], C[1]);

            } else if (num_samefield >= num_oppfield) {

                /* take one MV from same field set depending on priority

                the check for B may not be necessary */

                px = !field_a ? A[0] : B[0];

                py = !field_a ? A[1] : B[1];

            } else {

                px =  field_a ? A[0] : B[0];

                py =  field_a ? A[1] : B[1];

            }

        } else if (total_valid == 2) {

            if (num_samefield >= num_oppfield) {

                if (!field_a && a_valid) {

                    px = A[0];

                    py = A[1];

                } else if (!field_b && b_valid) {

                    px = B[0];

                    py = B[1];

                } else if (c_valid) {

                    px = C[0];

                    py = C[1];

                } else px = py = 0;

            } else {

                if (field_a && a_valid) {

                    px = A[0];

                    py = A[1];

                } else if (field_b && b_valid) {

                    px = B[0];

                    py = B[1];

                } else if (c_valid) {

                    px = C[0];

                    py = C[1];

                } else px = py = 0;

            }

        } else if (total_valid == 1) {

            px = (a_valid) ? A[0] : ((b_valid) ? B[0] : C[0]);

            py = (a_valid) ? A[1] : ((b_valid) ? B[1] : C[1]);

        } else

            px = py = 0;

    }

    /* store MV using signed modulus of MV range defined in 4.11 */

    s->mv[0][n][0] = s->current_picture.f.motion_val[0][xy][0] = ((px + dmv_x + r_x) & ((r_x << 1) - 1)) - r_x;

    s->mv[0][n][1] = s->current_picture.f.motion_val[0][xy][1] = ((py + dmv_y + r_y) & ((r_y << 1) - 1)) - r_y;

    if (mvn == 1) { /* duplicate motion data for 1-MV block */

        s->current_picture.f.motion_val[0][xy +    1    ][0] = s->current_picture.f.motion_val[0][xy][0];

        s->current_picture.f.motion_val[0][xy +    1    ][1] = s->current_picture.f.motion_val[0][xy][1];

        s->current_picture.f.motion_val[0][xy + wrap    ][0] = s->current_picture.f.motion_val[0][xy][0];

        s->current_picture.f.motion_val[0][xy + wrap    ][1] = s->current_picture.f.motion_val[0][xy][1];

        s->current_picture.f.motion_val[0][xy + wrap + 1][0] = s->current_picture.f.motion_val[0][xy][0];

        s->current_picture.f.motion_val[0][xy + wrap + 1][1] = s->current_picture.f.motion_val[0][xy][1];

    } else if (mvn == 2) { /* duplicate motion data for 2-Field MV block */

        s->current_picture.f.motion_val[0][xy + 1][0] = s->current_picture.f.motion_val[0][xy][0];

        s->current_picture.f.motion_val[0][xy + 1][1] = s->current_picture.f.motion_val[0][xy][1];

        s->mv[0][n + 1][0] = s->mv[0][n][0];

        s->mv[0][n + 1][1] = s->mv[0][n][1];

    }

}


ip_reass(register struct ip *ip, register struct ipq *fp)

{

	register struct mbuf *m = dtom(ip);

	register struct ipasfrag *q;

	int hlen = ip->ip_hl << 2;

	int i, next;

	DEBUG_CALL("ip_reass");

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

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

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

	/*

	 * Presence of header sizes in mbufs

	 * would confuse code below.

         * Fragment m_data is concatenated.

	 */

	m->m_data += hlen;

	m->m_len -= hlen;

	/*

	 * If first fragment to arrive, create a reassembly queue.

	 */

	if (fp == 0) {

	  struct mbuf *t;

	  if ((t = m_get()) == NULL) goto dropfrag;

	  fp = mtod(t, struct ipq *);

	  insque(&fp->ip_link, &ipq.ip_link);

	  fp->ipq_ttl = IPFRAGTTL;

	  fp->ipq_p = ip->ip_p;

	  fp->ipq_id = ip->ip_id;

	  fp->frag_link.next = fp->frag_link.prev = &fp->frag_link;

	  fp->ipq_src = ip->ip_src;

	  fp->ipq_dst = ip->ip_dst;

	  q = (struct ipasfrag *)fp;

	  goto insert;

	}

	/*

	 * Find a segment which begins after this one does.

	 */

	for (q = fp->frag_link.next; q != (struct ipasfrag *)&fp->frag_link;

            q = q->ipf_next)

		if (q->ipf_off > ip->ip_off)

			break;

	/*

	 * If there is a preceding segment, it may provide some of

	 * our data already.  If so, drop the data from the incoming

	 * segment.  If it provides all of our data, drop us.

	 */

	if (q->ipf_prev != &fp->frag_link) {

        struct ipasfrag *pq = q->ipf_prev;

		i = pq->ipf_off + pq->ipf_len - ip->ip_off;

		if (i > 0) {

			if (i >= ip->ip_len)

				goto dropfrag;

			m_adj(dtom(ip), i);

			ip->ip_off += i;

			ip->ip_len -= i;

		}

	}

	/*

	 * While we overlap succeeding segments trim them or,

	 * if they are completely covered, dequeue them.

	 */

	while (q != (struct ipasfrag*)&fp->frag_link &&

            ip->ip_off + ip->ip_len > q->ipf_off) {

		i = (ip->ip_off + ip->ip_len) - q->ipf_off;

		if (i < q->ipf_len) {

			q->ipf_len -= i;

			q->ipf_off += i;

			m_adj(dtom(q), i);

			break;

		}

		q = q->ipf_next;

		m_freem(dtom(q->ipf_prev));

		ip_deq(q->ipf_prev);

	}

insert:

	/*

	 * Stick new segment in its place;

	 * check for complete reassembly.

	 */

	ip_enq(iptofrag(ip), q->ipf_prev);

	next = 0;

	for (q = fp->frag_link.next; q != (struct ipasfrag*)&fp->frag_link;

            q = q->ipf_next) {

		if (q->ipf_off != next)

			return (0);

		next += q->ipf_len;

	}

	if (((struct ipasfrag *)(q->ipf_prev))->ipf_tos & 1)

		return (0);

	/*

	 * Reassembly is complete; concatenate fragments.

	 */

    q = fp->frag_link.next;

	m = dtom(q);

	q = (struct ipasfrag *) q->ipf_next;

	while (q != (struct ipasfrag*)&fp->frag_link) {

	  struct mbuf *t = dtom(q);

	  q = (struct ipasfrag *) q->ipf_next;

	  m_cat(m, t);

	}

	/*

	 * Create header for new ip packet by

	 * modifying header of first packet;

	 * dequeue and discard fragment reassembly header.

	 * Make header visible.

	 */

	q = fp->frag_link.next;

	/*

	 * If the fragments concatenated to an mbuf that's

	 * bigger than the total size of the fragment, then and

	 * m_ext buffer was alloced. But fp->ipq_next points to

	 * the old buffer (in the mbuf), so we must point ip

	 * into the new buffer.

	 */

	if (m->m_flags & M_EXT) {

	  int delta;

	  delta = (char *)ip - m->m_dat;

	  q = (struct ipasfrag *)(m->m_ext + delta);

	}

	/* DEBUG_ARG("ip = %lx", (long)ip);

	 * ip=(struct ipasfrag *)m->m_data; */

    ip = fragtoip(q);

	ip->ip_len = next;

	ip->ip_tos &= ~1;

	ip->ip_src = fp->ipq_src;

	ip->ip_dst = fp->ipq_dst;

	remque(&fp->ip_link);

	(void) m_free(dtom(fp));

	m->m_len += (ip->ip_hl << 2);

	m->m_data -= (ip->ip_hl << 2);

	return ip;

dropfrag:

	STAT(ipstat.ips_fragdropped++);

	m_freem(m);

	return (0);

}


static void qtrle_encode_line(QtrleEncContext *s, AVFrame *p, int line, uint8_t **buf)

{

    int width=s->logical_width;

    int i;

    signed char rlecode;

    /* We will use it to compute the best bulk copy sequence */

    unsigned int bulkcount;

    /* This will be the number of pixels equal to the preivous frame one's

     * starting from the ith pixel */

    unsigned int skipcount;

    /* This will be the number of consecutive equal pixels in the current

     * frame, starting from the ith one also */

    unsigned int repeatcount;

    /* The cost of the three different possibilities */

    int total_bulk_cost;

    int total_skip_cost;

    int total_repeat_cost;

    int temp_cost;

    int j;

    uint8_t *this_line = p->               data[0] + line*p->               linesize[0] +

        (width - 1)*s->pixel_size;

    uint8_t *prev_line = s->previous_frame.data[0] + line*s->previous_frame.linesize[0] +

        (width - 1)*s->pixel_size;

    s->length_table[width] = 0;

    skipcount = 0;

    for (i = width - 1; i >= 0; i--) {

        if (!s->frame.key_frame && !memcmp(this_line, prev_line, s->pixel_size))

            skipcount = FFMIN(skipcount + 1, MAX_RLE_SKIP);

        else

            skipcount = 0;

        total_skip_cost  = s->length_table[i + skipcount] + 2;

        s->skip_table[i] = skipcount;

        if (i < width - 1 && !memcmp(this_line, this_line + s->pixel_size, s->pixel_size))

            repeatcount = FFMIN(repeatcount + 1, MAX_RLE_REPEAT);

        else

            repeatcount = 1;

        total_repeat_cost = s->length_table[i + repeatcount] + 1 + s->pixel_size;

        /* skip code is free for the first pixel, it costs one byte for repeat and bulk copy

         * so let's make it aware */

        if (i == 0) {

            total_skip_cost--;

            total_repeat_cost++;

        }

        if (repeatcount > 1 && (skipcount == 0 || total_repeat_cost < total_skip_cost)) {

            /* repeat is the best */

            s->length_table[i]  = total_repeat_cost;

            s->rlecode_table[i] = -repeatcount;

        }

        else if (skipcount > 0) {

            /* skip is the best choice here */

            s->length_table[i]  = total_skip_cost;

            s->rlecode_table[i] = 0;

        }

        else {

            /* We cannot do neither skip nor repeat

             * thus we search for the best bulk copy to do */

            int limit = FFMIN(width - i, MAX_RLE_BULK);

            temp_cost = 1 + s->pixel_size + !i;

            total_bulk_cost = INT_MAX;

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

                if (s->length_table[i + j] + temp_cost < total_bulk_cost) {

                    /* We have found a better bulk copy ... */

                    total_bulk_cost = s->length_table[i + j] + temp_cost;

                    bulkcount = j;

                }

                temp_cost += s->pixel_size;

            }

            s->length_table[i]  = total_bulk_cost;

            s->rlecode_table[i] = bulkcount;

        }

        this_line -= s->pixel_size;

        prev_line -= s->pixel_size;

    }

    /* Good ! Now we have the best sequence for this line, let's output it */

    /* We do a special case for the first pixel so that we avoid testing it in

     * the whole loop */

    i=0;

    this_line = p->               data[0] + line*p->linesize[0];

    if (s->rlecode_table[0] == 0) {

        bytestream_put_byte(buf, s->skip_table[0] + 1);

        i += s->skip_table[0];

    }

    else bytestream_put_byte(buf, 1);

    while (i < width) {

        rlecode = s->rlecode_table[i];

        bytestream_put_byte(buf, rlecode);

        if (rlecode == 0) {

            /* Write a skip sequence */

            bytestream_put_byte(buf, s->skip_table[i] + 1);

            i += s->skip_table[i];

        }

        else if (rlecode > 0) {

            /* bulk copy */

            if (s->avctx->pix_fmt == PIX_FMT_GRAY8) {

                int j;

                // QT grayscale colorspace has 0=white and 255=black, we will

                // ignore the palette that is included in the AVFrame because

                // PIX_FMT_GRAY8 has defined color mapping

                for (j = 0; j < rlecode*s->pixel_size; ++j)

                    bytestream_put_byte(buf, *(this_line + i*s->pixel_size + j) ^ 0xff);

            } else {

                bytestream_put_buffer(buf, this_line + i*s->pixel_size, rlecode*s->pixel_size);

            }

            i += rlecode;

        }

        else {

            /* repeat the bits */

            if (s->avctx->pix_fmt == PIX_FMT_GRAY8) {

                int j;

                // QT grayscale colorspace has 0=white and 255=black, ...

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

                    bytestream_put_byte(buf, *(this_line + i*s->pixel_size + j) ^ 0xff);

            } else {

                bytestream_put_buffer(buf, this_line + i*s->pixel_size, s->pixel_size);

            }

            i -= rlecode;

        }

    }

    bytestream_put_byte(buf, -1); // end RLE line

}


static void rv34_idct_add_c(uint8_t *dst, ptrdiff_t stride, DCTELEM *block){

    int      temp[16];

    uint8_t *cm = ff_cropTbl + MAX_NEG_CROP;

    int      i;

    rv34_row_transform(temp, block);

    memset(block, 0, 16*sizeof(DCTELEM));

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

        const int z0 = 13*(temp[4*0+i] +    temp[4*2+i]) + 0x200;

        const int z1 = 13*(temp[4*0+i] -    temp[4*2+i]) + 0x200;

        const int z2 =  7* temp[4*1+i] - 17*temp[4*3+i];

        const int z3 = 17* temp[4*1+i] +  7*temp[4*3+i];

        dst[0] = cm[ dst[0] + ( (z0 + z3) >> 10 ) ];

        dst[1] = cm[ dst[1] + ( (z1 + z2) >> 10 ) ];

        dst[2] = cm[ dst[2] + ( (z1 - z2) >> 10 ) ];

        dst[3] = cm[ dst[3] + ( (z0 - z3) >> 10 ) ];

        dst  += stride;

    }

}


int ff_lpc_calc_coefs(DSPContext *s,

                      const int32_t *samples, int blocksize, int min_order,

                      int max_order, int precision,

                      int32_t coefs[][MAX_LPC_ORDER], int *shift, int use_lpc,

                      int omethod, int max_shift, int zero_shift)

{

    double autoc[MAX_LPC_ORDER+1];

    double ref[MAX_LPC_ORDER];

    double lpc[MAX_LPC_ORDER][MAX_LPC_ORDER];

    int i, j, pass;

    int opt_order;

    assert(max_order >= MIN_LPC_ORDER && max_order <= MAX_LPC_ORDER && use_lpc > 0);

    if(use_lpc == 1){

        s->flac_compute_autocorr(samples, blocksize, max_order, autoc);

        compute_lpc_coefs(autoc, max_order, &lpc[0][0], MAX_LPC_ORDER, 0, 1);

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

            ref[i] = fabs(lpc[i][i]);

    }else{

        LLSModel m[2];

        double var[MAX_LPC_ORDER+1], weight;

        for(pass=0; pass<use_lpc-1; pass++){

            av_init_lls(&m[pass&1], max_order);

            weight=0;

            for(i=max_order; i<blocksize; i++){

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

                    var[j]= samples[i-j];

                if(pass){

                    double eval, inv, rinv;

                    eval= av_evaluate_lls(&m[(pass-1)&1], var+1, max_order-1);

                    eval= (512>>pass) + fabs(eval - var[0]);

                    inv = 1/eval;

                    rinv = sqrt(inv);

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

                        var[j] *= rinv;

                    weight += inv;

                }else

                    weight++;

                av_update_lls(&m[pass&1], var, 1.0);

            }

            av_solve_lls(&m[pass&1], 0.001, 0);

        }

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

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

                lpc[i][j]=-m[(pass-1)&1].coeff[i][j];

            ref[i]= sqrt(m[(pass-1)&1].variance[i] / weight) * (blocksize - max_order) / 4000;

        }

        for(i=max_order-1; i>0; i--)

            ref[i] = ref[i-1] - ref[i];

    }

    opt_order = max_order;

    if(omethod == ORDER_METHOD_EST) {

        opt_order = estimate_best_order(ref, min_order, max_order);

        i = opt_order-1;

        quantize_lpc_coefs(lpc[i], i+1, precision, coefs[i], &shift[i], max_shift, zero_shift);

    } else {

        for(i=min_order-1; i<max_order; i++) {

            quantize_lpc_coefs(lpc[i], i+1, precision, coefs[i], &shift[i], max_shift, zero_shift);

        }

    }

    return opt_order;

}


av_cold void ff_cavsdsp_init_x86(CAVSDSPContext *c, AVCodecContext *avctx)

{

    av_unused int cpu_flags = av_get_cpu_flags();

    cavsdsp_init_mmx(c, avctx);

#if HAVE_AMD3DNOW_INLINE

    if (INLINE_AMD3DNOW(cpu_flags))

        cavsdsp_init_3dnow(c, avctx);

#endif /* HAVE_AMD3DNOW_INLINE */

#if HAVE_MMXEXT_INLINE

    if (INLINE_MMXEXT(cpu_flags)) {

        DSPFUNC(put, 0, 16, mmxext);

        DSPFUNC(put, 1,  8, mmxext);

        DSPFUNC(avg, 0, 16, mmxext);

        DSPFUNC(avg, 1,  8, mmxext);

    }

#endif

#if HAVE_MMX_EXTERNAL

    if (EXTERNAL_MMXEXT(cpu_flags)) {

        c->avg_cavs_qpel_pixels_tab[0][0] = avg_cavs_qpel16_mc00_mmxext;

        c->avg_cavs_qpel_pixels_tab[1][0] = avg_cavs_qpel8_mc00_mmxext;

    }

#endif

#if HAVE_SSE2_EXTERNAL

    if (EXTERNAL_SSE2(cpu_flags)) {

        c->put_cavs_qpel_pixels_tab[0][0] = put_cavs_qpel16_mc00_sse2;

        c->avg_cavs_qpel_pixels_tab[0][0] = avg_cavs_qpel16_mc00_sse2;

    }

#endif

}


static bool object_create_initial(const char *type)
{
    if (g_str_equal(type, "rng-egd")) {
    /*
     * return false for concrete netfilters since
     * they depend on netdevs already existing
    if (g_str_equal(type, "filter-buffer") ||
        g_str_equal(type, "filter-dump") ||
        g_str_equal(type, "filter-mirror") ||
        g_str_equal(type, "filter-redirector")) {
    return true;


static int bochs_open(BlockDriverState *bs, QDict *options, int flags,

                      Error **errp)

{

    BDRVBochsState *s = bs->opaque;

    int i;

    struct bochs_header bochs;

    struct bochs_header_v1 header_v1;

    int ret;

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

    ret = bdrv_pread(bs->file, 0, &bochs, sizeof(bochs));

    if (ret < 0) {

        return ret;

    }

    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))) {

        error_setg(errp, "Image not in Bochs format");

        return -EINVAL;

    }

    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);

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

                     s->catalog_size * 4);

    if (ret < 0) {

        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:

    g_free(s->catalog_bitmap);

    return ret;

}