static int init_directory(BDRVVVFATState* s,const char* dirname)

{

    bootsector_t* bootsector=(bootsector_t*)&(s->first_sectors[(s->first_sectors_number-1)*0x200]);

    unsigned int i;

    unsigned int cluster;

    memset(&(s->first_sectors[0]),0,0x40*0x200);

    /* TODO: if FAT32, this is probably wrong */

    s->sectors_per_fat=0xfc;

    s->sectors_per_cluster=0x10;

    s->cluster_size=s->sectors_per_cluster*0x200;

    s->cluster=malloc(s->cluster_size);

    array_init(&(s->mapping),sizeof(mapping_t));

    array_init(&(s->directory),sizeof(direntry_t));

    array_init(&(s->commit),sizeof(commit_t));

    /* add volume label */

    {

	direntry_t* entry=array_get_next(&(s->directory));

	entry->attributes=0x28; /* archive | volume label */

	snprintf(entry->name,11,"QEMU VVFAT");

    }

    if(read_directory(s,dirname,0))

	return -1;

    /* make sure that the number of directory entries is multiple of 0x200/0x20 (to fit the last sector exactly) */

    s->sectors_for_directory=s->directory.next/0x10;

    s->faked_sectors=s->first_sectors_number+s->sectors_per_fat*2+s->sectors_for_directory;

    s->cluster_count=(s->sector_count-s->faked_sectors)/s->sectors_per_cluster;

    /* Now build FAT, and write back information into directory */

    init_fat(s);

    cluster=s->sectors_for_directory/s->sectors_per_cluster;

    assert(s->sectors_for_directory%s->sectors_per_cluster==0);

    /* set the end of the last read directory */

    if(s->first_file_mapping>0) {

	mapping_t* mapping=array_get(&(s->mapping),s->first_file_mapping-1);

	mapping->end=cluster;

    }

    for(i=1;i<s->mapping.next;i++) {

	mapping_t* mapping=array_get(&(s->mapping),i);

	direntry_t* direntry=array_get(&(s->directory),mapping->dir_index);

	if(mapping->mode==MODE_DIRECTORY) {

	    /* directory */

	    int i;

#ifdef DEBUG

	    fprintf(stderr,"assert: %s %d < %d\n",mapping->filename,(int)mapping->begin,(int)mapping->end);

#endif

	    assert(mapping->begin<mapping->end);

	    for(i=mapping->begin;i<mapping->end-1;i++)

		fat_set(s,i,i+1);

	    fat_set(s,i,0x7fffffff);

	} else {

	    /* as the space is virtual, we can be sloppy about it */

	    unsigned int end_cluster=cluster+mapping->end/s->cluster_size;

	    if(end_cluster>=s->cluster_count) {

		fprintf(stderr,"Directory does not fit in FAT%d\n",s->fat_type);

		return -1;

	    }

	    mapping->begin=cluster;

	    mapping->mode=MODE_NORMAL;

	    mapping->offset=0;

	    direntry->size=cpu_to_le32(mapping->end);

	    if(direntry->size==0) {

		direntry->begin=0;

		mapping->end=cluster;

		continue;

	    }

	    direntry->begin=cpu_to_le16(cluster);

	    mapping->end=end_cluster+1;

	    for(;cluster<end_cluster;cluster++)

	        fat_set(s,cluster,cluster+1);

	    fat_set(s,cluster,0x7fffffff);

	    cluster++;

	}

    }

    s->current_mapping=0;

    bootsector->jump[0]=0xeb;

    bootsector->jump[1]=0x3e;

    bootsector->jump[2]=0x90;

    memcpy(bootsector->name,"QEMU    ",8);

    bootsector->sector_size=cpu_to_le16(0x200);

    bootsector->sectors_per_cluster=s->sectors_per_cluster;

    bootsector->reserved_sectors=cpu_to_le16(1);

    bootsector->number_of_fats=0x2; /* number of FATs */

    bootsector->root_entries=cpu_to_le16(s->sectors_of_root_directory*0x10);

    bootsector->zero=0;

    bootsector->media_type=(s->first_sectors_number==1?0xf0:0xf8); /* media descriptor */

    bootsector->sectors_per_fat=cpu_to_le16(s->sectors_per_fat);

    bootsector->sectors_per_track=cpu_to_le16(0x3f);

    bootsector->number_of_heads=cpu_to_le16(0x10);

    bootsector->hidden_sectors=cpu_to_le32(s->first_sectors_number==1?0:0x3f);

    /* TODO: if FAT32, adjust */

    bootsector->total_sectors=cpu_to_le32(s->sector_count);

    /* TODO: if FAT32, this is wrong */

    bootsector->u.fat16.drive_number=0x80; /* assume this is hda (TODO) */

    bootsector->u.fat16.current_head=0;

    bootsector->u.fat16.signature=0x29;

    bootsector->u.fat16.id=cpu_to_le32(0xfabe1afd);

    memcpy(bootsector->u.fat16.volume_label,"QEMU VVFAT ",11);

    memcpy(bootsector->fat_type,(s->fat_type==12?"FAT12   ":s->fat_type==16?"FAT16   ":"FAT32   "),8);

    bootsector->magic[0]=0x55; bootsector->magic[1]=0xaa;

    return 0;

}


static void filter_mb_mbaff_edgecv( H264Context *h, uint8_t *pix, int stride, int16_t bS[8], int qp[2] ) {

    int i;

    for( i = 0; i < 8; i++, pix += stride) {

        int index_a;

        int alpha;

        int beta;

        int qp_index;

        int bS_index = i;

        if( bS[bS_index] == 0 ) {

            continue;

        }

        qp_index = MB_FIELD ? (i >> 2) : (i & 1);

        index_a = qp[qp_index] + h->slice_alpha_c0_offset;

        alpha = (alpha_table+52)[index_a];

        beta  = (beta_table+52)[qp[qp_index] + h->slice_beta_offset];

        if( bS[bS_index] < 4 ) {

            const int tc = (tc0_table+52)[index_a][bS[bS_index]] + 1;

            const int p0 = pix[-1];

            const int p1 = pix[-2];

            const int q0 = pix[0];

            const int q1 = pix[1];

            if( FFABS( p0 - q0 ) < alpha &&

                FFABS( p1 - p0 ) < beta &&

                FFABS( q1 - q0 ) < beta ) {

                const int i_delta = av_clip( (((q0 - p0 ) << 2) + (p1 - q1) + 4) >> 3, -tc, tc );

                pix[-1] = av_clip_uint8( p0 + i_delta );    /* p0' */

                pix[0]  = av_clip_uint8( q0 - i_delta );    /* q0' */

                tprintf(h->s.avctx, "filter_mb_mbaff_edgecv i:%d, qp:%d, indexA:%d, alpha:%d, beta:%d, tc:%d\n# bS:%d -> [%02x, %02x, %02x, %02x, %02x, %02x] =>[%02x, %02x, %02x, %02x]\n", i, qp[qp_index], index_a, alpha, beta, tc, bS[bS_index], pix[-3], p1, p0, q0, q1, pix[2], p1, pix[-1], pix[0], q1);

            }

        }else{

            const int p0 = pix[-1];

            const int p1 = pix[-2];

            const int q0 = pix[0];

            const int q1 = pix[1];

            if( FFABS( p0 - q0 ) < alpha &&

                FFABS( p1 - p0 ) < beta &&

                FFABS( q1 - q0 ) < beta ) {

                pix[-1] = ( 2*p1 + p0 + q1 + 2 ) >> 2;   /* p0' */

                pix[0]  = ( 2*q1 + q0 + p1 + 2 ) >> 2;   /* q0' */

                tprintf(h->s.avctx, "filter_mb_mbaff_edgecv i:%d\n# bS:4 -> [%02x, %02x, %02x, %02x, %02x, %02x] =>[%02x, %02x, %02x, %02x, %02x, %02x]\n", i, pix[-3], p1, p0, q0, q1, pix[2], pix[-3], pix[-2], pix[-1], pix[0], pix[1], pix[2]);

            }

        }

    }

}


int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)

{

    int ret;

    AVStream *st;

    ff_read_frame_flush(s);

    if(flags & AVSEEK_FLAG_BYTE)

        return seek_frame_byte(s, stream_index, timestamp, flags);

    if(stream_index < 0){

        stream_index= av_find_default_stream_index(s);

        if(stream_index < 0)

            return -1;

        st= s->streams[stream_index];

        /* timestamp for default must be expressed in AV_TIME_BASE units */

        timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);

    }

    /* first, we try the format specific seek */

    if (s->iformat->read_seek)

        ret = s->iformat->read_seek(s, stream_index, timestamp, flags);

    else

        ret = -1;

    if (ret >= 0) {

        return 0;

    }

    if(s->iformat->read_timestamp && !(s->iformat->flags & AVFMT_NOBINSEARCH))

        return av_seek_frame_binary(s, stream_index, timestamp, flags);

    else if (!(s->iformat->flags & AVFMT_NOGENSEARCH))

        return seek_frame_generic(s, stream_index, timestamp, flags);

    else

        return -1;

}


static const char *srt_to_ass(AVCodecContext *avctx, char *out, char *out_end,

                              const char *in, int x1, int y1, int x2, int y2)

{

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

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

    SrtStack stack[16];

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

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

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

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

    if (x1 >= 0 && y1 >= 0) {

        if (x2 >= 0 && y2 >= 0 && (x2 != x1 || y2 != y1))

            out += snprintf(out, out_end-out,

                            "{\\an1}{\\move(%d,%d,%d,%d)}", x1, y1, x2, y2);

        else

            out += snprintf(out, out_end-out, "{\\an1}{\\pos(%d,%d)}", x1, y1);

    }

    for (; out < out_end && !end && *in; in++) {

        switch (*in) {

        case '\r':

            break;

        case '\n':

            if (line_start) {

                end = 1;

                break;

            }

            while (out[-1] == ' ')

                out--;

            out += snprintf(out, out_end-out, "\\N");

            line_start = 1;

            break;

        case ' ':

            if (!line_start)

                *out++ = *in;

            break;

        case '{':    /* skip all {\xxx} substrings except for {\an%d}

                        and all microdvd like styles such as {Y:xxx} */

            an += sscanf(in, "{\\an%*1u}%c", &c) == 1;

            if ((an != 1 && sscanf(in, "{\\%*[^}]}%n%c", &len, &c) > 0) ||

                sscanf(in, "{%*1[CcFfoPSsYy]:%*[^}]}%n%c", &len, &c) > 0) {

                in += len - 1;

            } else

                *out++ = *in;

            break;

        case '<':

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

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

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

                    *param++ = 0;

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

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

                    int i, j, unknown = 0;

                    in += len + tag_close;

                    if (!tag_close)

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

                    if (!strcmp(buffer, "font")) {

                        if (tag_close) {

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

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

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

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

                                            out += snprintf(out, out_end-out,

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

                                            break;

                                        }

                        } else {

                            while (param) {

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

                                    unsigned font_size;

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

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

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

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

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

                                    }

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

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

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

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

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

                                         html_color_parse(avctx, param));

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

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

                                    len = strcspn(param,

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

                                    av_strlcpy(tmp, param,

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

                                    param += len;

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

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

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

                                }

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

                                    param++;

                            }

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

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

                                    out += snprintf(out, out_end-out,

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

                        }

                    } else if (!buffer[1] && strspn(buffer, "bisu") == 1) {

                        out += snprintf(out, out_end-out,

                                        "{\\%c%d}", buffer[0], !tag_close);

                    } else {

                        unknown = 1;

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

                    }

                    if (tag_close) {

                        sptr--;

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

                        in -= len + tag_close;

                        *out++ = *in;

                    } else

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

                                   sizeof(stack[0].tag));

                    break;

                }

            }

        default:

            *out++ = *in;

            break;

        }

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

            line_start = 0;

    }

    out = FFMIN(out, out_end-3);

    while (!strncmp(out-2, "\\N", 2))

        out -= 2;

    while (out[-1] == ' ')

        out--;

    out += snprintf(out, out_end-out, "\r\n");

    return in;

}


int av_metadata_set(AVMetadata **pm, const char *key, const char *value)

{

    AVMetadata *m= *pm;

    AVMetadataTag *tag= av_metadata_get(m, key, NULL, AV_METADATA_MATCH_CASE);

    if(!m)

        m=*pm= av_mallocz(sizeof(*m));

    if(tag){

        av_free(tag->value);

        av_free(tag->key);

        *tag= m->elems[--m->count];

    }else{

        AVMetadataTag *tmp= av_realloc(m->elems, (m->count+1) * sizeof(*m->elems));

        if(tmp){

            m->elems= tmp;

        }else

            return AVERROR(ENOMEM);

    }

    if(value){

        m->elems[m->count].key  = av_strdup(key  );

        m->elems[m->count].value= av_strdup(value);

        m->count++;

    }

    if(!m->count) {

        av_free(m->elems);

        av_freep(pm);

    }

    return 0;

}


static void zynq_init(MachineState *machine)

{

    ram_addr_t ram_size = machine->ram_size;

    const char *cpu_model = machine->cpu_model;

    const char *kernel_filename = machine->kernel_filename;

    const char *kernel_cmdline = machine->kernel_cmdline;

    const char *initrd_filename = machine->initrd_filename;

    ObjectClass *cpu_oc;

    ARMCPU *cpu;

    MemoryRegion *address_space_mem = get_system_memory();

    MemoryRegion *ext_ram = g_new(MemoryRegion, 1);

    MemoryRegion *ocm_ram = g_new(MemoryRegion, 1);

    DeviceState *dev;

    SysBusDevice *busdev;

    qemu_irq pic[64];

    Error *err = NULL;

    int n;

    if (!cpu_model) {

        cpu_model = "cortex-a9";

    }

    cpu_oc = cpu_class_by_name(TYPE_ARM_CPU, cpu_model);

    cpu = ARM_CPU(object_new(object_class_get_name(cpu_oc)));

    object_property_set_int(OBJECT(cpu), ZYNQ_BOARD_MIDR, "midr", &err);

    if (err) {

        error_report("%s", error_get_pretty(err));

        exit(1);

    }

    object_property_set_int(OBJECT(cpu), MPCORE_PERIPHBASE, "reset-cbar", &err);

    if (err) {

        error_report("%s", error_get_pretty(err));

        exit(1);

    }

    object_property_set_bool(OBJECT(cpu), true, "realized", &err);

    if (err) {

        error_report("%s", error_get_pretty(err));

        exit(1);

    }

    /* max 2GB ram */

    if (ram_size > 0x80000000) {

        ram_size = 0x80000000;

    }

    /* DDR remapped to address zero.  */

    memory_region_init_ram(ext_ram, NULL, "zynq.ext_ram", ram_size,

                           &error_abort);

    vmstate_register_ram_global(ext_ram);

    memory_region_add_subregion(address_space_mem, 0, ext_ram);

    /* 256K of on-chip memory */

    memory_region_init_ram(ocm_ram, NULL, "zynq.ocm_ram", 256 << 10,

                           &error_abort);

    vmstate_register_ram_global(ocm_ram);

    memory_region_add_subregion(address_space_mem, 0xFFFC0000, ocm_ram);

    DriveInfo *dinfo = drive_get(IF_PFLASH, 0, 0);

    /* AMD */

    pflash_cfi02_register(0xe2000000, NULL, "zynq.pflash", FLASH_SIZE,

                          dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL,

                          FLASH_SECTOR_SIZE,

                          FLASH_SIZE/FLASH_SECTOR_SIZE, 1,

                          1, 0x0066, 0x0022, 0x0000, 0x0000, 0x0555, 0x2aa,

                              0);

    dev = qdev_create(NULL, "xilinx,zynq_slcr");

    qdev_init_nofail(dev);

    sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0, 0xF8000000);

    dev = qdev_create(NULL, "a9mpcore_priv");

    qdev_prop_set_uint32(dev, "num-cpu", 1);

    qdev_init_nofail(dev);

    busdev = SYS_BUS_DEVICE(dev);

    sysbus_mmio_map(busdev, 0, MPCORE_PERIPHBASE);

    sysbus_connect_irq(busdev, 0,

                       qdev_get_gpio_in(DEVICE(cpu), ARM_CPU_IRQ));

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

        pic[n] = qdev_get_gpio_in(dev, n);

    }

    zynq_init_spi_flashes(0xE0006000, pic[58-IRQ_OFFSET], false);

    zynq_init_spi_flashes(0xE0007000, pic[81-IRQ_OFFSET], false);

    zynq_init_spi_flashes(0xE000D000, pic[51-IRQ_OFFSET], true);

    sysbus_create_simple("xlnx,ps7-usb", 0xE0002000, pic[53-IRQ_OFFSET]);

    sysbus_create_simple("xlnx,ps7-usb", 0xE0003000, pic[76-IRQ_OFFSET]);

    sysbus_create_simple("cadence_uart", 0xE0000000, pic[59-IRQ_OFFSET]);

    sysbus_create_simple("cadence_uart", 0xE0001000, pic[82-IRQ_OFFSET]);

    sysbus_create_varargs("cadence_ttc", 0xF8001000,

            pic[42-IRQ_OFFSET], pic[43-IRQ_OFFSET], pic[44-IRQ_OFFSET], NULL);

    sysbus_create_varargs("cadence_ttc", 0xF8002000,

            pic[69-IRQ_OFFSET], pic[70-IRQ_OFFSET], pic[71-IRQ_OFFSET], NULL);

    gem_init(&nd_table[0], 0xE000B000, pic[54-IRQ_OFFSET]);

    gem_init(&nd_table[1], 0xE000C000, pic[77-IRQ_OFFSET]);

    dev = qdev_create(NULL, "generic-sdhci");

    qdev_init_nofail(dev);

    sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0, 0xE0100000);

    sysbus_connect_irq(SYS_BUS_DEVICE(dev), 0, pic[56-IRQ_OFFSET]);

    dev = qdev_create(NULL, "generic-sdhci");

    qdev_init_nofail(dev);

    sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0, 0xE0101000);

    sysbus_connect_irq(SYS_BUS_DEVICE(dev), 0, pic[79-IRQ_OFFSET]);

    dev = qdev_create(NULL, "pl330");

    qdev_prop_set_uint8(dev, "num_chnls",  8);

    qdev_prop_set_uint8(dev, "num_periph_req",  4);

    qdev_prop_set_uint8(dev, "num_events",  16);

    qdev_prop_set_uint8(dev, "data_width",  64);

    qdev_prop_set_uint8(dev, "wr_cap",  8);

    qdev_prop_set_uint8(dev, "wr_q_dep",  16);

    qdev_prop_set_uint8(dev, "rd_cap",  8);

    qdev_prop_set_uint8(dev, "rd_q_dep",  16);

    qdev_prop_set_uint16(dev, "data_buffer_dep",  256);

    qdev_init_nofail(dev);

    busdev = SYS_BUS_DEVICE(dev);

    sysbus_mmio_map(busdev, 0, 0xF8003000);

    sysbus_connect_irq(busdev, 0, pic[45-IRQ_OFFSET]); /* abort irq line */

    for (n = 0; n < 8; ++n) { /* event irqs */

        sysbus_connect_irq(busdev, n + 1, pic[dma_irqs[n] - IRQ_OFFSET]);

    }

    zynq_binfo.ram_size = ram_size;

    zynq_binfo.kernel_filename = kernel_filename;

    zynq_binfo.kernel_cmdline = kernel_cmdline;

    zynq_binfo.initrd_filename = initrd_filename;

    zynq_binfo.nb_cpus = 1;

    zynq_binfo.board_id = 0xd32;

    zynq_binfo.loader_start = 0;

    arm_load_kernel(ARM_CPU(first_cpu), &zynq_binfo);

}


static void tcg_out_brcond(TCGContext *s, TCGMemOp ext, TCGCond c, TCGArg a,

                           TCGArg b, bool b_const, int label)

{

    TCGLabel *l = &s->labels[label];

    intptr_t offset;

    bool need_cmp;

    if (b_const && b == 0 && (c == TCG_COND_EQ || c == TCG_COND_NE)) {

        need_cmp = false;

    } else {

        need_cmp = true;

        tcg_out_cmp(s, ext, a, b, b_const);

    }

    if (!l->has_value) {

        tcg_out_reloc(s, s->code_ptr, R_AARCH64_CONDBR19, label, 0);

        offset = tcg_in32(s) >> 5;

    } else {

        offset = l->u.value_ptr - s->code_ptr;

        assert(offset == sextract64(offset, 0, 19));

    }

    if (need_cmp) {

        tcg_out_insn(s, 3202, B_C, c, offset);

    } else if (c == TCG_COND_EQ) {

        tcg_out_insn(s, 3201, CBZ, ext, a, offset);

    } else {

        tcg_out_insn(s, 3201, CBNZ, ext, a, offset);

    }

}


static target_ulong h_vio_signal(CPUState *env, sPAPREnvironment *spapr,

                                 target_ulong opcode,

                                 target_ulong *args)

{

    target_ulong reg = args[0];

    target_ulong mode = args[1];

    VIOsPAPRDevice *dev = spapr_vio_find_by_reg(spapr->vio_bus, reg);

    VIOsPAPRDeviceInfo *info;

    if (!dev) {

        return H_PARAMETER;

    }

    info = (VIOsPAPRDeviceInfo *)qdev_get_info(&dev->qdev);

    if (mode & ~info->signal_mask) {

        return H_PARAMETER;

    }

    dev->signal_state = mode;

    return H_SUCCESS;

}


static TCGArg do_constant_folding(int op, TCGArg x, TCGArg y)

{

    TCGArg res = do_constant_folding_2(op, x, y);

#if TCG_TARGET_REG_BITS == 64

    if (op_bits(op) == 32) {

        res &= 0xffffffff;

    }

#endif

    return res;

}


static int64_t seek_to_sector(BDRVParallelsState *s, int64_t sector_num)

{

    uint32_t index, offset;

    index = sector_num / s->tracks;

    offset = sector_num % s->tracks;

    /* not allocated */

    if ((index >= s->catalog_size) || (s->catalog_bitmap[index] == 0))

        return -1;

    return (uint64_t)s->catalog_bitmap[index] * s->off_multiplier + offset;

}


int load_image_targphys(const char *filename,

                        target_phys_addr_t addr, uint64_t max_sz)

{

    int size;

    size = get_image_size(filename);

    if (size > max_sz) {

        return -1;

    }

    if (size > 0) {

        rom_add_file_fixed(filename, addr, -1);

    }

    return size;

}


static uint64_t vfio_bar_read(void *opaque,

                              hwaddr addr, unsigned size)

{

    VFIOBAR *bar = opaque;

    union {

        uint8_t byte;

        uint16_t word;

        uint32_t dword;

        uint64_t qword;

    } buf;

    uint64_t data = 0;

    if (pread(bar->fd, &buf, size, bar->fd_offset + addr) != size) {

        error_report("%s(,0x%"HWADDR_PRIx", %d) failed: %m",

                     __func__, addr, size);

        return (uint64_t)-1;

    }

    switch (size) {

    case 1:

        data = buf.byte;

        break;

    case 2:

        data = le16_to_cpu(buf.word);

        break;

    case 4:

        data = le32_to_cpu(buf.dword);

        break;

    default:

        hw_error("vfio: unsupported read size, %d bytes\n", size);

        break;

    }

    DPRINTF("%s(BAR%d+0x%"HWADDR_PRIx", %d) = 0x%"PRIx64"\n",

            __func__, bar->nr, addr, size, data);

    /* Same as write above */

    vfio_eoi(container_of(bar, VFIODevice, bars[bar->nr]));

    return data;

}


static int l2tpv3_can_send(void *opaque)

{

    NetL2TPV3State *s = opaque;

    return qemu_can_send_packet(&s->nc);

}


static void extract_common_blockdev_options(QemuOpts *opts, int *bdrv_flags,

    const char **throttling_group, ThrottleConfig *throttle_cfg,

    BlockdevDetectZeroesOptions *detect_zeroes, Error **errp)

{

    const char *discard;

    Error *local_error = NULL;

    const char *aio;

    if (bdrv_flags) {

        if (!qemu_opt_get_bool(opts, "read-only", false)) {

            *bdrv_flags |= BDRV_O_RDWR;

        }

        if (qemu_opt_get_bool(opts, "copy-on-read", false)) {

            *bdrv_flags |= BDRV_O_COPY_ON_READ;

        }

        if ((discard = qemu_opt_get(opts, "discard")) != NULL) {

            if (bdrv_parse_discard_flags(discard, bdrv_flags) != 0) {

                error_setg(errp, "Invalid discard option");

                return;

            }

        }

        if ((aio = qemu_opt_get(opts, "aio")) != NULL) {

            if (!strcmp(aio, "native")) {

                *bdrv_flags |= BDRV_O_NATIVE_AIO;

            } else if (!strcmp(aio, "threads")) {

                /* this is the default */

            } else {

               error_setg(errp, "invalid aio option");

               return;

            }

        }

    }

    /* disk I/O throttling */

    if (throttling_group) {

        *throttling_group = qemu_opt_get(opts, "throttling.group");

    }

    if (throttle_cfg) {

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

        throttle_cfg->buckets[THROTTLE_BPS_TOTAL].avg =

            qemu_opt_get_number(opts, "throttling.bps-total", 0);

        throttle_cfg->buckets[THROTTLE_BPS_READ].avg  =

            qemu_opt_get_number(opts, "throttling.bps-read", 0);

        throttle_cfg->buckets[THROTTLE_BPS_WRITE].avg =

            qemu_opt_get_number(opts, "throttling.bps-write", 0);

        throttle_cfg->buckets[THROTTLE_OPS_TOTAL].avg =

            qemu_opt_get_number(opts, "throttling.iops-total", 0);

        throttle_cfg->buckets[THROTTLE_OPS_READ].avg =

            qemu_opt_get_number(opts, "throttling.iops-read", 0);

        throttle_cfg->buckets[THROTTLE_OPS_WRITE].avg =

            qemu_opt_get_number(opts, "throttling.iops-write", 0);

        throttle_cfg->buckets[THROTTLE_BPS_TOTAL].max =

            qemu_opt_get_number(opts, "throttling.bps-total-max", 0);

        throttle_cfg->buckets[THROTTLE_BPS_READ].max  =

            qemu_opt_get_number(opts, "throttling.bps-read-max", 0);

        throttle_cfg->buckets[THROTTLE_BPS_WRITE].max =

            qemu_opt_get_number(opts, "throttling.bps-write-max", 0);

        throttle_cfg->buckets[THROTTLE_OPS_TOTAL].max =

            qemu_opt_get_number(opts, "throttling.iops-total-max", 0);

        throttle_cfg->buckets[THROTTLE_OPS_READ].max =

            qemu_opt_get_number(opts, "throttling.iops-read-max", 0);

        throttle_cfg->buckets[THROTTLE_OPS_WRITE].max =

            qemu_opt_get_number(opts, "throttling.iops-write-max", 0);

        throttle_cfg->op_size =

            qemu_opt_get_number(opts, "throttling.iops-size", 0);

        if (!check_throttle_config(throttle_cfg, errp)) {

            return;

        }

    }

    if (detect_zeroes) {

        *detect_zeroes =

            qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,

                            qemu_opt_get(opts, "detect-zeroes"),

                            BLOCKDEV_DETECT_ZEROES_OPTIONS__MAX,

                            BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,

                            &local_error);

        if (local_error) {

            error_propagate(errp, local_error);

            return;

        }

        if (bdrv_flags &&

            *detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&

            !(*bdrv_flags & BDRV_O_UNMAP))

        {

            error_setg(errp, "setting detect-zeroes to unmap is not allowed "

                             "without setting discard operation to unmap");

            return;

        }

    }

}


static inline void tcg_out_dat_rI(TCGContext *s, int cond, int opc, TCGArg dst,

                                  TCGArg lhs, TCGArg rhs, int rhs_is_const)

{

    /* Emit either the reg,imm or reg,reg form of a data-processing insn.

     * rhs must satisfy the "rI" constraint.

     */

    if (rhs_is_const) {

        int rot = encode_imm(rhs);

        assert(rot >= 0);

        tcg_out_dat_imm(s, cond, opc, dst, lhs, rotl(rhs, rot) | (rot << 7));

    } else {

        tcg_out_dat_reg(s, cond, opc, dst, lhs, rhs, SHIFT_IMM_LSL(0));

    }

}


static always_inline void gen_bcond (DisasContext *ctx,

                                     TCGCond cond,

                                     int ra, int32_t disp16, int mask)

{

    int l1, l2;

    l1 = gen_new_label();

    l2 = gen_new_label();

    if (likely(ra != 31)) {

        if (mask) {

            TCGv tmp = tcg_temp_new(TCG_TYPE_I64);

            tcg_gen_andi_i64(tmp, cpu_ir[ra], 1);

            tcg_gen_brcondi_i64(cond, tmp, 0, l1);

            tcg_temp_free(tmp);

        } else

            tcg_gen_brcondi_i64(cond, cpu_ir[ra], 0, l1);

    } else {

        /* Very uncommon case - Do not bother to optimize.  */

        TCGv tmp = tcg_const_i64(0);

        tcg_gen_brcondi_i64(cond, tmp, 0, l1);

        tcg_temp_free(tmp);

    }

    tcg_gen_movi_i64(cpu_pc, ctx->pc);

    tcg_gen_br(l2);

    gen_set_label(l1);

    tcg_gen_movi_i64(cpu_pc, ctx->pc + (int64_t)(disp16 << 2));

    gen_set_label(l2);

}


void qemu_aio_set_event_notifier(EventNotifier *notifier,

                                 EventNotifierHandler *io_read,

                                 AioFlushEventNotifierHandler *io_flush)

{

    qemu_aio_set_fd_handler(event_notifier_get_fd(notifier),

                            (IOHandler *)io_read, NULL,

                            (AioFlushHandler *)io_flush, notifier);

}


uint32_t HELPER(lpebr)(CPUS390XState *env, uint32_t f1, uint32_t f2)

{

    float32 v1;

    float32 v2 = env->fregs[f2].d;

    v1 = float32_abs(v2);

    env->fregs[f1].d = v1;

    return set_cc_nz_f32(v1);

}


uint64_t helper_fsel (uint64_t arg1, uint64_t arg2, uint64_t arg3)

{

    CPU_DoubleU farg1;

    farg1.ll = arg1;

    if ((!float64_is_neg(farg1.d) || float64_is_zero(farg1.d)) && !float64_is_nan(farg1.d))

        return arg2;

    else

        return arg3;

}


static int ohci_service_td(OHCIState *ohci, struct ohci_ed *ed)

{

    int dir;

    size_t len = 0, pktlen = 0;

#ifdef DEBUG_PACKET

    const char *str = NULL;

#endif

    int pid;

    int ret;

    int i;

    USBDevice *dev;

    struct ohci_td td;

    uint32_t addr;

    int flag_r;

    int completion;

    addr = ed->head & OHCI_DPTR_MASK;

    /* See if this TD has already been submitted to the device.  */

    completion = (addr == ohci->async_td);

    if (completion && !ohci->async_complete) {

#ifdef DEBUG_PACKET

        DPRINTF("Skipping async TD\n");

#endif

        return 1;

    }

    if (!ohci_read_td(ohci, addr, &td)) {

        fprintf(stderr, "usb-ohci: TD read error at %x\n", addr);

        return 0;

    }

    dir = OHCI_BM(ed->flags, ED_D);

    switch (dir) {

    case OHCI_TD_DIR_OUT:

    case OHCI_TD_DIR_IN:

        /* Same value.  */

        break;

    default:

        dir = OHCI_BM(td.flags, TD_DP);

        break;

    }

    switch (dir) {

    case OHCI_TD_DIR_IN:

#ifdef DEBUG_PACKET

        str = "in";

#endif

        pid = USB_TOKEN_IN;

        break;

    case OHCI_TD_DIR_OUT:

#ifdef DEBUG_PACKET

        str = "out";

#endif

        pid = USB_TOKEN_OUT;

        break;

    case OHCI_TD_DIR_SETUP:

#ifdef DEBUG_PACKET

        str = "setup";

#endif

        pid = USB_TOKEN_SETUP;

        break;

    default:

        fprintf(stderr, "usb-ohci: Bad direction\n");

        return 1;

    }

    if (td.cbp && td.be) {

        if ((td.cbp & 0xfffff000) != (td.be & 0xfffff000)) {

            len = (td.be & 0xfff) + 0x1001 - (td.cbp & 0xfff);

        } else {

            len = (td.be - td.cbp) + 1;

        }

        pktlen = len;

        if (len && dir != OHCI_TD_DIR_IN) {

            /* The endpoint may not allow us to transfer it all now */

            pktlen = (ed->flags & OHCI_ED_MPS_MASK) >> OHCI_ED_MPS_SHIFT;

            if (pktlen > len) {

                pktlen = len;

            }

            if (!completion) {

                ohci_copy_td(ohci, &td, ohci->usb_buf, pktlen, 0);

            }

        }

    }

    flag_r = (td.flags & OHCI_TD_R) != 0;

#ifdef DEBUG_PACKET

    DPRINTF(" TD @ 0x%.8x %" PRId64 " of %" PRId64

            " bytes %s r=%d cbp=0x%.8x be=0x%.8x\n",

            addr, (int64_t)pktlen, (int64_t)len, str, flag_r, td.cbp, td.be);

    if (pktlen > 0 && dir != OHCI_TD_DIR_IN) {

        DPRINTF("  data:");

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

            printf(" %.2x", ohci->usb_buf[i]);

        }

        DPRINTF("\n");

    }

#endif

    if (completion) {

        ret = ohci->usb_packet.result;

        ohci->async_td = 0;

        ohci->async_complete = 0;

    } else {

        if (ohci->async_td) {

            /* ??? The hardware should allow one active packet per

               endpoint.  We only allow one active packet per controller.

               This should be sufficient as long as devices respond in a

               timely manner.

            */

#ifdef DEBUG_PACKET

            DPRINTF("Too many pending packets\n");

#endif

            return 1;

        }

        usb_packet_setup(&ohci->usb_packet, pid,

                         OHCI_BM(ed->flags, ED_FA),

                         OHCI_BM(ed->flags, ED_EN));

        usb_packet_addbuf(&ohci->usb_packet, ohci->usb_buf, pktlen);

        dev = ohci_find_device(ohci, ohci->usb_packet.devaddr);

        ret = usb_handle_packet(dev, &ohci->usb_packet);

#ifdef DEBUG_PACKET

        DPRINTF("ret=%d\n", ret);

#endif

        if (ret == USB_RET_ASYNC) {

            ohci->async_td = addr;

            return 1;

        }

    }

    if (ret >= 0) {

        if (dir == OHCI_TD_DIR_IN) {

            ohci_copy_td(ohci, &td, ohci->usb_buf, ret, 1);

#ifdef DEBUG_PACKET

            DPRINTF("  data:");

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

                printf(" %.2x", ohci->usb_buf[i]);

            DPRINTF("\n");

#endif

        } else {

            ret = pktlen;

        }

    }

    /* Writeback */

    if (ret == pktlen || (dir == OHCI_TD_DIR_IN && ret >= 0 && flag_r)) {

        /* Transmission succeeded.  */

        if (ret == len) {

            td.cbp = 0;

        } else {

            if ((td.cbp & 0xfff) + ret > 0xfff) {

                td.cbp = (td.be & ~0xfff) + ((td.cbp + ret) & 0xfff);

            } else {

                td.cbp += ret;

            }

        }

        td.flags |= OHCI_TD_T1;

        td.flags ^= OHCI_TD_T0;

        OHCI_SET_BM(td.flags, TD_CC, OHCI_CC_NOERROR);

        OHCI_SET_BM(td.flags, TD_EC, 0);

        if ((dir != OHCI_TD_DIR_IN) && (ret != len)) {

            /* Partial packet transfer: TD not ready to retire yet */

            goto exit_no_retire;

        }

        /* Setting ED_C is part of the TD retirement process */

        ed->head &= ~OHCI_ED_C;

        if (td.flags & OHCI_TD_T0)

            ed->head |= OHCI_ED_C;

    } else {

        if (ret >= 0) {

            DPRINTF("usb-ohci: Underrun\n");

            OHCI_SET_BM(td.flags, TD_CC, OHCI_CC_DATAUNDERRUN);

        } else {

            switch (ret) {

            case USB_RET_NODEV:

                OHCI_SET_BM(td.flags, TD_CC, OHCI_CC_DEVICENOTRESPONDING);

            case USB_RET_NAK:

                DPRINTF("usb-ohci: got NAK\n");

                return 1;

            case USB_RET_STALL:

                DPRINTF("usb-ohci: got STALL\n");

                OHCI_SET_BM(td.flags, TD_CC, OHCI_CC_STALL);

                break;

            case USB_RET_BABBLE:

                DPRINTF("usb-ohci: got BABBLE\n");

                OHCI_SET_BM(td.flags, TD_CC, OHCI_CC_DATAOVERRUN);

                break;

            default:

                fprintf(stderr, "usb-ohci: Bad device response %d\n", ret);

                OHCI_SET_BM(td.flags, TD_CC, OHCI_CC_UNDEXPETEDPID);

                OHCI_SET_BM(td.flags, TD_EC, 3);

                break;

            }

        }

        ed->head |= OHCI_ED_H;

    }

    /* Retire this TD */

    ed->head &= ~OHCI_DPTR_MASK;

    ed->head |= td.next & OHCI_DPTR_MASK;

    td.next = ohci->done;

    ohci->done = addr;

    i = OHCI_BM(td.flags, TD_DI);

    if (i < ohci->done_count)

        ohci->done_count = i;

exit_no_retire:

    ohci_put_td(ohci, addr, &td);

    return OHCI_BM(td.flags, TD_CC) != OHCI_CC_NOERROR;

}


static int txd_decode_frame(AVCodecContext *avctx, void *data, int *got_frame,

                            AVPacket *avpkt) {

    GetByteContext gb;

    AVFrame * const p = data;

    unsigned int version, w, h, d3d_format, depth, stride, flags;

    unsigned int y, v;

    uint8_t *ptr;

    uint32_t *pal;

    int ret;

    bytestream2_init(&gb, avpkt->data, avpkt->size);

    version         = bytestream2_get_le32(&gb);

    bytestream2_skip(&gb, 72);

    d3d_format      = bytestream2_get_le32(&gb);

    w               = bytestream2_get_le16(&gb);

    h               = bytestream2_get_le16(&gb);

    depth           = bytestream2_get_byte(&gb);

    bytestream2_skip(&gb, 2);

    flags           = bytestream2_get_byte(&gb);

    if (version < 8 || version > 9) {

        av_log(avctx, AV_LOG_ERROR, "texture data version %i is unsupported\n",

                                                                    version);

        return AVERROR_PATCHWELCOME;

    }

    if (depth == 8) {

        avctx->pix_fmt = AV_PIX_FMT_PAL8;

    } else if (depth == 16 || depth == 32) {

        avctx->pix_fmt = AV_PIX_FMT_RGB32;

    } else {

        av_log(avctx, AV_LOG_ERROR, "depth of %i is unsupported\n", depth);

        return AVERROR_PATCHWELCOME;

    }

    if ((ret = ff_set_dimensions(avctx, w, h)) < 0)

        return ret;

    if ((ret = ff_get_buffer(avctx, p, 0)) < 0)

        return ret;

    p->pict_type = AV_PICTURE_TYPE_I;

    ptr    = p->data[0];

    stride = p->linesize[0];

    if (depth == 8) {

        pal = (uint32_t *) p->data[1];

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

            v = bytestream2_get_be32(&gb);

            pal[y] = (v >> 8) + (v << 24);

        }

        if (bytestream2_get_bytes_left(&gb) < w * h)

            return AVERROR_INVALIDDATA;

        bytestream2_skip(&gb, 4);

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

            bytestream2_get_buffer(&gb, ptr, w);

            ptr += stride;

        }

    } else if (depth == 16) {

        bytestream2_skip(&gb, 4);

        switch (d3d_format) {

        case 0:

            if (!(flags & 1))

                goto unsupported;

        case FF_S3TC_DXT1:

            if (bytestream2_get_bytes_left(&gb) < (w/4) * (h/4) * 8)

                return AVERROR_INVALIDDATA;

            ff_decode_dxt1(&gb, ptr, w, h, stride);

            break;

        case FF_S3TC_DXT3:

            if (bytestream2_get_bytes_left(&gb) < (w/4) * (h/4) * 16)

                return AVERROR_INVALIDDATA;

            ff_decode_dxt3(&gb, ptr, w, h, stride);

            break;

        default:

            goto unsupported;

        }

    } else if (depth == 32) {

        switch (d3d_format) {

        case 0x15:

        case 0x16:

            if (bytestream2_get_bytes_left(&gb) < h * w * 4)

                return AVERROR_INVALIDDATA;

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

                bytestream2_get_buffer(&gb, ptr, w * 4);

                ptr += stride;

            }

            break;

        default:

            goto unsupported;

        }

    }

    *got_frame = 1;

    return avpkt->size;

unsupported:

    av_log(avctx, AV_LOG_ERROR, "unsupported d3d format (%08x)\n", d3d_format);

    return AVERROR_PATCHWELCOME;

}


static int read_packet(AVFormatContext* ctx, AVPacket *pkt)

{

    al_data *ad = ctx->priv_data;

    int error=0;

    const char *error_msg;

    ALCint nb_samples;

    /* Get number of samples available */

    alcGetIntegerv(ad->device, ALC_CAPTURE_SAMPLES, (ALCsizei) sizeof(ALCint), &nb_samples);

    if (error = al_get_error(ad->device, &error_msg)) goto fail;

    /* Create a packet of appropriate size */

    av_new_packet(pkt, nb_samples*ad->sample_step);

    pkt->pts = av_gettime();

    /* Fill the packet with the available samples */

    alcCaptureSamples(ad->device, pkt->data, nb_samples);

    if (error = al_get_error(ad->device, &error_msg)) goto fail;

    return pkt->size;

fail:

    /* Handle failure */

    if (pkt->data)

        av_destruct_packet(pkt);

    if (error_msg)

        av_log(ctx, AV_LOG_ERROR, "Error: %s\n", error_msg);

    return error;

}


static int read_header(FFV1Context *f){

    uint8_t state[CONTEXT_SIZE];

    int i, j, context_count;

    RangeCoder * const c= &f->slice_context[0]->c;

    memset(state, 128, sizeof(state));

    if(f->version < 2){

        f->version= get_symbol(c, state, 0);

        f->ac= f->avctx->coder_type= get_symbol(c, state, 0);

        if(f->ac>1){

            for(i=1; i<256; i++){

                f->state_transition[i]= get_symbol(c, state, 1) + c->one_state[i];

            }

        }

        f->colorspace= get_symbol(c, state, 0); //YUV cs type

        if(f->version>0)

            f->avctx->bits_per_raw_sample= get_symbol(c, state, 0);

        f->chroma_planes= get_rac(c, state);

        f->chroma_h_shift= get_symbol(c, state, 0);

        f->chroma_v_shift= get_symbol(c, state, 0);

        f->transparency= get_rac(c, state);

        f->plane_count= 2 + f->transparency;

    }

    if(f->colorspace==0){

        if(!f->transparency && !f->chroma_planes){

            if (f->avctx->bits_per_raw_sample<=8)

                f->avctx->pix_fmt= PIX_FMT_GRAY8;

            else

                f->avctx->pix_fmt= PIX_FMT_GRAY16;

        }else if(f->avctx->bits_per_raw_sample<=8 && !f->transparency){

            switch(16*f->chroma_h_shift + f->chroma_v_shift){

            case 0x00: f->avctx->pix_fmt= PIX_FMT_YUV444P; break;

            case 0x01: f->avctx->pix_fmt= PIX_FMT_YUV440P; break;

            case 0x10: f->avctx->pix_fmt= PIX_FMT_YUV422P; break;

            case 0x11: f->avctx->pix_fmt= PIX_FMT_YUV420P; break;

            case 0x20: f->avctx->pix_fmt= PIX_FMT_YUV411P; break;

            case 0x22: f->avctx->pix_fmt= PIX_FMT_YUV410P; break;

            default:

                av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");

                return -1;

            }

        }else if(f->avctx->bits_per_raw_sample<=8 && f->transparency){

            switch(16*f->chroma_h_shift + f->chroma_v_shift){

            case 0x00: f->avctx->pix_fmt= PIX_FMT_YUVA444P; break;

            case 0x11: f->avctx->pix_fmt= PIX_FMT_YUVA420P; break;

            default:

                av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");

                return -1;

            }

        }else if(f->avctx->bits_per_raw_sample==9) {

            f->packed_at_lsb=1;

            switch(16*f->chroma_h_shift + f->chroma_v_shift){

            case 0x00: f->avctx->pix_fmt= PIX_FMT_YUV444P9; break;

            case 0x10: f->avctx->pix_fmt= PIX_FMT_YUV422P9; break;

            case 0x11: f->avctx->pix_fmt= PIX_FMT_YUV420P9; break;

            default:

                av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");

                return -1;

            }

        }else if(f->avctx->bits_per_raw_sample==10) {

            f->packed_at_lsb=1;

            switch(16*f->chroma_h_shift + f->chroma_v_shift){

            case 0x00: f->avctx->pix_fmt= PIX_FMT_YUV444P10; break;

            case 0x10: f->avctx->pix_fmt= PIX_FMT_YUV422P10; break;

            case 0x11: f->avctx->pix_fmt= PIX_FMT_YUV420P10; break;

            default:

                av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");

                return -1;

            }

        }else {

            switch(16*f->chroma_h_shift + f->chroma_v_shift){

            case 0x00: f->avctx->pix_fmt= PIX_FMT_YUV444P16; break;

            case 0x10: f->avctx->pix_fmt= PIX_FMT_YUV422P16; break;

            case 0x11: f->avctx->pix_fmt= PIX_FMT_YUV420P16; break;

            default:

                av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");

                return -1;

            }

        }

    }else if(f->colorspace==1){

        if(f->chroma_h_shift || f->chroma_v_shift){

            av_log(f->avctx, AV_LOG_ERROR, "chroma subsampling not supported in this colorspace\n");

            return -1;

        }

        if(f->transparency) f->avctx->pix_fmt= PIX_FMT_RGB32;

        else                f->avctx->pix_fmt= PIX_FMT_0RGB32;

    }else{

        av_log(f->avctx, AV_LOG_ERROR, "colorspace not supported\n");

        return -1;

    }

//printf("%d %d %d\n", f->chroma_h_shift, f->chroma_v_shift,f->avctx->pix_fmt);

    if(f->version < 2){

        context_count= read_quant_tables(c, f->quant_table);

        if(context_count < 0){

                av_log(f->avctx, AV_LOG_ERROR, "read_quant_table error\n");

                return -1;

        }

    }else{

        f->slice_count= get_symbol(c, state, 0);

        if(f->slice_count > (unsigned)MAX_SLICES)

            return -1;

    }

    for(j=0; j<f->slice_count; j++){

        FFV1Context *fs= f->slice_context[j];

        fs->ac= f->ac;

        fs->packed_at_lsb= f->packed_at_lsb;

        if(f->version >= 2){

            fs->slice_x     = get_symbol(c, state, 0)   *f->width ;

            fs->slice_y     = get_symbol(c, state, 0)   *f->height;

            fs->slice_width =(get_symbol(c, state, 0)+1)*f->width  + fs->slice_x;

            fs->slice_height=(get_symbol(c, state, 0)+1)*f->height + fs->slice_y;

            fs->slice_x /= f->num_h_slices;

            fs->slice_y /= f->num_v_slices;

            fs->slice_width  = fs->slice_width /f->num_h_slices - fs->slice_x;

            fs->slice_height = fs->slice_height/f->num_v_slices - fs->slice_y;

            if((unsigned)fs->slice_width > f->width || (unsigned)fs->slice_height > f->height)

                return -1;

            if(    (unsigned)fs->slice_x + (uint64_t)fs->slice_width  > f->width

                || (unsigned)fs->slice_y + (uint64_t)fs->slice_height > f->height)

                return -1;

        }

        for(i=0; i<f->plane_count; i++){

            PlaneContext * const p= &fs->plane[i];

            if(f->version >= 2){

                int idx=get_symbol(c, state, 0);

                if(idx > (unsigned)f->quant_table_count){

                    av_log(f->avctx, AV_LOG_ERROR, "quant_table_index out of range\n");

                    return -1;

                }

                p->quant_table_index= idx;

                memcpy(p->quant_table, f->quant_tables[idx], sizeof(p->quant_table));

                context_count= f->context_count[idx];

            }else{

                memcpy(p->quant_table, f->quant_table, sizeof(p->quant_table));

            }

            if(p->context_count < context_count){

                av_freep(&p->state);

                av_freep(&p->vlc_state);

            }

            p->context_count= context_count;

        }

    }

    return 0;

}


static void avc_loopfilter_cb_or_cr_intra_edge_hor_msa(uint8_t *data_cb_or_cr,

                                                       uint8_t alpha_in,

                                                       uint8_t beta_in,

                                                       uint32_t img_width)

{

    v16u8 alpha, beta;

    v16u8 is_less_than;

    v8i16 p0_or_q0, q0_or_p0;

    v16u8 p1_or_q1_org, p0_or_q0_org, q0_or_p0_org, q1_or_p1_org;

    v16i8 zero = { 0 };

    v16u8 p0_asub_q0, p1_asub_p0, q1_asub_q0;

    v16u8 is_less_than_alpha, is_less_than_beta;

    v8i16 p1_org_r, p0_org_r, q0_org_r, q1_org_r;

    alpha = (v16u8) __msa_fill_b(alpha_in);

    beta = (v16u8) __msa_fill_b(beta_in);

    p1_or_q1_org = LOAD_UB(data_cb_or_cr - (img_width << 1));

    p0_or_q0_org = LOAD_UB(data_cb_or_cr - img_width);

    q0_or_p0_org = LOAD_UB(data_cb_or_cr);

    q1_or_p1_org = LOAD_UB(data_cb_or_cr + img_width);

    p0_asub_q0 = __msa_asub_u_b(p0_or_q0_org, q0_or_p0_org);

    p1_asub_p0 = __msa_asub_u_b(p1_or_q1_org, p0_or_q0_org);

    q1_asub_q0 = __msa_asub_u_b(q1_or_p1_org, q0_or_p0_org);

    is_less_than_alpha = (p0_asub_q0 < alpha);

    is_less_than_beta = (p1_asub_p0 < beta);

    is_less_than = is_less_than_beta & is_less_than_alpha;

    is_less_than_beta = (q1_asub_q0 < beta);

    is_less_than = is_less_than_beta & is_less_than;

    is_less_than = (v16u8) __msa_ilvr_d((v2i64) zero, (v2i64) is_less_than);

    if (!__msa_test_bz_v(is_less_than)) {

        p1_org_r = (v8i16) __msa_ilvr_b(zero, (v16i8) p1_or_q1_org);

        p0_org_r = (v8i16) __msa_ilvr_b(zero, (v16i8) p0_or_q0_org);

        q0_org_r = (v8i16) __msa_ilvr_b(zero, (v16i8) q0_or_p0_org);

        q1_org_r = (v8i16) __msa_ilvr_b(zero, (v16i8) q1_or_p1_org);

        AVC_LOOP_FILTER_P0_OR_Q0(p0_org_r, q1_org_r, p1_org_r, p0_or_q0);

        AVC_LOOP_FILTER_P0_OR_Q0(q0_org_r, p1_org_r, q1_org_r, q0_or_p0);

        p0_or_q0 = (v8i16) __msa_pckev_b(zero, (v16i8) p0_or_q0);

        q0_or_p0 = (v8i16) __msa_pckev_b(zero, (v16i8) q0_or_p0);

        p0_or_q0_org =

            __msa_bmnz_v(p0_or_q0_org, (v16u8) p0_or_q0, is_less_than);

        q0_or_p0_org =

            __msa_bmnz_v(q0_or_p0_org, (v16u8) q0_or_p0, is_less_than);

        STORE_UB(q0_or_p0_org, data_cb_or_cr);

        STORE_UB(p0_or_q0_org, data_cb_or_cr - img_width);

    }

}


static void gen_cli(DisasContext *ctx)

{

    /* Cache line invalidate: privileged and treated as no-op */

#if defined(CONFIG_USER_ONLY)

    gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

#else

    if (unlikely(ctx->pr)) {

        gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

        return;

    }

#endif

}


void palette8tobgr15(const uint8_t *src, uint8_t *dst, unsigned num_pixels, const uint8_t *palette)

{

	unsigned i;

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

		((uint16_t *)dst)[i] = bswap_16(((uint16_t *)palette)[ src[i] ]);

}


static int decode_interrupt_cb(void *ctx)

{

    return received_nb_signals > transcode_init_done;

}


static int mxf_read_content_storage(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)

{

    MXFContext *mxf = arg;

    switch (tag) {

    case 0x1901:

        mxf->packages_count = avio_rb32(pb);

        mxf->packages_refs = av_calloc(mxf->packages_count, sizeof(UID));

        if (!mxf->packages_refs)

            return AVERROR(ENOMEM);

        avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */

        avio_read(pb, (uint8_t *)mxf->packages_refs, mxf->packages_count * sizeof(UID));

        break;

    }

    return 0;

}


void qmp_cont(Error **errp)

{

    Error *local_err = NULL;

    if (runstate_check(RUN_STATE_INMIGRATE)) {

        error_set(errp, QERR_MIGRATION_EXPECTED);

        return;

    } else if (runstate_check(RUN_STATE_INTERNAL_ERROR) ||

               runstate_check(RUN_STATE_SHUTDOWN)) {

        error_set(errp, QERR_RESET_REQUIRED);

        return;

    } else if (runstate_check(RUN_STATE_SUSPENDED)) {

        return;

    }

    bdrv_iterate(iostatus_bdrv_it, NULL);

    bdrv_iterate(encrypted_bdrv_it, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        return;

    }

    vm_start();

}


int vc1_parse_frame_header_adv(VC1Context *v, GetBitContext* gb)

{

    int pqindex, lowquant;

    int status;

    int mbmodetab, imvtab, icbptab, twomvbptab, fourmvbptab; /* useful only for debugging */

    int scale, shift, i; /* for initializing LUT for intensity compensation */

    v->numref=0;

    v->fcm=0;

    v->field_mode=0;

    v->p_frame_skipped = 0;

    if (v->second_field) {

        v->s.pict_type = (v->fptype & 1) ? AV_PICTURE_TYPE_P : AV_PICTURE_TYPE_I;

        if (v->fptype & 4)

            v->s.pict_type = (v->fptype & 1) ? AV_PICTURE_TYPE_BI : AV_PICTURE_TYPE_B;

        v->s.current_picture_ptr->f.pict_type = v->s.pict_type;

        if (!v->pic_header_flag)

            goto parse_common_info;

    }

    if (v->interlace) {

        v->fcm = decode012(gb);

        if (v->fcm) {

            if (v->fcm == 2)

                v->field_mode = 1;

            else

                v->field_mode = 0;

            if (!v->warn_interlaced++)

                av_log(v->s.avctx, AV_LOG_ERROR,

                       "Interlaced frames/fields support is incomplete\n");

        }

    }

    if (v->field_mode) {

        v->fptype = get_bits(gb, 3);

        v->s.pict_type = (v->fptype & 2) ? AV_PICTURE_TYPE_P : AV_PICTURE_TYPE_I;

        if (v->fptype & 4) // B-picture

            v->s.pict_type = (v->fptype & 2) ? AV_PICTURE_TYPE_BI : AV_PICTURE_TYPE_B;

    } else {

        switch (get_unary(gb, 0, 4)) {

        case 0:

            v->s.pict_type = AV_PICTURE_TYPE_P;

            break;

        case 1:

            v->s.pict_type = AV_PICTURE_TYPE_B;

            break;

        case 2:

            v->s.pict_type = AV_PICTURE_TYPE_I;

            break;

        case 3:

            v->s.pict_type = AV_PICTURE_TYPE_BI;

            break;

        case 4:

            v->s.pict_type = AV_PICTURE_TYPE_P; // skipped pic

            v->p_frame_skipped = 1;

            break;

        }

    }

    if (v->tfcntrflag)

        skip_bits(gb, 8);

    if (v->broadcast) {

        if (!v->interlace || v->psf) {

            v->rptfrm = get_bits(gb, 2);

        } else {

            v->tff = get_bits1(gb);

            v->rff = get_bits1(gb);

        }

    }

    if (v->panscanflag) {

        av_log_missing_feature(v->s.avctx, "Pan-scan", 0);

        //...

    }

    if (v->p_frame_skipped) {

        return 0;

    }

    v->rnd = get_bits1(gb);

    if (v->interlace)

        v->uvsamp = get_bits1(gb);

    if (v->field_mode) {

        if (!v->refdist_flag)

            v->refdist = 0;

        else {

            if ((v->s.pict_type != AV_PICTURE_TYPE_B)

                && (v->s.pict_type != AV_PICTURE_TYPE_BI)) {

                v->refdist = get_bits(gb, 2);

                if (v->refdist == 3)

                    v->refdist += get_unary(gb, 0, 16);

            } else {

                v->bfraction_lut_index = get_vlc2(gb, ff_vc1_bfraction_vlc.table, VC1_BFRACTION_VLC_BITS, 1);

                v->bfraction           = ff_vc1_bfraction_lut[v->bfraction_lut_index];

                v->frfd = (v->bfraction * v->refdist) >> 8;

                v->brfd = v->refdist - v->frfd - 1;

                if (v->brfd < 0)

                    v->brfd = 0;

            }

        }

        goto parse_common_info;

    }

    if (v->finterpflag)

        v->interpfrm = get_bits1(gb);

    if (v->s.pict_type == AV_PICTURE_TYPE_B) {

        v->bfraction_lut_index = get_vlc2(gb, ff_vc1_bfraction_vlc.table, VC1_BFRACTION_VLC_BITS, 1);

        v->bfraction           = ff_vc1_bfraction_lut[v->bfraction_lut_index];

        if (v->bfraction == 0) {

            v->s.pict_type = AV_PICTURE_TYPE_BI; /* XXX: should not happen here */

        }

    }

    parse_common_info:

    if (v->field_mode)

        v->cur_field_type = !(v->tff ^ v->second_field);

    pqindex = get_bits(gb, 5);

    if (!pqindex)

        return -1;

    v->pqindex = pqindex;

    if (v->quantizer_mode == QUANT_FRAME_IMPLICIT)

        v->pq = ff_vc1_pquant_table[0][pqindex];

    else

        v->pq = ff_vc1_pquant_table[1][pqindex];

    v->pquantizer = 1;

    if (v->quantizer_mode == QUANT_FRAME_IMPLICIT)

        v->pquantizer = pqindex < 9;

    if (v->quantizer_mode == QUANT_NON_UNIFORM)

        v->pquantizer = 0;

    v->pqindex = pqindex;

    if (pqindex < 9)

        v->halfpq = get_bits1(gb);

    else

        v->halfpq = 0;

    if (v->quantizer_mode == QUANT_FRAME_EXPLICIT)

        v->pquantizer = get_bits1(gb);

    if (v->postprocflag)

        v->postproc = get_bits(gb, 2);

    if (v->s.pict_type == AV_PICTURE_TYPE_I || v->s.pict_type == AV_PICTURE_TYPE_P)

        v->use_ic = 0;

    if (v->parse_only)

        return 0;

    switch (v->s.pict_type) {

    case AV_PICTURE_TYPE_I:

    case AV_PICTURE_TYPE_BI:

        if (v->fcm == 1) { //interlace frame picture

            status = bitplane_decoding(v->fieldtx_plane, &v->fieldtx_is_raw, v);

            if (status < 0)

                return -1;

            av_log(v->s.avctx, AV_LOG_DEBUG, "FIELDTX plane encoding: "

                   "Imode: %i, Invert: %i\n", status>>1, status&1);

        }

        status = bitplane_decoding(v->acpred_plane, &v->acpred_is_raw, v);

        if (status < 0)

            return -1;

        av_log(v->s.avctx, AV_LOG_DEBUG, "ACPRED plane encoding: "

               "Imode: %i, Invert: %i\n", status>>1, status&1);

        v->condover = CONDOVER_NONE;

        if (v->overlap && v->pq <= 8) {

            v->condover = decode012(gb);

            if (v->condover == CONDOVER_SELECT) {

                status = bitplane_decoding(v->over_flags_plane, &v->overflg_is_raw, v);

                if (status < 0)

                    return -1;

                av_log(v->s.avctx, AV_LOG_DEBUG, "CONDOVER plane encoding: "

                       "Imode: %i, Invert: %i\n", status>>1, status&1);

            }

        }

        break;

    case AV_PICTURE_TYPE_P:

        if (v->field_mode) {

            av_log(v->s.avctx, AV_LOG_ERROR, "P Fields do not work currently\n");

            return -1;

            v->numref = get_bits1(gb);

            if (!v->numref) {

                v->reffield          = get_bits1(gb);

                v->ref_field_type[0] = v->reffield ^ !v->cur_field_type;

            }

        }

        if (v->extended_mv)

            v->mvrange = get_unary(gb, 0, 3);

        else

            v->mvrange = 0;

        if (v->interlace) {

            if (v->extended_dmv)

                v->dmvrange = get_unary(gb, 0, 3);

            else

                v->dmvrange = 0;

            if (v->fcm == 1) { // interlaced frame picture

                v->fourmvswitch = get_bits1(gb);

                v->intcomp      = get_bits1(gb);

                if (v->intcomp) {

                    v->lumscale = get_bits(gb, 6);

                    v->lumshift = get_bits(gb, 6);

                    INIT_LUT(v->lumscale, v->lumshift, v->luty, v->lutuv);

                }

                status = bitplane_decoding(v->s.mbskip_table, &v->skip_is_raw, v);

                av_log(v->s.avctx, AV_LOG_DEBUG, "SKIPMB plane encoding: "

                       "Imode: %i, Invert: %i\n", status>>1, status&1);

                mbmodetab = get_bits(gb, 2);

                if (v->fourmvswitch)

                    v->mbmode_vlc = &ff_vc1_intfr_4mv_mbmode_vlc[mbmodetab];

                else

                    v->mbmode_vlc = &ff_vc1_intfr_non4mv_mbmode_vlc[mbmodetab];

                imvtab         = get_bits(gb, 2);

                v->imv_vlc     = &ff_vc1_1ref_mvdata_vlc[imvtab];

                // interlaced p-picture cbpcy range is [1, 63]

                icbptab        = get_bits(gb, 3);

                v->cbpcy_vlc   = &ff_vc1_icbpcy_vlc[icbptab];

                twomvbptab     = get_bits(gb, 2);

                v->twomvbp_vlc = &ff_vc1_2mv_block_pattern_vlc[twomvbptab];

                if (v->fourmvswitch) {

                    fourmvbptab     = get_bits(gb, 2);

                    v->fourmvbp_vlc = &ff_vc1_4mv_block_pattern_vlc[fourmvbptab];

                }

            }

        }

        v->k_x = v->mvrange + 9 + (v->mvrange >> 1); //k_x can be 9 10 12 13

        v->k_y = v->mvrange + 8; //k_y can be 8 9 10 11

        v->range_x = 1 << (v->k_x - 1);

        v->range_y = 1 << (v->k_y - 1);

        if (v->pq < 5)

            v->tt_index = 0;

        else if (v->pq < 13)

            v->tt_index = 1;

        else

            v->tt_index = 2;

        if (v->fcm != 1) {

            int mvmode;

            mvmode     = get_unary(gb, 1, 4);

            lowquant   = (v->pq > 12) ? 0 : 1;

            v->mv_mode = ff_vc1_mv_pmode_table[lowquant][mvmode];

            if (v->mv_mode == MV_PMODE_INTENSITY_COMP) {

                int mvmode2;

                mvmode2 = get_unary(gb, 1, 3);

                v->mv_mode2 = ff_vc1_mv_pmode_table2[lowquant][mvmode2];

                if (v->field_mode)

                    v->intcompfield = decode210(gb);

                v->lumscale = get_bits(gb, 6);

                v->lumshift = get_bits(gb, 6);

                INIT_LUT(v->lumscale, v->lumshift, v->luty, v->lutuv);

                if ((v->field_mode) && !v->intcompfield) {

                    v->lumscale2 = get_bits(gb, 6);

                    v->lumshift2 = get_bits(gb, 6);

                    INIT_LUT(v->lumscale2, v->lumshift2, v->luty2, v->lutuv2);

                }

                v->use_ic = 1;

            }

            v->qs_last = v->s.quarter_sample;

            if (v->mv_mode == MV_PMODE_1MV_HPEL || v->mv_mode == MV_PMODE_1MV_HPEL_BILIN)

                v->s.quarter_sample = 0;

            else if (v->mv_mode == MV_PMODE_INTENSITY_COMP) {

                if (v->mv_mode2 == MV_PMODE_1MV_HPEL || v->mv_mode2 == MV_PMODE_1MV_HPEL_BILIN)

                    v->s.quarter_sample = 0;

                else

                    v->s.quarter_sample = 1;

            } else

                v->s.quarter_sample = 1;

            v->s.mspel = !(v->mv_mode == MV_PMODE_1MV_HPEL_BILIN

                           || (v->mv_mode == MV_PMODE_INTENSITY_COMP

                               && v->mv_mode2 == MV_PMODE_1MV_HPEL_BILIN));

        }

        if (v->fcm == 0) { // progressive

            if ((v->mv_mode == MV_PMODE_INTENSITY_COMP &&

                 v->mv_mode2 == MV_PMODE_MIXED_MV)

                || v->mv_mode == MV_PMODE_MIXED_MV) {

                status = bitplane_decoding(v->mv_type_mb_plane, &v->mv_type_is_raw, v);

                if (status < 0)

                    return -1;

                av_log(v->s.avctx, AV_LOG_DEBUG, "MB MV Type plane encoding: "

                       "Imode: %i, Invert: %i\n", status>>1, status&1);

            } else {

                v->mv_type_is_raw = 0;

                memset(v->mv_type_mb_plane, 0, v->s.mb_stride * v->s.mb_height);

            }

            status = bitplane_decoding(v->s.mbskip_table, &v->skip_is_raw, v);

            if (status < 0)

                return -1;

            av_log(v->s.avctx, AV_LOG_DEBUG, "MB Skip plane encoding: "

                   "Imode: %i, Invert: %i\n", status>>1, status&1);

            /* Hopefully this is correct for P frames */

            v->s.mv_table_index = get_bits(gb, 2); //but using ff_vc1_ tables

            v->cbpcy_vlc        = &ff_vc1_cbpcy_p_vlc[get_bits(gb, 2)];

        } else if (v->fcm == 1) { // frame interlaced

            v->qs_last          = v->s.quarter_sample;

            v->s.quarter_sample = 1;

            v->s.mspel          = 1;

        } else {    // field interlaced

            mbmodetab = get_bits(gb, 3);

            imvtab = get_bits(gb, 2 + v->numref);

            if (!v->numref)

                v->imv_vlc = &ff_vc1_1ref_mvdata_vlc[imvtab];

            else

                v->imv_vlc = &ff_vc1_2ref_mvdata_vlc[imvtab];

            icbptab = get_bits(gb, 3);

            v->cbpcy_vlc = &ff_vc1_icbpcy_vlc[icbptab];

            if ((v->mv_mode == MV_PMODE_INTENSITY_COMP &&

                v->mv_mode2 == MV_PMODE_MIXED_MV) || v->mv_mode == MV_PMODE_MIXED_MV) {

                fourmvbptab     = get_bits(gb, 2);

                v->fourmvbp_vlc = &ff_vc1_4mv_block_pattern_vlc[fourmvbptab];

                v->mbmode_vlc = &ff_vc1_if_mmv_mbmode_vlc[mbmodetab];

            } else {

                v->mbmode_vlc = &ff_vc1_if_1mv_mbmode_vlc[mbmodetab];

            }

        }

        if (v->dquant) {

            av_log(v->s.avctx, AV_LOG_DEBUG, "VOP DQuant info\n");

            vop_dquant_decoding(v);

        }

        v->ttfrm = 0; //FIXME Is that so ?

        if (v->vstransform) {

            v->ttmbf = get_bits1(gb);

            if (v->ttmbf) {

                v->ttfrm = ff_vc1_ttfrm_to_tt[get_bits(gb, 2)];

            }

        } else {

            v->ttmbf = 1;

            v->ttfrm = TT_8X8;

        }

        break;

    case AV_PICTURE_TYPE_B:

        // TODO: implement interlaced frame B picture decoding

        if (v->fcm == 1)

            return -1;

        if (v->extended_mv)

            v->mvrange = get_unary(gb, 0, 3);

        else

            v->mvrange = 0;

        v->k_x     = v->mvrange + 9 + (v->mvrange >> 1); //k_x can be 9 10 12 13

        v->k_y     = v->mvrange + 8; //k_y can be 8 9 10 11

        v->range_x = 1 << (v->k_x - 1);

        v->range_y = 1 << (v->k_y - 1);

        if (v->pq < 5)

            v->tt_index = 0;

        else if (v->pq < 13)

            v->tt_index = 1;

        else

            v->tt_index = 2;

        if (v->field_mode) {

            int mvmode;

            av_log(v->s.avctx, AV_LOG_ERROR, "B Fields do not work currently\n");

            return -1;

            if (v->extended_dmv)

                v->dmvrange = get_unary(gb, 0, 3);

            mvmode = get_unary(gb, 1, 3);

            lowquant = (v->pq > 12) ? 0 : 1;

            v->mv_mode          = ff_vc1_mv_pmode_table2[lowquant][mvmode];

            v->qs_last          = v->s.quarter_sample;

            v->s.quarter_sample = (v->mv_mode == MV_PMODE_1MV || v->mv_mode == MV_PMODE_MIXED_MV);

            v->s.mspel          = !(v->mv_mode == MV_PMODE_1MV_HPEL_BILIN || v->mv_mode == MV_PMODE_1MV_HPEL);

            status = bitplane_decoding(v->forward_mb_plane, &v->fmb_is_raw, v);

            if (status < 0)

                return -1;

            av_log(v->s.avctx, AV_LOG_DEBUG, "MB Forward Type plane encoding: "

                   "Imode: %i, Invert: %i\n", status>>1, status&1);

            mbmodetab = get_bits(gb, 3);

            if (v->mv_mode == MV_PMODE_MIXED_MV)

                v->mbmode_vlc = &ff_vc1_if_mmv_mbmode_vlc[mbmodetab];

            else

                v->mbmode_vlc = &ff_vc1_if_1mv_mbmode_vlc[mbmodetab];

            imvtab       = get_bits(gb, 3);

            v->imv_vlc   = &ff_vc1_2ref_mvdata_vlc[imvtab];

            icbptab      = get_bits(gb, 3);

            v->cbpcy_vlc = &ff_vc1_icbpcy_vlc[icbptab];

            if (v->mv_mode == MV_PMODE_MIXED_MV) {

                fourmvbptab     = get_bits(gb, 2);

                v->fourmvbp_vlc = &ff_vc1_4mv_block_pattern_vlc[fourmvbptab];

            }

            v->numref = 1; // interlaced field B pictures are always 2-ref

        } else {

            v->mv_mode          = get_bits1(gb) ? MV_PMODE_1MV : MV_PMODE_1MV_HPEL_BILIN;

            v->qs_last          = v->s.quarter_sample;

            v->s.quarter_sample = (v->mv_mode == MV_PMODE_1MV);

            v->s.mspel          = v->s.quarter_sample;

            status              = bitplane_decoding(v->direct_mb_plane, &v->dmb_is_raw, v);

            if (status < 0)

                return -1;

            av_log(v->s.avctx, AV_LOG_DEBUG, "MB Direct Type plane encoding: "

                   "Imode: %i, Invert: %i\n", status>>1, status&1);

            status = bitplane_decoding(v->s.mbskip_table, &v->skip_is_raw, v);

            if (status < 0)

                return -1;

            av_log(v->s.avctx, AV_LOG_DEBUG, "MB Skip plane encoding: "

                   "Imode: %i, Invert: %i\n", status>>1, status&1);

            v->s.mv_table_index = get_bits(gb, 2);

            v->cbpcy_vlc = &ff_vc1_cbpcy_p_vlc[get_bits(gb, 2)];

        }

        if (v->dquant) {

            av_log(v->s.avctx, AV_LOG_DEBUG, "VOP DQuant info\n");

            vop_dquant_decoding(v);

        }

        v->ttfrm = 0;

        if (v->vstransform) {

            v->ttmbf = get_bits1(gb);

            if (v->ttmbf) {

                v->ttfrm = ff_vc1_ttfrm_to_tt[get_bits(gb, 2)];

            }

        } else {

            v->ttmbf = 1;

            v->ttfrm = TT_8X8;

        }

        break;

    }

    /* AC Syntax */

    v->c_ac_table_index = decode012(gb);

    if (v->s.pict_type == AV_PICTURE_TYPE_I || v->s.pict_type == AV_PICTURE_TYPE_BI) {

        v->y_ac_table_index = decode012(gb);

    }

    /* DC Syntax */

    v->s.dc_table_index = get_bits1(gb);

    if ((v->s.pict_type == AV_PICTURE_TYPE_I || v->s.pict_type == AV_PICTURE_TYPE_BI)

        && v->dquant) {

        av_log(v->s.avctx, AV_LOG_DEBUG, "VOP DQuant info\n");

        vop_dquant_decoding(v);

    }

    v->bi_type = 0;

    if (v->s.pict_type == AV_PICTURE_TYPE_BI) {

        v->s.pict_type = AV_PICTURE_TYPE_B;

        v->bi_type = 1;

    }

    return 0;

}


static int decode_mb(MadContext *s, AVFrame *frame, int inter)

{

    int mv_map = 0;

    int mv_x, mv_y;

    int j;

    if (inter) {

        int v = decode210(&s->gb);

        if (v < 2) {

            mv_map = v ? get_bits(&s->gb, 6) : 63;

            mv_x = decode_motion(&s->gb);

            mv_y = decode_motion(&s->gb);

        }

    }

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

        if (mv_map & (1<<j)) {  // mv_x and mv_y are guarded by mv_map

            int add = 2*decode_motion(&s->gb);

            if (s->last_frame->data[0])

                comp_block(s, frame, s->mb_x, s->mb_y, j, mv_x, mv_y, add);

        } else {

            s->dsp.clear_block(s->block);

            if(decode_block_intra(s, s->block) < 0)

                return -1;

            idct_put(s, frame, s->block, s->mb_x, s->mb_y, j);

        }

    }

    return 0;

}


static inline uint16_t vring_avail_idx(VirtQueue *vq)

{

    VRingMemoryRegionCaches *caches = atomic_rcu_read(&vq->vring.caches);

    hwaddr pa = offsetof(VRingAvail, idx);

    vq->shadow_avail_idx = virtio_lduw_phys_cached(vq->vdev, &caches->avail, pa);

    return vq->shadow_avail_idx;

}


USBDevice *usb_create_simple(USBBus *bus, const char *name)

{

    USBDevice *dev = usb_create(bus, name);

    qdev_init(&dev->qdev);

    return dev;

}


static void qvirtio_pci_foreach_callback(

                        QPCIDevice *dev, int devfn, void *data)

{

    QVirtioPCIForeachData *d = data;

    QVirtioPCIDevice *vpcidev = qpcidevice_to_qvirtiodevice(dev);

    if (vpcidev->vdev.device_type == d->device_type &&

        (!d->has_slot || vpcidev->pdev->devfn == d->slot << 3)) {

        d->func(&vpcidev->vdev, d->user_data);

    } else {

        g_free(vpcidev);

    }

}


static inline void qpel_motion(MpegEncContext *s,

                               uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,

                               int field_based, int bottom_field, int field_select,

                               uint8_t **ref_picture, op_pixels_func (*pix_op)[4],

                               qpel_mc_func (*qpix_op)[16],

                               int motion_x, int motion_y, int h)

{

    uint8_t *ptr_y, *ptr_cb, *ptr_cr;

    int dxy, uvdxy, mx, my, src_x, src_y, uvsrc_x, uvsrc_y, v_edge_pos, linesize, uvlinesize;

    dxy = ((motion_y & 3) << 2) | (motion_x & 3);

    src_x = s->mb_x *  16                 + (motion_x >> 2);

    src_y = s->mb_y * (16 >> field_based) + (motion_y >> 2);

    v_edge_pos = s->v_edge_pos >> field_based;

    linesize = s->linesize << field_based;

    uvlinesize = s->uvlinesize << field_based;

    if(field_based){

        mx= motion_x/2;

        my= motion_y>>1;

    }else if(s->workaround_bugs&FF_BUG_QPEL_CHROMA2){

        static const int rtab[8]= {0,0,1,1,0,0,0,1};

        mx= (motion_x>>1) + rtab[motion_x&7];

        my= (motion_y>>1) + rtab[motion_y&7];

    }else if(s->workaround_bugs&FF_BUG_QPEL_CHROMA){

        mx= (motion_x>>1)|(motion_x&1);

        my= (motion_y>>1)|(motion_y&1);

    }else{

        mx= motion_x/2;

        my= motion_y/2;

    }

    mx= (mx>>1)|(mx&1);

    my= (my>>1)|(my&1);

    uvdxy= (mx&1) | ((my&1)<<1);

    mx>>=1;

    my>>=1;

    uvsrc_x = s->mb_x *  8                 + mx;

    uvsrc_y = s->mb_y * (8 >> field_based) + my;

    ptr_y  = ref_picture[0] +   src_y *   linesize +   src_x;

    ptr_cb = ref_picture[1] + uvsrc_y * uvlinesize + uvsrc_x;

    ptr_cr = ref_picture[2] + uvsrc_y * uvlinesize + uvsrc_x;

    if(   (unsigned)src_x > FFMAX(s->h_edge_pos - (motion_x&3) - 16, 0)

       || (unsigned)src_y > FFMAX(   v_edge_pos - (motion_y&3) - h , 0)){

        s->vdsp.emulated_edge_mc(s->edge_emu_buffer, ptr_y, s->linesize,

                            17, 17+field_based, src_x, src_y<<field_based,

                            s->h_edge_pos, s->v_edge_pos);

        ptr_y= s->edge_emu_buffer;

        if(!CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){

            uint8_t *uvbuf= s->edge_emu_buffer + 18*s->linesize;

            s->vdsp.emulated_edge_mc(uvbuf, ptr_cb, s->uvlinesize,

                                9, 9 + field_based,

                                uvsrc_x, uvsrc_y<<field_based,

                                s->h_edge_pos>>1, s->v_edge_pos>>1);

            s->vdsp.emulated_edge_mc(uvbuf + 16, ptr_cr, s->uvlinesize,

                                9, 9 + field_based,

                                uvsrc_x, uvsrc_y<<field_based,

                                s->h_edge_pos>>1, s->v_edge_pos>>1);

            ptr_cb= uvbuf;

            ptr_cr= uvbuf + 16;

        }

    }

    if(!field_based)

        qpix_op[0][dxy](dest_y, ptr_y, linesize);

    else{

        if(bottom_field){

            dest_y += s->linesize;

            dest_cb+= s->uvlinesize;

            dest_cr+= s->uvlinesize;

        }

        if(field_select){

            ptr_y  += s->linesize;

            ptr_cb += s->uvlinesize;

            ptr_cr += s->uvlinesize;

        }

        //damn interlaced mode

        //FIXME boundary mirroring is not exactly correct here

        qpix_op[1][dxy](dest_y  , ptr_y  , linesize);

        qpix_op[1][dxy](dest_y+8, ptr_y+8, linesize);

    }

    if(!CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){

        pix_op[1][uvdxy](dest_cr, ptr_cr, uvlinesize, h >> 1);

        pix_op[1][uvdxy](dest_cb, ptr_cb, uvlinesize, h >> 1);

    }

}


static int host_pci_config_read(int pos, int len, uint32_t val)

{

    char path[PATH_MAX];

    int config_fd;

    ssize_t size = sizeof(path);

    /* Access real host bridge. */

    int rc = snprintf(path, size, "/sys/bus/pci/devices/%04x:%02x:%02x.%d/%s",

                      0, 0, 0, 0, "config");

    if (rc >= size || rc < 0) {

        return -ENODEV;

    }

    config_fd = open(path, O_RDWR);

    if (config_fd < 0) {

        return -ENODEV;

    }

    if (lseek(config_fd, pos, SEEK_SET) != pos) {

        return -errno;

    }

    do {

        rc = read(config_fd, (uint8_t *)&val, len);

    } while (rc < 0 && (errno == EINTR || errno == EAGAIN));

    if (rc != len) {

        return -errno;

    }

    return 0;

}


static inline void read_mem(IVState *s, uint64_t off, void *buf, size_t len)

{

    QTestState *qtest = global_qtest;

    global_qtest = s->qtest;

    qpci_memread(s->dev, s->mem_base + off, buf, len);

    global_qtest = qtest;

}


static void sdhci_initfn(Object *obj)

{

    SDHCIState *s = SDHCI(obj);

    DriveInfo *di;

    di = drive_get_next(IF_SD);

    s->card = sd_init(di ? di->bdrv : NULL, false);

    if (s->card == NULL) {

        exit(1);

    }

    s->eject_cb = qemu_allocate_irqs(sdhci_insert_eject_cb, s, 1)[0];

    s->ro_cb = qemu_allocate_irqs(sdhci_card_readonly_cb, s, 1)[0];

    sd_set_cb(s->card, s->ro_cb, s->eject_cb);

    s->insert_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, sdhci_raise_insertion_irq, s);

    s->transfer_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, sdhci_do_data_transfer, s);

}


static int decode_packet(AVCodecContext *avctx,

                         void *data, int *data_size, AVPacket* avpkt)

{

    WmallDecodeCtx *s = avctx->priv_data;

    GetBitContext* gb  = &s->pgb;

    const uint8_t* buf = avpkt->data;

    int buf_size       = avpkt->size;

    int num_bits_prev_frame;

    int packet_sequence_number;

    s->samples       = data;

    s->samples_end   = (float*)((int8_t*)data + *data_size);

    *data_size = 0;

    if (s->packet_done || s->packet_loss) {

        s->packet_done = 0;

        /** sanity check for the buffer length */

        if (buf_size < avctx->block_align)

            return 0;

        s->next_packet_start = buf_size - avctx->block_align;

        buf_size = avctx->block_align;

        s->buf_bit_size = buf_size << 3;

        /** parse packet header */

        init_get_bits(gb, buf, s->buf_bit_size);

        packet_sequence_number = get_bits(gb, 4);

	int seekable_frame_in_packet = get_bits1(gb);

	int spliced_packet = get_bits1(gb);

        /** get number of bits that need to be added to the previous frame */

        num_bits_prev_frame = get_bits(gb, s->log2_frame_size);

        /** check for packet loss */

        if (!s->packet_loss &&

            ((s->packet_sequence_number + 1) & 0xF) != packet_sequence_number) {

            s->packet_loss = 1;

            av_log(avctx, AV_LOG_ERROR, "Packet loss detected! seq %x vs %x\n",

                   s->packet_sequence_number, packet_sequence_number);

        }

        s->packet_sequence_number = packet_sequence_number;

        if (num_bits_prev_frame > 0) {

            int remaining_packet_bits = s->buf_bit_size - get_bits_count(gb);

            if (num_bits_prev_frame >= remaining_packet_bits) {

                num_bits_prev_frame = remaining_packet_bits;

                s->packet_done = 1;

            }

            /** append the previous frame data to the remaining data from the

                previous packet to create a full frame */

            save_bits(s, gb, num_bits_prev_frame, 1);

            /** decode the cross packet frame if it is valid */

            if (!s->packet_loss)

		decode_frame(s);

        } else if (s->num_saved_bits - s->frame_offset) {

            dprintf(avctx, "ignoring %x previously saved bits\n",

                    s->num_saved_bits - s->frame_offset);

        }

        if (s->packet_loss) {

            /** reset number of saved bits so that the decoder

                does not start to decode incomplete frames in the

                s->len_prefix == 0 case */

            s->num_saved_bits = 0;

            s->packet_loss = 0;

        }

    } else {

        int frame_size;

        s->buf_bit_size = (avpkt->size - s->next_packet_start) << 3;

        init_get_bits(gb, avpkt->data, s->buf_bit_size);

        skip_bits(gb, s->packet_offset);

        if (s->len_prefix && remaining_bits(s, gb) > s->log2_frame_size &&

            (frame_size = show_bits(gb, s->log2_frame_size)) &&

            frame_size <= remaining_bits(s, gb)) {

            save_bits(s, gb, frame_size, 0);

            s->packet_done = !decode_frame(s);

        } else if (!s->len_prefix

                   && s->num_saved_bits > get_bits_count(&s->gb)) {

            /** when the frames do not have a length prefix, we don't know

                the compressed length of the individual frames

                however, we know what part of a new packet belongs to the

                previous frame

                therefore we save the incoming packet first, then we append

                the "previous frame" data from the next packet so that

                we get a buffer that only contains full frames */

            s->packet_done = !decode_frame(s);

        } else {

            s->packet_done = 1;

	}

    }

    if (s->packet_done && !s->packet_loss &&

        remaining_bits(s, gb) > 0) {

        /** save the rest of the data so that it can be decoded

            with the next packet */

        save_bits(s, gb, remaining_bits(s, gb), 0);

    }

    *data_size = 0; // (int8_t *)s->samples - (int8_t *)data;

    s->packet_offset = get_bits_count(gb) & 7;

    return (s->packet_loss) ? AVERROR_INVALIDDATA : get_bits_count(gb) >> 3;

}


int vhost_backend_update_device_iotlb(struct vhost_dev *dev,

                                             uint64_t iova, uint64_t uaddr,

                                             uint64_t len,

                                             IOMMUAccessFlags perm)

{

    struct vhost_iotlb_msg imsg;

    imsg.iova =  iova;

    imsg.uaddr = uaddr;

    imsg.size = len;

    imsg.type = VHOST_IOTLB_UPDATE;

    switch (perm) {

    case IOMMU_RO:

        imsg.perm = VHOST_ACCESS_RO;

        break;

    case IOMMU_WO:

        imsg.perm = VHOST_ACCESS_WO;

        break;

    case IOMMU_RW:

        imsg.perm = VHOST_ACCESS_RW;

        break;

    default:

        return -EINVAL;

    }

    return dev->vhost_ops->vhost_send_device_iotlb_msg(dev, &imsg);

}


void qemu_set_log_filename(const char *filename)

{

    char *pidstr;

    g_free(logfilename);

    pidstr = strstr(filename, "%");

    if (pidstr) {

        /* We only accept one %d, no other format strings */

        if (pidstr[1] != 'd' || strchr(pidstr + 2, '%')) {

            error_report("Bad logfile format: %s", filename);

            logfilename = NULL;

        } else {

            logfilename = g_strdup_printf(filename, getpid());

        }

    } else {

        logfilename = g_strdup(filename);

    }

    qemu_log_close();

    qemu_set_log(qemu_loglevel);

}


static void virtio_scsi_handle_event(VirtIODevice *vdev, VirtQueue *vq)

{

    VirtIOSCSI *s = VIRTIO_SCSI(vdev);

    if (s->ctx && !s->dataplane_started) {

        virtio_scsi_dataplane_start(s);

        return;

    }

    if (s->events_dropped) {

        virtio_scsi_push_event(s, NULL, VIRTIO_SCSI_T_NO_EVENT, 0);

    }

}


static int gdb_set_spe_reg(CPUState *env, uint8_t *mem_buf, int n)

{

    if (n < 32) {

#if defined(TARGET_PPC64)

        target_ulong lo = (uint32_t)env->gpr[n];

        target_ulong hi = (target_ulong)ldl_p(mem_buf) << 32;

        env->gpr[n] = lo | hi;

#else

        env->gprh[n] = ldl_p(mem_buf);

#endif

        return 4;

    }

    if (n == 33) {

        env->spe_acc = ldq_p(mem_buf);

        return 8;

    }

    if (n == 34) {

        /* SPEFSCR not implemented */

        return 4;

    }

    return 0;

}


int pci_bridge_initfn(PCIDevice *dev)

{

    PCIBus *parent = dev->bus;

    PCIBridge *br = DO_UPCAST(PCIBridge, dev, dev);

    PCIBus *sec_bus = &br->sec_bus;

    pci_word_test_and_set_mask(dev->config + PCI_STATUS,

                               PCI_STATUS_66MHZ | PCI_STATUS_FAST_BACK);

    pci_config_set_class(dev->config, PCI_CLASS_BRIDGE_PCI);

    dev->config[PCI_HEADER_TYPE] =

        (dev->config[PCI_HEADER_TYPE] & PCI_HEADER_TYPE_MULTI_FUNCTION) |

        PCI_HEADER_TYPE_BRIDGE;

    pci_set_word(dev->config + PCI_SEC_STATUS,

                 PCI_STATUS_66MHZ | PCI_STATUS_FAST_BACK);

    /*

     * If we don't specify the name, the bus will be addressed as <id>.0, where

     * id is the device id.

     * Since PCI Bridge devices have a single bus each, we don't need the index:

     * let users address the bus using the device name.

     */

    if (!br->bus_name && dev->qdev.id && *dev->qdev.id) {

	    br->bus_name = dev->qdev.id;

    }

    qbus_create_inplace(&sec_bus->qbus, TYPE_PCI_BUS, &dev->qdev,

                        br->bus_name);

    sec_bus->parent_dev = dev;

    sec_bus->map_irq = br->map_irq;

    sec_bus->address_space_mem = &br->address_space_mem;

    memory_region_init(&br->address_space_mem, "pci_bridge_pci", INT64_MAX);

    sec_bus->address_space_io = &br->address_space_io;

    memory_region_init(&br->address_space_io, "pci_bridge_io", 65536);

    pci_bridge_region_init(br);

    QLIST_INIT(&sec_bus->child);

    QLIST_INSERT_HEAD(&parent->child, sec_bus, sibling);

    return 0;

}