int qemu_timedate_diff(struct tm *tm)

{

    time_t seconds;

    if (rtc_date_offset == -1)

        if (rtc_utc)

            seconds = mktimegm(tm);

        else {

            struct tm tmp = *tm;

            tmp.tm_isdst = -1; /* use timezone to figure it out */

            seconds = mktime(&tmp);

	}

    else

        seconds = mktimegm(tm) + rtc_date_offset;

    return seconds - time(NULL);

}


VTDAddressSpace *vtd_find_add_as(IntelIOMMUState *s, PCIBus *bus, int devfn)

{

    uintptr_t key = (uintptr_t)bus;

    VTDBus *vtd_bus = g_hash_table_lookup(s->vtd_as_by_busptr, &key);

    VTDAddressSpace *vtd_dev_as;

    char name[128];

    if (!vtd_bus) {

        uintptr_t *new_key = g_malloc(sizeof(*new_key));

        *new_key = (uintptr_t)bus;

        /* No corresponding free() */

        vtd_bus = g_malloc0(sizeof(VTDBus) + sizeof(VTDAddressSpace *) * \

                            X86_IOMMU_PCI_DEVFN_MAX);

        vtd_bus->bus = bus;

        g_hash_table_insert(s->vtd_as_by_busptr, new_key, vtd_bus);

    }

    vtd_dev_as = vtd_bus->dev_as[devfn];

    if (!vtd_dev_as) {

        snprintf(name, sizeof(name), "intel_iommu_devfn_%d", devfn);

        vtd_bus->dev_as[devfn] = vtd_dev_as = g_malloc0(sizeof(VTDAddressSpace));

        vtd_dev_as->bus = bus;

        vtd_dev_as->devfn = (uint8_t)devfn;

        vtd_dev_as->iommu_state = s;

        vtd_dev_as->context_cache_entry.context_cache_gen = 0;

        memory_region_init_iommu(&vtd_dev_as->iommu, OBJECT(s),

                                 &s->iommu_ops, "intel_iommu", UINT64_MAX);

        memory_region_init_io(&vtd_dev_as->iommu_ir, OBJECT(s),

                              &vtd_mem_ir_ops, s, "intel_iommu_ir",

                              VTD_INTERRUPT_ADDR_SIZE);

        memory_region_add_subregion(&vtd_dev_as->iommu, VTD_INTERRUPT_ADDR_FIRST,

                                    &vtd_dev_as->iommu_ir);

        address_space_init(&vtd_dev_as->as,

                           &vtd_dev_as->iommu, name);

    }

    return vtd_dev_as;

}


void qemu_announce_self(void)

{

	static QEMUTimer *timer;

	timer = qemu_new_timer(rt_clock, qemu_announce_self_once, &timer);

	qemu_announce_self_once(&timer);

}


static int mpegts_probe(AVProbeData *p)

{

    const int size = p->buf_size;

    int maxscore = 0;

    int sumscore = 0;

    int i;

    int check_count = size / TS_FEC_PACKET_SIZE;

#define CHECK_COUNT 10

#define CHECK_BLOCK 100

    if (check_count < CHECK_COUNT)

        return 0;

    for (i = 0; i<check_count; i+=CHECK_BLOCK) {

        int left = FFMIN(check_count - i, CHECK_BLOCK);

        int score      = analyze(p->buf + TS_PACKET_SIZE     *i, TS_PACKET_SIZE     *left, TS_PACKET_SIZE     , NULL, 1);

        int dvhs_score = analyze(p->buf + TS_DVHS_PACKET_SIZE*i, TS_DVHS_PACKET_SIZE*left, TS_DVHS_PACKET_SIZE, NULL, 1);

        int fec_score  = analyze(p->buf + TS_FEC_PACKET_SIZE *i, TS_FEC_PACKET_SIZE *left, TS_FEC_PACKET_SIZE , NULL, 1);

        score = FFMAX3(score, dvhs_score, fec_score);

        sumscore += score;

        maxscore = FFMAX(maxscore, score);

    }

    sumscore = sumscore * CHECK_COUNT / check_count;

    maxscore = maxscore * CHECK_COUNT / CHECK_BLOCK;

    av_dlog(0, "TS score: %d %d\n", sumscore, maxscore);

    if      (sumscore > 6) return AVPROBE_SCORE_MAX   + sumscore - CHECK_COUNT;

    else if (maxscore > 6) return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT;

    else

        return 0;

}


static void do_commit(int argc, const char **argv)

{

    int i;

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

        if (bs_table[i])

            bdrv_commit(bs_table[i]);

    }

}


static int ppc_hash32_pp_check(int key, int pp, int nx)

{

    int access;

    /* Compute access rights */

    access = 0;

    if (key == 0) {

        switch (pp) {

        case 0x0:

        case 0x1:

        case 0x2:

            access |= PAGE_WRITE;

            /* No break here */

        case 0x3:

            access |= PAGE_READ;

            break;

        }

    } else {

        switch (pp) {

        case 0x0:

            access = 0;

            break;

        case 0x1:

        case 0x3:

            access = PAGE_READ;

            break;

        case 0x2:

            access = PAGE_READ | PAGE_WRITE;

            break;

        }

    }

    if (nx == 0) {

        access |= PAGE_EXEC;

    }

    return access;

}


static void tpm_tis_mmio_write_intern(void *opaque, hwaddr addr,

                                      uint64_t val, unsigned size,

                                      bool hw_access)

{

    TPMState *s = opaque;

    TPMTISEmuState *tis = &s->s.tis;

    uint16_t off = addr & 0xffc;

    uint8_t shift = (addr & 0x3) * 8;

    uint8_t locty = tpm_tis_locality_from_addr(addr);

    uint8_t active_locty, l;

    int c, set_new_locty = 1;

    uint16_t len;

    uint32_t mask = (size == 1) ? 0xff : ((size == 2) ? 0xffff : ~0);

    DPRINTF("tpm_tis: write.%u(%08x) = %08x\n", size, (int)addr, (uint32_t)val);

    if (locty == 4 && !hw_access) {

        DPRINTF("tpm_tis: Access to locality 4 only allowed from hardware\n");

        return;

    }

    if (tpm_backend_had_startup_error(s->be_driver)) {

        return;

    }

    val &= mask;

    if (shift) {

        val <<= shift;

        mask <<= shift;

    }

    mask ^= 0xffffffff;

    switch (off) {

    case TPM_TIS_REG_ACCESS:

        if ((val & TPM_TIS_ACCESS_SEIZE)) {

            val &= ~(TPM_TIS_ACCESS_REQUEST_USE |

                     TPM_TIS_ACCESS_ACTIVE_LOCALITY);

        }

        active_locty = tis->active_locty;

        if ((val & TPM_TIS_ACCESS_ACTIVE_LOCALITY)) {

            /* give up locality if currently owned */

            if (tis->active_locty == locty) {

                DPRINTF("tpm_tis: Releasing locality %d\n", locty);

                uint8_t newlocty = TPM_TIS_NO_LOCALITY;

                /* anybody wants the locality ? */

                for (c = TPM_TIS_NUM_LOCALITIES - 1; c >= 0; c--) {

                    if ((tis->loc[c].access & TPM_TIS_ACCESS_REQUEST_USE)) {

                        DPRINTF("tpm_tis: Locality %d requests use.\n", c);

                        newlocty = c;

                        break;

                    }

                }

                DPRINTF("tpm_tis: TPM_TIS_ACCESS_ACTIVE_LOCALITY: "

                        "Next active locality: %d\n",

                        newlocty);

                if (TPM_TIS_IS_VALID_LOCTY(newlocty)) {

                    set_new_locty = 0;

                    tpm_tis_prep_abort(s, locty, newlocty);

                } else {

                    active_locty = TPM_TIS_NO_LOCALITY;

                }

            } else {

                /* not currently the owner; clear a pending request */

                tis->loc[locty].access &= ~TPM_TIS_ACCESS_REQUEST_USE;

            }

        }

        if ((val & TPM_TIS_ACCESS_BEEN_SEIZED)) {

            tis->loc[locty].access &= ~TPM_TIS_ACCESS_BEEN_SEIZED;

        }

        if ((val & TPM_TIS_ACCESS_SEIZE)) {

            /*

             * allow seize if a locality is active and the requesting

             * locality is higher than the one that's active

             * OR

             * allow seize for requesting locality if no locality is

             * active

             */

            while ((TPM_TIS_IS_VALID_LOCTY(tis->active_locty) &&

                    locty > tis->active_locty) ||

                    !TPM_TIS_IS_VALID_LOCTY(tis->active_locty)) {

                bool higher_seize = FALSE;

                /* already a pending SEIZE ? */

                if ((tis->loc[locty].access & TPM_TIS_ACCESS_SEIZE)) {

                    break;

                }

                /* check for ongoing seize by a higher locality */

                for (l = locty + 1; l < TPM_TIS_NUM_LOCALITIES; l++) {

                    if ((tis->loc[l].access & TPM_TIS_ACCESS_SEIZE)) {

                        higher_seize = TRUE;

                        break;

                    }

                }

                if (higher_seize) {

                    break;

                }

                /* cancel any seize by a lower locality */

                for (l = 0; l < locty - 1; l++) {

                    tis->loc[l].access &= ~TPM_TIS_ACCESS_SEIZE;

                }

                tis->loc[locty].access |= TPM_TIS_ACCESS_SEIZE;

                DPRINTF("tpm_tis: TPM_TIS_ACCESS_SEIZE: "

                        "Locality %d seized from locality %d\n",

                        locty, tis->active_locty);

                DPRINTF("tpm_tis: TPM_TIS_ACCESS_SEIZE: Initiating abort.\n");

                set_new_locty = 0;

                tpm_tis_prep_abort(s, tis->active_locty, locty);

                break;

            }

        }

        if ((val & TPM_TIS_ACCESS_REQUEST_USE)) {

            if (tis->active_locty != locty) {

                if (TPM_TIS_IS_VALID_LOCTY(tis->active_locty)) {

                    tis->loc[locty].access |= TPM_TIS_ACCESS_REQUEST_USE;

                } else {

                    /* no locality active -> make this one active now */

                    active_locty = locty;

                }

            }

        }

        if (set_new_locty) {

            tpm_tis_new_active_locality(s, active_locty);

        }

        break;

    case TPM_TIS_REG_INT_ENABLE:

        if (tis->active_locty != locty) {

            break;

        }

        tis->loc[locty].inte &= mask;

        tis->loc[locty].inte |= (val & (TPM_TIS_INT_ENABLED |

                                        TPM_TIS_INT_POLARITY_MASK |

                                        TPM_TIS_INTERRUPTS_SUPPORTED));

        break;

    case TPM_TIS_REG_INT_VECTOR:

        /* hard wired -- ignore */

        break;

    case TPM_TIS_REG_INT_STATUS:

        if (tis->active_locty != locty) {

            break;

        }

        /* clearing of interrupt flags */

        if (((val & TPM_TIS_INTERRUPTS_SUPPORTED)) &&

            (tis->loc[locty].ints & TPM_TIS_INTERRUPTS_SUPPORTED)) {

            tis->loc[locty].ints &= ~val;

            if (tis->loc[locty].ints == 0) {

                qemu_irq_lower(tis->irq);

                DPRINTF("tpm_tis: Lowering IRQ\n");

            }

        }

        tis->loc[locty].ints &= ~(val & TPM_TIS_INTERRUPTS_SUPPORTED);

        break;

    case TPM_TIS_REG_STS:

        if (tis->active_locty != locty) {

            break;

        }

        val &= (TPM_TIS_STS_COMMAND_READY | TPM_TIS_STS_TPM_GO |

                TPM_TIS_STS_RESPONSE_RETRY);

        if (val == TPM_TIS_STS_COMMAND_READY) {

            switch (tis->loc[locty].state) {

            case TPM_TIS_STATE_READY:

                tis->loc[locty].w_offset = 0;

                tis->loc[locty].r_offset = 0;

            break;

            case TPM_TIS_STATE_IDLE:

                tis->loc[locty].sts = TPM_TIS_STS_COMMAND_READY;

                tis->loc[locty].state = TPM_TIS_STATE_READY;

                tpm_tis_raise_irq(s, locty, TPM_TIS_INT_COMMAND_READY);

            break;

            case TPM_TIS_STATE_EXECUTION:

            case TPM_TIS_STATE_RECEPTION:

                /* abort currently running command */

                DPRINTF("tpm_tis: %s: Initiating abort.\n",

                        __func__);

                tpm_tis_prep_abort(s, locty, locty);

            break;

            case TPM_TIS_STATE_COMPLETION:

                tis->loc[locty].w_offset = 0;

                tis->loc[locty].r_offset = 0;

                /* shortcut to ready state with C/R set */

                tis->loc[locty].state = TPM_TIS_STATE_READY;

                if (!(tis->loc[locty].sts & TPM_TIS_STS_COMMAND_READY)) {

                    tis->loc[locty].sts   = TPM_TIS_STS_COMMAND_READY;

                    tpm_tis_raise_irq(s, locty, TPM_TIS_INT_COMMAND_READY);

                }

                tis->loc[locty].sts &= ~(TPM_TIS_STS_DATA_AVAILABLE);

            break;

            }

        } else if (val == TPM_TIS_STS_TPM_GO) {

            switch (tis->loc[locty].state) {

            case TPM_TIS_STATE_RECEPTION:

                if ((tis->loc[locty].sts & TPM_TIS_STS_EXPECT) == 0) {

                    tpm_tis_tpm_send(s, locty);

                }

                break;

            default:

                /* ignore */

                break;

            }

        } else if (val == TPM_TIS_STS_RESPONSE_RETRY) {

            switch (tis->loc[locty].state) {

            case TPM_TIS_STATE_COMPLETION:

                tis->loc[locty].r_offset = 0;

                tis->loc[locty].sts = TPM_TIS_STS_VALID |

                                      TPM_TIS_STS_DATA_AVAILABLE;

                break;

            default:

                /* ignore */

                break;

            }

        }

        break;

    case TPM_TIS_REG_DATA_FIFO:

    case TPM_TIS_REG_DATA_XFIFO ... TPM_TIS_REG_DATA_XFIFO_END:

        /* data fifo */

        if (tis->active_locty != locty) {

            break;

        }

        if (tis->loc[locty].state == TPM_TIS_STATE_IDLE ||

            tis->loc[locty].state == TPM_TIS_STATE_EXECUTION ||

            tis->loc[locty].state == TPM_TIS_STATE_COMPLETION) {

            /* drop the byte */

        } else {

            DPRINTF("tpm_tis: Data to send to TPM: %08x (size=%d)\n",

                    val, size);

            if (tis->loc[locty].state == TPM_TIS_STATE_READY) {

                tis->loc[locty].state = TPM_TIS_STATE_RECEPTION;

                tis->loc[locty].sts = TPM_TIS_STS_EXPECT | TPM_TIS_STS_VALID;

            }

            val >>= shift;

            if (size > 4 - (addr & 0x3)) {

                /* prevent access beyond FIFO */

                size = 4 - (addr & 0x3);

            }

            while ((tis->loc[locty].sts & TPM_TIS_STS_EXPECT) && size > 0) {

                if (tis->loc[locty].w_offset < tis->loc[locty].w_buffer.size) {

                    tis->loc[locty].w_buffer.

                        buffer[tis->loc[locty].w_offset++] = (uint8_t)val;

                    val >>= 8;

                    size--;

                } else {

                    tis->loc[locty].sts = TPM_TIS_STS_VALID;

                }

            }

            /* check for complete packet */

            if (tis->loc[locty].w_offset > 5 &&

                (tis->loc[locty].sts & TPM_TIS_STS_EXPECT)) {

                /* we have a packet length - see if we have all of it */

#ifdef RAISE_STS_IRQ

                bool needIrq = !(tis->loc[locty].sts & TPM_TIS_STS_VALID);

#endif

                len = tpm_tis_get_size_from_buffer(&tis->loc[locty].w_buffer);

                if (len > tis->loc[locty].w_offset) {

                    tis->loc[locty].sts = TPM_TIS_STS_EXPECT |

                                          TPM_TIS_STS_VALID;

                } else {

                    /* packet complete */

                    tis->loc[locty].sts = TPM_TIS_STS_VALID;

                }

#ifdef RAISE_STS_IRQ

                if (needIrq) {

                    tpm_tis_raise_irq(s, locty, TPM_TIS_INT_STS_VALID);

                }

#endif

            }

        }

        break;

    }

}


int smbios_entry_add(const char *t)

{

    char buf[1024];

    if (get_param_value(buf, sizeof(buf), "file", t)) {

        struct smbios_structure_header *header;

        struct smbios_table *table;

        int size = get_image_size(buf);

        if (size < sizeof(struct smbios_structure_header)) {

            fprintf(stderr, "Cannot read smbios file %s", buf);

            exit(1);

        }

        if (!smbios_entries) {

            smbios_entries_len = sizeof(uint16_t);

            smbios_entries = qemu_mallocz(smbios_entries_len);

        }

        smbios_entries = qemu_realloc(smbios_entries, smbios_entries_len +

                                                      sizeof(*table) + size);

        table = (struct smbios_table *)(smbios_entries + smbios_entries_len);

        table->header.type = SMBIOS_TABLE_ENTRY;

        table->header.length = cpu_to_le16(sizeof(*table) + size);

        if (load_image(buf, table->data) != size) {

            fprintf(stderr, "Failed to load smbios file %s", buf);

            exit(1);

        }

        header = (struct smbios_structure_header *)(table->data);

        smbios_check_collision(header->type, SMBIOS_TABLE_ENTRY);

        smbios_entries_len += sizeof(*table) + size;

        (*(uint16_t *)smbios_entries) =

                cpu_to_le16(le16_to_cpu(*(uint16_t *)smbios_entries) + 1);

        return 0;

    }

    if (get_param_value(buf, sizeof(buf), "type", t)) {

        unsigned long type = strtoul(buf, NULL, 0);

        switch (type) {

        case 0:

            smbios_build_type_0_fields(t);

            return 0;

        case 1:

            smbios_build_type_1_fields(t);

            return 0;

        default:

            fprintf(stderr, "Don't know how to build fields for SMBIOS type "

                    "%ld\n", type);

            exit(1);

        }

    }

    fprintf(stderr, "smbios: must specify type= or file=\n");

    return -1;

}


void do_mouse_set(Monitor *mon, const QDict *qdict)

{

    QemuInputHandlerState *s;

    int index = qdict_get_int(qdict, "index");

    int found = 0;

    QTAILQ_FOREACH(s, &handlers, node) {

        if (s->id == index) {

            found = 1;

            qemu_input_handler_activate(s);

            break;

        }

    }

    if (!found) {

        monitor_printf(mon, "Mouse at given index not found\n");

    }

    qemu_input_check_mode_change();

}


static bool msix_is_masked(PCIDevice *dev, int vector)

{

    return msix_vector_masked(dev, vector, dev->msix_function_masked);

}


static int acpi_checksum(const uint8_t *data, int len)

{

    int sum, i;

    sum = 0;

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

        sum += data[i];

    return (-sum) & 0xff;

}


static inline void load_seg_cache_raw_dt(SegmentCache *sc, uint32_t e1, uint32_t e2)

{

    sc->base = get_seg_base(e1, e2);

    sc->limit = get_seg_limit(e1, e2);

    sc->flags = e2;

}


static inline int mpeg4_decode_block(MpegEncContext * s, DCTELEM * block,

                              int n, int coded, int intra, int rvlc)

{

    int level, i, last, run;

    int dc_pred_dir;

    RLTable * rl;

    RL_VLC_ELEM * rl_vlc;

    const uint8_t * scan_table;

    int qmul, qadd;

    //Note intra & rvlc should be optimized away if this is inlined

    if(intra) {

      if(s->qscale < s->intra_dc_threshold){

        /* DC coef */

        if(s->partitioned_frame){

            level = s->dc_val[0][ s->block_index[n] ];

            if(n<4) level= FASTDIV((level + (s->y_dc_scale>>1)), s->y_dc_scale);

            else    level= FASTDIV((level + (s->c_dc_scale>>1)), s->c_dc_scale);

            dc_pred_dir= (s->pred_dir_table[s->mb_x + s->mb_y*s->mb_stride]<<n)&32;

        }else{

            level = mpeg4_decode_dc(s, n, &dc_pred_dir);

            if (level < 0)

                return -1;

        }

        block[0] = level;

        i = 0;

      }else{

            i = -1;

            ff_mpeg4_pred_dc(s, n, 0, &dc_pred_dir, 0);

      }

        if (!coded)

            goto not_coded;

        if(rvlc){

            rl = &rvlc_rl_intra;

            rl_vlc = rvlc_rl_intra.rl_vlc[0];

        }else{

            rl = &rl_intra;

            rl_vlc = rl_intra.rl_vlc[0];

        }

        if (s->ac_pred) {

            if (dc_pred_dir == 0)

                scan_table = s->intra_v_scantable.permutated; /* left */

            else

                scan_table = s->intra_h_scantable.permutated; /* top */

        } else {

            scan_table = s->intra_scantable.permutated;

        }

        qmul=1;

        qadd=0;

    } else {

        i = -1;

        if (!coded) {

            s->block_last_index[n] = i;

            return 0;

        }

        if(rvlc) rl = &rvlc_rl_inter;

        else     rl = &rl_inter;

        scan_table = s->intra_scantable.permutated;

        if(s->mpeg_quant){

            qmul=1;

            qadd=0;

            if(rvlc){

                rl_vlc = rvlc_rl_inter.rl_vlc[0];

            }else{

                rl_vlc = rl_inter.rl_vlc[0];

            }

        }else{

            qmul = s->qscale << 1;

            qadd = (s->qscale - 1) | 1;

            if(rvlc){

                rl_vlc = rvlc_rl_inter.rl_vlc[s->qscale];

            }else{

                rl_vlc = rl_inter.rl_vlc[s->qscale];

            }

        }

    }

  {

    OPEN_READER(re, &s->gb);

    for(;;) {

        UPDATE_CACHE(re, &s->gb);

        GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 0);

        if (level==0) {

          /* escape */

          if(rvlc){

                if(SHOW_UBITS(re, &s->gb, 1)==0){

                    av_log(s->avctx, AV_LOG_ERROR, "1. marker bit missing in rvlc esc\n");

                    return -1;

                }; SKIP_CACHE(re, &s->gb, 1);

                last=  SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1);

                run=   SHOW_UBITS(re, &s->gb, 6); LAST_SKIP_CACHE(re, &s->gb, 6);

                SKIP_COUNTER(re, &s->gb, 1+1+6);

                UPDATE_CACHE(re, &s->gb);

                if(SHOW_UBITS(re, &s->gb, 1)==0){

                    av_log(s->avctx, AV_LOG_ERROR, "2. marker bit missing in rvlc esc\n");

                    return -1;

                }; SKIP_CACHE(re, &s->gb, 1);

                level= SHOW_UBITS(re, &s->gb, 11); SKIP_CACHE(re, &s->gb, 11);

                if(SHOW_UBITS(re, &s->gb, 5)!=0x10){

                    av_log(s->avctx, AV_LOG_ERROR, "reverse esc missing\n");

                    return -1;

                }; SKIP_CACHE(re, &s->gb, 5);

                level=  level * qmul + qadd;

                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1); LAST_SKIP_CACHE(re, &s->gb, 1);

                SKIP_COUNTER(re, &s->gb, 1+11+5+1);

                i+= run + 1;

                if(last) i+=192;

          }else{

            int cache;

            cache= GET_CACHE(re, &s->gb);

            if(IS_3IV1)

                cache ^= 0xC0000000;

            if (cache&0x80000000) {

                if (cache&0x40000000) {

                    /* third escape */

                    SKIP_CACHE(re, &s->gb, 2);

                    last=  SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1);

                    run=   SHOW_UBITS(re, &s->gb, 6); LAST_SKIP_CACHE(re, &s->gb, 6);

                    SKIP_COUNTER(re, &s->gb, 2+1+6);

                    UPDATE_CACHE(re, &s->gb);

                    if(IS_3IV1){

                        level= SHOW_SBITS(re, &s->gb, 12); LAST_SKIP_BITS(re, &s->gb, 12);

                    }else{

                        if(SHOW_UBITS(re, &s->gb, 1)==0){

                            av_log(s->avctx, AV_LOG_ERROR, "1. marker bit missing in 3. esc\n");

                            return -1;

                        }; SKIP_CACHE(re, &s->gb, 1);

                        level= SHOW_SBITS(re, &s->gb, 12); SKIP_CACHE(re, &s->gb, 12);

                        if(SHOW_UBITS(re, &s->gb, 1)==0){

                            av_log(s->avctx, AV_LOG_ERROR, "2. marker bit missing in 3. esc\n");

                            return -1;

                        }; LAST_SKIP_CACHE(re, &s->gb, 1);

                        SKIP_COUNTER(re, &s->gb, 1+12+1);

                    }

#if 0

                    if(s->error_resilience >= FF_ER_COMPLIANT){

                        const int abs_level= ABS(level);

                        if(abs_level<=MAX_LEVEL && run<=MAX_RUN){

                            const int run1= run - rl->max_run[last][abs_level] - 1;

                            if(abs_level <= rl->max_level[last][run]){

                                av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, vlc encoding possible\n");

                                return -1;

                            }

                            if(s->error_resilience > FF_ER_COMPLIANT){

                                if(abs_level <= rl->max_level[last][run]*2){

                                    av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 1 encoding possible\n");

                                    return -1;

                                }

                                if(run1 >= 0 && abs_level <= rl->max_level[last][run1]){

                                    av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 2 encoding possible\n");

                                    return -1;

                                }

                            }

                        }

                    }

#endif

                    if (level>0) level= level * qmul + qadd;

                    else         level= level * qmul - qadd;

                    if((unsigned)(level + 2048) > 4095){

                        if(s->error_resilience > FF_ER_COMPLIANT){

                            if(level > 2560 || level<-2560){

                                av_log(s->avctx, AV_LOG_ERROR, "|level| overflow in 3. esc, qp=%d\n", s->qscale);

                                return -1;

                            }

                        }

                        level= level<0 ? -2048 : 2047;

                    }

                    i+= run + 1;

                    if(last) i+=192;

                } else {

                    /* second escape */

#if MIN_CACHE_BITS < 20

                    LAST_SKIP_BITS(re, &s->gb, 2);

                    UPDATE_CACHE(re, &s->gb);

#else

                    SKIP_BITS(re, &s->gb, 2);

#endif

                    GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1);

                    i+= run + rl->max_run[run>>7][level/qmul] +1; //FIXME opt indexing

                    level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);

                    LAST_SKIP_BITS(re, &s->gb, 1);

                }

            } else {

                /* first escape */

#if MIN_CACHE_BITS < 19

                LAST_SKIP_BITS(re, &s->gb, 1);

                UPDATE_CACHE(re, &s->gb);

#else

                SKIP_BITS(re, &s->gb, 1);

#endif

                GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1);

                i+= run;

                level = level + rl->max_level[run>>7][(run-1)&63] * qmul;//FIXME opt indexing

                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);

                LAST_SKIP_BITS(re, &s->gb, 1);

            }

          }

        } else {

            i+= run;

            level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);

            LAST_SKIP_BITS(re, &s->gb, 1);

        }

        if (i > 62){

            i-= 192;

            if(i&(~63)){

                av_log(s->avctx, AV_LOG_ERROR, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);

                return -1;

            }

            block[scan_table[i]] = level;

            break;

        }

        block[scan_table[i]] = level;

    }

    CLOSE_READER(re, &s->gb);

  }

 not_coded:

    if (intra) {

        if(s->qscale >= s->intra_dc_threshold){

            block[0] = ff_mpeg4_pred_dc(s, n, block[0], &dc_pred_dir, 0);

            i -= i>>31; //if(i == -1) i=0;

        }

        mpeg4_pred_ac(s, block, n, dc_pred_dir);

        if (s->ac_pred) {

            i = 63; /* XXX: not optimal */

        }

    }

    s->block_last_index[n] = i;

    return 0;

}


static int ea_probe(AVProbeData *p)

{

    if (p->buf_size < 4)

        return 0;

    if (AV_RL32(&p->buf[0]) != SCHl_TAG)

        return 0;

    return AVPROBE_SCORE_MAX;

}


static int64_t ratelimit_calculate_delay(RateLimit *limit, uint64_t n)

{

    int64_t delay_ns = 0;

    int64_t now = qemu_get_clock_ns(rt_clock);

    if (limit->next_slice_time < now) {

        limit->next_slice_time = now + SLICE_TIME;

        limit->dispatched = 0;

    }

    if (limit->dispatched + n > limit->slice_quota) {

        delay_ns = limit->next_slice_time - now;

    } else {

        limit->dispatched += n;

    }

    return delay_ns;

}


static uint32_t iommu_mem_readw(void *opaque, target_phys_addr_t addr)

{

    IOMMUState *s = opaque;

    target_phys_addr_t saddr;

    uint32_t ret;

    saddr = (addr - s->addr) >> 2;

    switch (saddr) {

    default:

        ret = s->regs[saddr];

        break;

    case IOMMU_AFAR:

    case IOMMU_AFSR:

        ret = s->regs[saddr];

        qemu_irq_lower(s->irq);

        break;

    }

    DPRINTF("read reg[%d] = %x\n", (int)saddr, ret);

    return ret;

}


static void create_cpu_model_list(ObjectClass *klass, void *opaque)

{

    struct CpuDefinitionInfoListData *cpu_list_data = opaque;

    CpuDefinitionInfoList **cpu_list = &cpu_list_data->list;

    CpuDefinitionInfoList *entry;

    CpuDefinitionInfo *info;

    char *name = g_strdup(object_class_get_name(klass));

    S390CPUClass *scc = S390_CPU_CLASS(klass);

    /* strip off the -s390-cpu */

    g_strrstr(name, "-" TYPE_S390_CPU)[0] = 0;

    info = g_new0(CpuDefinitionInfo, 1);

    info->name = name;

    info->has_migration_safe = true;

    info->migration_safe = scc->is_migration_safe;

    info->q_static = scc->is_static;

    info->q_typename = g_strdup(object_class_get_name(klass));

    /* check for unavailable features */

    if (cpu_list_data->model) {

        Object *obj;

        S390CPU *sc;

        obj = object_new(object_class_get_name(klass));

        sc = S390_CPU(obj);

        if (sc->model) {

            info->has_unavailable_features = true;

            check_unavailable_features(cpu_list_data->model, sc->model,

                                       &info->unavailable_features);

        }

        object_unref(obj);

    }

    entry = g_new0(CpuDefinitionInfoList, 1);

    entry->value = info;

    entry->next = *cpu_list;

    *cpu_list = entry;

}


static int kvm_mips_put_fpu_registers(CPUState *cs, int level)

{

    MIPSCPU *cpu = MIPS_CPU(cs);

    CPUMIPSState *env = &cpu->env;

    int err, ret = 0;

    unsigned int i;

    /* Only put FPU state if we're emulating a CPU with an FPU */

    if (env->CP0_Config1 & (1 << CP0C1_FP)) {

        /* FPU Control Registers */

        if (level == KVM_PUT_FULL_STATE) {

            err = kvm_mips_put_one_ureg(cs, KVM_REG_MIPS_FCR_IR,

                                        &env->active_fpu.fcr0);

            if (err < 0) {

                DPRINTF("%s: Failed to put FCR_IR (%d)\n", __func__, err);

                ret = err;

            }

        }

        err = kvm_mips_put_one_ureg(cs, KVM_REG_MIPS_FCR_CSR,

                                    &env->active_fpu.fcr31);

        if (err < 0) {

            DPRINTF("%s: Failed to put FCR_CSR (%d)\n", __func__, err);

            ret = err;

        }

        /* Floating point registers */

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

            if (env->CP0_Status & (1 << CP0St_FR)) {

                err = kvm_mips_put_one_ureg64(cs, KVM_REG_MIPS_FPR_64(i),

                                              &env->active_fpu.fpr[i].d);

            } else {

                err = kvm_mips_get_one_ureg(cs, KVM_REG_MIPS_FPR_32(i),

                                      &env->active_fpu.fpr[i].w[FP_ENDIAN_IDX]);

            }

            if (err < 0) {

                DPRINTF("%s: Failed to put FPR%u (%d)\n", __func__, i, err);

                ret = err;

            }

        }

    }

    return ret;

}


void qemu_free(void *ptr)

{

    free(ptr);

}


static void v9fs_mknod(void *opaque)

{

    int mode;

    gid_t gid;

    int32_t fid;

    V9fsQID qid;

    int err = 0;

    int major, minor;

    size_t offset = 7;

    V9fsString name;

    struct stat stbuf;

    V9fsString fullname;

    V9fsFidState *fidp;

    V9fsPDU *pdu = opaque;

    V9fsState *s = pdu->s;

    v9fs_string_init(&fullname);

    pdu_unmarshal(pdu, offset, "dsdddd", &fid, &name, &mode,

                  &major, &minor, &gid);

    fidp = get_fid(s, fid);

    if (fidp == NULL) {

        err = -ENOENT;

        goto out_nofid;

    }

    v9fs_string_sprintf(&fullname, "%s/%s", fidp->path.data, name.data);

    err = v9fs_co_mknod(s, &fullname, fidp->uid, gid,

                        makedev(major, minor), mode);

    if (err < 0) {

        goto out;

    }

    err = v9fs_co_lstat(s, &fullname, &stbuf);

    if (err < 0) {

        goto out;

    }

    stat_to_qid(&stbuf, &qid);

    err = offset;

    err += pdu_marshal(pdu, offset, "Q", &qid);

out:

    put_fid(s, fidp);

out_nofid:

    complete_pdu(s, pdu, err);

    v9fs_string_free(&fullname);

    v9fs_string_free(&name);

}


static void intel_hda_set_st_ctl(IntelHDAState *d, const IntelHDAReg *reg, uint32_t old)

{

    bool output = reg->stream >= 4;

    IntelHDAStream *st = d->st + reg->stream;

    if (st->ctl & 0x01) {

        /* reset */

        dprint(d, 1, "st #%d: reset\n", reg->stream);

        st->ctl = 0;

    }

    if ((st->ctl & 0x02) != (old & 0x02)) {

        uint32_t stnr = (st->ctl >> 20) & 0x0f;

        /* run bit flipped */

        if (st->ctl & 0x02) {

            /* start */

            dprint(d, 1, "st #%d: start %d (ring buf %d bytes)\n",

                   reg->stream, stnr, st->cbl);

            intel_hda_parse_bdl(d, st);

            intel_hda_notify_codecs(d, stnr, true, output);

        } else {

            /* stop */

            dprint(d, 1, "st #%d: stop %d\n", reg->stream, stnr);

            intel_hda_notify_codecs(d, stnr, false, output);

        }

    }

    intel_hda_update_irq(d);

}


static void vnc_listen_read(void *opaque)

{

    VncDisplay *vs = opaque;

    struct sockaddr_in addr;

    socklen_t addrlen = sizeof(addr);

    /* Catch-up */

    vga_hw_update();

    int csock = qemu_accept(vs->lsock, (struct sockaddr *)&addr, &addrlen);

    if (csock != -1) {

        vnc_connect(vs, csock);

    }

}


static inline void int8x8_fmul_int32(DCADSPContext *dsp, float *dst,

                                     const int8_t *src, int scale)

{

    dsp->int8x8_fmul_int32(dst, src, scale);

}


static hwaddr get_offset(hwaddr phys_addr,

                                     DumpState *s)

{

    RAMBlock *block;

    hwaddr offset = s->memory_offset;

    int64_t size_in_block, start;

    if (s->has_filter) {

        if (phys_addr < s->begin || phys_addr >= s->begin + s->length) {

            return -1;

        }

    }

    QTAILQ_FOREACH(block, &ram_list.blocks, next) {

        if (s->has_filter) {

            if (block->offset >= s->begin + s->length ||

                block->offset + block->length <= s->begin) {

                /* This block is out of the range */

                continue;

            }

            if (s->begin <= block->offset) {

                start = block->offset;

            } else {

                start = s->begin;

            }

            size_in_block = block->length - (start - block->offset);

            if (s->begin + s->length < block->offset + block->length) {

                size_in_block -= block->offset + block->length -

                                 (s->begin + s->length);

            }

        } else {

            start = block->offset;

            size_in_block = block->length;

        }

        if (phys_addr >= start && phys_addr < start + size_in_block) {

            return phys_addr - start + offset;

        }

        offset += size_in_block;

    }

    return -1;

}


void net_cleanup(void)

{

    VLANState *vlan;

#if !defined(_WIN32)

    /* close network clients */

    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {

        VLANClientState *vc;

        for(vc = vlan->first_client; vc != NULL; vc = vc->next) {

            if (vc->fd_read == tap_receive) {

                char ifname[64];

                TAPState *s = vc->opaque;

                if (strcmp(vc->model, "tap") == 0 &&

                    sscanf(vc->info_str, "ifname=%63s ", ifname) == 1 &&

                    s->down_script[0])

                    launch_script(s->down_script, ifname, s->fd);

            }

#if defined(CONFIG_VDE)

            if (vc->fd_read == vde_from_qemu) {

                VDEState *s = vc->opaque;

                vde_close(s->vde);

            }

#endif

        }

    }

#endif

}


static int64_t coroutine_fn qcow_co_get_block_status(BlockDriverState *bs,

        int64_t sector_num, int nb_sectors, int *pnum)

{

    BDRVQcowState *s = bs->opaque;

    int index_in_cluster, n;

    uint64_t cluster_offset;

    qemu_co_mutex_lock(&s->lock);

    cluster_offset = get_cluster_offset(bs, sector_num << 9, 0, 0, 0, 0);

    qemu_co_mutex_unlock(&s->lock);

    index_in_cluster = sector_num & (s->cluster_sectors - 1);

    n = s->cluster_sectors - index_in_cluster;

    if (n > nb_sectors)

        n = nb_sectors;

    *pnum = n;

    if (!cluster_offset) {

        return 0;

    }

    if ((cluster_offset & QCOW_OFLAG_COMPRESSED) || s->cipher) {

        return BDRV_BLOCK_DATA;

    }

    cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);

    return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | cluster_offset;

}


static int v9fs_synth_rename(FsContext *ctx, const char *oldpath,

                             const char *newpath)

{

    errno = EPERM;

    return -1;

}


static void gen_spr_604 (CPUPPCState *env)

{

    /* Processor identification */

    spr_register(env, SPR_PIR, "PIR",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_pir,

                 0x00000000);

    /* Breakpoints */

    /* XXX : not implemented */

    spr_register(env, SPR_IABR, "IABR",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_DABR, "DABR",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* Performance counters */

    /* XXX : not implemented */

    spr_register(env, SPR_MMCR0, "MMCR0",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_MMCR1, "MMCR1",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_PMC1, "PMC1",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_PMC2, "PMC2",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_PMC3, "PMC3",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_PMC4, "PMC4",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_SIAR, "SIAR",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, SPR_NOACCESS,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_SDA, "SDA",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, SPR_NOACCESS,

                 0x00000000);

    /* External access control */

    /* XXX : not implemented */

    spr_register(env, SPR_EAR, "EAR",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

}


void helper_sysret(int dflag)

{

    int cpl, selector;

    if (!(env->efer & MSR_EFER_SCE)) {

        raise_exception_err(EXCP06_ILLOP, 0);

    }

    cpl = env->hflags & HF_CPL_MASK;

    if (!(env->cr[0] & CR0_PE_MASK) || cpl != 0) {

        raise_exception_err(EXCP0D_GPF, 0);

    }

    selector = (env->star >> 48) & 0xffff;

    if (env->hflags & HF_LMA_MASK) {

        if (dflag == 2) {

            cpu_x86_load_seg_cache(env, R_CS, (selector + 16) | 3,

                                   0, 0xffffffff,

                                   DESC_G_MASK | DESC_P_MASK |

                                   DESC_S_MASK | (3 << DESC_DPL_SHIFT) |

                                   DESC_CS_MASK | DESC_R_MASK | DESC_A_MASK |

                                   DESC_L_MASK);

            env->eip = ECX;

        } else {

            cpu_x86_load_seg_cache(env, R_CS, selector | 3,

                                   0, 0xffffffff,

                                   DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |

                                   DESC_S_MASK | (3 << DESC_DPL_SHIFT) |

                                   DESC_CS_MASK | DESC_R_MASK | DESC_A_MASK);

            env->eip = (uint32_t)ECX;

        }

        cpu_x86_load_seg_cache(env, R_SS, selector + 8,

                               0, 0xffffffff,

                               DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |

                               DESC_S_MASK | (3 << DESC_DPL_SHIFT) |

                               DESC_W_MASK | DESC_A_MASK);

        load_eflags((uint32_t)(env->regs[11]), TF_MASK | AC_MASK | ID_MASK |

                    IF_MASK | IOPL_MASK | VM_MASK | RF_MASK | NT_MASK);

        cpu_x86_set_cpl(env, 3);

    } else {

        cpu_x86_load_seg_cache(env, R_CS, selector | 3,

                               0, 0xffffffff,

                               DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |

                               DESC_S_MASK | (3 << DESC_DPL_SHIFT) |

                               DESC_CS_MASK | DESC_R_MASK | DESC_A_MASK);

        env->eip = (uint32_t)ECX;

        cpu_x86_load_seg_cache(env, R_SS, selector + 8,

                               0, 0xffffffff,

                               DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |

                               DESC_S_MASK | (3 << DESC_DPL_SHIFT) |

                               DESC_W_MASK | DESC_A_MASK);

        env->eflags |= IF_MASK;

        cpu_x86_set_cpl(env, 3);

    }

#ifdef CONFIG_KQEMU

    if (kqemu_is_ok(env)) {

        if (env->hflags & HF_LMA_MASK)

            CC_OP = CC_OP_EFLAGS;

        env->exception_index = -1;

        cpu_loop_exit();

    }

#endif

}


static int parallels_probe(const uint8_t *buf, int buf_size, const char *filename)

{

    const ParallelsHeader *ph = (const void *)buf;

    if (buf_size < sizeof(ParallelsHeader))

        return 0;

    if ((!memcmp(ph->magic, HEADER_MAGIC, 16) ||

        !memcmp(ph->magic, HEADER_MAGIC2, 16)) &&

        (le32_to_cpu(ph->version) == HEADER_VERSION))

        return 100;

    return 0;

}


static int decode_coeffs(WMAProDecodeCtx *s, int c)

{

    /* Integers 0..15 as single-precision floats.  The table saves a

       costly int to float conversion, and storing the values as

       integers allows fast sign-flipping. */

    static const int fval_tab[16] = {

        0x00000000, 0x3f800000, 0x40000000, 0x40400000,

        0x40800000, 0x40a00000, 0x40c00000, 0x40e00000,

        0x41000000, 0x41100000, 0x41200000, 0x41300000,

        0x41400000, 0x41500000, 0x41600000, 0x41700000,

    };

    int vlctable;

    VLC* vlc;

    WMAProChannelCtx* ci = &s->channel[c];

    int rl_mode = 0;

    int cur_coeff = 0;

    int num_zeros = 0;

    const uint16_t* run;

    const float* level;

    av_dlog(s->avctx, "decode coefficients for channel %i\n", c);

    vlctable = get_bits1(&s->gb);

    vlc = &coef_vlc[vlctable];

    if (vlctable) {

        run = coef1_run;

        level = coef1_level;

    } else {

        run = coef0_run;

        level = coef0_level;

    }

    /** decode vector coefficients (consumes up to 167 bits per iteration for

      4 vector coded large values) */

    while ((s->transmit_num_vec_coeffs || !rl_mode) &&

           (cur_coeff + 3 < ci->num_vec_coeffs)) {

        int vals[4];

        int i;

        unsigned int idx;

        idx = get_vlc2(&s->gb, vec4_vlc.table, VLCBITS, VEC4MAXDEPTH);

        if (idx == HUFF_VEC4_SIZE - 1) {

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

                idx = get_vlc2(&s->gb, vec2_vlc.table, VLCBITS, VEC2MAXDEPTH);

                if (idx == HUFF_VEC2_SIZE - 1) {

                    int v0, v1;

                    v0 = get_vlc2(&s->gb, vec1_vlc.table, VLCBITS, VEC1MAXDEPTH);

                    if (v0 == HUFF_VEC1_SIZE - 1)

                        v0 += ff_wma_get_large_val(&s->gb);

                    v1 = get_vlc2(&s->gb, vec1_vlc.table, VLCBITS, VEC1MAXDEPTH);

                    if (v1 == HUFF_VEC1_SIZE - 1)

                        v1 += ff_wma_get_large_val(&s->gb);

                    ((float*)vals)[i  ] = v0;

                    ((float*)vals)[i+1] = v1;

                } else {

                    vals[i]   = fval_tab[symbol_to_vec2[idx] >> 4 ];

                    vals[i+1] = fval_tab[symbol_to_vec2[idx] & 0xF];

                }

            }

        } else {

            vals[0] = fval_tab[ symbol_to_vec4[idx] >> 12      ];

            vals[1] = fval_tab[(symbol_to_vec4[idx] >> 8) & 0xF];

            vals[2] = fval_tab[(symbol_to_vec4[idx] >> 4) & 0xF];

            vals[3] = fval_tab[ symbol_to_vec4[idx]       & 0xF];

        }

        /** decode sign */

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

            if (vals[i]) {

                int sign = get_bits1(&s->gb) - 1;

                *(uint32_t*)&ci->coeffs[cur_coeff] = vals[i] ^ sign<<31;

                num_zeros = 0;

            } else {

                ci->coeffs[cur_coeff] = 0;

                /** switch to run level mode when subframe_len / 128 zeros

                    were found in a row */

                rl_mode |= (++num_zeros > s->subframe_len >> 8);

            }

            ++cur_coeff;

        }

    }

    /** decode run level coded coefficients */

    if (cur_coeff < s->subframe_len) {

        memset(&ci->coeffs[cur_coeff], 0,

               sizeof(*ci->coeffs) * (s->subframe_len - cur_coeff));

        if (ff_wma_run_level_decode(s->avctx, &s->gb, vlc,

                                    level, run, 1, ci->coeffs,

                                    cur_coeff, s->subframe_len,

                                    s->subframe_len, s->esc_len, 0))

            return AVERROR_INVALIDDATA;

    }

    return 0;

}


static void qemu_chr_parse_ringbuf(QemuOpts *opts, ChardevBackend *backend,

                                   Error **errp)

{

    int val;

    ChardevRingbuf *ringbuf;

    ringbuf = backend->u.ringbuf = g_new0(ChardevRingbuf, 1);

    qemu_chr_parse_common(opts, qapi_ChardevRingbuf_base(ringbuf));

    val = qemu_opt_get_size(opts, "size", 0);

    if (val != 0) {

        ringbuf->has_size = true;

        ringbuf->size = val;

    }

}


static coroutine_fn int sd_co_readv(BlockDriverState *bs, int64_t sector_num,

                       int nb_sectors, QEMUIOVector *qiov)

{

    SheepdogAIOCB acb;

    BDRVSheepdogState *s = bs->opaque;

    sd_aio_setup(&acb, s, qiov, sector_num, nb_sectors, AIOCB_READ_UDATA);

retry:

    if (check_overlapping_aiocb(s, &acb)) {

        qemu_co_queue_wait(&s->overlapping_queue);

        goto retry;

    }

    sd_co_rw_vector(&acb);

    QLIST_REMOVE(&acb, aiocb_siblings);

    qemu_co_queue_restart_all(&s->overlapping_queue);

    return acb.ret;

}


static void multiwrite_help(void)

{

    printf(

"\n"

" writes a range of bytes from the given offset source from multiple buffers,\n"

" in a batch of requests that may be merged by qemu\n"

"\n"

" Example:\n"

" 'multiwrite 512 1k 1k ; 4k 1k' \n"

"  writes 2 kB at 512 bytes and 1 kB at 4 kB into the open file\n"

"\n"

" Writes into a segment of the currently open file, using a buffer\n"

" filled with a set pattern (0xcdcdcdcd). The pattern byte is increased\n"

" by one for each request contained in the multiwrite command.\n"

" -P, -- use different pattern to fill file\n"

" -C, -- report statistics in a machine parsable format\n"

" -q, -- quiet mode, do not show I/O statistics\n"

"\n");

}


MemoryRegionSection memory_region_find(MemoryRegion *address_space,

                                       hwaddr addr, uint64_t size)

{

    AddressSpace *as = memory_region_to_address_space(address_space);

    AddrRange range = addrrange_make(int128_make64(addr),

                                     int128_make64(size));

    FlatRange *fr = address_space_lookup(as, range);

    MemoryRegionSection ret = { .mr = NULL, .size = 0 };

    if (!fr) {

        return ret;

    }

    while (fr > as->current_map->ranges

           && addrrange_intersects(fr[-1].addr, range)) {

        --fr;

    }

    ret.mr = fr->mr;

    range = addrrange_intersection(range, fr->addr);

    ret.offset_within_region = fr->offset_in_region;

    ret.offset_within_region += int128_get64(int128_sub(range.start,

                                                        fr->addr.start));

    ret.size = int128_get64(range.size);

    ret.offset_within_address_space = int128_get64(range.start);

    ret.readonly = fr->readonly;

    return ret;

}


static int check_pow_970MP (CPUPPCState *env)

{

    if (env->spr[SPR_HID0] & 0x01C00000)

        return 1;

    return 0;

}


void esp_reg_write(ESPState *s, uint32_t saddr, uint64_t val)

{

    trace_esp_mem_writeb(saddr, s->wregs[saddr], val);

    switch (saddr) {

    case ESP_TCHI:

        s->tchi_written = true;

        /* fall through */

    case ESP_TCLO:

    case ESP_TCMID:

        s->rregs[ESP_RSTAT] &= ~STAT_TC;

        break;

    case ESP_FIFO:

        if (s->do_cmd) {

            if (s->cmdlen < TI_BUFSZ) {

                s->cmdbuf[s->cmdlen++] = val & 0xff;

            } else {

                trace_esp_error_fifo_overrun();

            }

        } else if (s->ti_size == TI_BUFSZ - 1) {

            trace_esp_error_fifo_overrun();

        } else {

            s->ti_size++;

            s->ti_buf[s->ti_wptr++] = val & 0xff;

        }

        break;

    case ESP_CMD:

        s->rregs[saddr] = val;

        if (val & CMD_DMA) {

            s->dma = 1;

            /* Reload DMA counter.  */

            s->rregs[ESP_TCLO] = s->wregs[ESP_TCLO];

            s->rregs[ESP_TCMID] = s->wregs[ESP_TCMID];

            s->rregs[ESP_TCHI] = s->wregs[ESP_TCHI];

        } else {

            s->dma = 0;

        }

        switch(val & CMD_CMD) {

        case CMD_NOP:

            trace_esp_mem_writeb_cmd_nop(val);

            break;

        case CMD_FLUSH:

            trace_esp_mem_writeb_cmd_flush(val);

            //s->ti_size = 0;

            s->rregs[ESP_RINTR] = INTR_FC;

            s->rregs[ESP_RSEQ] = 0;

            s->rregs[ESP_RFLAGS] = 0;

            break;

        case CMD_RESET:

            trace_esp_mem_writeb_cmd_reset(val);

            esp_soft_reset(s);

            break;

        case CMD_BUSRESET:

            trace_esp_mem_writeb_cmd_bus_reset(val);

            s->rregs[ESP_RINTR] = INTR_RST;

            if (!(s->wregs[ESP_CFG1] & CFG1_RESREPT)) {

                esp_raise_irq(s);

            }

            break;

        case CMD_TI:

            handle_ti(s);

            break;

        case CMD_ICCS:

            trace_esp_mem_writeb_cmd_iccs(val);

            write_response(s);

            s->rregs[ESP_RINTR] = INTR_FC;

            s->rregs[ESP_RSTAT] |= STAT_MI;

            break;

        case CMD_MSGACC:

            trace_esp_mem_writeb_cmd_msgacc(val);

            s->rregs[ESP_RINTR] = INTR_DC;

            s->rregs[ESP_RSEQ] = 0;

            s->rregs[ESP_RFLAGS] = 0;

            esp_raise_irq(s);

            break;

        case CMD_PAD:

            trace_esp_mem_writeb_cmd_pad(val);

            s->rregs[ESP_RSTAT] = STAT_TC;

            s->rregs[ESP_RINTR] = INTR_FC;

            s->rregs[ESP_RSEQ] = 0;

            break;

        case CMD_SATN:

            trace_esp_mem_writeb_cmd_satn(val);

            break;

        case CMD_RSTATN:

            trace_esp_mem_writeb_cmd_rstatn(val);

            break;

        case CMD_SEL:

            trace_esp_mem_writeb_cmd_sel(val);

            handle_s_without_atn(s);

            break;

        case CMD_SELATN:

            trace_esp_mem_writeb_cmd_selatn(val);

            handle_satn(s);

            break;

        case CMD_SELATNS:

            trace_esp_mem_writeb_cmd_selatns(val);

            handle_satn_stop(s);

            break;

        case CMD_ENSEL:

            trace_esp_mem_writeb_cmd_ensel(val);

            s->rregs[ESP_RINTR] = 0;

            break;

        case CMD_DISSEL:

            trace_esp_mem_writeb_cmd_dissel(val);

            s->rregs[ESP_RINTR] = 0;

            esp_raise_irq(s);

            break;

        default:

            trace_esp_error_unhandled_command(val);

            break;

        }

        break;

    case ESP_WBUSID ... ESP_WSYNO:

        break;

    case ESP_CFG1:

    case ESP_CFG2: case ESP_CFG3:

    case ESP_RES3: case ESP_RES4:

        s->rregs[saddr] = val;

        break;

    case ESP_WCCF ... ESP_WTEST:

        break;

    default:

        trace_esp_error_invalid_write(val, saddr);

        return;

    }

    s->wregs[saddr] = val;

}


static void decode_delta_e(uint8_t *dst,

                           const uint8_t *buf, const uint8_t *buf_end,

                           int w, int flag, int bpp, int dst_size)

{

    int planepitch = FFALIGN(w, 16) >> 3;

    int pitch = planepitch * bpp;

    int planepitch_byte = (w + 7) / 8;

    unsigned entries, ofssrc;

    GetByteContext gb, ptrs;

    PutByteContext pb;

    int k;

    if (buf_end - buf <= 4 * bpp)

        return;

    bytestream2_init_writer(&pb, dst, dst_size);

    bytestream2_init(&ptrs, buf, bpp * 4);

    for (k = 0; k < bpp; k++) {

        ofssrc = bytestream2_get_be32(&ptrs);

        if (!ofssrc)

            continue;

        if (ofssrc >= buf_end - buf)

            continue;

        bytestream2_init(&gb, buf + ofssrc, buf_end - (buf + ofssrc));

        entries = bytestream2_get_be16(&gb);

        while (entries) {

            int16_t opcode  = bytestream2_get_be16(&gb);

            unsigned offset = bytestream2_get_be32(&gb);

            bytestream2_seek_p(&pb, (offset / planepitch_byte) * pitch + (offset % planepitch_byte) + k * planepitch, SEEK_SET);

            if (opcode >= 0) {

                uint16_t x = bytestream2_get_be16(&gb);

                while (opcode && bytestream2_get_bytes_left_p(&pb) > 0) {

                    bytestream2_put_be16(&pb, x);

                    bytestream2_skip_p(&pb, pitch - 2);

                    opcode--;

                }

            } else {

                opcode = -opcode;

                while (opcode && bytestream2_get_bytes_left(&gb) > 0) {

                    bytestream2_put_be16(&pb, bytestream2_get_be16(&gb));

                    bytestream2_skip_p(&pb, pitch - 2);

                    opcode--;

                }

            }

            entries--;

        }

    }

}


static void bonito_pciconf_writel(void *opaque, target_phys_addr_t addr,

                                  uint64_t val, unsigned size)

{

    PCIBonitoState *s = opaque;

    PCIDevice *d = PCI_DEVICE(s);

    DPRINTF("bonito_pciconf_writel "TARGET_FMT_plx" val %x\n", addr, val);

    d->config_write(d, addr, val, 4);

}


void ff_snow_vertical_compose97i_sse2(DWTELEM *b0, DWTELEM *b1, DWTELEM *b2, DWTELEM *b3, DWTELEM *b4, DWTELEM *b5, int width){

    long i = width;

    while(i & 0xF)

    {

        i--;

        b4[i] -= (W_DM*(b3[i] + b5[i])+W_DO)>>W_DS;

        b3[i] -= (W_CM*(b2[i] + b4[i])+W_CO)>>W_CS;

        b2[i] += (W_BM*(b1[i] + b3[i])+4*b2[i]+W_BO)>>W_BS;

        b1[i] += (W_AM*(b0[i] + b2[i])+W_AO)>>W_AS;

    }

         asm volatile (

        "jmp 2f                                      \n\t"

        "1:                                          \n\t"

        "mov %6, %%"REG_a"                           \n\t"

        "mov %4, %%"REG_S"                           \n\t"

        snow_vertical_compose_sse2_load(REG_S,"xmm0","xmm2","xmm4","xmm6")

        snow_vertical_compose_sse2_add(REG_a,"xmm0","xmm2","xmm4","xmm6")

        snow_vertical_compose_sse2_move("xmm0","xmm2","xmm4","xmm6","xmm1","xmm3","xmm5","xmm7")

        snow_vertical_compose_sse2_r2r_add("xmm0","xmm2","xmm4","xmm6","xmm0","xmm2","xmm4","xmm6")

        snow_vertical_compose_sse2_r2r_add("xmm1","xmm3","xmm5","xmm7","xmm0","xmm2","xmm4","xmm6")

        "pcmpeqd %%xmm1, %%xmm1                      \n\t"

        "pslld $31, %%xmm1                           \n\t"

        "psrld $29, %%xmm1                           \n\t"

        "mov %5, %%"REG_a"                           \n\t"

        snow_vertical_compose_sse2_r2r_add("xmm1","xmm1","xmm1","xmm1","xmm0","xmm2","xmm4","xmm6")

        snow_vertical_compose_sse2_sra("3","xmm0","xmm2","xmm4","xmm6")

        snow_vertical_compose_sse2_load(REG_a,"xmm1","xmm3","xmm5","xmm7")

        snow_vertical_compose_sse2_sub("xmm0","xmm2","xmm4","xmm6","xmm1","xmm3","xmm5","xmm7")

        snow_vertical_compose_sse2_store(REG_a,"xmm1","xmm3","xmm5","xmm7")

        "mov %3, %%"REG_c"                           \n\t"

        snow_vertical_compose_sse2_load(REG_S,"xmm0","xmm2","xmm4","xmm6")

        snow_vertical_compose_sse2_add(REG_c,"xmm1","xmm3","xmm5","xmm7")

        snow_vertical_compose_sse2_sub("xmm1","xmm3","xmm5","xmm7","xmm0","xmm2","xmm4","xmm6")

        snow_vertical_compose_sse2_store(REG_S,"xmm0","xmm2","xmm4","xmm6")

        "mov %2, %%"REG_a"                           \n\t"

        snow_vertical_compose_sse2_add(REG_a,"xmm0","xmm2","xmm4","xmm6")

        snow_vertical_compose_sse2_sra("2","xmm0","xmm2","xmm4","xmm6")

        snow_vertical_compose_sse2_add(REG_c,"xmm0","xmm2","xmm4","xmm6")

        "pcmpeqd %%xmm1, %%xmm1                      \n\t"

        "pslld $31, %%xmm1                           \n\t"

        "psrld $30, %%xmm1                           \n\t"

        "mov %1, %%"REG_S"                           \n\t"

        snow_vertical_compose_sse2_r2r_add("xmm1","xmm1","xmm1","xmm1","xmm0","xmm2","xmm4","xmm6")

        snow_vertical_compose_sse2_sra("2","xmm0","xmm2","xmm4","xmm6")

        snow_vertical_compose_sse2_add(REG_c,"xmm0","xmm2","xmm4","xmm6")

        snow_vertical_compose_sse2_store(REG_c,"xmm0","xmm2","xmm4","xmm6")

        snow_vertical_compose_sse2_add(REG_S,"xmm0","xmm2","xmm4","xmm6")

        snow_vertical_compose_sse2_move("xmm0","xmm2","xmm4","xmm6","xmm1","xmm3","xmm5","xmm7")

        snow_vertical_compose_sse2_sra("1","xmm0","xmm2","xmm4","xmm6")

        snow_vertical_compose_sse2_r2r_add("xmm1","xmm3","xmm5","xmm7","xmm0","xmm2","xmm4","xmm6")

        snow_vertical_compose_sse2_add(REG_a,"xmm0","xmm2","xmm4","xmm6")

        snow_vertical_compose_sse2_store(REG_a,"xmm0","xmm2","xmm4","xmm6")

        "2:                                          \n\t"

        "sub $16, %%"REG_d"                          \n\t"

        "jge 1b                                      \n\t"

        :"+d"(i)

        :

        "m"(b0),"m"(b1),"m"(b2),"m"(b3),"m"(b4),"m"(b5):

        "%"REG_a"","%"REG_S"","%"REG_c"");

}


int qemu_fclose(QEMUFile *f)

{

    int ret = 0;

    qemu_fflush(f);

    if (f->close)

        ret = f->close(f->opaque);

    g_free(f);

    return ret;

}


static bool block_is_active(void *opaque)

{

    return block_mig_state.blk_enable == 1;

}


static void filter1(int32_t *dst, const int32_t *src, int32_t coeff, ptrdiff_t len)

{

    int i;

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

        dst[i] -= mul23(src[i], coeff);

}


static int mpegts_write_end(AVFormatContext *s)

{

    MpegTSWrite *ts = s->priv_data;

    MpegTSWriteStream *ts_st;

    MpegTSService *service;

    AVStream *st;

    int i;

    /* flush current packets */

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

        st = s->streams[i];

        ts_st = st->priv_data;

        if (ts_st->payload_index > 0) {

            mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_index,

                             ts_st->payload_pts);

        }

    }

    put_flush_packet(&s->pb);

    for(i = 0; i < ts->nb_services; i++) {

        service = ts->services[i];

        av_freep(&service->provider_name);

        av_freep(&service->name);

        av_free(service);

    }

    av_free(ts->services);

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

        st = s->streams[i];

        av_free(st->priv_data);

    }

    return 0;

}


static int microdvd_probe(AVProbeData *p)

{

    unsigned char c;

    const uint8_t *ptr = p->buf;

    int i;

    if (AV_RB24(ptr) == 0xEFBBBF)

        ptr += 3;  /* skip UTF-8 BOM */

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

        if (sscanf(ptr, "{%*d}{}%c",     &c) != 1 &&

            sscanf(ptr, "{%*d}{%*d}%c",  &c) != 1 &&

            sscanf(ptr, "{DEFAULT}{}%c", &c) != 1)

            return 0;

        ptr += strcspn(ptr, "\n") + 1;

    }

    return AVPROBE_SCORE_MAX;

}


static void draw_char(AVCodecContext *avctx, int c)

{

    AnsiContext *s = avctx->priv_data;

    int fg = s->fg;

    int bg = s->bg;

    if ((s->attributes & ATTR_BOLD))

        fg += 8;

    if ((s->attributes & ATTR_BLINK))

        bg += 8;

    if ((s->attributes & ATTR_REVERSE))

        FFSWAP(int, fg, bg);

    if ((s->attributes & ATTR_CONCEALED))

        fg = bg;

    ff_draw_pc_font(s->frame->data[0] + s->y * s->frame->linesize[0] + s->x,

                    s->frame->linesize[0], s->font, s->font_height, c, fg, bg);

    s->x += FONT_WIDTH;

    if (s->x >= avctx->width) {

        s->x = 0;

        hscroll(avctx);

    }

}


static av_always_inline int vorbis_residue_decode_internal(vorbis_context *vc,

                                                           vorbis_residue *vr,

                                                           unsigned ch,

                                                           uint8_t *do_not_decode,

                                                           float *vec,

                                                           unsigned vlen,

                                                           unsigned ch_left,

                                                           int vr_type)

{

    GetBitContext *gb = &vc->gb;

    unsigned c_p_c        = vc->codebooks[vr->classbook].dimensions;

    uint8_t *classifs = vr->classifs;

    unsigned pass, ch_used, i, j, k, l;

    unsigned max_output = (ch - 1) * vlen;

    int ptns_to_read = vr->ptns_to_read;

    if (vr_type == 2) {

        for (j = 1; j < ch; ++j)

            do_not_decode[0] &= do_not_decode[j];  // FIXME - clobbering input

        if (do_not_decode[0])

            return 0;

        ch_used = 1;

        max_output += vr->end / ch;

    } else {

        ch_used = ch;

        max_output += vr->end;

    }

    if (max_output > ch_left * vlen) {

        av_log(vc->avctx, AV_LOG_ERROR, "Insufficient output buffer\n");

        return AVERROR_INVALIDDATA;

    }

    av_dlog(NULL, " residue type 0/1/2 decode begin, ch: %d  cpc %d  \n", ch, c_p_c);

    for (pass = 0; pass <= vr->maxpass; ++pass) { // FIXME OPTIMIZE?

        int voffset, partition_count, j_times_ptns_to_read;

        voffset = vr->begin;

        for (partition_count = 0; partition_count < ptns_to_read;) {  // SPEC        error

            if (!pass) {

                setup_classifs(vc, vr, do_not_decode, ch_used, partition_count);

            }

            for (i = 0; (i < c_p_c) && (partition_count < ptns_to_read); ++i) {

                for (j_times_ptns_to_read = 0, j = 0; j < ch_used; ++j) {

                    unsigned voffs;

                    if (!do_not_decode[j]) {

                        unsigned vqclass = classifs[j_times_ptns_to_read + partition_count];

                        int vqbook  = vr->books[vqclass][pass];

                        if (vqbook >= 0 && vc->codebooks[vqbook].codevectors) {

                            unsigned coffs;

                            unsigned dim  = vc->codebooks[vqbook].dimensions;

                            unsigned step = FASTDIV(vr->partition_size << 1, dim << 1);

                            vorbis_codebook codebook = vc->codebooks[vqbook];

                            if (vr_type == 0) {

                                voffs = voffset+j*vlen;

                                for (k = 0; k < step; ++k) {

                                    coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * dim;

                                    for (l = 0; l < dim; ++l)

                                        vec[voffs + k + l * step] += codebook.codevectors[coffs + l];

                                }

                            } else if (vr_type == 1) {

                                voffs = voffset + j * vlen;

                                for (k = 0; k < step; ++k) {

                                    coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * dim;

                                    for (l = 0; l < dim; ++l, ++voffs) {

                                        vec[voffs]+=codebook.codevectors[coffs+l];

                                        av_dlog(NULL, " pass %d offs: %d curr: %f change: %f cv offs.: %d  \n",

                                                pass, voffs, vec[voffs], codebook.codevectors[coffs+l], coffs);

                                    }

                                }

                            } else if (vr_type == 2 && ch == 2 && (voffset & 1) == 0 && (dim & 1) == 0) { // most frequent case optimized

                                voffs = voffset >> 1;

                                if (dim == 2) {

                                    for (k = 0; k < step; ++k) {

                                        coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * 2;

                                        vec[voffs + k       ] += codebook.codevectors[coffs    ];

                                        vec[voffs + k + vlen] += codebook.codevectors[coffs + 1];

                                    }

                                } else if (dim == 4) {

                                    for (k = 0; k < step; ++k, voffs += 2) {

                                        coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * 4;

                                        vec[voffs           ] += codebook.codevectors[coffs    ];

                                        vec[voffs + 1       ] += codebook.codevectors[coffs + 2];

                                        vec[voffs + vlen    ] += codebook.codevectors[coffs + 1];

                                        vec[voffs + vlen + 1] += codebook.codevectors[coffs + 3];

                                    }

                                } else

                                for (k = 0; k < step; ++k) {

                                    coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * dim;

                                    for (l = 0; l < dim; l += 2, voffs++) {

                                        vec[voffs       ] += codebook.codevectors[coffs + l    ];

                                        vec[voffs + vlen] += codebook.codevectors[coffs + l + 1];

                                        av_dlog(NULL, " pass %d offs: %d curr: %f change: %f cv offs.: %d+%d  \n",

                                                pass, voffset / ch + (voffs % ch) * vlen,

                                                vec[voffset / ch + (voffs % ch) * vlen],

                                                codebook.codevectors[coffs + l], coffs, l);

                                    }

                                }

                            } else if (vr_type == 2) {

                                unsigned voffs_div = FASTDIV(voffset << 1, ch <<1);

                                unsigned voffs_mod = voffset - voffs_div * ch;

                                for (k = 0; k < step; ++k) {

                                    coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * dim;

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

                                        vec[voffs_div + voffs_mod * vlen] +=

                                            codebook.codevectors[coffs + l];

                                        av_dlog(NULL, " pass %d offs: %d curr: %f change: %f cv offs.: %d+%d  \n",

                                                pass, voffs_div + voffs_mod * vlen,

                                                vec[voffs_div + voffs_mod * vlen],

                                                codebook.codevectors[coffs + l], coffs, l);

                                        if (++voffs_mod == ch) {

                                            voffs_div++;

                                            voffs_mod = 0;

                                        }

                                    }

                                }

                            }

                        }

                    }

                    j_times_ptns_to_read += ptns_to_read;

                }

                ++partition_count;

                voffset += vr->partition_size;

            }

        }

    }

    return 0;

}


static int init_quantization_noise(DCAEncContext *c, int noise)

{

    int ch, band, ret = 0;

    c->consumed_bits = 132 + 493 * c->fullband_channels;

    if (c->lfe_channel)

        c->consumed_bits += 72;

    /* attempt to guess the bit distribution based on the prevoius frame */

    for (ch = 0; ch < c->fullband_channels; ch++) {

        for (band = 0; band < 32; band++) {

            int snr_cb = c->peak_cb[band][ch] - c->band_masking_cb[band] - noise;

            if (snr_cb >= 1312) {

                c->abits[band][ch] = 26;

                ret |= USED_26ABITS;

            } else if (snr_cb >= 222) {

                c->abits[band][ch] = 8 + mul32(snr_cb - 222, 69000000);

                ret |= USED_NABITS;

            } else if (snr_cb >= 0) {

                c->abits[band][ch] = 2 + mul32(snr_cb, 106000000);

                ret |= USED_NABITS;

            } else {

                c->abits[band][ch] = 1;

                ret |= USED_1ABITS;

            }

        }

    }

    for (band = 0; band < 32; band++)

        for (ch = 0; ch < c->fullband_channels; ch++) {

            c->consumed_bits += bit_consumption[c->abits[band][ch]];

        }

    return ret;

}


static void hevc_await_progress(HEVCContext *s, HEVCFrame *ref,

                                const Mv *mv, int y0, int height)

{

    int y = FFMAX(0, (mv->y >> 2) + y0 + height + 9);

    if (s->threads_type == FF_THREAD_FRAME )

        ff_thread_await_progress(&ref->tf, y, 0);

}


static inline void h264_loop_filter_luma_intra_c(uint8_t *pix, int xstride, int ystride, int alpha, int beta)

{

    int d;

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

        const int p2 = pix[-3*xstride];

        const int p1 = pix[-2*xstride];

        const int p0 = pix[-1*xstride];

        const int q0 = pix[ 0*xstride];

        const int q1 = pix[ 1*xstride];

        const int q2 = pix[ 2*xstride];

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

            FFABS( p1 - p0 ) < beta &&

            FFABS( q1 - q0 ) < beta ) {

            if(FFABS( p0 - q0 ) < (( alpha >> 2 ) + 2 )){

                if( FFABS( p2 - p0 ) < beta)

                {

                    const int p3 = pix[-4*xstride];

                    /* p0', p1', p2' */

                    pix[-1*xstride] = ( p2 + 2*p1 + 2*p0 + 2*q0 + q1 + 4 ) >> 3;

                    pix[-2*xstride] = ( p2 + p1 + p0 + q0 + 2 ) >> 2;

                    pix[-3*xstride] = ( 2*p3 + 3*p2 + p1 + p0 + q0 + 4 ) >> 3;

                } else {

                    /* p0' */

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

                }

                if( FFABS( q2 - q0 ) < beta)

                {

                    const int q3 = pix[3*xstride];

                    /* q0', q1', q2' */

                    pix[0*xstride] = ( p1 + 2*p0 + 2*q0 + 2*q1 + q2 + 4 ) >> 3;

                    pix[1*xstride] = ( p0 + q0 + q1 + q2 + 2 ) >> 2;

                    pix[2*xstride] = ( 2*q3 + 3*q2 + q1 + q0 + p0 + 4 ) >> 3;

                } else {

                    /* q0' */

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

                }

            }else{

                /* p0', q0' */

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

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

            }

        }

        pix += ystride;

    }

}


void ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,

                              int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))

{

    AVPacketList **next_point, *this_pktl;

    this_pktl      = av_mallocz(sizeof(AVPacketList));

    this_pktl->pkt = *pkt;

#if FF_API_DESTRUCT_PACKET

FF_DISABLE_DEPRECATION_WARNINGS

    pkt->destruct  = NULL;           // do not free original but only the copy

FF_ENABLE_DEPRECATION_WARNINGS

#endif

    pkt->buf       = NULL;

    av_dup_packet(&this_pktl->pkt);  // duplicate the packet if it uses non-alloced memory

    if (s->streams[pkt->stream_index]->last_in_packet_buffer) {

        next_point = &(s->streams[pkt->stream_index]->last_in_packet_buffer->next);

    } else

        next_point = &s->packet_buffer;

    if (*next_point) {

        if (compare(s, &s->packet_buffer_end->pkt, pkt)) {

            while (!compare(s, &(*next_point)->pkt, pkt))

                next_point = &(*next_point)->next;

            goto next_non_null;

        } else {

            next_point = &(s->packet_buffer_end->next);

        }

    }

    assert(!*next_point);

    s->packet_buffer_end = this_pktl;

next_non_null:

    this_pktl->next = *next_point;

    s->streams[pkt->stream_index]->last_in_packet_buffer =

        *next_point                                      = this_pktl;

}


static int ipvideo_decode_block_opcode_0x7(IpvideoContext *s, AVFrame *frame)
{
    int x, y;
    unsigned char P[2];
    unsigned int flags;
    /* 2-color encoding */
    P[0] = bytestream2_get_byte(&s->stream_ptr);
    P[1] = bytestream2_get_byte(&s->stream_ptr);
    if (P[0] <= P[1]) {
        /* need 8 more bytes from the stream */
        for (y = 0; y < 8; y++) {
            flags = bytestream2_get_byte(&s->stream_ptr) | 0x100;
            for (; flags != 1; flags >>= 1)
                *s->pixel_ptr++ = P[flags & 1];
            s->pixel_ptr += s->line_inc;
    } else {
        /* need 2 more bytes from the stream */
        flags = bytestream2_get_le16(&s->stream_ptr);
        for (y = 0; y < 8; y += 2) {
            for (x = 0; x < 8; x += 2, flags >>= 1) {
                s->pixel_ptr[x                ] =
                s->pixel_ptr[x + 1            ] =
                s->pixel_ptr[x +     s->stride] =
                s->pixel_ptr[x + 1 + s->stride] = P[flags & 1];
            s->pixel_ptr += s->stride * 2;
    /* report success */
    return 0;


void nvdimm_build_acpi(GArray *table_offsets, GArray *table_data,

                       BIOSLinker *linker, GArray *dsm_dma_arrea,

                       uint32_t ram_slots)

{

    GSList *device_list;

    device_list = nvdimm_get_plugged_device_list();

    /* NVDIMM device is plugged. */

    if (device_list) {

        nvdimm_build_nfit(device_list, table_offsets, table_data, linker);

        g_slist_free(device_list);

    }

    /*

     * NVDIMM device is allowed to be plugged only if there is available

     * slot.

     */

    if (ram_slots) {

        nvdimm_build_ssdt(table_offsets, table_data, linker, dsm_dma_arrea,

                          ram_slots);

    }

}


int msmpeg4_decode_picture_header(MpegEncContext * s)

{

    int code;

#if 0

{

int i;

for(i=0; i<s->gb.size_in_bits; i++)

    printf("%d", get_bits1(&s->gb));

//    get_bits1(&s->gb);

printf("END\n");

#endif

    if(s->msmpeg4_version==1){

        int start_code, num;

        start_code = (get_bits(&s->gb, 16)<<16) | get_bits(&s->gb, 16);

        if(start_code!=0x00000100){

            fprintf(stderr, "invalid startcode\n");

        num= get_bits(&s->gb, 5); // frame number */

    s->pict_type = get_bits(&s->gb, 2) + 1;

    if (s->pict_type != I_TYPE &&

        s->pict_type != P_TYPE){

        fprintf(stderr, "invalid picture type\n");

#if 0

{

    static int had_i=0;

    if(s->pict_type == I_TYPE) had_i=1;

    if(!had_i) return -1;

#endif

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

    if (s->pict_type == I_TYPE) {

        code = get_bits(&s->gb, 5);

        if(s->msmpeg4_version==1){

            if(code==0 || code>s->mb_height){

                fprintf(stderr, "invalid slice height %d\n", code);

            s->slice_height = code;

        }else{

            /* 0x17: one slice, 0x18: two slices, ... */

            if (code < 0x17){

                fprintf(stderr, "error, slice code was %X\n", code);

            s->slice_height = s->mb_height / (code - 0x16);

        switch(s->msmpeg4_version){

        case 1:

        case 2:

            s->rl_chroma_table_index = 2;

            s->rl_table_index = 2;

            s->dc_table_index = 0; //not used

            break;

        case 3:

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

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

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

            break;

        case 4:

            msmpeg4_decode_ext_header(s, (2+5+5+17+7)/8);

            if(s->bit_rate > MBAC_BITRATE) s->per_mb_rl_table= get_bits1(&s->gb);

            else                           s->per_mb_rl_table= 0;

            if(!s->per_mb_rl_table){

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

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

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

            s->inter_intra_pred= 0;

            break;

        s->no_rounding = 1;

/*	printf("qscale:%d rlc:%d rl:%d dc:%d mbrl:%d slice:%d   \n",

		s->qscale,

		s->rl_chroma_table_index,

		s->rl_table_index,

		s->dc_table_index,

                s->per_mb_rl_table,

                s->slice_height);*/

    } else {

        switch(s->msmpeg4_version){

        case 1:

        case 2:

            if(s->msmpeg4_version==1)

                s->use_skip_mb_code = 1;

            else

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

            s->rl_table_index = 2;

            s->rl_chroma_table_index = s->rl_table_index;

            s->dc_table_index = 0; //not used

            s->mv_table_index = 0;

            break;

        case 3:

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

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

            s->rl_chroma_table_index = s->rl_table_index;

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

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

            break;

        case 4:

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

            if(s->bit_rate > MBAC_BITRATE) s->per_mb_rl_table= get_bits1(&s->gb);

            else                           s->per_mb_rl_table= 0;

            if(!s->per_mb_rl_table){

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

                s->rl_chroma_table_index = s->rl_table_index;

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

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

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

            break;

/*	printf("skip:%d rl:%d rlc:%d dc:%d mv:%d mbrl:%d qp:%d   \n",

		s->use_skip_mb_code,

		s->rl_table_index,

		s->rl_chroma_table_index,

		s->dc_table_index,

		s->mv_table_index,

                s->per_mb_rl_table,

                s->qscale);*/

	if(s->flipflop_rounding){

	    s->no_rounding ^= 1;

	}else{

	    s->no_rounding = 0;

//printf("%d %d %d %d %d\n", s->pict_type, s->bit_rate, s->inter_intra_pred, s->width, s->height);

    s->esc3_level_length= 0;

    s->esc3_run_length= 0;

#ifdef DEBUG

    printf("*****frame %d:\n", frame_count++);

#endif

    return 0;


int64_t qcow2_alloc_clusters(BlockDriverState *bs, int64_t size)

{

    int64_t offset;

    int ret;

    BLKDBG_EVENT(bs->file, BLKDBG_CLUSTER_ALLOC);

    offset = alloc_clusters_noref(bs, size);

    if (offset < 0) {

        return offset;

    }

    ret = update_refcount(bs, offset, size, 1, QCOW2_DISCARD_NEVER);

    if (ret < 0) {

        return ret;

    }

    return offset;

}


void vm_stop(int reason)

{

    do_vm_stop(reason);

}


int virtio_bus_device_plugged(VirtIODevice *vdev)

{

    DeviceState *qdev = DEVICE(vdev);

    BusState *qbus = BUS(qdev_get_parent_bus(qdev));

    VirtioBusState *bus = VIRTIO_BUS(qbus);

    VirtioBusClass *klass = VIRTIO_BUS_GET_CLASS(bus);

    VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(vdev);

    DPRINTF("%s: plug device.\n", qbus->name);

    if (klass->device_plugged != NULL) {

        klass->device_plugged(qbus->parent);

    }

    /* Get the features of the plugged device. */

    assert(vdc->get_features != NULL);

    vdev->host_features = vdc->get_features(vdev, vdev->host_features);

    return 0;

}


static int config_input_props(AVFilterLink *inlink)

{

    AVFilterContext *ctx = inlink->dst;

    Frei0rContext *s = ctx->priv;

    if (!(s->instance = s->construct(inlink->w, inlink->h))) {

        av_log(ctx, AV_LOG_ERROR, "Impossible to load frei0r instance");

        return AVERROR(EINVAL);

    }

    return set_params(ctx, s->params);

}


int qdev_prop_check_globals(void)

{

    GlobalProperty *prop;

    int ret = 0;

    QTAILQ_FOREACH(prop, &global_props, next) {

        ObjectClass *oc;

        DeviceClass *dc;

        if (prop->used) {

            continue;

        }

        if (!prop->user_provided) {

            continue;

        }

        oc = object_class_by_name(prop->driver);

        oc = object_class_dynamic_cast(oc, TYPE_DEVICE);

        if (!oc) {

            error_report("Warning: global %s.%s has invalid class name",

                       prop->driver, prop->property);

            ret = 1;

            continue;

        }

        dc = DEVICE_CLASS(oc);

        if (!dc->hotpluggable && !prop->used) {

            error_report("Warning: global %s.%s=%s not used",

                       prop->driver, prop->property, prop->value);

            ret = 1;

            continue;

        }

    }

    return ret;

}


static inline void RENAME(rgb32ToUV)(uint8_t *dstU, uint8_t *dstV, uint8_t *src1, uint8_t *src2, int width)

{

	int i;

        assert(src1==src2);

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

	{

		const int a= ((uint32_t*)src1)[2*i+0];

		const int e= ((uint32_t*)src1)[2*i+1];

		const int l= (a&0xFF00FF) + (e&0xFF00FF);

		const int h= (a&0x00FF00) + (e&0x00FF00);

 		const int r=  l&0x3FF;

		const int g=  h>>8;

		const int b=  l>>16;

		dstU[i]= ((RU*r + GU*g + BU*b)>>(RGB2YUV_SHIFT+1)) + 128;

		dstV[i]= ((RV*r + GV*g + BV*b)>>(RGB2YUV_SHIFT+1)) + 128;

	}

}


static av_cold void init_vlcs(FourXContext *f)

{

    static VLC_TYPE table[8][32][2];

    int i;

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

        block_type_vlc[0][i].table           = table[i];

        block_type_vlc[0][i].table_allocated = 32;

        init_vlc(&block_type_vlc[0][i], BLOCK_TYPE_VLC_BITS, 7,

                 &block_type_tab[0][i][0][1], 2, 1,

                 &block_type_tab[0][i][0][0], 2, 1, INIT_VLC_USE_NEW_STATIC);

    }

}


static BlockAIOCB *blkverify_aio_writev(BlockDriverState *bs,

        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,

        BlockCompletionFunc *cb, void *opaque)

{

    BDRVBlkverifyState *s = bs->opaque;

    BlkverifyAIOCB *acb = blkverify_aio_get(bs, true, sector_num, qiov,

                                            nb_sectors, cb, opaque);

    bdrv_aio_writev(s->test_file, sector_num, qiov, nb_sectors,

                    blkverify_aio_cb, acb);

    bdrv_aio_writev(bs->file, sector_num, qiov, nb_sectors,

                    blkverify_aio_cb, acb);

    return &acb->common;

}


static int coroutine_fn bdrv_driver_preadv(BlockDriverState *bs,
                                           uint64_t offset, uint64_t bytes,
                                           QEMUIOVector *qiov, int flags)
{
    BlockDriver *drv = bs->drv;
    int64_t sector_num;
    unsigned int nb_sectors;
    if (drv->bdrv_co_preadv) {
        return drv->bdrv_co_preadv(bs, offset, bytes, qiov, flags);
    }
    sector_num = offset >> BDRV_SECTOR_BITS;
    nb_sectors = bytes >> BDRV_SECTOR_BITS;
    assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
    assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
    assert((bytes >> BDRV_SECTOR_BITS) <= BDRV_REQUEST_MAX_SECTORS);
    if (drv->bdrv_co_readv) {
        return drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
    } else {
        BlockAIOCB *acb;
        CoroutineIOCompletion co = {
            .coroutine = qemu_coroutine_self(),
        };
        acb = bs->drv->bdrv_aio_readv(bs, sector_num, qiov, nb_sectors,
                                      bdrv_co_io_em_complete, &co);
        if (acb == NULL) {
            return -EIO;
        } else {
            qemu_coroutine_yield();
            return co.ret;
        }
    }
}


static void bdrv_close(BlockDriverState *bs)

{

    BdrvAioNotifier *ban, *ban_next;

    assert(!bs->job);

    assert(!bs->refcnt);

    bdrv_drained_begin(bs); /* complete I/O */

    bdrv_flush(bs);

    bdrv_drain(bs); /* in case flush left pending I/O */

    if (bs->drv) {

        BdrvChild *child, *next;

        bs->drv->bdrv_close(bs);

        bs->drv = NULL;

        bdrv_set_backing_hd(bs, NULL, &error_abort);

        if (bs->file != NULL) {

            bdrv_unref_child(bs, bs->file);

            bs->file = NULL;

        }

        QLIST_FOREACH_SAFE(child, &bs->children, next, next) {

            /* TODO Remove bdrv_unref() from drivers' close function and use

             * bdrv_unref_child() here */

            if (child->bs->inherits_from == bs) {

                child->bs->inherits_from = NULL;

            }

            bdrv_detach_child(child);

        }

        g_free(bs->opaque);

        bs->opaque = NULL;

        atomic_set(&bs->copy_on_read, 0);

        bs->backing_file[0] = '\0';

        bs->backing_format[0] = '\0';

        bs->total_sectors = 0;

        bs->encrypted = false;

        bs->sg = false;

        QDECREF(bs->options);

        QDECREF(bs->explicit_options);

        bs->options = NULL;

        bs->explicit_options = NULL;

        QDECREF(bs->full_open_options);

        bs->full_open_options = NULL;

    }

    bdrv_release_named_dirty_bitmaps(bs);

    assert(QLIST_EMPTY(&bs->dirty_bitmaps));

    QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {

        g_free(ban);

    }

    QLIST_INIT(&bs->aio_notifiers);

    bdrv_drained_end(bs);

}


static void kvm_add_routing_entry(KVMState *s,

                                  struct kvm_irq_routing_entry *entry)

{

    struct kvm_irq_routing_entry *new;

    int n, size;

    if (s->irq_routes->nr == s->nr_allocated_irq_routes) {

        n = s->nr_allocated_irq_routes * 2;

        if (n < 64) {

            n = 64;

        }

        size = sizeof(struct kvm_irq_routing);

        size += n * sizeof(*new);

        s->irq_routes = g_realloc(s->irq_routes, size);

        s->nr_allocated_irq_routes = n;

    }

    n = s->irq_routes->nr++;

    new = &s->irq_routes->entries[n];

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

    new->gsi = entry->gsi;

    new->type = entry->type;

    new->flags = entry->flags;

    new->u = entry->u;

    set_gsi(s, entry->gsi);

}


PCA *ff_pca_init(int n){
    PCA *pca;
    if(n<=0)
    pca= av_mallocz(sizeof(*pca));
    pca->n= n;
    pca->z = av_malloc_array(n, sizeof(*pca->z));
    pca->count=0;
    pca->covariance= av_calloc(n*n, sizeof(double));
    pca->mean= av_calloc(n, sizeof(double));
    return pca;


static int nuv_header(AVFormatContext *s)

{

    NUVContext *ctx = s->priv_data;

    AVIOContext *pb = s->pb;

    char id_string[12];

    double aspect, fps;

    int is_mythtv, width, height, v_packs, a_packs, ret;

    AVStream *vst = NULL, *ast = NULL;

    avio_read(pb, id_string, 12);

    is_mythtv = !memcmp(id_string, "MythTVVideo", 12);

    avio_skip(pb, 5);       // version string

    avio_skip(pb, 3);       // padding

    width  = avio_rl32(pb);

    height = avio_rl32(pb);

    avio_rl32(pb);          // unused, "desiredwidth"

    avio_rl32(pb);          // unused, "desiredheight"

    avio_r8(pb);            // 'P' == progressive, 'I' == interlaced

    avio_skip(pb, 3);       // padding

    aspect = av_int2double(avio_rl64(pb));

    if (aspect > 0.9999 && aspect < 1.0001)

        aspect = 4.0 / 3.0;

    fps = av_int2double(avio_rl64(pb));

    if (fps < 0.0f) {

        if (s->error_recognition & AV_EF_EXPLODE) {

            av_log(s, AV_LOG_ERROR, "Invalid frame rate %f\n", fps);

            return AVERROR_INVALIDDATA;

        } else {

            av_log(s, AV_LOG_WARNING, "Invalid frame rate %f, setting to 0.\n", fps);

            fps = 0.0f;

        }

    }

    // number of packets per stream type, -1 means unknown, e.g. streaming

    v_packs = avio_rl32(pb);

    a_packs = avio_rl32(pb);

    avio_rl32(pb); // text

    avio_rl32(pb); // keyframe distance (?)

    if (v_packs) {

        vst = avformat_new_stream(s, NULL);

        if (!vst)

            return AVERROR(ENOMEM);

        ctx->v_id = vst->index;

        ret = av_image_check_size(width, height, 0, s);

        if (ret < 0)

            return ret;

        vst->codecpar->codec_type            = AVMEDIA_TYPE_VIDEO;

        vst->codecpar->codec_id              = AV_CODEC_ID_NUV;

        vst->codecpar->width                 = width;

        vst->codecpar->height                = height;

        vst->codecpar->bits_per_coded_sample = 10;

        vst->sample_aspect_ratio          = av_d2q(aspect * height / width,

                                                   10000);

#if FF_API_R_FRAME_RATE

        vst->r_frame_rate =

#endif

        vst->avg_frame_rate = av_d2q(fps, 60000);

        avpriv_set_pts_info(vst, 32, 1, 1000);

    } else

        ctx->v_id = -1;

    if (a_packs) {

        ast = avformat_new_stream(s, NULL);

        if (!ast)

            return AVERROR(ENOMEM);

        ctx->a_id = ast->index;

        ast->codecpar->codec_type            = AVMEDIA_TYPE_AUDIO;

        ast->codecpar->codec_id              = AV_CODEC_ID_PCM_S16LE;

        ast->codecpar->channels              = 2;

        ast->codecpar->channel_layout        = AV_CH_LAYOUT_STEREO;

        ast->codecpar->sample_rate           = 44100;

        ast->codecpar->bit_rate              = 2 * 2 * 44100 * 8;

        ast->codecpar->block_align           = 2 * 2;

        ast->codecpar->bits_per_coded_sample = 16;

        avpriv_set_pts_info(ast, 32, 1, 1000);

    } else

        ctx->a_id = -1;

    if ((ret = get_codec_data(pb, vst, ast, is_mythtv)) < 0)

        return ret;

    ctx->rtjpg_video = vst && vst->codecpar->codec_id == AV_CODEC_ID_NUV;

    return 0;

}


setup_return(CPUARMState *env, struct target_sigaction *ka,

	     abi_ulong *rc, abi_ulong frame_addr, int usig, abi_ulong rc_addr)

{

	abi_ulong handler = ka->_sa_handler;

	abi_ulong retcode;

	int thumb = handler & 1;

	uint32_t cpsr = cpsr_read(env);

	cpsr &= ~CPSR_IT;

	if (thumb) {

		cpsr |= CPSR_T;

	} else {

		cpsr &= ~CPSR_T;

	}

	if (ka->sa_flags & TARGET_SA_RESTORER) {

		retcode = ka->sa_restorer;

	} else {

		unsigned int idx = thumb;

		if (ka->sa_flags & TARGET_SA_SIGINFO)

			idx += 2;

		if (__put_user(retcodes[idx], rc))

			return 1;

		retcode = rc_addr + thumb;

	}

	env->regs[0] = usig;

	env->regs[13] = frame_addr;

	env->regs[14] = retcode;

	env->regs[15] = handler & (thumb ? ~1 : ~3);

	cpsr_write(env, cpsr, 0xffffffff);

	return 0;

}


static void floor_fit(vorbis_enc_context *venc, vorbis_enc_floor *fc,

                      float *coeffs, uint_fast16_t *posts, int samples)

{

    int range = 255 / fc->multiplier + 1;

    int i;

    float tot_average = 0.;

    float averages[fc->values];

    for (i = 0; i < fc->values; i++) {

        averages[i] = get_floor_average(fc, coeffs, i);

        tot_average += averages[i];

    }

    tot_average /= fc->values;

    tot_average /= venc->quality;

    for (i = 0; i < fc->values; i++) {

        int position  = fc->list[fc->list[i].sort].x;

        float average = averages[i];

        int j;

        average *= pow(tot_average / average, 0.5) * pow(1.25, position/200.); // MAGIC!

        for (j = 0; j < range - 1; j++)

            if (ff_vorbis_floor1_inverse_db_table[j * fc->multiplier] > average)

                break;

        posts[fc->list[i].sort] = j;

    }

}


void av_destruct_packet(AVPacket *pkt)

{

    int i;

    av_free(pkt->data);

    pkt->data = NULL; pkt->size = 0;

    for (i = 0; i < pkt->side_data_elems; i++)

        av_free(pkt->side_data[i].data);

    av_freep(&pkt->side_data);

    pkt->side_data_elems = 0;

}


GuestFileWrite *qmp_guest_file_write(int64_t handle, const char *buf_b64,

                                     bool has_count, int64_t count,

                                     Error **errp)

{

    GuestFileWrite *write_data = NULL;

    guchar *buf;

    gsize buf_len;

    int write_count;

    GuestFileHandle *gfh = guest_file_handle_find(handle, errp);

    FILE *fh;

    if (!gfh) {

        return NULL;

    }

    fh = gfh->fh;

    buf = g_base64_decode(buf_b64, &buf_len);

    if (!has_count) {

        count = buf_len;

    } else if (count < 0 || count > buf_len) {

        error_setg(errp, "value '%" PRId64 "' is invalid for argument count",

                   count);

        g_free(buf);

        return NULL;

    }

    write_count = fwrite(buf, 1, count, fh);

    if (ferror(fh)) {

        error_setg_errno(errp, errno, "failed to write to file");

        slog("guest-file-write failed, handle: %" PRId64, handle);

    } else {

        write_data = g_malloc0(sizeof(GuestFileWrite));

        write_data->count = write_count;

        write_data->eof = feof(fh);

    }

    g_free(buf);

    clearerr(fh);

    return write_data;

}


static int rtp_parse_mp4_au(RTPDemuxContext *s, const uint8_t *buf)

{

    int au_headers_length, au_header_size, i;

    GetBitContext getbitcontext;

    RTPPayloadData *infos;

    infos = s->rtp_payload_data;

    if (infos == NULL)

        return -1;

    /* decode the first 2 bytes where the AUHeader sections are stored

       length in bits */

    au_headers_length = AV_RB16(buf);

    if (au_headers_length > RTP_MAX_PACKET_LENGTH)

      return -1;

    infos->au_headers_length_bytes = (au_headers_length + 7) / 8;

    /* skip AU headers length section (2 bytes) */

    buf += 2;

    init_get_bits(&getbitcontext, buf, infos->au_headers_length_bytes * 8);

    /* XXX: Wrong if optionnal additional sections are present (cts, dts etc...) */

    au_header_size = infos->sizelength + infos->indexlength;

    if (au_header_size <= 0 || (au_headers_length % au_header_size != 0))

        return -1;

    infos->nb_au_headers = au_headers_length / au_header_size;

    infos->au_headers = av_malloc(sizeof(struct AUHeaders) * infos->nb_au_headers);

    /* XXX: We handle multiple AU Section as only one (need to fix this for interleaving)

       In my test, the FAAD decoder does not behave correctly when sending each AU one by one

       but does when sending the whole as one big packet...  */

    infos->au_headers[0].size = 0;

    infos->au_headers[0].index = 0;

    for (i = 0; i < infos->nb_au_headers; ++i) {

        infos->au_headers[0].size += get_bits_long(&getbitcontext, infos->sizelength);

        infos->au_headers[0].index = get_bits_long(&getbitcontext, infos->indexlength);

    infos->nb_au_headers = 1;

    return 0;