static av_cold int encode_init(AVCodecContext *avctx)

{

    FFV1Context *s = avctx->priv_data;

    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);

    int i, j, k, m, ret;

    if ((ret = ff_ffv1_common_init(avctx)) < 0)

        return ret;

    s->version = 0;

    if ((avctx->flags & (AV_CODEC_FLAG_PASS1 | AV_CODEC_FLAG_PASS2)) ||

        avctx->slices > 1)

        s->version = FFMAX(s->version, 2);

    // Unspecified level & slices, we choose version 1.2+ to ensure multithreaded decodability

    if (avctx->slices == 0 && avctx->level < 0 && avctx->width * avctx->height > 720*576)

        s->version = FFMAX(s->version, 2);

    if (avctx->level <= 0 && s->version == 2) {

        s->version = 3;

    }

    if (avctx->level >= 0 && avctx->level <= 4) {

        if (avctx->level < s->version) {

            av_log(avctx, AV_LOG_ERROR, "Version %d needed for requested features but %d requested\n", s->version, avctx->level);

            return AVERROR(EINVAL);

        }

        s->version = avctx->level;

    }

    if (s->ec < 0) {

        s->ec = (s->version >= 3);

    }

    if ((s->version == 2 || s->version>3) && avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {

        av_log(avctx, AV_LOG_ERROR, "Version 2 needed for requested features but version 2 is experimental and not enabled\n");

        return AVERROR_INVALIDDATA;

    }

#if FF_API_CODER_TYPE

FF_DISABLE_DEPRECATION_WARNINGS

    if (avctx->coder_type != -1)

        s->ac = avctx->coder_type > 0 ? AC_RANGE_CUSTOM_TAB : AC_GOLOMB_RICE;

    else

FF_ENABLE_DEPRECATION_WARNINGS

#endif

    if (s->ac == 1) // Compatbility with common command line usage

        s->ac = AC_RANGE_CUSTOM_TAB;

    else if (s->ac == AC_RANGE_DEFAULT_TAB_FORCE)

        s->ac = AC_RANGE_DEFAULT_TAB;

    s->plane_count = 3;

    switch(avctx->pix_fmt) {

    case AV_PIX_FMT_YUV444P9:

    case AV_PIX_FMT_YUV422P9:

    case AV_PIX_FMT_YUV420P9:

    case AV_PIX_FMT_YUVA444P9:

    case AV_PIX_FMT_YUVA422P9:

    case AV_PIX_FMT_YUVA420P9:

        if (!avctx->bits_per_raw_sample)

            s->bits_per_raw_sample = 9;

    case AV_PIX_FMT_GRAY10:

    case AV_PIX_FMT_YUV444P10:

    case AV_PIX_FMT_YUV420P10:

    case AV_PIX_FMT_YUV422P10:

    case AV_PIX_FMT_YUVA444P10:

    case AV_PIX_FMT_YUVA422P10:

    case AV_PIX_FMT_YUVA420P10:

        if (!avctx->bits_per_raw_sample && !s->bits_per_raw_sample)

            s->bits_per_raw_sample = 10;

    case AV_PIX_FMT_GRAY12:

    case AV_PIX_FMT_YUV444P12:

    case AV_PIX_FMT_YUV420P12:

    case AV_PIX_FMT_YUV422P12:

        s->packed_at_lsb = 1;

        if (!avctx->bits_per_raw_sample && !s->bits_per_raw_sample)

            s->bits_per_raw_sample = 12;

    case AV_PIX_FMT_GRAY16:

    case AV_PIX_FMT_YUV444P16:

    case AV_PIX_FMT_YUV422P16:

    case AV_PIX_FMT_YUV420P16:

    case AV_PIX_FMT_YUVA444P16:

    case AV_PIX_FMT_YUVA422P16:

    case AV_PIX_FMT_YUVA420P16:

        if (!avctx->bits_per_raw_sample && !s->bits_per_raw_sample) {

            s->bits_per_raw_sample = 16;

        } else if (!s->bits_per_raw_sample) {

            s->bits_per_raw_sample = avctx->bits_per_raw_sample;

        }

        if (s->bits_per_raw_sample <= 8) {

            av_log(avctx, AV_LOG_ERROR, "bits_per_raw_sample invalid\n");

            return AVERROR_INVALIDDATA;

        }

        s->version = FFMAX(s->version, 1);

    case AV_PIX_FMT_GRAY8:

    case AV_PIX_FMT_YA8:

    case AV_PIX_FMT_YUV444P:

    case AV_PIX_FMT_YUV440P:

    case AV_PIX_FMT_YUV422P:

    case AV_PIX_FMT_YUV420P:

    case AV_PIX_FMT_YUV411P:

    case AV_PIX_FMT_YUV410P:

    case AV_PIX_FMT_YUVA444P:

    case AV_PIX_FMT_YUVA422P:

    case AV_PIX_FMT_YUVA420P:

        s->chroma_planes = desc->nb_components < 3 ? 0 : 1;

        s->colorspace = 0;

        s->transparency = desc->nb_components == 4 || desc->nb_components == 2;

        if (!avctx->bits_per_raw_sample && !s->bits_per_raw_sample)

            s->bits_per_raw_sample = 8;

        else if (!s->bits_per_raw_sample)

            s->bits_per_raw_sample = 8;

        break;

    case AV_PIX_FMT_RGB32:

        s->colorspace = 1;

        s->transparency = 1;

        s->chroma_planes = 1;

        s->bits_per_raw_sample = 8;

        break;

    case AV_PIX_FMT_RGB48:

        s->colorspace = 1;

        s->chroma_planes = 1;

        s->bits_per_raw_sample = 16;

        s->use32bit = 1;

        s->version = FFMAX(s->version, 1);

        if (avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {

            av_log(avctx, AV_LOG_ERROR, "16bit RGB is experimental and under development, only use it for experiments\n");

            return AVERROR_INVALIDDATA;

        }

        break;

    case AV_PIX_FMT_0RGB32:

        s->colorspace = 1;

        s->chroma_planes = 1;

        s->bits_per_raw_sample = 8;

        break;

    case AV_PIX_FMT_GBRP9:

        if (!avctx->bits_per_raw_sample)

            s->bits_per_raw_sample = 9;

    case AV_PIX_FMT_GBRP10:

        if (!avctx->bits_per_raw_sample && !s->bits_per_raw_sample)

            s->bits_per_raw_sample = 10;

    case AV_PIX_FMT_GBRP12:

        if (!avctx->bits_per_raw_sample && !s->bits_per_raw_sample)

            s->bits_per_raw_sample = 12;

    case AV_PIX_FMT_GBRP14:

        if (!avctx->bits_per_raw_sample && !s->bits_per_raw_sample)

            s->bits_per_raw_sample = 14;

    case AV_PIX_FMT_GBRP16:

        if (!avctx->bits_per_raw_sample && !s->bits_per_raw_sample)

            s->bits_per_raw_sample = 16;

        else if (!s->bits_per_raw_sample)

            s->bits_per_raw_sample = avctx->bits_per_raw_sample;

        s->colorspace = 1;

        s->chroma_planes = 1;

        if (s->bits_per_raw_sample >= 16) {

            s->use32bit = 1;

            if (avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {

                av_log(avctx, AV_LOG_ERROR, "16bit RGB is experimental and under development, only use it for experiments\n");

                return AVERROR_INVALIDDATA;

            }

        }

        s->version = FFMAX(s->version, 1);

        break;

    default:

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

        return AVERROR(ENOSYS);

    }

    av_assert0(s->bits_per_raw_sample >= 8);

    if (s->bits_per_raw_sample > 8) {

        if (s->ac == AC_GOLOMB_RICE) {

            av_log(avctx, AV_LOG_INFO,

                    "bits_per_raw_sample > 8, forcing range coder\n");

            s->ac = AC_RANGE_CUSTOM_TAB;

        }

    }

    if (s->transparency) {

        av_log(avctx, AV_LOG_WARNING, "Storing alpha plane, this will require a recent FFV1 decoder to playback!\n");

    }

#if FF_API_PRIVATE_OPT

FF_DISABLE_DEPRECATION_WARNINGS

    if (avctx->context_model)

        s->context_model = avctx->context_model;

    if (avctx->context_model > 1U) {

        av_log(avctx, AV_LOG_ERROR, "Invalid context model %d, valid values are 0 and 1\n", avctx->context_model);

        return AVERROR(EINVAL);

    }

FF_ENABLE_DEPRECATION_WARNINGS

#endif

    if (s->ac == AC_RANGE_CUSTOM_TAB) {

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

            s->state_transition[i] = ver2_state[i];

    } else {

        RangeCoder c;

        ff_build_rac_states(&c, 0.05 * (1LL << 32), 256 - 8);

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

            s->state_transition[i] = c.one_state[i];

    }

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

        s->quant_table_count = 2;

        if (s->bits_per_raw_sample <= 8) {

            s->quant_tables[0][0][i]=           quant11[i];

            s->quant_tables[0][1][i]=        11*quant11[i];

            s->quant_tables[0][2][i]=     11*11*quant11[i];

            s->quant_tables[1][0][i]=           quant11[i];

            s->quant_tables[1][1][i]=        11*quant11[i];

            s->quant_tables[1][2][i]=     11*11*quant5 [i];

            s->quant_tables[1][3][i]=   5*11*11*quant5 [i];

            s->quant_tables[1][4][i]= 5*5*11*11*quant5 [i];

        } else {

            s->quant_tables[0][0][i]=           quant9_10bit[i];

            s->quant_tables[0][1][i]=        11*quant9_10bit[i];

            s->quant_tables[0][2][i]=     11*11*quant9_10bit[i];

            s->quant_tables[1][0][i]=           quant9_10bit[i];

            s->quant_tables[1][1][i]=        11*quant9_10bit[i];

            s->quant_tables[1][2][i]=     11*11*quant5_10bit[i];

            s->quant_tables[1][3][i]=   5*11*11*quant5_10bit[i];

            s->quant_tables[1][4][i]= 5*5*11*11*quant5_10bit[i];

        }

    }

    s->context_count[0] = (11 * 11 * 11        + 1) / 2;

    s->context_count[1] = (11 * 11 * 5 * 5 * 5 + 1) / 2;

    memcpy(s->quant_table, s->quant_tables[s->context_model],

           sizeof(s->quant_table));

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

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

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

        p->quant_table_index = s->context_model;

        p->context_count     = s->context_count[p->quant_table_index];

    }

    if ((ret = ff_ffv1_allocate_initial_states(s)) < 0)

        return ret;

#if FF_API_CODED_FRAME

FF_DISABLE_DEPRECATION_WARNINGS

    avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;

FF_ENABLE_DEPRECATION_WARNINGS

#endif

    if (!s->transparency)

        s->plane_count = 2;

    if (!s->chroma_planes && s->version > 3)

        s->plane_count--;

    avcodec_get_chroma_sub_sample(avctx->pix_fmt, &s->chroma_h_shift, &s->chroma_v_shift);

    s->picture_number = 0;

    if (avctx->flags & (AV_CODEC_FLAG_PASS1 | AV_CODEC_FLAG_PASS2)) {

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

            s->rc_stat2[i] = av_mallocz(s->context_count[i] *

                                        sizeof(*s->rc_stat2[i]));

            if (!s->rc_stat2[i])

                return AVERROR(ENOMEM);

        }

    }

    if (avctx->stats_in) {

        char *p = avctx->stats_in;

        uint8_t (*best_state)[256] = av_malloc_array(256, 256);

        int gob_count = 0;

        char *next;

        if (!best_state)

            return AVERROR(ENOMEM);

        av_assert0(s->version >= 2);

        for (;;) {

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

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

                    s->rc_stat[j][i] = strtol(p, &next, 0);

                    if (next == p) {

                        av_log(avctx, AV_LOG_ERROR,

                               "2Pass file invalid at %d %d [%s]\n", j, i, p);

                        av_freep(&best_state);

                        return AVERROR_INVALIDDATA;

                    }

                    p = next;

                }

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

                for (j = 0; j < s->context_count[i]; j++) {

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

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

                            s->rc_stat2[i][j][k][m] = strtol(p, &next, 0);

                            if (next == p) {

                                av_log(avctx, AV_LOG_ERROR,

                                       "2Pass file invalid at %d %d %d %d [%s]\n",

                                       i, j, k, m, p);

                                av_freep(&best_state);

                                return AVERROR_INVALIDDATA;

                            }

                            p = next;

                        }

                }

            gob_count = strtol(p, &next, 0);

            if (next == p || gob_count <= 0) {

                av_log(avctx, AV_LOG_ERROR, "2Pass file invalid\n");

                av_freep(&best_state);

                return AVERROR_INVALIDDATA;

            }

            p = next;

            while (*p == '\n' || *p == ' ')

                p++;

            if (p[0] == 0)

                break;

        }

        if (s->ac == AC_RANGE_CUSTOM_TAB)

            sort_stt(s, s->state_transition);

        find_best_state(best_state, s->state_transition);

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

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

                double a=0, b=0;

                int jp = 0;

                for (j = 0; j < s->context_count[i]; j++) {

                    double p = 128;

                    if (s->rc_stat2[i][j][k][0] + s->rc_stat2[i][j][k][1] > 200 && j || a+b > 200) {

                        if (a+b)

                            p = 256.0 * b / (a + b);

                        s->initial_states[i][jp][k] =

                            best_state[av_clip(round(p), 1, 255)][av_clip_uint8((a + b) / gob_count)];

                        for(jp++; jp<j; jp++)

                            s->initial_states[i][jp][k] = s->initial_states[i][jp-1][k];

                        a=b=0;

                    }

                    a += s->rc_stat2[i][j][k][0];

                    b += s->rc_stat2[i][j][k][1];

                    if (a+b) {

                        p = 256.0 * b / (a + b);

                    }

                    s->initial_states[i][j][k] =

                        best_state[av_clip(round(p), 1, 255)][av_clip_uint8((a + b) / gob_count)];

                }

            }

        }

        av_freep(&best_state);

    }

    if (s->version > 1) {

        int plane_count = 1 + 2*s->chroma_planes + s->transparency;

        s->num_v_slices = (avctx->width > 352 || avctx->height > 288 || !avctx->slices) ? 2 : 1;

        if (avctx->height < 5)

            s->num_v_slices = 1;

        for (; s->num_v_slices < 32; s->num_v_slices++) {

            for (s->num_h_slices = s->num_v_slices; s->num_h_slices < 2*s->num_v_slices; s->num_h_slices++) {

                int maxw = (avctx->width  + s->num_h_slices - 1) / s->num_h_slices;

                int maxh = (avctx->height + s->num_v_slices - 1) / s->num_v_slices;

                if (s->num_h_slices > avctx->width || s->num_v_slices > avctx->height)

                    continue;

                if (maxw * maxh * (int64_t)(s->bits_per_raw_sample+1) * plane_count > 8<<24)

                    continue;

                if (avctx->slices == s->num_h_slices * s->num_v_slices && avctx->slices <= MAX_SLICES || !avctx->slices)

                    goto slices_ok;

            }

        }

        av_log(avctx, AV_LOG_ERROR,

               "Unsupported number %d of slices requested, please specify a "

               "supported number with -slices (ex:4,6,9,12,16, ...)\n",

               avctx->slices);

        return AVERROR(ENOSYS);

slices_ok:

        if ((ret = write_extradata(s)) < 0)

            return ret;

    }

    if ((ret = ff_ffv1_init_slice_contexts(s)) < 0)

        return ret;

    s->slice_count = s->max_slice_count;

    if ((ret = ff_ffv1_init_slices_state(s)) < 0)

        return ret;

#define STATS_OUT_SIZE 1024 * 1024 * 6

    if (avctx->flags & AV_CODEC_FLAG_PASS1) {

        avctx->stats_out = av_mallocz(STATS_OUT_SIZE);

        if (!avctx->stats_out)

            return AVERROR(ENOMEM);

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

            for (j = 0; j < s->max_slice_count; j++) {

                FFV1Context *sf = s->slice_context[j];

                av_assert0(!sf->rc_stat2[i]);

                sf->rc_stat2[i] = av_mallocz(s->context_count[i] *

                                             sizeof(*sf->rc_stat2[i]));

                if (!sf->rc_stat2[i])

                    return AVERROR(ENOMEM);

            }

    }

    return 0;

}


static int hls_slice_data_wpp(HEVCContext *s, const HEVCNAL *nal)

{

    const uint8_t *data = nal->data;

    int length          = nal->size;

    HEVCLocalContext *lc = s->HEVClc;

    int *ret = av_malloc_array(s->sh.num_entry_point_offsets + 1, sizeof(int));

    int *arg = av_malloc_array(s->sh.num_entry_point_offsets + 1, sizeof(int));

    int64_t offset;

    int startheader, cmpt = 0;

    int i, j, res = 0;

    if (!ret || !arg) {

        av_free(ret);

        av_free(arg);

        return AVERROR(ENOMEM);

    }

    if (!s->sList[1]) {

        ff_alloc_entries(s->avctx, s->sh.num_entry_point_offsets + 1);

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

            s->sList[i] = av_malloc(sizeof(HEVCContext));

            memcpy(s->sList[i], s, sizeof(HEVCContext));

            s->HEVClcList[i] = av_mallocz(sizeof(HEVCLocalContext));

            s->sList[i]->HEVClc = s->HEVClcList[i];

        }

    }

    offset = (lc->gb.index >> 3);

    for (j = 0, cmpt = 0, startheader = offset + s->sh.entry_point_offset[0]; j < nal->skipped_bytes; j++) {

        if (nal->skipped_bytes_pos[j] >= offset && nal->skipped_bytes_pos[j] < startheader) {

            startheader--;

            cmpt++;

        }

    }

    for (i = 1; i < s->sh.num_entry_point_offsets; i++) {

        offset += (s->sh.entry_point_offset[i - 1] - cmpt);

        for (j = 0, cmpt = 0, startheader = offset

             + s->sh.entry_point_offset[i]; j < nal->skipped_bytes; j++) {

            if (nal->skipped_bytes_pos[j] >= offset && nal->skipped_bytes_pos[j] < startheader) {

                startheader--;

                cmpt++;

            }

        }

        s->sh.size[i - 1] = s->sh.entry_point_offset[i] - cmpt;

        s->sh.offset[i - 1] = offset;

    }

    if (s->sh.num_entry_point_offsets != 0) {

        offset += s->sh.entry_point_offset[s->sh.num_entry_point_offsets - 1] - cmpt;

        if (length < offset) {

            av_log(s->avctx, AV_LOG_ERROR, "entry_point_offset table is corrupted\n");

            res = AVERROR_INVALIDDATA;

            goto error;

        }

        s->sh.size[s->sh.num_entry_point_offsets - 1] = length - offset;

        s->sh.offset[s->sh.num_entry_point_offsets - 1] = offset;

    }

    s->data = data;

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

        s->sList[i]->HEVClc->first_qp_group = 1;

        s->sList[i]->HEVClc->qp_y = s->sList[0]->HEVClc->qp_y;

        memcpy(s->sList[i], s, sizeof(HEVCContext));

        s->sList[i]->HEVClc = s->HEVClcList[i];

    }

    avpriv_atomic_int_set(&s->wpp_err, 0);

    ff_reset_entries(s->avctx);

    for (i = 0; i <= s->sh.num_entry_point_offsets; i++) {

        arg[i] = i;

        ret[i] = 0;

    }

    if (s->ps.pps->entropy_coding_sync_enabled_flag)

        s->avctx->execute2(s->avctx, hls_decode_entry_wpp, arg, ret, s->sh.num_entry_point_offsets + 1);

    for (i = 0; i <= s->sh.num_entry_point_offsets; i++)

        res += ret[i];

error:

    av_free(ret);

    av_free(arg);

    return res;

}


static void pxa2xx_lcdc_dma0_redraw_rot0(PXA2xxLCDState *s,

                hwaddr addr, int *miny, int *maxy)

{

    DisplaySurface *surface = qemu_console_surface(s->con);

    int src_width, dest_width;

    drawfn fn = NULL;

    if (s->dest_width)

        fn = s->line_fn[s->transp][s->bpp];

    if (!fn)

        return;

    src_width = (s->xres + 3) & ~3;     /* Pad to a 4 pixels multiple */

    if (s->bpp == pxa_lcdc_19pbpp || s->bpp == pxa_lcdc_18pbpp)

        src_width *= 3;

    else if (s->bpp > pxa_lcdc_16bpp)

        src_width *= 4;

    else if (s->bpp > pxa_lcdc_8bpp)

        src_width *= 2;

    dest_width = s->xres * s->dest_width;

    *miny = 0;

    framebuffer_update_display(surface, s->sysmem,

                               addr, s->xres, s->yres,

                               src_width, dest_width, s->dest_width,

                               s->invalidated,

                               fn, s->dma_ch[0].palette, miny, maxy);

}


build_dmar_q35(GArray *table_data, GArray *linker)

{

    int dmar_start = table_data->len;

    AcpiTableDmar *dmar;

    AcpiDmarHardwareUnit *drhd;

    dmar = acpi_data_push(table_data, sizeof(*dmar));

    dmar->host_address_width = VTD_HOST_ADDRESS_WIDTH - 1;

    dmar->flags = 0;    /* No intr_remap for now */

    /* DMAR Remapping Hardware Unit Definition structure */

    drhd = acpi_data_push(table_data, sizeof(*drhd));

    drhd->type = cpu_to_le16(ACPI_DMAR_TYPE_HARDWARE_UNIT);

    drhd->length = cpu_to_le16(sizeof(*drhd));   /* No device scope now */

    drhd->flags = ACPI_DMAR_INCLUDE_PCI_ALL;

    drhd->pci_segment = cpu_to_le16(0);

    drhd->address = cpu_to_le64(Q35_HOST_BRIDGE_IOMMU_ADDR);

    build_header(linker, table_data, (void *)(table_data->data + dmar_start),

                 "DMAR", table_data->len - dmar_start, 1, NULL);

}


static GtkWidget *gd_create_menu_machine(GtkDisplayState *s, GtkAccelGroup *accel_group)

{

    GtkWidget *machine_menu;

    GtkWidget *separator;

    machine_menu = gtk_menu_new();

    gtk_menu_set_accel_group(GTK_MENU(machine_menu), accel_group);

    s->pause_item = gtk_check_menu_item_new_with_mnemonic(_("_Pause"));

    gtk_menu_shell_append(GTK_MENU_SHELL(machine_menu), s->pause_item);

    separator = gtk_separator_menu_item_new();

    gtk_menu_shell_append(GTK_MENU_SHELL(machine_menu), separator);

    s->reset_item = gtk_menu_item_new_with_mnemonic(_("_Reset"));

    gtk_menu_shell_append(GTK_MENU_SHELL(machine_menu), s->reset_item);

    s->powerdown_item = gtk_menu_item_new_with_mnemonic(_("Power _Down"));

    gtk_menu_shell_append(GTK_MENU_SHELL(machine_menu), s->powerdown_item);

    separator = gtk_separator_menu_item_new();

    gtk_menu_shell_append(GTK_MENU_SHELL(machine_menu), separator);

    s->quit_item = gtk_menu_item_new_with_mnemonic(_("_Quit"));

    gtk_menu_item_set_accel_path(GTK_MENU_ITEM(s->quit_item),

                                 "<QEMU>/Machine/Quit");

    gtk_accel_map_add_entry("<QEMU>/Machine/Quit",

                            GDK_KEY_q, GDK_CONTROL_MASK);

    gtk_menu_shell_append(GTK_MENU_SHELL(machine_menu), s->quit_item);

    return machine_menu;

}


static void mv88w8618_flashcfg_write(void *opaque, target_phys_addr_t offset,

                                     uint64_t value, unsigned size)

{

    mv88w8618_flashcfg_state *s = opaque;

    switch (offset) {

    case MP_FLASHCFG_CFGR0:

        s->cfgr0 = value;

        break;

    }

}


static int qemu_rdma_get_fd(void *opaque)

{

    QEMUFileRDMA *rfile = opaque;

    RDMAContext *rdma = rfile->rdma;

    return rdma->comp_channel->fd;

}


static void dump_ppc_insns (CPUPPCState *env)

{

    opc_handler_t **table, *handler;

    const char *p, *q;

    uint8_t opc1, opc2, opc3;

    printf("Instructions set:\n");

    /* opc1 is 6 bits long */

    for (opc1 = 0x00; opc1 < PPC_CPU_OPCODES_LEN; opc1++) {

        table = env->opcodes;

        handler = table[opc1];

        if (is_indirect_opcode(handler)) {

            /* opc2 is 5 bits long */

            for (opc2 = 0; opc2 < PPC_CPU_INDIRECT_OPCODES_LEN; opc2++) {

                table = env->opcodes;

                handler = env->opcodes[opc1];

                table = ind_table(handler);

                handler = table[opc2];

                if (is_indirect_opcode(handler)) {

                    table = ind_table(handler);

                    /* opc3 is 5 bits long */

                    for (opc3 = 0; opc3 < PPC_CPU_INDIRECT_OPCODES_LEN;

                            opc3++) {

                        handler = table[opc3];

                        if (handler->handler != &gen_invalid) {

                            /* Special hack to properly dump SPE insns */

                            p = strchr(handler->oname, '_');

                            if (p == NULL) {

                                printf("INSN: %02x %02x %02x (%02d %04d) : "

                                       "%s\n",

                                       opc1, opc2, opc3, opc1,

                                       (opc3 << 5) | opc2,

                                       handler->oname);

                            } else {

                                q = "speundef";

                                if ((p - handler->oname) != strlen(q) ||

                                    memcmp(handler->oname, q, strlen(q)) != 0) {

                                    /* First instruction */

                                    printf("INSN: %02x %02x %02x (%02d %04d) : "

                                           "%.*s\n",

                                           opc1, opc2 << 1, opc3, opc1,

                                           (opc3 << 6) | (opc2 << 1),

                                           (int)(p - handler->oname),

                                           handler->oname);

                                }

                                if (strcmp(p + 1, q) != 0) {

                                    /* Second instruction */

                                    printf("INSN: %02x %02x %02x (%02d %04d) : "

                                           "%s\n",

                                           opc1, (opc2 << 1) | 1, opc3, opc1,

                                           (opc3 << 6) | (opc2 << 1) | 1,

                                           p + 1);

                                }

                            }

                        }

                    }

                } else {

                    if (handler->handler != &gen_invalid) {

                        printf("INSN: %02x %02x -- (%02d %04d) : %s\n",

                               opc1, opc2, opc1, opc2, handler->oname);

                    }

                }

            }

        } else {

            if (handler->handler != &gen_invalid) {

                printf("INSN: %02x -- -- (%02d ----) : %s\n",

                       opc1, opc1, handler->oname);

            }

        }

    }

}


yuv2rgb_2_c_template(SwsContext *c, const int16_t *buf[2],

                     const int16_t *ubuf[2], const int16_t *vbuf[2],

                     const int16_t *abuf[2], uint8_t *dest, int dstW,

                     int yalpha, int uvalpha, int y,

                     enum PixelFormat target, int hasAlpha)

{

    const int16_t *buf0  = buf[0],  *buf1  = buf[1],

                  *ubuf0 = ubuf[0], *ubuf1 = ubuf[1],

                  *vbuf0 = vbuf[0], *vbuf1 = vbuf[1],

                  *abuf0 = abuf[0], *abuf1 = abuf[1];

    int  yalpha1 = 4095 - yalpha;

    int uvalpha1 = 4095 - uvalpha;

    int i;

    for (i = 0; i < (dstW >> 1); i++) {

        int Y1 = (buf0[i * 2]     * yalpha1  + buf1[i * 2]     * yalpha)  >> 19;

        int Y2 = (buf0[i * 2 + 1] * yalpha1  + buf1[i * 2 + 1] * yalpha)  >> 19;

        int U  = (ubuf0[i]        * uvalpha1 + ubuf1[i]        * uvalpha) >> 19;

        int V  = (vbuf0[i]        * uvalpha1 + vbuf1[i]        * uvalpha) >> 19;

        int A1, A2;

        const void *r =  c->table_rV[V],

                   *g = (c->table_gU[U] + c->table_gV[V]),

                   *b =  c->table_bU[U];

        if (hasAlpha) {

            A1 = (abuf0[i * 2    ] * yalpha1 + abuf1[i * 2    ] * yalpha) >> 19;

            A2 = (abuf0[i * 2 + 1] * yalpha1 + abuf1[i * 2 + 1] * yalpha) >> 19;

        }

        yuv2rgb_write(dest, i, Y1, Y2, U, V, hasAlpha ? A1 : 0, hasAlpha ? A2 : 0,

                      r, g, b, y, target, hasAlpha);

    }

}


static int minimum_frame_bits(VC2EncContext *s)

{

    int slice_x, slice_y, bits = 0;

    s->size_scaler = 64;

    for (slice_y = 0; slice_y < s->num_y; slice_y++) {

        for (slice_x = 0; slice_x < s->num_x; slice_x++) {

            bits += count_hq_slice(s, NULL, slice_x, slice_y, s->q_ceil);

        }

    }

    return bits;

}


static void fd_coroutine_enter(void *opaque)

{

    FDYieldUntilData *data = opaque;

    qemu_set_fd_handler(data->fd, NULL, NULL, NULL);

    qemu_coroutine_enter(data->co, NULL);

}


static void qcow_aio_write_cb(void *opaque, int ret)

{

    QCowAIOCB *acb = opaque;

    BlockDriverState *bs = acb->common.bs;

    BDRVQcowState *s = bs->opaque;

    int index_in_cluster;

    uint64_t cluster_offset;

    const uint8_t *src_buf;

    int n_end;

    acb->hd_aiocb = NULL;

    if (ret < 0) {

    fail:

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

        qemu_aio_release(acb);

        return;

    }

    acb->nb_sectors -= acb->n;

    acb->sector_num += acb->n;

    acb->buf += acb->n * 512;

    if (acb->nb_sectors == 0) {

        /* request completed */

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

        qemu_aio_release(acb);

        return;

    }

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

    n_end = index_in_cluster + acb->nb_sectors;

    if (s->crypt_method &&

        n_end > QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors)

        n_end = QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors;

    cluster_offset = alloc_cluster_offset(bs, acb->sector_num << 9,

                                          index_in_cluster,

                                          n_end, &acb->n);

    if (!cluster_offset || (cluster_offset & 511) != 0) {

        ret = -EIO;

        goto fail;

    }

    if (s->crypt_method) {

        if (!acb->cluster_data) {

            acb->cluster_data = qemu_mallocz(QCOW_MAX_CRYPT_CLUSTERS *

                                             s->cluster_size);

            if (!acb->cluster_data) {

                ret = -ENOMEM;

                goto fail;

            }

        }

        encrypt_sectors(s, acb->sector_num, acb->cluster_data, acb->buf,

                        acb->n, 1, &s->aes_encrypt_key);

        src_buf = acb->cluster_data;

    } else {

        src_buf = acb->buf;

    }

    acb->hd_aiocb = bdrv_aio_write(s->hd,

                                   (cluster_offset >> 9) + index_in_cluster,

                                   src_buf, acb->n,

                                   qcow_aio_write_cb, acb);

    if (acb->hd_aiocb == NULL)

        goto fail;

}


static int opt_input_file(const char *opt, const char *filename)

{

    AVFormatContext *ic;

    AVInputFormat *file_iformat = NULL;

    int err, i, ret, rfps, rfps_base;

    int64_t timestamp;

    uint8_t buf[128];

    AVDictionary **opts;

    int orig_nb_streams;                     // number of streams before avformat_find_stream_info

    if (last_asked_format) {

        if (!(file_iformat = av_find_input_format(last_asked_format))) {

            fprintf(stderr, "Unknown input format: '%s'\n", last_asked_format);

            ffmpeg_exit(1);

        }

        last_asked_format = NULL;

    }

    if (!strcmp(filename, "-"))

        filename = "pipe:";

    using_stdin |= !strncmp(filename, "pipe:", 5) ||

                    !strcmp(filename, "/dev/stdin");

    /* get default parameters from command line */

    ic = avformat_alloc_context();

    if (!ic) {

        print_error(filename, AVERROR(ENOMEM));

        ffmpeg_exit(1);

    }

    if (audio_sample_rate) {

        snprintf(buf, sizeof(buf), "%d", audio_sample_rate);

        av_dict_set(&format_opts, "sample_rate", buf, 0);

    }

    if (audio_channels) {

        snprintf(buf, sizeof(buf), "%d", audio_channels);

        av_dict_set(&format_opts, "channels", buf, 0);

    }

    if (frame_rate.num) {

        snprintf(buf, sizeof(buf), "%d/%d", frame_rate.num, frame_rate.den);

        av_dict_set(&format_opts, "framerate", buf, 0);

    }

    if (frame_width && frame_height) {

        snprintf(buf, sizeof(buf), "%dx%d", frame_width, frame_height);

        av_dict_set(&format_opts, "video_size", buf, 0);

    }

    if (frame_pix_fmt != PIX_FMT_NONE)

        av_dict_set(&format_opts, "pixel_format", av_get_pix_fmt_name(frame_pix_fmt), 0);

    ic->video_codec_id   =

        find_codec_or_die(video_codec_name   , AVMEDIA_TYPE_VIDEO   , 0);

    ic->audio_codec_id   =

        find_codec_or_die(audio_codec_name   , AVMEDIA_TYPE_AUDIO   , 0);

    ic->subtitle_codec_id=

        find_codec_or_die(subtitle_codec_name, AVMEDIA_TYPE_SUBTITLE, 0);

    ic->flags |= AVFMT_FLAG_NONBLOCK;

    /* open the input file with generic libav function */

    err = avformat_open_input(&ic, filename, file_iformat, &format_opts);

    if (err < 0) {

        print_error(filename, err);

        ffmpeg_exit(1);

    }

    assert_avoptions(format_opts);

    if(opt_programid) {

        int i, j;

        int found=0;

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

            ic->streams[i]->discard= AVDISCARD_ALL;

        }

        for(i=0; i<ic->nb_programs; i++){

            AVProgram *p= ic->programs[i];

            if(p->id != opt_programid){

                p->discard = AVDISCARD_ALL;

            }else{

                found=1;

                for(j=0; j<p->nb_stream_indexes; j++){

                    ic->streams[p->stream_index[j]]->discard= AVDISCARD_DEFAULT;

                }

            }

        }

        if(!found){

            fprintf(stderr, "Specified program id not found\n");

            ffmpeg_exit(1);

        }

        opt_programid=0;

    }

    if (loop_input) {

        av_log(NULL, AV_LOG_WARNING, "-loop_input is deprecated, use -loop 1\n");

        ic->loop_input = loop_input;

    }

    /* Set AVCodecContext options for avformat_find_stream_info */

    opts = setup_find_stream_info_opts(ic, codec_opts);

    orig_nb_streams = ic->nb_streams;

    /* If not enough info to get the stream parameters, we decode the

       first frames to get it. (used in mpeg case for example) */

    ret = avformat_find_stream_info(ic, opts);

    if (ret < 0 && verbose >= 0) {

        fprintf(stderr, "%s: could not find codec parameters\n", filename);

        av_close_input_file(ic);

        ffmpeg_exit(1);

    }

    timestamp = start_time;

    /* add the stream start time */

    if (ic->start_time != AV_NOPTS_VALUE)

        timestamp += ic->start_time;

    /* if seeking requested, we execute it */

    if (start_time != 0) {

        ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);

        if (ret < 0) {

            fprintf(stderr, "%s: could not seek to position %0.3f\n",

                    filename, (double)timestamp / AV_TIME_BASE);

        }

        /* reset seek info */

        start_time = 0;

    }

    /* update the current parameters so that they match the one of the input stream */

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

        AVStream *st = ic->streams[i];

        AVCodecContext *dec = st->codec;

        InputStream *ist;

        dec->thread_count = thread_count;

        input_streams = grow_array(input_streams, sizeof(*input_streams), &nb_input_streams, nb_input_streams + 1);

        ist = &input_streams[nb_input_streams - 1];

        ist->st = st;

        ist->file_index = nb_input_files;

        ist->discard = 1;

        ist->opts = filter_codec_opts(codec_opts, ist->st->codec->codec_id, 0);

        if (i < nb_ts_scale)

            ist->ts_scale = ts_scale[i];

        switch (dec->codec_type) {

        case AVMEDIA_TYPE_AUDIO:

            ist->dec = avcodec_find_decoder_by_name(audio_codec_name);

            if(!ist->dec)

                ist->dec = avcodec_find_decoder(dec->codec_id);

            if(audio_disable)

                st->discard= AVDISCARD_ALL;

            break;

        case AVMEDIA_TYPE_VIDEO:

            ist->dec= avcodec_find_decoder_by_name(video_codec_name);

            if(!ist->dec)

                ist->dec = avcodec_find_decoder(dec->codec_id);

            rfps      = ic->streams[i]->r_frame_rate.num;

            rfps_base = ic->streams[i]->r_frame_rate.den;

            if (dec->lowres) {

                dec->flags |= CODEC_FLAG_EMU_EDGE;

            }

            if(me_threshold)

                dec->debug |= FF_DEBUG_MV;

            if (dec->time_base.den != rfps*dec->ticks_per_frame || dec->time_base.num != rfps_base) {

                if (verbose >= 0)

                    fprintf(stderr,"\nSeems stream %d codec frame rate differs from container frame rate: %2.2f (%d/%d) -> %2.2f (%d/%d)\n",

                            i, (float)dec->time_base.den / dec->time_base.num, dec->time_base.den, dec->time_base.num,

                    (float)rfps / rfps_base, rfps, rfps_base);

            }

            if(video_disable)

                st->discard= AVDISCARD_ALL;

            else if(video_discard)

                st->discard= video_discard;

            break;

        case AVMEDIA_TYPE_DATA:

            break;

        case AVMEDIA_TYPE_SUBTITLE:

            ist->dec = avcodec_find_decoder_by_name(subtitle_codec_name);

            if(!ist->dec)

                ist->dec = avcodec_find_decoder(dec->codec_id);

            if(subtitle_disable)

                st->discard = AVDISCARD_ALL;

            break;

        case AVMEDIA_TYPE_ATTACHMENT:

        case AVMEDIA_TYPE_UNKNOWN:

            break;

        default:

            abort();

        }

    }

    /* dump the file content */

    if (verbose >= 0)

        av_dump_format(ic, nb_input_files, filename, 0);

    input_files = grow_array(input_files, sizeof(*input_files), &nb_input_files, nb_input_files + 1);

    input_files[nb_input_files - 1].ctx        = ic;

    input_files[nb_input_files - 1].ist_index  = nb_input_streams - ic->nb_streams;

    input_files[nb_input_files - 1].ts_offset  = input_ts_offset - (copy_ts ? 0 : timestamp);

    top_field_first = -1;

    frame_rate    = (AVRational){0, 0};

    frame_pix_fmt = PIX_FMT_NONE;

    frame_height = 0;

    frame_width  = 0;

    audio_sample_rate = 0;

    audio_channels    = 0;

    audio_sample_fmt  = AV_SAMPLE_FMT_NONE;

    av_freep(&ts_scale);

    nb_ts_scale = 0;

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

        av_dict_free(&opts[i]);

    av_freep(&opts);

    av_freep(&video_codec_name);

    av_freep(&audio_codec_name);

    av_freep(&subtitle_codec_name);

    uninit_opts();

    init_opts();

    return 0;

}


static int usb_hub_handle_control(USBDevice *dev, USBPacket *p,

               int request, int value, int index, int length, uint8_t *data)

{

    USBHubState *s = (USBHubState *)dev;

    int ret;

    ret = usb_desc_handle_control(dev, p, request, value, index, length, data);

    if (ret >= 0) {

        return ret;

    }

    switch(request) {

    case EndpointOutRequest | USB_REQ_CLEAR_FEATURE:

        if (value == 0 && index != 0x81) { /* clear ep halt */

            goto fail;

        }

        ret = 0;

        break;

    case DeviceRequest | USB_REQ_GET_INTERFACE:

        data[0] = 0;

        ret = 1;

        break;

    case DeviceOutRequest | USB_REQ_SET_INTERFACE:

        ret = 0;

        break;

        /* usb specific requests */

    case GetHubStatus:

        data[0] = 0;

        data[1] = 0;

        data[2] = 0;

        data[3] = 0;

        ret = 4;

        break;

    case GetPortStatus:

        {

            unsigned int n = index - 1;

            USBHubPort *port;

            if (n >= NUM_PORTS) {

                goto fail;

            }

            port = &s->ports[n];

            data[0] = port->wPortStatus;

            data[1] = port->wPortStatus >> 8;

            data[2] = port->wPortChange;

            data[3] = port->wPortChange >> 8;

            ret = 4;

        }

        break;

    case SetHubFeature:

    case ClearHubFeature:

        if (value == 0 || value == 1) {

        } else {

            goto fail;

        }

        ret = 0;

        break;

    case SetPortFeature:

        {

            unsigned int n = index - 1;

            USBHubPort *port;

            USBDevice *dev;

            if (n >= NUM_PORTS) {

                goto fail;

            }

            port = &s->ports[n];

            dev = port->port.dev;

            switch(value) {

            case PORT_SUSPEND:

                port->wPortStatus |= PORT_STAT_SUSPEND;

                break;

            case PORT_RESET:

                if (dev) {

                    usb_send_msg(dev, USB_MSG_RESET);

                    port->wPortChange |= PORT_STAT_C_RESET;

                    /* set enable bit */

                    port->wPortStatus |= PORT_STAT_ENABLE;

                }

                break;

            case PORT_POWER:

                break;

            default:

                goto fail;

            }

            ret = 0;

        }

        break;

    case ClearPortFeature:

        {

            unsigned int n = index - 1;

            USBHubPort *port;

            if (n >= NUM_PORTS) {

                goto fail;

            }

            port = &s->ports[n];

            switch(value) {

            case PORT_ENABLE:

                port->wPortStatus &= ~PORT_STAT_ENABLE;

                break;

            case PORT_C_ENABLE:

                port->wPortChange &= ~PORT_STAT_C_ENABLE;

                break;

            case PORT_SUSPEND:

                port->wPortStatus &= ~PORT_STAT_SUSPEND;

                break;

            case PORT_C_SUSPEND:

                port->wPortChange &= ~PORT_STAT_C_SUSPEND;

                break;

            case PORT_C_CONNECTION:

                port->wPortChange &= ~PORT_STAT_C_CONNECTION;

                break;

            case PORT_C_OVERCURRENT:

                port->wPortChange &= ~PORT_STAT_C_OVERCURRENT;

                break;

            case PORT_C_RESET:

                port->wPortChange &= ~PORT_STAT_C_RESET;

                break;

            default:

                goto fail;

            }

            ret = 0;

        }

        break;

    case GetHubDescriptor:

        {

            unsigned int n, limit, var_hub_size = 0;

            memcpy(data, qemu_hub_hub_descriptor,

                   sizeof(qemu_hub_hub_descriptor));

            data[2] = NUM_PORTS;

            /* fill DeviceRemovable bits */

            limit = ((NUM_PORTS + 1 + 7) / 8) + 7;

            for (n = 7; n < limit; n++) {

                data[n] = 0x00;

                var_hub_size++;

            }

            /* fill PortPwrCtrlMask bits */

            limit = limit + ((NUM_PORTS + 7) / 8);

            for (;n < limit; n++) {

                data[n] = 0xff;

                var_hub_size++;

            }

            ret = sizeof(qemu_hub_hub_descriptor) + var_hub_size;

            data[0] = ret;

            break;

        }

    default:

    fail:

        ret = USB_RET_STALL;

        break;

    }

    return ret;

}


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

{

    MXFContext *mxf = s->priv_data;

    AVIOContext *pb = s->pb;

    AVStream *st = s->streams[pkt->stream_index];

    MXFStreamContext *sc = st->priv_data;

    MXFIndexEntry ie = {0};

    if (!mxf->edit_unit_byte_count && !(mxf->edit_units_count % EDIT_UNITS_PER_BODY)) {

        mxf->index_entries = av_realloc(mxf->index_entries,

            (mxf->edit_units_count + EDIT_UNITS_PER_BODY)*sizeof(*mxf->index_entries));

        if (!mxf->index_entries) {

            av_log(s, AV_LOG_ERROR, "could not allocate index entries\n");

            return -1;

        }

    }

    if (st->codec->codec_id == AV_CODEC_ID_MPEG2VIDEO) {

        if (!mxf_parse_mpeg2_frame(s, st, pkt, &ie)) {

            av_log(s, AV_LOG_ERROR, "could not get mpeg2 profile and level\n");

            return -1;

        }

    }

    if (!mxf->header_written) {

        if (mxf->edit_unit_byte_count) {

            mxf_write_partition(s, 1, 2, header_open_partition_key, 1);

            mxf_write_klv_fill(s);

            mxf_write_index_table_segment(s);

        } else {

            mxf_write_partition(s, 0, 0, header_open_partition_key, 1);

        }

        mxf->header_written = 1;

    }

    if (st->index == 0) {

        if (!mxf->edit_unit_byte_count &&

            (!mxf->edit_units_count || mxf->edit_units_count > EDIT_UNITS_PER_BODY) &&

            !(ie.flags & 0x33)) { // I frame, Gop start

            mxf_write_klv_fill(s);

            mxf_write_partition(s, 1, 2, body_partition_key, 0);

            mxf_write_klv_fill(s);

            mxf_write_index_table_segment(s);

        }

        mxf_write_klv_fill(s);

        mxf_write_system_item(s);

        if (!mxf->edit_unit_byte_count) {

            mxf->index_entries[mxf->edit_units_count].offset = mxf->body_offset;

            mxf->index_entries[mxf->edit_units_count].flags = ie.flags;

            mxf->index_entries[mxf->edit_units_count].temporal_ref = ie.temporal_ref;

            mxf->body_offset += KAG_SIZE; // size of system element

        }

        mxf->edit_units_count++;

    } else if (!mxf->edit_unit_byte_count && st->index == 1) {

        mxf->index_entries[mxf->edit_units_count-1].slice_offset =

            mxf->body_offset - mxf->index_entries[mxf->edit_units_count-1].offset;

    }

    mxf_write_klv_fill(s);

    avio_write(pb, sc->track_essence_element_key, 16); // write key

    if (s->oformat == &ff_mxf_d10_muxer) {

        if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)

            mxf_write_d10_video_packet(s, st, pkt);

        else

            mxf_write_d10_audio_packet(s, st, pkt);

    } else {

        klv_encode_ber4_length(pb, pkt->size); // write length

        avio_write(pb, pkt->data, pkt->size);

        mxf->body_offset += 16+4+pkt->size + klv_fill_size(16+4+pkt->size);

    }

    avio_flush(pb);

    return 0;

}


int cpu_arm_handle_mmu_fault (CPUState *env, target_ulong address,

                              int access_type, int mmu_idx, int is_softmmu)

{

    uint32_t phys_addr;

    target_ulong page_size;

    int prot;

    int ret, is_user;

    is_user = mmu_idx == MMU_USER_IDX;

    ret = get_phys_addr(env, address, access_type, is_user, &phys_addr, &prot,

                        &page_size);

    if (ret == 0) {

        /* Map a single [sub]page.  */

        phys_addr &= ~(uint32_t)0x3ff;

        address &= ~(uint32_t)0x3ff;

        tlb_set_page (env, address, phys_addr, prot | PAGE_EXEC, mmu_idx,

                      page_size);

        return 0;

    }

    if (access_type == 2) {

        env->cp15.c5_insn = ret;

        env->cp15.c6_insn = address;

        env->exception_index = EXCP_PREFETCH_ABORT;

    } else {

        env->cp15.c5_data = ret;

        if (access_type == 1 && arm_feature(env, ARM_FEATURE_V6))

            env->cp15.c5_data |= (1 << 11);

        env->cp15.c6_data = address;

        env->exception_index = EXCP_DATA_ABORT;

    }

    return 1;

}


static inline int get_chroma_qp(H264Context *h, int t, int qscale){

    return h->pps.chroma_qp_table[t][qscale];

}


static int binkb_decode_plane(BinkContext *c, AVFrame *frame, BitstreamContext *bc,

                              int plane_idx, int is_key, int is_chroma)

{

    int blk, ret;

    int i, j, bx, by;

    uint8_t *dst, *ref, *ref_start, *ref_end;

    int v, col[2];

    const uint8_t *scan;

    int xoff, yoff;

    LOCAL_ALIGNED_16(int16_t, block, [64]);

    LOCAL_ALIGNED_16(int32_t, dctblock, [64]);

    int coordmap[64];

    int ybias = is_key ? -15 : 0;

    int qp;

    const int stride = frame->linesize[plane_idx];

    int bw = is_chroma ? (c->avctx->width  + 15) >> 4 : (c->avctx->width  + 7) >> 3;

    int bh = is_chroma ? (c->avctx->height + 15) >> 4 : (c->avctx->height + 7) >> 3;

    binkb_init_bundles(c);

    ref_start = frame->data[plane_idx];

    ref_end   = frame->data[plane_idx] + (bh * frame->linesize[plane_idx] + bw) * 8;

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

        coordmap[i] = (i & 7) + (i >> 3) * stride;

    for (by = 0; by < bh; by++) {

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

            if ((ret = binkb_read_bundle(c, bc, i)) < 0)

                return ret;

        }

        dst  = frame->data[plane_idx]  + 8*by*stride;

        for (bx = 0; bx < bw; bx++, dst += 8) {

            blk = binkb_get_value(c, BINKB_SRC_BLOCK_TYPES);

            switch (blk) {

            case 0:

                break;

            case 1:

                scan = bink_patterns[bitstream_read(bc, 4)];

                i = 0;

                do {

                    int mode = bitstream_read_bit(bc);

                    int run  = bitstream_read(bc, binkb_runbits[i]) + 1;

                    i += run;

                    if (i > 64) {

                        av_log(c->avctx, AV_LOG_ERROR, "Run went out of bounds\n");

                        return AVERROR_INVALIDDATA;

                    }

                    if (mode) {

                        v = binkb_get_value(c, BINKB_SRC_COLORS);

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

                            dst[coordmap[*scan++]] = v;

                    } else {

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

                            dst[coordmap[*scan++]] = binkb_get_value(c, BINKB_SRC_COLORS);

                    }

                } while (i < 63);

                if (i == 63)

                    dst[coordmap[*scan++]] = binkb_get_value(c, BINKB_SRC_COLORS);

                break;

            case 2:

                memset(dctblock, 0, sizeof(*dctblock) * 64);

                dctblock[0] = binkb_get_value(c, BINKB_SRC_INTRA_DC);

                qp = binkb_get_value(c, BINKB_SRC_INTRA_Q);

                read_dct_coeffs(bc, dctblock, bink_scan, binkb_intra_quant, qp);

                c->binkdsp.idct_put(dst, stride, dctblock);

                break;

            case 3:

                xoff = binkb_get_value(c, BINKB_SRC_X_OFF);

                yoff = binkb_get_value(c, BINKB_SRC_Y_OFF) + ybias;

                ref = dst + xoff + yoff * stride;

                if (ref < ref_start || ref + 8*stride > ref_end) {

                    av_log(c->avctx, AV_LOG_WARNING, "Reference block is out of bounds\n");

                } else if (ref + 8*stride < dst || ref >= dst + 8*stride) {

                    c->hdsp.put_pixels_tab[1][0](dst, ref, stride, 8);

                } else {

                    put_pixels8x8_overlapped(dst, ref, stride);

                }

                c->bdsp.clear_block(block);

                v = binkb_get_value(c, BINKB_SRC_INTER_COEFS);

                read_residue(bc, block, v);

                c->binkdsp.add_pixels8(dst, block, stride);

                break;

            case 4:

                xoff = binkb_get_value(c, BINKB_SRC_X_OFF);

                yoff = binkb_get_value(c, BINKB_SRC_Y_OFF) + ybias;

                ref = dst + xoff + yoff * stride;

                if (ref < ref_start || ref + 8 * stride > ref_end) {

                    av_log(c->avctx, AV_LOG_WARNING, "Reference block is out of bounds\n");

                } else if (ref + 8*stride < dst || ref >= dst + 8*stride) {

                    c->hdsp.put_pixels_tab[1][0](dst, ref, stride, 8);

                } else {

                    put_pixels8x8_overlapped(dst, ref, stride);

                }

                memset(dctblock, 0, sizeof(*dctblock) * 64);

                dctblock[0] = binkb_get_value(c, BINKB_SRC_INTER_DC);

                qp = binkb_get_value(c, BINKB_SRC_INTER_Q);

                read_dct_coeffs(bc, dctblock, bink_scan, binkb_inter_quant, qp);

                c->binkdsp.idct_add(dst, stride, dctblock);

                break;

            case 5:

                v = binkb_get_value(c, BINKB_SRC_COLORS);

                c->bdsp.fill_block_tab[1](dst, v, stride, 8);

                break;

            case 6:

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

                    col[i] = binkb_get_value(c, BINKB_SRC_COLORS);

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

                    v = binkb_get_value(c, BINKB_SRC_PATTERN);

                    for (j = 0; j < 8; j++, v >>= 1)

                        dst[i*stride + j] = col[v & 1];

                }

                break;

            case 7:

                xoff = binkb_get_value(c, BINKB_SRC_X_OFF);

                yoff = binkb_get_value(c, BINKB_SRC_Y_OFF) + ybias;

                ref = dst + xoff + yoff * stride;

                if (ref < ref_start || ref + 8 * stride > ref_end) {

                    av_log(c->avctx, AV_LOG_WARNING, "Reference block is out of bounds\n");

                } else if (ref + 8*stride < dst || ref >= dst + 8*stride) {

                    c->hdsp.put_pixels_tab[1][0](dst, ref, stride, 8);

                } else {

                    put_pixels8x8_overlapped(dst, ref, stride);

                }

                break;

            case 8:

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

                    memcpy(dst + i*stride, c->bundle[BINKB_SRC_COLORS].cur_ptr + i*8, 8);

                c->bundle[BINKB_SRC_COLORS].cur_ptr += 64;

                break;

            default:

                av_log(c->avctx, AV_LOG_ERROR, "Unknown block type %d\n", blk);

                return AVERROR_INVALIDDATA;

            }

        }

    }

    if (bitstream_tell(bc) & 0x1F) // next plane data starts at 32-bit boundary

        bitstream_skip(bc, 32 - (bitstream_tell(bc) & 0x1F));

    return 0;

}


static int get_cpsr(QEMUFile *f, void *opaque, size_t size)

{

    ARMCPU *cpu = opaque;

    CPUARMState *env = &cpu->env;

    uint32_t val = qemu_get_be32(f);

    env->aarch64 = ((val & PSTATE_nRW) == 0);

    if (is_a64(env)) {

        pstate_write(env, val);

        return 0;

    }

    /* Avoid mode switch when restoring CPSR */

    env->uncached_cpsr = val & CPSR_M;

    cpsr_write(env, val, 0xffffffff, CPSRWriteRaw);

    return 0;

}


static void term_handle_byte(int ch)

{

    switch(term_esc_state) {

    case IS_NORM:

        switch(ch) {

        case 1:

            term_bol();

            break;

        case 4:

            term_delete_char();

            break;

        case 5:

            term_eol();

            break;

        case 9:

            term_completion();

            break;

        case 10:

        case 13:

            term_cmd_buf[term_cmd_buf_size] = '\0';

	    term_hist_add(term_cmd_buf);

            term_printf("\n");

            term_handle_command(term_cmd_buf);

            term_show_prompt();

            break;

        case 27:

            term_esc_state = IS_ESC;

            break;

        case 127:

        case 8:

            term_backspace();

            break;

	case 155:

            term_esc_state = IS_CSI;

	    break;

        default:

            if (ch >= 32) {

                term_insert_char(ch);

            }

            break;

        }

        break;

    case IS_ESC:

        if (ch == '[') {

            term_esc_state = IS_CSI;

            term_esc_param = 0;

        } else {

            term_esc_state = IS_NORM;

        }

        break;

    case IS_CSI:

        switch(ch) {

	case 'A':

	case 'F':

	    term_up_char();

	    break;

	case 'B':

	case 'E':

	    term_down_char();

	    break;

        case 'D':

            term_backward_char();

            break;

        case 'C':

            term_forward_char();

            break;

        case '0' ... '9':

            term_esc_param = term_esc_param * 10 + (ch - '0');

            goto the_end;

        case '~':

            switch(term_esc_param) {

            case 1:

                term_bol();

                break;

            case 3:

                term_delete_char();

                break;

            case 4:

                term_eol();

                break;

            }

            break;

        default:

            break;

        }

        term_esc_state = IS_NORM;

    the_end:

        break;

    }

    term_update();

}


struct omap_l4_s *omap_l4_init(target_phys_addr_t base, int ta_num)

{

    struct omap_l4_s *bus = g_malloc0(

                    sizeof(*bus) + ta_num * sizeof(*bus->ta));

    bus->ta_num = ta_num;

    bus->base = base;

#ifdef L4_MUX_HACK

    omap_l4_io_entries = 1;

    omap_l4_io_entry = g_malloc0(125 * sizeof(*omap_l4_io_entry));

    omap_cpu_io_entry =

            cpu_register_io_memory(omap_l4_io_readfn,

                            omap_l4_io_writefn, bus, DEVICE_NATIVE_ENDIAN);

# define L4_PAGES	(0xb4000 / TARGET_PAGE_SIZE)

    omap_l4_io_readb_fn = g_malloc0(sizeof(void *) * L4_PAGES);

    omap_l4_io_readh_fn = g_malloc0(sizeof(void *) * L4_PAGES);

    omap_l4_io_readw_fn = g_malloc0(sizeof(void *) * L4_PAGES);

    omap_l4_io_writeb_fn = g_malloc0(sizeof(void *) * L4_PAGES);

    omap_l4_io_writeh_fn = g_malloc0(sizeof(void *) * L4_PAGES);

    omap_l4_io_writew_fn = g_malloc0(sizeof(void *) * L4_PAGES);

    omap_l4_io_opaque = g_malloc0(sizeof(void *) * L4_PAGES);

#endif

    return bus;

}


static void qbus_list_bus(DeviceState *dev, char *dest, int len)

{

    BusState *child;

    const char *sep = " ";

    int pos = 0;

    pos += snprintf(dest+pos, len-pos,"child busses at \"%s\":",

                    dev->id ? dev->id : dev->info->name);

    LIST_FOREACH(child, &dev->child_bus, sibling) {

        pos += snprintf(dest+pos, len-pos, "%s\"%s\"", sep, child->name);

        sep = ", ";

    }

}


static int read_directory(BDRVVVFATState* s, int mapping_index)

{

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

    direntry_t* direntry;

    const char* dirname = mapping->path;

    int first_cluster = mapping->begin;

    int parent_index = mapping->info.dir.parent_mapping_index;

    mapping_t* parent_mapping = (mapping_t*)

        (parent_index >= 0 ? array_get(&(s->mapping), parent_index) : NULL);

    int first_cluster_of_parent = parent_mapping ? parent_mapping->begin : -1;

    DIR* dir=opendir(dirname);

    struct dirent* entry;

    int i;

    assert(mapping->mode & MODE_DIRECTORY);

    if(!dir) {

        mapping->end = mapping->begin;

        return -1;

    }

    i = mapping->info.dir.first_dir_index =

            first_cluster == 0 ? 0 : s->directory.next;

    if (first_cluster != 0) {

        /* create the top entries of a subdirectory */

        (void)create_short_and_long_name(s, i, ".", 1);

        (void)create_short_and_long_name(s, i, "..", 1);

    }

    /* actually read the directory, and allocate the mappings */

    while((entry=readdir(dir))) {

        unsigned int length=strlen(dirname)+2+strlen(entry->d_name);

        char* buffer;

        direntry_t* direntry;

        struct stat st;

        int is_dot=!strcmp(entry->d_name,".");

        int is_dotdot=!strcmp(entry->d_name,"..");

        if(first_cluster == 0 && (is_dotdot || is_dot))

            continue;

        buffer = g_malloc(length);

        snprintf(buffer,length,"%s/%s",dirname,entry->d_name);

        if(stat(buffer,&st)<0) {

            g_free(buffer);

            continue;

        }

        /* create directory entry for this file */

        if (!is_dot && !is_dotdot) {

            direntry = create_short_and_long_name(s, i, entry->d_name, 0);

        } else {

            direntry = array_get(&(s->directory), is_dot ? i : i + 1);

        }

        direntry->attributes=(S_ISDIR(st.st_mode)?0x10:0x20);

        direntry->reserved[0]=direntry->reserved[1]=0;

        direntry->ctime=fat_datetime(st.st_ctime,1);

        direntry->cdate=fat_datetime(st.st_ctime,0);

        direntry->adate=fat_datetime(st.st_atime,0);

        direntry->begin_hi=0;

        direntry->mtime=fat_datetime(st.st_mtime,1);

        direntry->mdate=fat_datetime(st.st_mtime,0);

        if(is_dotdot)

            set_begin_of_direntry(direntry, first_cluster_of_parent);

        else if(is_dot)

            set_begin_of_direntry(direntry, first_cluster);

        else

            direntry->begin=0; /* do that later */

        if (st.st_size > 0x7fffffff) {

            fprintf(stderr, "File %s is larger than 2GB\n", buffer);

            g_free(buffer);

            closedir(dir);

            return -2;

        }

        direntry->size=cpu_to_le32(S_ISDIR(st.st_mode)?0:st.st_size);

        /* create mapping for this file */

        if(!is_dot && !is_dotdot && (S_ISDIR(st.st_mode) || st.st_size)) {

            s->current_mapping = array_get_next(&(s->mapping));

            s->current_mapping->begin=0;

            s->current_mapping->end=st.st_size;

            /*

             * we get the direntry of the most recent direntry, which

             * contains the short name and all the relevant information.

             */

            s->current_mapping->dir_index=s->directory.next-1;

            s->current_mapping->first_mapping_index = -1;

            if (S_ISDIR(st.st_mode)) {

                s->current_mapping->mode = MODE_DIRECTORY;

                s->current_mapping->info.dir.parent_mapping_index =

                    mapping_index;

            } else {

                s->current_mapping->mode = MODE_UNDEFINED;

                s->current_mapping->info.file.offset = 0;

            }

            s->current_mapping->path=buffer;

            s->current_mapping->read_only =

                (st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)) == 0;

        } else {

            g_free(buffer);

        }

    }

    closedir(dir);

    /* fill with zeroes up to the end of the cluster */

    while(s->directory.next%(0x10*s->sectors_per_cluster)) {

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

        memset(direntry,0,sizeof(direntry_t));

    }

/* TODO: if there are more entries, bootsector has to be adjusted! */

#define ROOT_ENTRIES (0x02 * 0x10 * s->sectors_per_cluster)

    if (mapping_index == 0 && s->directory.next < ROOT_ENTRIES) {

        /* root directory */

        int cur = s->directory.next;

        array_ensure_allocated(&(s->directory), ROOT_ENTRIES - 1);

        s->directory.next = ROOT_ENTRIES;

        memset(array_get(&(s->directory), cur), 0,

                (ROOT_ENTRIES - cur) * sizeof(direntry_t));

    }

    /* re-get the mapping, since s->mapping was possibly realloc()ed */

    mapping = array_get(&(s->mapping), mapping_index);

    first_cluster += (s->directory.next - mapping->info.dir.first_dir_index)

        * 0x20 / s->cluster_size;

    mapping->end = first_cluster;

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

    set_begin_of_direntry(direntry, mapping->begin);

    return 0;

}


static int replace_int_data_in_filename(char *buf, int buf_size, const char *filename, char placeholder, int64_t number)

{

    const char *p;

    char *q, buf1[20], c;

    int nd, len, addchar_count;

    int found_count = 0;

    q = buf;

    p = filename;

    for (;;) {

        c = *p;

        if (c == '\0')

            break;

        if (c == '%' && *(p+1) == '%')  // %%

            addchar_count = 2;

        else if (c == '%' && (av_isdigit(*(p+1)) || *(p+1) == placeholder)) {

            nd = 0;

            addchar_count = 1;

            while (av_isdigit(*(p + addchar_count))) {

                nd = nd * 10 + *(p + addchar_count) - '0';

                addchar_count++;

            }

            if (*(p + addchar_count) == placeholder) {

                len = snprintf(buf1, sizeof(buf1), "%0*"PRId64, (number < 0) ? nd : nd++, number);

                if (len < 1)  // returned error or empty buf1

                    goto fail;

                if ((q - buf + len) > buf_size - 1)

                    goto fail;

                memcpy(q, buf1, len);

                q += len;

                p += (addchar_count + 1);

                addchar_count = 0;

                found_count++;

            }

        } else

            addchar_count = 1;

        while (addchar_count--)

            if ((q - buf) < buf_size - 1)

                *q++ = *p++;

            else

                goto fail;

    }

    *q = '\0';

    return found_count;

fail:

    *q = '\0';

    return -1;

}


static void cubieboard_init(QEMUMachineInitArgs *args)

{

    CubieBoardState *s = g_new(CubieBoardState, 1);

    Error *err = NULL;

    s->a10 = AW_A10(object_new(TYPE_AW_A10));

    object_property_set_bool(OBJECT(s->a10), true, "realized", &err);

    if (err != NULL) {

        error_report("Couldn't realize Allwinner A10: %s\n",

                error_get_pretty(err));

        exit(1);

    }

    memory_region_init_ram(&s->sdram, NULL, "cubieboard.ram", args->ram_size);

    vmstate_register_ram_global(&s->sdram);

    memory_region_add_subregion(get_system_memory(), AW_A10_SDRAM_BASE,

                                &s->sdram);

    cubieboard_binfo.ram_size = args->ram_size;

    cubieboard_binfo.kernel_filename = args->kernel_filename;

    cubieboard_binfo.kernel_cmdline = args->kernel_cmdline;

    arm_load_kernel(&s->a10->cpu, &cubieboard_binfo);

}


void esp_init(target_phys_addr_t espaddr, int it_shift,

              ESPDMAMemoryReadWriteFunc dma_memory_read,

              ESPDMAMemoryReadWriteFunc dma_memory_write,

              void *dma_opaque, qemu_irq irq, qemu_irq *reset,

              qemu_irq *dma_enable)

{

    DeviceState *dev;

    SysBusDevice *s;

    SysBusESPState *sysbus;

    ESPState *esp;

    dev = qdev_create(NULL, "esp");

    sysbus = DO_UPCAST(SysBusESPState, busdev.qdev, dev);

    esp = &sysbus->esp;

    esp->dma_memory_read = dma_memory_read;

    esp->dma_memory_write = dma_memory_write;

    esp->dma_opaque = dma_opaque;

    sysbus->it_shift = it_shift;

    /* XXX for now until rc4030 has been changed to use DMA enable signal */

    esp->dma_enabled = 1;

    qdev_init_nofail(dev);

    s = sysbus_from_qdev(dev);

    sysbus_connect_irq(s, 0, irq);

    sysbus_mmio_map(s, 0, espaddr);

    *reset = qdev_get_gpio_in(dev, 0);

    *dma_enable = qdev_get_gpio_in(dev, 1);

}


static void apply_window_and_mdct(AVCodecContext *avctx, const AVFrame *frame)

{

    WMACodecContext *s = avctx->priv_data;

    float **audio      = (float **) frame->extended_data;

    int len            = frame->nb_samples;

    int window_index   = s->frame_len_bits - s->block_len_bits;

    FFTContext *mdct   = &s->mdct_ctx[window_index];

    int ch;

    const float *win   = s->windows[window_index];

    int window_len     = 1 << s->block_len_bits;

    float n            = 2.0 * 32768.0 / window_len;

    for (ch = 0; ch < avctx->channels; ch++) {

        memcpy(s->output, s->frame_out[ch], window_len * sizeof(*s->output));

        s->fdsp->vector_fmul_scalar(s->frame_out[ch], audio[ch], n, len);

        s->fdsp->vector_fmul_reverse(&s->output[window_len], s->frame_out[ch],

                                    win, len);

        s->fdsp->vector_fmul(s->frame_out[ch], s->frame_out[ch], win, len);

        mdct->mdct_calc(mdct, s->coefs[ch], s->output);

    }

}


static void diff_pixels_altivec(int16_t *restrict block, const uint8_t *s1,

                                const uint8_t *s2, int stride)

{

    int i;

    vec_u8 perm1 = vec_lvsl(0, s1);

    vec_u8 perm2 = vec_lvsl(0, s2);

    const vec_u8 zero = (const vec_u8)vec_splat_u8(0);

    vec_s16 shorts1, shorts2;

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

        /* Read potentially unaligned pixels.

         * We're reading 16 pixels, and actually only want 8,

         * but we simply ignore the extras. */

        vec_u8 pixl  = vec_ld(0,  s1);

        vec_u8 pixr  = vec_ld(15, s1);

        vec_u8 bytes = vec_perm(pixl, pixr, perm1);

        // Convert the bytes into shorts.

        shorts1 = (vec_s16)vec_mergeh(zero, bytes);

        // Do the same for the second block of pixels.

        pixl  = vec_ld(0,  s2);

        pixr  = vec_ld(15, s2);

        bytes = vec_perm(pixl, pixr, perm2);

        // Convert the bytes into shorts.

        shorts2 = (vec_s16)vec_mergeh(zero, bytes);

        // Do the subtraction.

        shorts1 = vec_sub(shorts1, shorts2);

        // Save the data to the block, we assume the block is 16-byte aligned.

        vec_st(shorts1, 0, (vec_s16 *)block);

        s1    += stride;

        s2    += stride;

        block += 8;

        /* The code below is a copy of the code above...

         * This is a manual unroll. */

        /* Read potentially unaligned pixels.

         * We're reading 16 pixels, and actually only want 8,

         * but we simply ignore the extras. */

        pixl  = vec_ld(0,  s1);

        pixr  = vec_ld(15, s1);

        bytes = vec_perm(pixl, pixr, perm1);

        // Convert the bytes into shorts.

        shorts1 = (vec_s16)vec_mergeh(zero, bytes);

        // Do the same for the second block of pixels.

        pixl  = vec_ld(0,  s2);

        pixr  = vec_ld(15, s2);

        bytes = vec_perm(pixl, pixr, perm2);

        // Convert the bytes into shorts.

        shorts2 = (vec_s16)vec_mergeh(zero, bytes);

        // Do the subtraction.

        shorts1 = vec_sub(shorts1, shorts2);

        // Save the data to the block, we assume the block is 16-byte aligned.

        vec_st(shorts1, 0, (vec_s16 *)block);

        s1    += stride;

        s2    += stride;

        block += 8;

    }

}


int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f)

{

    PerThreadContext *p = avctx->thread_opaque;

    int *progress, err;

    f->owner = avctx;

    ff_init_buffer_info(avctx, f);

    if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {

        f->thread_opaque = NULL;

        return avctx->get_buffer(avctx, f);

    }

    if (p->state != STATE_SETTING_UP &&

        (avctx->codec->update_thread_context || (!avctx->thread_safe_callbacks &&

                avctx->get_buffer != avcodec_default_get_buffer))) {

        av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");

        return -1;

    }

    pthread_mutex_lock(&p->parent->buffer_mutex);

    f->thread_opaque = progress = allocate_progress(p);

    if (!progress) {

        pthread_mutex_unlock(&p->parent->buffer_mutex);

        return -1;

    }

    progress[0] =

    progress[1] = -1;

    if (avctx->thread_safe_callbacks ||

        avctx->get_buffer == avcodec_default_get_buffer) {

        err = avctx->get_buffer(avctx, f);

    } else {

        p->requested_frame = f;

        p->state = STATE_GET_BUFFER;

        pthread_mutex_lock(&p->progress_mutex);

        pthread_cond_signal(&p->progress_cond);

        while (p->state != STATE_SETTING_UP)

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

        err = p->result;

        pthread_mutex_unlock(&p->progress_mutex);

        if (!avctx->codec->update_thread_context)

            ff_thread_finish_setup(avctx);

    }

    pthread_mutex_unlock(&p->parent->buffer_mutex);

    return err;

}


bool qio_task_propagate_error(QIOTask *task,

                              Error **errp)

{

    if (task->err) {

        error_propagate(errp, task->err);

        return true;

    }

    return false;

}


static void hds_free(AVFormatContext *s)

{

    HDSContext *c = s->priv_data;

    int i, j;

    if (!c->streams)

        return;

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

        OutputStream *os = &c->streams[i];

        if (os->out)

            avio_close(os->out);

        os->out = NULL;

        if (os->ctx && os->ctx_inited)

            av_write_trailer(os->ctx);

        if (os->ctx && os->ctx->pb)

            av_free(os->ctx->pb);

        if (os->ctx)

            avformat_free_context(os->ctx);

        av_free(os->metadata);

        for (j = 0; j < os->nb_extra_packets; j++)

            av_free(os->extra_packets[j]);

        for (j = 0; j < os->nb_fragments; j++)

            av_free(os->fragments[j]);

        av_free(os->fragments);

    }

    av_freep(&c->streams);

}


yuv2ya8_2_c(SwsContext *c, const int16_t *buf[2],

            const int16_t *ubuf[2], const int16_t *vbuf[2],

            const int16_t *abuf[2], uint8_t *dest, int dstW,

            int yalpha, int uvalpha, int y)

{

    int hasAlpha = abuf[0] && abuf[1];

    const int16_t *buf0  = buf[0],  *buf1  = buf[1],

                  *abuf0 = hasAlpha ? abuf[0] : NULL,

                  *abuf1 = hasAlpha ? abuf[1] : NULL;

    int  yalpha1 = 4096 - yalpha;

    int i;

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

        int Y = (buf0[i * 2] * yalpha1 + buf1[i * 2] * yalpha) >> 19;

        int A;

        Y = av_clip_uint8(Y);

        if (hasAlpha) {

            A = (abuf0[i * 2] * yalpha1 + abuf1[i * 2] * yalpha) >> 19;

            A = av_clip_uint8(A);

        }

        dest[i * 2    ] = Y;

        dest[i * 2 + 1] = hasAlpha ? A : 255;

    }

}


static void device_unparent(Object *obj)

{

    DeviceState *dev = DEVICE(obj);

    BusState *bus;

    if (dev->realized) {

        object_property_set_bool(obj, false, "realized", NULL);

    }

    while (dev->num_child_bus) {

        bus = QLIST_FIRST(&dev->child_bus);

        object_unparent(OBJECT(bus));

    }

    if (dev->parent_bus) {

        bus_remove_child(dev->parent_bus, dev);

        object_unref(OBJECT(dev->parent_bus));

        dev->parent_bus = NULL;

    }

    /* Only send event if the device had been completely realized */

    if (dev->pending_deleted_event) {

        g_assert(dev->canonical_path);

        qapi_event_send_device_deleted(!!dev->id, dev->id, dev->canonical_path,

                                       &error_abort);

        g_free(dev->canonical_path);

        dev->canonical_path = NULL;

    }

}


QBool *qbool_from_bool(bool value)

{

    QBool *qb;

    qb = g_malloc(sizeof(*qb));

    qb->value = value;

    QOBJECT_INIT(qb, &qbool_type);

    return qb;

}


static void setup_rt_frame(int usig, struct emulated_sigaction *ka,

                           target_siginfo_t *info,

			   target_sigset_t *set, CPUState *env)

{

	struct rt_sigframe *frame = get_sigframe(ka, env, sizeof(*frame));

	int err = 0;

#if 0

	if (!access_ok(VERIFY_WRITE, frame, sizeof (*frame)))

            return 1;

#endif

	__put_user_error(&frame->info, (target_ulong *)&frame->pinfo, err);

	__put_user_error(&frame->uc, (target_ulong *)&frame->puc, err);

	err |= copy_siginfo_to_user(&frame->info, info);

	/* Clear all the bits of the ucontext we don't use.  */

	err |= __clear_user(&frame->uc, offsetof(struct ucontext, uc_mcontext));

	err |= setup_sigcontext(&frame->uc.uc_mcontext, /*&frame->fpstate,*/

				env, set->sig[0]);

	err |= __copy_to_user(&frame->uc.uc_sigmask, set, sizeof(*set));

	if (err == 0)

		err = setup_return(env, ka, &frame->retcode, frame, usig);

	if (err == 0) {

		/*

		 * For realtime signals we must also set the second and third

		 * arguments for the signal handler.

		 *   -- Peter Maydell <pmaydell@chiark.greenend.org.uk> 2000-12-06

		 */

            env->regs[1] = (target_ulong)frame->pinfo;

            env->regs[2] = (target_ulong)frame->puc;

	}

        //	return err;

}


static void spapr_phb_placement(sPAPRMachineState *spapr, uint32_t index,

                                uint64_t *buid, hwaddr *pio,

                                hwaddr *mmio32, hwaddr *mmio64,

                                unsigned n_dma, uint32_t *liobns, Error **errp)

{

    /*

     * New-style PHB window placement.

     *

     * Goals: Gives large (1TiB), naturally aligned 64-bit MMIO window

     * for each PHB, in addition to 2GiB 32-bit MMIO and 64kiB PIO

     * windows.

     *

     * Some guest kernels can't work with MMIO windows above 1<<46

     * (64TiB), so we place up to 31 PHBs in the area 32TiB..64TiB

     *

     * 32TiB..(33TiB+1984kiB) contains the 64kiB PIO windows for each

     * PHB stacked together.  (32TiB+2GiB)..(32TiB+64GiB) contains the

     * 2GiB 32-bit MMIO windows for each PHB.  Then 33..64TiB has the

     * 1TiB 64-bit MMIO windows for each PHB.

     */

    const uint64_t base_buid = 0x800000020000000ULL;

    const int max_phbs =

        (SPAPR_PCI_LIMIT - SPAPR_PCI_BASE) / SPAPR_PCI_MEM64_WIN_SIZE - 1;

    int i;

    /* Sanity check natural alignments */

    QEMU_BUILD_BUG_ON((SPAPR_PCI_BASE % SPAPR_PCI_MEM64_WIN_SIZE) != 0);

    QEMU_BUILD_BUG_ON((SPAPR_PCI_LIMIT % SPAPR_PCI_MEM64_WIN_SIZE) != 0);

    QEMU_BUILD_BUG_ON((SPAPR_PCI_MEM64_WIN_SIZE % SPAPR_PCI_MEM32_WIN_SIZE) != 0);

    QEMU_BUILD_BUG_ON((SPAPR_PCI_MEM32_WIN_SIZE % SPAPR_PCI_IO_WIN_SIZE) != 0);

    /* Sanity check bounds */

    QEMU_BUILD_BUG_ON((max_phbs * SPAPR_PCI_IO_WIN_SIZE) > SPAPR_PCI_MEM32_WIN_SIZE);

    QEMU_BUILD_BUG_ON((max_phbs * SPAPR_PCI_MEM32_WIN_SIZE) > SPAPR_PCI_MEM64_WIN_SIZE);

    if (index >= max_phbs) {

        error_setg(errp, "\"index\" for PAPR PHB is too large (max %u)",

                   max_phbs - 1);

        return;

    }

    *buid = base_buid + index;

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

        liobns[i] = SPAPR_PCI_LIOBN(index, i);

    }

    *pio = SPAPR_PCI_BASE + index * SPAPR_PCI_IO_WIN_SIZE;

    *mmio32 = SPAPR_PCI_BASE + (index + 1) * SPAPR_PCI_MEM32_WIN_SIZE;

    *mmio64 = SPAPR_PCI_BASE + (index + 1) * SPAPR_PCI_MEM64_WIN_SIZE;

}


static void ppc405ep_compute_clocks (ppc405ep_cpc_t *cpc)

{

    uint32_t CPU_clk, PLB_clk, OPB_clk, EBC_clk, MAL_clk, PCI_clk;

    uint32_t UART0_clk, UART1_clk;

    uint64_t VCO_out, PLL_out;

    int M, D;

    VCO_out = 0;

    if ((cpc->pllmr[1] & 0x80000000) && !(cpc->pllmr[1] & 0x40000000)) {

        M = (((cpc->pllmr[1] >> 20) - 1) & 0xF) + 1; /* FBMUL */

#ifdef DEBUG_CLOCKS_LL

        printf("FBMUL %01" PRIx32 " %d\n", (cpc->pllmr[1] >> 20) & 0xF, M);

#endif

        D = 8 - ((cpc->pllmr[1] >> 16) & 0x7); /* FWDA */

#ifdef DEBUG_CLOCKS_LL

        printf("FWDA %01" PRIx32 " %d\n", (cpc->pllmr[1] >> 16) & 0x7, D);

#endif

        VCO_out = cpc->sysclk * M * D;

        if (VCO_out < 500000000UL || VCO_out > 1000000000UL) {

            /* Error - unlock the PLL */

            printf("VCO out of range %" PRIu64 "\n", VCO_out);

#if 0

            cpc->pllmr[1] &= ~0x80000000;

            goto pll_bypass;

#endif

        }

        PLL_out = VCO_out / D;

        /* Pretend the PLL is locked */

        cpc->boot |= 0x00000001;

    } else {

#if 0

    pll_bypass:

#endif

        PLL_out = cpc->sysclk;

        if (cpc->pllmr[1] & 0x40000000) {

            /* Pretend the PLL is not locked */

            cpc->boot &= ~0x00000001;

        }

    }

    /* Now, compute all other clocks */

    D = ((cpc->pllmr[0] >> 20) & 0x3) + 1; /* CCDV */

#ifdef DEBUG_CLOCKS_LL

    printf("CCDV %01" PRIx32 " %d\n", (cpc->pllmr[0] >> 20) & 0x3, D);

#endif

    CPU_clk = PLL_out / D;

    D = ((cpc->pllmr[0] >> 16) & 0x3) + 1; /* CBDV */

#ifdef DEBUG_CLOCKS_LL

    printf("CBDV %01" PRIx32 " %d\n", (cpc->pllmr[0] >> 16) & 0x3, D);

#endif

    PLB_clk = CPU_clk / D;

    D = ((cpc->pllmr[0] >> 12) & 0x3) + 1; /* OPDV */

#ifdef DEBUG_CLOCKS_LL

    printf("OPDV %01" PRIx32 " %d\n", (cpc->pllmr[0] >> 12) & 0x3, D);

#endif

    OPB_clk = PLB_clk / D;

    D = ((cpc->pllmr[0] >> 8) & 0x3) + 2; /* EPDV */

#ifdef DEBUG_CLOCKS_LL

    printf("EPDV %01" PRIx32 " %d\n", (cpc->pllmr[0] >> 8) & 0x3, D);

#endif

    EBC_clk = PLB_clk / D;

    D = ((cpc->pllmr[0] >> 4) & 0x3) + 1; /* MPDV */

#ifdef DEBUG_CLOCKS_LL

    printf("MPDV %01" PRIx32 " %d\n", (cpc->pllmr[0] >> 4) & 0x3, D);

#endif

    MAL_clk = PLB_clk / D;

    D = (cpc->pllmr[0] & 0x3) + 1; /* PPDV */

#ifdef DEBUG_CLOCKS_LL

    printf("PPDV %01" PRIx32 " %d\n", cpc->pllmr[0] & 0x3, D);

#endif

    PCI_clk = PLB_clk / D;

    D = ((cpc->ucr - 1) & 0x7F) + 1; /* U0DIV */

#ifdef DEBUG_CLOCKS_LL

    printf("U0DIV %01" PRIx32 " %d\n", cpc->ucr & 0x7F, D);

#endif

    UART0_clk = PLL_out / D;

    D = (((cpc->ucr >> 8) - 1) & 0x7F) + 1; /* U1DIV */

#ifdef DEBUG_CLOCKS_LL

    printf("U1DIV %01" PRIx32 " %d\n", (cpc->ucr >> 8) & 0x7F, D);

#endif

    UART1_clk = PLL_out / D;

#ifdef DEBUG_CLOCKS

    printf("Setup PPC405EP clocks - sysclk %" PRIu32 " VCO %" PRIu64

           " PLL out %" PRIu64 " Hz\n", cpc->sysclk, VCO_out, PLL_out);

    printf("CPU %" PRIu32 " PLB %" PRIu32 " OPB %" PRIu32 " EBC %" PRIu32

           " MAL %" PRIu32 " PCI %" PRIu32 " UART0 %" PRIu32

           " UART1 %" PRIu32 "\n",

           CPU_clk, PLB_clk, OPB_clk, EBC_clk, MAL_clk, PCI_clk,

           UART0_clk, UART1_clk);

#endif

    /* Setup CPU clocks */

    clk_setup(&cpc->clk_setup[PPC405EP_CPU_CLK], CPU_clk);

    /* Setup PLB clock */

    clk_setup(&cpc->clk_setup[PPC405EP_PLB_CLK], PLB_clk);

    /* Setup OPB clock */

    clk_setup(&cpc->clk_setup[PPC405EP_OPB_CLK], OPB_clk);

    /* Setup external clock */

    clk_setup(&cpc->clk_setup[PPC405EP_EBC_CLK], EBC_clk);

    /* Setup MAL clock */

    clk_setup(&cpc->clk_setup[PPC405EP_MAL_CLK], MAL_clk);

    /* Setup PCI clock */

    clk_setup(&cpc->clk_setup[PPC405EP_PCI_CLK], PCI_clk);

    /* Setup UART0 clock */

    clk_setup(&cpc->clk_setup[PPC405EP_UART0_CLK], UART0_clk);

    /* Setup UART1 clock */

    clk_setup(&cpc->clk_setup[PPC405EP_UART1_CLK], UART1_clk);

}


av_cold void ff_wmv2_common_init(Wmv2Context * w){

    MpegEncContext * const s= &w->s;

    ff_init_scantable(s->dsp.idct_permutation, &w->abt_scantable[0], ff_wmv2_scantableA);

    ff_init_scantable(s->dsp.idct_permutation, &w->abt_scantable[1], ff_wmv2_scantableB);

}


void tap_fd_set_offload(int fd, int csum, int tso4,
                        int tso6, int ecn, int ufo)
{
    unsigned int offload = 0;
    if (csum) {
        offload |= TUN_F_CSUM;
        if (tso4)
            offload |= TUN_F_TSO4;
        if (tso6)
            offload |= TUN_F_TSO6;
        if ((tso4 || tso6) && ecn)
            offload |= TUN_F_TSO_ECN;
        if (ufo)
            offload |= TUN_F_UFO;
    if (ioctl(fd, TUNSETOFFLOAD, offload) != 0) {
        offload &= ~TUN_F_UFO;
        if (ioctl(fd, TUNSETOFFLOAD, offload) != 0) {
            fprintf(stderr, "TUNSETOFFLOAD ioctl() failed: %s\n",
                    strerror(errno));


void ff_mpeg1_encode_init(MpegEncContext *s)

{

    static int done=0;

    common_init(s);

    if(!done){

        int f_code;

        int mv;

	int i;

        done=1;

        init_rl(&rl_mpeg1);

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

	{

		mpeg1_max_level[0][i]= rl_mpeg1.max_level[0][i];

		mpeg1_index_run[0][i]= rl_mpeg1.index_run[0][i];

	}

        init_uni_ac_vlc(&rl_mpeg1, uni_mpeg1_ac_vlc_bits, uni_mpeg1_ac_vlc_len);

	/* build unified dc encoding tables */

	for(i=-255; i<256; i++)

	{

		int adiff, index;

		int bits, code;

		int diff=i;

		adiff = ABS(diff);

		if(diff<0) diff--;

		index = av_log2(2*adiff);

		bits= vlc_dc_lum_bits[index] + index;

		code= (vlc_dc_lum_code[index]<<index) + (diff & ((1 << index) - 1));

		mpeg1_lum_dc_uni[i+255]= bits + (code<<8);

		bits= vlc_dc_chroma_bits[index] + index;

		code= (vlc_dc_chroma_code[index]<<index) + (diff & ((1 << index) - 1));

		mpeg1_chr_dc_uni[i+255]= bits + (code<<8);

	}

        mv_penalty= av_mallocz( sizeof(uint8_t)*(MAX_FCODE+1)*(2*MAX_MV+1) );

        for(f_code=1; f_code<=MAX_FCODE; f_code++){

            for(mv=-MAX_MV; mv<=MAX_MV; mv++){

                int len;

                if(mv==0) len= mbMotionVectorTable[0][1];

                else{

                    int val, bit_size, range, code;

                    bit_size = f_code - 1;

                    range = 1 << bit_size;

                    val=mv;

                    if (val < 0)

                        val = -val;

                    val--;

                    code = (val >> bit_size) + 1;

                    if(code<17){

                        len= mbMotionVectorTable[code][1] + 1 + bit_size;

                    }else{

                        len= mbMotionVectorTable[16][1] + 2 + bit_size;

                    }

                }

                mv_penalty[f_code][mv+MAX_MV]= len;

            }

        }

        for(f_code=MAX_FCODE; f_code>0; f_code--){

            for(mv=-(8<<f_code); mv<(8<<f_code); mv++){

                fcode_tab[mv+MAX_MV]= f_code;

            }

        }

    }

    s->me.mv_penalty= mv_penalty;

    s->fcode_tab= fcode_tab;

    if(s->codec_id == CODEC_ID_MPEG1VIDEO){

        s->min_qcoeff=-255;

        s->max_qcoeff= 255;

    }else{

        s->min_qcoeff=-2047;

        s->max_qcoeff= 2047;

    }

    s->intra_ac_vlc_length=

    s->inter_ac_vlc_length=

    s->intra_ac_vlc_last_length=

    s->inter_ac_vlc_last_length= uni_mpeg1_ac_vlc_len;

}


static av_cold int ac3_decode_init(AVCodecContext *avctx)

{

    AC3DecodeContext *s = avctx->priv_data;

    s->avctx = avctx;

    ff_ac3_common_init();

    ac3_tables_init();

    ff_mdct_init(&s->imdct_256, 8, 1, 1.0);

    ff_mdct_init(&s->imdct_512, 9, 1, 1.0);

    ff_kbd_window_init(s->window, 5.0, 256);

    dsputil_init(&s->dsp, avctx);

    ff_fmt_convert_init(&s->fmt_conv, avctx);

    av_lfg_init(&s->dith_state, 0);

    /* set scale value for float to int16 conversion */

    s->mul_bias = 32767.0f;

    /* allow downmixing to stereo or mono */

    if (avctx->channels > 0 && avctx->request_channels > 0 &&

            avctx->request_channels < avctx->channels &&

            avctx->request_channels <= 2) {

        avctx->channels = avctx->request_channels;

    }

    s->downmixed = 1;

    /* allocate context input buffer */

    if (avctx->error_recognition >= FF_ER_CAREFUL) {

        s->input_buffer = av_mallocz(AC3_FRAME_BUFFER_SIZE + FF_INPUT_BUFFER_PADDING_SIZE);

        if (!s->input_buffer)

            return AVERROR(ENOMEM);

    }

    avctx->sample_fmt = AV_SAMPLE_FMT_S16;

    return 0;

}


static void count_frame_bits_fixed(AC3EncodeContext *s)

{

    static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };

    int blk;

    int frame_bits;

    /* assumptions:

     *   no dynamic range codes

     *   bit allocation parameters do not change between blocks

     *   no delta bit allocation

     *   no skipped data

     *   no auxilliary data

     *   no E-AC-3 metadata

     */

    /* header */

    frame_bits = 16; /* sync info */

    if (s->eac3) {

        /* bitstream info header */

        frame_bits += 35;

        frame_bits += 1 + 1 + 1;

        /* audio frame header */

        frame_bits += 2;

        frame_bits += 10;

        /* exponent strategy */

        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)

            frame_bits += 2 * s->fbw_channels + s->lfe_on;

        /* converter exponent strategy */

        frame_bits += s->fbw_channels * 5;

        /* snr offsets */

        frame_bits += 10;

        /* block start info */

        frame_bits++;

    } else {

        frame_bits += 49;

        frame_bits += frame_bits_inc[s->channel_mode];

    }

    /* audio blocks */

    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {

        if (!s->eac3) {

            /* block switch flags */

            frame_bits += s->fbw_channels;

            /* dither flags */

            frame_bits += s->fbw_channels;

        }

        /* dynamic range */

        frame_bits++;

        /* spectral extension */

        if (s->eac3)

            frame_bits++;

        if (!s->eac3) {

            /* exponent strategy */

            frame_bits += 2 * s->fbw_channels;

            if (s->lfe_on)

                frame_bits++;

            /* bit allocation params */

            frame_bits++;

            if (!blk)

                frame_bits += 2 + 2 + 2 + 2 + 3;

        }

        /* converter snr offset */

        if (s->eac3)

            frame_bits++;

        if (!s->eac3) {

            /* delta bit allocation */

            frame_bits++;

            /* skipped data */

            frame_bits++;

        }

    }

    /* auxiliary data */

    frame_bits++;

    /* CRC */

    frame_bits += 1 + 16;

    s->frame_bits_fixed = frame_bits;

}


static void av_noinline filter_mb_edgev( uint8_t *pix, int stride, int16_t bS[4], unsigned int qp, H264Context *h) {

    const unsigned int index_a = 52 + qp + h->slice_alpha_c0_offset;

    const int alpha = alpha_table[index_a];

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

    if (alpha ==0 || beta == 0) return;

    if( bS[0] < 4 ) {

        int8_t tc[4];

        tc[0] = tc0_table[index_a][bS[0]];

        tc[1] = tc0_table[index_a][bS[1]];

        tc[2] = tc0_table[index_a][bS[2]];

        tc[3] = tc0_table[index_a][bS[3]];

        h->s.dsp.h264_h_loop_filter_luma(pix, stride, alpha, beta, tc);

    } else {

        h->s.dsp.h264_h_loop_filter_luma_intra(pix, stride, alpha, beta);

    }

}


int avcodec_decode_audio(AVCodecContext *avctx, int16_t *samples,

                         int *frame_size_ptr,

                         uint8_t *buf, int buf_size)

{

    int ret;

    *frame_size_ptr= 0;

    if((avctx->codec->capabilities & CODEC_CAP_DELAY) || buf_size){

        ret = avctx->codec->decode(avctx, samples, frame_size_ptr,

                                buf, buf_size);

        avctx->frame_number++;

    }else

        ret= 0;

    return ret;

}


void vp8_decode_mvs(VP8Context *s, VP8Macroblock *mb,

                    int mb_x, int mb_y, int layout)

{

    VP8Macroblock *mb_edge[3] = { 0      /* top */,

                                  mb - 1 /* left */,

                                  0      /* top-left */ };

    enum { CNT_ZERO, CNT_NEAREST, CNT_NEAR, CNT_SPLITMV };

    enum { VP8_EDGE_TOP, VP8_EDGE_LEFT, VP8_EDGE_TOPLEFT };

    int idx = CNT_ZERO;

    int cur_sign_bias = s->sign_bias[mb->ref_frame];

    int8_t *sign_bias = s->sign_bias;

    VP56mv near_mv[4];

    uint8_t cnt[4] = { 0 };

    VP56RangeCoder *c = &s->c;

    if (!layout) { // layout is inlined (s->mb_layout is not)

        mb_edge[0] = mb + 2;

        mb_edge[2] = mb + 1;

    } else {

        mb_edge[0] = mb - s->mb_width - 1;

        mb_edge[2] = mb - s->mb_width - 2;

    }

    AV_ZERO32(&near_mv[0]);

    AV_ZERO32(&near_mv[1]);

    AV_ZERO32(&near_mv[2]);

    /* Process MB on top, left and top-left */

#define MV_EDGE_CHECK(n)                                                      \

    {                                                                         \

        VP8Macroblock *edge = mb_edge[n];                                     \

        int edge_ref = edge->ref_frame;                                       \

        if (edge_ref != VP56_FRAME_CURRENT) {                                 \

            uint32_t mv = AV_RN32A(&edge->mv);                                \

            if (mv) {                                                         \

                if (cur_sign_bias != sign_bias[edge_ref]) {                   \

                    /* SWAR negate of the values in mv. */                    \

                    mv = ~mv;                                                 \

                    mv = ((mv & 0x7fff7fff) +                                 \

                          0x00010001) ^ (mv & 0x80008000);                    \

                }                                                             \

                if (!n || mv != AV_RN32A(&near_mv[idx]))                      \

                    AV_WN32A(&near_mv[++idx], mv);                            \

                cnt[idx] += 1 + (n != 2);                                     \

            } else                                                            \

                cnt[CNT_ZERO] += 1 + (n != 2);                                \

        }                                                                     \

    }

    MV_EDGE_CHECK(0)

    MV_EDGE_CHECK(1)

    MV_EDGE_CHECK(2)

    mb->partitioning = VP8_SPLITMVMODE_NONE;

    if (vp56_rac_get_prob_branchy(c, vp8_mode_contexts[cnt[CNT_ZERO]][0])) {

        mb->mode = VP8_MVMODE_MV;

        /* If we have three distinct MVs, merge first and last if they're the same */

        if (cnt[CNT_SPLITMV] &&

            AV_RN32A(&near_mv[1 + VP8_EDGE_TOP]) == AV_RN32A(&near_mv[1 + VP8_EDGE_TOPLEFT]))

            cnt[CNT_NEAREST] += 1;

        /* Swap near and nearest if necessary */

        if (cnt[CNT_NEAR] > cnt[CNT_NEAREST]) {

            FFSWAP(uint8_t,     cnt[CNT_NEAREST],     cnt[CNT_NEAR]);

            FFSWAP( VP56mv, near_mv[CNT_NEAREST], near_mv[CNT_NEAR]);

        }

        if (vp56_rac_get_prob_branchy(c, vp8_mode_contexts[cnt[CNT_NEAREST]][1])) {

            if (vp56_rac_get_prob_branchy(c, vp8_mode_contexts[cnt[CNT_NEAR]][2])) {

                /* Choose the best mv out of 0,0 and the nearest mv */

                clamp_mv(s, &mb->mv, &near_mv[CNT_ZERO + (cnt[CNT_NEAREST] >= cnt[CNT_ZERO])]);

                cnt[CNT_SPLITMV] = ((mb_edge[VP8_EDGE_LEFT]->mode    == VP8_MVMODE_SPLIT) +

                                    (mb_edge[VP8_EDGE_TOP]->mode     == VP8_MVMODE_SPLIT)) * 2 +

                                    (mb_edge[VP8_EDGE_TOPLEFT]->mode == VP8_MVMODE_SPLIT);

                if (vp56_rac_get_prob_branchy(c, vp8_mode_contexts[cnt[CNT_SPLITMV]][3])) {

                    mb->mode = VP8_MVMODE_SPLIT;

                    mb->mv = mb->bmv[decode_splitmvs(s, c, mb, layout, IS_VP8) - 1];

                } else {

                    mb->mv.y  += vp8_read_mv_component(c, s->prob->mvc[0]);

                    mb->mv.x  += vp8_read_mv_component(c, s->prob->mvc[1]);

                    mb->bmv[0] = mb->mv;

                }

            } else {

                clamp_mv(s, &mb->mv, &near_mv[CNT_NEAR]);

                mb->bmv[0] = mb->mv;

            }

        } else {

            clamp_mv(s, &mb->mv, &near_mv[CNT_NEAREST]);

            mb->bmv[0] = mb->mv;

        }

    } else {

        mb->mode = VP8_MVMODE_ZERO;

        AV_ZERO32(&mb->mv);

        mb->bmv[0] = mb->mv;

    }

}


int main()

{

    int rd, rt, dsp;

    int result, resultdsp;

    rt        = 0x12345678;

    result    = 0xA000C000;

    resultdsp = 1;

    __asm

        ("shll.ph %0, %2, 0x0B\n\t"

         "rddsp %1\n\t"

         : "=r"(rd), "=r"(dsp)

         : "r"(rt)

        );

    dsp = (dsp >> 22) & 0x01;

    assert(dsp == resultdsp);

    assert(rd  == result);

    return 0;

}


int ff_rle_encode(uint8_t *outbuf, int out_size, const uint8_t *ptr , int bpp, int w, int8_t add, uint8_t xor)

{

    int count, x;

    uint8_t *out;

    out = outbuf;

        for(x = 0; x < w; x += count) {

            /* see if we can encode the next set of pixels with RLE */

            if((count = count_pixels(ptr, w-x, bpp, 1)) > 1) {

                if(out + bpp + 1 > outbuf + out_size) return -1;

                *out++ = (count ^ xor) + add;

                memcpy(out, ptr, bpp);

                out += bpp;

            } else {

                /* fall back on uncompressed */

                count = count_pixels(ptr, w-x, bpp, 0);

                *out++ = count - 1;

                if(out + bpp*count > outbuf + out_size) return -1;

                memcpy(out, ptr, bpp * count);

                out += bpp * count;

        }

        ptr += count * bpp;

    }

    return out - outbuf;

}


static int vdpau_frames_init(AVHWFramesContext *ctx)

{

    VDPAUDeviceContext *device_priv = ctx->device_ctx->internal->priv;

    VDPAUFramesContext        *priv = ctx->internal->priv;

    int i;

    switch (ctx->sw_format) {

    case AV_PIX_FMT_YUV420P: priv->chroma_type = VDP_CHROMA_TYPE_420; break;

    case AV_PIX_FMT_YUV422P: priv->chroma_type = VDP_CHROMA_TYPE_422; break;

    case AV_PIX_FMT_YUV444P: priv->chroma_type = VDP_CHROMA_TYPE_444; break;

    default:

        av_log(ctx, AV_LOG_ERROR, "Unsupported data layout: %s\n",

               av_get_pix_fmt_name(ctx->sw_format));

        return AVERROR(ENOSYS);

    }

    for (i = 0; i < FF_ARRAY_ELEMS(vdpau_pix_fmts); i++) {

        if (vdpau_pix_fmts[i].chroma_type == priv->chroma_type) {

            priv->chroma_idx  = i;

            priv->pix_fmts    = device_priv->pix_fmts[i];

            priv->nb_pix_fmts = device_priv->nb_pix_fmts[i];

            break;

        }

    }

    if (!priv->pix_fmts) {

        av_log(ctx, AV_LOG_ERROR, "Unsupported chroma type: %d\n", priv->chroma_type);

        return AVERROR(ENOSYS);

    }

    if (!ctx->pool) {

        ctx->internal->pool_internal = av_buffer_pool_init2(sizeof(VdpVideoSurface), ctx,

                                                            vdpau_pool_alloc, NULL);

        if (!ctx->internal->pool_internal)

            return AVERROR(ENOMEM);

    }

    priv->get_data = device_priv->get_data;

    priv->put_data = device_priv->put_data;

    return 0;

}


int vm_stop(RunState state)

{

    if (qemu_in_vcpu_thread()) {

        qemu_system_vmstop_request(state);

        /*

         * FIXME: should not return to device code in case

         * vm_stop() has been requested.

         */

        cpu_stop_current();

        return 0;

    }

    return do_vm_stop(state);

}