static int aarch64_tr_init_disas_context(DisasContextBase *dcbase,

                                         CPUState *cpu, int max_insns)

{

    DisasContext *dc = container_of(dcbase, DisasContext, base);

    CPUARMState *env = cpu->env_ptr;

    ARMCPU *arm_cpu = arm_env_get_cpu(env);

    dc->pc = dc->base.pc_first;

    dc->condjmp = 0;

    dc->aarch64 = 1;

    /* If we are coming from secure EL0 in a system with a 32-bit EL3, then

     * there is no secure EL1, so we route exceptions to EL3.

     */

    dc->secure_routed_to_el3 = arm_feature(env, ARM_FEATURE_EL3) &&

                               !arm_el_is_aa64(env, 3);

    dc->thumb = 0;

    dc->sctlr_b = 0;

    dc->be_data = ARM_TBFLAG_BE_DATA(dc->base.tb->flags) ? MO_BE : MO_LE;

    dc->condexec_mask = 0;

    dc->condexec_cond = 0;

    dc->mmu_idx = core_to_arm_mmu_idx(env, ARM_TBFLAG_MMUIDX(dc->base.tb->flags));

    dc->tbi0 = ARM_TBFLAG_TBI0(dc->base.tb->flags);

    dc->tbi1 = ARM_TBFLAG_TBI1(dc->base.tb->flags);

    dc->current_el = arm_mmu_idx_to_el(dc->mmu_idx);

#if !defined(CONFIG_USER_ONLY)

    dc->user = (dc->current_el == 0);

#endif

    dc->fp_excp_el = ARM_TBFLAG_FPEXC_EL(dc->base.tb->flags);

    dc->vec_len = 0;

    dc->vec_stride = 0;

    dc->cp_regs = arm_cpu->cp_regs;

    dc->features = env->features;

    /* Single step state. The code-generation logic here is:

     *  SS_ACTIVE == 0:

     *   generate code with no special handling for single-stepping (except

     *   that anything that can make us go to SS_ACTIVE == 1 must end the TB;

     *   this happens anyway because those changes are all system register or

     *   PSTATE writes).

     *  SS_ACTIVE == 1, PSTATE.SS == 1: (active-not-pending)

     *   emit code for one insn

     *   emit code to clear PSTATE.SS

     *   emit code to generate software step exception for completed step

     *   end TB (as usual for having generated an exception)

     *  SS_ACTIVE == 1, PSTATE.SS == 0: (active-pending)

     *   emit code to generate a software step exception

     *   end the TB

     */

    dc->ss_active = ARM_TBFLAG_SS_ACTIVE(dc->base.tb->flags);

    dc->pstate_ss = ARM_TBFLAG_PSTATE_SS(dc->base.tb->flags);

    dc->is_ldex = false;

    dc->ss_same_el = (arm_debug_target_el(env) == dc->current_el);

    dc->next_page_start =

        (dc->base.pc_first & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE;

    init_tmp_a64_array(dc);

    return max_insns;

}


static void monitor_print_error(Monitor *mon)

{

    qerror_print(mon->error);

    QDECREF(mon->error);

    mon->error = NULL;

}


void nvdimm_build_acpi(GArray *table_offsets, GArray *table_data,

                       GArray *linker)

{

    GSList *device_list;

    /* no NVDIMM device is plugged. */

    device_list = nvdimm_get_plugged_device_list();

    if (!device_list) {

        return;

    }

    nvdimm_build_nfit(device_list, table_offsets, table_data, linker);

    nvdimm_build_ssdt(device_list, table_offsets, table_data, linker);

    g_slist_free(device_list);

}


static void qio_channel_websock_handshake_process(QIOChannelWebsock *ioc,

                                                  char *buffer,

                                                  Error **errp)

{

    QIOChannelWebsockHTTPHeader hdrs[32];

    size_t nhdrs = G_N_ELEMENTS(hdrs);

    const char *protocols = NULL, *version = NULL, *key = NULL,

        *host = NULL, *connection = NULL, *upgrade = NULL;

    nhdrs = qio_channel_websock_extract_headers(ioc, buffer, hdrs, nhdrs, errp);

    if (!nhdrs) {

        return;

    }

    protocols = qio_channel_websock_find_header(

        hdrs, nhdrs, QIO_CHANNEL_WEBSOCK_HEADER_PROTOCOL);

    if (!protocols) {

        error_setg(errp, "Missing websocket protocol header data");

        goto bad_request;

    }

    version = qio_channel_websock_find_header(

        hdrs, nhdrs, QIO_CHANNEL_WEBSOCK_HEADER_VERSION);

    if (!version) {

        error_setg(errp, "Missing websocket version header data");

        goto bad_request;

    }

    key = qio_channel_websock_find_header(

        hdrs, nhdrs, QIO_CHANNEL_WEBSOCK_HEADER_KEY);

    if (!key) {

        error_setg(errp, "Missing websocket key header data");

        goto bad_request;

    }

    host = qio_channel_websock_find_header(

        hdrs, nhdrs, QIO_CHANNEL_WEBSOCK_HEADER_HOST);

    if (!host) {

        error_setg(errp, "Missing websocket host header data");

        goto bad_request;

    }

    connection = qio_channel_websock_find_header(

        hdrs, nhdrs, QIO_CHANNEL_WEBSOCK_HEADER_CONNECTION);

    if (!connection) {

        error_setg(errp, "Missing websocket connection header data");

        goto bad_request;

    }

    upgrade = qio_channel_websock_find_header(

        hdrs, nhdrs, QIO_CHANNEL_WEBSOCK_HEADER_UPGRADE);

    if (!upgrade) {

        error_setg(errp, "Missing websocket upgrade header data");

        goto bad_request;

    }

    if (!g_strrstr(protocols, QIO_CHANNEL_WEBSOCK_PROTOCOL_BINARY)) {

        error_setg(errp, "No '%s' protocol is supported by client '%s'",

                   QIO_CHANNEL_WEBSOCK_PROTOCOL_BINARY, protocols);

        goto bad_request;

    }

    if (!g_str_equal(version, QIO_CHANNEL_WEBSOCK_SUPPORTED_VERSION)) {

        error_setg(errp, "Version '%s' is not supported by client '%s'",

                   QIO_CHANNEL_WEBSOCK_SUPPORTED_VERSION, version);

        goto bad_request;

    }

    if (strlen(key) != QIO_CHANNEL_WEBSOCK_CLIENT_KEY_LEN) {

        error_setg(errp, "Key length '%zu' was not as expected '%d'",

                   strlen(key), QIO_CHANNEL_WEBSOCK_CLIENT_KEY_LEN);

        goto bad_request;

    }

    if (!g_strrstr(connection, QIO_CHANNEL_WEBSOCK_CONNECTION_UPGRADE)) {

        error_setg(errp, "No connection upgrade requested '%s'", connection);

        goto bad_request;

    }

    if (!g_str_equal(upgrade, QIO_CHANNEL_WEBSOCK_UPGRADE_WEBSOCKET)) {

        error_setg(errp, "Incorrect upgrade method '%s'", upgrade);

        goto bad_request;

    }

    qio_channel_websock_handshake_send_res_ok(ioc, key, errp);

    return;

 bad_request:

    qio_channel_websock_handshake_send_res_err(

        ioc, QIO_CHANNEL_WEBSOCK_HANDSHAKE_RES_BAD_REQUEST);

}


uint16_t css_build_subchannel_id(SubchDev *sch)

{

    if (channel_subsys.max_cssid > 0) {

        return (sch->cssid << 8) | (1 << 3) | (sch->ssid << 1) | 1;

    }

    return (sch->ssid << 1) | 1;

}


void aio_bh_call(QEMUBH *bh)

{

    bh->cb(bh->opaque);

}


static void gd_connect_signals(GtkDisplayState *s)

{

    g_signal_connect(s->show_tabs_item, "activate",

                     G_CALLBACK(gd_menu_show_tabs), s);

    g_signal_connect(s->window, "key-press-event",

                     G_CALLBACK(gd_window_key_event), s);

    g_signal_connect(s->window, "delete-event",

                     G_CALLBACK(gd_window_close), s);

#if GTK_CHECK_VERSION(3, 0, 0)

    g_signal_connect(s->drawing_area, "draw",

                     G_CALLBACK(gd_draw_event), s);

#else

    g_signal_connect(s->drawing_area, "expose-event",

                     G_CALLBACK(gd_expose_event), s);

#endif

    g_signal_connect(s->drawing_area, "motion-notify-event",

                     G_CALLBACK(gd_motion_event), s);

    g_signal_connect(s->drawing_area, "button-press-event",

                     G_CALLBACK(gd_button_event), s);

    g_signal_connect(s->drawing_area, "button-release-event",

                     G_CALLBACK(gd_button_event), s);

    g_signal_connect(s->drawing_area, "scroll-event",

                     G_CALLBACK(gd_scroll_event), s);

    g_signal_connect(s->drawing_area, "key-press-event",

                     G_CALLBACK(gd_key_event), s);

    g_signal_connect(s->drawing_area, "key-release-event",

                     G_CALLBACK(gd_key_event), s);

    g_signal_connect(s->pause_item, "activate",

                     G_CALLBACK(gd_menu_pause), s);

    g_signal_connect(s->reset_item, "activate",

                     G_CALLBACK(gd_menu_reset), s);

    g_signal_connect(s->powerdown_item, "activate",

                     G_CALLBACK(gd_menu_powerdown), s);

    g_signal_connect(s->quit_item, "activate",

                     G_CALLBACK(gd_menu_quit), s);

    g_signal_connect(s->full_screen_item, "activate",

                     G_CALLBACK(gd_menu_full_screen), s);

    g_signal_connect(s->zoom_in_item, "activate",

                     G_CALLBACK(gd_menu_zoom_in), s);

    g_signal_connect(s->zoom_out_item, "activate",

                     G_CALLBACK(gd_menu_zoom_out), s);

    g_signal_connect(s->zoom_fixed_item, "activate",

                     G_CALLBACK(gd_menu_zoom_fixed), s);

    g_signal_connect(s->zoom_fit_item, "activate",

                     G_CALLBACK(gd_menu_zoom_fit), s);

    g_signal_connect(s->vga_item, "activate",

                     G_CALLBACK(gd_menu_switch_vc), s);

    g_signal_connect(s->grab_item, "activate",

                     G_CALLBACK(gd_menu_grab_input), s);

    g_signal_connect(s->notebook, "switch-page",

                     G_CALLBACK(gd_change_page), s);

    g_signal_connect(s->drawing_area, "enter-notify-event",

                     G_CALLBACK(gd_enter_event), s);

    g_signal_connect(s->drawing_area, "leave-notify-event",

                     G_CALLBACK(gd_leave_event), s);

    g_signal_connect(s->drawing_area, "focus-out-event",

                     G_CALLBACK(gd_focus_out_event), s);

}


int ff_v4l2_context_set_status(V4L2Context* ctx, int cmd)

{

    int type = ctx->type;

    int ret;

    ret = ioctl(ctx_to_m2mctx(ctx)->fd, cmd, &type);

    if (ret < 0)

        return AVERROR(errno);

    ctx->streamon = (cmd == VIDIOC_STREAMON);

    return 0;

}


static void scoop_writeb(void *opaque, target_phys_addr_t addr, uint32_t value)

{

    ScoopInfo *s = (ScoopInfo *) opaque;

    value &= 0xffff;

    switch (addr) {

    case SCOOP_MCR:

        s->mcr = value;

        break;

    case SCOOP_CDR:

        s->cdr = value;

        break;

    case SCOOP_CPR:

        s->power = value;

        if (value & 0x80)

            s->power |= 0x8040;

        break;

    case SCOOP_CCR:

        s->ccr = value;

        break;

    case SCOOP_IRR_IRM:

        s->irr = value;

        break;

    case SCOOP_IMR:

        s->imr = value;

        break;

    case SCOOP_ISR:

        s->isr = value;

        break;

    case SCOOP_GPCR:

        s->gpio_dir = value;

        scoop_gpio_handler_update(s);

        break;

    case SCOOP_GPWR:

    case SCOOP_GPRR:	/* GPRR is probably R/O in real HW */

        s->gpio_level = value & s->gpio_dir;

        scoop_gpio_handler_update(s);

        break;

    default:

        zaurus_printf("Bad register offset " REG_FMT "\n", (unsigned long)addr);

    }

}


static int proxy_lsetxattr(FsContext *ctx, V9fsPath *fs_path, const char *name,

                           void *value, size_t size, int flags)

{

    int retval;

    V9fsString xname, xvalue;

    v9fs_string_init(&xname);

    v9fs_string_sprintf(&xname, "%s", name);

    v9fs_string_init(&xvalue);

    xvalue.size = size;

    xvalue.data = g_malloc(size);

    memcpy(xvalue.data, value, size);

    retval = v9fs_request(ctx->private, T_LSETXATTR, value, "sssdd",

                          fs_path, &xname, &xvalue, size, flags);

    v9fs_string_free(&xname);

    v9fs_string_free(&xvalue);

    if (retval < 0) {

        errno = -retval;

    }

    return retval;

}


static int usb_host_claim_interfaces(USBHostDevice *dev, int configuration)

{

    int dev_descr_len, config_descr_len;

    int interface, nb_interfaces;

    int ret, i;

    if (configuration == 0) /* address state - ignore */

        return 1;

    DPRINTF("husb: claiming interfaces. config %d\n", configuration);

    i = 0;

    dev_descr_len = dev->descr[0];

    if (dev_descr_len > dev->descr_len) {

        goto fail;

    }

    i += dev_descr_len;

    while (i < dev->descr_len) {

        DPRINTF("husb: i is %d, descr_len is %d, dl %d, dt %d\n",

                i, dev->descr_len,

               dev->descr[i], dev->descr[i+1]);

        if (dev->descr[i+1] != USB_DT_CONFIG) {

            i += dev->descr[i];

            continue;

        }

        config_descr_len = dev->descr[i];

        printf("husb: config #%d need %d\n", dev->descr[i + 5], configuration);

        if (configuration < 0 || configuration == dev->descr[i + 5]) {

            configuration = dev->descr[i + 5];

            break;

        }

        i += config_descr_len;

    }

    if (i >= dev->descr_len) {

        fprintf(stderr,

                "husb: update iface failed. no matching configuration\n");

        goto fail;

    }

    nb_interfaces = dev->descr[i + 4];

#ifdef USBDEVFS_DISCONNECT

    /* earlier Linux 2.4 do not support that */

    {

        struct usbdevfs_ioctl ctrl;

        for (interface = 0; interface < nb_interfaces; interface++) {

            ctrl.ioctl_code = USBDEVFS_DISCONNECT;

            ctrl.ifno = interface;

            ctrl.data = 0;

            ret = ioctl(dev->fd, USBDEVFS_IOCTL, &ctrl);

            if (ret < 0 && errno != ENODATA) {

                perror("USBDEVFS_DISCONNECT");

                goto fail;

            }

        }

    }

#endif

    /* XXX: only grab if all interfaces are free */

    for (interface = 0; interface < nb_interfaces; interface++) {

        ret = ioctl(dev->fd, USBDEVFS_CLAIMINTERFACE, &interface);

        if (ret < 0) {

            if (errno == EBUSY) {

                printf("husb: update iface. device already grabbed\n");

            } else {

                perror("husb: failed to claim interface");

            }

        fail:

            return 0;

        }

    }

    printf("husb: %d interfaces claimed for configuration %d\n",

           nb_interfaces, configuration);

    dev->ninterfaces   = nb_interfaces;

    dev->configuration = configuration;

    return 1;

}


static void rtas_nvram_store(sPAPREnvironment *spapr,

                             uint32_t token, uint32_t nargs,

                             target_ulong args,

                             uint32_t nret, target_ulong rets)

{

    sPAPRNVRAM *nvram = spapr->nvram;

    hwaddr offset, buffer, len;

    int alen;

    void *membuf;

    if ((nargs != 3) || (nret != 2)) {

        rtas_st(rets, 0, -3);

        return;

    }

    if (!nvram) {

        rtas_st(rets, 0, -1);

        return;

    }

    offset = rtas_ld(args, 0);

    buffer = rtas_ld(args, 1);

    len = rtas_ld(args, 2);

    if (((offset + len) < offset)

        || ((offset + len) > nvram->size)) {

        rtas_st(rets, 0, -3);

        return;

    }

    membuf = cpu_physical_memory_map(buffer, &len, 0);

    if (nvram->drive) {

        alen = bdrv_pwrite(nvram->drive, offset, membuf, len);

    } else {

        assert(nvram->buf);

        memcpy(nvram->buf + offset, membuf, len);

        alen = len;

    }

    cpu_physical_memory_unmap(membuf, len, 0, len);

    rtas_st(rets, 0, (alen < len) ? -1 : 0);

    rtas_st(rets, 1, (alen < 0) ? 0 : alen);

}


static bool sd_get_inserted(SDState *sd)

{

    return blk_is_inserted(sd->blk);

}


uint32_t helper_efdctsi (uint64_t val)

{

    CPU_DoubleU u;

    u.ll = val;

    /* NaN are not treated the same way IEEE 754 does */

    if (unlikely(float64_is_nan(u.d)))

        return 0;

    return float64_to_int32(u.d, &env->vec_status);

}


target_ulong helper_yield(target_ulong arg1)

{

    if (arg1 < 0) {

        /* No scheduling policy implemented. */

        if (arg1 != -2) {

            if (env->CP0_VPEControl & (1 << CP0VPECo_YSI) &&

                env->active_tc.CP0_TCStatus & (1 << CP0TCSt_DT)) {

                env->CP0_VPEControl &= ~(0x7 << CP0VPECo_EXCPT);

                env->CP0_VPEControl |= 4 << CP0VPECo_EXCPT;

                helper_raise_exception(EXCP_THREAD);

            }

        }

    } else if (arg1 == 0) {

        if (0 /* TODO: TC underflow */) {

            env->CP0_VPEControl &= ~(0x7 << CP0VPECo_EXCPT);

            helper_raise_exception(EXCP_THREAD);

        } else {

            // TODO: Deallocate TC

        }

    } else if (arg1 > 0) {

        /* Yield qualifier inputs not implemented. */

        env->CP0_VPEControl &= ~(0x7 << CP0VPECo_EXCPT);

        env->CP0_VPEControl |= 2 << CP0VPECo_EXCPT;

        helper_raise_exception(EXCP_THREAD);

    }

    return env->CP0_YQMask;

}


static int lag_read_prob_header(lag_rac *rac, GetBitContext *gb)

{

    int i, j, scale_factor;

    unsigned prob, cumulative_target;

    unsigned cumul_prob = 0;

    unsigned scaled_cumul_prob = 0;

    rac->prob[0] = 0;

    rac->prob[257] = UINT_MAX;

    /* Read probabilities from bitstream */

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

        if (lag_decode_prob(gb, &rac->prob[i]) < 0) {

            av_log(rac->avctx, AV_LOG_ERROR, "Invalid probability encountered.\n");

            return -1;

        }

        if ((uint64_t)cumul_prob + rac->prob[i] > UINT_MAX) {

            av_log(rac->avctx, AV_LOG_ERROR, "Integer overflow encountered in cumulative probability calculation.\n");

            return -1;

        }

        cumul_prob += rac->prob[i];

        if (!rac->prob[i]) {

            if (lag_decode_prob(gb, &prob)) {

                av_log(rac->avctx, AV_LOG_ERROR, "Invalid probability run encountered.\n");

                return -1;

            }

            if (prob > 257 - i)

                prob = 257 - i;

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

                rac->prob[++i] = 0;

        }

    }

    if (!cumul_prob) {

        av_log(rac->avctx, AV_LOG_ERROR, "All probabilities are 0!\n");

        return -1;

    }

    /* Scale probabilities so cumulative probability is an even power of 2. */

    scale_factor = av_log2(cumul_prob);

    if (cumul_prob & (cumul_prob - 1)) {

        uint64_t mul = softfloat_reciprocal(cumul_prob);

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

            rac->prob[i] = softfloat_mul(rac->prob[i], mul);

            scaled_cumul_prob += rac->prob[i];

        }

        scale_factor++;

        cumulative_target = 1 << scale_factor;

        if (scaled_cumul_prob > cumulative_target) {

            av_log(rac->avctx, AV_LOG_ERROR,

                   "Scaled probabilities are larger than target!\n");

            return -1;

        }

        scaled_cumul_prob = cumulative_target - scaled_cumul_prob;

        for (i = 1; scaled_cumul_prob; i = (i & 0x7f) + 1) {

            if (rac->prob[i]) {

                rac->prob[i]++;

                scaled_cumul_prob--;

            }

            /* Comment from reference source:

             * if (b & 0x80 == 0) {     // order of operations is 'wrong'; it has been left this way

             *                          // since the compression change is negligable and fixing it

             *                          // breaks backwards compatibility

             *      b =- (signed int)b;

             *      b &= 0xFF;

             * } else {

             *      b++;

             *      b &= 0x7f;

             * }

             */

        }

    }

    rac->scale = scale_factor;

    /* Fill probability array with cumulative probability for each symbol. */

    for (i = 1; i < 257; i++)

        rac->prob[i] += rac->prob[i - 1];

    return 0;

}


MemTxResult gicv3_redist_read(void *opaque, hwaddr offset, uint64_t *data,
                              unsigned size, MemTxAttrs attrs)
{
    GICv3State *s = opaque;
    GICv3CPUState *cs;
    MemTxResult r;
    int cpuidx;
    /* This region covers all the redistributor pages; there are
     * (for GICv3) two 64K pages per CPU. At the moment they are
     * all contiguous (ie in this one region), though we might later
     * want to allow splitting of redistributor pages into several
     * blocks so we can support more CPUs.
     */
    cpuidx = offset / 0x20000;
    offset %= 0x20000;
    assert(cpuidx < s->num_cpu);
    cs = &s->cpu[cpuidx];
    switch (size) {
    case 1:
        r = gicr_readb(cs, offset, data, attrs);
        break;
    case 4:
        r = gicr_readl(cs, offset, data, attrs);
        break;
    case 8:
        r = gicr_readll(cs, offset, data, attrs);
        break;
    default:
        r = MEMTX_ERROR;
        break;
    }
    if (r == MEMTX_ERROR) {
        qemu_log_mask(LOG_GUEST_ERROR,
                      "%s: invalid guest read at offset " TARGET_FMT_plx
                      "size %u\n", __func__, offset, size);
        trace_gicv3_redist_badread(gicv3_redist_affid(cs), offset,
                                   size, attrs.secure);
    } else {
        trace_gicv3_redist_read(gicv3_redist_affid(cs), offset, *data,
                                size, attrs.secure);
    }
    return r;
}


uint32_t av_crc(const AVCRC *ctx, uint32_t crc, const uint8_t *buffer, size_t length){

    const uint8_t *end= buffer+length;

#if !CONFIG_SMALL

    if(!ctx[256])

        while(buffer<end-3){

            crc ^= le2me_32(*(const uint32_t*)buffer); buffer+=4;

            crc =  ctx[3*256 + ( crc     &0xFF)]

                  ^ctx[2*256 + ((crc>>8 )&0xFF)]

                  ^ctx[1*256 + ((crc>>16)&0xFF)]

                  ^ctx[0*256 + ((crc>>24)     )];

        }

#endif

    while(buffer<end)

        crc = ctx[((uint8_t)crc) ^ *buffer++] ^ (crc >> 8);

    return crc;

}


void migrate_add_blocker(Error *reason)

{

    migration_blockers = g_slist_prepend(migration_blockers, reason);

}


static int encode_superframe(AVCodecContext *avctx,

                            unsigned char *buf, int buf_size, void *data){

    WMACodecContext *s = avctx->priv_data;

    const short *samples = data;

    int i, total_gain;

    s->block_len_bits= s->frame_len_bits; //required by non variable block len

    s->block_len = 1 << s->block_len_bits;

    apply_window_and_mdct(avctx, samples, avctx->frame_size);

    if (s->ms_stereo) {

        float a, b;

        int i;

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

            a = s->coefs[0][i]*0.5;

            b = s->coefs[1][i]*0.5;

            s->coefs[0][i] = a + b;

            s->coefs[1][i] = a - b;

        }

    }

    if (buf_size < 2 * MAX_CODED_SUPERFRAME_SIZE) {

        av_log(avctx, AV_LOG_ERROR, "output buffer size is too small\n");

        return AVERROR(EINVAL);

    }

#if 1

    total_gain= 128;

    for(i=64; i; i>>=1){

        int error= encode_frame(s, s->coefs, buf, buf_size, total_gain-i);

        if(error<0)

            total_gain-= i;

    }

#else

    total_gain= 90;

    best= encode_frame(s, s->coefs, buf, buf_size, total_gain);

    for(i=32; i; i>>=1){

        int scoreL= encode_frame(s, s->coefs, buf, buf_size, total_gain-i);

        int scoreR= encode_frame(s, s->coefs, buf, buf_size, total_gain+i);

        av_log(NULL, AV_LOG_ERROR, "%d %d %d (%d)\n", scoreL, best, scoreR, total_gain);

        if(scoreL < FFMIN(best, scoreR)){

            best = scoreL;

            total_gain -= i;

        }else if(scoreR < best){

            best = scoreR;

            total_gain += i;

        }

    }

#endif

    if ((i = encode_frame(s, s->coefs, buf, buf_size, total_gain)) >= 0) {

        av_log(avctx, AV_LOG_ERROR, "required frame size too large. please "

               "use a higher bit rate.\n");

        return AVERROR(EINVAL);

    }

    assert((put_bits_count(&s->pb) & 7) == 0);

    while (i++)

        put_bits(&s->pb, 8, 'N');

    flush_put_bits(&s->pb);

    return s->block_align;

}


static int encode_residual_ch(FlacEncodeContext *s, int ch)

{

    int i, n;

    int min_order, max_order, opt_order, omethod;

    FlacFrame *frame;

    FlacSubframe *sub;

    int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];

    int shift[MAX_LPC_ORDER];

    int32_t *res, *smp;

    frame = &s->frame;

    sub   = &frame->subframes[ch];

    res   = sub->residual;

    smp   = sub->samples;

    n     = frame->blocksize;

    /* CONSTANT */

    for (i = 1; i < n; i++)

        if(smp[i] != smp[0])

            break;

    if (i == n) {

        sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;

        res[0] = smp[0];

        return subframe_count_exact(s, sub, 0);

    }

    /* VERBATIM */

    if (frame->verbatim_only || n < 5) {

        sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;

        memcpy(res, smp, n * sizeof(int32_t));

        return subframe_count_exact(s, sub, 0);

    }

    min_order  = s->options.min_prediction_order;

    max_order  = s->options.max_prediction_order;

    omethod    = s->options.prediction_order_method;

    /* FIXED */

    sub->type = FLAC_SUBFRAME_FIXED;

    if (s->options.lpc_type == FF_LPC_TYPE_NONE  ||

        s->options.lpc_type == FF_LPC_TYPE_FIXED || n <= max_order) {

        uint32_t bits[MAX_FIXED_ORDER+1];

        if (max_order > MAX_FIXED_ORDER)

            max_order = MAX_FIXED_ORDER;

        opt_order = 0;

        bits[0]   = UINT32_MAX;

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

            encode_residual_fixed(res, smp, n, i);

            bits[i] = find_subframe_rice_params(s, sub, i);

            if (bits[i] < bits[opt_order])

                opt_order = i;

        }

        sub->order     = opt_order;

        sub->type_code = sub->type | sub->order;

        if (sub->order != max_order) {

            encode_residual_fixed(res, smp, n, sub->order);

            find_subframe_rice_params(s, sub, sub->order);

        }

        return subframe_count_exact(s, sub, sub->order);

    }

    /* LPC */

    sub->type = FLAC_SUBFRAME_LPC;

    opt_order = ff_lpc_calc_coefs(&s->lpc_ctx, smp, n, min_order, max_order,

                                  s->options.lpc_coeff_precision, coefs, shift, s->options.lpc_type,

                                  s->options.lpc_passes, omethod,

                                  MAX_LPC_SHIFT, 0);

    if (omethod == ORDER_METHOD_2LEVEL ||

        omethod == ORDER_METHOD_4LEVEL ||

        omethod == ORDER_METHOD_8LEVEL) {

        int levels = 1 << omethod;

        uint32_t bits[1 << ORDER_METHOD_8LEVEL];

        int order;

        int opt_index   = levels-1;

        opt_order       = max_order-1;

        bits[opt_index] = UINT32_MAX;

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

            order = min_order + (((max_order-min_order+1) * (i+1)) / levels)-1;

            if (order < 0)

                order = 0;

            encode_residual_lpc(res, smp, n, order+1, coefs[order], shift[order]);

            bits[i] = find_subframe_rice_params(s, sub, order+1);

            if (bits[i] < bits[opt_index]) {

                opt_index = i;

                opt_order = order;

            }

        }

        opt_order++;

    } else if (omethod == ORDER_METHOD_SEARCH) {

        // brute-force optimal order search

        uint32_t bits[MAX_LPC_ORDER];

        opt_order = 0;

        bits[0]   = UINT32_MAX;

        for (i = min_order-1; i < max_order; i++) {

            encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);

            bits[i] = find_subframe_rice_params(s, sub, i+1);

            if (bits[i] < bits[opt_order])

                opt_order = i;

        }

        opt_order++;

    } else if (omethod == ORDER_METHOD_LOG) {

        uint32_t bits[MAX_LPC_ORDER];

        int step;

        opt_order = min_order - 1 + (max_order-min_order)/3;

        memset(bits, -1, sizeof(bits));

        for (step = 16; step; step >>= 1) {

            int last = opt_order;

            for (i = last-step; i <= last+step; i += step) {

                if (i < min_order-1 || i >= max_order || bits[i] < UINT32_MAX)

                    continue;

                encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);

                bits[i] = find_subframe_rice_params(s, sub, i+1);

                if (bits[i] < bits[opt_order])

                    opt_order = i;

            }

        }

        opt_order++;

    }

    sub->order     = opt_order;

    sub->type_code = sub->type | (sub->order-1);

    sub->shift     = shift[sub->order-1];

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

        sub->coefs[i] = coefs[sub->order-1][i];

    encode_residual_lpc(res, smp, n, sub->order, sub->coefs, sub->shift);

    find_subframe_rice_params(s, sub, sub->order);

    return subframe_count_exact(s, sub, sub->order);

}


static int open_url(AVFormatContext *s, AVIOContext **pb, const char *url,

                    AVDictionary *opts, AVDictionary *opts2, int *is_http)

{

    HLSContext *c = s->priv_data;

    AVDictionary *tmp = NULL;

    const char *proto_name = NULL;

    int ret;

    av_dict_copy(&tmp, opts, 0);

    av_dict_copy(&tmp, opts2, 0);

    if (av_strstart(url, "crypto", NULL)) {

        if (url[6] == '+' || url[6] == ':')

            proto_name = avio_find_protocol_name(url + 7);

    }

    if (!proto_name)

        proto_name = avio_find_protocol_name(url);

    if (!proto_name)

        return AVERROR_INVALIDDATA;

    // only http(s) & file are allowed

    if (!av_strstart(proto_name, "http", NULL) && !av_strstart(proto_name, "file", NULL))

        return AVERROR_INVALIDDATA;

    if (!strncmp(proto_name, url, strlen(proto_name)) && url[strlen(proto_name)] == ':')

        ;

    else if (av_strstart(url, "crypto", NULL) && !strncmp(proto_name, url + 7, strlen(proto_name)) && url[7 + strlen(proto_name)] == ':')

        ;

    else if (strcmp(proto_name, "file") || !strncmp(url, "file,", 5))

        return AVERROR_INVALIDDATA;

    ret = s->io_open(s, pb, url, AVIO_FLAG_READ, &tmp);

    if (ret >= 0) {

        // update cookies on http response with setcookies.

        char *new_cookies = NULL;

        if (!(s->flags & AVFMT_FLAG_CUSTOM_IO))

            av_opt_get(*pb, "cookies", AV_OPT_SEARCH_CHILDREN, (uint8_t**)&new_cookies);

        if (new_cookies) {

            av_free(c->cookies);

            c->cookies = new_cookies;

        }

        av_dict_set(&opts, "cookies", c->cookies, 0);

    }

    av_dict_free(&tmp);

    if (is_http)

        *is_http = av_strstart(proto_name, "http", NULL);

    return ret;

}


static int do_fork(CPUArchState *env, unsigned int flags, abi_ulong newsp,

                   abi_ulong parent_tidptr, target_ulong newtls,

                   abi_ulong child_tidptr)

{

    CPUState *cpu = ENV_GET_CPU(env);

    int ret;

    TaskState *ts;

    CPUState *new_cpu;

    CPUArchState *new_env;

    sigset_t sigmask;

    /* Emulate vfork() with fork() */

    if (flags & CLONE_VFORK)

        flags &= ~(CLONE_VFORK | CLONE_VM);

    if (flags & CLONE_VM) {

        TaskState *parent_ts = (TaskState *)cpu->opaque;

        new_thread_info info;

        pthread_attr_t attr;

        ts = g_new0(TaskState, 1);

        init_task_state(ts);

        /* we create a new CPU instance. */

        new_env = cpu_copy(env);

        /* Init regs that differ from the parent.  */

        cpu_clone_regs(new_env, newsp);

        new_cpu = ENV_GET_CPU(new_env);

        new_cpu->opaque = ts;

        ts->bprm = parent_ts->bprm;

        ts->info = parent_ts->info;

        ts->signal_mask = parent_ts->signal_mask;

        if (flags & CLONE_CHILD_CLEARTID) {

            ts->child_tidptr = child_tidptr;

        }

        if (flags & CLONE_SETTLS) {

            cpu_set_tls (new_env, newtls);

        }

        /* Grab a mutex so that thread setup appears atomic.  */

        pthread_mutex_lock(&clone_lock);

        memset(&info, 0, sizeof(info));

        pthread_mutex_init(&info.mutex, NULL);

        pthread_mutex_lock(&info.mutex);

        pthread_cond_init(&info.cond, NULL);

        info.env = new_env;

        if (flags & CLONE_CHILD_SETTID) {

            info.child_tidptr = child_tidptr;

        }

        if (flags & CLONE_PARENT_SETTID) {

            info.parent_tidptr = parent_tidptr;

        }

        ret = pthread_attr_init(&attr);

        ret = pthread_attr_setstacksize(&attr, NEW_STACK_SIZE);

        ret = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

        /* It is not safe to deliver signals until the child has finished

           initializing, so temporarily block all signals.  */

        sigfillset(&sigmask);

        sigprocmask(SIG_BLOCK, &sigmask, &info.sigmask);

        ret = pthread_create(&info.thread, &attr, clone_func, &info);

        /* TODO: Free new CPU state if thread creation failed.  */

        sigprocmask(SIG_SETMASK, &info.sigmask, NULL);

        pthread_attr_destroy(&attr);

        if (ret == 0) {

            /* Wait for the child to initialize.  */

            pthread_cond_wait(&info.cond, &info.mutex);

            ret = info.tid;

        } else {

            ret = -1;

        }

        pthread_mutex_unlock(&info.mutex);

        pthread_cond_destroy(&info.cond);

        pthread_mutex_destroy(&info.mutex);

        pthread_mutex_unlock(&clone_lock);

    } else {

        /* if no CLONE_VM, we consider it is a fork */

        if ((flags & ~(CSIGNAL | CLONE_NPTL_FLAGS2)) != 0) {

            return -TARGET_EINVAL;

        }

        if (block_signals()) {

            return -TARGET_ERESTARTSYS;

        }

        fork_start();

        ret = fork();

        if (ret == 0) {

            /* Child Process.  */

            rcu_after_fork();

            cpu_clone_regs(env, newsp);

            fork_end(1);

            /* There is a race condition here.  The parent process could

               theoretically read the TID in the child process before the child

               tid is set.  This would require using either ptrace

               (not implemented) or having *_tidptr to point at a shared memory

               mapping.  We can't repeat the spinlock hack used above because

               the child process gets its own copy of the lock.  */

            if (flags & CLONE_CHILD_SETTID)

                put_user_u32(gettid(), child_tidptr);

            if (flags & CLONE_PARENT_SETTID)

                put_user_u32(gettid(), parent_tidptr);

            ts = (TaskState *)cpu->opaque;

            if (flags & CLONE_SETTLS)

                cpu_set_tls (env, newtls);

            if (flags & CLONE_CHILD_CLEARTID)

                ts->child_tidptr = child_tidptr;

        } else {

            fork_end(0);

        }

    }

    return ret;

}


static AVFilterContext *create_filter(AVFilterGraph *ctx, int index,

                                      const char *name, const char *args,

                                      AVClass *log_ctx)

{

    AVFilterContext *filt;

    AVFilter *filterdef;

    char inst_name[30];

    snprintf(inst_name, sizeof(inst_name), "Parsed filter %d", index);

    filterdef = avfilter_get_by_name(name);

    if(!filterdef) {

        av_log(log_ctx, AV_LOG_ERROR,

               "no such filter: '%s'\n", name);

        return NULL;

    }

    filt = avfilter_open(filterdef, inst_name);

    if(!filt) {

        av_log(log_ctx, AV_LOG_ERROR,

               "error creating filter '%s'\n", name);

        return NULL;

    }

    if(avfilter_graph_add_filter(ctx, filt) < 0)

        return NULL;

    if(avfilter_init_filter(filt, args, NULL)) {

        av_log(log_ctx, AV_LOG_ERROR,

               "error initializing filter '%s' with args '%s'\n", name, args);

        return NULL;

    }

    return filt;

}


static int find_tag(ByteIOContext *pb, uint32_t tag1)

{

    unsigned int tag;

    int size;

    for(;;) {

        if (url_feof(pb))

            return -1;

        tag = get_le32(pb);

        size = get_le32(pb);

        if (tag == tag1)

            break;

        url_fseek(pb, size, SEEK_CUR);

    }

    if (size < 0)

        size = 0x7fffffff;

    return size;

}


static av_always_inline int dnxhd_decode_dct_block(const DNXHDContext *ctx,

                                                   RowContext *row,

                                                   int n,

                                                   int index_bits,

                                                   int level_bias,

                                                   int level_shift)

{

    int i, j, index1, index2, len, flags;

    int level, component, sign;

    const int *scale;

    const uint8_t *weight_matrix;

    const uint8_t *ac_level = ctx->cid_table->ac_level;

    const uint8_t *ac_flags = ctx->cid_table->ac_flags;

    int16_t *block = row->blocks[n];

    const int eob_index     = ctx->cid_table->eob_index;

    int ret = 0;

    OPEN_READER(bs, &row->gb);

    ctx->bdsp.clear_block(block);

    if (!ctx->is_444) {

        if (n & 2) {

            component     = 1 + (n & 1);

            scale = row->chroma_scale;

            weight_matrix = ctx->cid_table->chroma_weight;

        } else {

            component     = 0;

            scale = row->luma_scale;

            weight_matrix = ctx->cid_table->luma_weight;

        }

    } else {

        component = (n >> 1) % 3;

        if (component) {

            scale = row->chroma_scale;

            weight_matrix = ctx->cid_table->chroma_weight;

        } else {

            scale = row->luma_scale;

            weight_matrix = ctx->cid_table->luma_weight;

        }

    }

    UPDATE_CACHE(bs, &row->gb);

    GET_VLC(len, bs, &row->gb, ctx->dc_vlc.table, DNXHD_DC_VLC_BITS, 1);

    if (len) {

        level = GET_CACHE(bs, &row->gb);

        LAST_SKIP_BITS(bs, &row->gb, len);

        sign  = ~level >> 31;

        level = (NEG_USR32(sign ^ level, len) ^ sign) - sign;

        row->last_dc[component] += level;

    }

    block[0] = row->last_dc[component];

    i = 0;

    UPDATE_CACHE(bs, &row->gb);

    GET_VLC(index1, bs, &row->gb, ctx->ac_vlc.table,

            DNXHD_VLC_BITS, 2);

    while (index1 != eob_index) {

        level = ac_level[index1];

        flags = ac_flags[index1];

        sign = SHOW_SBITS(bs, &row->gb, 1);

        SKIP_BITS(bs, &row->gb, 1);

        if (flags & 1) {

            level += SHOW_UBITS(bs, &row->gb, index_bits) << 7;

            SKIP_BITS(bs, &row->gb, index_bits);

        }

        if (flags & 2) {

            UPDATE_CACHE(bs, &row->gb);

            GET_VLC(index2, bs, &row->gb, ctx->run_vlc.table,

                    DNXHD_VLC_BITS, 2);

            i += ctx->cid_table->run[index2];

        }

        if (++i > 63) {

            av_log(ctx->avctx, AV_LOG_ERROR, "ac tex damaged %d, %d\n", n, i);

            ret = -1;

            break;

        }

        j     = ctx->scantable.permutated[i];

        level *= scale[i];

        level += scale[i] >> 1;

        if (level_bias < 32 || weight_matrix[i] != level_bias)

            level += level_bias; // 1<<(level_shift-1)

        level >>= level_shift;

        block[j] = (level ^ sign) - sign;

        UPDATE_CACHE(bs, &row->gb);

        GET_VLC(index1, bs, &row->gb, ctx->ac_vlc.table,

                DNXHD_VLC_BITS, 2);

    }

    CLOSE_READER(bs, &row->gb);

    return ret;

}


static int read_data(void *opaque, uint8_t *buf, int buf_size)

{

    struct playlist *v = opaque;

    HLSContext *c = v->parent->priv_data;

    int ret, i;

    int just_opened = 0;

    if (!v->needed)

        return AVERROR_EOF;

restart:

    if (!v->input) {

        /* If this is a live stream and the reload interval has elapsed since

         * the last playlist reload, reload the playlists now. */

        int64_t reload_interval = default_reload_interval(v);

reload:

        if (!v->finished &&

            av_gettime() - v->last_load_time >= reload_interval) {

            if ((ret = parse_playlist(c, v->url, v, NULL)) < 0) {

                av_log(v->parent, AV_LOG_WARNING, "Failed to reload playlist %d\n",

                       v->index);

                return ret;

            }

            /* If we need to reload the playlist again below (if

             * there's still no more segments), switch to a reload

             * interval of half the target duration. */

            reload_interval = v->target_duration / 2;

        }

        if (v->cur_seq_no < v->start_seq_no) {

            av_log(NULL, AV_LOG_WARNING,

                   "skipping %d segments ahead, expired from playlists\n",

                   v->start_seq_no - v->cur_seq_no);

            v->cur_seq_no = v->start_seq_no;

        }

        if (v->cur_seq_no >= v->start_seq_no + v->n_segments) {

            if (v->finished)

                return AVERROR_EOF;

            while (av_gettime() - v->last_load_time < reload_interval) {

                if (ff_check_interrupt(c->interrupt_callback))

                    return AVERROR_EXIT;

                av_usleep(100*1000);

            }

            /* Enough time has elapsed since the last reload */

            goto reload;

        }

        ret = open_input(c, v);

        if (ret < 0) {

            av_log(v->parent, AV_LOG_WARNING, "Failed to open segment of playlist %d\n",

                   v->index);

            return ret;

        }

        just_opened = 1;

    }

    ret = read_from_url(v, buf, buf_size, READ_NORMAL);

    if (ret > 0) {

        if (just_opened && v->is_id3_timestamped != 0) {

            /* Intercept ID3 tags here, elementary audio streams are required

             * to convey timestamps using them in the beginning of each segment. */

            intercept_id3(v, buf, buf_size, &ret);

        }

        return ret;

    }

    ffurl_close(v->input);

    v->input = NULL;

    v->cur_seq_no++;

    c->end_of_segment = 1;

    c->cur_seq_no = v->cur_seq_no;

    if (v->ctx && v->ctx->nb_streams &&

        v->parent->nb_streams >= v->stream_offset + v->ctx->nb_streams) {

        v->needed = 0;

        for (i = v->stream_offset; i < v->stream_offset + v->ctx->nb_streams;

             i++) {

            if (v->parent->streams[i]->discard < AVDISCARD_ALL)

                v->needed = 1;

        }

    }

    if (!v->needed) {

        av_log(v->parent, AV_LOG_INFO, "No longer receiving playlist %d\n",

               v->index);

        return AVERROR_EOF;

    }

    goto restart;

}


static int decode_header(SnowContext *s){

    int plane_index, tmp;

    uint8_t kstate[32];

    memset(kstate, MID_STATE, sizeof(kstate));

    s->keyframe= get_rac(&s->c, kstate);

    if(s->keyframe || s->always_reset){

        reset_contexts(s);

        s->spatial_decomposition_type=

        s->qlog=

        s->qbias=

        s->mv_scale=

        s->block_max_depth= 0;

    }

    if(s->keyframe){

        s->version= get_symbol(&s->c, s->header_state, 0);

        if(s->version>0){

            av_log(s->avctx, AV_LOG_ERROR, "version %d not supported", s->version);

            return -1;

        }

        s->always_reset= get_rac(&s->c, s->header_state);

        s->temporal_decomposition_type= get_symbol(&s->c, s->header_state, 0);

        s->temporal_decomposition_count= get_symbol(&s->c, s->header_state, 0);

        s->spatial_decomposition_count= get_symbol(&s->c, s->header_state, 0);

        s->colorspace_type= get_symbol(&s->c, s->header_state, 0);

        s->chroma_h_shift= get_symbol(&s->c, s->header_state, 0);

        s->chroma_v_shift= get_symbol(&s->c, s->header_state, 0);

        s->spatial_scalability= get_rac(&s->c, s->header_state);

//        s->rate_scalability= get_rac(&s->c, s->header_state);

        tmp= get_symbol(&s->c, s->header_state, 0)+1;

        if(tmp < 1 || tmp > MAX_REF_FRAMES){

            av_log(s->avctx, AV_LOG_ERROR, "reference frame count is %d\n", tmp);

            return -1;

        }

        s->max_ref_frames= tmp;

        decode_qlogs(s);

    }

    if(!s->keyframe){

        if(get_rac(&s->c, s->header_state)){

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

                int htaps, i, sum=0;

                Plane *p= &s->plane[plane_index];

                p->diag_mc= get_rac(&s->c, s->header_state);

                htaps= get_symbol(&s->c, s->header_state, 0)*2 + 2;

                if((unsigned)htaps > HTAPS_MAX || htaps==0)

                    return -1;

                p->htaps= htaps;

                for(i= htaps/2; i; i--){

                    p->hcoeff[i]= get_symbol(&s->c, s->header_state, 0) * (1-2*(i&1));

                    sum += p->hcoeff[i];

                }

                p->hcoeff[0]= 32-sum;

            }

            s->plane[2].diag_mc= s->plane[1].diag_mc;

            s->plane[2].htaps  = s->plane[1].htaps;

            memcpy(s->plane[2].hcoeff, s->plane[1].hcoeff, sizeof(s->plane[1].hcoeff));

        }

        if(get_rac(&s->c, s->header_state)){

            s->spatial_decomposition_count= get_symbol(&s->c, s->header_state, 0);

            decode_qlogs(s);

        }

    }

    s->spatial_decomposition_type+= get_symbol(&s->c, s->header_state, 1);

    if(s->spatial_decomposition_type > 1){

        av_log(s->avctx, AV_LOG_ERROR, "spatial_decomposition_type %d not supported", s->spatial_decomposition_type);

        return -1;

    }

    s->qlog           += get_symbol(&s->c, s->header_state, 1);

    s->mv_scale       += get_symbol(&s->c, s->header_state, 1);

    s->qbias          += get_symbol(&s->c, s->header_state, 1);

    s->block_max_depth+= get_symbol(&s->c, s->header_state, 1);

    if(s->block_max_depth > 1 || s->block_max_depth < 0){

        av_log(s->avctx, AV_LOG_ERROR, "block_max_depth= %d is too large", s->block_max_depth);

        s->block_max_depth= 0;

        return -1;

    }

    return 0;

}


static av_cold void x8_vlc_init(void){

    int i;

    int offset = 0;

    int sizeidx = 0;

    static const uint16_t sizes[8*4 + 8*2 + 2 + 4] = {

        576, 548, 582, 618, 546, 616, 560, 642,

        584, 582, 704, 664, 512, 544, 656, 640,

        512, 648, 582, 566, 532, 614, 596, 648,

        586, 552, 584, 590, 544, 578, 584, 624,

        528, 528, 526, 528, 536, 528, 526, 544,

        544, 512, 512, 528, 528, 544, 512, 544,

        128, 128, 128, 128, 128, 128};

    static VLC_TYPE table[28150][2];

#define  init_ac_vlc(dst,src) \

    dst.table = &table[offset]; \

    dst.table_allocated = sizes[sizeidx]; \

    offset += sizes[sizeidx++]; \

       init_vlc(&dst, \

              AC_VLC_BITS,77, \

              &src[1],4,2, \

              &src[0],4,2, \

              INIT_VLC_USE_NEW_STATIC)

//set ac tables

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

        init_ac_vlc( j_ac_vlc[0][0][i], x8_ac0_highquant_table[i][0] );

        init_ac_vlc( j_ac_vlc[0][1][i], x8_ac1_highquant_table[i][0] );

        init_ac_vlc( j_ac_vlc[1][0][i], x8_ac0_lowquant_table [i][0] );

        init_ac_vlc( j_ac_vlc[1][1][i], x8_ac1_lowquant_table [i][0] );

    }

#undef init_ac_vlc

//set dc tables

#define init_dc_vlc(dst,src) \

    dst.table = &table[offset]; \

    dst.table_allocated = sizes[sizeidx]; \

    offset += sizes[sizeidx++]; \

        init_vlc(&dst, \

        DC_VLC_BITS,34, \

        &src[1],4,2, \

        &src[0],4,2, \

        INIT_VLC_USE_NEW_STATIC);

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

        init_dc_vlc( j_dc_vlc[0][i], x8_dc_highquant_table[i][0]);

        init_dc_vlc( j_dc_vlc[1][i], x8_dc_lowquant_table [i][0]);

    }

#undef init_dc_vlc

//set orient tables

#define init_or_vlc(dst,src) \

    dst.table = &table[offset]; \

    dst.table_allocated = sizes[sizeidx]; \

    offset += sizes[sizeidx++]; \

    init_vlc(&dst, \

    OR_VLC_BITS,12, \

    &src[1],4,2, \

    &src[0],4,2, \

    INIT_VLC_USE_NEW_STATIC);

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

        init_or_vlc( j_orient_vlc[0][i], x8_orient_highquant_table[i][0]);

    }

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

        init_or_vlc( j_orient_vlc[1][i], x8_orient_lowquant_table [i][0])

    }

    if (offset != sizeof(table)/sizeof(VLC_TYPE)/2)

        av_log(NULL, AV_LOG_ERROR, "table size %i does not match needed %i\n", (int)(sizeof(table)/sizeof(VLC_TYPE)/2), offset);

}


static int ass_split(ASSSplitContext *ctx, const char *buf)

{

    char c, section[16];

    int i;

    if (ctx->current_section >= 0)

        buf = ass_split_section(ctx, buf);

    while (buf && *buf) {

        if (sscanf(buf, "[%15[0-9A-Za-z+ ]]%c", section, &c) == 2) {

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

            for (i=0; i<FF_ARRAY_ELEMS(ass_sections); i++)

                if (!strcmp(section, ass_sections[i].section)) {

                    ctx->current_section = i;

                    buf = ass_split_section(ctx, buf);

                }

        } else

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

    }

    return buf ? 0 : AVERROR_INVALIDDATA;

}


static int aac_decode_frame(AVCodecContext *avctx, void *data,

                            int *got_frame_ptr, AVPacket *avpkt)

{

    AACContext *ac = avctx->priv_data;

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    GetBitContext gb;

    int buf_consumed;

    int buf_offset;

    int err;

    int new_extradata_size;

    const uint8_t *new_extradata = av_packet_get_side_data(avpkt,

                                       AV_PKT_DATA_NEW_EXTRADATA,

                                       &new_extradata_size);

    if (new_extradata) {

        av_free(avctx->extradata);

        avctx->extradata = av_mallocz(new_extradata_size +

                                      FF_INPUT_BUFFER_PADDING_SIZE);

        if (!avctx->extradata)

            return AVERROR(ENOMEM);

        avctx->extradata_size = new_extradata_size;

        memcpy(avctx->extradata, new_extradata, new_extradata_size);

        push_output_configuration(ac);

        if (decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,

                                         avctx->extradata,

                                         avctx->extradata_size*8, 1) < 0) {

            pop_output_configuration(ac);

            return AVERROR_INVALIDDATA;

        }

    }

    init_get_bits(&gb, buf, buf_size * 8);

    if ((err = aac_decode_frame_int(avctx, data, got_frame_ptr, &gb)) < 0)

        return err;

    buf_consumed = (get_bits_count(&gb) + 7) >> 3;

    for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)

        if (buf[buf_offset])

            break;

    return buf_size > buf_offset ? buf_consumed : buf_size;

}


static inline void t_gen_swapw(TCGv d, TCGv s)

{

	TCGv t;

	/* d and s refer the same object.  */

	t = tcg_temp_new(TCG_TYPE_TL);

	tcg_gen_mov_tl(t, s);

	tcg_gen_shli_tl(d, t, 16);

	tcg_gen_shri_tl(t, t, 16);

	tcg_gen_or_tl(d, d, t);

	tcg_temp_free(t);

}


static int get_block_status(BlockDriverState *bs, int64_t sector_num,

                            int nb_sectors, MapEntry *e)

{

    int64_t ret;

    int depth;

    /* As an optimization, we could cache the current range of unallocated

     * clusters in each file of the chain, and avoid querying the same

     * range repeatedly.

     */

    depth = 0;

    for (;;) {

        ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &nb_sectors);

        if (ret < 0) {

            return ret;

        }

        assert(nb_sectors);

        if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {

            break;

        }

        bs = backing_bs(bs);

        if (bs == NULL) {

            ret = 0;

            break;

        }

        depth++;

    }

    e->start = sector_num * BDRV_SECTOR_SIZE;

    e->length = nb_sectors * BDRV_SECTOR_SIZE;

    e->flags = ret & ~BDRV_BLOCK_OFFSET_MASK;

    e->offset = ret & BDRV_BLOCK_OFFSET_MASK;

    e->depth = depth;

    e->bs = bs;

    return 0;

}


void HELPER(cas2w)(CPUM68KState *env, uint32_t regs, uint32_t a1, uint32_t a2)

{

    uint32_t Dc1 = extract32(regs, 9, 3);

    uint32_t Dc2 = extract32(regs, 6, 3);

    uint32_t Du1 = extract32(regs, 3, 3);

    uint32_t Du2 = extract32(regs, 0, 3);

    int16_t c1 = env->dregs[Dc1];

    int16_t c2 = env->dregs[Dc2];

    int16_t u1 = env->dregs[Du1];

    int16_t u2 = env->dregs[Du2];

    int16_t l1, l2;

    uintptr_t ra = GETPC();

    if (parallel_cpus) {

        /* Tell the main loop we need to serialize this insn.  */

        cpu_loop_exit_atomic(ENV_GET_CPU(env), ra);

    } else {

        /* We're executing in a serial context -- no need to be atomic.  */

        l1 = cpu_lduw_data_ra(env, a1, ra);

        l2 = cpu_lduw_data_ra(env, a2, ra);

        if (l1 == c1 && l2 == c2) {

            cpu_stw_data_ra(env, a1, u1, ra);

            cpu_stw_data_ra(env, a2, u2, ra);

        }

    }

    if (c1 != l1) {

        env->cc_n = l1;

        env->cc_v = c1;

    } else {

        env->cc_n = l2;

        env->cc_v = c2;

    }

    env->cc_op = CC_OP_CMPW;

    env->dregs[Dc1] = deposit32(env->dregs[Dc1], 0, 16, l1);

    env->dregs[Dc2] = deposit32(env->dregs[Dc2], 0, 16, l2);

}


static void glib_select_fill(int *max_fd, fd_set *rfds, fd_set *wfds,

                             fd_set *xfds, struct timeval *tv)

{

    GMainContext *context = g_main_context_default();

    int i;

    int timeout = 0, cur_timeout;

    g_main_context_prepare(context, &max_priority);

    n_poll_fds = g_main_context_query(context, max_priority, &timeout,

                                      poll_fds, ARRAY_SIZE(poll_fds));

    g_assert(n_poll_fds <= ARRAY_SIZE(poll_fds));

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

        GPollFD *p = &poll_fds[i];

        if ((p->events & G_IO_IN)) {

            FD_SET(p->fd, rfds);

            *max_fd = MAX(*max_fd, p->fd);

        }

        if ((p->events & G_IO_OUT)) {

            FD_SET(p->fd, wfds);

            *max_fd = MAX(*max_fd, p->fd);

        }

        if ((p->events & G_IO_ERR)) {

            FD_SET(p->fd, xfds);

            *max_fd = MAX(*max_fd, p->fd);

        }

    }

    cur_timeout = (tv->tv_sec * 1000) + ((tv->tv_usec + 500) / 1000);

    if (timeout >= 0 && timeout < cur_timeout) {

        tv->tv_sec = timeout / 1000;

        tv->tv_usec = (timeout % 1000) * 1000;

    }

}


void bdrv_info(Monitor *mon, QObject **ret_data)

{

    QList *bs_list;

    BlockDriverState *bs;

    bs_list = qlist_new();

    QTAILQ_FOREACH(bs, &bdrv_states, list) {

        QObject *bs_obj;

        bs_obj = qobject_from_jsonf("{ 'device': %s, 'type': 'unknown', "

                                    "'removable': %i, 'locked': %i }",

                                    bs->device_name, bs->removable,

                                    bdrv_dev_is_medium_locked(bs));

        if (bs->drv) {

            QObject *obj;

            QDict *bs_dict = qobject_to_qdict(bs_obj);

            obj = qobject_from_jsonf("{ 'file': %s, 'ro': %i, 'drv': %s, "

                                     "'encrypted': %i }",

                                     bs->filename, bs->read_only,

                                     bs->drv->format_name,

                                     bdrv_is_encrypted(bs));

            if (bs->backing_file[0] != '\0') {

                QDict *qdict = qobject_to_qdict(obj);

                qdict_put(qdict, "backing_file",

                          qstring_from_str(bs->backing_file));

            }

            qdict_put_obj(bs_dict, "inserted", obj);

        }

        qlist_append_obj(bs_list, bs_obj);

    }

    *ret_data = QOBJECT(bs_list);

}


static abi_long do_recvfrom(int fd, abi_ulong msg, size_t len, int flags,

                            abi_ulong target_addr,

                            abi_ulong target_addrlen)

{

    socklen_t addrlen;

    void *addr;

    void *host_msg;

    abi_long ret;

    host_msg = lock_user(VERIFY_WRITE, msg, len, 0);

    if (!host_msg)

        return -TARGET_EFAULT;

    if (target_addr) {

        if (get_user_u32(addrlen, target_addrlen)) {

            ret = -TARGET_EFAULT;

            goto fail;

        }

        if (addrlen < 0 || addrlen > MAX_SOCK_ADDR) {

            ret = -TARGET_EINVAL;

            goto fail;

        }

        addr = alloca(addrlen);

        ret = get_errno(recvfrom(fd, host_msg, len, flags, addr, &addrlen));

    } else {

        addr = NULL; /* To keep compiler quiet.  */

        ret = get_errno(recv(fd, host_msg, len, flags));

    }

    if (!is_error(ret)) {

        if (target_addr) {

            host_to_target_sockaddr(target_addr, addr, addrlen);

            if (put_user_u32(addrlen, target_addrlen)) {

                ret = -TARGET_EFAULT;

                goto fail;

            }

        }

        unlock_user(host_msg, msg, len);

    } else {

fail:

        unlock_user(host_msg, msg, 0);

    }

    return ret;

}


static PageDesc *page_find_alloc(tb_page_addr_t index, int alloc)

{

    PageDesc *pd;

    void **lp;

    int i;

#if defined(CONFIG_USER_ONLY)

    /* We can't use g_malloc because it may recurse into a locked mutex. */

# define ALLOC(P, SIZE)                                 \

    do {                                                \

        P = mmap(NULL, SIZE, PROT_READ | PROT_WRITE,    \

                 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);   \

    } while (0)

#else

# define ALLOC(P, SIZE) \

    do { P = g_malloc0(SIZE); } while (0)

#endif

    /* Level 1.  Always allocated.  */

    lp = l1_map + ((index >> V_L1_SHIFT) & (V_L1_SIZE - 1));

    /* Level 2..N-1.  */

    for (i = V_L1_SHIFT / V_L2_BITS - 1; i > 0; i--) {

        void **p = *lp;

        if (p == NULL) {

            if (!alloc) {

                return NULL;

            }

            ALLOC(p, sizeof(void *) * V_L2_SIZE);

            *lp = p;

        }

        lp = p + ((index >> (i * V_L2_BITS)) & (V_L2_SIZE - 1));

    }

    pd = *lp;

    if (pd == NULL) {

        if (!alloc) {

            return NULL;

        }

        ALLOC(pd, sizeof(PageDesc) * V_L2_SIZE);

        *lp = pd;

    }

#undef ALLOC

    return pd + (index & (V_L2_SIZE - 1));

}


static void pointer_event(VncState *vs, int button_mask, int x, int y)

{

    static uint32_t bmap[INPUT_BUTTON__MAX] = {

        [INPUT_BUTTON_LEFT]       = 0x01,

        [INPUT_BUTTON_MIDDLE]     = 0x02,

        [INPUT_BUTTON_RIGHT]      = 0x04,

        [INPUT_BUTTON_WHEEL_UP]   = 0x08,

        [INPUT_BUTTON_WHEEL_DOWN] = 0x10,

    };

    QemuConsole *con = vs->vd->dcl.con;

    int width = pixman_image_get_width(vs->vd->server);

    int height = pixman_image_get_height(vs->vd->server);

    if (vs->last_bmask != button_mask) {

        qemu_input_update_buttons(con, bmap, vs->last_bmask, button_mask);

        vs->last_bmask = button_mask;

    }

    if (vs->absolute) {

        qemu_input_queue_abs(con, INPUT_AXIS_X, x, width);

        qemu_input_queue_abs(con, INPUT_AXIS_Y, y, height);

    } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {

        qemu_input_queue_rel(con, INPUT_AXIS_X, x - 0x7FFF);

        qemu_input_queue_rel(con, INPUT_AXIS_Y, y - 0x7FFF);

    } else {

        if (vs->last_x != -1) {

            qemu_input_queue_rel(con, INPUT_AXIS_X, x - vs->last_x);

            qemu_input_queue_rel(con, INPUT_AXIS_Y, y - vs->last_y);

        }

        vs->last_x = x;

        vs->last_y = y;

    }

    qemu_input_event_sync();

}


static bool is_zero_cluster(BlockDriverState *bs, int64_t start)

{

    BDRVQcow2State *s = bs->opaque;

    int nr;

    BlockDriverState *file;

    int64_t res = bdrv_get_block_status_above(bs, NULL, start,

                                              s->cluster_sectors, &nr, &file);

    return res >= 0 && (res & BDRV_BLOCK_ZERO);

}


static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,

    int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,

    BdrvRequestFlags flags)

{

    if (nb_sectors < 0 || nb_sectors > (UINT_MAX >> BDRV_SECTOR_BITS)) {

        return -EINVAL;

    }

    return bdrv_co_do_preadv(bs, sector_num << BDRV_SECTOR_BITS,

                             nb_sectors << BDRV_SECTOR_BITS, qiov, flags);

}


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

{

    const char *param = qdict_get_str(qdict, "parameter");

    const char *valuestr = qdict_get_str(qdict, "value");

    int64_t valuebw = 0;

    long valueint = 0;

    Error *err = NULL;

    bool use_int_value = false;

    int i;

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

        if (strcmp(param, MigrationParameter_lookup[i]) == 0) {

            MigrationParameters p = { 0 };

            switch (i) {

            case MIGRATION_PARAMETER_COMPRESS_LEVEL:

                p.has_compress_level = true;

                use_int_value = true;

                break;

            case MIGRATION_PARAMETER_COMPRESS_THREADS:

                p.has_compress_threads = true;

                use_int_value = true;

                break;

            case MIGRATION_PARAMETER_DECOMPRESS_THREADS:

                p.has_decompress_threads = true;

                use_int_value = true;

                break;

            case MIGRATION_PARAMETER_CPU_THROTTLE_INITIAL:

                p.has_cpu_throttle_initial = true;

                use_int_value = true;

                break;

            case MIGRATION_PARAMETER_CPU_THROTTLE_INCREMENT:

                p.has_cpu_throttle_increment = true;

                use_int_value = true;

                break;

            case MIGRATION_PARAMETER_TLS_CREDS:

                p.has_tls_creds = true;

                p.tls_creds = (char *) valuestr;

                break;

            case MIGRATION_PARAMETER_TLS_HOSTNAME:

                p.has_tls_hostname = true;

                p.tls_hostname = (char *) valuestr;

                break;

            case MIGRATION_PARAMETER_MAX_BANDWIDTH:

                p.has_max_bandwidth = true;

                valuebw = qemu_strtosz_MiB(valuestr, NULL);

                if (valuebw < 0 || (size_t)valuebw != valuebw) {

                    error_setg(&err, "Invalid size %s", valuestr);

                    goto cleanup;

                }

                p.max_bandwidth = valuebw;

                break;

            case MIGRATION_PARAMETER_DOWNTIME_LIMIT:

                p.has_downtime_limit = true;

                use_int_value = true;

                break;

            case MIGRATION_PARAMETER_X_CHECKPOINT_DELAY:

                p.has_x_checkpoint_delay = true;

                use_int_value = true;

                break;

            }

            if (use_int_value) {

                if (qemu_strtol(valuestr, NULL, 10, &valueint) < 0) {

                    error_setg(&err, "Unable to parse '%s' as an int",

                               valuestr);

                    goto cleanup;

                }

                /* Set all integers; only one has_FOO will be set, and

                 * the code ignores the remaining values */

                p.compress_level = valueint;

                p.compress_threads = valueint;

                p.decompress_threads = valueint;

                p.cpu_throttle_initial = valueint;

                p.cpu_throttle_increment = valueint;

                p.downtime_limit = valueint;

                p.x_checkpoint_delay = valueint;

            }

            qmp_migrate_set_parameters(&p, &err);

            break;

        }

    }

    if (i == MIGRATION_PARAMETER__MAX) {

        error_setg(&err, QERR_INVALID_PARAMETER, param);

    }

 cleanup:

    if (err) {

        error_report_err(err);

    }

}


static void mcf5208evb_init(MachineState *machine)

{

    ram_addr_t ram_size = machine->ram_size;

    const char *cpu_model = machine->cpu_model;

    const char *kernel_filename = machine->kernel_filename;

    M68kCPU *cpu;

    CPUM68KState *env;

    int kernel_size;

    uint64_t elf_entry;

    hwaddr entry;

    qemu_irq *pic;

    MemoryRegion *address_space_mem = get_system_memory();

    MemoryRegion *ram = g_new(MemoryRegion, 1);

    MemoryRegion *sram = g_new(MemoryRegion, 1);

    if (!cpu_model) {

        cpu_model = "m5208";

    }

    cpu = M68K_CPU(cpu_generic_init(TYPE_M68K_CPU, cpu_model));

    env = &cpu->env;

    /* Initialize CPU registers.  */

    env->vbr = 0;

    /* TODO: Configure BARs.  */

    /* DRAM at 0x40000000 */

    memory_region_allocate_system_memory(ram, NULL, "mcf5208.ram", ram_size);

    memory_region_add_subregion(address_space_mem, 0x40000000, ram);

    /* Internal SRAM.  */

    memory_region_init_ram(sram, NULL, "mcf5208.sram", 16384, &error_fatal);

    memory_region_add_subregion(address_space_mem, 0x80000000, sram);

    /* Internal peripherals.  */

    pic = mcf_intc_init(address_space_mem, 0xfc048000, cpu);

    mcf_uart_mm_init(0xfc060000, pic[26], serial_hds[0]);

    mcf_uart_mm_init(0xfc064000, pic[27], serial_hds[1]);

    mcf_uart_mm_init(0xfc068000, pic[28], serial_hds[2]);

    mcf5208_sys_init(address_space_mem, pic);

    if (nb_nics > 1) {

        fprintf(stderr, "Too many NICs\n");

        exit(1);

    }

    if (nd_table[0].used) {

        mcf_fec_init(address_space_mem, &nd_table[0],

                     0xfc030000, pic + 36);

    }

    /*  0xfc000000 SCM.  */

    /*  0xfc004000 XBS.  */

    /*  0xfc008000 FlexBus CS.  */

    /* 0xfc030000 FEC.  */

    /*  0xfc040000 SCM + Power management.  */

    /*  0xfc044000 eDMA.  */

    /* 0xfc048000 INTC.  */

    /*  0xfc058000 I2C.  */

    /*  0xfc05c000 QSPI.  */

    /* 0xfc060000 UART0.  */

    /* 0xfc064000 UART0.  */

    /* 0xfc068000 UART0.  */

    /*  0xfc070000 DMA timers.  */

    /* 0xfc080000 PIT0.  */

    /* 0xfc084000 PIT1.  */

    /*  0xfc088000 EPORT.  */

    /*  0xfc08c000 Watchdog.  */

    /*  0xfc090000 clock module.  */

    /*  0xfc0a0000 CCM + reset.  */

    /*  0xfc0a4000 GPIO.  */

    /* 0xfc0a8000 SDRAM controller.  */

    /* Load kernel.  */

    if (!kernel_filename) {

        if (qtest_enabled()) {

            return;

        }

        fprintf(stderr, "Kernel image must be specified\n");

        exit(1);

    }

    kernel_size = load_elf(kernel_filename, NULL, NULL, &elf_entry,

                           NULL, NULL, 1, EM_68K, 0, 0);

    entry = elf_entry;

    if (kernel_size < 0) {

        kernel_size = load_uimage(kernel_filename, &entry, NULL, NULL,

                                  NULL, NULL);

    }

    if (kernel_size < 0) {

        kernel_size = load_image_targphys(kernel_filename, 0x40000000,

                                          ram_size);

        entry = 0x40000000;

    }

    if (kernel_size < 0) {

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

        exit(1);

    }

    env->pc = entry;

}


static CharDriverState *qemu_chr_open_tty_fd(int fd)

{

    CharDriverState *chr;

    tty_serial_init(fd, 115200, 'N', 8, 1);

    chr = qemu_chr_open_fd(fd, fd);

    chr->chr_ioctl = tty_serial_ioctl;

    chr->chr_close = qemu_chr_close_tty;

    return chr;

}


void qdev_property_add_static(DeviceState *dev, Property *prop,

                              Error **errp)

{

    Error *local_err = NULL;

    Object *obj = OBJECT(dev);

    /*

     * TODO qdev_prop_ptr does not have getters or setters.  It must

     * go now that it can be replaced with links.  The test should be

     * removed along with it: all static properties are read/write.

     */

    if (!prop->info->get && !prop->info->set) {

        return;

    }

    object_property_add(obj, prop->name, prop->info->name,

                        prop->info->get, prop->info->set,

                        prop->info->release,

                        prop, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        return;

    }

    object_property_set_description(obj, prop->name,

                                    prop->info->description,

                                    &error_abort);

    if (prop->info->set_default_value) {

        prop->info->set_default_value(obj, prop);

    }

}


static uint16_t shpc_get_status(SHPCDevice *shpc, int slot, uint16_t msk)

{

    uint8_t *status = shpc->config + SHPC_SLOT_STATUS(slot);

    return (pci_get_word(status) & msk) >> (ffs(msk) - 1);

}


static int hls_start(AVFormatContext *s, VariantStream *vs)

{

    HLSContext *c = s->priv_data;

    AVFormatContext *oc = vs->avf;

    AVFormatContext *vtt_oc = vs->vtt_avf;

    AVDictionary *options = NULL;

    char *filename, iv_string[KEYSIZE*2 + 1];

    int err = 0;

    if (c->flags & HLS_SINGLE_FILE) {

        av_strlcpy(oc->filename, vs->basename,

                   sizeof(oc->filename));

        if (vs->vtt_basename)

            av_strlcpy(vtt_oc->filename, vs->vtt_basename,

                  sizeof(vtt_oc->filename));

    } else if (c->max_seg_size > 0) {

        if (replace_int_data_in_filename(oc->filename, sizeof(oc->filename),

#if FF_API_HLS_WRAP

            vs->basename, 'd', c->wrap ? vs->sequence % c->wrap : vs->sequence) < 1) {

#else

            vs->basename, 'd', vs->sequence) < 1) {

#endif

                av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s', you can try to use -use_localtime 1 with it\n", vs->basename);

                return AVERROR(EINVAL);

        }

    } else {

        if (c->use_localtime) {

            time_t now0;

            struct tm *tm, tmpbuf;

            time(&now0);

            tm = localtime_r(&now0, &tmpbuf);

            if (!strftime(oc->filename, sizeof(oc->filename), vs->basename, tm)) {

                av_log(oc, AV_LOG_ERROR, "Could not get segment filename with use_localtime\n");

                return AVERROR(EINVAL);

            }

            err = sls_flag_use_localtime_filename(oc, c, vs);

            if (err < 0) {

                return AVERROR(ENOMEM);

            }

            if (c->use_localtime_mkdir) {

                const char *dir;

                char *fn_copy = av_strdup(oc->filename);

                if (!fn_copy) {

                    return AVERROR(ENOMEM);

                }

                dir = av_dirname(fn_copy);

                if (mkdir_p(dir) == -1 && errno != EEXIST) {

                    av_log(oc, AV_LOG_ERROR, "Could not create directory %s with use_localtime_mkdir\n", dir);

                    av_free(fn_copy);

                    return AVERROR(errno);

                }

                av_free(fn_copy);

            }

        } else if (replace_int_data_in_filename(oc->filename, sizeof(oc->filename),

#if FF_API_HLS_WRAP

                   vs->basename, 'd', c->wrap ? vs->sequence % c->wrap : vs->sequence) < 1) {

#else

                   vs->basename, 'd', vs->sequence) < 1) {

#endif

            av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s' you can try to use -use_localtime 1 with it\n", vs->basename);

            return AVERROR(EINVAL);

        }

        if( vs->vtt_basename) {

            if (replace_int_data_in_filename(vtt_oc->filename, sizeof(vtt_oc->filename),

#if FF_API_HLS_WRAP

                vs->vtt_basename, 'd', c->wrap ? vs->sequence % c->wrap : vs->sequence) < 1) {

#else

                vs->vtt_basename, 'd', vs->sequence) < 1) {

#endif

                av_log(vtt_oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", vs->vtt_basename);

                return AVERROR(EINVAL);

            }

       }

    }

    vs->number++;

    set_http_options(s, &options, c);

    if (c->flags & HLS_TEMP_FILE) {

        av_strlcat(oc->filename, ".tmp", sizeof(oc->filename));

    }

    if (c->key_info_file || c->encrypt) {

        if (c->key_info_file && c->encrypt) {

            av_log(s, AV_LOG_WARNING, "Cannot use both -hls_key_info_file and -hls_enc,"

                  " will use -hls_key_info_file priority\n");

        }

        if (!c->encrypt_started || (c->flags & HLS_PERIODIC_REKEY)) {

            if (c->key_info_file) {

                if ((err = hls_encryption_start(s)) < 0)

                    goto fail;

            } else {

                if ((err = do_encrypt(s, vs)) < 0)

                    goto fail;

            }

            c->encrypt_started = 1;

        }

        if ((err = av_dict_set(&options, "encryption_key", c->key_string, 0))

                < 0)

            goto fail;

        err = av_strlcpy(iv_string, c->iv_string, sizeof(iv_string));

        if (!err)

            snprintf(iv_string, sizeof(iv_string), "%032"PRIx64, vs->sequence);

        if ((err = av_dict_set(&options, "encryption_iv", iv_string, 0)) < 0)

           goto fail;

        filename = av_asprintf("crypto:%s", oc->filename);

        if (!filename) {

            err = AVERROR(ENOMEM);

            goto fail;

        }

        err = hlsenc_io_open(s, &oc->pb, filename, &options);

        av_free(filename);

        av_dict_free(&options);

        if (err < 0)

            return err;

    } else if (c->segment_type != SEGMENT_TYPE_FMP4) {

        if ((err = hlsenc_io_open(s, &oc->pb, oc->filename, &options)) < 0)

            goto fail;

    }

    if (vs->vtt_basename) {

        set_http_options(s, &options, c);

        if ((err = hlsenc_io_open(s, &vtt_oc->pb, vtt_oc->filename, &options)) < 0)

            goto fail;

    }

    av_dict_free(&options);

    if (c->segment_type != SEGMENT_TYPE_FMP4) {

        /* We only require one PAT/PMT per segment. */

        if (oc->oformat->priv_class && oc->priv_data) {

            char period[21];

            snprintf(period, sizeof(period), "%d", (INT_MAX / 2) - 1);

            av_opt_set(oc->priv_data, "mpegts_flags", "resend_headers", 0);

            av_opt_set(oc->priv_data, "sdt_period", period, 0);

            av_opt_set(oc->priv_data, "pat_period", period, 0);

        }

    }

    if (vs->vtt_basename) {

        err = avformat_write_header(vtt_oc,NULL);

        if (err < 0)

            return err;

    }

    return 0;

fail:

    av_dict_free(&options);

    return err;

}


void virtio_submit_multiwrite(BlockDriverState *bs, MultiReqBuffer *mrb)

{

    int i, ret;

    if (!mrb->num_writes) {

        return;

    }

    ret = bdrv_aio_multiwrite(bs, mrb->blkreq, mrb->num_writes);

    if (ret != 0) {

        for (i = 0; i < mrb->num_writes; i++) {

            if (mrb->blkreq[i].error) {

                virtio_blk_rw_complete(mrb->blkreq[i].opaque, -EIO);

            }

        }

    }

    mrb->num_writes = 0;

}


DeviceState *pc_vga_init(ISABus *isa_bus, PCIBus *pci_bus)

{

    DeviceState *dev = NULL;

    if (cirrus_vga_enabled) {

        if (pci_bus) {

            dev = pci_cirrus_vga_init(pci_bus);

        } else {

            dev = isa_cirrus_vga_init(get_system_memory());

        }

    } else if (vmsvga_enabled) {

        if (pci_bus) {

            dev = pci_vmsvga_init(pci_bus);

            if (!dev) {

                fprintf(stderr, "Warning: vmware_vga not available,"

                        " using standard VGA instead\n");

                dev = pci_vga_init(pci_bus);

            }

        } else {

            fprintf(stderr, "%s: vmware_vga: no PCI bus\n", __FUNCTION__);

        }

#ifdef CONFIG_SPICE

    } else if (qxl_enabled) {

        if (pci_bus) {

            dev = &pci_create_simple(pci_bus, -1, "qxl-vga")->qdev;

        } else {

            fprintf(stderr, "%s: qxl: no PCI bus\n", __FUNCTION__);

        }

#endif

    } else if (std_vga_enabled) {

        if (pci_bus) {

            dev = pci_vga_init(pci_bus);

        } else {

            dev = isa_vga_init(isa_bus);

        }

    }

    return dev;

}


static void v9fs_version(void *opaque)

{

    V9fsPDU *pdu = opaque;

    V9fsState *s = pdu->s;

    V9fsString version;

    size_t offset = 7;

    pdu_unmarshal(pdu, offset, "ds", &s->msize, &version);

    trace_v9fs_version(pdu->tag, pdu->id, s->msize, version.data);

    virtfs_reset(pdu);

    if (!strcmp(version.data, "9P2000.u")) {

        s->proto_version = V9FS_PROTO_2000U;

    } else if (!strcmp(version.data, "9P2000.L")) {

        s->proto_version = V9FS_PROTO_2000L;

    } else {

        v9fs_string_sprintf(&version, "unknown");

    }

    offset += pdu_marshal(pdu, offset, "ds", s->msize, &version);

    trace_v9fs_version_return(pdu->tag, pdu->id, s->msize, version.data);

    complete_pdu(s, pdu, offset);

    v9fs_string_free(&version);

    return;

}


static void openpic_irq_raise(openpic_t *opp, int n_CPU, IRQ_src_t *src)

{

    int n_ci = IDR_CI0 - n_CPU;

    if ((opp->flags & OPENPIC_FLAG_IDE_CRIT) && test_bit(&src->ide, n_ci)) {

        qemu_irq_raise(opp->dst[n_CPU].irqs[OPENPIC_OUTPUT_CINT]);

    } else {

        qemu_irq_raise(opp->dst[n_CPU].irqs[OPENPIC_OUTPUT_INT]);

    }

}


void vm_stop(int reason)

{

    QemuThread me;

    qemu_thread_self(&me);

    if (!qemu_thread_equal(&me, &io_thread)) {

        qemu_system_vmstop_request(reason);

        /*

         * FIXME: should not return to device code in case

         * vm_stop() has been requested.

         */

        cpu_stop_current();

        return;

    }

    do_vm_stop(reason);

}


int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,

    const void *buf, int count)

{

    int ret;

    ret = bdrv_pwrite(bs, offset, buf, count);

    if (ret < 0) {

        return ret;

    }

    /* No flush needed for cache modes that already do it */

    if (bs->enable_write_cache) {

        bdrv_flush(bs);

    }

    return 0;

}


static uint64_t mv88w8618_pit_read(void *opaque, target_phys_addr_t offset,

                                   unsigned size)

{

    mv88w8618_pit_state *s = opaque;

    mv88w8618_timer_state *t;

    switch (offset) {

    case MP_PIT_TIMER1_VALUE ... MP_PIT_TIMER4_VALUE:

        t = &s->timer[(offset-MP_PIT_TIMER1_VALUE) >> 2];

        return ptimer_get_count(t->ptimer);

    default:

        return 0;

    }

}


static int amrwb_decode_frame(AVCodecContext *avctx, void *data,

                              int *got_frame_ptr, AVPacket *avpkt)

{

    AMRWBContext *ctx  = avctx->priv_data;

    AMRWBFrame   *cf   = &ctx->frame;

    const uint8_t *buf = avpkt->data;

    int buf_size       = avpkt->size;

    int expected_fr_size, header_size;

    float *buf_out;

    float spare_vector[AMRWB_SFR_SIZE];      // extra stack space to hold result from anti-sparseness processing

    float fixed_gain_factor;                 // fixed gain correction factor (gamma)

    float *synth_fixed_vector;               // pointer to the fixed vector that synthesis should use

    float synth_fixed_gain;                  // the fixed gain that synthesis should use

    float voice_fac, stab_fac;               // parameters used for gain smoothing

    float synth_exc[AMRWB_SFR_SIZE];         // post-processed excitation for synthesis

    float hb_exc[AMRWB_SFR_SIZE_16k];        // excitation for the high frequency band

    float hb_samples[AMRWB_SFR_SIZE_16k];    // filtered high-band samples from synthesis

    float hb_gain;

    int sub, i, ret;

    /* get output buffer */

    ctx->avframe.nb_samples = 4 * AMRWB_SFR_SIZE_16k;

    if ((ret = avctx->get_buffer(avctx, &ctx->avframe)) < 0) {

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

        return ret;

    }

    buf_out = (float *)ctx->avframe.data[0];

    header_size      = decode_mime_header(ctx, buf);

    expected_fr_size = ((cf_sizes_wb[ctx->fr_cur_mode] + 7) >> 3) + 1;

    if (buf_size < expected_fr_size) {

        av_log(avctx, AV_LOG_ERROR,

            "Frame too small (%d bytes). Truncated file?\n", buf_size);

        *got_frame_ptr = 0;

        return buf_size;

    }

    if (!ctx->fr_quality || ctx->fr_cur_mode > MODE_SID)

        av_log(avctx, AV_LOG_ERROR, "Encountered a bad or corrupted frame\n");

    if (ctx->fr_cur_mode == MODE_SID) /* Comfort noise frame */

        av_log_missing_feature(avctx, "SID mode", 1);

    if (ctx->fr_cur_mode >= MODE_SID)

        return -1;

    ff_amr_bit_reorder((uint16_t *) &ctx->frame, sizeof(AMRWBFrame),

        buf + header_size, amr_bit_orderings_by_mode[ctx->fr_cur_mode]);

    /* Decode the quantized ISF vector */

    if (ctx->fr_cur_mode == MODE_6k60) {

        decode_isf_indices_36b(cf->isp_id, ctx->isf_cur);

    } else {

        decode_isf_indices_46b(cf->isp_id, ctx->isf_cur);

    }

    isf_add_mean_and_past(ctx->isf_cur, ctx->isf_q_past);

    ff_set_min_dist_lsf(ctx->isf_cur, MIN_ISF_SPACING, LP_ORDER - 1);

    stab_fac = stability_factor(ctx->isf_cur, ctx->isf_past_final);

    ctx->isf_cur[LP_ORDER - 1] *= 2.0;

    ff_acelp_lsf2lspd(ctx->isp[3], ctx->isf_cur, LP_ORDER);

    /* Generate a ISP vector for each subframe */

    if (ctx->first_frame) {

        ctx->first_frame = 0;

        memcpy(ctx->isp_sub4_past, ctx->isp[3], LP_ORDER * sizeof(double));

    }

    interpolate_isp(ctx->isp, ctx->isp_sub4_past);

    for (sub = 0; sub < 4; sub++)

        ff_amrwb_lsp2lpc(ctx->isp[sub], ctx->lp_coef[sub], LP_ORDER);

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

        const AMRWBSubFrame *cur_subframe = &cf->subframe[sub];

        float *sub_buf = buf_out + sub * AMRWB_SFR_SIZE_16k;

        /* Decode adaptive codebook (pitch vector) */

        decode_pitch_vector(ctx, cur_subframe, sub);

        /* Decode innovative codebook (fixed vector) */

        decode_fixed_vector(ctx->fixed_vector, cur_subframe->pul_ih,

                            cur_subframe->pul_il, ctx->fr_cur_mode);

        pitch_sharpening(ctx, ctx->fixed_vector);

        decode_gains(cur_subframe->vq_gain, ctx->fr_cur_mode,

                     &fixed_gain_factor, &ctx->pitch_gain[0]);

        ctx->fixed_gain[0] =

            ff_amr_set_fixed_gain(fixed_gain_factor,

                       ff_dot_productf(ctx->fixed_vector, ctx->fixed_vector,

                                       AMRWB_SFR_SIZE) / AMRWB_SFR_SIZE,

                       ctx->prediction_error,

                       ENERGY_MEAN, energy_pred_fac);

        /* Calculate voice factor and store tilt for next subframe */

        voice_fac      = voice_factor(ctx->pitch_vector, ctx->pitch_gain[0],

                                      ctx->fixed_vector, ctx->fixed_gain[0]);

        ctx->tilt_coef = voice_fac * 0.25 + 0.25;

        /* Construct current excitation */

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

            ctx->excitation[i] *= ctx->pitch_gain[0];

            ctx->excitation[i] += ctx->fixed_gain[0] * ctx->fixed_vector[i];

            ctx->excitation[i] = truncf(ctx->excitation[i]);

        }

        /* Post-processing of excitation elements */

        synth_fixed_gain = noise_enhancer(ctx->fixed_gain[0], &ctx->prev_tr_gain,

                                          voice_fac, stab_fac);

        synth_fixed_vector = anti_sparseness(ctx, ctx->fixed_vector,

                                             spare_vector);

        pitch_enhancer(synth_fixed_vector, voice_fac);

        synthesis(ctx, ctx->lp_coef[sub], synth_exc, synth_fixed_gain,

                  synth_fixed_vector, &ctx->samples_az[LP_ORDER]);

        /* Synthesis speech post-processing */

        de_emphasis(&ctx->samples_up[UPS_MEM_SIZE],

                    &ctx->samples_az[LP_ORDER], PREEMPH_FAC, ctx->demph_mem);

        ff_acelp_apply_order_2_transfer_function(&ctx->samples_up[UPS_MEM_SIZE],

            &ctx->samples_up[UPS_MEM_SIZE], hpf_zeros, hpf_31_poles,

            hpf_31_gain, ctx->hpf_31_mem, AMRWB_SFR_SIZE);

        upsample_5_4(sub_buf, &ctx->samples_up[UPS_FIR_SIZE],

                     AMRWB_SFR_SIZE_16k);

        /* High frequency band (6.4 - 7.0 kHz) generation part */

        ff_acelp_apply_order_2_transfer_function(hb_samples,

            &ctx->samples_up[UPS_MEM_SIZE], hpf_zeros, hpf_400_poles,

            hpf_400_gain, ctx->hpf_400_mem, AMRWB_SFR_SIZE);

        hb_gain = find_hb_gain(ctx, hb_samples,

                               cur_subframe->hb_gain, cf->vad);

        scaled_hb_excitation(ctx, hb_exc, synth_exc, hb_gain);

        hb_synthesis(ctx, sub, &ctx->samples_hb[LP_ORDER_16k],

                     hb_exc, ctx->isf_cur, ctx->isf_past_final);

        /* High-band post-processing filters */

        hb_fir_filter(hb_samples, bpf_6_7_coef, ctx->bpf_6_7_mem,

                      &ctx->samples_hb[LP_ORDER_16k]);

        if (ctx->fr_cur_mode == MODE_23k85)

            hb_fir_filter(hb_samples, lpf_7_coef, ctx->lpf_7_mem,

                          hb_samples);

        /* Add the low and high frequency bands */

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

            sub_buf[i] = (sub_buf[i] + hb_samples[i]) * (1.0f / (1 << 15));

        /* Update buffers and history */

        update_sub_state(ctx);

    }

    /* update state for next frame */

    memcpy(ctx->isp_sub4_past, ctx->isp[3], LP_ORDER * sizeof(ctx->isp[3][0]));

    memcpy(ctx->isf_past_final, ctx->isf_cur, LP_ORDER * sizeof(float));

    *got_frame_ptr   = 1;

    *(AVFrame *)data = ctx->avframe;

    return expected_fr_size;

}


static ssize_t mcf_fec_receive(NetClientState *nc, const uint8_t *buf, size_t size)

{

    mcf_fec_state *s = qemu_get_nic_opaque(nc);

    mcf_fec_bd bd;

    uint32_t flags = 0;

    uint32_t addr;

    uint32_t crc;

    uint32_t buf_addr;

    uint8_t *crc_ptr;

    unsigned int buf_len;

    size_t retsize;

    DPRINTF("do_rx len %d\n", size);

    if (!s->rx_enabled) {

        return -1;

    }

    /* 4 bytes for the CRC.  */

    size += 4;

    crc = cpu_to_be32(crc32(~0, buf, size));

    crc_ptr = (uint8_t *)&crc;

    /* Huge frames are truncted.  */

    if (size > FEC_MAX_FRAME_SIZE) {

        size = FEC_MAX_FRAME_SIZE;

        flags |= FEC_BD_TR | FEC_BD_LG;

    }

    /* Frames larger than the user limit just set error flags.  */

    if (size > (s->rcr >> 16)) {

        flags |= FEC_BD_LG;

    }

    addr = s->rx_descriptor;

    retsize = size;

    while (size > 0) {

        mcf_fec_read_bd(&bd, addr);

        if ((bd.flags & FEC_BD_E) == 0) {

            /* No descriptors available.  Bail out.  */

            /* FIXME: This is wrong.  We should probably either save the

               remainder for when more RX buffers are available, or

               flag an error.  */

            fprintf(stderr, "mcf_fec: Lost end of frame\n");

            break;

        }

        buf_len = (size <= s->emrbr) ? size: s->emrbr;

        bd.length = buf_len;

        size -= buf_len;

        DPRINTF("rx_bd %x length %d\n", addr, bd.length);

        /* The last 4 bytes are the CRC.  */

        if (size < 4)

            buf_len += size - 4;

        buf_addr = bd.data;

        cpu_physical_memory_write(buf_addr, buf, buf_len);

        buf += buf_len;

        if (size < 4) {

            cpu_physical_memory_write(buf_addr + buf_len, crc_ptr, 4 - size);

            crc_ptr += 4 - size;

        }

        bd.flags &= ~FEC_BD_E;

        if (size == 0) {

            /* Last buffer in frame.  */

            bd.flags |= flags | FEC_BD_L;

            DPRINTF("rx frame flags %04x\n", bd.flags);

            s->eir |= FEC_INT_RXF;

        } else {

            s->eir |= FEC_INT_RXB;

        }

        mcf_fec_write_bd(&bd, addr);

        /* Advance to the next descriptor.  */

        if ((bd.flags & FEC_BD_W) != 0) {

            addr = s->erdsr;

        } else {

            addr += 8;

        }

    }

    s->rx_descriptor = addr;

    mcf_fec_enable_rx(s);

    mcf_fec_update(s);

    return retsize;

}


static int openfile(char *name, int flags, int growable)

{

	if (bs) {

		fprintf(stderr, "file open already, try 'help close'\n");

		return 1;

	}

	bs = bdrv_new("hda");

	if (!bs)

		return 1;

	if (bdrv_open(bs, name, flags) == -1) {

		fprintf(stderr, "%s: can't open device %s\n", progname, name);

		bs = NULL;

		return 1;

	}

	if (growable) {

		if (!bs->drv || !bs->drv->protocol_name) {

			fprintf(stderr,

				"%s: only protocols can be opened growable\n",

				progname);

			return 1;

		}

		bs->growable = 1;

	}

	return 0;

}


static BlockDriverAIOCB *rbd_aio_rw_vector(BlockDriverState *bs,

                                           int64_t sector_num,

                                           QEMUIOVector *qiov,

                                           int nb_sectors,

                                           BlockDriverCompletionFunc *cb,

                                           void *opaque, int write)

{

    RBDAIOCB *acb;

    RADOSCB *rcb;

    rbd_completion_t c;

    int64_t off, size;

    char *buf;

    BDRVRBDState *s = bs->opaque;

    acb = qemu_aio_get(&rbd_aio_pool, bs, cb, opaque);

    acb->write = write;

    acb->qiov = qiov;

    acb->bounce = qemu_blockalign(bs, qiov->size);

    acb->ret = 0;

    acb->error = 0;

    acb->s = s;

    acb->cancelled = 0;

    acb->bh = NULL;

    if (write) {

        qemu_iovec_to_buffer(acb->qiov, acb->bounce);

    }

    buf = acb->bounce;

    off = sector_num * BDRV_SECTOR_SIZE;

    size = nb_sectors * BDRV_SECTOR_SIZE;

    s->qemu_aio_count++; /* All the RADOSCB */

    rcb = qemu_malloc(sizeof(RADOSCB));

    rcb->done = 0;

    rcb->acb = acb;

    rcb->buf = buf;

    rcb->s = acb->s;

    rcb->size = size;

    if (write) {

        rbd_aio_create_completion(rcb, (rbd_callback_t) rbd_finish_aiocb, &c);

        rbd_aio_write(s->image, off, size, buf, c);

    } else {

        rbd_aio_create_completion(rcb, (rbd_callback_t) rbd_finish_aiocb, &c);

        rbd_aio_read(s->image, off, size, buf, c);

    }

    return &acb->common;

}


static int plot_cqt(AVFilterContext *ctx)

{

    AVFilterLink *outlink = ctx->outputs[0];

    ShowCQTContext *s = ctx->priv;

    int ret;

    memcpy(s->fft_result, s->fft_data, s->fft_len * sizeof(*s->fft_data));

    av_fft_permute(s->fft_ctx, s->fft_result);

    av_fft_calc(s->fft_ctx, s->fft_result);

    s->fft_result[s->fft_len] = s->fft_result[0];

    s->cqt_calc(s->cqt_result, s->fft_result, s->coeffs, s->cqt_len, s->fft_len);

    process_cqt(s);

    if (s->sono_h)

        s->update_sono(s->sono_frame, s->c_buf, s->sono_idx);

    if (!s->sono_count) {

        AVFrame *out = ff_get_video_buffer(outlink, outlink->w, outlink->h);

        if (!out)

            return AVERROR(ENOMEM);

        if (s->bar_h)

            s->draw_bar(out, s->h_buf, s->rcp_h_buf, s->c_buf, s->bar_h);

        if (s->axis_h)

            s->draw_axis(out, s->axis_frame, s->c_buf, s->bar_h);

        if (s->sono_h)

            s->draw_sono(out, s->sono_frame, s->bar_h + s->axis_h, s->sono_idx);

        out->pts = s->frame_count;

        ret = ff_filter_frame(outlink, out);

        s->frame_count++;

    }

    s->sono_count = (s->sono_count + 1) % s->count;

    if (s->sono_h)

        s->sono_idx = (s->sono_idx + s->sono_h - 1) % s->sono_h;

    return ret;

}


static inline void vring_used_idx_set(VirtQueue *vq, uint16_t val)

{

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

    hwaddr pa = offsetof(VRingUsed, idx);

    virtio_stw_phys_cached(vq->vdev, &caches->used, pa, val);

    address_space_cache_invalidate(&caches->used, pa, sizeof(val));

    vq->used_idx = val;

}


static void usbredir_interrupt_packet(void *priv, uint64_t id,

    struct usb_redir_interrupt_packet_header *interrupt_packet,

    uint8_t *data, int data_len)

{

    USBRedirDevice *dev = priv;

    uint8_t ep = interrupt_packet->endpoint;

    DPRINTF("interrupt-in status %d ep %02X len %d id %"PRIu64"\n",

            interrupt_packet->status, ep, data_len, id);

    if (dev->endpoint[EP2I(ep)].type != USB_ENDPOINT_XFER_INT) {

        ERROR("received int packet for non interrupt endpoint %02X\n", ep);

        free(data);

        return;

    }

    if (ep & USB_DIR_IN) {

        if (dev->endpoint[EP2I(ep)].interrupt_started == 0) {

            DPRINTF("received int packet while not started ep %02X\n", ep);

            free(data);

            return;

        }

        /* bufp_alloc also adds the packet to the ep queue */

        bufp_alloc(dev, data, data_len, interrupt_packet->status, ep);

    } else {

        USBPacket *p = usbredir_find_packet_by_id(dev, ep, id);

        if (p) {

            usbredir_handle_status(dev, p, interrupt_packet->status);

            p->actual_length = interrupt_packet->length;

            usb_packet_complete(&dev->dev, p);

        }

    }

}


static int decode_band(IVI45DecContext *ctx,

                       IVIBandDesc *band, AVCodecContext *avctx)

{

    int         result, i, t, idx1, idx2, pos;

    IVITile     *tile;

    band->buf     = band->bufs[ctx->dst_buf];

    if (!band->buf) {

        av_log(avctx, AV_LOG_ERROR, "Band buffer points to no data!\n");

        return AVERROR_INVALIDDATA;

    }

    band->ref_buf = band->bufs[ctx->ref_buf];

    band->data_ptr = ctx->frame_data + (get_bits_count(&ctx->gb) >> 3);

    result = ctx->decode_band_hdr(ctx, band, avctx);

    if (result) {

        av_log(avctx, AV_LOG_ERROR, "Error while decoding band header: %d\n",

               result);

        return result;

    }

    if (band->is_empty) {

        av_log(avctx, AV_LOG_ERROR, "Empty band encountered!\n");

        return AVERROR_INVALIDDATA;

    }

    band->rv_map = &ctx->rvmap_tabs[band->rvmap_sel];

    /* apply corrections to the selected rvmap table if present */

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

        idx1 = band->corr[i * 2];

        idx2 = band->corr[i * 2 + 1];

        FFSWAP(uint8_t, band->rv_map->runtab[idx1], band->rv_map->runtab[idx2]);

        FFSWAP(int16_t, band->rv_map->valtab[idx1], band->rv_map->valtab[idx2]);

    }

    pos = get_bits_count(&ctx->gb);

    for (t = 0; t < band->num_tiles; t++) {

        tile = &band->tiles[t];

        if (tile->mb_size != band->mb_size) {

            av_log(avctx, AV_LOG_ERROR, "MB sizes mismatch: %d vs. %d\n",

                   band->mb_size, tile->mb_size);

            return AVERROR_INVALIDDATA;

        }

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

        if (tile->is_empty) {

            result = ivi_process_empty_tile(avctx, band, tile,

                                      (ctx->planes[0].bands[0].mb_size >> 3) - (band->mb_size >> 3));

            if (result < 0)

                break;

            av_dlog(avctx, "Empty tile encountered!\n");

        } else {

            tile->data_size = ivi_dec_tile_data_size(&ctx->gb);

            if (!tile->data_size) {

                av_log(avctx, AV_LOG_ERROR, "Tile data size is zero!\n");

                return AVERROR_INVALIDDATA;

            }

            result = ctx->decode_mb_info(ctx, band, tile, avctx);

            if (result < 0)

                break;

            result = ivi_decode_blocks(&ctx->gb, band, tile, avctx);

            if (result < 0 || ((get_bits_count(&ctx->gb) - pos) >> 3) != tile->data_size) {

                av_log(avctx, AV_LOG_ERROR, "Corrupted tile data encountered!\n");

                break;

            }

            pos += tile->data_size << 3; // skip to next tile

        }

    }

    /* restore the selected rvmap table by applying its corrections in reverse order */

    for (i = band->num_corr-1; i >= 0; i--) {

        idx1 = band->corr[i*2];

        idx2 = band->corr[i*2+1];

        FFSWAP(uint8_t, band->rv_map->runtab[idx1], band->rv_map->runtab[idx2]);

        FFSWAP(int16_t, band->rv_map->valtab[idx1], band->rv_map->valtab[idx2]);

    }

#ifdef DEBUG

    if (band->checksum_present) {

        uint16_t chksum = ivi_calc_band_checksum(band);

        if (chksum != band->checksum) {

            av_log(avctx, AV_LOG_ERROR,

                   "Band checksum mismatch! Plane %d, band %d, received: %x, calculated: %x\n",

                   band->plane, band->band_num, band->checksum, chksum);

        }

    }

#endif

    align_get_bits(&ctx->gb);

    return result;

}


int e820_add_entry(uint64_t address, uint64_t length, uint32_t type)

{

    int index = le32_to_cpu(e820_reserve.count);

    struct e820_entry *entry;

    if (type != E820_RAM) {

        /* old FW_CFG_E820_TABLE entry -- reservations only */

        if (index >= E820_NR_ENTRIES) {

            return -EBUSY;

        }

        entry = &e820_reserve.entry[index++];

        entry->address = cpu_to_le64(address);

        entry->length = cpu_to_le64(length);

        entry->type = cpu_to_le32(type);

        e820_reserve.count = cpu_to_le32(index);

    }

    /* new "etc/e820" file -- include ram too */

    e820_table = g_realloc(e820_table,

                           sizeof(struct e820_entry) * (e820_entries+1));

    e820_table[e820_entries].address = cpu_to_le64(address);

    e820_table[e820_entries].length = cpu_to_le64(length);

    e820_table[e820_entries].type = cpu_to_le32(type);

    e820_entries++;

    return e820_entries;

}


static int mov_read_keys(MOVContext *c, AVIOContext *pb, MOVAtom atom)

{

    uint32_t count;

    uint32_t i;

    if (atom.size < 8)

        return 0;

    avio_skip(pb, 4);

    count = avio_rb32(pb);

    if (count > UINT_MAX / sizeof(*c->meta_keys)) {

        av_log(c->fc, AV_LOG_ERROR,

               "The 'keys' atom with the invalid key count: %d\n", count);

        return AVERROR_INVALIDDATA;

    }

    c->meta_keys_count = count + 1;

    c->meta_keys = av_mallocz(c->meta_keys_count * sizeof(*c->meta_keys));

    if (!c->meta_keys)

        return AVERROR(ENOMEM);

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

        uint32_t key_size = avio_rb32(pb);

        uint32_t type = avio_rl32(pb);

        if (key_size < 8) {

            av_log(c->fc, AV_LOG_ERROR,

                   "The key# %d in meta has invalid size: %d\n", i, key_size);

            return AVERROR_INVALIDDATA;

        }

        key_size -= 8;

        if (type != MKTAG('m','d','t','a')) {

            avio_skip(pb, key_size);

        }

        c->meta_keys[i] = av_mallocz(key_size + 1);

        if (!c->meta_keys[i])

            return AVERROR(ENOMEM);

        avio_read(pb, c->meta_keys[i], key_size);

    }

    return 0;

}


static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)

{

    AVStream *st;

    uint32_t type;

    uint32_t av_unused ctype;

    int64_t title_size;

    char *title_str;

    if (c->fc->nb_streams < 1) // meta before first trak

        return 0;

    st = c->fc->streams[c->fc->nb_streams-1];

    avio_r8(pb); /* version */

    avio_rb24(pb); /* flags */

    /* component type */

    ctype = avio_rl32(pb);

    type = avio_rl32(pb); /* component subtype */

    av_log(c->fc, AV_LOG_TRACE, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);

    av_log(c->fc, AV_LOG_TRACE, "stype= %.4s\n", (char*)&type);

    if     (type == MKTAG('v','i','d','e'))

        st->codec->codec_type = AVMEDIA_TYPE_VIDEO;

    else if (type == MKTAG('s','o','u','n'))

        st->codec->codec_type = AVMEDIA_TYPE_AUDIO;

    else if (type == MKTAG('m','1','a',' '))

        st->codec->codec_id = AV_CODEC_ID_MP2;

    else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))

        st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;

    avio_rb32(pb); /* component  manufacture */

    avio_rb32(pb); /* component flags */

    avio_rb32(pb); /* component flags mask */

    title_size = atom.size - 24;

    if (title_size > 0) {

        title_str = av_malloc(title_size + 1); /* Add null terminator */

        if (!title_str)

            return AVERROR(ENOMEM);

        avio_read(pb, title_str, title_size);

        title_str[title_size] = 0;

        if (title_str[0]) {

            int off = (!c->isom && title_str[0] == title_size - 1);

            av_dict_set(&st->metadata, "handler_name", title_str + off, 0);

        }

        av_freep(&title_str);

    }

    return 0;

}