static int decode_init_mp3on4(AVCodecContext * avctx)

{

    MP3On4DecodeContext *s = avctx->priv_data;

    int i;

    if ((avctx->extradata_size < 2) || (avctx->extradata == NULL)) {

        av_log(avctx, AV_LOG_ERROR, "Codec extradata missing or too short.\n");

        return -1;

    }

    s->chan_cfg = (((unsigned char *)avctx->extradata)[1] >> 3) & 0x0f;

    s->frames = mp3Frames[s->chan_cfg];

    if(!s->frames) {

        av_log(avctx, AV_LOG_ERROR, "Invalid channel config number.\n");

        return -1;

    }

    avctx->channels = mp3Channels[s->chan_cfg];

    /* Init the first mp3 decoder in standard way, so that all tables get builded

     * We replace avctx->priv_data with the context of the first decoder so that

     * decode_init() does not have to be changed.

     * Other decoders will be inited here copying data from the first context

     */

    // Allocate zeroed memory for the first decoder context

    s->mp3decctx[0] = av_mallocz(sizeof(MPADecodeContext));

    // Put decoder context in place to make init_decode() happy

    avctx->priv_data = s->mp3decctx[0];

    decode_init(avctx);

    // Restore mp3on4 context pointer

    avctx->priv_data = s;

    s->mp3decctx[0]->adu_mode = 1; // Set adu mode

    /* Create a separate codec/context for each frame (first is already ok).

     * Each frame is 1 or 2 channels - up to 5 frames allowed

     */

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

        s->mp3decctx[i] = av_mallocz(sizeof(MPADecodeContext));

        s->mp3decctx[i]->compute_antialias = s->mp3decctx[0]->compute_antialias;

        s->mp3decctx[i]->adu_mode = 1;

        s->mp3decctx[i]->avctx = avctx;

    }

    return 0;

}


_syscall4(int,sys_utimensat,int,dirfd,const char *,pathname,

          const struct timespec *,tsp,int,flags)

#endif

#endif /* CONFIG_UTIMENSAT  */

#ifdef CONFIG_INOTIFY

#include <sys/inotify.h>

#if defined(TARGET_NR_inotify_init) && defined(__NR_inotify_init)

static int sys_inotify_init(void)

{

  return (inotify_init());

}


static void curl_readv_bh_cb(void *p)

{

    CURLState *state;

    int running;

    CURLAIOCB *acb = p;

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

    qemu_bh_delete(acb->bh);

    acb->bh = NULL;

    size_t start = acb->sector_num * SECTOR_SIZE;

    size_t end;

    // In case we have the requested data already (e.g. read-ahead),

    // we can just call the callback and be done.

    switch (curl_find_buf(s, start, acb->nb_sectors * SECTOR_SIZE, acb)) {

        case FIND_RET_OK:

            qemu_aio_release(acb);

            // fall through

        case FIND_RET_WAIT:

            return;

        default:

            break;

    }

    // No cache found, so let's start a new request

    state = curl_init_state(s);

    if (!state) {

        acb->common.cb(acb->common.opaque, -EIO);

        qemu_aio_release(acb);

        return;

    }

    acb->start = 0;

    acb->end = (acb->nb_sectors * SECTOR_SIZE);

    state->buf_off = 0;

    g_free(state->orig_buf);

    state->buf_start = start;

    state->buf_len = acb->end + s->readahead_size;

    end = MIN(start + state->buf_len, s->len) - 1;

    state->orig_buf = g_malloc(state->buf_len);

    state->acb[0] = acb;

    snprintf(state->range, 127, "%zd-%zd", start, end);

    DPRINTF("CURL (AIO): Reading %d at %zd (%s)\n",

            (acb->nb_sectors * SECTOR_SIZE), start, state->range);

    curl_easy_setopt(state->curl, CURLOPT_RANGE, state->range);

    curl_multi_add_handle(s->multi, state->curl);

    /* Tell curl it needs to kick things off */

    curl_multi_socket_action(s->multi, CURL_SOCKET_TIMEOUT, 0, &running);

}


static int dnxhd_encode_rdo(AVCodecContext *avctx, DNXHDEncContext *ctx)

{

    int lambda, up_step, down_step;

    int last_lower = INT_MAX, last_higher = 0;

    int x, y, q;

    for (q = 1; q < avctx->qmax; q++) {

        ctx->qscale = q;

        avctx->execute2(avctx, dnxhd_calc_bits_thread, NULL, NULL, ctx->m.mb_height);

    }

    up_step = down_step = 2<<LAMBDA_FRAC_BITS;

    lambda = ctx->lambda;

    for (;;) {

        int bits = 0;

        int end = 0;

        if (lambda == last_higher) {

            lambda++;

            end = 1; // need to set final qscales/bits

        }

        for (y = 0; y < ctx->m.mb_height; y++) {

            for (x = 0; x < ctx->m.mb_width; x++) {

                unsigned min = UINT_MAX;

                int qscale = 1;

                int mb = y*ctx->m.mb_width+x;

                for (q = 1; q < avctx->qmax; q++) {

                    unsigned score = ctx->mb_rc[q][mb].bits*lambda+(ctx->mb_rc[q][mb].ssd<<LAMBDA_FRAC_BITS);

                    if (score < min) {

                        min = score;

                        qscale = q;

                    }

                }

                bits += ctx->mb_rc[qscale][mb].bits;

                ctx->mb_qscale[mb] = qscale;

                ctx->mb_bits[mb] = ctx->mb_rc[qscale][mb].bits;

            }

            bits = (bits+31)&~31; // padding

            if (bits > ctx->frame_bits)

                break;

        }

        //av_dlog(ctx->m.avctx, "lambda %d, up %u, down %u, bits %d, frame %d\n",

        //        lambda, last_higher, last_lower, bits, ctx->frame_bits);

        if (end) {

            if (bits > ctx->frame_bits)

                return -1;

            break;

        }

        if (bits < ctx->frame_bits) {

            last_lower = FFMIN(lambda, last_lower);

            if (last_higher != 0)

                lambda = (lambda+last_higher)>>1;

            else

                lambda -= down_step;

            down_step *= 5; // XXX tune ?

            up_step = 1<<LAMBDA_FRAC_BITS;

            lambda = FFMAX(1, lambda);

            if (lambda == last_lower)

                break;

        } else {

            last_higher = FFMAX(lambda, last_higher);

            if (last_lower != INT_MAX)

                lambda = (lambda+last_lower)>>1;

            else if ((int64_t)lambda + up_step > INT_MAX)

                return -1;

            else

                lambda += up_step;

            up_step = FFMIN((int64_t)up_step*5, INT_MAX);

            down_step = 1<<LAMBDA_FRAC_BITS;

        }

    }

    //av_dlog(ctx->m.avctx, "out lambda %d\n", lambda);

    ctx->lambda = lambda;

    return 0;

}


static int find_and_decode_index(NUTContext *nut)

{

    AVFormatContext *s = nut->avf;

    AVIOContext *bc    = s->pb;

    uint64_t tmp, end;

    int i, j, syncpoint_count;

    int64_t filesize = avio_size(bc);

    int64_t *syncpoints;

    int8_t *has_keyframe;

    int ret = AVERROR_INVALIDDATA;

    avio_seek(bc, filesize - 12, SEEK_SET);

    avio_seek(bc, filesize - avio_rb64(bc), SEEK_SET);

    if (avio_rb64(bc) != INDEX_STARTCODE) {

        av_log(s, AV_LOG_ERROR, "no index at the end\n");

        return ret;

    }

    end  = get_packetheader(nut, bc, 1, INDEX_STARTCODE);

    end += avio_tell(bc);

    ffio_read_varlen(bc); // max_pts

    GET_V(syncpoint_count, tmp < INT_MAX / 8 && tmp > 0);

    syncpoints   = av_malloc(sizeof(int64_t) *  syncpoint_count);

    has_keyframe = av_malloc(sizeof(int8_t)  * (syncpoint_count + 1));

    if (!syncpoints || !has_keyframe)

        return AVERROR(ENOMEM);

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

        syncpoints[i] = ffio_read_varlen(bc);

        if (syncpoints[i] <= 0)

            goto fail;

        if (i)

            syncpoints[i] += syncpoints[i - 1];

    }

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

        int64_t last_pts = -1;

        for (j = 0; j < syncpoint_count;) {

            uint64_t x = ffio_read_varlen(bc);

            int type   = x & 1;

            int n      = j;

            x >>= 1;

            if (type) {

                int flag = x & 1;

                x >>= 1;

                if (n + x >= syncpoint_count + 1) {

                    av_log(s, AV_LOG_ERROR, "index overflow A\n");

                    goto fail;

                }

                while (x--)

                    has_keyframe[n++] = flag;

                has_keyframe[n++] = !flag;

            } else {

                while (x != 1) {

                    if (n >= syncpoint_count + 1) {

                        av_log(s, AV_LOG_ERROR, "index overflow B\n");

                        goto fail;

                    }

                    has_keyframe[n++] = x & 1;

                    x >>= 1;

                }

            }

            if (has_keyframe[0]) {

                av_log(s, AV_LOG_ERROR, "keyframe before first syncpoint in index\n");

                goto fail;

            }

            assert(n <= syncpoint_count + 1);

            for (; j < n && j < syncpoint_count; j++) {

                if (has_keyframe[j]) {

                    uint64_t B, A = ffio_read_varlen(bc);

                    if (!A) {

                        A = ffio_read_varlen(bc);

                        B = ffio_read_varlen(bc);

                        // eor_pts[j][i] = last_pts + A + B

                    } else

                        B = 0;

                    av_add_index_entry(s->streams[i], 16 * syncpoints[j - 1],

                                       last_pts + A, 0, 0, AVINDEX_KEYFRAME);

                    last_pts += A + B;

                }

            }

        }

    }

    if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {

        av_log(s, AV_LOG_ERROR, "index checksum mismatch\n");

        goto fail;

    }

    ret = 0;

fail:

    av_free(syncpoints);

    av_free(has_keyframe);

    return ret;

}


static inline void menelaus_rtc_stop(struct menelaus_s *s)

{

    qemu_del_timer(s->rtc.hz);

    s->rtc.next =- qemu_get_clock(rt_clock);

    if (s->rtc.next < 1)

        s->rtc.next = 1;

}


int drive_init(struct drive_opt *arg, int snapshot, void *opaque)

{

    char buf[128];

    char file[1024];

    char devname[128];

    char serial[21];

    const char *mediastr = "";

    BlockInterfaceType type;

    enum { MEDIA_DISK, MEDIA_CDROM } media;

    int bus_id, unit_id;

    int cyls, heads, secs, translation;

    BlockDriverState *bdrv;

    BlockDriver *drv = NULL;

    QEMUMachine *machine = opaque;

    int max_devs;

    int index;

    int cache;

    int bdrv_flags, onerror;

    int drives_table_idx;

    char *str = arg->opt;

    static const char * const params[] = { "bus", "unit", "if", "index",

                                           "cyls", "heads", "secs", "trans",

                                           "media", "snapshot", "file",

                                           "cache", "format", "serial", "werror",

                                           NULL };

    if (check_params(params, str) < 0) {

         fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",

                         buf, str);

         return -1;

    }

    file[0] = 0;

    cyls = heads = secs = 0;

    bus_id = 0;

    unit_id = -1;

    translation = BIOS_ATA_TRANSLATION_AUTO;

    index = -1;

    cache = 3;

    if (machine->use_scsi) {

        type = IF_SCSI;

        max_devs = MAX_SCSI_DEVS;

        pstrcpy(devname, sizeof(devname), "scsi");

    } else {

        type = IF_IDE;

        max_devs = MAX_IDE_DEVS;

        pstrcpy(devname, sizeof(devname), "ide");

    }

    media = MEDIA_DISK;

    /* extract parameters */

    if (get_param_value(buf, sizeof(buf), "bus", str)) {

        bus_id = strtol(buf, NULL, 0);

	if (bus_id < 0) {

	    fprintf(stderr, "qemu: '%s' invalid bus id\n", str);

	    return -1;

	}

    }

    if (get_param_value(buf, sizeof(buf), "unit", str)) {

        unit_id = strtol(buf, NULL, 0);

	if (unit_id < 0) {

	    fprintf(stderr, "qemu: '%s' invalid unit id\n", str);

	    return -1;

	}

    }

    if (get_param_value(buf, sizeof(buf), "if", str)) {

        pstrcpy(devname, sizeof(devname), buf);

        if (!strcmp(buf, "ide")) {

	    type = IF_IDE;

            max_devs = MAX_IDE_DEVS;

        } else if (!strcmp(buf, "scsi")) {

	    type = IF_SCSI;

            max_devs = MAX_SCSI_DEVS;

        } else if (!strcmp(buf, "floppy")) {

	    type = IF_FLOPPY;

            max_devs = 0;

        } else if (!strcmp(buf, "pflash")) {

	    type = IF_PFLASH;

            max_devs = 0;

	} else if (!strcmp(buf, "mtd")) {

	    type = IF_MTD;

            max_devs = 0;

	} else if (!strcmp(buf, "sd")) {

	    type = IF_SD;

            max_devs = 0;

        } else if (!strcmp(buf, "virtio")) {

            type = IF_VIRTIO;

            max_devs = 0;

	} else if (!strcmp(buf, "xen")) {

	    type = IF_XEN;

            max_devs = 0;

	} else {

            fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);

            return -1;

	}

    }

    if (get_param_value(buf, sizeof(buf), "index", str)) {

        index = strtol(buf, NULL, 0);

	if (index < 0) {

	    fprintf(stderr, "qemu: '%s' invalid index\n", str);

	    return -1;

	}

    }

    if (get_param_value(buf, sizeof(buf), "cyls", str)) {

        cyls = strtol(buf, NULL, 0);

    }

    if (get_param_value(buf, sizeof(buf), "heads", str)) {

        heads = strtol(buf, NULL, 0);

    }

    if (get_param_value(buf, sizeof(buf), "secs", str)) {

        secs = strtol(buf, NULL, 0);

    }

    if (cyls || heads || secs) {

        if (cyls < 1 || cyls > 16383) {

            fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);

	    return -1;

	}

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

            fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);

	    return -1;

	}

        if (secs < 1 || secs > 63) {

            fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);

	    return -1;

	}

    }

    if (get_param_value(buf, sizeof(buf), "trans", str)) {

        if (!cyls) {

            fprintf(stderr,

                    "qemu: '%s' trans must be used with cyls,heads and secs\n",

                    str);

            return -1;

        }

        if (!strcmp(buf, "none"))

            translation = BIOS_ATA_TRANSLATION_NONE;

        else if (!strcmp(buf, "lba"))

            translation = BIOS_ATA_TRANSLATION_LBA;

        else if (!strcmp(buf, "auto"))

            translation = BIOS_ATA_TRANSLATION_AUTO;

	else {

            fprintf(stderr, "qemu: '%s' invalid translation type\n", str);

	    return -1;

	}

    }

    if (get_param_value(buf, sizeof(buf), "media", str)) {

        if (!strcmp(buf, "disk")) {

	    media = MEDIA_DISK;

	} else if (!strcmp(buf, "cdrom")) {

            if (cyls || secs || heads) {

                fprintf(stderr,

                        "qemu: '%s' invalid physical CHS format\n", str);

	        return -1;

            }

	    media = MEDIA_CDROM;

	} else {

	    fprintf(stderr, "qemu: '%s' invalid media\n", str);

	    return -1;

	}

    }

    if (get_param_value(buf, sizeof(buf), "snapshot", str)) {

        if (!strcmp(buf, "on"))

	    snapshot = 1;

        else if (!strcmp(buf, "off"))

	    snapshot = 0;

	else {

	    fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);

	    return -1;

	}

    }

    if (get_param_value(buf, sizeof(buf), "cache", str)) {

        if (!strcmp(buf, "off") || !strcmp(buf, "none"))

            cache = 0;

        else if (!strcmp(buf, "writethrough"))

            cache = 1;

        else if (!strcmp(buf, "writeback"))

            cache = 2;

        else {

           fprintf(stderr, "qemu: invalid cache option\n");

           return -1;

        }

    }

    if (get_param_value(buf, sizeof(buf), "format", str)) {

       if (strcmp(buf, "?") == 0) {

            fprintf(stderr, "qemu: Supported formats:");

            bdrv_iterate_format(bdrv_format_print, NULL);

            fprintf(stderr, "\n");

	    return -1;

        }

        drv = bdrv_find_format(buf);

        if (!drv) {

            fprintf(stderr, "qemu: '%s' invalid format\n", buf);

            return -1;

        }

    }

    if (arg->file == NULL)

        get_param_value(file, sizeof(file), "file", str);

    else

        pstrcpy(file, sizeof(file), arg->file);

    if (!get_param_value(serial, sizeof(serial), "serial", str))

	    memset(serial, 0,  sizeof(serial));

    onerror = BLOCK_ERR_STOP_ENOSPC;

    if (get_param_value(buf, sizeof(serial), "werror", str)) {

        if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {

            fprintf(stderr, "werror is no supported by this format\n");

            return -1;

        }

        if (!strcmp(buf, "ignore"))

            onerror = BLOCK_ERR_IGNORE;

        else if (!strcmp(buf, "enospc"))

            onerror = BLOCK_ERR_STOP_ENOSPC;

        else if (!strcmp(buf, "stop"))

            onerror = BLOCK_ERR_STOP_ANY;

        else if (!strcmp(buf, "report"))

            onerror = BLOCK_ERR_REPORT;

        else {

            fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);

            return -1;

        }

    }

    /* compute bus and unit according index */

    if (index != -1) {

        if (bus_id != 0 || unit_id != -1) {

            fprintf(stderr,

                    "qemu: '%s' index cannot be used with bus and unit\n", str);

            return -1;

        }

        if (max_devs == 0)

        {

            unit_id = index;

            bus_id = 0;

        } else {

            unit_id = index % max_devs;

            bus_id = index / max_devs;

        }

    }

    /* if user doesn't specify a unit_id,

     * try to find the first free

     */

    if (unit_id == -1) {

       unit_id = 0;

       while (drive_get_index(type, bus_id, unit_id) != -1) {

           unit_id++;

           if (max_devs && unit_id >= max_devs) {

               unit_id -= max_devs;

               bus_id++;

           }

       }

    }

    /* check unit id */

    if (max_devs && unit_id >= max_devs) {

        fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",

                        str, unit_id, max_devs - 1);

        return -1;

    }

    /*

     * ignore multiple definitions

     */

    if (drive_get_index(type, bus_id, unit_id) != -1)

        return -2;

    /* init */

    if (type == IF_IDE || type == IF_SCSI)

        mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";

    if (max_devs)

        snprintf(buf, sizeof(buf), "%s%i%s%i",

                 devname, bus_id, mediastr, unit_id);

    else

        snprintf(buf, sizeof(buf), "%s%s%i",

                 devname, mediastr, unit_id);

    bdrv = bdrv_new(buf);

    drives_table_idx = drive_get_free_idx();

    drives_table[drives_table_idx].bdrv = bdrv;

    drives_table[drives_table_idx].type = type;

    drives_table[drives_table_idx].bus = bus_id;

    drives_table[drives_table_idx].unit = unit_id;

    drives_table[drives_table_idx].onerror = onerror;

    drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;

    strncpy(drives_table[drives_table_idx].serial, serial, sizeof(serial));

    nb_drives++;

    switch(type) {

    case IF_IDE:

    case IF_SCSI:

    case IF_XEN:

        switch(media) {

	case MEDIA_DISK:

            if (cyls != 0) {

                bdrv_set_geometry_hint(bdrv, cyls, heads, secs);

                bdrv_set_translation_hint(bdrv, translation);

            }

	    break;

	case MEDIA_CDROM:

            bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);

	    break;

	}

        break;

    case IF_SD:

        /* FIXME: This isn't really a floppy, but it's a reasonable

           approximation.  */

    case IF_FLOPPY:

        bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);

        break;

    case IF_PFLASH:

    case IF_MTD:

    case IF_VIRTIO:

        break;

    case IF_COUNT:

        abort();

    }

    if (!file[0])

        return -2;

    bdrv_flags = 0;

    if (snapshot) {

        bdrv_flags |= BDRV_O_SNAPSHOT;

        cache = 2; /* always use write-back with snapshot */

    }

    if (cache == 0) /* no caching */

        bdrv_flags |= BDRV_O_NOCACHE;

    else if (cache == 2) /* write-back */

        bdrv_flags |= BDRV_O_CACHE_WB;

    else if (cache == 3) /* not specified */

        bdrv_flags |= BDRV_O_CACHE_DEF;

    if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {

        fprintf(stderr, "qemu: could not open disk image %s\n",

                        file);

        return -1;

    }

    if (bdrv_key_required(bdrv))

        autostart = 0;

    return drives_table_idx;

}


static void gic_complete_irq(gic_state * s, int cpu, int irq)

{

    int update = 0;

    int cm = 1 << cpu;

    DPRINTF("EOI %d\n", irq);

    if (s->running_irq[cpu] == 1023)

        return; /* No active IRQ.  */

    if (irq != 1023) {

        /* Mark level triggered interrupts as pending if they are still

           raised.  */

        if (!GIC_TEST_TRIGGER(irq) && GIC_TEST_ENABLED(irq, cm)

                && GIC_TEST_LEVEL(irq, cm) && (GIC_TARGET(irq) & cm) != 0) {

            DPRINTF("Set %d pending mask %x\n", irq, cm);

            GIC_SET_PENDING(irq, cm);

            update = 1;

        }

    }

    if (irq != s->running_irq[cpu]) {

        /* Complete an IRQ that is not currently running.  */

        int tmp = s->running_irq[cpu];

        while (s->last_active[tmp][cpu] != 1023) {

            if (s->last_active[tmp][cpu] == irq) {

                s->last_active[tmp][cpu] = s->last_active[irq][cpu];

                break;

            }

            tmp = s->last_active[tmp][cpu];

        }

        if (update) {

            gic_update(s);

        }

    } else {

        /* Complete the current running IRQ.  */

        gic_set_running_irq(s, cpu, s->last_active[s->running_irq[cpu]][cpu]);

    }

}


static void init_dequant8_coeff_table(H264Context *h){

    int i,q,x;

    const int transpose = (h->h264dsp.h264_idct8_add != ff_h264_idct8_add_c); //FIXME ugly

    h->dequant8_coeff[0] = h->dequant8_buffer[0];

    h->dequant8_coeff[1] = h->dequant8_buffer[1];

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

        if(i && !memcmp(h->pps.scaling_matrix8[0], h->pps.scaling_matrix8[1], 64*sizeof(uint8_t))){

            h->dequant8_coeff[1] = h->dequant8_buffer[0];

            break;

        }

        for(q=0; q<52; q++){

            int shift = div6[q];

            int idx = rem6[q];

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

                h->dequant8_coeff[i][q][transpose ? (x>>3)|((x&7)<<3) : x] =

                    ((uint32_t)dequant8_coeff_init[idx][ dequant8_coeff_init_scan[((x>>1)&12) | (x&3)] ] *

                    h->pps.scaling_matrix8[i][x]) << shift;

        }

    }

}


char *vnc_display_local_addr(const char *id)

{

    VncDisplay *vs = vnc_display_find(id);

    return vnc_socket_local_addr("%s:%s", vs->lsock);

}


PPC_OP(set_T0)

{

    T0 = PARAM(1);

    RETURN();

}


static void test_validate_fail_struct_nested(TestInputVisitorData *data,

                                              const void *unused)

{

    UserDefTwo *udp = NULL;

    Error *err = NULL;

    Visitor *v;

    v = validate_test_init(data, "{ 'string0': 'string0', 'dict1': { 'string1': 'string1', 'dict2': { 'userdef1': { 'integer': 42, 'string': 'string', 'extra': [42, 23, {'foo':'bar'}] }, 'string2': 'string2'}}}");

    visit_type_UserDefTwo(v, NULL, &udp, &err);

    error_free_or_abort(&err);

    qapi_free_UserDefTwo(udp);

}


static int socket_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)

{

    QEMUFileSocket *s = opaque;

    ssize_t len;

    do {

        len = qemu_recv(s->fd, buf, size, 0);

    } while (len == -1 && socket_error() == EINTR);

    if (len == -1)

        len = -socket_error();

    return len;

}


static GIOStatus ga_channel_write(GAChannel *c, const char *buf, size_t size,

                                  size_t *count)

{

    GIOStatus status;

    OVERLAPPED ov = {0};

    BOOL ret;

    DWORD written;

    ov.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);

    ret = WriteFile(c->handle, buf, size, &written, &ov);

    if (!ret) {

        if (GetLastError() == ERROR_IO_PENDING) {

            /* write is pending */

            ret = GetOverlappedResult(c->handle, &ov, &written, TRUE);

            if (!ret) {

                if (!GetLastError()) {

                    status = G_IO_STATUS_AGAIN;

                } else {

                    status = G_IO_STATUS_ERROR;

            } else {

                /* write is complete */

                status = G_IO_STATUS_NORMAL;

                *count = written;

        } else {

            status = G_IO_STATUS_ERROR;

    } else {

        /* write returned immediately */

        status = G_IO_STATUS_NORMAL;

        *count = written;

    return status;


int ff_jni_exception_get_summary(JNIEnv *env, jthrowable exception, char **error, void *log_ctx)

{

    int ret = 0;

    AVBPrint bp;

    char *name = NULL;

    char *message = NULL;

    jclass class_class = NULL;

    jmethodID get_name_id = NULL;

    jclass exception_class = NULL;

    jmethodID get_message_id = NULL;

    jstring string;

    av_bprint_init(&bp, 0, AV_BPRINT_SIZE_AUTOMATIC);

    exception_class = (*env)->GetObjectClass(env, exception);

    if ((*env)->ExceptionCheck(env)) {

        (*env)->ExceptionClear(env);

        av_log(log_ctx, AV_LOG_ERROR, "Could not find Throwable class\n");

        ret = AVERROR_EXTERNAL;

        goto done;

    }

    class_class = (*env)->GetObjectClass(env, exception_class);

    if ((*env)->ExceptionCheck(env)) {

        (*env)->ExceptionClear(env);

        av_log(log_ctx, AV_LOG_ERROR, "Could not find Throwable class's class\n");

        ret = AVERROR_EXTERNAL;

        goto done;

    }

    get_name_id = (*env)->GetMethodID(env, class_class, "getName", "()Ljava/lang/String;");

    if ((*env)->ExceptionCheck(env)) {

        (*env)->ExceptionClear(env);

        av_log(log_ctx, AV_LOG_ERROR, "Could not find method Class.getName()\n");

        ret = AVERROR_EXTERNAL;

        goto done;

    }

    string = (*env)->CallObjectMethod(env, exception_class, get_name_id);

    if ((*env)->ExceptionCheck(env)) {

        (*env)->ExceptionClear(env);

        av_log(log_ctx, AV_LOG_ERROR, "Class.getName() threw an exception\n");

        ret = AVERROR_EXTERNAL;

        goto done;

    }

    if (string) {

        name = ff_jni_jstring_to_utf_chars(env, string, log_ctx);

        (*env)->DeleteLocalRef(env, string);

        string = NULL;

    }

    get_message_id = (*env)->GetMethodID(env, exception_class, "getMessage", "()Ljava/lang/String;");

    if ((*env)->ExceptionCheck(env)) {

        (*env)->ExceptionClear(env);

        av_log(log_ctx, AV_LOG_ERROR, "Could not find method java/lang/Throwable.getMessage()\n");

        ret = AVERROR_EXTERNAL;

        goto done;

    }

    string = (*env)->CallObjectMethod(env, exception, get_message_id);

    if ((*env)->ExceptionCheck(env)) {

        (*env)->ExceptionClear(env);

        av_log(log_ctx, AV_LOG_ERROR, "Throwable.getMessage() threw an exception\n");

        ret = AVERROR_EXTERNAL;

        goto done;

    }

    if (string) {

        message = ff_jni_jstring_to_utf_chars(env, string, log_ctx);

        (*env)->DeleteLocalRef(env, string);

        string = NULL;

    }

    if (name && message) {

        av_bprintf(&bp, "%s: %s", name, message);

    } else if (name && !message) {

        av_bprintf(&bp, "%s occurred", name);

    } else if (!name && message) {

        av_bprintf(&bp, "Exception: %s", message);

    } else {

        av_log(log_ctx, AV_LOG_WARNING, "Could not retreive exception name and message\n");

        av_bprintf(&bp, "Exception occurred");

    }

    ret = av_bprint_finalize(&bp, error);

done:

    av_free(name);

    av_free(message);

    if (class_class) {

        (*env)->DeleteLocalRef(env, class_class);

    }

    if (exception_class) {

        (*env)->DeleteLocalRef(env, exception_class);

    }

    if (string) {

        (*env)->DeleteLocalRef(env, string);

    }

    return ret;

}


static void vscsi_command_complete(SCSIBus *bus, int reason, uint32_t tag,

                                   uint32_t arg)

{

    VSCSIState *s = DO_UPCAST(VSCSIState, vdev.qdev, bus->qbus.parent);

    vscsi_req *req = vscsi_find_req(s, tag);

    SCSIDevice *sdev;

    uint8_t *buf;

    int32_t res_in = 0, res_out = 0;

    int len, rc = 0;

    dprintf("VSCSI: SCSI cmd complete, r=0x%x tag=0x%x arg=0x%x, req=%p\n",

            reason, tag, arg, req);

    if (req == NULL) {

        fprintf(stderr, "VSCSI: Can't find request for tag 0x%x\n", tag);

        return;

    }

    sdev = req->sdev;

    if (req->sensing) {

        if (reason == SCSI_REASON_DONE) {

            dprintf("VSCSI: Sense done !\n");

            vscsi_send_rsp(s, req, CHECK_CONDITION, 0, 0);

            vscsi_put_req(s, req);

        } else {

            uint8_t *buf = sdev->info->get_buf(sdev, tag);

            len = MIN(arg, SCSI_SENSE_BUF_SIZE);

            dprintf("VSCSI: Sense data, %d bytes:\n", len);

            dprintf("       %02x  %02x  %02x  %02x  %02x  %02x  %02x  %02x\n",

                    buf[0], buf[1], buf[2], buf[3],

                    buf[4], buf[5], buf[6], buf[7]);

            dprintf("       %02x  %02x  %02x  %02x  %02x  %02x  %02x  %02x\n",

                    buf[8], buf[9], buf[10], buf[11],

                    buf[12], buf[13], buf[14], buf[15]);

            memcpy(req->sense, buf, len);

            req->senselen = len;

            sdev->info->read_data(sdev, req->qtag);

        }

        return;

    }

    if (reason == SCSI_REASON_DONE) {

        dprintf("VSCSI: Command complete err=%d\n", arg);

        if (arg == 0) {

            /* We handle overflows, not underflows for normal commands,

             * but hopefully nobody cares

             */

            if (req->writing) {

                res_out = req->data_len;

            } else {

                res_in = req->data_len;

            }

            vscsi_send_rsp(s, req, 0, res_in, res_out);

        } else if (arg == CHECK_CONDITION) {

            dprintf("VSCSI: Got CHECK_CONDITION, requesting sense...\n");

            vscsi_send_request_sense(s, req);

            return;

        } else {

            vscsi_send_rsp(s, req, arg, 0, 0);

        }

        vscsi_put_req(s, req);

        return;

    }

    /* "arg" is how much we have read for reads and how much we want

     * to write for writes (ie, how much is to be DMA'd)

     */

    if (arg) {

        buf = sdev->info->get_buf(sdev, tag);

        rc = vscsi_srp_transfer_data(s, req, req->writing, buf, arg);

    }

    if (rc < 0) {

        fprintf(stderr, "VSCSI: RDMA error rc=%d!\n", rc);

        sdev->info->cancel_io(sdev, req->qtag);

        vscsi_makeup_sense(s, req, HARDWARE_ERROR, 0, 0);

        vscsi_send_rsp(s, req, CHECK_CONDITION, 0, 0);

        vscsi_put_req(s, req);

        return;

    }

    /* Start next chunk */

    req->data_len -= rc;

    if (req->writing) {

        sdev->info->write_data(sdev, req->qtag);

    } else {

        sdev->info->read_data(sdev, req->qtag);

    }

}


void helper_store_sdr1(CPUPPCState *env, target_ulong val)

{

    PowerPCCPU *cpu = ppc_env_get_cpu(env);

    if (!env->external_htab) {

        if (env->spr[SPR_SDR1] != val) {

            ppc_store_sdr1(env, val);

            tlb_flush(CPU(cpu));

        }

    }

}


static bool fw_cfg_comb_valid(void *opaque, target_phys_addr_t addr,

                                  unsigned size, bool is_write)

{

    return (size == 1) || (is_write && size == 2);

}


sPAPRTCETable *spapr_tce_new_table(DeviceState *owner, uint32_t liobn,

                                   uint64_t bus_offset,

                                   uint32_t page_shift,

                                   uint32_t nb_table,

                                   bool vfio_accel)

{

    sPAPRTCETable *tcet;

    char tmp[64];

    if (spapr_tce_find_by_liobn(liobn)) {

        fprintf(stderr, "Attempted to create TCE table with duplicate"

                " LIOBN 0x%x\n", liobn);

        return NULL;

    }

    if (!nb_table) {

        return NULL;

    }

    tcet = SPAPR_TCE_TABLE(object_new(TYPE_SPAPR_TCE_TABLE));

    tcet->liobn = liobn;

    tcet->bus_offset = bus_offset;

    tcet->page_shift = page_shift;

    tcet->nb_table = nb_table;

    tcet->vfio_accel = vfio_accel;

    snprintf(tmp, sizeof(tmp), "tce-table-%x", liobn);

    object_property_add_child(OBJECT(owner), tmp, OBJECT(tcet), NULL);

    object_property_set_bool(OBJECT(tcet), true, "realized", NULL);

    return tcet;

}


static void debug_print_fis(uint8_t *fis, int cmd_len)

{

#ifdef DEBUG_AHCI

    int i;

    fprintf(stderr, "fis:");

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

        if ((i & 0xf) == 0) {

            fprintf(stderr, "\n%02x:",i);

        }

        fprintf(stderr, "%02x ",fis[i]);

    }

    fprintf(stderr, "\n");

#endif

}


static av_cold int svc_encode_init(AVCodecContext *avctx)

{

    SVCContext *s = avctx->priv_data;

    SEncParamExt param = { 0 };

    int err = AVERROR_UNKNOWN;

    int log_level;

    WelsTraceCallback callback_function;

    AVCPBProperties *props;

    // Mingw GCC < 4.7 on x86_32 uses an incorrect/buggy ABI for the WelsGetCodecVersion

    // function (for functions returning larger structs), thus skip the check in those

    // configurations.

#if !defined(_WIN32) || !defined(__GNUC__) || !ARCH_X86_32 || AV_GCC_VERSION_AT_LEAST(4, 7)

    OpenH264Version libver = WelsGetCodecVersion();

    if (memcmp(&libver, &g_stCodecVersion, sizeof(libver))) {

        av_log(avctx, AV_LOG_ERROR, "Incorrect library version loaded\n");

        return AVERROR(EINVAL);

    }

#endif

    if (WelsCreateSVCEncoder(&s->encoder)) {

        av_log(avctx, AV_LOG_ERROR, "Unable to create encoder\n");

        return AVERROR_UNKNOWN;

    }

    // Pass all libopenh264 messages to our callback, to allow ourselves to filter them.

    log_level = WELS_LOG_DETAIL;

    (*s->encoder)->SetOption(s->encoder, ENCODER_OPTION_TRACE_LEVEL, &log_level);

    // Set the logging callback function to one that uses av_log() (see implementation above).

    callback_function = (WelsTraceCallback) libopenh264_trace_callback;

    (*s->encoder)->SetOption(s->encoder, ENCODER_OPTION_TRACE_CALLBACK, (void *)&callback_function);

    // Set the AVCodecContext as the libopenh264 callback context so that it can be passed to av_log().

    (*s->encoder)->SetOption(s->encoder, ENCODER_OPTION_TRACE_CALLBACK_CONTEXT, (void *)&avctx);

    (*s->encoder)->GetDefaultParams(s->encoder, &param);

    param.fMaxFrameRate              = avctx->time_base.den / avctx->time_base.num;

    param.iPicWidth                  = avctx->width;

    param.iPicHeight                 = avctx->height;

    param.iTargetBitrate             = avctx->bit_rate;

    param.iMaxBitrate                = FFMAX(avctx->rc_max_rate, avctx->bit_rate);

    param.iRCMode                    = RC_QUALITY_MODE;

    param.iTemporalLayerNum          = 1;

    param.iSpatialLayerNum           = 1;

    param.bEnableDenoise             = 0;

    param.bEnableBackgroundDetection = 1;

    param.bEnableAdaptiveQuant       = 1;

    param.bEnableFrameSkip           = s->skip_frames;

    param.bEnableLongTermReference   = 0;

    param.iLtrMarkPeriod             = 30;

    param.uiIntraPeriod              = avctx->gop_size;

#if OPENH264_VER_AT_LEAST(1, 4)

    param.eSpsPpsIdStrategy          = CONSTANT_ID;

#else

    param.bEnableSpsPpsIdAddition    = 0;

#endif

    param.bPrefixNalAddingCtrl       = 0;

    param.iLoopFilterDisableIdc      = !s->loopfilter;

    param.iEntropyCodingModeFlag     = 0;

    param.iMultipleThreadIdc         = avctx->thread_count;

    if (s->profile && !strcmp(s->profile, "main"))

        param.iEntropyCodingModeFlag = 1;

    else if (!s->profile && avctx->coder_type == FF_CODER_TYPE_AC)

        param.iEntropyCodingModeFlag = 1;

    param.sSpatialLayers[0].iVideoWidth         = param.iPicWidth;

    param.sSpatialLayers[0].iVideoHeight        = param.iPicHeight;

    param.sSpatialLayers[0].fFrameRate          = param.fMaxFrameRate;

    param.sSpatialLayers[0].iSpatialBitrate     = param.iTargetBitrate;

    param.sSpatialLayers[0].iMaxSpatialBitrate  = param.iMaxBitrate;

    if ((avctx->slices > 1) && (s->max_nal_size)){

        av_log(avctx,AV_LOG_ERROR,"Invalid combination -slices %d and -max_nal_size %d.\n",avctx->slices,s->max_nal_size);

        goto fail;

    }

    if (avctx->slices > 1)

        s->slice_mode = SM_FIXEDSLCNUM_SLICE;

    if (s->max_nal_size)

        s->slice_mode = SM_DYN_SLICE;

    param.sSpatialLayers[0].sSliceCfg.uiSliceMode               = s->slice_mode;

    param.sSpatialLayers[0].sSliceCfg.sSliceArgument.uiSliceNum = avctx->slices;

    if (s->slice_mode == SM_DYN_SLICE) {

        if (s->max_nal_size){

            param.uiMaxNalSize = s->max_nal_size;

            param.sSpatialLayers[0].sSliceCfg.sSliceArgument.uiSliceSizeConstraint = s->max_nal_size;

        } else {

            if (avctx->rtp_payload_size) {

                av_log(avctx,AV_LOG_DEBUG,"Using RTP Payload size for uiMaxNalSize");

                param.uiMaxNalSize = avctx->rtp_payload_size;

                param.sSpatialLayers[0].sSliceCfg.sSliceArgument.uiSliceSizeConstraint = avctx->rtp_payload_size;

            } else {

                av_log(avctx,AV_LOG_ERROR,"Invalid -max_nal_size, specify a valid max_nal_size to use -slice_mode dyn\n");

                goto fail;

            }

        }

    }

    if ((*s->encoder)->InitializeExt(s->encoder, &param) != cmResultSuccess) {

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

        goto fail;

    }

    if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {

        SFrameBSInfo fbi = { 0 };

        int i, size = 0;

        (*s->encoder)->EncodeParameterSets(s->encoder, &fbi);

        for (i = 0; i < fbi.sLayerInfo[0].iNalCount; i++)

            size += fbi.sLayerInfo[0].pNalLengthInByte[i];

        avctx->extradata = av_mallocz(size + AV_INPUT_BUFFER_PADDING_SIZE);

        if (!avctx->extradata) {

            err = AVERROR(ENOMEM);

            goto fail;

        }

        avctx->extradata_size = size;

        memcpy(avctx->extradata, fbi.sLayerInfo[0].pBsBuf, size);

    }

    props = ff_add_cpb_side_data(avctx);

    if (!props) {

        err = AVERROR(ENOMEM);

        goto fail;

    }

    props->max_bitrate = param.iMaxBitrate;

    props->avg_bitrate = param.iTargetBitrate;

    return 0;

fail:

    svc_encode_close(avctx);

    return err;

}


static void sm501_disp_ctrl_write(void *opaque, hwaddr addr,

                                  uint64_t value, unsigned size)

{

    SM501State *s = (SM501State *)opaque;

    SM501_DPRINTF("sm501 disp ctrl regs : write addr=%x, val=%x\n",

                  (unsigned)addr, (unsigned)value);

    switch (addr) {

    case SM501_DC_PANEL_CONTROL:

        s->dc_panel_control = value & 0x0FFF73FF;

        break;

    case SM501_DC_PANEL_PANNING_CONTROL:

        s->dc_panel_panning_control = value & 0xFF3FFF3F;

        break;

    case SM501_DC_PANEL_FB_ADDR:

        s->dc_panel_fb_addr = value & 0x8FFFFFF0;

        break;

    case SM501_DC_PANEL_FB_OFFSET:

        s->dc_panel_fb_offset = value & 0x3FF03FF0;

        break;

    case SM501_DC_PANEL_FB_WIDTH:

        s->dc_panel_fb_width = value & 0x0FFF0FFF;

        break;

    case SM501_DC_PANEL_FB_HEIGHT:

        s->dc_panel_fb_height = value & 0x0FFF0FFF;

        break;

    case SM501_DC_PANEL_TL_LOC:

        s->dc_panel_tl_location = value & 0x07FF07FF;

        break;

    case SM501_DC_PANEL_BR_LOC:

        s->dc_panel_br_location = value & 0x07FF07FF;

        break;

    case SM501_DC_PANEL_H_TOT:

        s->dc_panel_h_total = value & 0x0FFF0FFF;

        break;

    case SM501_DC_PANEL_H_SYNC:

        s->dc_panel_h_sync = value & 0x00FF0FFF;

        break;

    case SM501_DC_PANEL_V_TOT:

        s->dc_panel_v_total = value & 0x0FFF0FFF;

        break;

    case SM501_DC_PANEL_V_SYNC:

        s->dc_panel_v_sync = value & 0x003F0FFF;

        break;

    case SM501_DC_PANEL_HWC_ADDR:

        s->dc_panel_hwc_addr = value & 0x8FFFFFF0;

        break;

    case SM501_DC_PANEL_HWC_LOC:

        s->dc_panel_hwc_location = value & 0x0FFF0FFF;

        break;

    case SM501_DC_PANEL_HWC_COLOR_1_2:

        s->dc_panel_hwc_color_1_2 = value;

        break;

    case SM501_DC_PANEL_HWC_COLOR_3:

        s->dc_panel_hwc_color_3 = value & 0x0000FFFF;

        break;

    case SM501_DC_CRT_CONTROL:

        s->dc_crt_control = value & 0x0003FFFF;

        break;

    case SM501_DC_CRT_FB_ADDR:

        s->dc_crt_fb_addr = value & 0x8FFFFFF0;

        break;

    case SM501_DC_CRT_FB_OFFSET:

        s->dc_crt_fb_offset = value & 0x3FF03FF0;

        break;

    case SM501_DC_CRT_H_TOT:

        s->dc_crt_h_total = value & 0x0FFF0FFF;

        break;

    case SM501_DC_CRT_H_SYNC:

        s->dc_crt_h_sync = value & 0x00FF0FFF;

        break;

    case SM501_DC_CRT_V_TOT:

        s->dc_crt_v_total = value & 0x0FFF0FFF;

        break;

    case SM501_DC_CRT_V_SYNC:

        s->dc_crt_v_sync = value & 0x003F0FFF;

        break;

    case SM501_DC_CRT_HWC_ADDR:

        s->dc_crt_hwc_addr = value & 0x8FFFFFF0;

        break;

    case SM501_DC_CRT_HWC_LOC:

        s->dc_crt_hwc_location = value & 0x0FFF0FFF;

        break;

    case SM501_DC_CRT_HWC_COLOR_1_2:

        s->dc_crt_hwc_color_1_2 = value;

        break;

    case SM501_DC_CRT_HWC_COLOR_3:

        s->dc_crt_hwc_color_3 = value & 0x0000FFFF;

        break;

    case SM501_DC_PANEL_PALETTE ... SM501_DC_PANEL_PALETTE + 0x400 * 3 - 4:

        sm501_palette_write(opaque, addr - SM501_DC_PANEL_PALETTE, value);

        break;

    default:

        printf("sm501 disp ctrl : not implemented register write."

               " addr=%x, val=%x\n", (int)addr, (unsigned)value);

        abort();

    }

}


void rgb15to16(const uint8_t *src,uint8_t *dst,uint32_t src_size)

{

#ifdef HAVE_MMX

  register const char* s=src+src_size;

  register char* d=dst+src_size;

  register int offs=-src_size;

  __asm __volatile(PREFETCH"	%0"::"m"(*(s+offs)):"memory");

  __asm __volatile(

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

	"movq	%1, %%mm5"

	::"m"(mask15b), "m"(mask15rg):"memory");

  while(offs<0)

  {

	__asm __volatile(

		PREFETCH"	32%1\n\t"

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

		"movq	8%1, %%mm2\n\t"

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

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

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

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

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

		"pand	%%mm5, %%mm3\n\t"

		"psllq	$1, %%mm1\n\t"

		"psllq	$1, %%mm3\n\t"

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

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

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

		MOVNTQ"	%%mm2, 8%0"

		:"=m"(*(d+offs))

		:"m"(*(s+offs))

		:"memory");

	offs+=16;

  }

  __asm __volatile(SFENCE:::"memory");

  __asm __volatile(EMMS:::"memory");

#else

   const uint16_t *s1=( uint16_t * )src;

   uint16_t *d1=( uint16_t * )dst;

   uint16_t *e=((uint8_t *)s1)+src_size;

   while( s1<e ){

     register int x=*( s1++ );

     /* rrrrrggggggbbbbb

        0rrrrrgggggbbbbb

        0111 1111 1110 0000=0x7FE0

        00000000000001 1111=0x001F */

     *( d1++ )=( x&0x001F )|( ( x&0x7FE0 )<<1 );

   }

#endif

}


static int rle_unpack(const unsigned char *src, unsigned char *dest,

    int src_len, int dest_len)

{

    const unsigned char *ps;

    unsigned char *pd;

    int i, l;

    unsigned char *dest_end = dest + dest_len;

    ps = src;

    pd = dest;

    if (src_len & 1)

        *pd++ = *ps++;

    src_len >>= 1;

    i = 0;

    do {

        l = *ps++;

        if (l & 0x80) {

            l = (l & 0x7F) * 2;

            if (pd + l > dest_end)

                return ps - src;

            memcpy(pd, ps, l);

            ps += l;

            pd += l;

        } else {

            if (pd + i > dest_end)

                return ps - src;

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

                *pd++ = ps[0];

                *pd++ = ps[1];

            }

            ps += 2;

        }

        i += l;

    } while (i < src_len);

    return ps - src;

}


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

                                 ptrdiff_t stride)

{

    avc_luma_hv_qrt_and_aver_dst_16x16_msa(src + stride - 2,

                                           src - (stride * 2) +

                                           sizeof(uint8_t), stride,

                                           dst, stride);

}


static int vorbis_parse(AVCodecParserContext *s1, AVCodecContext *avctx,

                        const uint8_t **poutbuf, int *poutbuf_size,

                        const uint8_t *buf, int buf_size)

{

    VorbisParseContext *s = s1->priv_data;

    int duration;

    if (!s->vp && avctx->extradata && avctx->extradata_size) {

        s->vp = av_vorbis_parse_init(avctx->extradata, avctx->extradata_size);

        if (!s->vp)

            goto end;

    }

    if ((duration = av_vorbis_parse_frame(s->vp, buf, buf_size)) >= 0)

        s1->duration = duration;

end:

    /* always return the full packet. this parser isn't doing any splitting or

       combining, only packet analysis */

    *poutbuf      = buf;

    *poutbuf_size = buf_size;

    return buf_size;

}


static void xen_ram_init(PCMachineState *pcms,

                         ram_addr_t ram_size, MemoryRegion **ram_memory_p)

{

    MemoryRegion *sysmem = get_system_memory();

    ram_addr_t block_len;

    uint64_t user_lowmem = object_property_get_int(qdev_get_machine(),

                                                   PC_MACHINE_MAX_RAM_BELOW_4G,

                                                   &error_abort);

    /* Handle the machine opt max-ram-below-4g.  It is basically doing

     * min(xen limit, user limit).

     */

    if (HVM_BELOW_4G_RAM_END <= user_lowmem) {

        user_lowmem = HVM_BELOW_4G_RAM_END;

    }

    if (ram_size >= user_lowmem) {

        pcms->above_4g_mem_size = ram_size - user_lowmem;

        pcms->below_4g_mem_size = user_lowmem;

    } else {

        pcms->above_4g_mem_size = 0;

        pcms->below_4g_mem_size = ram_size;

    }

    if (!pcms->above_4g_mem_size) {

        block_len = ram_size;

    } else {

        /*

         * Xen does not allocate the memory continuously, it keeps a

         * hole of the size computed above or passed in.

         */

        block_len = (1ULL << 32) + pcms->above_4g_mem_size;

    }

    memory_region_init_ram(&ram_memory, NULL, "xen.ram", block_len,

                           &error_abort);

    *ram_memory_p = &ram_memory;

    vmstate_register_ram_global(&ram_memory);

    memory_region_init_alias(&ram_640k, NULL, "xen.ram.640k",

                             &ram_memory, 0, 0xa0000);

    memory_region_add_subregion(sysmem, 0, &ram_640k);

    /* Skip of the VGA IO memory space, it will be registered later by the VGA

     * emulated device.

     *

     * The area between 0xc0000 and 0x100000 will be used by SeaBIOS to load

     * the Options ROM, so it is registered here as RAM.

     */

    memory_region_init_alias(&ram_lo, NULL, "xen.ram.lo",

                             &ram_memory, 0xc0000,

                             pcms->below_4g_mem_size - 0xc0000);

    memory_region_add_subregion(sysmem, 0xc0000, &ram_lo);

    if (pcms->above_4g_mem_size > 0) {

        memory_region_init_alias(&ram_hi, NULL, "xen.ram.hi",

                                 &ram_memory, 0x100000000ULL,

                                 pcms->above_4g_mem_size);

        memory_region_add_subregion(sysmem, 0x100000000ULL, &ram_hi);

    }

}


static void pci_spapr_set_irq(void *opaque, int irq_num, int level)

{

    /*

     * Here we use the number returned by pci_spapr_map_irq to find a

     * corresponding qemu_irq.

     */

    sPAPRPHBState *phb = opaque;

    trace_spapr_pci_lsi_set(phb->busname, irq_num, phb->lsi_table[irq_num].irq);

    qemu_set_irq(spapr_phb_lsi_qirq(phb, irq_num), level);

}


static int alloc_sequence_buffers(DiracContext *s)

{

    int sbwidth  = DIVRNDUP(s->source.width,  4);

    int sbheight = DIVRNDUP(s->source.height, 4);

    int i, w, h, top_padding;

    /* todo: think more about this / use or set Plane here */

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

        int max_xblen = MAX_BLOCKSIZE >> (i ? s->chroma_x_shift : 0);

        int max_yblen = MAX_BLOCKSIZE >> (i ? s->chroma_y_shift : 0);

        w = s->source.width  >> (i ? s->chroma_x_shift : 0);

        h = s->source.height >> (i ? s->chroma_y_shift : 0);

        /* we allocate the max we support here since num decompositions can

         * change from frame to frame. Stride is aligned to 16 for SIMD, and

         * 1<<MAX_DWT_LEVELS top padding to avoid if(y>0) in arith decoding

         * MAX_BLOCKSIZE padding for MC: blocks can spill up to half of that

         * on each side */

        top_padding = FFMAX(1<<MAX_DWT_LEVELS, max_yblen/2);

        w = FFALIGN(CALC_PADDING(w, MAX_DWT_LEVELS), 8); /* FIXME: Should this be 16 for SSE??? */

        h = top_padding + CALC_PADDING(h, MAX_DWT_LEVELS) + max_yblen/2;

        s->plane[i].idwt_buf_base = av_mallocz((w+max_xblen)*h * sizeof(IDWTELEM));

        s->plane[i].idwt_tmp      = av_malloc((w+16) * sizeof(IDWTELEM));

        s->plane[i].idwt_buf      = s->plane[i].idwt_buf_base + top_padding*w;

        if (!s->plane[i].idwt_buf_base || !s->plane[i].idwt_tmp)

            return AVERROR(ENOMEM);

    }

    w = s->source.width;

    h = s->source.height;

    /* fixme: allocate using real stride here */

    s->sbsplit  = av_malloc(sbwidth * sbheight);

    s->blmotion = av_malloc(sbwidth * sbheight * 16 * sizeof(*s->blmotion));

    s->edge_emu_buffer_base = av_malloc((w+64)*MAX_BLOCKSIZE);

    s->mctmp     = av_malloc((w+64+MAX_BLOCKSIZE) * (h*MAX_BLOCKSIZE) * sizeof(*s->mctmp));

    s->mcscratch = av_malloc((w+64)*MAX_BLOCKSIZE);

    if (!s->sbsplit || !s->blmotion)

        return AVERROR(ENOMEM);

    return 0;

}


static int hevc_handle_packet(AVFormatContext *ctx, PayloadContext *rtp_hevc_ctx,

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

                              const uint8_t *buf, int len, uint16_t seq,

                              int flags)

{

    const uint8_t *rtp_pl = buf;

    int tid, lid, nal_type;

    int first_fragment, last_fragment, fu_type;

    uint8_t new_nal_header[2];

    int res = 0;

    /* sanity check for size of input packet: 1 byte payload at least */

    if (len < RTP_HEVC_PAYLOAD_HEADER_SIZE + 1) {

        av_log(ctx, AV_LOG_ERROR, "Too short RTP/HEVC packet, got %d bytes\n", len);

        return AVERROR_INVALIDDATA;

    }

    /*

     * decode the HEVC payload header according to section 4 of draft version 6:

     *

     *    0                   1

     *    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5

     *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

     *   |F|   Type    |  LayerId  | TID |

     *   +-------------+-----------------+

     *

     *      Forbidden zero (F): 1 bit

     *      NAL unit type (Type): 6 bits

     *      NUH layer ID (LayerId): 6 bits

     *      NUH temporal ID plus 1 (TID): 3 bits

     */

    nal_type =  (buf[0] >> 1) & 0x3f;

    lid  = ((buf[0] << 5) & 0x20) | ((buf[1] >> 3) & 0x1f);

    tid  =   buf[1] & 0x07;

    /* sanity check for correct layer ID */

    if (lid) {

        /* future scalable or 3D video coding extensions */

        avpriv_report_missing_feature(ctx, "Multi-layer HEVC coding\n");

        return AVERROR_PATCHWELCOME;

    }

    /* sanity check for correct temporal ID */

    if (!tid) {

        av_log(ctx, AV_LOG_ERROR, "Illegal temporal ID in RTP/HEVC packet\n");

        return AVERROR_INVALIDDATA;

    }

    /* sanity check for correct NAL unit type */

    if (nal_type > 50) {

        av_log(ctx, AV_LOG_ERROR, "Unsupported (HEVC) NAL type (%d)\n", nal_type);

        return AVERROR_INVALIDDATA;

    }

    switch (nal_type) {

    /* video parameter set (VPS) */

    case 32:

    /* sequence parameter set (SPS) */

    case 33:

    /* picture parameter set (PPS) */

    case 34:

    /*  supplemental enhancement information (SEI) */

    case 39:

    /* single NAL unit packet */

    default:

        /* sanity check for size of input packet: 1 byte payload at least */

        if (len < 1) {

            av_log(ctx, AV_LOG_ERROR,

                   "Too short RTP/HEVC packet, got %d bytes of NAL unit type %d\n",

                   len, nal_type);

            return AVERROR_INVALIDDATA;

        }

        /* create A/V packet */

        if ((res = av_new_packet(pkt, sizeof(start_sequence) + len)) < 0)

            return res;

        /* A/V packet: copy start sequence */

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

        /* A/V packet: copy NAL unit data */

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

        break;

    /* aggregated packet (AP) - with two or more NAL units */

    case 48:

        /* pass the HEVC payload header */

        buf += RTP_HEVC_PAYLOAD_HEADER_SIZE;

        len -= RTP_HEVC_PAYLOAD_HEADER_SIZE;

        /* pass the HEVC DONL field */

        if (rtp_hevc_ctx->using_donl_field) {

            buf += RTP_HEVC_DONL_FIELD_SIZE;

            len -= RTP_HEVC_DONL_FIELD_SIZE;

        }

        res = ff_h264_handle_aggregated_packet(ctx, pkt, buf, len,

                                               rtp_hevc_ctx->using_donl_field ?

                                               RTP_HEVC_DOND_FIELD_SIZE : 0,

                                               NULL, 0);

        if (res < 0)

            return res;

        break;

    /* fragmentation unit (FU) */

    case 49:

        /* pass the HEVC payload header */

        buf += RTP_HEVC_PAYLOAD_HEADER_SIZE;

        len -= RTP_HEVC_PAYLOAD_HEADER_SIZE;

        /*

         *    decode the FU header

         *

         *     0 1 2 3 4 5 6 7

         *    +-+-+-+-+-+-+-+-+

         *    |S|E|  FuType   |

         *    +---------------+

         *

         *       Start fragment (S): 1 bit

         *       End fragment (E): 1 bit

         *       FuType: 6 bits

         */

        first_fragment = buf[0] & 0x80;

        last_fragment  = buf[0] & 0x40;

        fu_type        = buf[0] & 0x3f;

        /* pass the HEVC FU header */

        buf += RTP_HEVC_FU_HEADER_SIZE;

        len -= RTP_HEVC_FU_HEADER_SIZE;

        /* pass the HEVC DONL field */

        if (rtp_hevc_ctx->using_donl_field) {

            buf += RTP_HEVC_DONL_FIELD_SIZE;

            len -= RTP_HEVC_DONL_FIELD_SIZE;

        }

        av_dlog(ctx, " FU type %d with %d bytes\n", fu_type, len);

        if (len <= 0) {

            /* sanity check for size of input packet: 1 byte payload at least */

            av_log(ctx, AV_LOG_ERROR,

                   "Too short RTP/HEVC packet, got %d bytes of NAL unit type %d\n",

                   len, nal_type);

            return AVERROR_INVALIDDATA;

        }

        if (first_fragment && last_fragment) {

            av_log(ctx, AV_LOG_ERROR, "Illegal combination of S and E bit in RTP/HEVC packet\n");

            return AVERROR_INVALIDDATA;

        }

        new_nal_header[0] = (rtp_pl[0] & 0x81) | (fu_type << 1);

        new_nal_header[1] = rtp_pl[1];

        res = ff_h264_handle_frag_packet(pkt, buf, len, first_fragment,

                                         new_nal_header, sizeof(new_nal_header));

        break;

    /* PACI packet */

    case 50:

        /* Temporal scalability control information (TSCI) */

        avpriv_report_missing_feature(ctx, "PACI packets for RTP/HEVC\n");

        res = AVERROR_PATCHWELCOME;

        break;

    }

    pkt->stream_index = st->index;

    return res;

}


int avpriv_lock_avformat(void)

{

    if (lockmgr_cb) {

        if ((*lockmgr_cb)(&avformat_mutex, AV_LOCK_OBTAIN))

            return -1;

    }

    return 0;

}


static int libschroedinger_encode_close(AVCodecContext *avctx)

{

    SchroEncoderParams *p_schro_params = avctx->priv_data;

    /* Close the encoder. */

    schro_encoder_free(p_schro_params->encoder);

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

    ff_schro_queue_free(&p_schro_params->enc_frame_queue,

                        libschroedinger_free_frame);

    /* Free the encoder buffer. */

    if (p_schro_params->enc_buf_size)

        av_freep(&p_schro_params->enc_buf);

    /* Free the video format structure. */

    av_freep(&p_schro_params->format);

    return 0;

}


static int cinepak_decode_frame(AVCodecContext *avctx,

                                void *data, int *got_frame,

                                AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int ret = 0, buf_size = avpkt->size;

    CinepakContext *s = avctx->priv_data;

    s->data = buf;

    s->size = buf_size;

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

        return ret;

    if (s->palette_video) {

        const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, NULL);

        if (pal) {

            s->frame->palette_has_changed = 1;

            memcpy(s->pal, pal, AVPALETTE_SIZE);

        }

    }

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

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

    }

    if (s->palette_video)

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

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

        return ret;

    *got_frame = 1;

    /* report that the buffer was completely consumed */

    return buf_size;

}


static void taihu_405ep_init(MachineState *machine)

{

    ram_addr_t ram_size = machine->ram_size;

    const char *kernel_filename = machine->kernel_filename;

    const char *initrd_filename = machine->initrd_filename;

    char *filename;

    qemu_irq *pic;

    MemoryRegion *sysmem = get_system_memory();

    MemoryRegion *bios;

    MemoryRegion *ram_memories = g_malloc(2 * sizeof(*ram_memories));

    MemoryRegion *ram = g_malloc0(sizeof(*ram));

    hwaddr ram_bases[2], ram_sizes[2];

    long bios_size;

    target_ulong kernel_base, initrd_base;

    long kernel_size, initrd_size;

    int linux_boot;

    int fl_idx, fl_sectors;

    DriveInfo *dinfo;

    /* RAM is soldered to the board so the size cannot be changed */

    ram_size = 0x08000000;

    memory_region_allocate_system_memory(ram, NULL, "taihu_405ep.ram",

                                         ram_size);

    ram_bases[0] = 0;

    ram_sizes[0] = 0x04000000;

    memory_region_init_alias(&ram_memories[0], NULL,

                             "taihu_405ep.ram-0", ram, ram_bases[0],

                             ram_sizes[0]);

    ram_bases[1] = 0x04000000;

    ram_sizes[1] = 0x04000000;

    memory_region_init_alias(&ram_memories[1], NULL,

                             "taihu_405ep.ram-1", ram, ram_bases[1],

                             ram_sizes[1]);

#ifdef DEBUG_BOARD_INIT

    printf("%s: register cpu\n", __func__);

#endif

    ppc405ep_init(sysmem, ram_memories, ram_bases, ram_sizes,

                  33333333, &pic, kernel_filename == NULL ? 0 : 1);

    /* allocate and load BIOS */

#ifdef DEBUG_BOARD_INIT

    printf("%s: register BIOS\n", __func__);

#endif

    fl_idx = 0;

#if defined(USE_FLASH_BIOS)

    dinfo = drive_get(IF_PFLASH, 0, fl_idx);

    if (dinfo) {

        BlockDriverState *bs = blk_bs(blk_by_legacy_dinfo(dinfo));

        bios_size = bdrv_getlength(bs);

        /* XXX: should check that size is 2MB */

        //        bios_size = 2 * 1024 * 1024;

        fl_sectors = (bios_size + 65535) >> 16;

#ifdef DEBUG_BOARD_INIT

        printf("Register parallel flash %d size %lx"

               " at addr %lx '%s' %d\n",

               fl_idx, bios_size, -bios_size,

               bdrv_get_device_name(bs), fl_sectors);

#endif

        pflash_cfi02_register((uint32_t)(-bios_size),

                              NULL, "taihu_405ep.bios", bios_size,

                              bs, 65536, fl_sectors, 1,

                              4, 0x0001, 0x22DA, 0x0000, 0x0000, 0x555, 0x2AA,

                              1);

        fl_idx++;

    } else

#endif

    {

#ifdef DEBUG_BOARD_INIT

        printf("Load BIOS from file\n");

#endif

        if (bios_name == NULL)

            bios_name = BIOS_FILENAME;

        bios = g_new(MemoryRegion, 1);

        memory_region_init_ram(bios, NULL, "taihu_405ep.bios", BIOS_SIZE,

                               &error_abort);

        vmstate_register_ram_global(bios);

        filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);

        if (filename) {

            bios_size = load_image(filename, memory_region_get_ram_ptr(bios));

            g_free(filename);

            if (bios_size < 0 || bios_size > BIOS_SIZE) {

                error_report("Could not load PowerPC BIOS '%s'", bios_name);

                exit(1);

            }

            bios_size = (bios_size + 0xfff) & ~0xfff;

            memory_region_add_subregion(sysmem, (uint32_t)(-bios_size), bios);

        } else if (!qtest_enabled()) {

            error_report("Could not load PowerPC BIOS '%s'", bios_name);

            exit(1);

        }

        memory_region_set_readonly(bios, true);

    }

    /* Register Linux flash */

    dinfo = drive_get(IF_PFLASH, 0, fl_idx);

    if (dinfo) {

        BlockDriverState *bs = blk_bs(blk_by_legacy_dinfo(dinfo));

        bios_size = bdrv_getlength(bs);

        /* XXX: should check that size is 32MB */

        bios_size = 32 * 1024 * 1024;

        fl_sectors = (bios_size + 65535) >> 16;

#ifdef DEBUG_BOARD_INIT

        printf("Register parallel flash %d size %lx"

               " at addr " TARGET_FMT_lx " '%s'\n",

               fl_idx, bios_size, (target_ulong)0xfc000000,

               bdrv_get_device_name(bs));

#endif

        pflash_cfi02_register(0xfc000000, NULL, "taihu_405ep.flash", bios_size,

                              bs, 65536, fl_sectors, 1,

                              4, 0x0001, 0x22DA, 0x0000, 0x0000, 0x555, 0x2AA,

                              1);

        fl_idx++;

    }

    /* Register CLPD & LCD display */

#ifdef DEBUG_BOARD_INIT

    printf("%s: register CPLD\n", __func__);

#endif

    taihu_cpld_init(sysmem, 0x50100000);

    /* Load kernel */

    linux_boot = (kernel_filename != NULL);

    if (linux_boot) {

#ifdef DEBUG_BOARD_INIT

        printf("%s: load kernel\n", __func__);

#endif

        kernel_base = KERNEL_LOAD_ADDR;

        /* now we can load the kernel */

        kernel_size = load_image_targphys(kernel_filename, kernel_base,

                                          ram_size - kernel_base);

        if (kernel_size < 0) {

            fprintf(stderr, "qemu: could not load kernel '%s'\n",

                    kernel_filename);

            exit(1);

        }

        /* load initrd */

        if (initrd_filename) {

            initrd_base = INITRD_LOAD_ADDR;

            initrd_size = load_image_targphys(initrd_filename, initrd_base,

                                              ram_size - initrd_base);

            if (initrd_size < 0) {

                fprintf(stderr,

                        "qemu: could not load initial ram disk '%s'\n",

                        initrd_filename);

                exit(1);

            }

        } else {

            initrd_base = 0;

            initrd_size = 0;

        }

    } else {

        kernel_base = 0;

        kernel_size = 0;

        initrd_base = 0;

        initrd_size = 0;

    }

#ifdef DEBUG_BOARD_INIT

    printf("%s: Done\n", __func__);

#endif

}


static void *ff_avio_child_next(void *obj, void *prev)

{

    AVIOContext *s = obj;

    AVIOInternal *internal = s->opaque;

    return prev ? NULL : internal->h;

}


static void pm_ioport_read(IORange *ioport, uint64_t addr, unsigned width,

                            uint64_t *data)

{

    PIIX4PMState *s = container_of(ioport, PIIX4PMState, ioport);

    uint32_t val;

    switch(addr) {

    case 0x00:

        val = acpi_pm1_evt_get_sts(&s->ar, s->ar.tmr.overflow_time);

        break;

    case 0x02:

        val = s->ar.pm1.evt.en;

        break;

    case 0x04:

        val = s->ar.pm1.cnt.cnt;

        break;

    case 0x08:

        val = acpi_pm_tmr_get(&s->ar);

        break;

    default:

        val = 0;

        break;

    }

    PIIX4_DPRINTF("PM readw port=0x%04x val=0x%04x\n", (unsigned int)addr, val);

    *data = val;

}


static int update_dimensions(VP8Context *s, int width, int height)

{

    if (width  != s->avctx->width ||

        height != s->avctx->height) {

        if (av_image_check_size(width, height, 0, s->avctx))

            return AVERROR_INVALIDDATA;

        vp8_decode_flush_impl(s->avctx, 1, 0, 1);

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

    }

    s->mb_width  = (s->avctx->coded_width +15) / 16;

    s->mb_height = (s->avctx->coded_height+15) / 16;

    s->macroblocks_base        = av_mallocz((s->mb_width+s->mb_height*2+1)*sizeof(*s->macroblocks));

    s->filter_strength         = av_mallocz(s->mb_width*sizeof(*s->filter_strength));

    s->intra4x4_pred_mode_top  = av_mallocz(s->mb_width*4);

    s->top_nnz                 = av_mallocz(s->mb_width*sizeof(*s->top_nnz));

    s->top_border              = av_mallocz((s->mb_width+1)*sizeof(*s->top_border));

    if (!s->macroblocks_base || !s->filter_strength || !s->intra4x4_pred_mode_top ||

        !s->top_nnz || !s->top_border)

        return AVERROR(ENOMEM);

    s->macroblocks        = s->macroblocks_base + 1;

    return 0;

}


int nbd_receive_reply(QIOChannel *ioc, NBDReply *reply, Error **errp)

{

    int ret;

    const char *type;

    ret = nbd_read_eof(ioc, &reply->magic, sizeof(reply->magic), errp);

    if (ret <= 0) {

        return ret;

    }

    be32_to_cpus(&reply->magic);

    switch (reply->magic) {

    case NBD_SIMPLE_REPLY_MAGIC:

        ret = nbd_receive_simple_reply(ioc, &reply->simple, errp);

        if (ret < 0) {

            break;

        }

        trace_nbd_receive_simple_reply(reply->simple.error,

                                       nbd_err_lookup(reply->simple.error),

                                       reply->handle);

        if (reply->simple.error == NBD_ESHUTDOWN) {

            /* This works even on mingw which lacks a native ESHUTDOWN */

            error_setg(errp, "server shutting down");

            return -EINVAL;

        }

        break;

    case NBD_STRUCTURED_REPLY_MAGIC:

        ret = nbd_receive_structured_reply_chunk(ioc, &reply->structured, errp);

        if (ret < 0) {

            break;

        }

        type = nbd_reply_type_lookup(reply->structured.type);

        trace_nbd_receive_structured_reply_chunk(reply->structured.flags,

                                                 reply->structured.type, type,

                                                 reply->structured.handle,

                                                 reply->structured.length);

        break;

    default:

        error_setg(errp, "invalid magic (got 0x%" PRIx32 ")", reply->magic);

        return -EINVAL;

    }

    if (ret < 0) {

        return ret;

    }

    return 1;

}


static void ne2000_receive(void *opaque, const uint8_t *buf, int size)

{

    NE2000State *s = opaque;

    uint8_t *p;

    int total_len, next, avail, len, index, mcast_idx;

    uint8_t buf1[60];

    static const uint8_t broadcast_macaddr[6] =

        { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };

#if defined(DEBUG_NE2000)

    printf("NE2000: received len=%d\n", size);

#endif

    if (!ne2000_can_receive(s))

        return;

    /* XXX: check this */

    if (s->rxcr & 0x10) {

        /* promiscuous: receive all */

    } else {

        if (!memcmp(buf,  broadcast_macaddr, 6)) {

            /* broadcast address */

            if (!(s->rxcr & 0x04))

                return;

        } else if (buf[0] & 0x01) {

            /* multicast */

            if (!(s->rxcr & 0x08))

                return;

            mcast_idx = compute_mcast_idx(buf);

            if (!(s->mult[mcast_idx >> 3] & (1 << (mcast_idx & 7))))

                return;

        } else if (s->mem[0] == buf[0] &&

                   s->mem[2] == buf[1] &&

                   s->mem[4] == buf[2] &&

                   s->mem[6] == buf[3] &&

                   s->mem[8] == buf[4] &&

                   s->mem[10] == buf[5]) {

            /* match */

        } else {

            return;

        }

    }

    /* if too small buffer, then expand it */

    if (size < MIN_BUF_SIZE) {

        memcpy(buf1, buf, size);

        memset(buf1 + size, 0, MIN_BUF_SIZE - size);

        buf = buf1;

        size = MIN_BUF_SIZE;

    }

    index = s->curpag << 8;

    /* 4 bytes for header */

    total_len = size + 4;

    /* address for next packet (4 bytes for CRC) */

    next = index + ((total_len + 4 + 255) & ~0xff);

    if (next >= s->stop)

        next -= (s->stop - s->start);

    /* prepare packet header */

    p = s->mem + index;

    s->rsr = ENRSR_RXOK; /* receive status */

    /* XXX: check this */

    if (buf[0] & 0x01)

        s->rsr |= ENRSR_PHY;

    p[0] = s->rsr;

    p[1] = next >> 8;

    p[2] = total_len;

    p[3] = total_len >> 8;

    index += 4;

    /* write packet data */

    while (size > 0) {

        avail = s->stop - index;

        len = size;

        if (len > avail)

            len = avail;

        memcpy(s->mem + index, buf, len);

        buf += len;

        index += len;

        if (index == s->stop)

            index = s->start;

        size -= len;

    }

    s->curpag = next >> 8;

    /* now we can signal we have receive something */

    s->isr |= ENISR_RX;

    ne2000_update_irq(s);

}


static void truespeech_apply_twopoint_filter(TSContext *dec, int quart)

{

    int16_t tmp[146 + 60], *ptr0, *ptr1;

    const int16_t *filter;

    int i, t, off;

    t = dec->offset2[quart];

    if(t == 127){

        memset(dec->newvec, 0, 60 * sizeof(*dec->newvec));

        return;

    }

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

        tmp[i] = dec->filtbuf[i];

    off = (t / 25) + dec->offset1[quart >> 1] + 18;

    ptr0 = tmp + 145 - off;

    ptr1 = tmp + 146;

    filter = (const int16_t*)ts_order2_coeffs + (t % 25) * 2;

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

        t = (ptr0[0] * filter[0] + ptr0[1] * filter[1] + 0x2000) >> 14;

        ptr0++;

        dec->newvec[i] = t;

        ptr1[i] = t;

    }

}


static void scsi_disk_purge_requests(SCSIDiskState *s)

{

    SCSIDiskReq *r;

    while (!QTAILQ_EMPTY(&s->qdev.requests)) {

        r = DO_UPCAST(SCSIDiskReq, req, QTAILQ_FIRST(&s->qdev.requests));

        if (r->req.aiocb) {

            bdrv_aio_cancel(r->req.aiocb);

        }

        scsi_remove_request(r);

    }

}


static int net_slirp_init(VLANState *vlan)

{

    if (!slirp_inited) {

        slirp_inited = 1;

        slirp_init();

    }

    slirp_vc = qemu_new_vlan_client(vlan,

                                    slirp_receive, NULL);

    snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");

    return 0;

}


static int pnm_decode_header(AVCodecContext *avctx, PNMContext * const s){

    char buf1[32], tuple_type[32];

    int h, w, depth, maxval;;

    pnm_get(s, buf1, sizeof(buf1));

    if (!strcmp(buf1, "P4")) {

        avctx->pix_fmt = PIX_FMT_MONOWHITE;

    } else if (!strcmp(buf1, "P5")) {

        if (avctx->codec_id == CODEC_ID_PGMYUV)

            avctx->pix_fmt = PIX_FMT_YUV420P;

        else

            avctx->pix_fmt = PIX_FMT_GRAY8;

    } else if (!strcmp(buf1, "P6")) {

        avctx->pix_fmt = PIX_FMT_RGB24;

    } else if (!strcmp(buf1, "P7")) {

        w = -1;

        h = -1;

        maxval = -1;

        depth = -1;

        tuple_type[0] = '\0';

        for(;;) {

            pnm_get(s, buf1, sizeof(buf1));

            if (!strcmp(buf1, "WIDTH")) {

                pnm_get(s, buf1, sizeof(buf1));

                w = strtol(buf1, NULL, 10);

            } else if (!strcmp(buf1, "HEIGHT")) {

                pnm_get(s, buf1, sizeof(buf1));

                h = strtol(buf1, NULL, 10);

            } else if (!strcmp(buf1, "DEPTH")) {

                pnm_get(s, buf1, sizeof(buf1));

                depth = strtol(buf1, NULL, 10);

            } else if (!strcmp(buf1, "MAXVAL")) {

                pnm_get(s, buf1, sizeof(buf1));

                maxval = strtol(buf1, NULL, 10);

            } else if (!strcmp(buf1, "TUPLETYPE")) {

                pnm_get(s, tuple_type, sizeof(tuple_type));

            } else if (!strcmp(buf1, "ENDHDR")) {

                break;

            } else {

                return -1;

            }

        }

        /* check that all tags are present */

        if (w <= 0 || h <= 0 || maxval <= 0 || depth <= 0 || tuple_type[0] == '\0')

            return -1;

        avctx->width = w;

        avctx->height = h;

        if (depth == 1) {

            if (maxval == 1)

                avctx->pix_fmt = PIX_FMT_MONOWHITE;

            else

                avctx->pix_fmt = PIX_FMT_GRAY8;

        } else if (depth == 3) {

            avctx->pix_fmt = PIX_FMT_RGB24;

        } else if (depth == 4) {

            avctx->pix_fmt = PIX_FMT_RGBA32;

        } else {

            return -1;

        }

        return 0;

    } else {

        return -1;

    }

    pnm_get(s, buf1, sizeof(buf1));

    avctx->width = atoi(buf1);

    if (avctx->width <= 0)

        return -1;

    pnm_get(s, buf1, sizeof(buf1));

    avctx->height = atoi(buf1);

    if (avctx->height <= 0)

        return -1;

    if (avctx->pix_fmt != PIX_FMT_MONOWHITE) {

        pnm_get(s, buf1, sizeof(buf1));

    }

    /* more check if YUV420 */

    if (avctx->pix_fmt == PIX_FMT_YUV420P) {

        if ((avctx->width & 1) != 0)

            return -1;

        h = (avctx->height * 2);

        if ((h % 3) != 0)

            return -1;

        h /= 3;

        avctx->height = h;

    }

    return 0;

}


void cpu_physical_memory_rw(target_phys_addr_t addr, uint8_t *buf,

                            int len, int is_write)

{

    return address_space_rw(&address_space_memory, addr, buf, len, is_write);

}


static void v9fs_link(void *opaque)

{

    V9fsPDU *pdu = opaque;

    V9fsState *s = pdu->s;

    int32_t dfid, oldfid;

    V9fsFidState *dfidp, *oldfidp;

    V9fsString name;

    size_t offset = 7;

    int err = 0;

    pdu_unmarshal(pdu, offset, "dds", &dfid, &oldfid, &name);

    trace_v9fs_link(pdu->tag, pdu->id, dfid, oldfid, name.data);

    dfidp = get_fid(pdu, dfid);

    if (dfidp == NULL) {

        err = -ENOENT;

        goto out_nofid;

    }

    oldfidp = get_fid(pdu, oldfid);

    if (oldfidp == NULL) {

        err = -ENOENT;

        goto out;

    }

    err = v9fs_co_link(pdu, oldfidp, dfidp, &name);

    if (!err) {

        err = offset;

    }

out:

    put_fid(pdu, dfidp);

out_nofid:

    v9fs_string_free(&name);

    complete_pdu(s, pdu, err);

}


int dxva2_init(AVCodecContext *s)

{

    InputStream *ist = s->opaque;

    int loglevel = (ist->hwaccel_id == HWACCEL_AUTO) ? AV_LOG_VERBOSE : AV_LOG_ERROR;

    DXVA2Context *ctx;

    int ret;

    if (!ist->hwaccel_ctx) {

        ret = dxva2_alloc(s);

        if (ret < 0)

            return ret;

    }

    ctx = ist->hwaccel_ctx;

    if (s->codec_id == AV_CODEC_ID_H264 &&

        (s->profile & ~FF_PROFILE_H264_CONSTRAINED) > FF_PROFILE_H264_HIGH) {

        av_log(NULL, loglevel, "Unsupported H.264 profile for DXVA2 HWAccel: %d\n", s->profile);

        return AVERROR(EINVAL);

    }

    if (s->codec_id == AV_CODEC_ID_HEVC &&

        s->profile != FF_PROFILE_HEVC_MAIN && s->profile != FF_PROFILE_HEVC_MAIN_10) {

        av_log(NULL, loglevel, "Unsupported HEVC profile for DXVA2 HWAccel: %d\n", s->profile);

        return AVERROR(EINVAL);

    }

    av_buffer_unref(&ctx->hw_frames_ctx);

    ret = dxva2_create_decoder(s);

    if (ret < 0) {

        av_log(NULL, loglevel, "Error creating the DXVA2 decoder\n");

        return ret;

    }

    return 0;

}


static XenPTBarFlag xen_pt_bar_reg_parse(XenPCIPassthroughState *s,

                                         XenPTRegInfo *reg)

{

    PCIDevice *d = &s->dev;

    XenPTRegion *region = NULL;

    PCIIORegion *r;

    int index = 0;

    /* check 64bit BAR */

    index = xen_pt_bar_offset_to_index(reg->offset);

    if ((0 < index) && (index < PCI_ROM_SLOT)) {

        int type = s->real_device.io_regions[index - 1].type;

        if ((type & XEN_HOST_PCI_REGION_TYPE_MEM)

            && (type & XEN_HOST_PCI_REGION_TYPE_MEM_64)) {

            region = &s->bases[index - 1];

            if (region->bar_flag != XEN_PT_BAR_FLAG_UPPER) {

                return XEN_PT_BAR_FLAG_UPPER;

            }

        }

    }

    /* check unused BAR */

    r = &d->io_regions[index];

    if (!xen_pt_get_bar_size(r)) {

        return XEN_PT_BAR_FLAG_UNUSED;

    }

    /* for ExpROM BAR */

    if (index == PCI_ROM_SLOT) {

        return XEN_PT_BAR_FLAG_MEM;

    }

    /* check BAR I/O indicator */

    if (s->real_device.io_regions[index].type & XEN_HOST_PCI_REGION_TYPE_IO) {

        return XEN_PT_BAR_FLAG_IO;

    } else {

        return XEN_PT_BAR_FLAG_MEM;

    }

}


static av_cold int g726_encode_init(AVCodecContext *avctx)

{

    G726Context* c = avctx->priv_data;

    if (avctx->strict_std_compliance > FF_COMPLIANCE_UNOFFICIAL &&

        avctx->sample_rate != 8000) {

        av_log(avctx, AV_LOG_ERROR, "Sample rates other than 8kHz are not "

               "allowed when the compliance level is higher than unofficial. "

               "Resample or reduce the compliance level.\n");

        return AVERROR(EINVAL);

    }

    if (avctx->sample_rate <= 0) {

        av_log(avctx, AV_LOG_ERROR, "Samplerate is invalid\n");

        return -1;

    }

    if(avctx->channels != 1){

        av_log(avctx, AV_LOG_ERROR, "Only mono is supported\n");

        return -1;

    }

    if (avctx->bit_rate % avctx->sample_rate) {

        av_log(avctx, AV_LOG_ERROR, "Bitrate - Samplerate combination is invalid\n");

        return AVERROR(EINVAL);

    }

    c->code_size = (avctx->bit_rate + avctx->sample_rate/2) / avctx->sample_rate;

    if (c->code_size < 2 || c->code_size > 5) {

        av_log(avctx, AV_LOG_ERROR, "Invalid number of bits %d\n", c->code_size);

        return AVERROR(EINVAL);

    }

    avctx->bits_per_coded_sample = c->code_size;

    g726_reset(c, c->code_size - 2);

    avctx->coded_frame = avcodec_alloc_frame();

    if (!avctx->coded_frame)

        return AVERROR(ENOMEM);

    avctx->coded_frame->key_frame = 1;

    /* select a frame size that will end on a byte boundary and have a size of

       approximately 1024 bytes */

    avctx->frame_size = ((int[]){ 4096, 2736, 2048, 1640 })[c->code_size - 2];

    return 0;

}


static int dv_read_seek(AVFormatContext *s, int stream_index,

                       int64_t timestamp, int flags)

{

    RawDVContext *r   = s->priv_data;

    DVDemuxContext *c = r->dv_demux;

    int64_t offset    = dv_frame_offset(s, c, timestamp, flags);

    dv_offset_reset(c, offset / c->sys->frame_size);

    offset = avio_seek(s->pb, offset, SEEK_SET);

    return (offset < 0) ? offset : 0;

}


static void spapr_phb_hot_plug_child(HotplugHandler *plug_handler,

                                     DeviceState *plugged_dev, Error **errp)

{

    sPAPRPHBState *phb = SPAPR_PCI_HOST_BRIDGE(DEVICE(plug_handler));

    PCIDevice *pdev = PCI_DEVICE(plugged_dev);

    sPAPRDRConnector *drc = spapr_phb_get_pci_drc(phb, pdev);

    Error *local_err = NULL;

    /* if DR is disabled we don't need to do anything in the case of

     * hotplug or coldplug callbacks

     */

    if (!phb->dr_enabled) {

        /* if this is a hotplug operation initiated by the user

         * we need to let them know it's not enabled

         */

        if (plugged_dev->hotplugged) {

            error_setg(errp, QERR_BUS_NO_HOTPLUG,

                       object_get_typename(OBJECT(phb)));

        }

        return;

    }

    g_assert(drc);

    spapr_phb_add_pci_device(drc, phb, pdev, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        return;

    }

    if (plugged_dev->hotplugged) {

        spapr_hotplug_req_add_by_index(drc);

    }

}


av_cold int ff_dvvideo_init(AVCodecContext *avctx)

{

    DVVideoContext *s = avctx->priv_data;

    DSPContext dsp;

    static int done = 0;

    int i, j;

    if (!done) {

        VLC dv_vlc;

        uint16_t new_dv_vlc_bits[NB_DV_VLC*2];

        uint8_t  new_dv_vlc_len[NB_DV_VLC*2];

        uint8_t  new_dv_vlc_run[NB_DV_VLC*2];

        int16_t  new_dv_vlc_level[NB_DV_VLC*2];

        done = 1;

        /* it's faster to include sign bit in a generic VLC parsing scheme */

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

            new_dv_vlc_bits[j]  = dv_vlc_bits[i];

            new_dv_vlc_len[j]   = dv_vlc_len[i];

            new_dv_vlc_run[j]   = dv_vlc_run[i];

            new_dv_vlc_level[j] = dv_vlc_level[i];

            if (dv_vlc_level[i]) {

                new_dv_vlc_bits[j] <<= 1;

                new_dv_vlc_len[j]++;

                j++;

                new_dv_vlc_bits[j]  = (dv_vlc_bits[i] << 1) | 1;

                new_dv_vlc_len[j]   =  dv_vlc_len[i] + 1;

                new_dv_vlc_run[j]   =  dv_vlc_run[i];

                new_dv_vlc_level[j] = -dv_vlc_level[i];

            }

        }

        /* NOTE: as a trick, we use the fact the no codes are unused

           to accelerate the parsing of partial codes */

        init_vlc(&dv_vlc, TEX_VLC_BITS, j,

                 new_dv_vlc_len, 1, 1, new_dv_vlc_bits, 2, 2, 0);

        assert(dv_vlc.table_size == 1184);

        for (i = 0; i < dv_vlc.table_size; i++){

            int code = dv_vlc.table[i][0];

            int len  = dv_vlc.table[i][1];

            int level, run;

            if (len < 0){ //more bits needed

                run   = 0;

                level = code;

            } else {

                run   = new_dv_vlc_run  [code] + 1;

                level = new_dv_vlc_level[code];

            }

            ff_dv_rl_vlc[i].len   = len;

            ff_dv_rl_vlc[i].level = level;

            ff_dv_rl_vlc[i].run   = run;

        }

        ff_free_vlc(&dv_vlc);

    }

    /* Generic DSP setup */

    ff_dsputil_init(&dsp, avctx);

    ff_set_cmp(&dsp, dsp.ildct_cmp, avctx->ildct_cmp);

    s->get_pixels = dsp.get_pixels;

    s->ildct_cmp = dsp.ildct_cmp[5];

    /* 88DCT setup */

    s->fdct[0]     = dsp.fdct;

    s->idct_put[0] = dsp.idct_put;

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

       s->dv_zigzag[0][i] = dsp.idct_permutation[ff_zigzag_direct[i]];

    /* 248DCT setup */

    s->fdct[1]     = dsp.fdct248;

    s->idct_put[1] = ff_simple_idct248_put;  // FIXME: need to add it to DSP

    memcpy(s->dv_zigzag[1], ff_zigzag248_direct, 64);

    avctx->coded_frame = &s->picture;

    s->avctx = avctx;

    avctx->chroma_sample_location = AVCHROMA_LOC_TOPLEFT;

    return 0;

}


static int libquvi_read_header(AVFormatContext *s)

{

    int i, ret;

    quvi_t q;

    quvi_media_t m;

    QUVIcode rc;

    LibQuviContext *qc = s->priv_data;

    char *media_url, *pagetitle;

    rc = quvi_init(&q);

    if (rc != QUVI_OK)

        goto quvi_fail;

    quvi_setopt(q, QUVIOPT_FORMAT, qc->format);

    rc = quvi_parse(q, s->filename, &m);

    if (rc != QUVI_OK)

        goto quvi_fail;

    rc = quvi_getprop(m, QUVIPROP_MEDIAURL, &media_url);

    if (rc != QUVI_OK)

        goto quvi_fail;

    av_assert0(!qc->fmtctx->codec_whitelist && !qc->fmtctx->format_whitelist);

    qc->fmtctx-> codec_whitelist = av_strdup(s->codec_whitelist);

    qc->fmtctx->format_whitelist = av_strdup(s->format_whitelist);

    ret = avformat_open_input(&qc->fmtctx, media_url, NULL, NULL);

    if (ret < 0)

        goto end;

    rc = quvi_getprop(m, QUVIPROP_PAGETITLE, &pagetitle);

    if (rc == QUVI_OK)

        av_dict_set(&s->metadata, "title", pagetitle, 0);

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

        AVStream *st = avformat_new_stream(s, NULL);

        AVStream *ist = qc->fmtctx->streams[i];

        if (!st) {

            ret = AVERROR(ENOMEM);

            goto end;

        }

        avpriv_set_pts_info(st, ist->pts_wrap_bits, ist->time_base.num, ist->time_base.den);

        avcodec_copy_context(st->codec, qc->fmtctx->streams[i]->codec);

    }

    return 0;

quvi_fail:

    av_log(s, AV_LOG_ERROR, "%s\n", quvi_strerror(q, rc));

    ret = AVERROR_EXTERNAL;

end:

    quvi_parse_close(&m);

    quvi_close(&q);

    return ret;

}


static int add_old_style_options(const char *fmt, QemuOpts *opts,

                                 const char *base_filename,

                                 const char *base_fmt)

{

    if (base_filename) {

        if (qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename)) {

            error_report("Backing file not supported for file format '%s'",

                         fmt);

            return -1;

        }

    }

    if (base_fmt) {

        if (qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt)) {

            error_report("Backing file format not supported for file "

                         "format '%s'", fmt);

            return -1;

        }

    }

    return 0;

}


void qemu_flush_queued_packets(VLANClientState *vc)

{

    while (!TAILQ_EMPTY(&vc->vlan->send_queue)) {

        VLANPacket *packet;

        int ret;

        packet = TAILQ_FIRST(&vc->vlan->send_queue);

        TAILQ_REMOVE(&vc->vlan->send_queue, packet, entry);

        ret = qemu_deliver_packet(packet->sender, packet->data, packet->size);

        if (ret == 0 && packet->sent_cb != NULL) {

            TAILQ_INSERT_HEAD(&vc->vlan->send_queue, packet, entry);

            break;

        }

        if (packet->sent_cb)

            packet->sent_cb(packet->sender, ret);

        qemu_free(packet);

    }

}


LF_FUNC (h,  luma,         sse2)

LF_IFUNC(h,  luma_intra,   sse2)

LF_FUNC (v,  luma,         sse2)

LF_IFUNC(v,  luma_intra,   sse2)

/***********************************/

/* weighted prediction */

#define H264_WEIGHT(W, H, OPT) \

void ff_h264_weight_ ## W ## x ## H ## _ ## OPT(uint8_t *dst, \

    int stride, int log2_denom, int weight, int offset);

#define H264_BIWEIGHT(W, H, OPT) \

void ff_h264_biweight_ ## W ## x ## H ## _ ## OPT(uint8_t *dst, \

    uint8_t *src, int stride, int log2_denom, int weightd, \

    int weights, int offset);

#define H264_BIWEIGHT_MMX(W,H) \

H264_WEIGHT  (W, H, mmx2) \

H264_BIWEIGHT(W, H, mmx2)

#define H264_BIWEIGHT_MMX_SSE(W,H) \

H264_BIWEIGHT_MMX(W, H) \

H264_WEIGHT      (W, H, sse2) \

H264_BIWEIGHT    (W, H, sse2) \

H264_BIWEIGHT    (W, H, ssse3)

H264_BIWEIGHT_MMX_SSE(16, 16)

H264_BIWEIGHT_MMX_SSE(16,  8)

H264_BIWEIGHT_MMX_SSE( 8, 16)

H264_BIWEIGHT_MMX_SSE( 8,  8)

H264_BIWEIGHT_MMX_SSE( 8,  4)

H264_BIWEIGHT_MMX    ( 4,  8)

H264_BIWEIGHT_MMX    ( 4,  4)

H264_BIWEIGHT_MMX    ( 4,  2)

void ff_h264dsp_init_x86(H264DSPContext *c)

{

    int mm_flags = av_get_cpu_flags();

    if (mm_flags & AV_CPU_FLAG_MMX2) {

        c->h264_loop_filter_strength= h264_loop_filter_strength_mmx2;

    }

#if HAVE_YASM

    if (mm_flags & AV_CPU_FLAG_MMX) {

        c->h264_idct_dc_add=

        c->h264_idct_add= ff_h264_idct_add_mmx;

        c->h264_idct8_dc_add=

        c->h264_idct8_add= ff_h264_idct8_add_mmx;

        c->h264_idct_add16     = ff_h264_idct_add16_mmx;

        c->h264_idct8_add4     = ff_h264_idct8_add4_mmx;

        c->h264_idct_add8      = ff_h264_idct_add8_mmx;

        c->h264_idct_add16intra= ff_h264_idct_add16intra_mmx;

        if (mm_flags & AV_CPU_FLAG_MMX2) {

            c->h264_idct_dc_add= ff_h264_idct_dc_add_mmx2;

            c->h264_idct8_dc_add= ff_h264_idct8_dc_add_mmx2;

            c->h264_idct_add16     = ff_h264_idct_add16_mmx2;

            c->h264_idct8_add4     = ff_h264_idct8_add4_mmx2;

            c->h264_idct_add8      = ff_h264_idct_add8_mmx2;

            c->h264_idct_add16intra= ff_h264_idct_add16intra_mmx2;

            c->h264_v_loop_filter_chroma= ff_x264_deblock_v_chroma_mmxext;

            c->h264_h_loop_filter_chroma= ff_x264_deblock_h_chroma_mmxext;

            c->h264_v_loop_filter_chroma_intra= ff_x264_deblock_v_chroma_intra_mmxext;

            c->h264_h_loop_filter_chroma_intra= ff_x264_deblock_h_chroma_intra_mmxext;

#if ARCH_X86_32

            c->h264_v_loop_filter_luma= ff_x264_deblock_v_luma_mmxext;

            c->h264_h_loop_filter_luma= ff_x264_deblock_h_luma_mmxext;

            c->h264_v_loop_filter_luma_intra = ff_x264_deblock_v_luma_intra_mmxext;

            c->h264_h_loop_filter_luma_intra = ff_x264_deblock_h_luma_intra_mmxext;

            c->weight_h264_pixels_tab[0]= ff_h264_weight_16x16_mmx2;

            c->weight_h264_pixels_tab[1]= ff_h264_weight_16x8_mmx2;

            c->weight_h264_pixels_tab[2]= ff_h264_weight_8x16_mmx2;

            c->weight_h264_pixels_tab[3]= ff_h264_weight_8x8_mmx2;

            c->weight_h264_pixels_tab[4]= ff_h264_weight_8x4_mmx2;

            c->weight_h264_pixels_tab[5]= ff_h264_weight_4x8_mmx2;

            c->weight_h264_pixels_tab[6]= ff_h264_weight_4x4_mmx2;

            c->weight_h264_pixels_tab[7]= ff_h264_weight_4x2_mmx2;

            c->biweight_h264_pixels_tab[0]= ff_h264_biweight_16x16_mmx2;

            c->biweight_h264_pixels_tab[1]= ff_h264_biweight_16x8_mmx2;

            c->biweight_h264_pixels_tab[2]= ff_h264_biweight_8x16_mmx2;

            c->biweight_h264_pixels_tab[3]= ff_h264_biweight_8x8_mmx2;

            c->biweight_h264_pixels_tab[4]= ff_h264_biweight_8x4_mmx2;

            c->biweight_h264_pixels_tab[5]= ff_h264_biweight_4x8_mmx2;

            c->biweight_h264_pixels_tab[6]= ff_h264_biweight_4x4_mmx2;

            c->biweight_h264_pixels_tab[7]= ff_h264_biweight_4x2_mmx2;

            if (mm_flags&AV_CPU_FLAG_SSE2) {

                c->h264_idct8_add = ff_h264_idct8_add_sse2;

                c->h264_idct8_add4= ff_h264_idct8_add4_sse2;

                c->weight_h264_pixels_tab[0]= ff_h264_weight_16x16_sse2;

                c->weight_h264_pixels_tab[1]= ff_h264_weight_16x8_sse2;

                c->weight_h264_pixels_tab[2]= ff_h264_weight_8x16_sse2;

                c->weight_h264_pixels_tab[3]= ff_h264_weight_8x8_sse2;

                c->weight_h264_pixels_tab[4]= ff_h264_weight_8x4_sse2;

                c->biweight_h264_pixels_tab[0]= ff_h264_biweight_16x16_sse2;

                c->biweight_h264_pixels_tab[1]= ff_h264_biweight_16x8_sse2;

                c->biweight_h264_pixels_tab[2]= ff_h264_biweight_8x16_sse2;

                c->biweight_h264_pixels_tab[3]= ff_h264_biweight_8x8_sse2;

                c->biweight_h264_pixels_tab[4]= ff_h264_biweight_8x4_sse2;

                c->h264_v_loop_filter_luma = ff_x264_deblock_v_luma_sse2;

                c->h264_h_loop_filter_luma = ff_x264_deblock_h_luma_sse2;

                c->h264_v_loop_filter_luma_intra = ff_x264_deblock_v_luma_intra_sse2;

                c->h264_h_loop_filter_luma_intra = ff_x264_deblock_h_luma_intra_sse2;

                c->h264_idct_add16 = ff_h264_idct_add16_sse2;

                c->h264_idct_add8  = ff_h264_idct_add8_sse2;

                c->h264_idct_add16intra = ff_h264_idct_add16intra_sse2;

            }

            if (mm_flags&AV_CPU_FLAG_SSSE3) {

                c->biweight_h264_pixels_tab[0]= ff_h264_biweight_16x16_ssse3;

                c->biweight_h264_pixels_tab[1]= ff_h264_biweight_16x8_ssse3;

                c->biweight_h264_pixels_tab[2]= ff_h264_biweight_8x16_ssse3;

                c->biweight_h264_pixels_tab[3]= ff_h264_biweight_8x8_ssse3;

                c->biweight_h264_pixels_tab[4]= ff_h264_biweight_8x4_ssse3;

            }

        }

    }

}


static int decode_band_hdr(IVI45DecContext *ctx, IVIBandDesc *band,

                           AVCodecContext *avctx)

{

    int plane, band_num, indx, transform_id, scan_indx;

    int i;

    plane    = get_bits(&ctx->gb, 2);

    band_num = get_bits(&ctx->gb, 4);

    if (band->plane != plane || band->band_num != band_num) {

        av_log(avctx, AV_LOG_ERROR, "Invalid band header sequence!\n");

        return AVERROR_INVALIDDATA;

    }

    band->is_empty = get_bits1(&ctx->gb);

    if (!band->is_empty) {

        int old_blk_size = band->blk_size;

        /* skip header size

         * If header size is not given, header size is 4 bytes. */

        if (get_bits1(&ctx->gb))

            skip_bits(&ctx->gb, 16);

        band->is_halfpel = get_bits(&ctx->gb, 2);

        if (band->is_halfpel >= 2) {

            av_log(avctx, AV_LOG_ERROR, "Invalid/unsupported mv resolution: %d!\n",

                   band->is_halfpel);

            return AVERROR_INVALIDDATA;

        }

#if IVI4_STREAM_ANALYSER

        if (!band->is_halfpel)

            ctx->uses_fullpel = 1;

#endif

        band->checksum_present = get_bits1(&ctx->gb);

        if (band->checksum_present)

            band->checksum = get_bits(&ctx->gb, 16);

        indx = get_bits(&ctx->gb, 2);

        if (indx == 3) {

            av_log(avctx, AV_LOG_ERROR, "Invalid block size!\n");

            return AVERROR_INVALIDDATA;

        }

        band->mb_size  = 16 >> indx;

        band->blk_size = 8 >> (indx >> 1);

        band->inherit_mv     = get_bits1(&ctx->gb);

        band->inherit_qdelta = get_bits1(&ctx->gb);

        band->glob_quant = get_bits(&ctx->gb, 5);

        if (!get_bits1(&ctx->gb) || ctx->frame_type == IVI4_FRAMETYPE_INTRA) {

            transform_id = get_bits(&ctx->gb, 5);

            if (transform_id >= FF_ARRAY_ELEMS(transforms) ||

                !transforms[transform_id].inv_trans) {

                avpriv_request_sample(avctx, "Transform %d", transform_id);

                return AVERROR_PATCHWELCOME;

            }

            if ((transform_id >= 7 && transform_id <= 9) ||

                 transform_id == 17) {

                avpriv_request_sample(avctx, "DCT transform");

                return AVERROR_PATCHWELCOME;

            }

#if IVI4_STREAM_ANALYSER

            if ((transform_id >= 0 && transform_id <= 2) || transform_id == 10)

                ctx->uses_haar = 1;

#endif

            band->inv_transform = transforms[transform_id].inv_trans;

            band->dc_transform  = transforms[transform_id].dc_trans;

            band->is_2d_trans   = transforms[transform_id].is_2d_trans;

            if (transform_id < 10)

                band->transform_size = 8;

            else

                band->transform_size = 4;

            if (band->blk_size != band->transform_size)

                return AVERROR_INVALIDDATA;

            scan_indx = get_bits(&ctx->gb, 4);

            if (scan_indx == 15) {

                av_log(avctx, AV_LOG_ERROR, "Custom scan pattern encountered!\n");

                return AVERROR_INVALIDDATA;

            }

            if (scan_indx > 4 && scan_indx < 10) {

                if (band->blk_size != 4)

                    return AVERROR_INVALIDDATA;

            } else if (band->blk_size != 8)

                return AVERROR_INVALIDDATA;

            band->scan = scan_index_to_tab[scan_indx];

            band->quant_mat = get_bits(&ctx->gb, 5);

            if (band->quant_mat >= FF_ARRAY_ELEMS(quant_index_to_tab)) {

                if (band->quant_mat == 31)

                    av_log(avctx, AV_LOG_ERROR,

                           "Custom quant matrix encountered!\n");

                else

                    avpriv_request_sample(avctx, "Quantization matrix %d",

                                          band->quant_mat);

                band->quant_mat = -1;

                return AVERROR_INVALIDDATA;

            }

        } else {

            if (old_blk_size != band->blk_size) {

                av_log(avctx, AV_LOG_ERROR,

                       "The band block size does not match the configuration "

                       "inherited\n");

                return AVERROR_INVALIDDATA;

            }

            if (band->quant_mat < 0) {

                av_log(avctx, AV_LOG_ERROR, "Invalid quant_mat inherited\n");

                return AVERROR_INVALIDDATA;

            }

        }

        /* decode block huffman codebook */

        if (!get_bits1(&ctx->gb))

            band->blk_vlc.tab = ctx->blk_vlc.tab;

        else

            if (ff_ivi_dec_huff_desc(&ctx->gb, 1, IVI_BLK_HUFF,

                                     &band->blk_vlc, avctx))

                return AVERROR_INVALIDDATA;

        /* select appropriate rvmap table for this band */

        band->rvmap_sel = get_bits1(&ctx->gb) ? get_bits(&ctx->gb, 3) : 8;

        /* decode rvmap probability corrections if any */

        band->num_corr = 0; /* there is no corrections */

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

            band->num_corr = get_bits(&ctx->gb, 8); /* get number of correction pairs */

            if (band->num_corr > 61) {

                av_log(avctx, AV_LOG_ERROR, "Too many corrections: %d\n",

                       band->num_corr);

                return AVERROR_INVALIDDATA;

            }

            /* read correction pairs */

            for (i = 0; i < band->num_corr * 2; i++)

                band->corr[i] = get_bits(&ctx->gb, 8);

        }

    }

    if (band->blk_size == 8) {

        band->intra_base = &ivi4_quant_8x8_intra[quant_index_to_tab[band->quant_mat]][0];

        band->inter_base = &ivi4_quant_8x8_inter[quant_index_to_tab[band->quant_mat]][0];

    } else {

        band->intra_base = &ivi4_quant_4x4_intra[quant_index_to_tab[band->quant_mat]][0];

        band->inter_base = &ivi4_quant_4x4_inter[quant_index_to_tab[band->quant_mat]][0];

    }

    /* Indeo 4 doesn't use scale tables */

    band->intra_scale = NULL;

    band->inter_scale = NULL;

    align_get_bits(&ctx->gb);

    return 0;

}