static void calxeda_init(MachineState *machine, enum cxmachines machine_id)

{

    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;

    DeviceState *dev = NULL;

    SysBusDevice *busdev;

    qemu_irq pic[128];

    int n;

    qemu_irq cpu_irq[4];

    MemoryRegion *sysram;

    MemoryRegion *dram;

    MemoryRegion *sysmem;

    char *sysboot_filename;

    if (!cpu_model) {

        switch (machine_id) {

        case CALXEDA_HIGHBANK:

            cpu_model = "cortex-a9";

            break;

        case CALXEDA_MIDWAY:

            cpu_model = "cortex-a15";

            break;

        }

    }

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

        ObjectClass *oc = cpu_class_by_name(TYPE_ARM_CPU, cpu_model);

        Object *cpuobj;

        ARMCPU *cpu;

        Error *err = NULL;

        if (!oc) {

            error_report("Unable to find CPU definition");

            exit(1);

        }

        cpuobj = object_new(object_class_get_name(oc));

        cpu = ARM_CPU(cpuobj);

        /* By default A9 and A15 CPUs have EL3 enabled.  This board does not

         * currently support EL3 so the CPU EL3 property is disabled before

         * realization.

         */

        if (object_property_find(cpuobj, "has_el3", NULL)) {

            object_property_set_bool(cpuobj, false, "has_el3", &err);

            if (err) {

                error_report_err(err);

                exit(1);

            }

        }

        if (object_property_find(cpuobj, "reset-cbar", NULL)) {

            object_property_set_int(cpuobj, MPCORE_PERIPHBASE,

                                    "reset-cbar", &error_abort);

        }

        object_property_set_bool(cpuobj, true, "realized", &err);

        if (err) {

            error_report_err(err);

            exit(1);

        }

        cpu_irq[n] = qdev_get_gpio_in(DEVICE(cpu), ARM_CPU_IRQ);

    }

    sysmem = get_system_memory();

    dram = g_new(MemoryRegion, 1);

    memory_region_init_ram(dram, NULL, "highbank.dram", ram_size, &error_abort);

    /* SDRAM at address zero.  */

    memory_region_add_subregion(sysmem, 0, dram);

    sysram = g_new(MemoryRegion, 1);

    memory_region_init_ram(sysram, NULL, "highbank.sysram", 0x8000,

                           &error_abort);

    memory_region_add_subregion(sysmem, 0xfff88000, sysram);

    if (bios_name != NULL) {

        sysboot_filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);

        if (sysboot_filename != NULL) {

            uint32_t filesize = get_image_size(sysboot_filename);

            if (load_image_targphys("sysram.bin", 0xfff88000, filesize) < 0) {

                hw_error("Unable to load %s\n", bios_name);

            }

            g_free(sysboot_filename);

        } else {

           hw_error("Unable to find %s\n", bios_name);

        }

    }

    switch (machine_id) {

    case CALXEDA_HIGHBANK:

        dev = qdev_create(NULL, "l2x0");

        qdev_init_nofail(dev);

        busdev = SYS_BUS_DEVICE(dev);

        sysbus_mmio_map(busdev, 0, 0xfff12000);

        dev = qdev_create(NULL, "a9mpcore_priv");

        break;

    case CALXEDA_MIDWAY:

        dev = qdev_create(NULL, "a15mpcore_priv");

        break;

    }

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

    qdev_prop_set_uint32(dev, "num-irq", NIRQ_GIC);

    qdev_init_nofail(dev);

    busdev = SYS_BUS_DEVICE(dev);

    sysbus_mmio_map(busdev, 0, MPCORE_PERIPHBASE);

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

        sysbus_connect_irq(busdev, n, cpu_irq[n]);

    }

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

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

    }

    dev = qdev_create(NULL, "sp804");

    qdev_prop_set_uint32(dev, "freq0", 150000000);

    qdev_prop_set_uint32(dev, "freq1", 150000000);

    qdev_init_nofail(dev);

    busdev = SYS_BUS_DEVICE(dev);

    sysbus_mmio_map(busdev, 0, 0xfff34000);

    sysbus_connect_irq(busdev, 0, pic[18]);

    sysbus_create_simple("pl011", 0xfff36000, pic[20]);

    dev = qdev_create(NULL, "highbank-regs");

    qdev_init_nofail(dev);

    busdev = SYS_BUS_DEVICE(dev);

    sysbus_mmio_map(busdev, 0, 0xfff3c000);

    sysbus_create_simple("pl061", 0xfff30000, pic[14]);

    sysbus_create_simple("pl061", 0xfff31000, pic[15]);

    sysbus_create_simple("pl061", 0xfff32000, pic[16]);

    sysbus_create_simple("pl061", 0xfff33000, pic[17]);

    sysbus_create_simple("pl031", 0xfff35000, pic[19]);

    sysbus_create_simple("pl022", 0xfff39000, pic[23]);

    sysbus_create_simple("sysbus-ahci", 0xffe08000, pic[83]);

    if (nd_table[0].used) {

        qemu_check_nic_model(&nd_table[0], "xgmac");

        dev = qdev_create(NULL, "xgmac");

        qdev_set_nic_properties(dev, &nd_table[0]);

        qdev_init_nofail(dev);

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

        sysbus_connect_irq(SYS_BUS_DEVICE(dev), 0, pic[77]);

        sysbus_connect_irq(SYS_BUS_DEVICE(dev), 1, pic[78]);

        sysbus_connect_irq(SYS_BUS_DEVICE(dev), 2, pic[79]);

        qemu_check_nic_model(&nd_table[1], "xgmac");

        dev = qdev_create(NULL, "xgmac");

        qdev_set_nic_properties(dev, &nd_table[1]);

        qdev_init_nofail(dev);

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

        sysbus_connect_irq(SYS_BUS_DEVICE(dev), 0, pic[80]);

        sysbus_connect_irq(SYS_BUS_DEVICE(dev), 1, pic[81]);

        sysbus_connect_irq(SYS_BUS_DEVICE(dev), 2, pic[82]);

    }

    highbank_binfo.ram_size = ram_size;

    highbank_binfo.kernel_filename = kernel_filename;

    highbank_binfo.kernel_cmdline = kernel_cmdline;

    highbank_binfo.initrd_filename = initrd_filename;

    /* highbank requires a dtb in order to boot, and the dtb will override

     * the board ID. The following value is ignored, so set it to -1 to be

     * clear that the value is meaningless.

     */

    highbank_binfo.board_id = -1;

    highbank_binfo.nb_cpus = smp_cpus;

    highbank_binfo.loader_start = 0;

    highbank_binfo.write_secondary_boot = hb_write_secondary;

    highbank_binfo.secondary_cpu_reset_hook = hb_reset_secondary;

    arm_load_kernel(ARM_CPU(first_cpu), &highbank_binfo);

}


bool trace_init_backends(void)
{
#ifdef CONFIG_TRACE_SIMPLE
    if (!st_init()) {
        fprintf(stderr, "failed to initialize simple tracing backend.\n");
        return false;
    }
#ifdef CONFIG_TRACE_FTRACE
    if (!ftrace_init()) {
        fprintf(stderr, "failed to initialize ftrace backend.\n");
        return false;
    }
    return true;
}


static inline void acpi_build_tables_cleanup(AcpiBuildTables *tables, bool mfre)

{

    void *linker_data = bios_linker_loader_cleanup(tables->linker);

    if (mfre) {

        g_free(linker_data);

    }

    g_array_free(tables->rsdp, mfre);

    g_array_free(tables->table_data, mfre);

    g_array_free(tables->tcpalog, mfre);

}


static void dec_mul(DisasContext *dc)

{

    if (dc->format == OP_FMT_RI) {

        LOG_DIS("muli r%d, r%d, %d\n", dc->r0, dc->r1,

                sign_extend(dc->imm16, 16));

    } else {

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

    }

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

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

    }

    if (dc->format == OP_FMT_RI) {

        tcg_gen_muli_tl(cpu_R[dc->r1], cpu_R[dc->r0],

                sign_extend(dc->imm16, 16));

    } else {

        tcg_gen_mul_tl(cpu_R[dc->r2], cpu_R[dc->r0], cpu_R[dc->r1]);

    }

}


static void v9fs_clunk(void *opaque)

{

    int err;

    int32_t fid;

    size_t offset = 7;

    V9fsFidState *fidp;

    V9fsPDU *pdu = opaque;

    V9fsState *s = pdu->s;

    pdu_unmarshal(pdu, offset, "d", &fid);

    fidp = clunk_fid(s, fid);

    if (fidp == NULL) {

        err = -ENOENT;

        goto out_nofid;

    }

    /*

     * Bump the ref so that put_fid will

     * free the fid.

     */

    fidp->ref++;

    err = offset;

    put_fid(pdu, fidp);

out_nofid:

    complete_pdu(s, pdu, err);

}


static int cbs_mpeg2_read_unit(CodedBitstreamContext *ctx,

                               CodedBitstreamUnit *unit)

{

    BitstreamContext bc;

    int err;

    err = bitstream_init(&bc, unit->data, 8 * unit->data_size);

    if (err < 0)

        return err;

    if (MPEG2_START_IS_SLICE(unit->type)) {

        MPEG2RawSlice *slice;

        int pos, len;

        slice = av_mallocz(sizeof(*slice));

        if (!slice)

            return AVERROR(ENOMEM);

        err = cbs_mpeg2_read_slice_header(ctx, &bc, &slice->header);

        if (err < 0) {

            av_free(slice);

            return err;

        }

        pos = bitstream_tell(&bc);

        len = unit->data_size;

        slice->data_size = len - pos / 8;

        slice->data = av_malloc(slice->data_size);

        if (!slice->data) {

            av_free(slice);

            return AVERROR(ENOMEM);

        }

        memcpy(slice->data,

               unit->data + pos / 8, slice->data_size);

        slice->data_bit_start = pos % 8;

        unit->content = slice;

    } else {

        switch (unit->type) {

#define START(start_code, type, func) \

        case start_code: \

            { \

                type *header; \

                header = av_mallocz(sizeof(*header)); \

                if (!header) \

                    return AVERROR(ENOMEM); \

                err = cbs_mpeg2_read_ ## func(ctx, &bc, header); \

                if (err < 0) { \

                    av_free(header); \

                    return err; \

                } \

                unit->content = header; \

            } \

            break;

            START(0x00, MPEG2RawPictureHeader,  picture_header);

            START(0xb2, MPEG2RawUserData,       user_data);

            START(0xb3, MPEG2RawSequenceHeader, sequence_header);

            START(0xb5, MPEG2RawExtensionData,  extension_data);

            START(0xb8, MPEG2RawGroupOfPicturesHeader, group_of_pictures_header);

#undef START

        default:

            av_log(ctx->log_ctx, AV_LOG_ERROR, "Unknown start code %02x.\n",

                   unit->type);

            return AVERROR_INVALIDDATA;

        }

    }

    return 0;

}


static int scan_for_extensions(AVCodecContext *avctx)

{

    DCAContext *s = avctx->priv_data;

    int core_ss_end, ret;

    core_ss_end = FFMIN(s->frame_size, s->dca_buffer_size) * 8;

    /* only scan for extensions if ext_descr was unknown or indicated a

     * supported XCh extension */

    if (s->core_ext_mask < 0 || s->core_ext_mask & DCA_EXT_XCH) {

        /* if ext_descr was unknown, clear s->core_ext_mask so that the

         * extensions scan can fill it up */

        s->core_ext_mask = FFMAX(s->core_ext_mask, 0);

        /* extensions start at 32-bit boundaries into bitstream */

        skip_bits_long(&s->gb, (-get_bits_count(&s->gb)) & 31);

        while (core_ss_end - get_bits_count(&s->gb) >= 32) {

            uint32_t bits = get_bits_long(&s->gb, 32);

            int i;

            switch (bits) {

            case DCA_SYNCWORD_XCH: {

                int ext_amode, xch_fsize;

                s->xch_base_channel = s->prim_channels;

                /* validate sync word using XCHFSIZE field */

                xch_fsize = show_bits(&s->gb, 10);

                if ((s->frame_size != (get_bits_count(&s->gb) >> 3) - 4 + xch_fsize) &&

                    (s->frame_size != (get_bits_count(&s->gb) >> 3) - 4 + xch_fsize + 1))

                    continue;

                /* skip length-to-end-of-frame field for the moment */

                skip_bits(&s->gb, 10);

                s->core_ext_mask |= DCA_EXT_XCH;

                /* extension amode(number of channels in extension) should be 1 */

                /* AFAIK XCh is not used for more channels */

                if ((ext_amode = get_bits(&s->gb, 4)) != 1) {

                    av_log(avctx, AV_LOG_ERROR,

                           "XCh extension amode %d not supported!\n",

                           ext_amode);

                    continue;

                }

                /* much like core primary audio coding header */

                dca_parse_audio_coding_header(s, s->xch_base_channel);

                for (i = 0; i < (s->sample_blocks / 8); i++)

                    if ((ret = dca_decode_block(s, s->xch_base_channel, i))) {

                        av_log(avctx, AV_LOG_ERROR, "error decoding XCh extension\n");

                        continue;

                    }

                s->xch_present = 1;

                break;

            }

            case DCA_SYNCWORD_XXCH:

                /* XXCh: extended channels */

                /* usually found either in core or HD part in DTS-HD HRA streams,

                 * but not in DTS-ES which contains XCh extensions instead */

                s->core_ext_mask |= DCA_EXT_XXCH;

                break;

            case 0x1d95f262: {

                int fsize96 = show_bits(&s->gb, 12) + 1;

                if (s->frame_size != (get_bits_count(&s->gb) >> 3) - 4 + fsize96)

                    continue;

                av_log(avctx, AV_LOG_DEBUG, "X96 extension found at %d bits\n",

                       get_bits_count(&s->gb));

                skip_bits(&s->gb, 12);

                av_log(avctx, AV_LOG_DEBUG, "FSIZE96 = %d bytes\n", fsize96);

                av_log(avctx, AV_LOG_DEBUG, "REVNO = %d\n", get_bits(&s->gb, 4));

                s->core_ext_mask |= DCA_EXT_X96;

                break;

            }

            }

            skip_bits_long(&s->gb, (-get_bits_count(&s->gb)) & 31);

        }

    } else {

        /* no supported extensions, skip the rest of the core substream */

        skip_bits_long(&s->gb, core_ss_end - get_bits_count(&s->gb));

    }

    if (s->core_ext_mask & DCA_EXT_X96)

        s->profile = FF_PROFILE_DTS_96_24;

    else if (s->core_ext_mask & (DCA_EXT_XCH | DCA_EXT_XXCH))

        s->profile = FF_PROFILE_DTS_ES;

    /* check for ExSS (HD part) */

    if (s->dca_buffer_size - s->frame_size > 32 &&

        get_bits_long(&s->gb, 32) == DCA_SYNCWORD_SUBSTREAM)

        ff_dca_exss_parse_header(s);

    return ret;

}


udp_input(register struct mbuf *m, int iphlen)

{

	Slirp *slirp = m->slirp;

	register struct ip *ip;

	register struct udphdr *uh;

	int len;

	struct ip save_ip;

	struct socket *so;

	DEBUG_CALL("udp_input");

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

	DEBUG_ARG("iphlen = %d", iphlen);

	/*

	 * Strip IP options, if any; should skip this,

	 * make available to user, and use on returned packets,

	 * but we don't yet have a way to check the checksum

	 * with options still present.

	 */

	if(iphlen > sizeof(struct ip)) {

		ip_stripoptions(m, (struct mbuf *)0);

		iphlen = sizeof(struct ip);

	}

	/*

	 * Get IP and UDP header together in first mbuf.

	 */

	ip = mtod(m, struct ip *);

	uh = (struct udphdr *)((caddr_t)ip + iphlen);

	/*

	 * Make mbuf data length reflect UDP length.

	 * If not enough data to reflect UDP length, drop.

	 */

	len = ntohs((uint16_t)uh->uh_ulen);

	if (ip->ip_len != len) {

		if (len > ip->ip_len) {

			goto bad;

		}

		m_adj(m, len - ip->ip_len);

		ip->ip_len = len;

	}

	/*

	 * Save a copy of the IP header in case we want restore it

	 * for sending an ICMP error message in response.

	 */

	save_ip = *ip;

	save_ip.ip_len+= iphlen;         /* tcp_input subtracts this */

	/*

	 * Checksum extended UDP header and data.

	 */

	if (uh->uh_sum) {

      memset(&((struct ipovly *)ip)->ih_mbuf, 0, sizeof(struct mbuf_ptr));

	  ((struct ipovly *)ip)->ih_x1 = 0;

	  ((struct ipovly *)ip)->ih_len = uh->uh_ulen;

	  if(cksum(m, len + sizeof(struct ip))) {

	    goto bad;

	  }

	}

        /*

         *  handle DHCP/BOOTP

         */

        if (ntohs(uh->uh_dport) == BOOTP_SERVER &&

            (ip->ip_dst.s_addr == slirp->vhost_addr.s_addr ||

             ip->ip_dst.s_addr == 0xffffffff)) {

                bootp_input(m);

                goto bad;

            }

        /*

         *  handle TFTP

         */

        if (ntohs(uh->uh_dport) == TFTP_SERVER &&

            ip->ip_dst.s_addr == slirp->vhost_addr.s_addr) {

            tftp_input(m);

            goto bad;

        }

        if (slirp->restricted) {

            goto bad;

        }

	/*

	 * Locate pcb for datagram.

	 */

	so = slirp->udp_last_so;

	if (so->so_lport != uh->uh_sport ||

	    so->so_laddr.s_addr != ip->ip_src.s_addr) {

		struct socket *tmp;

		for (tmp = slirp->udb.so_next; tmp != &slirp->udb;

		     tmp = tmp->so_next) {

			if (tmp->so_lport == uh->uh_sport &&

			    tmp->so_laddr.s_addr == ip->ip_src.s_addr) {

				so = tmp;

				break;

			}

		}

		if (tmp == &slirp->udb) {

		  so = NULL;

		} else {

		  slirp->udp_last_so = so;

		}

	}

	if (so == NULL) {

	  /*

	   * If there's no socket for this packet,

	   * create one

	   */

	  so = socreate(slirp);

	  if (!so) {

	      goto bad;

	  }

	  if(udp_attach(so) == -1) {

	    DEBUG_MISC((dfd," udp_attach errno = %d-%s\n",

			errno,strerror(errno)));

	    sofree(so);

	    goto bad;

	  }

	  /*

	   * Setup fields

	   */

	  so->so_laddr = ip->ip_src;

	  so->so_lport = uh->uh_sport;

	  if ((so->so_iptos = udp_tos(so)) == 0)

	    so->so_iptos = ip->ip_tos;

	  /*

	   * XXXXX Here, check if it's in udpexec_list,

	   * and if it is, do the fork_exec() etc.

	   */

	}

        so->so_faddr = ip->ip_dst; /* XXX */

        so->so_fport = uh->uh_dport; /* XXX */

	iphlen += sizeof(struct udphdr);

	m->m_len -= iphlen;

	m->m_data += iphlen;

	/*

	 * Now we sendto() the packet.

	 */

	if(sosendto(so,m) == -1) {

	  m->m_len += iphlen;

	  m->m_data -= iphlen;

	  *ip=save_ip;

	  DEBUG_MISC((dfd,"udp tx errno = %d-%s\n",errno,strerror(errno)));

	  icmp_error(m, ICMP_UNREACH,ICMP_UNREACH_NET, 0,strerror(errno));

	}

	m_free(so->so_m);   /* used for ICMP if error on sorecvfrom */

	/* restore the orig mbuf packet */

	m->m_len += iphlen;

	m->m_data -= iphlen;

	*ip=save_ip;

	so->so_m=m;         /* ICMP backup */

	return;

bad:

	m_free(m);

}


static int con_init(struct XenDevice *xendev)

{

    struct XenConsole *con = container_of(xendev, struct XenConsole, xendev);

    char *type, *dom;

    /* setup */

    dom = xs_get_domain_path(xenstore, con->xendev.dom);

    snprintf(con->console, sizeof(con->console), "%s/console", dom);

    free(dom);

    type = xenstore_read_str(con->console, "type");

    if (!type || strcmp(type, "ioemu") != 0) {

	xen_be_printf(xendev, 1, "not for me (type=%s)\n", type);

	return -1;

    }

    if (!serial_hds[con->xendev.dev])

	xen_be_printf(xendev, 1, "WARNING: serial line %d not configured\n",

                      con->xendev.dev);

    else

        con->chr = serial_hds[con->xendev.dev];

    return 0;

}


static av_unused FFPsyWindowInfo psy_3gpp_window(FFPsyContext *ctx,

                                                 const int16_t *audio,

                                                 const int16_t *la,

                                                 int channel, int prev_type)

{

    int i, j;

    int br               = ctx->avctx->bit_rate / ctx->avctx->channels;

    int attack_ratio     = br <= 16000 ? 18 : 10;

    AacPsyContext *pctx = (AacPsyContext*) ctx->model_priv_data;

    AacPsyChannel *pch  = &pctx->ch[channel];

    uint8_t grouping     = 0;

    int next_type        = pch->next_window_seq;

    FFPsyWindowInfo wi  = { { 0 } };

    if (la) {

        float s[8], v;

        int switch_to_eight = 0;

        float sum = 0.0, sum2 = 0.0;

        int attack_n = 0;

        int stay_short = 0;

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

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

                v = iir_filter(la[i*128+j], pch->iir_state);

                sum += v*v;

            }

            s[i]  = sum;

            sum2 += sum;

        }

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

            if (s[i] > pch->win_energy * attack_ratio) {

                attack_n        = i + 1;

                switch_to_eight = 1;

                break;

            }

        }

        pch->win_energy = pch->win_energy*7/8 + sum2/64;

        wi.window_type[1] = prev_type;

        switch (prev_type) {

        case ONLY_LONG_SEQUENCE:

            wi.window_type[0] = switch_to_eight ? LONG_START_SEQUENCE : ONLY_LONG_SEQUENCE;

            next_type = switch_to_eight ? EIGHT_SHORT_SEQUENCE : ONLY_LONG_SEQUENCE;

            break;

        case LONG_START_SEQUENCE:

            wi.window_type[0] = EIGHT_SHORT_SEQUENCE;

            grouping = pch->next_grouping;

            next_type = switch_to_eight ? EIGHT_SHORT_SEQUENCE : LONG_STOP_SEQUENCE;

            break;

        case LONG_STOP_SEQUENCE:

            wi.window_type[0] = switch_to_eight ? LONG_START_SEQUENCE : ONLY_LONG_SEQUENCE;

            next_type = switch_to_eight ? EIGHT_SHORT_SEQUENCE : ONLY_LONG_SEQUENCE;

            break;

        case EIGHT_SHORT_SEQUENCE:

            stay_short = next_type == EIGHT_SHORT_SEQUENCE || switch_to_eight;

            wi.window_type[0] = stay_short ? EIGHT_SHORT_SEQUENCE : LONG_STOP_SEQUENCE;

            grouping = next_type == EIGHT_SHORT_SEQUENCE ? pch->next_grouping : 0;

            next_type = switch_to_eight ? EIGHT_SHORT_SEQUENCE : LONG_STOP_SEQUENCE;

            break;

        }

        pch->next_grouping = window_grouping[attack_n];

        pch->next_window_seq = next_type;

    } else {

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

            wi.window_type[i] = prev_type;

        grouping = (prev_type == EIGHT_SHORT_SEQUENCE) ? window_grouping[0] : 0;

    }

    wi.window_shape   = 1;

    if (wi.window_type[0] != EIGHT_SHORT_SEQUENCE) {

        wi.num_windows = 1;

        wi.grouping[0] = 1;

    } else {

        int lastgrp = 0;

        wi.num_windows = 8;

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

            if (!((grouping >> i) & 1))

                lastgrp = i;

            wi.grouping[lastgrp]++;

        }

    }

    return wi;

}


static int rac_get_model_sym(RangeCoder *c, Model *m)

{

    int prob, prob2, helper, val;

    int end, end2;

    prob       = 0;

    prob2      = c->range;

    c->range >>= MODEL_SCALE;

    val        = 0;

    end        = m->num_syms >> 1;

    end2       = m->num_syms;

    do {

        helper = m->freqs[end] * c->range;

        if (helper <= c->low) {

            val   = end;

            prob  = helper;

        } else {

            end2  = end;

            prob2 = helper;

        }

        end = (end2 + val) >> 1;

    } while (end != val);

    c->low  -= prob;

    c->range = prob2 - prob;

    if (c->range < RAC_BOTTOM)

        rac_normalise(c);

    model_update(m, val);

    return val;

}


static int dvbsub_display_end_segment(AVCodecContext *avctx, const uint8_t *buf,

                                        int buf_size, AVSubtitle *sub)

{

    DVBSubContext *ctx = avctx->priv_data;

    DVBSubDisplayDefinition *display_def = ctx->display_definition;

    DVBSubRegion *region;

    DVBSubRegionDisplay *display;

    AVSubtitleRect *rect;

    DVBSubCLUT *clut;

    uint32_t *clut_table;

    int i;

    int offset_x=0, offset_y=0;

    sub->end_display_time = ctx->time_out * 1000;

    if (display_def) {

        offset_x = display_def->x;

        offset_y = display_def->y;

    }

    sub->num_rects = ctx->display_list_size;

    if (sub->num_rects > 0){

        sub->rects = av_mallocz(sizeof(*sub->rects) * sub->num_rects);

        for(i=0; i<sub->num_rects; i++)

            sub->rects[i] = av_mallocz(sizeof(*sub->rects[i]));

    i = 0;

    for (display = ctx->display_list; display; display = display->next) {

        region = get_region(ctx, display->region_id);

        if (!region)

            continue;

        if (!region->dirty)

            continue;

        rect = sub->rects[i];

        rect->x = display->x_pos + offset_x;

        rect->y = display->y_pos + offset_y;

        rect->w = region->width;

        rect->h = region->height;

        rect->nb_colors = (1 << region->depth);

        rect->type      = SUBTITLE_BITMAP;

        rect->pict.linesize[0] = region->width;

        clut = get_clut(ctx, region->clut);

        if (!clut)

            clut = &default_clut;

        switch (region->depth) {

        case 2:

            clut_table = clut->clut4;

            break;

        case 8:

            clut_table = clut->clut256;

            break;

        case 4:

        default:

            clut_table = clut->clut16;

            break;

        }

        rect->pict.data[1] = av_mallocz(AVPALETTE_SIZE);

        memcpy(rect->pict.data[1], clut_table, (1 << region->depth) * sizeof(uint32_t));

        rect->pict.data[0] = av_malloc(region->buf_size);

        memcpy(rect->pict.data[0], region->pbuf, region->buf_size);

        i++;

    }

    sub->num_rects = i;

    }

#ifdef DEBUG

    save_display_set(ctx);

#endif

    return 1;

}


static void pnv_chip_realize(DeviceState *dev, Error **errp)
{
    PnvChip *chip = PNV_CHIP(dev);
    Error *error = NULL;
    PnvChipClass *pcc = PNV_CHIP_GET_CLASS(chip);
    char *typename = pnv_core_typename(pcc->cpu_model);
    size_t typesize = object_type_get_instance_size(typename);
    int i, core_hwid;
    if (!object_class_by_name(typename)) {
        error_setg(errp, "Unable to find PowerNV CPU Core '%s'", typename);
    /* Cores */
    pnv_chip_core_sanitize(chip, &error);
    chip->cores = g_malloc0(typesize * chip->nr_cores);
    for (i = 0, core_hwid = 0; (core_hwid < sizeof(chip->cores_mask) * 8)
             && (i < chip->nr_cores); core_hwid++) {
        char core_name[32];
        void *pnv_core = chip->cores + i * typesize;
        if (!(chip->cores_mask & (1ull << core_hwid))) {
            continue;
        object_initialize(pnv_core, typesize, typename);
        snprintf(core_name, sizeof(core_name), "core[%d]", core_hwid);
        object_property_add_child(OBJECT(chip), core_name, OBJECT(pnv_core),
                                  &error_fatal);
        object_property_set_int(OBJECT(pnv_core), smp_threads, "nr-threads",
                                &error_fatal);
        object_property_set_int(OBJECT(pnv_core), core_hwid,
                                CPU_CORE_PROP_CORE_ID, &error_fatal);
        object_property_set_int(OBJECT(pnv_core),
                                pcc->core_pir(chip, core_hwid),
                                "pir", &error_fatal);
        object_property_set_bool(OBJECT(pnv_core), true, "realized",
                                 &error_fatal);
        object_unref(OBJECT(pnv_core));
        i++;
    g_free(typename);


static void bt_l2cap_sdp_close_ch(void *opaque)

{

    struct bt_l2cap_sdp_state_s *sdp = opaque;

    int i;

    for (i = 0; i < sdp->services; i ++) {

        g_free(sdp->service_list[i].attribute_list->pair);

        g_free(sdp->service_list[i].attribute_list);

        g_free(sdp->service_list[i].uuid);

    }

    g_free(sdp->service_list);

    g_free(sdp);

}


static uint16_t vring_used_idx(VirtQueue *vq)

{

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

    hwaddr pa = offsetof(VRingUsed, idx);

    return virtio_lduw_phys_cached(vq->vdev, &caches->used, pa);

}


static av_always_inline void hl_decode_mb_internal(H264Context *h, int simple){

    MpegEncContext * const s = &h->s;

    const int mb_x= s->mb_x;

    const int mb_y= s->mb_y;

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

    const int mb_type= s->current_picture.mb_type[mb_xy];

    uint8_t  *dest_y, *dest_cb, *dest_cr;

    int linesize, uvlinesize /*dct_offset*/;

    int i;

    int *block_offset = &h->block_offset[0];

    const unsigned int bottom = mb_y & 1;

    const int transform_bypass = (s->qscale == 0 && h->sps.transform_bypass), is_h264 = (simple || s->codec_id == CODEC_ID_H264);

    void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);

    void (*idct_dc_add)(uint8_t *dst, DCTELEM *block, int stride);

    dest_y  = s->current_picture.data[0] + (mb_y * 16* s->linesize  ) + mb_x * 16;

    dest_cb = s->current_picture.data[1] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;

    dest_cr = s->current_picture.data[2] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;

    s->dsp.prefetch(dest_y + (s->mb_x&3)*4*s->linesize + 64, s->linesize, 4);

    s->dsp.prefetch(dest_cb + (s->mb_x&7)*s->uvlinesize + 64, dest_cr - dest_cb, 2);

    if (!simple && MB_FIELD) {

        linesize   = h->mb_linesize   = s->linesize * 2;

        uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;

        block_offset = &h->block_offset[24];

        if(mb_y&1){ //FIXME move out of this func?

            dest_y -= s->linesize*15;

            dest_cb-= s->uvlinesize*7;

            dest_cr-= s->uvlinesize*7;

        }

        if(FRAME_MBAFF) {

            int list;

            for(list=0; list<h->list_count; list++){

                if(!USES_LIST(mb_type, list))

                    continue;

                if(IS_16X16(mb_type)){

                    int8_t *ref = &h->ref_cache[list][scan8[0]];

                    fill_rectangle(ref, 4, 4, 8, 16+*ref^(s->mb_y&1), 1);

                }else{

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

                        //FIXME can refs be smaller than 8x8 when !direct_8x8_inference ?

                        int ref = h->ref_cache[list][scan8[i]];

                        if(ref >= 0)

                            fill_rectangle(&h->ref_cache[list][scan8[i]], 2, 2, 8, 16+ref^(s->mb_y&1), 1);

                    }

                }

            }

        }

    } else {

        linesize   = h->mb_linesize   = s->linesize;

        uvlinesize = h->mb_uvlinesize = s->uvlinesize;

//        dct_offset = s->linesize * 16;

    }

    if(transform_bypass){

        idct_dc_add =

        idct_add = IS_8x8DCT(mb_type) ? s->dsp.add_pixels8 : s->dsp.add_pixels4;

    }else if(IS_8x8DCT(mb_type)){

        idct_dc_add = s->dsp.h264_idct8_dc_add;

        idct_add = s->dsp.h264_idct8_add;

    }else{

        idct_dc_add = s->dsp.h264_idct_dc_add;

        idct_add = s->dsp.h264_idct_add;

    }

    if(!simple && FRAME_MBAFF && h->deblocking_filter && IS_INTRA(mb_type)

       && (!bottom || !IS_INTRA(s->current_picture.mb_type[mb_xy-s->mb_stride]))){

        int mbt_y = mb_y&~1;

        uint8_t *top_y  = s->current_picture.data[0] + (mbt_y * 16* s->linesize  ) + mb_x * 16;

        uint8_t *top_cb = s->current_picture.data[1] + (mbt_y * 8 * s->uvlinesize) + mb_x * 8;

        uint8_t *top_cr = s->current_picture.data[2] + (mbt_y * 8 * s->uvlinesize) + mb_x * 8;

        xchg_pair_border(h, top_y, top_cb, top_cr, s->linesize, s->uvlinesize, 1);

    }

    if (!simple && IS_INTRA_PCM(mb_type)) {

        unsigned int x, y;

        // The pixels are stored in h->mb array in the same order as levels,

        // copy them in output in the correct order.

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

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

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

                    *(dest_y + block_offset[i] + y*linesize + x) = h->mb[i*16+y*4+x];

                }

            }

        }

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

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

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

                    *(dest_cb + block_offset[i] + y*uvlinesize + x) = h->mb[i*16+y*4+x];

                }

            }

        }

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

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

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

                    *(dest_cr + block_offset[i] + y*uvlinesize + x) = h->mb[i*16+y*4+x];

                }

            }

        }

    } else {

        if(IS_INTRA(mb_type)){

            if(h->deblocking_filter && (simple || !FRAME_MBAFF))

                xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 1, simple);

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

                h->pred8x8[ h->chroma_pred_mode ](dest_cb, uvlinesize);

                h->pred8x8[ h->chroma_pred_mode ](dest_cr, uvlinesize);

            }

            if(IS_INTRA4x4(mb_type)){

                if(simple || !s->encoding){

                    if(IS_8x8DCT(mb_type)){

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

                            uint8_t * const ptr= dest_y + block_offset[i];

                            const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];

                            const int nnz = h->non_zero_count_cache[ scan8[i] ];

                            h->pred8x8l[ dir ](ptr, (h->topleft_samples_available<<i)&0x8000,

                                                   (h->topright_samples_available<<i)&0x4000, linesize);

                            if(nnz){

                                if(nnz == 1 && h->mb[i*16])

                                    idct_dc_add(ptr, h->mb + i*16, linesize);

                                else

                                    idct_add(ptr, h->mb + i*16, linesize);

                            }

                        }

                    }else

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

                        uint8_t * const ptr= dest_y + block_offset[i];

                        uint8_t *topright;

                        const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];

                        int nnz, tr;

                        if(dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED){

                            const int topright_avail= (h->topright_samples_available<<i)&0x8000;

                            assert(mb_y || linesize <= block_offset[i]);

                            if(!topright_avail){

                                tr= ptr[3 - linesize]*0x01010101;

                                topright= (uint8_t*) &tr;

                            }else

                                topright= ptr + 4 - linesize;

                        }else

                            topright= NULL;

                        h->pred4x4[ dir ](ptr, topright, linesize);

                        nnz = h->non_zero_count_cache[ scan8[i] ];

                        if(nnz){

                            if(is_h264){

                                if(nnz == 1 && h->mb[i*16])

                                    idct_dc_add(ptr, h->mb + i*16, linesize);

                                else

                                    idct_add(ptr, h->mb + i*16, linesize);

                            }else

                                svq3_add_idct_c(ptr, h->mb + i*16, linesize, s->qscale, 0);

                        }

                    }

                }

            }else{

                h->pred16x16[ h->intra16x16_pred_mode ](dest_y , linesize);

                if(is_h264){

                    if(!transform_bypass)

                        h264_luma_dc_dequant_idct_c(h->mb, s->qscale, h->dequant4_coeff[IS_INTRA(mb_type) ? 0:3][s->qscale][0]);

                }else

                    svq3_luma_dc_dequant_idct_c(h->mb, s->qscale);

            }

            if(h->deblocking_filter && (simple || !FRAME_MBAFF))

                xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 0, simple);

        }else if(is_h264){

            hl_motion(h, dest_y, dest_cb, dest_cr,

                      s->me.qpel_put, s->dsp.put_h264_chroma_pixels_tab,

                      s->me.qpel_avg, s->dsp.avg_h264_chroma_pixels_tab,

                      s->dsp.weight_h264_pixels_tab, s->dsp.biweight_h264_pixels_tab);

        }

        if(!IS_INTRA4x4(mb_type)){

            if(is_h264){

                if(IS_INTRA16x16(mb_type)){

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

                        if(h->non_zero_count_cache[ scan8[i] ])

                            idct_add(dest_y + block_offset[i], h->mb + i*16, linesize);

                        else if(h->mb[i*16])

                            idct_dc_add(dest_y + block_offset[i], h->mb + i*16, linesize);

                    }

                }else{

                    const int di = IS_8x8DCT(mb_type) ? 4 : 1;

                    for(i=0; i<16; i+=di){

                        int nnz = h->non_zero_count_cache[ scan8[i] ];

                        if(nnz){

                            if(nnz==1 && h->mb[i*16])

                                idct_dc_add(dest_y + block_offset[i], h->mb + i*16, linesize);

                            else

                                idct_add(dest_y + block_offset[i], h->mb + i*16, linesize);

                        }

                    }

                }

            }else{

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

                    if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){ //FIXME benchmark weird rule, & below

                        uint8_t * const ptr= dest_y + block_offset[i];

                        svq3_add_idct_c(ptr, h->mb + i*16, linesize, s->qscale, IS_INTRA(mb_type) ? 1 : 0);

                    }

                }

            }

        }

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

            uint8_t *dest[2] = {dest_cb, dest_cr};

            if(transform_bypass){

                idct_add = idct_dc_add = s->dsp.add_pixels4;

            }else{

                idct_add = s->dsp.h264_idct_add;

                idct_dc_add = s->dsp.h264_idct_dc_add;

                chroma_dc_dequant_idct_c(h->mb + 16*16, h->chroma_qp, h->dequant4_coeff[IS_INTRA(mb_type) ? 1:4][h->chroma_qp][0]);

                chroma_dc_dequant_idct_c(h->mb + 16*16+4*16, h->chroma_qp, h->dequant4_coeff[IS_INTRA(mb_type) ? 2:5][h->chroma_qp][0]);

            }

            if(is_h264){

                for(i=16; i<16+8; i++){

                    if(h->non_zero_count_cache[ scan8[i] ])

                        idct_add(dest[(i&4)>>2] + block_offset[i], h->mb + i*16, uvlinesize);

                    else if(h->mb[i*16])

                        idct_dc_add(dest[(i&4)>>2] + block_offset[i], h->mb + i*16, uvlinesize);

                }

            }else{

                for(i=16; i<16+8; i++){

                    if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){

                        uint8_t * const ptr= dest[(i&4)>>2] + block_offset[i];

                        svq3_add_idct_c(ptr, h->mb + i*16, uvlinesize, chroma_qp[s->qscale + 12] - 12, 2);

                    }

                }

            }

        }

    }

    if(h->deblocking_filter) {

        if (!simple && FRAME_MBAFF) {

            //FIXME try deblocking one mb at a time?

            // the reduction in load/storing mvs and such might outweigh the extra backup/xchg_border

            const int mb_y = s->mb_y - 1;

            uint8_t  *pair_dest_y, *pair_dest_cb, *pair_dest_cr;

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

            const int mb_type_top   = s->current_picture.mb_type[mb_xy];

            const int mb_type_bottom= s->current_picture.mb_type[mb_xy+s->mb_stride];

            if (!bottom) return;

            pair_dest_y  = s->current_picture.data[0] + (mb_y * 16* s->linesize  ) + mb_x * 16;

            pair_dest_cb = s->current_picture.data[1] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;

            pair_dest_cr = s->current_picture.data[2] + (mb_y * 8 * s->uvlinesize) + mb_x * 8;

            if(IS_INTRA(mb_type_top | mb_type_bottom))

                xchg_pair_border(h, pair_dest_y, pair_dest_cb, pair_dest_cr, s->linesize, s->uvlinesize, 0);

            backup_pair_border(h, pair_dest_y, pair_dest_cb, pair_dest_cr, s->linesize, s->uvlinesize);

            // deblock a pair

            // top

            s->mb_y--;

            tprintf(h->s.avctx, "call mbaff filter_mb mb_x:%d mb_y:%d pair_dest_y = %p, dest_y = %p\n", mb_x, mb_y, pair_dest_y, dest_y);

            fill_caches(h, mb_type_top, 1); //FIXME don't fill stuff which isn't used by filter_mb

            h->chroma_qp = get_chroma_qp(h, s->current_picture.qscale_table[mb_xy]);

            filter_mb(h, mb_x, mb_y, pair_dest_y, pair_dest_cb, pair_dest_cr, linesize, uvlinesize);

            // bottom

            s->mb_y++;

            tprintf(h->s.avctx, "call mbaff filter_mb\n");

            fill_caches(h, mb_type_bottom, 1); //FIXME don't fill stuff which isn't used by filter_mb

            h->chroma_qp = get_chroma_qp(h, s->current_picture.qscale_table[mb_xy+s->mb_stride]);

            filter_mb(h, mb_x, mb_y+1, dest_y, dest_cb, dest_cr, linesize, uvlinesize);

        } else {

            tprintf(h->s.avctx, "call filter_mb\n");

            backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, simple);

            fill_caches(h, mb_type, 1); //FIXME don't fill stuff which isn't used by filter_mb

            filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb, dest_cr, linesize, uvlinesize);

        }

    }

}


static void spapr_rtc_class_init(ObjectClass *oc, void *data)

{

    DeviceClass *dc = DEVICE_CLASS(oc);

    dc->realize = spapr_rtc_realize;

    dc->vmsd = &vmstate_spapr_rtc;

    spapr_rtas_register(RTAS_GET_TIME_OF_DAY, "get-time-of-day",

                        rtas_get_time_of_day);

    spapr_rtas_register(RTAS_SET_TIME_OF_DAY, "set-time-of-day",

                        rtas_set_time_of_day);

}


static int read_len_table(uint8_t *dst, GetBitContext *gb){

    int i, val, repeat;

    for(i=0; i<256;){

        repeat= get_bits(gb, 3);

        val   = get_bits(gb, 5);

        if(repeat==0)

            repeat= get_bits(gb, 8);

//printf("%d %d\n", val, repeat);

        if(i+repeat > 256) {

            av_log(NULL, AV_LOG_ERROR, "Error reading huffman table\n");

            return -1;

        }

        while (repeat--)

            dst[i++] = val;

    }

    return 0;

}


static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,

    int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)

{

    BlockDriver *drv = bs->drv;

    QEMUIOVector qiov;

    struct iovec iov = {0};

    int ret = 0;

    int max_write_zeroes = bs->bl.max_write_zeroes ?

                           bs->bl.max_write_zeroes : MAX_WRITE_ZEROES_DEFAULT;

    while (nb_sectors > 0 && !ret) {

        int num = nb_sectors;

        /* Align request.  Block drivers can expect the "bulk" of the request

         * to be aligned.

         */

        if (bs->bl.write_zeroes_alignment

            && num > bs->bl.write_zeroes_alignment) {

            if (sector_num % bs->bl.write_zeroes_alignment != 0) {

                /* Make a small request up to the first aligned sector.  */

                num = bs->bl.write_zeroes_alignment;

                num -= sector_num % bs->bl.write_zeroes_alignment;

            } else if ((sector_num + num) % bs->bl.write_zeroes_alignment != 0) {

                /* Shorten the request to the last aligned sector.  num cannot

                 * underflow because num > bs->bl.write_zeroes_alignment.

                 */

                num -= (sector_num + num) % bs->bl.write_zeroes_alignment;

            }

        }

        /* limit request size */

        if (num > max_write_zeroes) {

            num = max_write_zeroes;

        }

        ret = -ENOTSUP;

        /* First try the efficient write zeroes operation */

        if (drv->bdrv_co_write_zeroes) {

            ret = drv->bdrv_co_write_zeroes(bs, sector_num, num, flags);

        }

        if (ret == -ENOTSUP) {

            /* Fall back to bounce buffer if write zeroes is unsupported */

            iov.iov_len = num * BDRV_SECTOR_SIZE;

            if (iov.iov_base == NULL) {

                iov.iov_base = qemu_blockalign(bs, num * BDRV_SECTOR_SIZE);

                memset(iov.iov_base, 0, num * BDRV_SECTOR_SIZE);

            }

            qemu_iovec_init_external(&qiov, &iov, 1);

            ret = drv->bdrv_co_writev(bs, sector_num, num, &qiov);

            /* Keep bounce buffer around if it is big enough for all

             * all future requests.

             */

            if (num < max_write_zeroes) {

                qemu_vfree(iov.iov_base);

                iov.iov_base = NULL;

            }

        }

        sector_num += num;

        nb_sectors -= num;

    }

    qemu_vfree(iov.iov_base);

    return ret;

}


void ff_ivi_inverse_haar_4x4(const int32_t *in, int16_t *out, ptrdiff_t pitch,

                             const uint8_t *flags)

{

    int     i, shift, sp1, sp2;

    const int32_t *src;

    int32_t *dst;

    int     tmp[16];

    int     t0, t1, t2, t3, t4;

    /* apply the InvHaar4 to all columns */

#define COMPENSATE(x) (x)

    src = in;

    dst = tmp;

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

        if (flags[i]) {

            /* pre-scaling */

            shift = !(i & 2);

            sp1 = src[0] << shift;

            sp2 = src[4] << shift;

            INV_HAAR4(   sp1,    sp2, src[8], src[12],

                      dst[0], dst[4], dst[8], dst[12],

                      t0, t1, t2, t3, t4);

        } else

            dst[0] = dst[4] = dst[8] = dst[12] = 0;

        src++;

        dst++;

    }

#undef  COMPENSATE

    /* apply the InvHaar8 to all rows */

#define COMPENSATE(x) (x)

    src = tmp;

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

        if (!src[0] && !src[1] && !src[2] && !src[3]) {

            memset(out, 0, 4 * sizeof(out[0]));

        } else {

            INV_HAAR4(src[0], src[1], src[2], src[3],

                      out[0], out[1], out[2], out[3],

                      t0, t1, t2, t3, t4);

        }

        src += 4;

        out += pitch;

    }

#undef  COMPENSATE

}


static int submit_packet(PerThreadContext *p, AVPacket *avpkt)

{

    FrameThreadContext *fctx = p->parent;

    PerThreadContext *prev_thread = fctx->prev_thread;

    const AVCodec *codec = p->avctx->codec;

    if (!avpkt->size && !(codec->capabilities & AV_CODEC_CAP_DELAY))

        return 0;

    pthread_mutex_lock(&p->mutex);

    release_delayed_buffers(p);

    if (prev_thread) {

        int err;

        if (prev_thread->state == STATE_SETTING_UP) {

            pthread_mutex_lock(&prev_thread->progress_mutex);

            while (prev_thread->state == STATE_SETTING_UP)

                pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);

            pthread_mutex_unlock(&prev_thread->progress_mutex);

        }

        err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);

        if (err) {

            pthread_mutex_unlock(&p->mutex);

            return err;

        }

    }

    av_packet_unref(&p->avpkt);

    av_packet_ref(&p->avpkt, avpkt);

    p->state = STATE_SETTING_UP;

    pthread_cond_signal(&p->input_cond);

    pthread_mutex_unlock(&p->mutex);

    /*

     * If the client doesn't have a thread-safe get_buffer(),

     * then decoding threads call back to the main thread,

     * and it calls back to the client here.

     */

    if (!p->avctx->thread_safe_callbacks && (

         p->avctx->get_format != avcodec_default_get_format ||

         p->avctx->get_buffer2 != avcodec_default_get_buffer2)) {

        while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {

            int call_done = 1;

            pthread_mutex_lock(&p->progress_mutex);

            while (p->state == STATE_SETTING_UP)

                pthread_cond_wait(&p->progress_cond, &p->progress_mutex);

            switch (p->state) {

            case STATE_GET_BUFFER:

                p->result = ff_get_buffer(p->avctx, p->requested_frame, p->requested_flags);

                break;

            case STATE_GET_FORMAT:

                p->result_format = ff_get_format(p->avctx, p->available_formats);

                break;

            default:

                call_done = 0;

                break;

            }

            if (call_done) {

                p->state  = STATE_SETTING_UP;

                pthread_cond_signal(&p->progress_cond);

            }

            pthread_mutex_unlock(&p->progress_mutex);

        }

    }

    fctx->prev_thread = p;

    fctx->next_decoding++;

    return 0;

}


static int ty_read_packet(AVFormatContext *s, AVPacket *pkt)

{

    TYDemuxContext *ty = s->priv_data;

    AVIOContext *pb = s->pb;

    TyRecHdr *rec;

    int64_t rec_size = 0;

    int ret = 0;

    if (avio_feof(pb))

        return AVERROR_EOF;

    while (ret <= 0) {

        if (ty->first_chunk || ty->cur_rec >= ty->num_recs) {

            if (get_chunk(s) < 0 || ty->num_recs == 0)

                return AVERROR_EOF;

        }

        rec = &ty->rec_hdrs[ty->cur_rec];

        rec_size = rec->rec_size;

        ty->cur_rec++;

        if (rec_size <= 0)

            continue;

        if (ty->cur_chunk_pos + rec->rec_size > CHUNK_SIZE)

            return AVERROR_INVALIDDATA;

        if (avio_feof(pb))

            return AVERROR_EOF;

        switch (rec->rec_type) {

        case VIDEO_ID:

            ret = demux_video(s, rec, pkt);

            break;

        case AUDIO_ID:

            ret = demux_audio(s, rec, pkt);

            break;

        default:

            ff_dlog(s, "Invalid record type 0x%02x\n", rec->rec_type);

        case 0x01:

        case 0x02:

        case 0x03: /* TiVo data services */

        case 0x05: /* unknown, but seen regularly */

            ty->cur_chunk_pos += rec->rec_size;

            break;

        }

    }

    return 0;

}


static int lag_decode_frame(AVCodecContext *avctx,

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

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    LagarithContext *l = avctx->priv_data;

    AVFrame *const p = &l->picture;

    uint8_t frametype = 0;

    uint32_t offset_gu = 0, offset_bv = 0, offset_ry = 9;

    int offs[4];

    uint8_t *srcs[4], *dst;

    int i, j, planes = 3;

    AVFrame *picture = data;

    if (p->data[0])

        avctx->release_buffer(avctx, p);

    p->reference = 0;

    p->key_frame = 1;

    frametype = buf[0];

    offset_gu = AV_RL32(buf + 1);

    offset_bv = AV_RL32(buf + 5);

    switch (frametype) {

    case FRAME_SOLID_RGBA:

        avctx->pix_fmt = PIX_FMT_RGB32;

        if (avctx->get_buffer(avctx, p) < 0) {

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

            return -1;

        }

        dst = p->data[0];

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

            for (i = 0; i < avctx->width; i++)

                AV_WN32(dst + i * 4, offset_gu);

            dst += p->linesize[0];

        }

        break;

    case FRAME_ARITH_RGBA:

        avctx->pix_fmt = PIX_FMT_RGB32;

        planes = 4;

        offset_ry += 4;

        offs[3] = AV_RL32(buf + 9);

    case FRAME_ARITH_RGB24:

        if (frametype == FRAME_ARITH_RGB24)

            avctx->pix_fmt = PIX_FMT_RGB24;

        if (avctx->get_buffer(avctx, p) < 0) {

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

            return -1;

        }

        offs[0] = offset_bv;

        offs[1] = offset_gu;

        offs[2] = offset_ry;

        if (!l->rgb_planes) {

            l->rgb_stride = FFALIGN(avctx->width, 16);

            l->rgb_planes = av_malloc(l->rgb_stride * avctx->height * planes + 16);

            if (!l->rgb_planes) {

                av_log(avctx, AV_LOG_ERROR, "cannot allocate temporary buffer\n");

                return AVERROR(ENOMEM);

            }

        }

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

            srcs[i] = l->rgb_planes + (i + 1) * l->rgb_stride * avctx->height - l->rgb_stride;

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

            lag_decode_arith_plane(l, srcs[i],

                                   avctx->width, avctx->height,

                                   -l->rgb_stride, buf + offs[i],

                                   buf_size);

        dst = p->data[0];

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

            srcs[i] = l->rgb_planes + i * l->rgb_stride * avctx->height;

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

            for (i = 0; i < avctx->width; i++) {

                uint8_t r, g, b, a;

                r = srcs[0][i];

                g = srcs[1][i];

                b = srcs[2][i];

                r += g;

                b += g;

                if (frametype == FRAME_ARITH_RGBA) {

                    a = srcs[3][i];

                    AV_WN32(dst + i * 4, MKBETAG(a, r, g, b));

                } else {

                    dst[i * 3 + 0] = r;

                    dst[i * 3 + 1] = g;

                    dst[i * 3 + 2] = b;

                }

            }

            dst += p->linesize[0];

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

                srcs[i] += l->rgb_stride;

        }

        break;

    case FRAME_ARITH_YV12:

        avctx->pix_fmt = PIX_FMT_YUV420P;

        if (avctx->get_buffer(avctx, p) < 0) {

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

            return -1;

        }

        lag_decode_arith_plane(l, p->data[0], avctx->width, avctx->height,

                               p->linesize[0], buf + offset_ry,

                               buf_size);

        lag_decode_arith_plane(l, p->data[2], avctx->width / 2,

                               avctx->height / 2, p->linesize[2],

                               buf + offset_gu, buf_size);

        lag_decode_arith_plane(l, p->data[1], avctx->width / 2,

                               avctx->height / 2, p->linesize[1],

                               buf + offset_bv, buf_size);

        break;

    default:

        av_log(avctx, AV_LOG_ERROR,

               "Unsupported Lagarith frame type: %#x\n", frametype);

        return -1;

    }

    *picture = *p;

    *data_size = sizeof(AVFrame);

    return buf_size;

}


static inline int check_for_slice(AVSContext *h) {

    GetBitContext *gb = &h->s.gb;

    int align;

    if(h->mbx)

        return 0;

    align = (-get_bits_count(gb)) & 7;

    /* check for stuffing byte */

    if(!align && (show_bits(gb,8) == 0x80))

        get_bits(gb,8);

    if((show_bits_long(gb,24+align) & 0xFFFFFF) == 0x000001) {

        skip_bits_long(gb,24+align);

        h->stc = get_bits(gb,8);

        decode_slice_header(h,gb);

        return 1;

    }

    return 0;

}


static int decode_display_orientation(H264Context *h)

{

    h->sei_display_orientation_present = !get_bits1(&h->gb);

    if (h->sei_display_orientation_present) {

        h->sei_hflip = get_bits1(&h->gb);     // hor_flip

        h->sei_vflip = get_bits1(&h->gb);     // ver_flip

        h->sei_anticlockwise_rotation = get_bits(&h->gb, 16);

        get_ue_golomb(&h->gb);  // display_orientation_repetition_period

        skip_bits1(&h->gb);     // display_orientation_extension_flag

    }

    return 0;

}


static int init_image(TiffContext *s)

{

    int i, ret;

    uint32_t *pal;

    switch (s->bpp * 10 + s->bppcount) {

    case 11:

        if (!s->palette_is_set) {

            s->avctx->pix_fmt = AV_PIX_FMT_MONOBLACK;

            break;

        }

    case 21:

    case 41:

    case 81:

        s->avctx->pix_fmt = AV_PIX_FMT_PAL8;

        break;

    case 243:

        s->avctx->pix_fmt = AV_PIX_FMT_RGB24;

        break;

    case 161:

        s->avctx->pix_fmt = s->le ? AV_PIX_FMT_GRAY16LE : AV_PIX_FMT_GRAY16BE;

        break;

    case 162:

        s->avctx->pix_fmt = AV_PIX_FMT_GRAY8A;

        break;

    case 324:

        s->avctx->pix_fmt = AV_PIX_FMT_RGBA;

        break;

    case 483:

        s->avctx->pix_fmt = s->le ? AV_PIX_FMT_RGB48LE : AV_PIX_FMT_RGB48BE;

        break;

    case 644:

        s->avctx->pix_fmt = s->le ? AV_PIX_FMT_RGBA64LE : AV_PIX_FMT_RGBA64BE;

        break;

    default:

        av_log(s->avctx, AV_LOG_ERROR,

               "This format is not supported (bpp=%d, bppcount=%d)\n",

               s->bpp, s->bppcount);

        return AVERROR_INVALIDDATA;

    }

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

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

            return ret;

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

    }

    if (s->picture.data[0])

        s->avctx->release_buffer(s->avctx, &s->picture);

    if ((ret = s->avctx->get_buffer(s->avctx, &s->picture)) < 0) {

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

        return ret;

    }

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

        if (s->palette_is_set) {

            memcpy(s->picture.data[1], s->palette, sizeof(s->palette));

        } else {

            /* make default grayscale pal */

            pal = (uint32_t *) s->picture.data[1];

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

                pal[i] = 0xFF << 24 | i * 255 / ((1<<s->bpp) - 1) * 0x010101;

        }

    }

    return 0;

}


static int handle_sigp(S390CPU *cpu, struct kvm_run *run, uint8_t ipa1)

{

    CPUS390XState *env = &cpu->env;

    const uint8_t r1 = ipa1 >> 4;

    const uint8_t r3 = ipa1 & 0x0f;

    int ret;

    uint8_t order;

    uint64_t *status_reg;

    uint64_t param;

    S390CPU *dst_cpu = NULL;

    cpu_synchronize_state(CPU(cpu));

    /* get order code */

    order = decode_basedisp_rs(env, run->s390_sieic.ipb, NULL)

        & SIGP_ORDER_MASK;

    status_reg = &env->regs[r1];

    param = (r1 % 2) ? env->regs[r1] : env->regs[r1 + 1];

    if (qemu_mutex_trylock(&qemu_sigp_mutex)) {

        ret = SIGP_CC_BUSY;

        goto out;

    }

    switch (order) {

    case SIGP_SET_ARCH:

        ret = sigp_set_architecture(cpu, param, status_reg);

        break;

    default:

        /* all other sigp orders target a single vcpu */

        dst_cpu = s390_cpu_addr2state(env->regs[r3]);

        ret = handle_sigp_single_dst(dst_cpu, order, param, status_reg);

    }

    trace_kvm_sigp_finished(order, CPU(cpu)->cpu_index,

                            dst_cpu ? CPU(dst_cpu)->cpu_index : -1, ret);

    if (ret >= 0) {

        setcc(cpu, ret);

        return 0;

    }

    return ret;

}


static int h261_decode_gob_header(H261Context *h)

{

    unsigned int val;

    MpegEncContext *const s = &h->s;

    if (!h->gob_start_code_skipped) {

        /* Check for GOB Start Code */

        val = show_bits(&s->gb, 15);

        if (val)

            return -1;

        /* We have a GBSC */

        skip_bits(&s->gb, 16);

    }

    h->gob_start_code_skipped = 0;

    h->gob_number = get_bits(&s->gb, 4); /* GN */

    s->qscale     = get_bits(&s->gb, 5); /* GQUANT */

    /* Check if gob_number is valid */

    if (s->mb_height == 18) { // CIF

        if ((h->gob_number <= 0) || (h->gob_number > 12))

            return -1;

    } else { // QCIF

        if ((h->gob_number != 1) && (h->gob_number != 3) &&

            (h->gob_number != 5))

            return -1;

    }

    /* GEI */

    while (get_bits1(&s->gb) != 0)

        skip_bits(&s->gb, 8);

    if (s->qscale == 0) {

        av_log(s->avctx, AV_LOG_ERROR, "qscale has forbidden 0 value\n");

        if (s->avctx->err_recognition & (AV_EF_BITSTREAM | AV_EF_COMPLIANT))

            return -1;

    }

    /* For the first transmitted macroblock in a GOB, MBA is the absolute

     * address. For subsequent macroblocks, MBA is the difference between

     * the absolute addresses of the macroblock and the last transmitted

     * macroblock. */

    h->current_mba = 0;

    h->mba_diff    = 0;

    return 0;

}


static int has_decode_delay_been_guessed(AVStream *st)

{

    return st->codec->codec_id != CODEC_ID_H264 ||

        st->codec_info_nb_frames >= 6 + st->codec->has_b_frames;

}


static int64_t scene_sad8(FrameRateContext *s, uint8_t *p1, int p1_linesize, uint8_t* p2, int p2_linesize, int height)

{

    int64_t sad;

    int x, y;

    for (sad = y = 0; y < height; y += 8) {

        for (x = 0; x < p1_linesize; x += 8) {

            sad += s->sad(p1 + y * p1_linesize + x,

                          p1_linesize,

                          p2 + y * p2_linesize + x,

                          p2_linesize);

        }

    }

    emms_c();

    return sad;

}


e1000_link_up(E1000State *s)
{
    s->mac_reg[STATUS] |= E1000_STATUS_LU;
    s->phy_reg[PHY_STATUS] |= MII_SR_LINK_STATUS;
}


static void omap_gp_timer_clk_setup(struct omap_gp_timer_s *timer)

{

    omap_clk_adduser(timer->clk,

                    qemu_allocate_irqs(omap_gp_timer_clk_update, timer, 1)[0]);

    timer->rate = omap_clk_getrate(timer->clk);

}


Object *user_creatable_add_type(const char *type, const char *id,

                                const QDict *qdict,

                                Visitor *v, Error **errp)

{

    Object *obj;

    ObjectClass *klass;

    const QDictEntry *e;

    Error *local_err = NULL;

    klass = object_class_by_name(type);

    if (!klass) {

        error_setg(errp, "invalid object type: %s", type);

        return NULL;

    }

    if (!object_class_dynamic_cast(klass, TYPE_USER_CREATABLE)) {

        error_setg(errp, "object type '%s' isn't supported by object-add",

                   type);

        return NULL;

    }

    if (object_class_is_abstract(klass)) {

        error_setg(errp, "object type '%s' is abstract", type);

        return NULL;

    }

    obj = object_new(type);

    if (qdict) {

        for (e = qdict_first(qdict); e; e = qdict_next(qdict, e)) {

            object_property_set(obj, v, e->key, &local_err);

            if (local_err) {

                goto out;

            }

        }

    }

    object_property_add_child(object_get_objects_root(),

                              id, obj, &local_err);

    if (local_err) {

        goto out;

    }

    user_creatable_complete(obj, &local_err);

    if (local_err) {

        object_property_del(object_get_objects_root(),

                            id, &error_abort);

        goto out;

    }

out:

    if (local_err) {

        error_propagate(errp, local_err);

        object_unref(obj);

        return NULL;

    }

    return obj;

}


static int get_slice_offset(AVCodecContext *avctx, const uint8_t *buf, int n)

{

    if(avctx->slice_count) return avctx->slice_offset[n];

    else                   return AV_RL32(buf + n*8 - 4) == 1 ? AV_RL32(buf + n*8) :  AV_RB32(buf + n*8);

}


static int tls_read(URLContext *h, uint8_t *buf, int size)

{

    TLSContext *c = h->priv_data;

    size_t processed = 0;

    int ret = SSLRead(c->ssl_context, buf, size, &processed);

    ret = map_ssl_error(ret, processed);

    if (ret > 0)

        return ret;

    if (ret == 0)

        return AVERROR_EOF;

    return print_tls_error(h, ret);

}


static void test_io_channel_tls(const void *opaque)

{

    struct QIOChannelTLSTestData *data =

        (struct QIOChannelTLSTestData *)opaque;

    QCryptoTLSCreds *clientCreds;

    QCryptoTLSCreds *serverCreds;

    QIOChannelTLS *clientChanTLS;

    QIOChannelTLS *serverChanTLS;

    QIOChannelSocket *clientChanSock;

    QIOChannelSocket *serverChanSock;

    qemu_acl *acl;

    const char * const *wildcards;

    int channel[2];

    struct QIOChannelTLSHandshakeData clientHandshake = { false, false };

    struct QIOChannelTLSHandshakeData serverHandshake = { false, false };

    Error *err = NULL;

    QIOChannelTest *test;

    GMainContext *mainloop;

    /* We'll use this for our fake client-server connection */

    g_assert(socketpair(AF_UNIX, SOCK_STREAM, 0, channel) == 0);

#define CLIENT_CERT_DIR "tests/test-io-channel-tls-client/"

#define SERVER_CERT_DIR "tests/test-io-channel-tls-server/"

    mkdir(CLIENT_CERT_DIR, 0700);

    mkdir(SERVER_CERT_DIR, 0700);

    unlink(SERVER_CERT_DIR QCRYPTO_TLS_CREDS_X509_CA_CERT);

    unlink(SERVER_CERT_DIR QCRYPTO_TLS_CREDS_X509_SERVER_CERT);

    unlink(SERVER_CERT_DIR QCRYPTO_TLS_CREDS_X509_SERVER_KEY);

    unlink(CLIENT_CERT_DIR QCRYPTO_TLS_CREDS_X509_CA_CERT);

    unlink(CLIENT_CERT_DIR QCRYPTO_TLS_CREDS_X509_CLIENT_CERT);

    unlink(CLIENT_CERT_DIR QCRYPTO_TLS_CREDS_X509_CLIENT_KEY);

    g_assert(link(data->servercacrt,

                  SERVER_CERT_DIR QCRYPTO_TLS_CREDS_X509_CA_CERT) == 0);

    g_assert(link(data->servercrt,

                  SERVER_CERT_DIR QCRYPTO_TLS_CREDS_X509_SERVER_CERT) == 0);

    g_assert(link(KEYFILE,

                  SERVER_CERT_DIR QCRYPTO_TLS_CREDS_X509_SERVER_KEY) == 0);

    g_assert(link(data->clientcacrt,

                  CLIENT_CERT_DIR QCRYPTO_TLS_CREDS_X509_CA_CERT) == 0);

    g_assert(link(data->clientcrt,

                  CLIENT_CERT_DIR QCRYPTO_TLS_CREDS_X509_CLIENT_CERT) == 0);

    g_assert(link(KEYFILE,

                  CLIENT_CERT_DIR QCRYPTO_TLS_CREDS_X509_CLIENT_KEY) == 0);

    clientCreds = test_tls_creds_create(

        QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT,

        CLIENT_CERT_DIR,

        &err);

    g_assert(clientCreds != NULL);

    serverCreds = test_tls_creds_create(

        QCRYPTO_TLS_CREDS_ENDPOINT_SERVER,

        SERVER_CERT_DIR,

        &err);

    g_assert(serverCreds != NULL);

    acl = qemu_acl_init("channeltlsacl");

    qemu_acl_reset(acl);

    wildcards = data->wildcards;

    while (wildcards && *wildcards) {

        qemu_acl_append(acl, 0, *wildcards);

        wildcards++;

    }

    clientChanSock = qio_channel_socket_new_fd(

        channel[0], &err);

    g_assert(clientChanSock != NULL);

    serverChanSock = qio_channel_socket_new_fd(

        channel[1], &err);

    g_assert(serverChanSock != NULL);

    /*

     * We have an evil loop to do the handshake in a single

     * thread, so we need these non-blocking to avoid deadlock

     * of ourselves

     */

    qio_channel_set_blocking(QIO_CHANNEL(clientChanSock), false, NULL);

    qio_channel_set_blocking(QIO_CHANNEL(serverChanSock), false, NULL);

    /* Now the real part of the test, setup the sessions */

    clientChanTLS = qio_channel_tls_new_client(

        QIO_CHANNEL(clientChanSock), clientCreds,

        data->hostname, &err);

    g_assert(clientChanTLS != NULL);

    serverChanTLS = qio_channel_tls_new_server(

        QIO_CHANNEL(serverChanSock), serverCreds,

        "channeltlsacl", &err);

    g_assert(serverChanTLS != NULL);

    qio_channel_tls_handshake(clientChanTLS,

                              test_tls_handshake_done,

                              &clientHandshake,

                              NULL);

    qio_channel_tls_handshake(serverChanTLS,

                              test_tls_handshake_done,

                              &serverHandshake,

                              NULL);

    /*

     * Finally we loop around & around doing handshake on each

     * session until we get an error, or the handshake completes.

     * This relies on the socketpair being nonblocking to avoid

     * deadlocking ourselves upon handshake

     */

    mainloop = g_main_context_default();

    do {

        g_main_context_iteration(mainloop, TRUE);

    } while (!clientHandshake.finished &&

             !serverHandshake.finished);

    g_assert(clientHandshake.failed == data->expectClientFail);

    g_assert(serverHandshake.failed == data->expectServerFail);

    test = qio_channel_test_new();

    qio_channel_test_run_threads(test, false,

                                 QIO_CHANNEL(clientChanTLS),

                                 QIO_CHANNEL(serverChanTLS));

    qio_channel_test_validate(test);

    test = qio_channel_test_new();

    qio_channel_test_run_threads(test, true,

                                 QIO_CHANNEL(clientChanTLS),

                                 QIO_CHANNEL(serverChanTLS));

    qio_channel_test_validate(test);

    unlink(SERVER_CERT_DIR QCRYPTO_TLS_CREDS_X509_CA_CERT);

    unlink(SERVER_CERT_DIR QCRYPTO_TLS_CREDS_X509_SERVER_CERT);

    unlink(SERVER_CERT_DIR QCRYPTO_TLS_CREDS_X509_SERVER_KEY);

    unlink(CLIENT_CERT_DIR QCRYPTO_TLS_CREDS_X509_CA_CERT);

    unlink(CLIENT_CERT_DIR QCRYPTO_TLS_CREDS_X509_CLIENT_CERT);

    unlink(CLIENT_CERT_DIR QCRYPTO_TLS_CREDS_X509_CLIENT_KEY);

    rmdir(CLIENT_CERT_DIR);

    rmdir(SERVER_CERT_DIR);

    object_unparent(OBJECT(serverCreds));

    object_unparent(OBJECT(clientCreds));

    object_unref(OBJECT(serverChanTLS));

    object_unref(OBJECT(clientChanTLS));

    object_unref(OBJECT(serverChanSock));

    object_unref(OBJECT(clientChanSock));

    close(channel[0]);

    close(channel[1]);

}


int ff_wma_run_level_decode(AVCodecContext* avctx, GetBitContext* gb,

                            VLC *vlc,

                            const uint16_t *level_table, const uint16_t *run_table,

                            int version, WMACoef *ptr, int offset,

                            int num_coefs, int block_len, int frame_len_bits,

                            int coef_nb_bits)

{

    int code, run, level, sign;

    WMACoef* eptr = ptr + num_coefs;

    ptr += offset;

    for(;;) {

        code = get_vlc2(gb, vlc->table, VLCBITS, VLCMAX);

        if (code < 0)

            return -1;

        if (code == 1) {

            /* EOB */

            break;

        } else if (code == 0) {

            /* escape */

            if (!version) {

                level = get_bits(gb, coef_nb_bits);

                /* NOTE: this is rather suboptimal. reading

                   block_len_bits would be better */

                run = get_bits(gb, frame_len_bits);

            } else {

                level = ff_wma_get_large_val(gb);

                /** escape decode */

                if (get_bits1(gb)) {

                    if (get_bits1(gb)) {

                        if (get_bits1(gb)) {

                            av_log(avctx,AV_LOG_ERROR,

                                "broken escape sequence\n");

                            return -1;

                        } else

                            run = get_bits(gb, frame_len_bits) + 4;

                    } else

                        run = get_bits(gb, 2) + 1;

                } else

                     run = 0;

            }

        } else {

            /* normal code */

            run = run_table[code];

            level = level_table[code];

        }

        sign = get_bits1(gb);

        if (!sign)

             level = -level;

        ptr += run;

        if (ptr >= eptr)

        {

            av_log(NULL, AV_LOG_ERROR, "overflow in spectral RLE, ignoring\n");

            break;

        }

        *ptr++ = level;

        /* NOTE: EOB can be omitted */

        if (ptr >= eptr)

            break;

    }

    return 0;

}


static int qemu_rbd_snap_remove(BlockDriverState *bs,

                                const char *snapshot_name)

{

    BDRVRBDState *s = bs->opaque;

    int r;

    r = rbd_snap_remove(s->image, snapshot_name);

    return r;

}


static void blend_frames_c(BLEND_FUNC_PARAMS)

{

    int line, pixel;

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

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

            // integer version of (src1 * factor1) + (src2 * factor2) + 0.5

            // 0.5 is for rounding

            // 128 is the integer representation of 0.5 << 8

            dst[pixel] = ((src1[pixel] * factor1) + (src2[pixel] * factor2) + 128) >> 8;

        }

        src1 += src1_linesize;

        src2 += src2_linesize;

        dst  += dst_linesize;

    }

}


int tcp_start_incoming_migration(const char *host_port)

{

    struct sockaddr_in addr;

    int val;

    int s;

    if (parse_host_port(&addr, host_port) < 0) {

        fprintf(stderr, "invalid host/port combination: %s\n", host_port);

        return -EINVAL;

    }

    s = socket(PF_INET, SOCK_STREAM, 0);

    if (s == -1)

        return -socket_error();

    val = 1;

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

    if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) == -1)

        goto err;

    if (listen(s, 1) == -1)

        goto err;

    qemu_set_fd_handler2(s, NULL, tcp_accept_incoming_migration, NULL,

                         (void *)(unsigned long)s);

    return 0;

err:

    close(s);

    return -socket_error();

}


opts_type_size(Visitor *v, uint64_t *obj, const char *name, Error **errp)

{

    OptsVisitor *ov = DO_UPCAST(OptsVisitor, visitor, v);

    const QemuOpt *opt;

    int64_t val;

    char *endptr;

    opt = lookup_scalar(ov, name, errp);

    if (!opt) {

        return;

    }

    val = strtosz_suffix(opt->str ? opt->str : "", &endptr,

                         STRTOSZ_DEFSUFFIX_B);

    if (val != -1 && *endptr == '\0') {

        *obj = val;

        processed(ov, name);

        return;

    }

    error_set(errp, QERR_INVALID_PARAMETER_VALUE, opt->name,

              "a size value representible as a non-negative int64");

}