int av_buffersink_get_samples(AVFilterContext *ctx, AVFrame *frame, int nb_samples)

{

    BufferSinkContext *s = ctx->priv;

    AVFilterLink   *link = ctx->inputs[0];

    AVFrame *cur_frame;

    int ret = 0;

    if (!s->audio_fifo) {

        int nb_channels = link->channels;

        if (!(s->audio_fifo = av_audio_fifo_alloc(link->format, nb_channels, nb_samples)))

            return AVERROR(ENOMEM);

    }

    while (ret >= 0) {

        if (av_audio_fifo_size(s->audio_fifo) >= nb_samples)

            return read_from_fifo(ctx, frame, nb_samples);

        if (!(cur_frame = av_frame_alloc()))

            return AVERROR(ENOMEM);

        ret = av_buffersink_get_frame_flags(ctx, cur_frame, 0);

        if (ret == AVERROR_EOF && av_audio_fifo_size(s->audio_fifo)) {

            av_frame_free(&cur_frame);

            return read_from_fifo(ctx, frame, av_audio_fifo_size(s->audio_fifo));

        } else if (ret < 0) {

            av_frame_free(&cur_frame);

            return ret;

        }

        if (cur_frame->pts != AV_NOPTS_VALUE) {

            s->next_pts = cur_frame->pts -

                          av_rescale_q(av_audio_fifo_size(s->audio_fifo),

                                       (AVRational){ 1, link->sample_rate },

                                       link->time_base);

        }

        ret = av_audio_fifo_write(s->audio_fifo, (void**)cur_frame->extended_data,

                                  cur_frame->nb_samples);

        av_frame_free(&cur_frame);

    }

    return ret;

}


static int rtsp_parse_request(HTTPContext *c)

{

    const char *p, *p1, *p2;

    char cmd[32];

    char url[1024];

    char protocol[32];

    char line[1024];

    int len;

    RTSPMessageHeader header1, *header = &header1;

    c->buffer_ptr[0] = '\0';

    p = c->buffer;

    get_word(cmd, sizeof(cmd), &p);

    get_word(url, sizeof(url), &p);

    get_word(protocol, sizeof(protocol), &p);

    av_strlcpy(c->method, cmd, sizeof(c->method));

    av_strlcpy(c->url, url, sizeof(c->url));

    av_strlcpy(c->protocol, protocol, sizeof(c->protocol));

    if (url_open_dyn_buf(&c->pb) < 0) {

        /* XXX: cannot do more */

        c->pb = NULL; /* safety */

        return -1;

    }

    /* check version name */

    if (strcmp(protocol, "RTSP/1.0") != 0) {

        rtsp_reply_error(c, RTSP_STATUS_VERSION);

        goto the_end;

    }

    /* parse each header line */

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

    /* skip to next line */

    while (*p != '\n' && *p != '\0')

        p++;

    if (*p == '\n')

        p++;

    while (*p != '\0') {

        p1 = strchr(p, '\n');

        if (!p1)

            break;

        p2 = p1;

        if (p2 > p && p2[-1] == '\r')

            p2--;

        /* skip empty line */

        if (p2 == p)

            break;

        len = p2 - p;

        if (len > sizeof(line) - 1)

            len = sizeof(line) - 1;

        memcpy(line, p, len);

        line[len] = '\0';

        ff_rtsp_parse_line(header, line, NULL);

        p = p1 + 1;

    }

    /* handle sequence number */

    c->seq = header->seq;

    if (!strcmp(cmd, "DESCRIBE"))

        rtsp_cmd_describe(c, url);

    else if (!strcmp(cmd, "OPTIONS"))

        rtsp_cmd_options(c, url);

    else if (!strcmp(cmd, "SETUP"))

        rtsp_cmd_setup(c, url, header);

    else if (!strcmp(cmd, "PLAY"))

        rtsp_cmd_play(c, url, header);

    else if (!strcmp(cmd, "PAUSE"))

        rtsp_cmd_pause(c, url, header);

    else if (!strcmp(cmd, "TEARDOWN"))

        rtsp_cmd_teardown(c, url, header);

    else

        rtsp_reply_error(c, RTSP_STATUS_METHOD);

 the_end:

    len = url_close_dyn_buf(c->pb, &c->pb_buffer);

    c->pb = NULL; /* safety */

    if (len < 0) {

        /* XXX: cannot do more */

        return -1;

    }

    c->buffer_ptr = c->pb_buffer;

    c->buffer_end = c->pb_buffer + len;

    c->state = RTSPSTATE_SEND_REPLY;

    return 0;

}


void cpu_dump_state (CPUPPCState *env, FILE *f, fprintf_function cpu_fprintf,
                     int flags)
{
#define RGPL  4
#define RFPL  4
    int i;
    cpu_fprintf(f, "NIP " TARGET_FMT_lx "   LR " TARGET_FMT_lx " CTR "
                TARGET_FMT_lx " XER " TARGET_FMT_lx "\n",
                env->nip, env->lr, env->ctr, env->xer);
    cpu_fprintf(f, "MSR " TARGET_FMT_lx " HID0 " TARGET_FMT_lx "  HF "
                TARGET_FMT_lx " idx %d\n", env->msr, env->spr[SPR_HID0],
                env->hflags, env->mmu_idx);
#if !defined(NO_TIMER_DUMP)
    cpu_fprintf(f, "TB %08" PRIu32 " %08" PRIu64
#if !defined(CONFIG_USER_ONLY)
                " DECR %08" PRIu32
#endif
                "\n",
                cpu_ppc_load_tbu(env), cpu_ppc_load_tbl(env)
#if !defined(CONFIG_USER_ONLY)
                , cpu_ppc_load_decr(env)
#endif
                );
#endif
    for (i = 0; i < 32; i++) {
        if ((i & (RGPL - 1)) == 0)
            cpu_fprintf(f, "GPR%02d", i);
        cpu_fprintf(f, " %016" PRIx64, ppc_dump_gpr(env, i));
        if ((i & (RGPL - 1)) == (RGPL - 1))
            cpu_fprintf(f, "\n");
    }
    cpu_fprintf(f, "CR ");
    for (i = 0; i < 8; i++)
        cpu_fprintf(f, "%01x", env->crf[i]);
    cpu_fprintf(f, "  [");
    for (i = 0; i < 8; i++) {
        char a = '-';
        if (env->crf[i] & 0x08)
            a = 'L';
        else if (env->crf[i] & 0x04)
            a = 'G';
        else if (env->crf[i] & 0x02)
            a = 'E';
        cpu_fprintf(f, " %c%c", a, env->crf[i] & 0x01 ? 'O' : ' ');
    }
    cpu_fprintf(f, " ]             RES " TARGET_FMT_lx "\n",
                env->reserve_addr);
    for (i = 0; i < 32; i++) {
        if ((i & (RFPL - 1)) == 0)
            cpu_fprintf(f, "FPR%02d", i);
        cpu_fprintf(f, " %016" PRIx64, *((uint64_t *)&env->fpr[i]));
        if ((i & (RFPL - 1)) == (RFPL - 1))
            cpu_fprintf(f, "\n");
    }
    cpu_fprintf(f, "FPSCR %08x\n", env->fpscr);
#if !defined(CONFIG_USER_ONLY)
    cpu_fprintf(f, " SRR0 " TARGET_FMT_lx "  SRR1 " TARGET_FMT_lx
                   "    PVR " TARGET_FMT_lx " VRSAVE " TARGET_FMT_lx "\n",
                env->spr[SPR_SRR0], env->spr[SPR_SRR1],
                env->spr[SPR_PVR], env->spr[SPR_VRSAVE]);
    cpu_fprintf(f, "SPRG0 " TARGET_FMT_lx " SPRG1 " TARGET_FMT_lx
                   "  SPRG2 " TARGET_FMT_lx "  SPRG3 " TARGET_FMT_lx "\n",
                env->spr[SPR_SPRG0], env->spr[SPR_SPRG1],
                env->spr[SPR_SPRG2], env->spr[SPR_SPRG3]);
    cpu_fprintf(f, "SPRG4 " TARGET_FMT_lx " SPRG5 " TARGET_FMT_lx
                   "  SPRG6 " TARGET_FMT_lx "  SPRG7 " TARGET_FMT_lx "\n",
                env->spr[SPR_SPRG4], env->spr[SPR_SPRG5],
                env->spr[SPR_SPRG6], env->spr[SPR_SPRG7]);
    if (env->excp_model == POWERPC_EXCP_BOOKE) {
        cpu_fprintf(f, "CSRR0 " TARGET_FMT_lx " CSRR1 " TARGET_FMT_lx
                       " MCSRR0 " TARGET_FMT_lx " MCSRR1 " TARGET_FMT_lx "\n",
                    env->spr[SPR_BOOKE_CSRR0], env->spr[SPR_BOOKE_CSRR1],
                    env->spr[SPR_BOOKE_MCSRR0], env->spr[SPR_BOOKE_MCSRR1]);
        cpu_fprintf(f, "  TCR " TARGET_FMT_lx "   TSR " TARGET_FMT_lx
                       "    ESR " TARGET_FMT_lx "   DEAR " TARGET_FMT_lx "\n",
                    env->spr[SPR_BOOKE_TCR], env->spr[SPR_BOOKE_TSR],
                    env->spr[SPR_BOOKE_ESR], env->spr[SPR_BOOKE_DEAR]);
        cpu_fprintf(f, "  PIR " TARGET_FMT_lx " DECAR " TARGET_FMT_lx
                       "   IVPR " TARGET_FMT_lx "   EPCR " TARGET_FMT_lx "\n",
                    env->spr[SPR_BOOKE_PIR], env->spr[SPR_BOOKE_DECAR],
                    env->spr[SPR_BOOKE_IVPR], env->spr[SPR_BOOKE_EPCR]);
        cpu_fprintf(f, " MCSR " TARGET_FMT_lx " SPRG8 " TARGET_FMT_lx
                       "    EPR " TARGET_FMT_lx "\n",
                    env->spr[SPR_BOOKE_MCSR], env->spr[SPR_BOOKE_SPRG8],
                    env->spr[SPR_BOOKE_EPR]);
        /* FSL-specific */
        cpu_fprintf(f, " MCAR " TARGET_FMT_lx "  PID1 " TARGET_FMT_lx
                       "   PID2 " TARGET_FMT_lx "    SVR " TARGET_FMT_lx "\n",
                    env->spr[SPR_Exxx_MCAR], env->spr[SPR_BOOKE_PID1],
                    env->spr[SPR_BOOKE_PID2], env->spr[SPR_E500_SVR]);
        /*
         * IVORs are left out as they are large and do not change often --
         * they can be read with "p $ivor0", "p $ivor1", etc.
         */
    }
#if defined(TARGET_PPC64)
    if (env->flags & POWERPC_FLAG_CFAR) {
        cpu_fprintf(f, " CFAR " TARGET_FMT_lx"\n", env->cfar);
    }
#endif
    switch (env->mmu_model) {
    case POWERPC_MMU_32B:
    case POWERPC_MMU_601:
    case POWERPC_MMU_SOFT_6xx:
    case POWERPC_MMU_SOFT_74xx:
#if defined(TARGET_PPC64)
    case POWERPC_MMU_620:
    case POWERPC_MMU_64B:
#endif
        cpu_fprintf(f, " SDR1 " TARGET_FMT_lx "\n", env->spr[SPR_SDR1]);
        break;
    case POWERPC_MMU_BOOKE206:
        cpu_fprintf(f, " MAS0 " TARGET_FMT_lx "  MAS1 " TARGET_FMT_lx
                       "   MAS2 " TARGET_FMT_lx "   MAS3 " TARGET_FMT_lx "\n",
                    env->spr[SPR_BOOKE_MAS0], env->spr[SPR_BOOKE_MAS1],
                    env->spr[SPR_BOOKE_MAS2], env->spr[SPR_BOOKE_MAS3]);
        cpu_fprintf(f, " MAS4 " TARGET_FMT_lx "  MAS6 " TARGET_FMT_lx
                       "   MAS7 " TARGET_FMT_lx "    PID " TARGET_FMT_lx "\n",
                    env->spr[SPR_BOOKE_MAS4], env->spr[SPR_BOOKE_MAS6],
                    env->spr[SPR_BOOKE_MAS7], env->spr[SPR_BOOKE_PID]);
        cpu_fprintf(f, "MMUCFG " TARGET_FMT_lx " TLB0CFG " TARGET_FMT_lx
                       " TLB1CFG " TARGET_FMT_lx "\n",
                    env->spr[SPR_MMUCFG], env->spr[SPR_BOOKE_TLB0CFG],
                    env->spr[SPR_BOOKE_TLB1CFG]);
        break;
    default:
        break;
    }
#endif
#undef RGPL
#undef RFPL
}


pvscsi_init_msi(PVSCSIState *s)

{

    int res;

    PCIDevice *d = PCI_DEVICE(s);

    res = msi_init(d, PVSCSI_MSI_OFFSET(s), PVSCSI_MSIX_NUM_VECTORS,

                   PVSCSI_USE_64BIT, PVSCSI_PER_VECTOR_MASK);

    if (res < 0) {

        trace_pvscsi_init_msi_fail(res);

        s->msi_used = false;

    } else {

        s->msi_used = true;

    }

}


GuestFileWrite *qmp_guest_file_write(int64_t handle, const char *buf_b64,
                                     bool has_count, int64_t count,
                                     Error **errp)
{
    GuestFileWrite *write_data = NULL;
    guchar *buf;
    gsize buf_len;
    int write_count;
    GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
    FILE *fh;
    if (!gfh) {
    fh = gfh->fh;
    buf = g_base64_decode(buf_b64, &buf_len);
    if (!has_count) {
        count = buf_len;
    } else if (count < 0 || count > buf_len) {
        error_setg(errp, "value '%" PRId64 "' is invalid for argument count",
                   count);
        g_free(buf);
    write_count = fwrite(buf, 1, count, fh);
    if (ferror(fh)) {
        error_setg_errno(errp, errno, "failed to write to file");
        slog("guest-file-write failed, handle: %" PRId64, handle);
    } else {
        write_data = g_new0(GuestFileWrite, 1);
        write_data->count = write_count;
        write_data->eof = feof(fh);
        gfh->state = RW_STATE_WRITING;
    g_free(buf);
    clearerr(fh);
    return write_data;


static void fill_picture_parameters(AVCodecContext *avctx,

                                    struct dxva_context *ctx, const VC1Context *v,

                                    DXVA_PictureParameters *pp)

{

    const MpegEncContext *s = &v->s;

    const Picture *current_picture = s->current_picture_ptr;

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

    pp->wDecodedPictureIndex    =

    pp->wDeblockedPictureIndex  = ff_dxva2_get_surface_index(ctx, &current_picture->f);

    if (s->pict_type != AV_PICTURE_TYPE_I && !v->bi_type)

        pp->wForwardRefPictureIndex = ff_dxva2_get_surface_index(ctx, &s->last_picture.f);

    else

        pp->wForwardRefPictureIndex = 0xffff;

    if (s->pict_type == AV_PICTURE_TYPE_B && !v->bi_type)

        pp->wBackwardRefPictureIndex = ff_dxva2_get_surface_index(ctx, &s->next_picture.f);

    else

        pp->wBackwardRefPictureIndex = 0xffff;

    if (v->profile == PROFILE_ADVANCED) {

        /* It is the cropped width/height -1 of the frame */

        pp->wPicWidthInMBminus1 = avctx->width  - 1;

        pp->wPicHeightInMBminus1= avctx->height - 1;

    } else {

        /* It is the coded width/height in macroblock -1 of the frame */

        pp->wPicWidthInMBminus1 = s->mb_width  - 1;

        pp->wPicHeightInMBminus1= s->mb_height - 1;

    }

    pp->bMacroblockWidthMinus1  = 15;

    pp->bMacroblockHeightMinus1 = 15;

    pp->bBlockWidthMinus1       = 7;

    pp->bBlockHeightMinus1      = 7;

    pp->bBPPminus1              = 7;

    if (s->picture_structure & PICT_TOP_FIELD)

        pp->bPicStructure      |= 0x01;

    if (s->picture_structure & PICT_BOTTOM_FIELD)

        pp->bPicStructure      |= 0x02;

    pp->bSecondField            = v->interlace && v->fcm != ILACE_FIELD && !s->first_field;

    pp->bPicIntra               = s->pict_type == AV_PICTURE_TYPE_I || v->bi_type;

    pp->bPicBackwardPrediction  = s->pict_type == AV_PICTURE_TYPE_B && !v->bi_type;

    pp->bBidirectionalAveragingMode = (1                                           << 7) |

                                      ((ctx->cfg->ConfigIntraResidUnsigned != 0)   << 6) |

                                      ((ctx->cfg->ConfigResidDiffAccelerator != 0) << 5) |

                                      ((v->lumscale != 32 || v->lumshift != 0)     << 4) |

                                      ((v->profile == PROFILE_ADVANCED)            << 3);

    pp->bMVprecisionAndChromaRelation = ((v->mv_mode == MV_PMODE_1MV_HPEL_BILIN) << 3) |

                                        (1                                       << 2) |

                                        (0                                       << 1) |

                                        (!s->quarter_sample                          );

    pp->bChromaFormat           = v->chromaformat;

    ctx->report_id++;

    if (ctx->report_id >= (1 << 16))

        ctx->report_id = 1;

    pp->bPicScanFixed           = ctx->report_id >> 8;

    pp->bPicScanMethod          = ctx->report_id & 0xff;

    pp->bPicReadbackRequests    = 0;

    pp->bRcontrol               = v->rnd;

    pp->bPicSpatialResid8       = (v->panscanflag  << 7) |

                                  (v->refdist_flag << 6) |

                                  (s->loop_filter  << 5) |

                                  (v->fastuvmc     << 4) |

                                  (v->extended_mv  << 3) |

                                  (v->dquant       << 1) |

                                  (v->vstransform      );

    pp->bPicOverflowBlocks      = (v->quantizer_mode << 6) |

                                  (v->multires       << 5) |

                                  (v->resync_marker  << 4) |

                                  (v->rangered       << 3) |

                                  (s->max_b_frames       );

    pp->bPicExtrapolation       = (!v->interlace || v->fcm == PROGRESSIVE) ? 1 : 2;

    pp->bPicDeblocked           = ((!pp->bPicBackwardPrediction && v->overlap)        << 6) |

                                  ((v->profile != PROFILE_ADVANCED && v->rangeredfrm) << 5) |

                                  (s->loop_filter                                     << 1);

    pp->bPicDeblockConfined     = (v->postprocflag             << 7) |

                                  (v->broadcast                << 6) |

                                  (v->interlace                << 5) |

                                  (v->tfcntrflag               << 4) |

                                  (v->finterpflag              << 3) |

                                  ((s->pict_type != AV_PICTURE_TYPE_B) << 2) |

                                  (v->psf                      << 1) |

                                  (v->extended_dmv                 );

    if (s->pict_type != AV_PICTURE_TYPE_I)

        pp->bPic4MVallowed      = v->mv_mode == MV_PMODE_MIXED_MV ||

                                  (v->mv_mode == MV_PMODE_INTENSITY_COMP &&

                                   v->mv_mode2 == MV_PMODE_MIXED_MV);

    if (v->profile == PROFILE_ADVANCED)

        pp->bPicOBMC            = (v->range_mapy_flag  << 7) |

                                  (v->range_mapy       << 4) |

                                  (v->range_mapuv_flag << 3) |

                                  (v->range_mapuv          );

    pp->bPicBinPB               = 0;

    pp->bMV_RPS                 = 0;

    pp->bReservedBits           = 0;

    if (s->picture_structure == PICT_FRAME) {

        pp->wBitstreamFcodes        = v->lumscale;

        pp->wBitstreamPCEelements   = v->lumshift;

    } else {

        /* Syntax: (top_field_param << 8) | bottom_field_param */

        pp->wBitstreamFcodes        = (v->lumscale << 8) | v->lumscale;

        pp->wBitstreamPCEelements   = (v->lumshift << 8) | v->lumshift;

    }

    pp->bBitstreamConcealmentNeed   = 0;

    pp->bBitstreamConcealmentMethod = 0;

}


static av_always_inline void sbr_hf_apply_noise(int (*Y)[2],

                                                const SoftFloat *s_m,

                                                const SoftFloat *q_filt,

                                                int noise,

                                                int phi_sign0,

                                                int phi_sign1,

                                                int m_max)

{

    int m;

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

        int y0 = Y[m][0];

        int y1 = Y[m][1];

        noise = (noise + 1) & 0x1ff;

        if (s_m[m].mant) {

            int shift, round;

            shift = 22 - s_m[m].exp;

            if (shift < 30) {

                round = 1 << (shift-1);

                y0 += (s_m[m].mant * phi_sign0 + round) >> shift;

                y1 += (s_m[m].mant * phi_sign1 + round) >> shift;

            }

        } else {

            int shift, round, tmp;

            int64_t accu;

            shift = 22 - q_filt[m].exp;

            if (shift < 30) {

                round = 1 << (shift-1);

                accu = (int64_t)q_filt[m].mant * ff_sbr_noise_table_fixed[noise][0];

                tmp = (int)((accu + 0x40000000) >> 31);

                y0 += (tmp + round) >> shift;

                accu = (int64_t)q_filt[m].mant * ff_sbr_noise_table_fixed[noise][1];

                tmp = (int)((accu + 0x40000000) >> 31);

                y1 += (tmp + round) >> shift;

            }

        }

        Y[m][0] = y0;

        Y[m][1] = y1;

        phi_sign1 = -phi_sign1;

    }

}


av_cold void ff_h264dsp_init_ppc(H264DSPContext *c, const int bit_depth,

                                 const int chroma_format_idc)

{

#if HAVE_ALTIVEC

    if (!(av_get_cpu_flags() & AV_CPU_FLAG_ALTIVEC))

        return;

    if (bit_depth == 8) {

        c->h264_idct_add = h264_idct_add_altivec;

        if (chroma_format_idc == 1)

            c->h264_idct_add8 = h264_idct_add8_altivec;

        c->h264_idct_add16      = h264_idct_add16_altivec;

        c->h264_idct_add16intra = h264_idct_add16intra_altivec;

        c->h264_idct_dc_add= h264_idct_dc_add_altivec;

        c->h264_idct8_dc_add = h264_idct8_dc_add_altivec;

        c->h264_idct8_add    = h264_idct8_add_altivec;

        c->h264_idct8_add4   = h264_idct8_add4_altivec;

        c->h264_v_loop_filter_luma= h264_v_loop_filter_luma_altivec;

        c->h264_h_loop_filter_luma= h264_h_loop_filter_luma_altivec;

        c->weight_h264_pixels_tab[0]   = weight_h264_pixels16_altivec;

        c->weight_h264_pixels_tab[1]   = weight_h264_pixels8_altivec;

        c->biweight_h264_pixels_tab[0] = biweight_h264_pixels16_altivec;

        c->biweight_h264_pixels_tab[1] = biweight_h264_pixels8_altivec;

    }

#endif /* HAVE_ALTIVEC */

}


static av_cold int atrac1_decode_init(AVCodecContext *avctx)

{

    AT1Ctx *q = avctx->priv_data;

    avctx->sample_fmt = AV_SAMPLE_FMT_FLT;

    if (avctx->channels < 1 || avctx->channels > AT1_MAX_CHANNELS) {

        av_log(avctx, AV_LOG_ERROR, "Unsupported number of channels: %d\n",

               avctx->channels);

        return AVERROR(EINVAL);

    }

    q->channels = avctx->channels;

    if (avctx->channels == 2) {

        q->out_samples[0] = av_malloc(2 * AT1_SU_SAMPLES * sizeof(*q->out_samples[0]));

        q->out_samples[1] = q->out_samples[0] + AT1_SU_SAMPLES;

        if (!q->out_samples[0]) {

            av_freep(&q->out_samples[0]);

            return AVERROR(ENOMEM);

        }

    }

    /* Init the mdct transforms */

    ff_mdct_init(&q->mdct_ctx[0], 6, 1, -1.0/ (1 << 15));

    ff_mdct_init(&q->mdct_ctx[1], 8, 1, -1.0/ (1 << 15));

    ff_mdct_init(&q->mdct_ctx[2], 9, 1, -1.0/ (1 << 15));

    ff_init_ff_sine_windows(5);

    atrac_generate_tables();

    dsputil_init(&q->dsp, avctx);

    ff_fmt_convert_init(&q->fmt_conv, avctx);

    q->bands[0] = q->low;

    q->bands[1] = q->mid;

    q->bands[2] = q->high;

    /* Prepare the mdct overlap buffers */

    q->SUs[0].spectrum[0] = q->SUs[0].spec1;

    q->SUs[0].spectrum[1] = q->SUs[0].spec2;

    q->SUs[1].spectrum[0] = q->SUs[1].spec1;

    q->SUs[1].spectrum[1] = q->SUs[1].spec2;

    return 0;

}


static int query_formats(AVFilterContext *ctx)

{

    AVFilterFormats *formats = NULL;

    int fmt;

    for (fmt = 0; fmt < AV_PIX_FMT_NB; fmt++) {

        const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(fmt);

        if (!(desc->flags & PIX_FMT_PAL ||

            fmt == AV_PIX_FMT_NV21 ||

            fmt == AV_PIX_FMT_NV12))

            ff_add_format(&formats, fmt);

    }

    ff_set_common_formats(ctx, formats);

    return 0;

}


Object *container_get(Object *root, const char *path)

{

    Object *obj, *child;

    gchar **parts;

    int i;

    parts = g_strsplit(path, "/", 0);

    assert(parts != NULL && parts[0] != NULL && !parts[0][0]);

    obj = root;

    for (i = 1; parts[i] != NULL; i++, obj = child) {

        child = object_resolve_path_component(obj, parts[i]);

        if (!child) {

            child = object_new("container");

            object_property_add_child(obj, parts[i], child, NULL);

        }

    }

    g_strfreev(parts);

    return obj;

}


int ff_h264_decode_ref_pic_list_reordering(H264Context *h){

    int list, index, pic_structure, i;

    print_short_term(h);

    print_long_term(h);

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

        for (i = 0; i < h->ref_count[list]; i++)

            COPY_PICTURE(&h->ref_list[list][i], &h->default_ref_list[list][i]);

        if(get_bits1(&h->gb)){

            int pred= h->curr_pic_num;

            for(index=0; ; index++){

                unsigned int reordering_of_pic_nums_idc= get_ue_golomb_31(&h->gb);

                unsigned int pic_id;

                int i;

                Picture *ref = NULL;

                if(reordering_of_pic_nums_idc==3)

                    break;

                if(index >= h->ref_count[list]){

                    av_log(h->avctx, AV_LOG_ERROR, "reference count overflow\n");

                    return -1;

                }

                if(reordering_of_pic_nums_idc<3){

                    if(reordering_of_pic_nums_idc<2){

                        const unsigned int abs_diff_pic_num= get_ue_golomb(&h->gb) + 1;

                        int frame_num;

                        if(abs_diff_pic_num > h->max_pic_num){

                            av_log(h->avctx, AV_LOG_ERROR, "abs_diff_pic_num overflow\n");

                            return -1;

                        }

                        if(reordering_of_pic_nums_idc == 0) pred-= abs_diff_pic_num;

                        else                                pred+= abs_diff_pic_num;

                        pred &= h->max_pic_num - 1;

                        frame_num = pic_num_extract(h, pred, &pic_structure);

                        for(i= h->short_ref_count-1; i>=0; i--){

                            ref = h->short_ref[i];

                            assert(ref->reference);

                            assert(!ref->long_ref);

                            if(

                                   ref->frame_num == frame_num &&

                                   (ref->reference & pic_structure)

                              )

                                break;

                        }

                        if(i>=0)

                            ref->pic_id= pred;

                    }else{

                        int long_idx;

                        pic_id= get_ue_golomb(&h->gb); //long_term_pic_idx

                        long_idx= pic_num_extract(h, pic_id, &pic_structure);

                        if(long_idx>31){

                            av_log(h->avctx, AV_LOG_ERROR, "long_term_pic_idx overflow\n");

                            return -1;

                        }

                        ref = h->long_ref[long_idx];

                        assert(!(ref && !ref->reference));

                        if (ref && (ref->reference & pic_structure)) {

                            ref->pic_id= pic_id;

                            assert(ref->long_ref);

                            i=0;

                        }else{

                            i=-1;

                        }

                    }

                    if (i < 0) {

                        av_log(h->avctx, AV_LOG_ERROR, "reference picture missing during reorder\n");

                        memset(&h->ref_list[list][index], 0, sizeof(Picture)); //FIXME

                    } else {

                        for(i=index; i+1<h->ref_count[list]; i++){

                            if(ref->long_ref == h->ref_list[list][i].long_ref && ref->pic_id == h->ref_list[list][i].pic_id)

                                break;

                        }

                        for(; i > index; i--){

                            COPY_PICTURE(&h->ref_list[list][i], &h->ref_list[list][i - 1]);

                        }

                        COPY_PICTURE(&h->ref_list[list][index], ref);

                        if (FIELD_PICTURE){

                            pic_as_field(&h->ref_list[list][index], pic_structure);

                        }

                    }

                }else{

                    av_log(h->avctx, AV_LOG_ERROR, "illegal reordering_of_pic_nums_idc\n");

                    return -1;

                }

            }

        }

    }

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

        for(index= 0; index < h->ref_count[list]; index++){

            if (!h->ref_list[list][index].f.data[0]) {

                int i;

                av_log(h->avctx, AV_LOG_ERROR, "Missing reference picture, default is %d\n", h->default_ref_list[list][0].poc);

                for (i=0; i<FF_ARRAY_ELEMS(h->last_pocs); i++)

                    h->last_pocs[i] = INT_MIN;

                if (h->default_ref_list[list][0].f.data[0])

                    COPY_PICTURE(&h->ref_list[list][index], &h->default_ref_list[list][0]);

                else

                    return -1;

            }

        }

    }

    return 0;

}


static void nfs_client_close(NFSClient *client)

{

    if (client->context) {

        if (client->fh) {

            nfs_close(client->context, client->fh);

        }

        aio_set_fd_handler(client->aio_context, nfs_get_fd(client->context),

                           false, NULL, NULL, NULL, NULL);

        nfs_destroy_context(client->context);

    }

    memset(client, 0, sizeof(NFSClient));

}


static void musicpal_init(ram_addr_t ram_size,

               const char *boot_device,

               const char *kernel_filename, const char *kernel_cmdline,

               const char *initrd_filename, const char *cpu_model)

{

    CPUState *env;

    qemu_irq *cpu_pic;

    qemu_irq pic[32];

    DeviceState *dev;

    DeviceState *i2c_dev;

    DeviceState *lcd_dev;

    DeviceState *key_dev;

#ifdef HAS_AUDIO

    DeviceState *wm8750_dev;

    SysBusDevice *s;

#endif

    i2c_bus *i2c;

    int i;

    unsigned long flash_size;

    DriveInfo *dinfo;

    ram_addr_t sram_off;

    if (!cpu_model) {

        cpu_model = "arm926";

    }

    env = cpu_init(cpu_model);

    if (!env) {

        fprintf(stderr, "Unable to find CPU definition\n");

        exit(1);

    }

    cpu_pic = arm_pic_init_cpu(env);

    /* For now we use a fixed - the original - RAM size */

    cpu_register_physical_memory(0, MP_RAM_DEFAULT_SIZE,

                                 qemu_ram_alloc(MP_RAM_DEFAULT_SIZE));

    sram_off = qemu_ram_alloc(MP_SRAM_SIZE);

    cpu_register_physical_memory(MP_SRAM_BASE, MP_SRAM_SIZE, sram_off);

    dev = sysbus_create_simple("mv88w8618_pic", MP_PIC_BASE,

                               cpu_pic[ARM_PIC_CPU_IRQ]);

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

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

    }

    sysbus_create_varargs("mv88w8618_pit", MP_PIT_BASE, pic[MP_TIMER1_IRQ],

                          pic[MP_TIMER2_IRQ], pic[MP_TIMER3_IRQ],

                          pic[MP_TIMER4_IRQ], NULL);

    if (serial_hds[0]) {

        serial_mm_init(MP_UART1_BASE, 2, pic[MP_UART1_IRQ], 1825000,

                   serial_hds[0], 1);

    }

    if (serial_hds[1]) {

        serial_mm_init(MP_UART2_BASE, 2, pic[MP_UART2_IRQ], 1825000,

                   serial_hds[1], 1);

    }

    /* Register flash */

    dinfo = drive_get(IF_PFLASH, 0, 0);

    if (dinfo) {

        flash_size = bdrv_getlength(dinfo->bdrv);

        if (flash_size != 8*1024*1024 && flash_size != 16*1024*1024 &&

            flash_size != 32*1024*1024) {

            fprintf(stderr, "Invalid flash image size\n");

            exit(1);

        }

        /*

         * The original U-Boot accesses the flash at 0xFE000000 instead of

         * 0xFF800000 (if there is 8 MB flash). So remap flash access if the

         * image is smaller than 32 MB.

         */

        pflash_cfi02_register(0-MP_FLASH_SIZE_MAX, qemu_ram_alloc(flash_size),

                              dinfo->bdrv, 0x10000,

                              (flash_size + 0xffff) >> 16,

                              MP_FLASH_SIZE_MAX / flash_size,

                              2, 0x00BF, 0x236D, 0x0000, 0x0000,

                              0x5555, 0x2AAA);

    }

    sysbus_create_simple("mv88w8618_flashcfg", MP_FLASHCFG_BASE, NULL);

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

    dev = qdev_create(NULL, "mv88w8618_eth");

    dev->nd = &nd_table[0];

    qdev_init(dev);

    sysbus_mmio_map(sysbus_from_qdev(dev), 0, MP_ETH_BASE);

    sysbus_connect_irq(sysbus_from_qdev(dev), 0, pic[MP_ETH_IRQ]);

    sysbus_create_simple("mv88w8618_wlan", MP_WLAN_BASE, NULL);

    musicpal_misc_init();

    dev = sysbus_create_simple("musicpal_gpio", MP_GPIO_BASE, pic[MP_GPIO_IRQ]);

    i2c_dev = sysbus_create_simple("bitbang_i2c", 0, NULL);

    i2c = (i2c_bus *)qdev_get_child_bus(i2c_dev, "i2c");

    lcd_dev = sysbus_create_simple("musicpal_lcd", MP_LCD_BASE, NULL);

    key_dev = sysbus_create_simple("musicpal_key", 0, NULL);

    /* I2C read data */

    qdev_connect_gpio_out(i2c_dev, 0,

                          qdev_get_gpio_in(dev, MP_GPIO_I2C_DATA_BIT));

    /* I2C data */

    qdev_connect_gpio_out(dev, 3, qdev_get_gpio_in(i2c_dev, 0));

    /* I2C clock */

    qdev_connect_gpio_out(dev, 4, qdev_get_gpio_in(i2c_dev, 1));

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

        qdev_connect_gpio_out(dev, i, qdev_get_gpio_in(lcd_dev, i));

    }

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

        qdev_connect_gpio_out(key_dev, i, qdev_get_gpio_in(dev, i + 8));

    }

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

        qdev_connect_gpio_out(key_dev, i, qdev_get_gpio_in(dev, i + 15));

    }

#ifdef HAS_AUDIO

    wm8750_dev = i2c_create_slave(i2c, "wm8750", MP_WM_ADDR);

    dev = qdev_create(NULL, "mv88w8618_audio");

    s = sysbus_from_qdev(dev);

    qdev_prop_set_ptr(dev, "wm8750", wm8750_dev);

    qdev_init(dev);

    sysbus_mmio_map(s, 0, MP_AUDIO_BASE);

    sysbus_connect_irq(s, 0, pic[MP_AUDIO_IRQ]);

#endif

    musicpal_binfo.ram_size = MP_RAM_DEFAULT_SIZE;

    musicpal_binfo.kernel_filename = kernel_filename;

    musicpal_binfo.kernel_cmdline = kernel_cmdline;

    musicpal_binfo.initrd_filename = initrd_filename;

    arm_load_kernel(env, &musicpal_binfo);

}


size_t qemu_mempath_getpagesize(const char *mem_path)

{

#ifdef CONFIG_LINUX

    struct statfs fs;

    int ret;

    do {

        ret = statfs(mem_path, &fs);

    } while (ret != 0 && errno == EINTR);

    if (ret != 0) {

        fprintf(stderr, "Couldn't statfs() memory path: %s\n",

                strerror(errno));

        exit(1);

    }

    if (fs.f_type == HUGETLBFS_MAGIC) {

        /* It's hugepage, return the huge page size */

        return fs.f_bsize;

    }

    return getpagesize();

}


static int nbd_send_negotiate(NBDClient *client)

{

    int csock = client->sock;

    char buf[8 + 8 + 8 + 128];

    int rc;

    const int myflags = (NBD_FLAG_HAS_FLAGS | NBD_FLAG_SEND_TRIM |

                         NBD_FLAG_SEND_FLUSH | NBD_FLAG_SEND_FUA);

    /* Negotiation header without options:

        [ 0 ..   7]   passwd       ("NBDMAGIC")

        [ 8 ..  15]   magic        (NBD_CLIENT_MAGIC)

        [16 ..  23]   size

        [24 ..  25]   server flags (0)

        [24 ..  27]   export flags

        [28 .. 151]   reserved     (0)

       Negotiation header with options, part 1:

        [ 0 ..   7]   passwd       ("NBDMAGIC")

        [ 8 ..  15]   magic        (NBD_OPTS_MAGIC)

        [16 ..  17]   server flags (0)

       part 2 (after options are sent):

        [18 ..  25]   size

        [26 ..  27]   export flags

        [28 .. 151]   reserved     (0)

     */

    socket_set_block(csock);

    rc = -EINVAL;

    TRACE("Beginning negotiation.");

    memcpy(buf, "NBDMAGIC", 8);

    if (client->exp) {

        assert ((client->exp->nbdflags & ~65535) == 0);

        cpu_to_be64w((uint64_t*)(buf + 8), NBD_CLIENT_MAGIC);

        cpu_to_be64w((uint64_t*)(buf + 16), client->exp->size);

        cpu_to_be16w((uint16_t*)(buf + 26), client->exp->nbdflags | myflags);

    } else {

        cpu_to_be64w((uint64_t*)(buf + 8), NBD_OPTS_MAGIC);

    }

    memset(buf + 28, 0, 124);

    if (client->exp) {

        if (write_sync(csock, buf, sizeof(buf)) != sizeof(buf)) {

            LOG("write failed");

            goto fail;

        }

    } else {

        if (write_sync(csock, buf, 18) != 18) {

            LOG("write failed");

            goto fail;

        }

        rc = nbd_receive_options(client);

        if (rc < 0) {

            LOG("option negotiation failed");

            goto fail;

        }

        assert ((client->exp->nbdflags & ~65535) == 0);

        cpu_to_be64w((uint64_t*)(buf + 18), client->exp->size);

        cpu_to_be16w((uint16_t*)(buf + 26), client->exp->nbdflags | myflags);

        if (write_sync(csock, buf + 18, sizeof(buf) - 18) != sizeof(buf) - 18) {

            LOG("write failed");

            goto fail;

        }

    }

    TRACE("Negotiation succeeded.");

    rc = 0;

fail:

    socket_set_nonblock(csock);

    return rc;

}


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

{

    int i;

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

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

}


static int read_seek(AVFormatContext *s, int stream_index,

                     int64_t timestamp, int flags)

{

    AVStream *st = s->streams[0];

    CaffContext *caf = s->priv_data;

    int64_t pos;

    timestamp = FFMAX(timestamp, 0);

    if (caf->frames_per_packet > 0 && caf->bytes_per_packet > 0) {

        /* calculate new byte position based on target frame position */

        pos = caf->bytes_per_packet * timestamp / caf->frames_per_packet;

        if (caf->data_size > 0)

            pos = FFMIN(pos, caf->data_size);

        caf->packet_cnt = pos / caf->bytes_per_packet;

        caf->frame_cnt  = caf->frames_per_packet * caf->packet_cnt;

    } else if (st->nb_index_entries) {

        caf->packet_cnt = av_index_search_timestamp(st, timestamp, flags);

        caf->frame_cnt  = st->index_entries[caf->packet_cnt].timestamp;

        pos             = st->index_entries[caf->packet_cnt].pos;

    } else {

        return -1;

    }

    avio_seek(s->pb, pos + caf->data_start, SEEK_SET);

    return 0;

}


static int tta_read_header(AVFormatContext *s)

{

    TTAContext *c = s->priv_data;

    AVStream *st;

    int i, channels, bps, samplerate;

    uint64_t framepos, start_offset;

    uint32_t nb_samples, crc;

    ff_id3v1_read(s);

    start_offset = avio_tell(s->pb);

    ffio_init_checksum(s->pb, tta_check_crc, UINT32_MAX);

    if (avio_rl32(s->pb) != AV_RL32("TTA1"))

        return AVERROR_INVALIDDATA;

    avio_skip(s->pb, 2); // FIXME: flags

    channels = avio_rl16(s->pb);

    bps = avio_rl16(s->pb);

    samplerate = avio_rl32(s->pb);

    if(samplerate <= 0 || samplerate > 1000000){

        av_log(s, AV_LOG_ERROR, "nonsense samplerate\n");

        return AVERROR_INVALIDDATA;

    }

    nb_samples = avio_rl32(s->pb);

    if (!nb_samples) {

        av_log(s, AV_LOG_ERROR, "invalid number of samples\n");

        return AVERROR_INVALIDDATA;

    }

    crc = ffio_get_checksum(s->pb) ^ UINT32_MAX;

    if (crc != avio_rl32(s->pb)) {

        av_log(s, AV_LOG_ERROR, "Header CRC error\n");

        return AVERROR_INVALIDDATA;

    }

    c->frame_size      = samplerate * 256 / 245;

    c->last_frame_size = nb_samples % c->frame_size;

    if (!c->last_frame_size)

        c->last_frame_size = c->frame_size;

    c->totalframes = nb_samples / c->frame_size + (c->last_frame_size < c->frame_size);

    c->currentframe = 0;

    if(c->totalframes >= UINT_MAX/sizeof(uint32_t) || c->totalframes <= 0){

        av_log(s, AV_LOG_ERROR, "totalframes %d invalid\n", c->totalframes);

        return AVERROR_INVALIDDATA;

    }

    st = avformat_new_stream(s, NULL);

    if (!st)

        return AVERROR(ENOMEM);

    avpriv_set_pts_info(st, 64, 1, samplerate);

    st->start_time = 0;

    st->duration = nb_samples;

    framepos = avio_tell(s->pb) + 4*c->totalframes + 4;

    if (ff_alloc_extradata(st->codec, avio_tell(s->pb) - start_offset))

        return AVERROR(ENOMEM);

    avio_seek(s->pb, start_offset, SEEK_SET);

    avio_read(s->pb, st->codec->extradata, st->codec->extradata_size);

    ffio_init_checksum(s->pb, tta_check_crc, UINT32_MAX);

    for (i = 0; i < c->totalframes; i++) {

        uint32_t size = avio_rl32(s->pb);

        av_add_index_entry(st, framepos, i * c->frame_size, size, 0,

                           AVINDEX_KEYFRAME);

        framepos += size;

    }

    crc = ffio_get_checksum(s->pb) ^ UINT32_MAX;

    if (crc != avio_rl32(s->pb)) {

        av_log(s, AV_LOG_ERROR, "Seek table CRC error\n");

        return AVERROR_INVALIDDATA;

    }

    st->codec->codec_type = AVMEDIA_TYPE_AUDIO;

    st->codec->codec_id = AV_CODEC_ID_TTA;

    st->codec->channels = channels;

    st->codec->sample_rate = samplerate;

    st->codec->bits_per_coded_sample = bps;

    if (s->pb->seekable) {

        int64_t pos = avio_tell(s->pb);

        ff_ape_parse_tag(s);

        avio_seek(s->pb, pos, SEEK_SET);

    }

    return 0;

}


static int planarCopyWrapper(SwsContext *c, const uint8_t* src[], int srcStride[], int srcSliceY,

                             int srcSliceH, uint8_t* dst[], int dstStride[])

{

    int plane, i, j;

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

        int length= (plane==0 || plane==3) ? c->srcW  : -((-c->srcW  )>>c->chrDstHSubSample);

        int y=      (plane==0 || plane==3) ? srcSliceY: -((-srcSliceY)>>c->chrDstVSubSample);

        int height= (plane==0 || plane==3) ? srcSliceH: -((-srcSliceH)>>c->chrDstVSubSample);

        const uint8_t *srcPtr= src[plane];

        uint8_t *dstPtr= dst[plane] + dstStride[plane]*y;

        if (!dst[plane]) continue;

        // ignore palette for GRAY8

        if (plane == 1 && !dst[2]) continue;

        if (!src[plane] || (plane == 1 && !src[2])) {

            if(is16BPS(c->dstFormat))

                length*=2;

            fillPlane(dst[plane], dstStride[plane], length, height, y, (plane==3) ? 255 : 128);

        } else {

            if(is9_OR_10BPS(c->srcFormat)) {

                const int src_depth = av_pix_fmt_descriptors[c->srcFormat].comp[plane].depth_minus1+1;

                const int dst_depth = av_pix_fmt_descriptors[c->dstFormat].comp[plane].depth_minus1+1;

                const uint16_t *srcPtr2 = (const uint16_t*)srcPtr;

                if (is16BPS(c->dstFormat)) {

                    uint16_t *dstPtr2 = (uint16_t*)dstPtr;

#define COPY9_OR_10TO16(rfunc, wfunc) \

                    for (i = 0; i < height; i++) { \

                        for (j = 0; j < length; j++) { \

                            int srcpx = rfunc(&srcPtr2[j]); \

                            wfunc(&dstPtr2[j], (srcpx<<(16-src_depth)) | (srcpx>>(2*src_depth-16))); \

                        } \

                        dstPtr2 += dstStride[plane]/2; \

                        srcPtr2 += srcStride[plane]/2; \

                    }

                    if (isBE(c->dstFormat)) {

                        if (isBE(c->srcFormat)) {

                            COPY9_OR_10TO16(AV_RB16, AV_WB16);

                        } else {

                            COPY9_OR_10TO16(AV_RL16, AV_WB16);

                        }

                    } else {

                        if (isBE(c->srcFormat)) {

                            COPY9_OR_10TO16(AV_RB16, AV_WL16);

                        } else {

                            COPY9_OR_10TO16(AV_RL16, AV_WL16);

                        }

                    }

                } else if (is9_OR_10BPS(c->dstFormat)) {

                    uint16_t *dstPtr2 = (uint16_t*)dstPtr;

#define COPY9_OR_10TO9_OR_10(loop) \

                    for (i = 0; i < height; i++) { \

                        for (j = 0; j < length; j++) { \

                            loop; \

                        } \

                        dstPtr2 += dstStride[plane]/2; \

                        srcPtr2 += srcStride[plane]/2; \

                    }

#define COPY9_OR_10TO9_OR_10_2(rfunc, wfunc) \

                    if (dst_depth > src_depth) { \

                        COPY9_OR_10TO9_OR_10(int srcpx = rfunc(&srcPtr2[j]); \

                            wfunc(&dstPtr2[j], (srcpx << 1) | (srcpx >> 9))); \

                    } else if (dst_depth < src_depth) { \

                        DITHER_COPY(dstPtr2, dstStride[plane]/2, wfunc, \

                                    srcPtr2, srcStride[plane]/2, rfunc, \

                                    dither_8x8_1, 1); \

                    } else { \

                        COPY9_OR_10TO9_OR_10(wfunc(&dstPtr2[j], rfunc(&srcPtr2[j]))); \

                    }

                    if (isBE(c->dstFormat)) {

                        if (isBE(c->srcFormat)) {

                            COPY9_OR_10TO9_OR_10_2(AV_RB16, AV_WB16);

                        } else {

                            COPY9_OR_10TO9_OR_10_2(AV_RL16, AV_WB16);

                        }

                    } else {

                        if (isBE(c->srcFormat)) {

                            COPY9_OR_10TO9_OR_10_2(AV_RB16, AV_WL16);

                        } else {

                            COPY9_OR_10TO9_OR_10_2(AV_RL16, AV_WL16);

                        }

                    }

                } else {

#define W8(a, b) { *(a) = (b); }

#define COPY9_OR_10TO8(rfunc) \

                    if (src_depth == 9) { \

                        DITHER_COPY(dstPtr,  dstStride[plane],   W8, \

                                    srcPtr2, srcStride[plane]/2, rfunc, \

                                    dither_8x8_1, 1); \

                    } else { \

                        DITHER_COPY(dstPtr,  dstStride[plane],   W8, \

                                    srcPtr2, srcStride[plane]/2, rfunc, \

                                    dither_8x8_3, 2); \

                    }

                    if (isBE(c->srcFormat)) {

                        COPY9_OR_10TO8(AV_RB16);

                    } else {

                        COPY9_OR_10TO8(AV_RL16);

                    }

                }

            } else if(is9_OR_10BPS(c->dstFormat)) {

                const int dst_depth = av_pix_fmt_descriptors[c->dstFormat].comp[plane].depth_minus1+1;

                uint16_t *dstPtr2 = (uint16_t*)dstPtr;

                if (is16BPS(c->srcFormat)) {

                    const uint16_t *srcPtr2 = (const uint16_t*)srcPtr;

#define COPY16TO9_OR_10(rfunc, wfunc) \

                    if (dst_depth == 9) { \

                        DITHER_COPY(dstPtr2, dstStride[plane]/2, wfunc, \

                                    srcPtr2, srcStride[plane]/2, rfunc, \

                                    dither_8x8_128, 7); \

                    } else { \

                        DITHER_COPY(dstPtr2, dstStride[plane]/2, wfunc, \

                                    srcPtr2, srcStride[plane]/2, rfunc, \

                                    dither_8x8_64, 6); \

                    }

                    if (isBE(c->dstFormat)) {

                        if (isBE(c->srcFormat)) {

                            COPY16TO9_OR_10(AV_RB16, AV_WB16);

                        } else {

                            COPY16TO9_OR_10(AV_RL16, AV_WB16);

                        }

                    } else {

                        if (isBE(c->srcFormat)) {

                            COPY16TO9_OR_10(AV_RB16, AV_WL16);

                        } else {

                            COPY16TO9_OR_10(AV_RL16, AV_WL16);

                        }

                    }

                } else /* 8bit */ {

#define COPY8TO9_OR_10(wfunc) \

                    for (i = 0; i < height; i++) { \

                        for (j = 0; j < length; j++) { \

                            const int srcpx = srcPtr[j]; \

                            wfunc(&dstPtr2[j], (srcpx<<(dst_depth-8)) | (srcpx >> (16-dst_depth))); \

                        } \

                        dstPtr2 += dstStride[plane]/2; \

                        srcPtr  += srcStride[plane]; \

                    }

                    if (isBE(c->dstFormat)) {

                        COPY8TO9_OR_10(AV_WB16);

                    } else {

                        COPY8TO9_OR_10(AV_WL16);

                    }

                }

            } else if(is16BPS(c->srcFormat) && !is16BPS(c->dstFormat)) {

                const uint16_t *srcPtr2 = (const uint16_t*)srcPtr;

#define COPY16TO8(rfunc) \

                    DITHER_COPY(dstPtr,  dstStride[plane],   W8, \

                                srcPtr2, srcStride[plane]/2, rfunc, \

                                dither_8x8_256, 8);

                if (isBE(c->srcFormat)) {

                    COPY16TO8(AV_RB16);

                } else {

                    COPY16TO8(AV_RL16);

                }

            } else if(!is16BPS(c->srcFormat) && is16BPS(c->dstFormat)) {

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

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

                        dstPtr[ j<<1   ] = srcPtr[j];

                        dstPtr[(j<<1)+1] = srcPtr[j];

                    }

                    srcPtr+= srcStride[plane];

                    dstPtr+= dstStride[plane];

                }

            } else if(is16BPS(c->srcFormat) && is16BPS(c->dstFormat)

                  && isBE(c->srcFormat) != isBE(c->dstFormat)) {

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

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

                        ((uint16_t*)dstPtr)[j] = av_bswap16(((const uint16_t*)srcPtr)[j]);

                    srcPtr+= srcStride[plane];

                    dstPtr+= dstStride[plane];

                }

            } else if (dstStride[plane] == srcStride[plane] &&

                       srcStride[plane] > 0 && srcStride[plane] == length) {

                memcpy(dst[plane] + dstStride[plane]*y, src[plane],

                       height*dstStride[plane]);

            } else {

                if(is16BPS(c->srcFormat) && is16BPS(c->dstFormat))

                    length*=2;

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

                    memcpy(dstPtr, srcPtr, length);

                    srcPtr+= srcStride[plane];

                    dstPtr+= dstStride[plane];

                }

            }

        }

    }

    return srcSliceH;

}


static int nbd_co_receive_offset_data_payload(NBDClientSession *s,

                                              uint64_t orig_offset,

                                              QEMUIOVector *qiov, Error **errp)

{

    QEMUIOVector sub_qiov;

    uint64_t offset;

    size_t data_size;

    int ret;

    NBDStructuredReplyChunk *chunk = &s->reply.structured;

    assert(nbd_reply_is_structured(&s->reply));

    if (chunk->length < sizeof(offset)) {

        error_setg(errp, "Protocol error: invalid payload for "

                         "NBD_REPLY_TYPE_OFFSET_DATA");

        return -EINVAL;

    }

    if (nbd_read(s->ioc, &offset, sizeof(offset), errp) < 0) {

        return -EIO;

    }

    be64_to_cpus(&offset);

    data_size = chunk->length - sizeof(offset);

    if (offset < orig_offset || data_size > qiov->size ||

        offset > orig_offset + qiov->size - data_size) {

        error_setg(errp, "Protocol error: server sent chunk exceeding requested"

                         " region");

        return -EINVAL;

    }

    qemu_iovec_init(&sub_qiov, qiov->niov);

    qemu_iovec_concat(&sub_qiov, qiov, offset - orig_offset, data_size);

    ret = qio_channel_readv_all(s->ioc, sub_qiov.iov, sub_qiov.niov, errp);

    qemu_iovec_destroy(&sub_qiov);

    return ret < 0 ? -EIO : 0;

}


void xen_pt_msi_disable(XenPCIPassthroughState *s)

{

    XenPTMSI *msi = s->msi;

    if (!msi) {

        return;

    }

    xen_pt_msi_set_enable(s, false);

    msi_msix_disable(s, msi_addr64(msi), msi->data, msi->pirq, false,

                     msi->initialized);

    /* clear msi info */

    msi->flags = 0;

    msi->mapped = false;

    msi->pirq = XEN_PT_UNASSIGNED_PIRQ;

}


static inline void RENAME(hScale)(int16_t *dst, int dstW, uint8_t *src, int srcW, int xInc,

				  int16_t *filter, int16_t *filterPos, long filterSize)

{

#ifdef HAVE_MMX

	assert(filterSize % 4 == 0 && filterSize>0);

	if(filterSize==4) // Always true for upscaling, sometimes for down, too.

	{

		long counter= -2*dstW;

		filter-= counter*2;

		filterPos-= counter/2;

		dst-= counter/2;

		asm volatile(

#if defined(PIC)

			"push %%"REG_b"   		\n\t"

#endif

			"pxor %%mm7, %%mm7		\n\t"

			"movq "MANGLE(w02)", %%mm6	\n\t"

			"push %%"REG_BP"		\n\t" // we use 7 regs here ...

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

			ASMALIGN(4)

			"1:				\n\t"

			"movzwl (%2, %%"REG_BP"), %%eax	\n\t"

			"movzwl 2(%2, %%"REG_BP"), %%ebx\n\t"

			"movq (%1, %%"REG_BP", 4), %%mm1\n\t"

			"movq 8(%1, %%"REG_BP", 4), %%mm3\n\t"

			"movd (%3, %%"REG_a"), %%mm0	\n\t"

			"movd (%3, %%"REG_b"), %%mm2	\n\t"

			"punpcklbw %%mm7, %%mm0		\n\t"

			"punpcklbw %%mm7, %%mm2		\n\t"

			"pmaddwd %%mm1, %%mm0		\n\t"

			"pmaddwd %%mm2, %%mm3		\n\t"

			"psrad $8, %%mm0		\n\t"

			"psrad $8, %%mm3		\n\t"

			"packssdw %%mm3, %%mm0		\n\t"

			"pmaddwd %%mm6, %%mm0		\n\t"

			"packssdw %%mm0, %%mm0		\n\t"

			"movd %%mm0, (%4, %%"REG_BP")	\n\t"

			"add $4, %%"REG_BP"		\n\t"

			" jnc 1b			\n\t"

			"pop %%"REG_BP"			\n\t"

#if defined(PIC)

			"pop %%"REG_b"   		\n\t"

#endif

			: "+a" (counter)

			: "c" (filter), "d" (filterPos), "S" (src), "D" (dst)

#if !defined(PIC)

			: "%"REG_b

#endif

		);

	}

	else if(filterSize==8)

	{

		long counter= -2*dstW;

		filter-= counter*4;

		filterPos-= counter/2;

		dst-= counter/2;

		asm volatile(

#if defined(PIC)

			"push %%"REG_b"   		\n\t"

#endif

			"pxor %%mm7, %%mm7		\n\t"

			"movq "MANGLE(w02)", %%mm6	\n\t"

			"push %%"REG_BP"		\n\t" // we use 7 regs here ...

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

			ASMALIGN(4)

			"1:				\n\t"

			"movzwl (%2, %%"REG_BP"), %%eax	\n\t"

			"movzwl 2(%2, %%"REG_BP"), %%ebx\n\t"

			"movq (%1, %%"REG_BP", 8), %%mm1\n\t"

			"movq 16(%1, %%"REG_BP", 8), %%mm3\n\t"

			"movd (%3, %%"REG_a"), %%mm0	\n\t"

			"movd (%3, %%"REG_b"), %%mm2	\n\t"

			"punpcklbw %%mm7, %%mm0		\n\t"

			"punpcklbw %%mm7, %%mm2		\n\t"

			"pmaddwd %%mm1, %%mm0		\n\t"

			"pmaddwd %%mm2, %%mm3		\n\t"

			"movq 8(%1, %%"REG_BP", 8), %%mm1\n\t"

			"movq 24(%1, %%"REG_BP", 8), %%mm5\n\t"

			"movd 4(%3, %%"REG_a"), %%mm4	\n\t"

			"movd 4(%3, %%"REG_b"), %%mm2	\n\t"

			"punpcklbw %%mm7, %%mm4		\n\t"

			"punpcklbw %%mm7, %%mm2		\n\t"

			"pmaddwd %%mm1, %%mm4		\n\t"

			"pmaddwd %%mm2, %%mm5		\n\t"

			"paddd %%mm4, %%mm0		\n\t"

			"paddd %%mm5, %%mm3		\n\t"

			"psrad $8, %%mm0		\n\t"

			"psrad $8, %%mm3		\n\t"

			"packssdw %%mm3, %%mm0		\n\t"

			"pmaddwd %%mm6, %%mm0		\n\t"

			"packssdw %%mm0, %%mm0		\n\t"

			"movd %%mm0, (%4, %%"REG_BP")	\n\t"

			"add $4, %%"REG_BP"		\n\t"

			" jnc 1b			\n\t"

			"pop %%"REG_BP"			\n\t"

#if defined(PIC)

			"pop %%"REG_b"   		\n\t"

#endif

			: "+a" (counter)

			: "c" (filter), "d" (filterPos), "S" (src), "D" (dst)

#if !defined(PIC)

			: "%"REG_b

#endif

		);

	}

	else

	{

		uint8_t *offset = src+filterSize;

		long counter= -2*dstW;

//		filter-= counter*filterSize/2;

		filterPos-= counter/2;

		dst-= counter/2;

		asm volatile(

			"pxor %%mm7, %%mm7		\n\t"

			"movq "MANGLE(w02)", %%mm6	\n\t"

			ASMALIGN(4)

			"1:				\n\t"

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

			"movzwl (%%"REG_c", %0), %%eax	\n\t"

			"movzwl 2(%%"REG_c", %0), %%edx	\n\t"

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

			"pxor %%mm4, %%mm4		\n\t"

			"pxor %%mm5, %%mm5		\n\t"

			"2:				\n\t"

			"movq (%1), %%mm1		\n\t"

			"movq (%1, %6), %%mm3		\n\t"

			"movd (%%"REG_c", %%"REG_a"), %%mm0\n\t"

			"movd (%%"REG_c", %%"REG_d"), %%mm2\n\t"

			"punpcklbw %%mm7, %%mm0		\n\t"

			"punpcklbw %%mm7, %%mm2		\n\t"

			"pmaddwd %%mm1, %%mm0		\n\t"

			"pmaddwd %%mm2, %%mm3		\n\t"

			"paddd %%mm3, %%mm5		\n\t"

			"paddd %%mm0, %%mm4		\n\t"

			"add $8, %1			\n\t"

			"add $4, %%"REG_c"		\n\t"

			"cmp %4, %%"REG_c"		\n\t"

			" jb 2b				\n\t"

			"add %6, %1			\n\t"

			"psrad $8, %%mm4		\n\t"

			"psrad $8, %%mm5		\n\t"

			"packssdw %%mm5, %%mm4		\n\t"

			"pmaddwd %%mm6, %%mm4		\n\t"

			"packssdw %%mm4, %%mm4		\n\t"

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

			"movd %%mm4, (%%"REG_a", %0)	\n\t"

			"add $4, %0			\n\t"

			" jnc 1b			\n\t"

			: "+r" (counter), "+r" (filter)

			: "m" (filterPos), "m" (dst), "m"(offset),

			  "m" (src), "r" (filterSize*2)

			: "%"REG_a, "%"REG_c, "%"REG_d

		);

	}

#else

#ifdef HAVE_ALTIVEC

	hScale_altivec_real(dst, dstW, src, srcW, xInc, filter, filterPos, filterSize);

#else

	int i;

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

	{

		int j;

		int srcPos= filterPos[i];

		int val=0;

//		printf("filterPos: %d\n", filterPos[i]);

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

		{

//			printf("filter: %d, src: %d\n", filter[i], src[srcPos + j]);

			val += ((int)src[srcPos + j])*filter[filterSize*i + j];

		}

//		filter += hFilterSize;

		dst[i] = av_clip(val>>7, 0, (1<<15)-1); // the cubic equation does overflow ...

//		dst[i] = val>>7;

	}

#endif

#endif

}


static void qpeg_decode_inter(QpegContext *qctx, uint8_t *dst,

                              int stride, int width, int height,

                              int delta, const uint8_t *ctable,

                              uint8_t *refdata)

{

    int i, j;

    int code;

    int filled = 0;

    int orig_height;

    /* copy prev frame */

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

        memcpy(refdata + (i * width), dst + (i * stride), width);

    orig_height = height;

    height--;

    dst = dst + height * stride;

    while ((bytestream2_get_bytes_left(&qctx->buffer) > 0) && (height >= 0)) {

        code = bytestream2_get_byte(&qctx->buffer);

        if(delta) {

            /* motion compensation */

            while((code & 0xF0) == 0xF0) {

                if(delta == 1) {

                    int me_idx;

                    int me_w, me_h, me_x, me_y;

                    uint8_t *me_plane;

                    int corr, val;

                    /* get block size by index */

                    me_idx = code & 0xF;

                    me_w = qpeg_table_w[me_idx];

                    me_h = qpeg_table_h[me_idx];

                    /* extract motion vector */

                    corr = bytestream2_get_byte(&qctx->buffer);

                    val = corr >> 4;

                    if(val > 7)

                        val -= 16;

                    me_x = val;

                    val = corr & 0xF;

                    if(val > 7)

                        val -= 16;

                    me_y = val;

                    /* check motion vector */

                    if ((me_x + filled < 0) || (me_x + me_w + filled > width) ||

                       (height - me_y - me_h < 0) || (height - me_y > orig_height) ||

                       (filled + me_w > width) || (height - me_h < 0))

                        av_log(NULL, AV_LOG_ERROR, "Bogus motion vector (%i,%i), block size %ix%i at %i,%i\n",

                               me_x, me_y, me_w, me_h, filled, height);

                    else {

                        /* do motion compensation */

                        me_plane = refdata + (filled + me_x) + (height - me_y) * width;

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

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

                                dst[filled + i - (j * stride)] = me_plane[i - (j * width)];

                        }

                    }

                }

                code = bytestream2_get_byte(&qctx->buffer);

            }

        }

        if(code == 0xE0) /* end-of-picture code */

            break;

        if(code > 0xE0) { /* run code: 0xE1..0xFF */

            int p;

            code &= 0x1F;

            p = bytestream2_get_byte(&qctx->buffer);

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

                dst[filled++] = p;

                if(filled >= width) {

                    filled = 0;

                    dst -= stride;

                    height--;

                    if (height < 0)

                        break;

                }

            }

        } else if(code >= 0xC0) { /* copy code: 0xC0..0xDF */

            code &= 0x1F;

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

                dst[filled++] = bytestream2_get_byte(&qctx->buffer);

                if(filled >= width) {

                    filled = 0;

                    dst -= stride;

                    height--;

                    if (height < 0)

                        break;

                }

            }

        } else if(code >= 0x80) { /* skip code: 0x80..0xBF */

            int skip;

            code &= 0x3F;

            /* codes 0x80 and 0x81 are actually escape codes,

               skip value minus constant is in the next byte */

            if(!code)

                skip = bytestream2_get_byte(&qctx->buffer) +  64;

            else if(code == 1)

                skip = bytestream2_get_byte(&qctx->buffer) + 320;

            else

                skip = code;

            filled += skip;

            while( filled >= width) {

                filled -= width;

                dst -= stride;

                height--;

                if(height < 0)

                    break;

            }

        } else {

            /* zero code treated as one-pixel skip */

            if(code) {

                dst[filled++] = ctable[code & 0x7F];

            }

            else

                filled++;

            if(filled >= width) {

                filled = 0;

                dst -= stride;

                height--;

            }

        }

    }

}


static int unpack(const uint8_t *src, const uint8_t *src_end, unsigned char *dst, int width, int height) {

    unsigned char *dst_end = dst + width*height;

    int size,size1,size2,offset,run;

    unsigned char *dst_start = dst;

    if (src[0] & 0x01)

        src += 5;

    else

        src += 2;

    if (src+3>src_end)

        return -1;

    size = AV_RB24(src);

    src += 3;

    while(size>0 && src<src_end) {

        /* determine size1 and size2 */

        size1 = (src[0] & 3);

        if ( src[0] & 0x80 ) {  // 1

            if (src[0] & 0x40 ) {  // 11

                if ( src[0] & 0x20 ) {  // 111

                    if ( src[0] < 0xFC )  // !(111111)

                        size1 = (((src[0] & 31) + 1) << 2);

                    src++;

                    size2 = 0;

                } else {  // 110

                    offset = ((src[0] & 0x10) << 12) + AV_RB16(&src[1]) + 1;

                    size2 = ((src[0] & 0xC) << 6) + src[3] + 5;

                    src += 4;

                }

            } else {  // 10

                size1 = ( ( src[1] & 0xC0) >> 6 );

                offset = (AV_RB16(&src[1]) & 0x3FFF) + 1;

                size2 = (src[0] & 0x3F) + 4;

                src += 3;

            }

        } else {  // 0

            offset = ((src[0] & 0x60) << 3) + src[1] + 1;

            size2 = ((src[0] & 0x1C) >> 2) + 3;

            src += 2;

        }

        /* fetch strip from src */

        if (size1>src_end-src)

            break;

        if (size1>0) {

            size -= size1;

            run = FFMIN(size1, dst_end-dst);

            memcpy(dst, src, run);

            dst += run;

            src += run;

        }

        if (size2>0) {

            if (dst-dst_start<offset)

                return 0;

            size -= size2;

            run = FFMIN(size2, dst_end-dst);

            av_memcpy_backptr(dst, offset, run);

            dst += run;

        }

    }

    return 0;

}


void qmp_block_resize(bool has_device, const char *device,
                      bool has_node_name, const char *node_name,
                      int64_t size, Error **errp)
{
    Error *local_err = NULL;
    BlockDriverState *bs;
    int ret;
    bs = bdrv_lookup_bs(has_device ? device : NULL,
                        has_node_name ? node_name : NULL,
                        &local_err);
    if (local_err) {
        error_propagate(errp, local_err);
    if (!bdrv_is_first_non_filter(bs)) {
        error_set(errp, QERR_FEATURE_DISABLED, "resize");
    if (size < 0) {
        error_set(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
    /* complete all in-flight operations before resizing the device */
    bdrv_drain_all();
    ret = bdrv_truncate(bs, size);
    switch (ret) {
    case 0:
        break;
    case -ENOMEDIUM:
        error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
        break;
    case -ENOTSUP:
        error_set(errp, QERR_UNSUPPORTED);
        break;
    case -EACCES:
        error_set(errp, QERR_DEVICE_IS_READ_ONLY, device);
        break;
    case -EBUSY:
        break;
    default:
        error_setg_errno(errp, -ret, "Could not resize");
        break;


static int32_t bmdma_prepare_buf(IDEDMA *dma, int32_t limit)

{

    BMDMAState *bm = DO_UPCAST(BMDMAState, dma, dma);

    IDEState *s = bmdma_active_if(bm);

    PCIDevice *pci_dev = PCI_DEVICE(bm->pci_dev);

    struct {

        uint32_t addr;

        uint32_t size;

    } prd;

    int l, len;

    pci_dma_sglist_init(&s->sg, pci_dev,

                        s->nsector / (BMDMA_PAGE_SIZE / 512) + 1);

    s->io_buffer_size = 0;

    for(;;) {

        if (bm->cur_prd_len == 0) {

            /* end of table (with a fail safe of one page) */

            if (bm->cur_prd_last ||

                (bm->cur_addr - bm->addr) >= BMDMA_PAGE_SIZE) {

                return s->sg.size;

            }

            pci_dma_read(pci_dev, bm->cur_addr, &prd, 8);

            bm->cur_addr += 8;

            prd.addr = le32_to_cpu(prd.addr);

            prd.size = le32_to_cpu(prd.size);

            len = prd.size & 0xfffe;

            if (len == 0)

                len = 0x10000;

            bm->cur_prd_len = len;

            bm->cur_prd_addr = prd.addr;

            bm->cur_prd_last = (prd.size & 0x80000000);

        }

        l = bm->cur_prd_len;

        if (l > 0) {

            uint64_t sg_len;

            /* Don't add extra bytes to the SGList; consume any remaining

             * PRDs from the guest, but ignore them. */

            sg_len = MIN(limit - s->sg.size, bm->cur_prd_len);

            if (sg_len) {

                qemu_sglist_add(&s->sg, bm->cur_prd_addr, sg_len);

            }

            /* Note: We limit the max transfer to be 2GiB.

             * This should accommodate the largest ATA transaction

             * for LBA48 (65,536 sectors) and 32K sector sizes. */

            if (s->sg.size > INT32_MAX) {

                error_report("IDE: sglist describes more than 2GiB.");

                break;

            }

            bm->cur_prd_addr += l;

            bm->cur_prd_len -= l;

            s->io_buffer_size += l;

        }

    }

    qemu_sglist_destroy(&s->sg);

    s->io_buffer_size = 0;

    return -1;

}


static inline void RENAME(yvu9toyv12)(const uint8_t *ysrc, const uint8_t *usrc, const uint8_t *vsrc,

	uint8_t *ydst, uint8_t *udst, uint8_t *vdst,

	long width, long height, long lumStride, long chromStride)

{

	/* Y Plane */

	memcpy(ydst, ysrc, width*height);

	/* XXX: implement upscaling for U,V */

}


void qemu_iovec_add(QEMUIOVector *qiov, void *base, size_t len)

{

    assert(qiov->nalloc != -1);

    if (qiov->niov == qiov->nalloc) {

        qiov->nalloc = 2 * qiov->nalloc + 1;

        qiov->iov = g_realloc(qiov->iov, qiov->nalloc * sizeof(struct iovec));

    }

    qiov->iov[qiov->niov].iov_base = base;

    qiov->iov[qiov->niov].iov_len = len;

    qiov->size += len;

    ++qiov->niov;

}


int ff_hevc_cabac_init(HEVCContext *s, int ctb_addr_ts)

{

    if (ctb_addr_ts == s->ps.pps->ctb_addr_rs_to_ts[s->sh.slice_ctb_addr_rs]) {

        int ret = cabac_init_decoder(s);

        if (ret < 0)

            return ret;

        if (s->sh.dependent_slice_segment_flag == 0 ||

            (s->ps.pps->tiles_enabled_flag &&

             s->ps.pps->tile_id[ctb_addr_ts] != s->ps.pps->tile_id[ctb_addr_ts - 1]))

            cabac_init_state(s);

        if (!s->sh.first_slice_in_pic_flag &&

            s->ps.pps->entropy_coding_sync_enabled_flag) {

            if (ctb_addr_ts % s->ps.sps->ctb_width == 0) {

                if (s->ps.sps->ctb_width == 1)

                    cabac_init_state(s);

                else if (s->sh.dependent_slice_segment_flag == 1)

                    load_states(s);

            }

        }

    } else {

        if (s->ps.pps->tiles_enabled_flag &&

            s->ps.pps->tile_id[ctb_addr_ts] != s->ps.pps->tile_id[ctb_addr_ts - 1]) {

            if (s->threads_number == 1)

                cabac_reinit(s->HEVClc);

            else {

                int ret = cabac_init_decoder(s);

                if (ret < 0)

                    return ret;

            }

            cabac_init_state(s);

        }

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

            if (ctb_addr_ts % s->ps.sps->ctb_width == 0) {

                get_cabac_terminate(&s->HEVClc->cc);

                if (s->threads_number == 1)

                    cabac_reinit(s->HEVClc);

                else {

                    int ret = cabac_init_decoder(s);

                    if (ret < 0)

                        return ret;

                }

                if (s->ps.sps->ctb_width == 1)

                    cabac_init_state(s);

                else

                    load_states(s);

            }

        }

    }

    return 0;

}


static int handle_utimensat(FsContext *ctx, V9fsPath *fs_path,

                            const struct timespec *buf)

{

    int ret;

#ifdef CONFIG_UTIMENSAT

    int fd;

    struct handle_data *data = (struct handle_data *)ctx->private;

    fd = open_by_handle(data->mountfd, fs_path->data, O_NONBLOCK);

    if (fd < 0) {

        return fd;

    }

    ret = futimens(fd, buf);

    close(fd);

#else

    ret = -1;

    errno = ENOSYS;

#endif

    return ret;

}


void object_property_add_str(Object *obj, const char *name,

                           char *(*get)(Object *, Error **),

                           void (*set)(Object *, const char *, Error **),

                           Error **errp)

{

    StringProperty *prop = g_malloc0(sizeof(*prop));

    prop->get = get;

    prop->set = set;

    object_property_add(obj, name, "string",

                        get ? property_get_str : NULL,

                        set ? property_set_str : NULL,

                        property_release_str,

                        prop, errp);

}


static int disas_cp14_write(CPUState * env, DisasContext *s, uint32_t insn)

{

    int crn = (insn >> 16) & 0xf;

    int crm = insn & 0xf;

    int op1 = (insn >> 21) & 7;

    int op2 = (insn >> 5) & 7;

    int rt = (insn >> 12) & 0xf;

    TCGv tmp;

    if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {

        if (op1 == 6 && crn == 0 && crm == 0 && op2 == 0) {

            /* TEECR */

            if (IS_USER(s))

                return 1;

            tmp = load_reg(s, rt);

            gen_helper_set_teecr(cpu_env, tmp);

            dead_tmp(tmp);

            return 0;

        }

        if (op1 == 6 && crn == 1 && crm == 0 && op2 == 0) {

            /* TEEHBR */

            if (IS_USER(s) && (env->teecr & 1))

                return 1;

            tmp = load_reg(s, rt);

            store_cpu_field(tmp, teehbr);

            return 0;

        }

    }

    fprintf(stderr, "Unknown cp14 write op1:%d crn:%d crm:%d op2:%d\n",

            op1, crn, crm, op2);

    return 1;

}


static void tcp_wait_for_connect(int fd, Error *err, void *opaque)

{

    MigrationState *s = opaque;

    if (fd < 0) {

        DPRINTF("migrate connect error: %s\n", error_get_pretty(err));

        s->to_dst_file = NULL;

        migrate_fd_error(s);

    } else {

        DPRINTF("migrate connect success\n");

        s->to_dst_file = qemu_fopen_socket(fd, "wb");

        migrate_fd_connect(s);

    }

}


static FlatView generate_memory_topology(MemoryRegion *mr)

{

    FlatView view;

    flatview_init(&view);

    render_memory_region(&view, mr, 0, addrrange_make(0, UINT64_MAX));

    flatview_simplify(&view);

    return view;

}


static void visit_type_int32(Visitor *v, int *value, const char *name, Error **errp)

{

    int64_t val = *value;

    visit_type_int(v, &val, name, errp);

}


static inline int tcg_gen_code_common(TCGContext *s, uint8_t *gen_code_buf,

                                      int do_search_pc,

                                      const uint8_t *searched_pc)

{

    int opc, op_index, macro_op_index;

    const TCGOpDef *def;

    unsigned int dead_iargs;

    const TCGArg *args;

#ifdef DEBUG_DISAS

    if (unlikely(loglevel & CPU_LOG_TB_OP)) {

        fprintf(logfile, "OP:\n");

        tcg_dump_ops(s, logfile);

        fprintf(logfile, "\n");

    }

#endif

    tcg_liveness_analysis(s);

#ifdef DEBUG_DISAS

    if (unlikely(loglevel & CPU_LOG_TB_OP_OPT)) {

        fprintf(logfile, "OP after la:\n");

        tcg_dump_ops(s, logfile);

        fprintf(logfile, "\n");

    }

#endif

    tcg_reg_alloc_start(s);

    s->code_buf = gen_code_buf;

    s->code_ptr = gen_code_buf;

    macro_op_index = -1;

    args = gen_opparam_buf;

    op_index = 0;

    for(;;) {

        opc = gen_opc_buf[op_index];

#ifdef CONFIG_PROFILER

        dyngen_table_op_count[opc]++;

#endif

        def = &tcg_op_defs[opc];

#if 0

        printf("%s: %d %d %d\n", def->name,

               def->nb_oargs, def->nb_iargs, def->nb_cargs);

        //        dump_regs(s);

#endif

        switch(opc) {

        case INDEX_op_mov_i32:

#if TCG_TARGET_REG_BITS == 64

        case INDEX_op_mov_i64:

#endif

            dead_iargs = s->op_dead_iargs[op_index];

            tcg_reg_alloc_mov(s, def, args, dead_iargs);

            break;

        case INDEX_op_nop:

        case INDEX_op_nop1:

        case INDEX_op_nop2:

        case INDEX_op_nop3:

            break;

        case INDEX_op_nopn:

            args += args[0];

            goto next;

        case INDEX_op_discard:

            {

                TCGTemp *ts;

                ts = &s->temps[args[0]];

                /* mark the temporary as dead */

                if (ts->val_type != TEMP_VAL_CONST && !ts->fixed_reg) {

                    if (ts->val_type == TEMP_VAL_REG)

                        s->reg_to_temp[ts->reg] = -1;

                    ts->val_type = TEMP_VAL_DEAD;

                }

            }

            break;

        case INDEX_op_macro_goto:

            macro_op_index = op_index; /* only used for exceptions */

            op_index = args[0] - 1;

            args = gen_opparam_buf + args[1];

            goto next;

        case INDEX_op_macro_end:

            macro_op_index = -1; /* only used for exceptions */

            op_index = args[0] - 1;

            args = gen_opparam_buf + args[1];

            goto next;

        case INDEX_op_macro_start:

            /* must never happen here */

            tcg_abort();

        case INDEX_op_set_label:

            tcg_reg_alloc_bb_end(s);

            tcg_out_label(s, args[0], (long)s->code_ptr);

            break;

        case INDEX_op_call:

            dead_iargs = s->op_dead_iargs[op_index];

            args += tcg_reg_alloc_call(s, def, opc, args, dead_iargs);

            goto next;

        case INDEX_op_end:

            goto the_end;

        case 0 ... INDEX_op_end - 1:

            /* legacy dyngen ops */

#ifdef CONFIG_PROFILER

            {

                extern int64_t dyngen_old_op_count;

                dyngen_old_op_count++;

            }

#endif

            tcg_reg_alloc_bb_end(s);

            if (do_search_pc) {

                s->code_ptr += def->copy_size;

                args += def->nb_args;

            } else {

                args = dyngen_op(s, opc, args);

            }

            goto next;

        default:

            /* Note: in order to speed up the code, it would be much

               faster to have specialized register allocator functions for

               some common argument patterns */

            dead_iargs = s->op_dead_iargs[op_index];

            tcg_reg_alloc_op(s, def, opc, args, dead_iargs);

            break;

        }

        args += def->nb_args;

    next: ;

        if (do_search_pc) {

            if (searched_pc < s->code_ptr) {

                if (macro_op_index >= 0)

                    return macro_op_index;

                else

                    return op_index;

            }

        }

        op_index++;

#ifndef NDEBUG

        check_regs(s);

#endif

    }

 the_end:

    return -1;

}


static int setup_hwaccel(AVCodecContext *avctx,
                         const enum AVPixelFormat fmt,
                         const char *name)
{
    AVHWAccel *hwa = find_hwaccel(avctx->codec_id, fmt);
    int ret        = 0;
    if (!hwa) {
               "Could not find an AVHWAccel for the pixel format: %s",
               name);
        return AVERROR(ENOENT);
    if (hwa->capabilities & HWACCEL_CODEC_CAP_EXPERIMENTAL &&
        avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
        av_log(avctx, AV_LOG_WARNING, "Ignoring experimental hwaccel: %s\n",
               hwa->name);
        return AVERROR_PATCHWELCOME;
    if (hwa->priv_data_size) {
        avctx->internal->hwaccel_priv_data = av_mallocz(hwa->priv_data_size);
        if (!avctx->internal->hwaccel_priv_data)
            return AVERROR(ENOMEM);
    if (hwa->init) {
        ret = hwa->init(avctx);
        if (ret < 0) {
            av_freep(&avctx->internal->hwaccel_priv_data);
            return ret;
    avctx->hwaccel = hwa;
    return 0;


static void rpza_decode_stream(RpzaContext *s)

{

    int width = s->avctx->width;

    int stride = s->frame.linesize[0] / 2;

    int row_inc = stride - 4;

    int stream_ptr = 0;

    int chunk_size;

    unsigned char opcode;

    int n_blocks;

    unsigned short colorA = 0, colorB;

    unsigned short color4[4];

    unsigned char index, idx;

    unsigned short ta, tb;

    unsigned short *pixels = (unsigned short *)s->frame.data[0];

    int row_ptr = 0;

    int pixel_ptr = 0;

    int block_ptr;

    int pixel_x, pixel_y;

    int total_blocks;

    /* First byte is always 0xe1. Warn if it's different */

    if (s->buf[stream_ptr] != 0xe1)

        av_log(s->avctx, AV_LOG_ERROR, "First chunk byte is 0x%02x instead of 0xe1\n",

            s->buf[stream_ptr]);

    /* Get chunk size, ingnoring first byte */

    chunk_size = AV_RB32(&s->buf[stream_ptr]) & 0x00FFFFFF;

    stream_ptr += 4;

    /* If length mismatch use size from MOV file and try to decode anyway */

    if (chunk_size != s->size)

        av_log(s->avctx, AV_LOG_ERROR, "MOV chunk size != encoded chunk size; using MOV chunk size\n");

    chunk_size = s->size;

    /* Number of 4x4 blocks in frame. */

    total_blocks = ((s->avctx->width + 3) / 4) * ((s->avctx->height + 3) / 4);

    /* Process chunk data */

    while (stream_ptr < chunk_size) {

        opcode = s->buf[stream_ptr++]; /* Get opcode */

        n_blocks = (opcode & 0x1f) + 1; /* Extract block counter from opcode */

        /* If opcode MSbit is 0, we need more data to decide what to do */

        if ((opcode & 0x80) == 0) {

            colorA = (opcode << 8) | (s->buf[stream_ptr++]);

            opcode = 0;

            if ((s->buf[stream_ptr] & 0x80) != 0) {

                /* Must behave as opcode 110xxxxx, using colorA computed

                 * above. Use fake opcode 0x20 to enter switch block at

                 * the right place */

                opcode = 0x20;

                n_blocks = 1;

            }

        }

        switch (opcode & 0xe0) {

        /* Skip blocks */

        case 0x80:

            while (n_blocks--) {

              ADVANCE_BLOCK();

            }

            break;

        /* Fill blocks with one color */

        case 0xa0:

            colorA = AV_RB16 (&s->buf[stream_ptr]);

            stream_ptr += 2;

            while (n_blocks--) {

                block_ptr = row_ptr + pixel_ptr;

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

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

                        pixels[block_ptr] = colorA;

                        block_ptr++;

                    }

                    block_ptr += row_inc;

                }

                ADVANCE_BLOCK();

            }

            break;

        /* Fill blocks with 4 colors */

        case 0xc0:

            colorA = AV_RB16 (&s->buf[stream_ptr]);

            stream_ptr += 2;

        case 0x20:

            colorB = AV_RB16 (&s->buf[stream_ptr]);

            stream_ptr += 2;

            /* sort out the colors */

            color4[0] = colorB;

            color4[1] = 0;

            color4[2] = 0;

            color4[3] = colorA;

            /* red components */

            ta = (colorA >> 10) & 0x1F;

            tb = (colorB >> 10) & 0x1F;

            color4[1] |= ((11 * ta + 21 * tb) >> 5) << 10;

            color4[2] |= ((21 * ta + 11 * tb) >> 5) << 10;

            /* green components */

            ta = (colorA >> 5) & 0x1F;

            tb = (colorB >> 5) & 0x1F;

            color4[1] |= ((11 * ta + 21 * tb) >> 5) << 5;

            color4[2] |= ((21 * ta + 11 * tb) >> 5) << 5;

            /* blue components */

            ta = colorA & 0x1F;

            tb = colorB & 0x1F;

            color4[1] |= ((11 * ta + 21 * tb) >> 5);

            color4[2] |= ((21 * ta + 11 * tb) >> 5);

            while (n_blocks--) {

                block_ptr = row_ptr + pixel_ptr;

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

                    index = s->buf[stream_ptr++];

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

                        idx = (index >> (2 * (3 - pixel_x))) & 0x03;

                        pixels[block_ptr] = color4[idx];

                        block_ptr++;

                    }

                    block_ptr += row_inc;

                }

                ADVANCE_BLOCK();

            }

            break;

        /* Fill block with 16 colors */

        case 0x00:

            if (s->size - stream_ptr < 16)

            block_ptr = row_ptr + pixel_ptr;

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

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

                    /* We already have color of upper left pixel */

                    if ((pixel_y != 0) || (pixel_x !=0)) {

                        colorA = AV_RB16 (&s->buf[stream_ptr]);

                        stream_ptr += 2;

                    }

                    pixels[block_ptr] = colorA;

                    block_ptr++;

                }

                block_ptr += row_inc;

            }

            ADVANCE_BLOCK();

            break;

        /* Unknown opcode */

        default:

            av_log(s->avctx, AV_LOG_ERROR, "Unknown opcode %d in rpza chunk."

                 " Skip remaining %d bytes of chunk data.\n", opcode,

                 chunk_size - stream_ptr);

        } /* Opcode switch */

    }

}


static int mlib_YUV2RGB420_24(SwsContext *c, uint8_t* src[], int srcStride[], int srcSliceY,

             int srcSliceH, uint8_t* dst[], int dstStride[]){

    if(c->srcFormat == PIX_FMT_YUV422P){

	srcStride[1] *= 2;

	srcStride[2] *= 2;

    }

    assert(srcStride[1] == srcStride[2]);

    mlib_VideoColorYUV2RGB420(dst[0]+srcSliceY*dstStride[0], src[0], src[1], src[2], c->dstW,

			     srcSliceH, dstStride[0], srcStride[0], srcStride[1]);

    return srcSliceH;

}


uint64_t ldq_tce(VIOsPAPRDevice *dev, uint64_t taddr)

{

    uint64_t val;

    spapr_tce_dma_read(dev, taddr, &val, sizeof(val));

    return tswap64(val);

}


static int raw_reopen_prepare(BDRVReopenState *state,

                              BlockReopenQueue *queue, Error **errp)

{

    BDRVRawState *s;

    BDRVRawReopenState *raw_s;

    int ret = 0;

    Error *local_err = NULL;

    assert(state != NULL);

    assert(state->bs != NULL);

    s = state->bs->opaque;

    state->opaque = g_malloc0(sizeof(BDRVRawReopenState));

    raw_s = state->opaque;

#ifdef CONFIG_LINUX_AIO

    raw_s->use_aio = s->use_aio;

    /* we can use s->aio_ctx instead of a copy, because the use_aio flag is

     * valid in the 'false' condition even if aio_ctx is set, and raw_set_aio()

     * won't override aio_ctx if aio_ctx is non-NULL */

    if (raw_set_aio(&s->aio_ctx, &raw_s->use_aio, state->flags)) {

        error_setg(errp, "Could not set AIO state");

        return -1;

    }

#endif

    if (s->type == FTYPE_FD || s->type == FTYPE_CD) {

        raw_s->open_flags |= O_NONBLOCK;

    }

    raw_parse_flags(state->flags, &raw_s->open_flags);

    raw_s->fd = -1;

    int fcntl_flags = O_APPEND | O_NONBLOCK;

#ifdef O_NOATIME

    fcntl_flags |= O_NOATIME;

#endif

#ifdef O_ASYNC

    /* Not all operating systems have O_ASYNC, and those that don't

     * will not let us track the state into raw_s->open_flags (typically

     * you achieve the same effect with an ioctl, for example I_SETSIG

     * on Solaris). But we do not use O_ASYNC, so that's fine.

     */

    assert((s->open_flags & O_ASYNC) == 0);

#endif

    if ((raw_s->open_flags & ~fcntl_flags) == (s->open_flags & ~fcntl_flags)) {

        /* dup the original fd */

        /* TODO: use qemu fcntl wrapper */

#ifdef F_DUPFD_CLOEXEC

        raw_s->fd = fcntl(s->fd, F_DUPFD_CLOEXEC, 0);

#else

        raw_s->fd = dup(s->fd);

        if (raw_s->fd != -1) {

            qemu_set_cloexec(raw_s->fd);

        }

#endif

        if (raw_s->fd >= 0) {

            ret = fcntl_setfl(raw_s->fd, raw_s->open_flags);

            if (ret) {

                qemu_close(raw_s->fd);

                raw_s->fd = -1;

            }

        }

    }

    /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */

    if (raw_s->fd == -1) {

        assert(!(raw_s->open_flags & O_CREAT));

        raw_s->fd = qemu_open(state->bs->filename, raw_s->open_flags);

        if (raw_s->fd == -1) {

            error_setg_errno(errp, errno, "Could not reopen file");

            ret = -1;

        }

    }

    /* Fail already reopen_prepare() if we can't get a working O_DIRECT

     * alignment with the new fd. */

    if (raw_s->fd != -1) {

        raw_probe_alignment(state->bs, raw_s->fd, &local_err);

        if (local_err) {

            qemu_close(raw_s->fd);

            raw_s->fd = -1;

            error_propagate(errp, local_err);

            ret = -EINVAL;

        }

    }

    return ret;

}


int net_init_dump(QemuOpts *opts, const char *name, VLANState *vlan)

{

    int len;

    const char *file;

    char def_file[128];

    assert(vlan);

    file = qemu_opt_get(opts, "file");

    if (!file) {

        snprintf(def_file, sizeof(def_file), "qemu-vlan%d.pcap", vlan->id);

        file = def_file;

    }

    len = qemu_opt_get_size(opts, "len", 65536);

    return net_dump_init(vlan, "dump", name, file, len);

}


static int blk_free(struct XenDevice *xendev)

{

    struct XenBlkDev *blkdev = container_of(xendev, struct XenBlkDev, xendev);

    struct ioreq *ioreq;

    if (blkdev->blk || blkdev->sring) {

        blk_disconnect(xendev);

    }

    /* Free persistent grants */

    if (blkdev->feature_persistent) {

        g_tree_destroy(blkdev->persistent_gnts);

    }

    while (!QLIST_EMPTY(&blkdev->freelist)) {

        ioreq = QLIST_FIRST(&blkdev->freelist);

        QLIST_REMOVE(ioreq, list);

        qemu_iovec_destroy(&ioreq->v);

        g_free(ioreq);

    }

    g_free(blkdev->params);

    g_free(blkdev->mode);

    g_free(blkdev->type);

    g_free(blkdev->dev);

    g_free(blkdev->devtype);

    qemu_bh_delete(blkdev->bh);

    return 0;

}


static void r2d_init(ram_addr_t ram_size, int vga_ram_size,

              const char *boot_device,

	      const char *kernel_filename, const char *kernel_cmdline,

	      const char *initrd_filename, const char *cpu_model)

{

    CPUState *env;

    struct SH7750State *s;

    ram_addr_t sdram_addr, sm501_vga_ram_addr;

    qemu_irq *irq;

    PCIBus *pci;

    int i;

    if (!cpu_model)

        cpu_model = "SH7751R";

    env = cpu_init(cpu_model);

    if (!env) {

        fprintf(stderr, "Unable to find CPU definition\n");

        exit(1);

    }

    /* Allocate memory space */

    sdram_addr = qemu_ram_alloc(SDRAM_SIZE);

    cpu_register_physical_memory(SDRAM_BASE, SDRAM_SIZE, sdram_addr);

    /* Register peripherals */

    s = sh7750_init(env);

    irq = r2d_fpga_init(0x04000000, sh7750_irl(s));

    pci = sh_pci_register_bus(r2d_pci_set_irq, r2d_pci_map_irq, irq, 0, 4);

    sm501_vga_ram_addr = qemu_ram_alloc(SM501_VRAM_SIZE);

    sm501_init(0x10000000, sm501_vga_ram_addr, SM501_VRAM_SIZE,

	       serial_hds[2]);

    /* onboard CF (True IDE mode, Master only). */

    mmio_ide_init(0x14001000, 0x1400080c, irq[CF_IDE], 1,

        drives_table[drive_get_index(IF_IDE, 0, 0)].bdrv, NULL);

    /* NIC: rtl8139 on-board, and 2 slots. */

    pci_nic_init(pci, &nd_table[0], 2 << 3, "rtl8139");

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

        pci_nic_init(pci, &nd_table[i], -1, "ne2k_pci");

    /* Todo: register on board registers */

    {

      int kernel_size;

      /* initialization which should be done by firmware */

      stl_phys(SH7750_BCR1, 1<<3); /* cs3 SDRAM */

      stw_phys(SH7750_BCR2, 3<<(3*2)); /* cs3 32bit */

      kernel_size = load_image(kernel_filename, phys_ram_base);

      if (kernel_size < 0) {

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

        exit(1);

      }

      env->pc = SDRAM_BASE | 0xa0000000; /* Start from P2 area */

    }

}


MigrationIncomingState *migration_incoming_state_new(QEMUFile* f)

{

    mis_current = g_malloc0(sizeof(MigrationIncomingState));

    mis_current->file = f;

    QLIST_INIT(&mis_current->loadvm_handlers);

    return mis_current;

}


double av_get_double(void *obj, const char *name, const AVOption **o_out)

{

    int64_t intnum=1;

    double num=1;

    int den=1;

    av_get_number(obj, name, o_out, &num, &den, &intnum);

    return num*intnum/den;

}


static void laio_cancel(BlockDriverAIOCB *blockacb)

{

    struct qemu_laiocb *laiocb = (struct qemu_laiocb *)blockacb;

    struct io_event event;

    int ret;

    if (laiocb->ret != -EINPROGRESS)

        return;

    /*

     * Note that as of Linux 2.6.31 neither the block device code nor any

     * filesystem implements cancellation of AIO request.

     * Thus the polling loop below is the normal code path.

     */

    ret = io_cancel(laiocb->ctx->ctx, &laiocb->iocb, &event);

    if (ret == 0) {

        laiocb->ret = -ECANCELED;

        return;

    }

    /*

     * We have to wait for the iocb to finish.

     *

     * The only way to get the iocb status update is by polling the io context.

     * We might be able to do this slightly more optimal by removing the

     * O_NONBLOCK flag.

     */

    while (laiocb->ret == -EINPROGRESS) {

        qemu_laio_completion_cb(&laiocb->ctx->e);

    }

}


static inline void RENAME(yuv2bgr24_1)(SwsContext *c, const uint16_t *buf0,

                                       const uint16_t *ubuf0, const uint16_t *ubuf1,

                                       const uint16_t *vbuf0, const uint16_t *vbuf1,

                                       const uint16_t *abuf0, uint8_t *dest,

                                       int dstW, int uvalpha, enum PixelFormat dstFormat,

                                       int flags, int y)

{

    x86_reg uv_off = c->uv_off << 1;

    const uint16_t *buf1= buf0; //FIXME needed for RGB1/BGR1

    if (uvalpha < 2048) { // note this is not correct (shifts chrominance by 0.5 pixels) but it is a bit faster

        __asm__ volatile(

            "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"

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

            "push %%"REG_BP"                        \n\t"

            YSCALEYUV2RGB1(%%REGBP, %5, %6)

            "pxor    %%mm7, %%mm7                   \n\t"

            WRITEBGR24(%%REGb, 8280(%5), %%REGBP)

            "pop %%"REG_BP"                         \n\t"

            "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"

            :: "c" (buf0), "d" (buf1), "S" (ubuf0), "D" (ubuf1), "m" (dest),

               "a" (&c->redDither), "m"(uv_off)

        );

    } else {

        __asm__ volatile(

            "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"

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

            "push %%"REG_BP"                        \n\t"

            YSCALEYUV2RGB1b(%%REGBP, %5, %6)

            "pxor    %%mm7, %%mm7                   \n\t"

            WRITEBGR24(%%REGb, 8280(%5), %%REGBP)

            "pop %%"REG_BP"                         \n\t"

            "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"

            :: "c" (buf0), "d" (buf1), "S" (ubuf0), "D" (ubuf1), "m" (dest),

               "a" (&c->redDither), "m"(uv_off)

        );

    }

}


static int avi_read_idx1(AVFormatContext *s, int size)

{

    AVIContext *avi = s->priv_data;

    AVIOContext *pb = s->pb;

    int nb_index_entries, i;

    AVStream *st;

    AVIStream *ast;

    unsigned int index, tag, flags, pos, len, first_packet = 1;

    unsigned last_pos= -1;

    int64_t idx1_pos, first_packet_pos = 0, data_offset = 0;

    nb_index_entries = size / 16;

    if (nb_index_entries <= 0)

        return -1;

    idx1_pos = avio_tell(pb);

    avio_seek(pb, avi->movi_list+4, SEEK_SET);

    if (avi_sync(s, 1) == 0) {

        first_packet_pos = avio_tell(pb) - 8;

    }

    avi->stream_index = -1;

    avio_seek(pb, idx1_pos, SEEK_SET);

    /* Read the entries and sort them in each stream component. */

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

        tag = avio_rl32(pb);

        flags = avio_rl32(pb);

        pos = avio_rl32(pb);

        len = avio_rl32(pb);

        av_dlog(s, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",

                i, tag, flags, pos, len);

        index = ((tag & 0xff) - '0') * 10;

        index += ((tag >> 8) & 0xff) - '0';

        if (index >= s->nb_streams)

            continue;

        st = s->streams[index];

        ast = st->priv_data;

        if(first_packet && first_packet_pos && len) {

            data_offset = first_packet_pos - pos;

            first_packet = 0;

        }

        pos += data_offset;

        av_dlog(s, "%d cum_len=%"PRId64"\n", len, ast->cum_len);

        if(url_feof(pb))

            return -1;

        if(last_pos == pos)

            avi->non_interleaved= 1;

        else if(len || !ast->sample_size)

            av_add_index_entry(st, pos, ast->cum_len, len, 0, (flags&AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);

        ast->cum_len += get_duration(ast, len);

        last_pos= pos;

    }

    return 0;

}


static float quantize_band_cost_bits(struct AACEncContext *s, const float *in,

                                     const float *scaled, int size, int scale_idx,

                                     int cb, const float lambda, const float uplim,

                                     int *bits, int rtz)

{

    return get_band_numbits(s, NULL, in, scaled, size, scale_idx, cb, lambda, uplim, bits);

}


static void coroutine_fn stream_run(void *opaque)

{

    StreamBlockJob *s = opaque;

    BlockDriverState *bs = s->common.bs;

    BlockDriverState *base = s->base;

    int64_t sector_num, end;

    int error = 0;

    int ret = 0;

    int n = 0;

    void *buf;

    s->common.len = bdrv_getlength(bs);

    if (s->common.len < 0) {

        block_job_completed(&s->common, s->common.len);

        return;

    }

    end = s->common.len >> BDRV_SECTOR_BITS;

    buf = qemu_blockalign(bs, STREAM_BUFFER_SIZE);

    /* Turn on copy-on-read for the whole block device so that guest read

     * requests help us make progress.  Only do this when copying the entire

     * backing chain since the copy-on-read operation does not take base into

     * account.

     */

    if (!base) {

        bdrv_enable_copy_on_read(bs);

    }

    for (sector_num = 0; sector_num < end; sector_num += n) {

        uint64_t delay_ns = 0;

        bool copy;

wait:

        /* Note that even when no rate limit is applied we need to yield

         * with no pending I/O here so that bdrv_drain_all() returns.

         */

        block_job_sleep_ns(&s->common, QEMU_CLOCK_REALTIME, delay_ns);

        if (block_job_is_cancelled(&s->common)) {

            break;

        }

        ret = bdrv_is_allocated(bs, sector_num,

                                STREAM_BUFFER_SIZE / BDRV_SECTOR_SIZE, &n);

        if (ret == 1) {

            /* Allocated in the top, no need to copy.  */

            copy = false;

        } else if (ret >= 0) {

            /* Copy if allocated in the intermediate images.  Limit to the

             * known-unallocated area [sector_num, sector_num+n).  */

            ret = bdrv_is_allocated_above(bs->backing_hd, base,

                                          sector_num, n, &n);

            /* Finish early if end of backing file has been reached */

            if (ret == 0 && n == 0) {

                n = end - sector_num;

            }

            copy = (ret == 1);

        }

        trace_stream_one_iteration(s, sector_num, n, ret);

        if (ret >= 0 && copy) {

            if (s->common.speed) {

                delay_ns = ratelimit_calculate_delay(&s->limit, n);

                if (delay_ns > 0) {

                    goto wait;

                }

            }

            ret = stream_populate(bs, sector_num, n, buf);

        }

        if (ret < 0) {

            BlockErrorAction action =

                block_job_error_action(&s->common, s->common.bs, s->on_error,

                                       true, -ret);

            if (action == BDRV_ACTION_STOP) {

                n = 0;

                continue;

            }

            if (error == 0) {

                error = ret;

            }

            if (action == BDRV_ACTION_REPORT) {

                break;

            }

        }

        ret = 0;

        /* Publish progress */

        s->common.offset += n * BDRV_SECTOR_SIZE;

    }

    if (!base) {

        bdrv_disable_copy_on_read(bs);

    }

    /* Do not remove the backing file if an error was there but ignored.  */

    ret = error;

    if (!block_job_is_cancelled(&s->common) && sector_num == end && ret == 0) {

        const char *base_id = NULL, *base_fmt = NULL;

        if (base) {

            base_id = s->backing_file_id;

            if (base->drv) {

                base_fmt = base->drv->format_name;

            }

        }

        ret = bdrv_change_backing_file(bs, base_id, base_fmt);

        close_unused_images(bs, base, base_id);

    }

    qemu_vfree(buf);

    block_job_completed(&s->common, ret);

}