START_TEST(escaped_string)

{

    int i;

    struct {

        const char *encoded;

        const char *decoded;

    } test_cases[] = {

        { "\"\\\"\"", "\"" },

        { "\"hello world \\\"embedded string\\\"\"",

          "hello world \"embedded string\"" },

        { "\"hello world\\nwith new line\"", "hello world\nwith new line" },

        { "\"single byte utf-8 \\u0020\"", "single byte utf-8  " },

        { "\"double byte utf-8 \\u00A2\"", "double byte utf-8 \xc2\xa2" },

        { "\"triple byte utf-8 \\u20AC\"", "triple byte utf-8 \xe2\x82\xac" },

        {}

    };

    for (i = 0; test_cases[i].encoded; i++) {

        QObject *obj;

        QString *str;

        obj = qobject_from_json(test_cases[i].encoded);

        fail_unless(obj != NULL);

        fail_unless(qobject_type(obj) == QTYPE_QSTRING);

        str = qobject_to_qstring(obj);

        fail_unless(strcmp(qstring_get_str(str), test_cases[i].decoded) == 0);

        QDECREF(str);

    }

}


static void handle_mrs(DisasContext *s, uint32_t insn, unsigned int op0,

                       unsigned int op1, unsigned int op2,

                       unsigned int crn, unsigned int crm, unsigned int rt)

{

    unsupported_encoding(s, insn);

}


int kvm_irqchip_add_msi_route(KVMState *s, MSIMessage msg)

{

    struct kvm_irq_routing_entry kroute;

    int virq;

    if (!kvm_gsi_routing_enabled()) {

        return -ENOSYS;

    }

    virq = kvm_irqchip_get_virq(s);

    if (virq < 0) {

        return virq;

    }

    kroute.gsi = virq;

    kroute.type = KVM_IRQ_ROUTING_MSI;

    kroute.flags = 0;

    kroute.u.msi.address_lo = (uint32_t)msg.address;

    kroute.u.msi.address_hi = msg.address >> 32;

    kroute.u.msi.data = le32_to_cpu(msg.data);

    kvm_add_routing_entry(s, &kroute);

    kvm_irqchip_commit_routes(s);

    return virq;

}


static int oma_read_header(AVFormatContext *s)

{

    int     ret, framesize, jsflag, samplerate;

    uint32_t codec_params, channel_id;

    int16_t eid;

    uint8_t buf[EA3_HEADER_SIZE];

    uint8_t *edata;

    AVStream *st;

    ID3v2ExtraMeta *extra_meta = NULL;

    OMAContext *oc = s->priv_data;

    ff_id3v2_read(s, ID3v2_EA3_MAGIC, &extra_meta, 0);

    ret = avio_read(s->pb, buf, EA3_HEADER_SIZE);

    if (ret < EA3_HEADER_SIZE)

        return -1;

    if (memcmp(buf, ((const uint8_t[]){'E', 'A', '3'}), 3) ||

        buf[4] != 0 || buf[5] != EA3_HEADER_SIZE) {

        av_log(s, AV_LOG_ERROR, "Couldn't find the EA3 header !\n");

        return AVERROR_INVALIDDATA;

    }

    oc->content_start = avio_tell(s->pb);

    /* encrypted file */

    eid = AV_RB16(&buf[6]);

    if (eid != -1 && eid != -128 && decrypt_init(s, extra_meta, buf) < 0) {

        ff_id3v2_free_extra_meta(&extra_meta);

        return -1;

    }

    ff_id3v2_free_extra_meta(&extra_meta);

    codec_params = AV_RB24(&buf[33]);

    st = avformat_new_stream(s, NULL);

    if (!st)

        return AVERROR(ENOMEM);

    st->start_time = 0;

    st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;

    st->codecpar->codec_tag  = buf[32];

    st->codecpar->codec_id   = ff_codec_get_id(ff_oma_codec_tags,

                                               st->codecpar->codec_tag);

    switch (buf[32]) {

    case OMA_CODECID_ATRAC3:

        samplerate = ff_oma_srate_tab[(codec_params >> 13) & 7] * 100;

        if (!samplerate) {

            av_log(s, AV_LOG_ERROR, "Unsupported sample rate\n");

            return AVERROR_INVALIDDATA;

        }

        if (samplerate != 44100)

            avpriv_request_sample(s, "Sample rate %d", samplerate);

        framesize = (codec_params & 0x3FF) * 8;

        /* get stereo coding mode, 1 for joint-stereo */

        jsflag = (codec_params >> 17) & 1;

        st->codecpar->channels    = 2;

        st->codecpar->channel_layout = AV_CH_LAYOUT_STEREO;

        st->codecpar->sample_rate = samplerate;

        st->codecpar->bit_rate    = st->codecpar->sample_rate * framesize * 8 / 1024;

        /* fake the ATRAC3 extradata

         * (wav format, makes stream copy to wav work) */

        if (ff_alloc_extradata(st->codecpar, 14))

            return AVERROR(ENOMEM);

        edata = st->codecpar->extradata;

        AV_WL16(&edata[0],  1);             // always 1

        AV_WL32(&edata[2],  samplerate);    // samples rate

        AV_WL16(&edata[6],  jsflag);        // coding mode

        AV_WL16(&edata[8],  jsflag);        // coding mode

        AV_WL16(&edata[10], 1);             // always 1

        // AV_WL16(&edata[12], 0);          // always 0

        avpriv_set_pts_info(st, 64, 1, st->codecpar->sample_rate);

        break;

    case OMA_CODECID_ATRAC3P:

        channel_id = (codec_params >> 10) & 7;

        if (!channel_id) {

            av_log(s, AV_LOG_ERROR,

                   "Invalid ATRAC-X channel id: %"PRIu32"\n", channel_id);

            return AVERROR_INVALIDDATA;

        }

        st->codecpar->channel_layout = ff_oma_chid_to_native_layout[channel_id - 1];

        st->codecpar->channels       = ff_oma_chid_to_num_channels[channel_id - 1];

        framesize = ((codec_params & 0x3FF) * 8) + 8;

        samplerate = ff_oma_srate_tab[(codec_params >> 13) & 7] * 100;

        if (!samplerate) {

            av_log(s, AV_LOG_ERROR, "Unsupported sample rate\n");

            return AVERROR_INVALIDDATA;

        }

        st->codecpar->sample_rate = samplerate;

        st->codecpar->bit_rate    = samplerate * framesize * 8 / 2048;

        avpriv_set_pts_info(st, 64, 1, samplerate);

        break;

    case OMA_CODECID_MP3:

        st->need_parsing = AVSTREAM_PARSE_FULL_RAW;

        framesize = 1024;

        break;

    case OMA_CODECID_LPCM:

        /* PCM 44.1 kHz 16 bit stereo big-endian */

        st->codecpar->channels = 2;

        st->codecpar->channel_layout = AV_CH_LAYOUT_STEREO;

        st->codecpar->sample_rate = 44100;

        framesize = 1024;

        /* bit rate = sample rate x PCM block align (= 4) x 8 */

        st->codecpar->bit_rate = st->codecpar->sample_rate * 32;

        st->codecpar->bits_per_coded_sample =

            av_get_bits_per_sample(st->codecpar->codec_id);

        avpriv_set_pts_info(st, 64, 1, st->codecpar->sample_rate);

        break;

    default:

        av_log(s, AV_LOG_ERROR, "Unsupported codec %d!\n", buf[32]);

        return AVERROR(ENOSYS);

    }

    st->codecpar->block_align = framesize;

    return 0;

}


static int temporal_luma_motion_vector(HEVCContext *s, int x0, int y0,

                                       int nPbW, int nPbH, int refIdxLx,

                                       Mv *mvLXCol, int X)

{

    MvField *tab_mvf;

    MvField temp_col;

    int x, y, x_pu, y_pu;

    int min_pu_width = s->sps->min_pu_width;

    int availableFlagLXCol = 0;

    int colPic;

    HEVCFrame *ref = s->ref->collocated_ref;

    if (!ref)

        return 0;

    tab_mvf = ref->tab_mvf;

    colPic  = ref->poc;

    //bottom right collocated motion vector

    x = x0 + nPbW;

    y = y0 + nPbH;

    if (tab_mvf &&

        (y0 >> s->sps->log2_ctb_size) == (y >> s->sps->log2_ctb_size) &&

        y < s->sps->height &&

        x < s->sps->width) {

        x                 &= ~15;

        y                 &= ~15;

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

        x_pu               = x >> s->sps->log2_min_pu_size;

        y_pu               = y >> s->sps->log2_min_pu_size;

        temp_col           = TAB_MVF(x_pu, y_pu);

        availableFlagLXCol = DERIVE_TEMPORAL_COLOCATED_MVS;

    }

    // derive center collocated motion vector

    if (tab_mvf && !availableFlagLXCol) {

        x                  = x0 + (nPbW >> 1);

        y                  = y0 + (nPbH >> 1);

        x                 &= ~15;

        y                 &= ~15;

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

        x_pu               = x >> s->sps->log2_min_pu_size;

        y_pu               = y >> s->sps->log2_min_pu_size;

        temp_col           = TAB_MVF(x_pu, y_pu);

        availableFlagLXCol = DERIVE_TEMPORAL_COLOCATED_MVS;

    }

    return availableFlagLXCol;

}


static int decode_audio_specific_config(AACContext *ac,

                                        AVCodecContext *avctx,

                                        MPEG4AudioConfig *m4ac,

                                        const uint8_t *data, int bit_size,

                                        int sync_extension)

{

    GetBitContext gb;

    int i, ret;

    ff_dlog(avctx, "audio specific config size %d\n", bit_size >> 3);

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

        ff_dlog(avctx, "%02x ", data[i]);

    ff_dlog(avctx, "\n");

    if ((ret = init_get_bits(&gb, data, bit_size)) < 0)

        return ret;

    if ((i = avpriv_mpeg4audio_get_config(m4ac, data, bit_size,

                                          sync_extension)) < 0)

        return AVERROR_INVALIDDATA;

    if (m4ac->sampling_index > 12) {

        av_log(avctx, AV_LOG_ERROR,

               "invalid sampling rate index %d\n",

               m4ac->sampling_index);

        return AVERROR_INVALIDDATA;

    }

    if (m4ac->object_type == AOT_ER_AAC_LD &&

        (m4ac->sampling_index < 3 || m4ac->sampling_index > 7)) {

        av_log(avctx, AV_LOG_ERROR,

               "invalid low delay sampling rate index %d\n",

               m4ac->sampling_index);

        return AVERROR_INVALIDDATA;

    }

    skip_bits_long(&gb, i);

    switch (m4ac->object_type) {

    case AOT_AAC_MAIN:

    case AOT_AAC_LC:

    case AOT_AAC_LTP:

    case AOT_ER_AAC_LC:

    case AOT_ER_AAC_LD:

        if ((ret = decode_ga_specific_config(ac, avctx, &gb,

                                            m4ac, m4ac->chan_config)) < 0)

            return ret;

        break;

    case AOT_ER_AAC_ELD:

        if ((ret = decode_eld_specific_config(ac, avctx, &gb,

                                              m4ac, m4ac->chan_config)) < 0)

            return ret;

        break;

    default:

        avpriv_report_missing_feature(avctx,

                                      "Audio object type %s%d",

                                      m4ac->sbr == 1 ? "SBR+" : "",

                                      m4ac->object_type);

        return AVERROR(ENOSYS);

    }

    ff_dlog(avctx,

            "AOT %d chan config %d sampling index %d (%d) SBR %d PS %d\n",

            m4ac->object_type, m4ac->chan_config, m4ac->sampling_index,

            m4ac->sample_rate, m4ac->sbr,

            m4ac->ps);

    return get_bits_count(&gb);

}


long do_sigreturn(CPUS390XState *env)

{

    sigframe *frame;

    abi_ulong frame_addr = env->regs[15];

    target_sigset_t target_set;

    sigset_t set;

    trace_user_do_sigreturn(env, frame_addr);

    if (!lock_user_struct(VERIFY_READ, frame, frame_addr, 1)) {

        goto badframe;

    }

    __get_user(target_set.sig[0], &frame->sc.oldmask[0]);

    target_to_host_sigset_internal(&set, &target_set);

    set_sigmask(&set); /* ~_BLOCKABLE? */

    if (restore_sigregs(env, &frame->sregs)) {

        goto badframe;

    }

    unlock_user_struct(frame, frame_addr, 0);

    return -TARGET_QEMU_ESIGRETURN;

badframe:

    force_sig(TARGET_SIGSEGV);

    return 0;

}


static inline int get_symbol_inline(RangeCoder *c, uint8_t *state, int is_signed){

    if(get_rac(c, state+0))

        return 0;

    else{

        int i, e, a;

        e= 0;

        while(get_rac(c, state+1 + e) && e<9){ //1..10

            e++;

        }

        a= 1;

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

            a += a + get_rac(c, state+22 + i); //22..31

        }

        e= -(is_signed && get_rac(c, state+11 + e)); //11..21

        return (a^e)-e;

    }

}


START_TEST(qobject_to_qint_test)

{

    QInt *qi;

    qi = qint_from_int(0);

    fail_unless(qobject_to_qint(QOBJECT(qi)) == qi);

    QDECREF(qi);

}


static void tcg_out_label(TCGContext *s, TCGLabel *l, tcg_insn_unit *ptr)

{

    intptr_t value = (intptr_t)ptr;

    TCGRelocation *r;

    assert(!l->has_value);

    for (r = l->u.first_reloc; r != NULL; r = r->next) {

        patch_reloc(r->ptr, r->type, value, r->addend);

    }

    l->has_value = 1;

    l->u.value_ptr = ptr;

}


BlockDriverState *bdrv_lookup_bs(const char *device,

                                 const char *node_name,

                                 Error **errp)

{

    BlockBackend *blk;

    BlockDriverState *bs;

    if (device) {

        blk = blk_by_name(device);

        if (blk) {

            return blk_bs(blk);

        }

    }

    if (node_name) {

        bs = bdrv_find_node(node_name);

        if (bs) {

            return bs;

        }

    }

    error_setg(errp, "Cannot find device=%s nor node_name=%s",

                     device ? device : "",

                     node_name ? node_name : "");

    return NULL;

}


static int idcin_read_packet(AVFormatContext *s,

                             AVPacket *pkt)

{

    int ret;

    unsigned int command;

    unsigned int chunk_size;

    IdcinDemuxContext *idcin = s->priv_data;

    AVIOContext *pb = s->pb;

    int i;

    int palette_scale;

    unsigned char r, g, b;

    unsigned char palette_buffer[768];

    uint32_t palette[256];

    if (s->pb->eof_reached)

        return AVERROR(EIO);

    if (idcin->next_chunk_is_video) {

        command = avio_rl32(pb);

        if (command == 2) {

            return AVERROR(EIO);

        } else if (command == 1) {

            /* trigger a palette change */

            if (avio_read(pb, palette_buffer, 768) != 768)

                return AVERROR(EIO);

            /* scale the palette as necessary */

            palette_scale = 2;

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

                if (palette_buffer[i] > 63) {

                    palette_scale = 0;

                    break;

                }

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

                r = palette_buffer[i * 3    ] << palette_scale;

                g = palette_buffer[i * 3 + 1] << palette_scale;

                b = palette_buffer[i * 3 + 2] << palette_scale;

                palette[i] = (r << 16) | (g << 8) | (b);

            }

        }

        chunk_size = avio_rl32(pb);

        if (chunk_size < 4 || chunk_size > INT_MAX - 4) {

            av_log(s, AV_LOG_ERROR, "invalid chunk size: %u\n", chunk_size);

            return AVERROR_INVALIDDATA;

        }

        /* skip the number of decoded bytes (always equal to width * height) */

        avio_skip(pb, 4);

        chunk_size -= 4;

        ret= av_get_packet(pb, pkt, chunk_size);

        if (ret < 0)

            return ret;

        if (command == 1) {

            uint8_t *pal;

            pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE,

                                          AVPALETTE_SIZE);

            if (ret < 0)

                return ret;

            memcpy(pal, palette, AVPALETTE_SIZE);

            pkt->flags |= AV_PKT_FLAG_KEY;

        }

        pkt->stream_index = idcin->video_stream_index;

        pkt->duration     = 1;

    } else {

        /* send out the audio chunk */

        if (idcin->current_audio_chunk)

            chunk_size = idcin->audio_chunk_size2;

        else

            chunk_size = idcin->audio_chunk_size1;

        ret= av_get_packet(pb, pkt, chunk_size);

        if (ret < 0)

            return ret;

        pkt->stream_index = idcin->audio_stream_index;

        pkt->duration     = chunk_size / idcin->block_align;

        idcin->current_audio_chunk ^= 1;

    }

    if (idcin->audio_present)

        idcin->next_chunk_is_video ^= 1;

    return ret;

}


void avcodec_register_all(void)

{

    static int initialized;

    if (initialized)

        return;

    initialized = 1;

    /* hardware accelerators */

    REGISTER_HWACCEL(H263_VAAPI,        h263_vaapi);

    REGISTER_HWACCEL(H264_D3D11VA,      h264_d3d11va);

    REGISTER_HWACCEL(H264_DXVA2,        h264_dxva2);

    REGISTER_HWACCEL(H264_MMAL,         h264_mmal);

    REGISTER_HWACCEL(H264_QSV,          h264_qsv);

    REGISTER_HWACCEL(H264_VAAPI,        h264_vaapi);

    REGISTER_HWACCEL(H264_VDA,          h264_vda);

    REGISTER_HWACCEL(H264_VDA_OLD,      h264_vda_old);

    REGISTER_HWACCEL(H264_VDPAU,        h264_vdpau);

    REGISTER_HWACCEL(HEVC_D3D11VA,      hevc_d3d11va);

    REGISTER_HWACCEL(HEVC_DXVA2,        hevc_dxva2);

    REGISTER_HWACCEL(HEVC_QSV,          hevc_qsv);

    REGISTER_HWACCEL(HEVC_VAAPI,        hevc_vaapi);

    REGISTER_HWACCEL(HEVC_VDPAU,        hevc_vdpau);

    REGISTER_HWACCEL(MPEG1_VDPAU,       mpeg1_vdpau);

    REGISTER_HWACCEL(MPEG2_D3D11VA,     mpeg2_d3d11va);

    REGISTER_HWACCEL(MPEG2_DXVA2,       mpeg2_dxva2);

    REGISTER_HWACCEL(MPEG2_MMAL,        mpeg2_mmal);

    REGISTER_HWACCEL(MPEG2_QSV,         mpeg2_qsv);

    REGISTER_HWACCEL(MPEG2_VAAPI,       mpeg2_vaapi);

    REGISTER_HWACCEL(MPEG2_VDPAU,       mpeg2_vdpau);

    REGISTER_HWACCEL(MPEG4_VAAPI,       mpeg4_vaapi);

    REGISTER_HWACCEL(MPEG4_VDPAU,       mpeg4_vdpau);

    REGISTER_HWACCEL(VC1_D3D11VA,       vc1_d3d11va);

    REGISTER_HWACCEL(VC1_DXVA2,         vc1_dxva2);

    REGISTER_HWACCEL(VC1_QSV,           vc1_qsv);

    REGISTER_HWACCEL(VC1_VAAPI,         vc1_vaapi);

    REGISTER_HWACCEL(VC1_VDPAU,         vc1_vdpau);

    REGISTER_HWACCEL(VC1_MMAL,          vc1_mmal);

    REGISTER_HWACCEL(VP8_QSV,           vp8_qsv);

    REGISTER_HWACCEL(VP8_VAAPI,         vp8_vaapi);

    REGISTER_HWACCEL(WMV3_D3D11VA,      wmv3_d3d11va);

    REGISTER_HWACCEL(WMV3_DXVA2,        wmv3_dxva2);

    REGISTER_HWACCEL(WMV3_VAAPI,        wmv3_vaapi);

    REGISTER_HWACCEL(WMV3_VDPAU,        wmv3_vdpau);

    /* video codecs */

    REGISTER_ENCODER(A64MULTI,          a64multi);

    REGISTER_ENCODER(A64MULTI5,         a64multi5);

    REGISTER_DECODER(AASC,              aasc);

    REGISTER_DECODER(AIC,               aic);

    REGISTER_ENCDEC (ALIAS_PIX,         alias_pix);

    REGISTER_DECODER(AMV,               amv);

    REGISTER_DECODER(ANM,               anm);

    REGISTER_DECODER(ANSI,              ansi);

    REGISTER_ENCDEC (ASV1,              asv1);

    REGISTER_ENCDEC (ASV2,              asv2);

    REGISTER_DECODER(AURA,              aura);

    REGISTER_DECODER(AURA2,             aura2);

    REGISTER_DECODER(AVS,               avs);

    REGISTER_DECODER(BETHSOFTVID,       bethsoftvid);

    REGISTER_DECODER(BFI,               bfi);

    REGISTER_DECODER(BINK,              bink);

    REGISTER_ENCDEC (BMP,               bmp);

    REGISTER_DECODER(BMV_VIDEO,         bmv_video);

    REGISTER_DECODER(BRENDER_PIX,       brender_pix);

    REGISTER_DECODER(C93,               c93);

    REGISTER_DECODER(CAVS,              cavs);

    REGISTER_DECODER(CDGRAPHICS,        cdgraphics);

    REGISTER_DECODER(CDXL,              cdxl);

    REGISTER_DECODER(CFHD,              cfhd);

    REGISTER_DECODER(CINEPAK,           cinepak);

    REGISTER_ENCDEC (CLJR,              cljr);

    REGISTER_DECODER(CLLC,              cllc);

    REGISTER_ENCDEC (COMFORTNOISE,      comfortnoise);

    REGISTER_DECODER(CSCD,              cscd);

    REGISTER_DECODER(CYUV,              cyuv);

    REGISTER_DECODER(DDS,               dds);

    REGISTER_DECODER(DFA,               dfa);

    REGISTER_ENCDEC (DNXHD,             dnxhd);

    REGISTER_ENCDEC (DPX,               dpx);

    REGISTER_DECODER(DSICINVIDEO,       dsicinvideo);

    REGISTER_ENCDEC (DVVIDEO,           dvvideo);

    REGISTER_DECODER(DXA,               dxa);

    REGISTER_DECODER(DXTORY,            dxtory);

    REGISTER_DECODER(DXV,               dxv);

    REGISTER_DECODER(EACMV,             eacmv);

    REGISTER_DECODER(EAMAD,             eamad);

    REGISTER_DECODER(EATGQ,             eatgq);

    REGISTER_DECODER(EATGV,             eatgv);

    REGISTER_DECODER(EATQI,             eatqi);

    REGISTER_DECODER(EIGHTBPS,          eightbps);

    REGISTER_DECODER(EIGHTSVX_EXP,      eightsvx_exp);

    REGISTER_DECODER(EIGHTSVX_FIB,      eightsvx_fib);

    REGISTER_DECODER(ESCAPE124,         escape124);

    REGISTER_DECODER(ESCAPE130,         escape130);

    REGISTER_DECODER(EXR,               exr);

    REGISTER_ENCDEC (FFV1,              ffv1);

    REGISTER_ENCDEC (FFVHUFF,           ffvhuff);

    REGISTER_DECODER(FIC,               fic);

    REGISTER_ENCDEC (FLASHSV,           flashsv);

    REGISTER_DECODER(FLASHSV2,          flashsv2);

    REGISTER_DECODER(FLIC,              flic);

    REGISTER_ENCDEC (FLV,               flv);

    REGISTER_DECODER(FOURXM,            fourxm);

    REGISTER_DECODER(FRAPS,             fraps);

    REGISTER_DECODER(FRWU,              frwu);

    REGISTER_DECODER(G2M,               g2m);

    REGISTER_ENCDEC (GIF,               gif);

    REGISTER_ENCDEC (H261,              h261);

    REGISTER_ENCDEC (H263,              h263);

    REGISTER_DECODER(H263I,             h263i);

    REGISTER_ENCODER(H263P,             h263p);

    REGISTER_DECODER(H264,              h264);

    REGISTER_DECODER(H264_MMAL,         h264_mmal);

    REGISTER_DECODER(H264_QSV,          h264_qsv);

    REGISTER_ENCDEC (HAP,               hap);

    REGISTER_DECODER(HEVC,              hevc);

    REGISTER_DECODER(HEVC_QSV,          hevc_qsv);

    REGISTER_DECODER(HNM4_VIDEO,        hnm4_video);

    REGISTER_DECODER(HQ_HQA,            hq_hqa);

    REGISTER_DECODER(HQX,               hqx);

    REGISTER_ENCDEC (HUFFYUV,           huffyuv);

    REGISTER_DECODER(IDCIN,             idcin);

    REGISTER_DECODER(IFF_BYTERUN1,      iff_byterun1);

    REGISTER_DECODER(IFF_ILBM,          iff_ilbm);

    REGISTER_DECODER(INDEO2,            indeo2);

    REGISTER_DECODER(INDEO3,            indeo3);

    REGISTER_DECODER(INDEO4,            indeo4);

    REGISTER_DECODER(INDEO5,            indeo5);

    REGISTER_DECODER(INTERPLAY_VIDEO,   interplay_video);

    REGISTER_DECODER(JPEG2000,          jpeg2000);

    REGISTER_ENCDEC (JPEGLS,            jpegls);

    REGISTER_DECODER(JV,                jv);

    REGISTER_DECODER(KGV1,              kgv1);

    REGISTER_DECODER(KMVC,              kmvc);

    REGISTER_DECODER(LAGARITH,          lagarith);

    REGISTER_ENCODER(LJPEG,             ljpeg);

    REGISTER_DECODER(LOCO,              loco);

    REGISTER_DECODER(MAGICYUV,          magicyuv);

    REGISTER_DECODER(MDEC,              mdec);

    REGISTER_DECODER(MIMIC,             mimic);

    REGISTER_ENCDEC (MJPEG,             mjpeg);

    REGISTER_DECODER(MJPEGB,            mjpegb);

    REGISTER_DECODER(MMVIDEO,           mmvideo);

    REGISTER_DECODER(MOTIONPIXELS,      motionpixels);

#if FF_API_XVMC

    REGISTER_DECODER(MPEG_XVMC,         mpeg_xvmc);

#endif /* FF_API_XVMC */

    REGISTER_ENCDEC (MPEG1VIDEO,        mpeg1video);

    REGISTER_ENCDEC (MPEG2VIDEO,        mpeg2video);

    REGISTER_DECODER(MPEG2_MMAL,        mpeg2_mmal);

    REGISTER_DECODER(MPEG2_QSV,         mpeg2_qsv);

    REGISTER_ENCDEC (MPEG4,             mpeg4);

    REGISTER_DECODER(MSA1,              msa1);

    REGISTER_DECODER(MSMPEG4V1,         msmpeg4v1);

    REGISTER_ENCDEC (MSMPEG4V2,         msmpeg4v2);

    REGISTER_ENCDEC (MSMPEG4V3,         msmpeg4v3);

    REGISTER_DECODER(MSRLE,             msrle);

    REGISTER_DECODER(MSS1,              mss1);

    REGISTER_DECODER(MSS2,              mss2);

    REGISTER_DECODER(MSVIDEO1,          msvideo1);

    REGISTER_DECODER(MSZH,              mszh);

    REGISTER_DECODER(MTS2,              mts2);

    REGISTER_DECODER(MVC1,              mvc1);

    REGISTER_DECODER(MVC2,              mvc2);

    REGISTER_DECODER(MXPEG,             mxpeg);

    REGISTER_DECODER(NUV,               nuv);

    REGISTER_DECODER(PAF_VIDEO,         paf_video);

    REGISTER_ENCDEC (PAM,               pam);

    REGISTER_ENCDEC (PBM,               pbm);

    REGISTER_ENCDEC (PCX,               pcx);

    REGISTER_ENCDEC (PGM,               pgm);

    REGISTER_ENCDEC (PGMYUV,            pgmyuv);

    REGISTER_DECODER(PICTOR,            pictor);

    REGISTER_DECODER(PIXLET,            pixlet);

    REGISTER_ENCDEC (PNG,               png);

    REGISTER_ENCDEC (PPM,               ppm);

    REGISTER_ENCDEC (PRORES,            prores);

    REGISTER_DECODER(PTX,               ptx);

    REGISTER_DECODER(QDRAW,             qdraw);

    REGISTER_DECODER(QPEG,              qpeg);

    REGISTER_ENCDEC (QTRLE,             qtrle);

    REGISTER_DECODER(R10K,              r10k);

    REGISTER_DECODER(R210,              r210);

    REGISTER_ENCDEC (RAWVIDEO,          rawvideo);

    REGISTER_DECODER(RL2,               rl2);

    REGISTER_ENCDEC (ROQ,               roq);

    REGISTER_DECODER(RPZA,              rpza);

    REGISTER_DECODER(RSCC,              rscc);

    REGISTER_ENCDEC (RV10,              rv10);

    REGISTER_ENCDEC (RV20,              rv20);

    REGISTER_DECODER(RV30,              rv30);

    REGISTER_DECODER(RV40,              rv40);

    REGISTER_DECODER(S302M,             s302m);

    REGISTER_DECODER(SANM,              sanm);

    REGISTER_DECODER(SCREENPRESSO,      screenpresso);

    REGISTER_ENCDEC (SGI,               sgi);

    REGISTER_DECODER(SGIRLE,            sgirle);

    REGISTER_DECODER(SMACKER,           smacker);

    REGISTER_DECODER(SMC,               smc);

    REGISTER_DECODER(SP5X,              sp5x);

    REGISTER_ENCDEC (SUNRAST,           sunrast);

    REGISTER_ENCDEC (SVQ1,              svq1);

    REGISTER_DECODER(SVQ3,              svq3);

    REGISTER_ENCDEC (TARGA,             targa);

    REGISTER_DECODER(TDSC,              tdsc);

    REGISTER_DECODER(THEORA,            theora);

    REGISTER_DECODER(THP,               thp);

    REGISTER_DECODER(TIERTEXSEQVIDEO,   tiertexseqvideo);

    REGISTER_ENCDEC (TIFF,              tiff);

    REGISTER_DECODER(TMV,               tmv);

    REGISTER_DECODER(TRUEMOTION1,       truemotion1);

    REGISTER_DECODER(TRUEMOTION2,       truemotion2);

    REGISTER_DECODER(TRUEMOTION2RT,     truemotion2rt);

    REGISTER_DECODER(TSCC,              tscc);

    REGISTER_DECODER(TSCC2,             tscc2);

    REGISTER_DECODER(TXD,               txd);

    REGISTER_DECODER(ULTI,              ulti);

    REGISTER_ENCDEC (UTVIDEO,           utvideo);

    REGISTER_ENCDEC (V210,              v210);

    REGISTER_DECODER(V210X,             v210x);

    REGISTER_ENCDEC (V410,              v410);

    REGISTER_DECODER(VB,                vb);

    REGISTER_DECODER(VBLE,              vble);

    REGISTER_DECODER(VC1,               vc1);

    REGISTER_DECODER(VC1IMAGE,          vc1image);

    REGISTER_DECODER(VC1_MMAL,          vc1_mmal);

    REGISTER_DECODER(VC1_QSV,           vc1_qsv);

    REGISTER_DECODER(VCR1,              vcr1);

    REGISTER_DECODER(VMDVIDEO,          vmdvideo);

    REGISTER_DECODER(VMNC,              vmnc);

    REGISTER_DECODER(VP3,               vp3);

    REGISTER_DECODER(VP5,               vp5);

    REGISTER_DECODER(VP6,               vp6);

    REGISTER_DECODER(VP6A,              vp6a);

    REGISTER_DECODER(VP6F,              vp6f);

    REGISTER_DECODER(VP7,               vp7);

    REGISTER_DECODER(VP8,               vp8);

    REGISTER_DECODER(VP8_QSV,           vp8_qsv);

    REGISTER_DECODER(VP9,               vp9);

    REGISTER_DECODER(VQA,               vqa);

    REGISTER_DECODER(WEBP,              webp);

    REGISTER_ENCODER(WRAPPED_AVFRAME,   wrapped_avframe);

    REGISTER_ENCDEC (WMV1,              wmv1);

    REGISTER_ENCDEC (WMV2,              wmv2);

    REGISTER_DECODER(WMV3,              wmv3);

    REGISTER_DECODER(WMV3IMAGE,         wmv3image);

    REGISTER_DECODER(WNV1,              wnv1);

    REGISTER_DECODER(XAN_WC3,           xan_wc3);

    REGISTER_DECODER(XAN_WC4,           xan_wc4);

    REGISTER_ENCDEC (XBM,               xbm);

    REGISTER_DECODER(XL,                xl);

    REGISTER_ENCDEC (XWD,               xwd);

    REGISTER_DECODER(YOP,               yop);

    REGISTER_DECODER(ZEROCODEC,         zerocodec);

    REGISTER_ENCDEC (ZLIB,              zlib);

    REGISTER_ENCDEC (ZMBV,              zmbv);

    /* audio codecs */

    REGISTER_ENCDEC (AAC,               aac);

    REGISTER_DECODER(AAC_LATM,          aac_latm);

    REGISTER_ENCDEC (AC3,               ac3);

    REGISTER_ENCODER(AC3_FIXED,         ac3_fixed);

    REGISTER_ENCDEC (ALAC,              alac);

    REGISTER_DECODER(ALS,               als);

    REGISTER_DECODER(AMRNB,             amrnb);

    REGISTER_DECODER(AMRWB,             amrwb);

    REGISTER_DECODER(APE,               ape);

    REGISTER_DECODER(ATRAC1,            atrac1);

    REGISTER_DECODER(ATRAC3,            atrac3);

    REGISTER_DECODER(ATRAC3P,           atrac3p);

    REGISTER_DECODER(BINKAUDIO_DCT,     binkaudio_dct);

    REGISTER_DECODER(BINKAUDIO_RDFT,    binkaudio_rdft);

    REGISTER_DECODER(BMV_AUDIO,         bmv_audio);

    REGISTER_DECODER(COOK,              cook);

    REGISTER_DECODER(DCA,               dca);

    REGISTER_DECODER(DSICINAUDIO,       dsicinaudio);

    REGISTER_DECODER(DSS_SP,            dss_sp);

    REGISTER_ENCDEC (EAC3,              eac3);

    REGISTER_ENCDEC (FLAC,              flac);

    REGISTER_ENCDEC (G723_1,            g723_1);

    REGISTER_DECODER(GSM,               gsm);

    REGISTER_DECODER(GSM_MS,            gsm_ms);

    REGISTER_DECODER(IAC,               iac);

    REGISTER_DECODER(IMC,               imc);

    REGISTER_DECODER(MACE3,             mace3);

    REGISTER_DECODER(MACE6,             mace6);

    REGISTER_DECODER(METASOUND,         metasound);

    REGISTER_DECODER(MLP,               mlp);

    REGISTER_DECODER(MP1,               mp1);

    REGISTER_DECODER(MP1FLOAT,          mp1float);

    REGISTER_ENCDEC (MP2,               mp2);

    REGISTER_DECODER(MP2FLOAT,          mp2float);

    REGISTER_DECODER(MP3,               mp3);

    REGISTER_DECODER(MP3FLOAT,          mp3float);

    REGISTER_DECODER(MP3ADU,            mp3adu);

    REGISTER_DECODER(MP3ADUFLOAT,       mp3adufloat);

    REGISTER_DECODER(MP3ON4,            mp3on4);

    REGISTER_DECODER(MP3ON4FLOAT,       mp3on4float);

    REGISTER_DECODER(MPC7,              mpc7);

    REGISTER_DECODER(MPC8,              mpc8);

    REGISTER_ENCDEC (NELLYMOSER,        nellymoser);

    REGISTER_DECODER(ON2AVC,            on2avc);

    REGISTER_DECODER(OPUS,              opus);

    REGISTER_DECODER(PAF_AUDIO,         paf_audio);

    REGISTER_DECODER(QCELP,             qcelp);

    REGISTER_DECODER(QDM2,              qdm2);

    REGISTER_ENCDEC (RA_144,            ra_144);

    REGISTER_DECODER(RA_288,            ra_288);

    REGISTER_DECODER(RALF,              ralf);

    REGISTER_DECODER(SHORTEN,           shorten);

    REGISTER_DECODER(SIPR,              sipr);

    REGISTER_DECODER(SMACKAUD,          smackaud);

    REGISTER_DECODER(TAK,               tak);

    REGISTER_DECODER(TRUEHD,            truehd);

    REGISTER_DECODER(TRUESPEECH,        truespeech);

    REGISTER_DECODER(TTA,               tta);

    REGISTER_DECODER(TWINVQ,            twinvq);

    REGISTER_DECODER(VMDAUDIO,          vmdaudio);

    REGISTER_ENCDEC (VORBIS,            vorbis);

    REGISTER_DECODER(WAVPACK,           wavpack);

    REGISTER_DECODER(WMALOSSLESS,       wmalossless);

    REGISTER_DECODER(WMAPRO,            wmapro);

    REGISTER_ENCDEC (WMAV1,             wmav1);

    REGISTER_ENCDEC (WMAV2,             wmav2);

    REGISTER_DECODER(WMAVOICE,          wmavoice);

    REGISTER_DECODER(WS_SND1,           ws_snd1);

    /* PCM codecs */

    REGISTER_ENCDEC (PCM_ALAW,          pcm_alaw);

    REGISTER_DECODER(PCM_BLURAY,        pcm_bluray);

    REGISTER_DECODER(PCM_DVD,           pcm_dvd);

    REGISTER_ENCDEC (PCM_F32BE,         pcm_f32be);

    REGISTER_ENCDEC (PCM_F32LE,         pcm_f32le);

    REGISTER_ENCDEC (PCM_F64BE,         pcm_f64be);

    REGISTER_ENCDEC (PCM_F64LE,         pcm_f64le);

    REGISTER_DECODER(PCM_LXF,           pcm_lxf);

    REGISTER_ENCDEC (PCM_MULAW,         pcm_mulaw);

    REGISTER_ENCDEC (PCM_S8,            pcm_s8);

    REGISTER_DECODER(PCM_S8_PLANAR,     pcm_s8_planar);

    REGISTER_ENCDEC (PCM_S16BE,         pcm_s16be);

    REGISTER_DECODER(PCM_S16BE_PLANAR,  pcm_s16be_planar);

    REGISTER_ENCDEC (PCM_S16LE,         pcm_s16le);

    REGISTER_DECODER(PCM_S16LE_PLANAR,  pcm_s16le_planar);

    REGISTER_ENCDEC (PCM_S24BE,         pcm_s24be);

    REGISTER_ENCDEC (PCM_S24DAUD,       pcm_s24daud);

    REGISTER_ENCDEC (PCM_S24LE,         pcm_s24le);

    REGISTER_DECODER(PCM_S24LE_PLANAR,  pcm_s24le_planar);

    REGISTER_ENCDEC (PCM_S32BE,         pcm_s32be);

    REGISTER_ENCDEC (PCM_S32LE,         pcm_s32le);

    REGISTER_DECODER(PCM_S32LE_PLANAR,  pcm_s32le_planar);

    REGISTER_ENCDEC (PCM_U8,            pcm_u8);

    REGISTER_ENCDEC (PCM_U16BE,         pcm_u16be);

    REGISTER_ENCDEC (PCM_U16LE,         pcm_u16le);

    REGISTER_ENCDEC (PCM_U24BE,         pcm_u24be);

    REGISTER_ENCDEC (PCM_U24LE,         pcm_u24le);

    REGISTER_ENCDEC (PCM_U32BE,         pcm_u32be);

    REGISTER_ENCDEC (PCM_U32LE,         pcm_u32le);

    REGISTER_DECODER(PCM_ZORK ,         pcm_zork);

    /* DPCM codecs */

    REGISTER_DECODER(INTERPLAY_DPCM,    interplay_dpcm);

    REGISTER_ENCDEC (ROQ_DPCM,          roq_dpcm);

    REGISTER_DECODER(SOL_DPCM,          sol_dpcm);

    REGISTER_DECODER(XAN_DPCM,          xan_dpcm);

    /* ADPCM codecs */

    REGISTER_DECODER(ADPCM_4XM,         adpcm_4xm);

    REGISTER_ENCDEC (ADPCM_ADX,         adpcm_adx);

    REGISTER_DECODER(ADPCM_CT,          adpcm_ct);

    REGISTER_DECODER(ADPCM_EA,          adpcm_ea);

    REGISTER_DECODER(ADPCM_EA_MAXIS_XA, adpcm_ea_maxis_xa);

    REGISTER_DECODER(ADPCM_EA_R1,       adpcm_ea_r1);

    REGISTER_DECODER(ADPCM_EA_R2,       adpcm_ea_r2);

    REGISTER_DECODER(ADPCM_EA_R3,       adpcm_ea_r3);

    REGISTER_DECODER(ADPCM_EA_XAS,      adpcm_ea_xas);

    REGISTER_ENCDEC (ADPCM_G722,        adpcm_g722);

    REGISTER_ENCDEC (ADPCM_G726,        adpcm_g726);

    REGISTER_DECODER(ADPCM_IMA_AMV,     adpcm_ima_amv);

    REGISTER_DECODER(ADPCM_IMA_APC,     adpcm_ima_apc);

    REGISTER_DECODER(ADPCM_IMA_DK3,     adpcm_ima_dk3);

    REGISTER_DECODER(ADPCM_IMA_DK4,     adpcm_ima_dk4);

    REGISTER_DECODER(ADPCM_IMA_EA_EACS, adpcm_ima_ea_eacs);

    REGISTER_DECODER(ADPCM_IMA_EA_SEAD, adpcm_ima_ea_sead);

    REGISTER_DECODER(ADPCM_IMA_ISS,     adpcm_ima_iss);

    REGISTER_ENCDEC (ADPCM_IMA_QT,      adpcm_ima_qt);

    REGISTER_DECODER(ADPCM_IMA_SMJPEG,  adpcm_ima_smjpeg);

    REGISTER_ENCDEC (ADPCM_IMA_WAV,     adpcm_ima_wav);

    REGISTER_DECODER(ADPCM_IMA_WS,      adpcm_ima_ws);

    REGISTER_ENCDEC (ADPCM_MS,          adpcm_ms);

    REGISTER_DECODER(ADPCM_SBPRO_2,     adpcm_sbpro_2);

    REGISTER_DECODER(ADPCM_SBPRO_3,     adpcm_sbpro_3);

    REGISTER_DECODER(ADPCM_SBPRO_4,     adpcm_sbpro_4);

    REGISTER_ENCDEC (ADPCM_SWF,         adpcm_swf);

    REGISTER_DECODER(ADPCM_THP,         adpcm_thp);

    REGISTER_DECODER(ADPCM_VIMA,        adpcm_vima);

    REGISTER_DECODER(ADPCM_XA,          adpcm_xa);

    REGISTER_ENCDEC (ADPCM_YAMAHA,      adpcm_yamaha);

    /* subtitles */

    REGISTER_ENCDEC (ASS,               ass);

    REGISTER_ENCDEC (DVBSUB,            dvbsub);

    REGISTER_ENCDEC (DVDSUB,            dvdsub);

    REGISTER_DECODER(PGSSUB,            pgssub);

    REGISTER_DECODER(SRT,               srt);

    REGISTER_ENCDEC (XSUB,              xsub);

    /* external libraries */

    REGISTER_DECODER(LIBDCADEC,         libdcadec)

    REGISTER_ENCODER(LIBFAAC,           libfaac);

    REGISTER_ENCDEC (LIBFDK_AAC,        libfdk_aac);

    REGISTER_ENCDEC (LIBGSM,            libgsm);

    REGISTER_ENCDEC (LIBGSM_MS,         libgsm_ms);

    REGISTER_ENCDEC (LIBILBC,           libilbc);

    REGISTER_ENCODER(LIBMP3LAME,        libmp3lame);

    REGISTER_ENCDEC (LIBOPENCORE_AMRNB, libopencore_amrnb);

    REGISTER_DECODER(LIBOPENCORE_AMRWB, libopencore_amrwb);

    REGISTER_ENCDEC (LIBOPENJPEG,       libopenjpeg);

    REGISTER_ENCDEC (LIBOPUS,           libopus);

    REGISTER_ENCDEC (LIBSCHROEDINGER,   libschroedinger);

    REGISTER_ENCDEC (LIBSPEEX,          libspeex);

    REGISTER_ENCODER(LIBTHEORA,         libtheora);

    REGISTER_ENCODER(LIBTWOLAME,        libtwolame);

    REGISTER_ENCODER(LIBVO_AACENC,      libvo_aacenc);

    REGISTER_ENCODER(LIBVO_AMRWBENC,    libvo_amrwbenc);

    REGISTER_ENCODER(LIBVORBIS,         libvorbis);

    REGISTER_ENCDEC (LIBVPX_VP8,        libvpx_vp8);

    REGISTER_ENCDEC (LIBVPX_VP9,        libvpx_vp9);

    REGISTER_ENCODER(LIBWAVPACK,        libwavpack);

    REGISTER_ENCODER(LIBWEBP,           libwebp);

    REGISTER_ENCODER(LIBX262,           libx262);

    REGISTER_ENCODER(LIBX264,           libx264);

    REGISTER_ENCODER(LIBX265,           libx265);

    REGISTER_ENCODER(LIBXAVS,           libxavs);

    REGISTER_ENCODER(LIBXVID,           libxvid);

    /* external libraries, that shouldn't be used by default if one of the

     * above is available */

    REGISTER_ENCDEC (LIBOPENH264,       libopenh264);

    REGISTER_ENCODER(H264_NVENC,        h264_nvenc);

    REGISTER_ENCODER(H264_OMX,          h264_omx);

    REGISTER_ENCODER(H264_QSV,          h264_qsv);

    REGISTER_ENCODER(H264_VAAPI,        h264_vaapi);

    REGISTER_ENCODER(LIBKVAZAAR,        libkvazaar);

    REGISTER_ENCODER(HEVC_NVENC,        hevc_nvenc);

    REGISTER_ENCODER(HEVC_QSV,          hevc_qsv);

    REGISTER_ENCODER(HEVC_VAAPI,        hevc_vaapi);

    REGISTER_ENCODER(MJPEG_VAAPI,       mjpeg_vaapi);

    REGISTER_ENCODER(MPEG2_QSV,         mpeg2_qsv);

    REGISTER_ENCODER(MPEG2_VAAPI,       mpeg2_vaapi);

    REGISTER_ENCODER(MPEG4_OMX,         mpeg4_omx);

#if FF_API_NVENC_OLD_NAME

    REGISTER_ENCODER(NVENC_H264,        nvenc_h264);

    REGISTER_ENCODER(NVENC_HEVC,        nvenc_hevc);

#endif

    REGISTER_ENCODER(VP8_VAAPI,         vp8_vaapi);

    /* parsers */

    REGISTER_PARSER(AAC,                aac);

    REGISTER_PARSER(AAC_LATM,           aac_latm);

    REGISTER_PARSER(AC3,                ac3);

    REGISTER_PARSER(ADX,                adx);

    REGISTER_PARSER(BMP,                bmp);

    REGISTER_PARSER(CAVSVIDEO,          cavsvideo);

    REGISTER_PARSER(COOK,               cook);

    REGISTER_PARSER(DCA,                dca);

    REGISTER_PARSER(DIRAC,              dirac);

    REGISTER_PARSER(DNXHD,              dnxhd);

    REGISTER_PARSER(DPX,                dpx);

    REGISTER_PARSER(DVBSUB,             dvbsub);

    REGISTER_PARSER(DVDSUB,             dvdsub);

    REGISTER_PARSER(FLAC,               flac);

    REGISTER_PARSER(GSM,                gsm);

    REGISTER_PARSER(H261,               h261);

    REGISTER_PARSER(H263,               h263);

    REGISTER_PARSER(H264,               h264);

    REGISTER_PARSER(HEVC,               hevc);

    REGISTER_PARSER(MJPEG,              mjpeg);

    REGISTER_PARSER(MLP,                mlp);

    REGISTER_PARSER(MPEG4VIDEO,         mpeg4video);

    REGISTER_PARSER(MPEGAUDIO,          mpegaudio);

    REGISTER_PARSER(MPEGVIDEO,          mpegvideo);

    REGISTER_PARSER(OPUS,               opus);

    REGISTER_PARSER(PNG,                png);

    REGISTER_PARSER(PNM,                pnm);

    REGISTER_PARSER(RV30,               rv30);

    REGISTER_PARSER(RV40,               rv40);

    REGISTER_PARSER(TAK,                tak);

    REGISTER_PARSER(VC1,                vc1);

    REGISTER_PARSER(VORBIS,             vorbis);

    REGISTER_PARSER(VP3,                vp3);

    REGISTER_PARSER(VP8,                vp8);

}


int ff_audio_convert(AudioConvert *ac, AudioData *out, AudioData *in)

{

    int use_generic = 1;

    int len         = in->nb_samples;

    int p;

    if (ac->dc) {

        /* dithered conversion */

        av_dlog(ac->avr, "%d samples - audio_convert: %s to %s (dithered)\n",

                len, av_get_sample_fmt_name(ac->in_fmt),

                av_get_sample_fmt_name(ac->out_fmt));

        return ff_convert_dither(ac->dc, out, in);

    }

    /* determine whether to use the optimized function based on pointer and

       samples alignment in both the input and output */

    if (ac->has_optimized_func) {

        int ptr_align     = FFMIN(in->ptr_align,     out->ptr_align);

        int samples_align = FFMIN(in->samples_align, out->samples_align);

        int aligned_len   = FFALIGN(len, ac->samples_align);

        if (!(ptr_align % ac->ptr_align) && samples_align >= aligned_len) {

            len = aligned_len;

            use_generic = 0;

        }

    }

    av_dlog(ac->avr, "%d samples - audio_convert: %s to %s (%s)\n", len,

            av_get_sample_fmt_name(ac->in_fmt),

            av_get_sample_fmt_name(ac->out_fmt),

            use_generic ? ac->func_descr_generic : ac->func_descr);

    if (ac->apply_map) {

        ChannelMapInfo *map = &ac->avr->ch_map_info;

        if (!av_sample_fmt_is_planar(ac->out_fmt)) {

            av_log(ac->avr, AV_LOG_ERROR, "cannot remap packed format during conversion\n");

            return AVERROR(EINVAL);

        }

        if (map->do_remap) {

            if (av_sample_fmt_is_planar(ac->in_fmt)) {

                conv_func_flat *convert = use_generic ? ac->conv_flat_generic :

                                                        ac->conv_flat;

                for (p = 0; p < ac->planes; p++)

                    if (map->channel_map[p] >= 0)

                        convert(out->data[p], in->data[map->channel_map[p]], len);

            } else {

                uint8_t *data[AVRESAMPLE_MAX_CHANNELS];

                conv_func_deinterleave *convert = use_generic ?

                                                  ac->conv_deinterleave_generic :

                                                  ac->conv_deinterleave;

                for (p = 0; p < ac->channels; p++)

                    data[map->input_map[p]] = out->data[p];

                convert(data, in->data[0], len, ac->channels);

            }

        }

        if (map->do_copy || map->do_zero) {

            for (p = 0; p < ac->planes; p++) {

                if (map->channel_copy[p])

                    memcpy(out->data[p], out->data[map->channel_copy[p]],

                           len * out->stride);

                else if (map->channel_zero[p])

                    av_samples_set_silence(&out->data[p], 0, len, 1, ac->out_fmt);

            }

        }

    } else {

        switch (ac->func_type) {

        case CONV_FUNC_TYPE_FLAT: {

            if (!in->is_planar)

                len *= in->channels;

            if (use_generic) {

                for (p = 0; p < ac->planes; p++)

                    ac->conv_flat_generic(out->data[p], in->data[p], len);

            } else {

                for (p = 0; p < ac->planes; p++)

                    ac->conv_flat(out->data[p], in->data[p], len);

            }

            break;

        }

        case CONV_FUNC_TYPE_INTERLEAVE:

            if (use_generic)

                ac->conv_interleave_generic(out->data[0], in->data, len,

                                            ac->channels);

            else

                ac->conv_interleave(out->data[0], in->data, len, ac->channels);

            break;

        case CONV_FUNC_TYPE_DEINTERLEAVE:

            if (use_generic)

                ac->conv_deinterleave_generic(out->data, in->data[0], len,

                                              ac->channels);

            else

                ac->conv_deinterleave(out->data, in->data[0], len,

                                      ac->channels);

            break;

        }

    }

    out->nb_samples = in->nb_samples;

    return 0;

}


static int qcow2_set_up_encryption(BlockDriverState *bs, const char *encryptfmt,

                                   QemuOpts *opts, Error **errp)

{

    BDRVQcow2State *s = bs->opaque;

    QCryptoBlockCreateOptions *cryptoopts = NULL;

    QCryptoBlock *crypto = NULL;

    int ret = -EINVAL;

    QDict *options, *encryptopts;

    options = qemu_opts_to_qdict(opts, NULL);

    qdict_extract_subqdict(options, &encryptopts, "encrypt.");

    QDECREF(options);

    if (!g_str_equal(encryptfmt, "aes")) {

        error_setg(errp, "Unknown encryption format '%s', expected 'aes'",

                   encryptfmt);

        ret = -EINVAL;

        goto out;

    }

    cryptoopts = block_crypto_create_opts_init(

        Q_CRYPTO_BLOCK_FORMAT_QCOW, encryptopts, errp);

    if (!cryptoopts) {

        ret = -EINVAL;

        goto out;

    }

    s->crypt_method_header = QCOW_CRYPT_AES;

    crypto = qcrypto_block_create(cryptoopts,

                                  NULL, NULL,

                                  bs, errp);

    if (!crypto) {

        ret = -EINVAL;

        goto out;

    }

    ret = qcow2_update_header(bs);

    if (ret < 0) {

        error_setg_errno(errp, -ret, "Could not write encryption header");

        goto out;

    }

 out:

    QDECREF(encryptopts);

    qcrypto_block_free(crypto);

    qapi_free_QCryptoBlockCreateOptions(cryptoopts);

    return ret;

}


static void tilegx_cpu_class_init(ObjectClass *oc, void *data)
{
    DeviceClass *dc = DEVICE_CLASS(oc);
    CPUClass *cc = CPU_CLASS(oc);
    TileGXCPUClass *tcc = TILEGX_CPU_CLASS(oc);
    tcc->parent_realize = dc->realize;
    dc->realize = tilegx_cpu_realizefn;
    tcc->parent_reset = cc->reset;
    cc->reset = tilegx_cpu_reset;
    cc->has_work = tilegx_cpu_has_work;
    cc->do_interrupt = tilegx_cpu_do_interrupt;
    cc->cpu_exec_interrupt = tilegx_cpu_exec_interrupt;
    cc->dump_state = tilegx_cpu_dump_state;
    cc->set_pc = tilegx_cpu_set_pc;
    cc->handle_mmu_fault = tilegx_cpu_handle_mmu_fault;
    cc->gdb_num_core_regs = 0;
}


static inline void downmix_2f_1r_to_stereo(float *samples)

{

    int i;

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

        samples[i] += samples[i + 512];

        samples[i + 256] += samples[i + 512];

        samples[i + 512] = 0;

    }

}


static PayloadContext *h264_new_extradata(void)

{

    PayloadContext *data =

        av_mallocz(sizeof(PayloadContext) +

                   FF_INPUT_BUFFER_PADDING_SIZE);

    if (data) {

        data->cookie = MAGIC_COOKIE;

    }

    return data;

}


static void dma_complete(DMAAIOCB *dbs, int ret)

{

    trace_dma_complete(dbs, ret, dbs->common.cb);

    dma_bdrv_unmap(dbs);

    if (dbs->common.cb) {

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

    }

    qemu_iovec_destroy(&dbs->iov);

    if (dbs->bh) {

        qemu_bh_delete(dbs->bh);

        dbs->bh = NULL;

    }

    qemu_aio_unref(dbs);

}


static int proxy_mkdir(FsContext *fs_ctx, V9fsPath *dir_path,

                       const char *name, FsCred *credp)

{

    int retval;

    V9fsString fullname;

    v9fs_string_init(&fullname);

    v9fs_string_sprintf(&fullname, "%s/%s", dir_path->data, name);

    retval = v9fs_request(fs_ctx->private, T_MKDIR, NULL, &fullname,

                          credp->fc_mode, credp->fc_uid, credp->fc_gid);

    v9fs_string_free(&fullname);

    if (retval < 0) {

        errno = -retval;

        retval = -1;

    }

    v9fs_string_free(&fullname);

    return retval;

}


static int decode_init_thread_copy(AVCodecContext *avctx)

{

    H264Context *h = avctx->priv_data;

    if (!avctx->internal->is_copy)

        return 0;

    memset(h->sps_buffers, 0, sizeof(h->sps_buffers));

    memset(h->pps_buffers, 0, sizeof(h->pps_buffers));

    h->rbsp_buffer[0]      = NULL;

    h->rbsp_buffer[1]      = NULL;

    h->rbsp_buffer_size[0] = 0;

    h->rbsp_buffer_size[1] = 0;

    h->context_initialized = 0;

    return 0;

}


static int dvvideo_decode_frame(AVCodecContext *avctx,

                                 void *data, int *data_size,

                                 uint8_t *buf, int buf_size)

{

    DVVideoContext *s = avctx->priv_data;

    s->sys = dv_frame_profile(buf);

    if (!s->sys || buf_size < s->sys->frame_size)

        return -1; /* NOTE: we only accept several full frames */

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

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

    s->picture.reference = 0;

    s->picture.key_frame = 1;

    s->picture.pict_type = FF_I_TYPE;

    avctx->pix_fmt = s->sys->pix_fmt;

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

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

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

        return -1;

    }

    s->picture.interlaced_frame = 1;

    s->picture.top_field_first = 0;

    s->buf = buf;

    avctx->execute(avctx, dv_decode_mt, (void**)&dv_anchor[0], NULL,

                   s->sys->difseg_size * 27);

    emms_c();

    /* return image */

    *data_size = sizeof(AVFrame);

    *(AVFrame*)data= s->picture;

    return s->sys->frame_size;

}


static uint32_t eepro100_read4(EEPRO100State * s, uint32_t addr)

{

    uint32_t val;

    if (addr <= sizeof(s->mem) - sizeof(val)) {

        memcpy(&val, &s->mem[addr], sizeof(val));

    }

    switch (addr) {

    case SCBStatus:

        TRACE(OTHER, logout("addr=%s val=0x%08x\n", regname(addr), val));

        break;

    case SCBPointer:

#if 0

        val = eepro100_read_pointer(s);

#endif

        TRACE(OTHER, logout("addr=%s val=0x%08x\n", regname(addr), val));

        break;

    case SCBPort:

        val = eepro100_read_port(s);

        TRACE(OTHER, logout("addr=%s val=0x%08x\n", regname(addr), val));

        break;

    case SCBCtrlMDI:

        val = eepro100_read_mdi(s);

        break;

    default:

        logout("addr=%s val=0x%08x\n", regname(addr), val);

        missing("unknown longword read");

    }

    return val;

}


static void mpeg_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,

                              int (*mv)[2][4][2],

                              int mb_x, int mb_y, int mb_intra, int mb_skipped)

{

    MpegEncContext *s = opaque;

    s->mv_dir     = mv_dir;

    s->mv_type    = mv_type;

    s->mb_intra   = mb_intra;

    s->mb_skipped = mb_skipped;

    s->mb_x       = mb_x;

    s->mb_y       = mb_y;

    memcpy(s->mv, mv, sizeof(*mv));

    ff_init_block_index(s);

    ff_update_block_index(s);

    s->dsp.clear_blocks(s->block[0]);

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

    s->dest[1] = s->current_picture.f.data[1] + (s->mb_y * (16 >> s->chroma_y_shift) * s->uvlinesize) + s->mb_x * (16 >> s->chroma_x_shift);

    s->dest[2] = s->current_picture.f.data[2] + (s->mb_y * (16 >> s->chroma_y_shift) * s->uvlinesize) + s->mb_x * (16 >> s->chroma_x_shift);

    assert(ref == 0);

    ff_MPV_decode_mb(s, s->block);

}


static abi_long do_setsockopt(int sockfd, int level, int optname,

                              abi_ulong optval_addr, socklen_t optlen)

{

    abi_long ret;

    int val;

    struct ip_mreqn *ip_mreq;

    struct ip_mreq_source *ip_mreq_source;

    switch(level) {

    case SOL_TCP:

        /* TCP options all take an 'int' value.  */

        if (optlen < sizeof(uint32_t))

            return -TARGET_EINVAL;

        if (get_user_u32(val, optval_addr))

            return -TARGET_EFAULT;

        ret = get_errno(setsockopt(sockfd, level, optname, &val, sizeof(val)));

        break;

    case SOL_IP:

        switch(optname) {

        case IP_TOS:

        case IP_TTL:

        case IP_HDRINCL:

        case IP_ROUTER_ALERT:

        case IP_RECVOPTS:

        case IP_RETOPTS:

        case IP_PKTINFO:

        case IP_MTU_DISCOVER:

        case IP_RECVERR:

        case IP_RECVTOS:

#ifdef IP_FREEBIND

        case IP_FREEBIND:

#endif

        case IP_MULTICAST_TTL:

        case IP_MULTICAST_LOOP:

            val = 0;

            if (optlen >= sizeof(uint32_t)) {

                if (get_user_u32(val, optval_addr))

                    return -TARGET_EFAULT;

            } else if (optlen >= 1) {

                if (get_user_u8(val, optval_addr))

                    return -TARGET_EFAULT;

            }

            ret = get_errno(setsockopt(sockfd, level, optname, &val, sizeof(val)));

            break;

        case IP_ADD_MEMBERSHIP:

        case IP_DROP_MEMBERSHIP:

            if (optlen < sizeof (struct target_ip_mreq) ||

                optlen > sizeof (struct target_ip_mreqn))

                return -TARGET_EINVAL;

            ip_mreq = (struct ip_mreqn *) alloca(optlen);

            target_to_host_ip_mreq(ip_mreq, optval_addr, optlen);

            ret = get_errno(setsockopt(sockfd, level, optname, ip_mreq, optlen));

            break;

        case IP_BLOCK_SOURCE:

        case IP_UNBLOCK_SOURCE:

        case IP_ADD_SOURCE_MEMBERSHIP:

        case IP_DROP_SOURCE_MEMBERSHIP:

            if (optlen != sizeof (struct target_ip_mreq_source))

                return -TARGET_EINVAL;

            ip_mreq_source = lock_user(VERIFY_READ, optval_addr, optlen, 1);

            ret = get_errno(setsockopt(sockfd, level, optname, ip_mreq_source, optlen));

            unlock_user (ip_mreq_source, optval_addr, 0);

            break;

        default:

            goto unimplemented;

        }

        break;

    case TARGET_SOL_SOCKET:

        switch (optname) {

            /* Options with 'int' argument.  */

        case TARGET_SO_DEBUG:

		optname = SO_DEBUG;

		break;

        case TARGET_SO_REUSEADDR:

		optname = SO_REUSEADDR;

		break;

        case TARGET_SO_TYPE:

		optname = SO_TYPE;

		break;

        case TARGET_SO_ERROR:

		optname = SO_ERROR;

		break;

        case TARGET_SO_DONTROUTE:

		optname = SO_DONTROUTE;

		break;

        case TARGET_SO_BROADCAST:

		optname = SO_BROADCAST;

		break;

        case TARGET_SO_SNDBUF:

		optname = SO_SNDBUF;

		break;

        case TARGET_SO_RCVBUF:

		optname = SO_RCVBUF;

		break;

        case TARGET_SO_KEEPALIVE:

		optname = SO_KEEPALIVE;

		break;

        case TARGET_SO_OOBINLINE:

		optname = SO_OOBINLINE;

		break;

        case TARGET_SO_NO_CHECK:

		optname = SO_NO_CHECK;

		break;

        case TARGET_SO_PRIORITY:

		optname = SO_PRIORITY;

		break;

#ifdef SO_BSDCOMPAT

        case TARGET_SO_BSDCOMPAT:

		optname = SO_BSDCOMPAT;

		break;

#endif

        case TARGET_SO_PASSCRED:

		optname = SO_PASSCRED;

		break;

        case TARGET_SO_TIMESTAMP:

		optname = SO_TIMESTAMP;

		break;

        case TARGET_SO_RCVLOWAT:

		optname = SO_RCVLOWAT;

		break;

        case TARGET_SO_RCVTIMEO:

		optname = SO_RCVTIMEO;

		break;

        case TARGET_SO_SNDTIMEO:

		optname = SO_SNDTIMEO;

		break;

            break;

        default:

            goto unimplemented;

        }

	if (optlen < sizeof(uint32_t))

            return -TARGET_EINVAL;

	if (get_user_u32(val, optval_addr))

            return -TARGET_EFAULT;

	ret = get_errno(setsockopt(sockfd, SOL_SOCKET, optname, &val, sizeof(val)));

        break;

    default:

    unimplemented:

        gemu_log("Unsupported setsockopt level=%d optname=%d \n", level, optname);

        ret = -TARGET_ENOPROTOOPT;

    }

    return ret;

}


void vty_putchars(VIOsPAPRDevice *sdev, uint8_t *buf, int len)

{

    VIOsPAPRVTYDevice *dev = VIO_SPAPR_VTY_DEVICE(sdev);

    /* FIXME: should check the qemu_chr_fe_write() return value */

    qemu_chr_fe_write(dev->chardev, buf, len);

}


static inline int cris_addc_m(int a, const int *b)

{

	asm volatile ("addc [%1], %0\n" : "+r" (a) : "r" (b));

	return a;

}


int av_find_stream_info(AVFormatContext *ic)

{

    int i, count, ret, read_size, j;

    AVStream *st;

    AVPacket pkt1, *pkt;

    AVPacketList *pktl=NULL, **ppktl;

    int64_t last_dts[MAX_STREAMS];

    int duration_count[MAX_STREAMS]={0};

    double duration_error[MAX_STREAMS][MAX_STD_TIMEBASES]={{0}}; //FIXME malloc()?

    offset_t old_offset = url_ftell(&ic->pb);

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

        st = ic->streams[i];

        if(st->codec->codec_type == CODEC_TYPE_VIDEO){

/*            if(!st->time_base.num)

                st->time_base= */

            if(!st->codec->time_base.num)

                st->codec->time_base= st->time_base;

        }

        //only for the split stuff

        if (!st->parser) {

            st->parser = av_parser_init(st->codec->codec_id);

            if(st->need_parsing == 2 && st->parser){

                st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;

            }

        }

    }

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

        last_dts[i]= AV_NOPTS_VALUE;

    }

    count = 0;

    read_size = 0;

    ppktl = &ic->packet_buffer;

    for(;;) {

        /* check if one codec still needs to be handled */

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

            st = ic->streams[i];

            if (!has_codec_parameters(st->codec))

                break;

            /* variable fps and no guess at the real fps */

            if(   st->codec->time_base.den >= 101LL*st->codec->time_base.num

               && duration_count[i]<20 && st->codec->codec_type == CODEC_TYPE_VIDEO)

                break;

            if(st->parser && st->parser->parser->split && !st->codec->extradata)

                break;

        }

        if (i == ic->nb_streams) {

            /* NOTE: if the format has no header, then we need to read

               some packets to get most of the streams, so we cannot

               stop here */

            if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {

                /* if we found the info for all the codecs, we can stop */

                ret = count;

                break;

            }

        }

        /* we did not get all the codec info, but we read too much data */

        if (read_size >= MAX_READ_SIZE) {

            ret = count;

            break;

        }

        /* NOTE: a new stream can be added there if no header in file

           (AVFMTCTX_NOHEADER) */

        ret = av_read_frame_internal(ic, &pkt1);

        if (ret < 0) {

            /* EOF or error */

            ret = -1; /* we could not have all the codec parameters before EOF */

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

                st = ic->streams[i];

                if (!has_codec_parameters(st->codec)){

                    char buf[256];

                    avcodec_string(buf, sizeof(buf), st->codec, 0);

                    av_log(ic, AV_LOG_INFO, "Could not find codec parameters (%s)\n", buf);

                } else {

                    ret = 0;

                }

            }

            break;

        }

        pktl = av_mallocz(sizeof(AVPacketList));

        if (!pktl) {

            ret = AVERROR_NOMEM;

            break;

        }

        /* add the packet in the buffered packet list */

        *ppktl = pktl;

        ppktl = &pktl->next;

        pkt = &pktl->pkt;

        *pkt = pkt1;

        /* duplicate the packet */

        if (av_dup_packet(pkt) < 0) {

            ret = AVERROR_NOMEM;

            break;

        }

        read_size += pkt->size;

        st = ic->streams[pkt->stream_index];

        if(st->codec_info_nb_frames>1) //FIXME move codec_info_nb_frames and codec_info_duration from AVStream into this func

            st->codec_info_duration += pkt->duration;

        if (pkt->duration != 0)

            st->codec_info_nb_frames++;

        {

            int index= pkt->stream_index;

            int64_t last= last_dts[index];

            int64_t duration= pkt->dts - last;

            if(pkt->dts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && duration>0){

                double dur= duration * av_q2d(st->time_base);

//                if(st->codec->codec_type == CODEC_TYPE_VIDEO)

//                    av_log(NULL, AV_LOG_ERROR, "%f\n", dur);

                if(duration_count[index] < 2)

                    memset(duration_error, 0, sizeof(duration_error));

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

                    int framerate= get_std_framerate(i);

                    int ticks= lrintf(dur*framerate/(1001*12));

                    double error= dur - ticks*1001*12/(double)framerate;

                    duration_error[index][i] += error*error;

                }

                duration_count[index]++;

                if(st->codec_info_nb_frames == 0 && 0)

                    st->codec_info_duration += duration;

            }

            if(last == AV_NOPTS_VALUE || duration_count[index]<=1)

                last_dts[pkt->stream_index]= pkt->dts;

        }

        if(st->parser && st->parser->parser->split && !st->codec->extradata){

            int i= st->parser->parser->split(st->codec, pkt->data, pkt->size);

            if(i){

                st->codec->extradata_size= i;

                st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);

                memcpy(st->codec->extradata, pkt->data, st->codec->extradata_size);

                memset(st->codec->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);

            }

        }

        /* if still no information, we try to open the codec and to

           decompress the frame. We try to avoid that in most cases as

           it takes longer and uses more memory. For MPEG4, we need to

           decompress for Quicktime. */

        if (!has_codec_parameters(st->codec) /*&&

            (st->codec->codec_id == CODEC_ID_FLV1 ||

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

             st->codec->codec_id == CODEC_ID_H263 ||

             st->codec->codec_id == CODEC_ID_H261 ||

             st->codec->codec_id == CODEC_ID_VORBIS ||

             st->codec->codec_id == CODEC_ID_MJPEG ||

             st->codec->codec_id == CODEC_ID_PNG ||

             st->codec->codec_id == CODEC_ID_PAM ||

             st->codec->codec_id == CODEC_ID_PGM ||

             st->codec->codec_id == CODEC_ID_PGMYUV ||

             st->codec->codec_id == CODEC_ID_PBM ||

             st->codec->codec_id == CODEC_ID_PPM ||

             st->codec->codec_id == CODEC_ID_SHORTEN ||

             (st->codec->codec_id == CODEC_ID_MPEG4 && !st->need_parsing))*/)

            try_decode_frame(st, pkt->data, pkt->size);

        if (av_rescale_q(st->codec_info_duration, st->time_base, AV_TIME_BASE_Q) >= ic->max_analyze_duration) {

            break;

        }

        count++;

    }

    // close codecs which where opened in try_decode_frame()

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

        st = ic->streams[i];

        if(st->codec->codec)

            avcodec_close(st->codec);

    }

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

        st = ic->streams[i];

        if (st->codec->codec_type == CODEC_TYPE_VIDEO) {

            if(st->codec->codec_id == CODEC_ID_RAWVIDEO && !st->codec->codec_tag && !st->codec->bits_per_sample)

                st->codec->codec_tag= avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);

            if(duration_count[i]

               && (st->codec->time_base.num*101LL <= st->codec->time_base.den || st->codec->codec_id == CODEC_ID_MPEG2VIDEO) /*&&

               //FIXME we should not special case mpeg2, but this needs testing with non mpeg2 ...

               st->time_base.num*duration_sum[i]/duration_count[i]*101LL > st->time_base.den*/){

                double best_error= 2*av_q2d(st->time_base);

                best_error= best_error*best_error*duration_count[i]*1000*12*30;

                for(j=1; j<MAX_STD_TIMEBASES; j++){

                    double error= duration_error[i][j] * get_std_framerate(j);

//                    if(st->codec->codec_type == CODEC_TYPE_VIDEO)

//                        av_log(NULL, AV_LOG_ERROR, "%f %f\n", get_std_framerate(j) / 12.0/1001, error);

                    if(error < best_error){

                        best_error= error;

                        av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, get_std_framerate(j), 12*1001, INT_MAX);

                    }

                }

            }

            if (!st->r_frame_rate.num){

                if(    st->codec->time_base.den * (int64_t)st->time_base.num

                    <= st->codec->time_base.num * (int64_t)st->time_base.den){

                    st->r_frame_rate.num = st->codec->time_base.den;

                    st->r_frame_rate.den = st->codec->time_base.num;

                }else{

                    st->r_frame_rate.num = st->time_base.den;

                    st->r_frame_rate.den = st->time_base.num;

                }

            }

        }else if(st->codec->codec_type == CODEC_TYPE_AUDIO) {

            if(!st->codec->bits_per_sample)

                st->codec->bits_per_sample= av_get_bits_per_sample(st->codec->codec_id);

        }

    }

    av_estimate_timings(ic, old_offset);

#if 0

    /* correct DTS for b frame streams with no timestamps */

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

        st = ic->streams[i];

        if (st->codec->codec_type == CODEC_TYPE_VIDEO) {

            if(b-frames){

                ppktl = &ic->packet_buffer;

                while(ppkt1){

                    if(ppkt1->stream_index != i)

                        continue;

                    if(ppkt1->pkt->dts < 0)

                        break;

                    if(ppkt1->pkt->pts != AV_NOPTS_VALUE)

                        break;

                    ppkt1->pkt->dts -= delta;

                    ppkt1= ppkt1->next;

                }

                if(ppkt1)

                    continue;

                st->cur_dts -= delta;

            }

        }

    }

#endif

    return ret;

}


static void create_vorbis_context(vorbis_enc_context *venc,

                                  AVCodecContext *avccontext)

{

    vorbis_enc_floor   *fc;

    vorbis_enc_residue *rc;

    vorbis_enc_mapping *mc;

    int i, book;

    venc->channels    = avccontext->channels;

    venc->sample_rate = avccontext->sample_rate;

    venc->log2_blocksize[0] = venc->log2_blocksize[1] = 11;

    venc->ncodebooks = FF_ARRAY_ELEMS(cvectors);

    venc->codebooks  = av_malloc(sizeof(vorbis_enc_codebook) * venc->ncodebooks);

    // codebook 0..14 - floor1 book, values 0..255

    // codebook 15 residue masterbook

    // codebook 16..29 residue

    for (book = 0; book < venc->ncodebooks; book++) {

        vorbis_enc_codebook *cb = &venc->codebooks[book];

        int vals;

        cb->ndimentions = cvectors[book].dim;

        cb->nentries    = cvectors[book].real_len;

        cb->min         = cvectors[book].min;

        cb->delta       = cvectors[book].delta;

        cb->lookup      = cvectors[book].lookup;

        cb->seq_p       = 0;

        cb->lens      = av_malloc(sizeof(uint8_t)  * cb->nentries);

        cb->codewords = av_malloc(sizeof(uint32_t) * cb->nentries);

        memcpy(cb->lens, cvectors[book].clens, cvectors[book].len);

        memset(cb->lens + cvectors[book].len, 0, cb->nentries - cvectors[book].len);

        if (cb->lookup) {

            vals = cb_lookup_vals(cb->lookup, cb->ndimentions, cb->nentries);

            cb->quantlist = av_malloc(sizeof(int) * vals);

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

                cb->quantlist[i] = cvectors[book].quant[i];

        } else {

            cb->quantlist = NULL;

        }

        ready_codebook(cb);

    }

    venc->nfloors = 1;

    venc->floors  = av_malloc(sizeof(vorbis_enc_floor) * venc->nfloors);

    // just 1 floor

    fc = &venc->floors[0];

    fc->partitions         = NUM_FLOOR_PARTITIONS;

    fc->partition_to_class = av_malloc(sizeof(int) * fc->partitions);

    fc->nclasses           = 0;

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

        static const int a[] = {0, 1, 2, 2, 3, 3, 4, 4};

        fc->partition_to_class[i] = a[i];

        fc->nclasses = FFMAX(fc->nclasses, fc->partition_to_class[i]);

    }

    fc->nclasses++;

    fc->classes = av_malloc(sizeof(vorbis_enc_floor_class) * fc->nclasses);

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

        vorbis_enc_floor_class * c = &fc->classes[i];

        int j, books;

        c->dim        = floor_classes[i].dim;

        c->subclass   = floor_classes[i].subclass;

        c->masterbook = floor_classes[i].masterbook;

        books         = (1 << c->subclass);

        c->books      = av_malloc(sizeof(int) * books);

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

            c->books[j] = floor_classes[i].nbooks[j];

    }

    fc->multiplier = 2;

    fc->rangebits  = venc->log2_blocksize[0] - 1;

    fc->values = 2;

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

        fc->values += fc->classes[fc->partition_to_class[i]].dim;

    fc->list = av_malloc(sizeof(vorbis_floor1_entry) * fc->values);

    fc->list[0].x = 0;

    fc->list[1].x = 1 << fc->rangebits;

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

        static const int a[] = {

             93, 23,372,  6, 46,186,750, 14, 33, 65,

            130,260,556,  3, 10, 18, 28, 39, 55, 79,

            111,158,220,312,464,650,850

        };

        fc->list[i].x = a[i - 2];

    }

    ff_vorbis_ready_floor1_list(fc->list, fc->values);

    venc->nresidues = 1;

    venc->residues  = av_malloc(sizeof(vorbis_enc_residue) * venc->nresidues);

    // single residue

    rc = &venc->residues[0];

    rc->type            = 2;

    rc->begin           = 0;

    rc->end             = 1600;

    rc->partition_size  = 32;

    rc->classifications = 10;

    rc->classbook       = 15;

    rc->books           = av_malloc(sizeof(*rc->books) * rc->classifications);

    {

        static const int8_t a[10][8] = {

            { -1, -1, -1, -1, -1, -1, -1, -1, },

            { -1, -1, 16, -1, -1, -1, -1, -1, },

            { -1, -1, 17, -1, -1, -1, -1, -1, },

            { -1, -1, 18, -1, -1, -1, -1, -1, },

            { -1, -1, 19, -1, -1, -1, -1, -1, },

            { -1, -1, 20, -1, -1, -1, -1, -1, },

            { -1, -1, 21, -1, -1, -1, -1, -1, },

            { 22, 23, -1, -1, -1, -1, -1, -1, },

            { 24, 25, -1, -1, -1, -1, -1, -1, },

            { 26, 27, 28, -1, -1, -1, -1, -1, },

        };

        memcpy(rc->books, a, sizeof a);

    }

    ready_residue(rc, venc);

    venc->nmappings = 1;

    venc->mappings  = av_malloc(sizeof(vorbis_enc_mapping) * venc->nmappings);

    // single mapping

    mc = &venc->mappings[0];

    mc->submaps = 1;

    mc->mux     = av_malloc(sizeof(int) * venc->channels);

    for (i = 0; i < venc->channels; i++)

        mc->mux[i] = 0;

    mc->floor   = av_malloc(sizeof(int) * mc->submaps);

    mc->residue = av_malloc(sizeof(int) * mc->submaps);

    for (i = 0; i < mc->submaps; i++) {

        mc->floor[i]   = 0;

        mc->residue[i] = 0;

    }

    mc->coupling_steps = venc->channels == 2 ? 1 : 0;

    mc->magnitude      = av_malloc(sizeof(int) * mc->coupling_steps);

    mc->angle          = av_malloc(sizeof(int) * mc->coupling_steps);

    if (mc->coupling_steps) {

        mc->magnitude[0] = 0;

        mc->angle[0]     = 1;

    }

    venc->nmodes = 1;

    venc->modes  = av_malloc(sizeof(vorbis_enc_mode) * venc->nmodes);

    // single mode

    venc->modes[0].blockflag = 0;

    venc->modes[0].mapping   = 0;

    venc->have_saved = 0;

    venc->saved      = av_malloc(sizeof(float) * venc->channels * (1 << venc->log2_blocksize[1]) / 2);

    venc->samples    = av_malloc(sizeof(float) * venc->channels * (1 << venc->log2_blocksize[1]));

    venc->floor      = av_malloc(sizeof(float) * venc->channels * (1 << venc->log2_blocksize[1]) / 2);

    venc->coeffs     = av_malloc(sizeof(float) * venc->channels * (1 << venc->log2_blocksize[1]) / 2);

    venc->win[0] = ff_vorbis_vwin[venc->log2_blocksize[0] - 6];

    venc->win[1] = ff_vorbis_vwin[venc->log2_blocksize[1] - 6];

    ff_mdct_init(&venc->mdct[0], venc->log2_blocksize[0], 0, 1.0);

    ff_mdct_init(&venc->mdct[1], venc->log2_blocksize[1], 0, 1.0);

}


QEMUOptionParameter *append_option_parameters(QEMUOptionParameter *dest,

    QEMUOptionParameter *list)

{

    size_t num_options, num_dest_options;

    num_options = count_option_parameters(dest);

    num_dest_options = num_options;

    num_options += count_option_parameters(list);

    dest = qemu_realloc(dest, (num_options + 1) * sizeof(QEMUOptionParameter));

    while (list && list->name) {

        if (get_option_parameter(dest, list->name) == NULL) {

            dest[num_dest_options++] = *list;

        }

        list++;

    }

    return dest;

}


void stream_start(const char *job_id, BlockDriverState *bs,

                  BlockDriverState *base, const char *backing_file_str,

                  int64_t speed, BlockdevOnError on_error, Error **errp)

{

    StreamBlockJob *s;

    BlockDriverState *iter;

    int orig_bs_flags;

    /* Make sure that the image is opened in read-write mode */

    orig_bs_flags = bdrv_get_flags(bs);

    if (!(orig_bs_flags & BDRV_O_RDWR)) {

        if (bdrv_reopen(bs, orig_bs_flags | BDRV_O_RDWR, errp) != 0) {

            return;

        }

    }

    /* Prevent concurrent jobs trying to modify the graph structure here, we

     * already have our own plans. Also don't allow resize as the image size is

     * queried only at the job start and then cached. */

    s = block_job_create(job_id, &stream_job_driver, bs,

                         BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED |

                         BLK_PERM_GRAPH_MOD,

                         BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED |

                         BLK_PERM_WRITE,

                         speed, BLOCK_JOB_DEFAULT, NULL, NULL, errp);

    if (!s) {

        goto fail;

    }

    /* Block all intermediate nodes between bs and base, because they will

     * disappear from the chain after this operation. The streaming job reads

     * every block only once, assuming that it doesn't change, so block writes

     * and resizes. */

    for (iter = backing_bs(bs); iter && iter != base; iter = backing_bs(iter)) {

        block_job_add_bdrv(&s->common, "intermediate node", iter, 0,

                           BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED,

                           &error_abort);

    }

    s->base = base;

    s->backing_file_str = g_strdup(backing_file_str);

    s->bs_flags = orig_bs_flags;

    s->on_error = on_error;

    trace_stream_start(bs, base, s);

    block_job_start(&s->common);

    return;

fail:

    if (orig_bs_flags != bdrv_get_flags(bs)) {

        bdrv_reopen(bs, s->bs_flags, NULL);

    }

}


static void tcg_target_qemu_prologue(TCGContext *s)

{

    int i, frame_size;

    /* reserve some stack space */

    frame_size = ARRAY_SIZE(tcg_target_callee_save_regs) * 4

                 + TCG_STATIC_CALL_ARGS_SIZE;

    frame_size = (frame_size + TCG_TARGET_STACK_ALIGN - 1) &

                 ~(TCG_TARGET_STACK_ALIGN - 1);

    /* TB prologue */

    tcg_out_addi(s, TCG_REG_SP, -frame_size);

    for(i = 0 ; i < ARRAY_SIZE(tcg_target_callee_save_regs) ; i++) {

        tcg_out_st(s, TCG_TYPE_I32, tcg_target_callee_save_regs[i],

                   TCG_REG_SP, TCG_STATIC_CALL_ARGS_SIZE + i * 4);

    }

    /* Call generated code */

    tcg_out_opc_reg(s, OPC_JR, 0, tcg_target_call_iarg_regs[1]), 0);

    tcg_out_mov(s, TCG_TYPE_PTR, TCG_AREG0, tcg_target_call_iarg_regs[0]);

    tb_ret_addr = s->code_ptr;

    /* TB epilogue */

    for(i = 0 ; i < ARRAY_SIZE(tcg_target_callee_save_regs) ; i++) {

        tcg_out_ld(s, TCG_TYPE_I32, tcg_target_callee_save_regs[i],

                   TCG_REG_SP, TCG_STATIC_CALL_ARGS_SIZE + i * 4);

    }

    tcg_out_opc_reg(s, OPC_JR, 0, TCG_REG_RA, 0);

    tcg_out_addi(s, TCG_REG_SP, frame_size);

}


static void virtio_scsi_vring_teardown(VirtIOSCSI *s)

{

    VirtIODevice *vdev = VIRTIO_DEVICE(s);

    VirtIOSCSICommon *vs = VIRTIO_SCSI_COMMON(s);

    int i;

    if (s->ctrl_vring) {

        vring_teardown(&s->ctrl_vring->vring, vdev, 0);

    }

    if (s->event_vring) {

        vring_teardown(&s->event_vring->vring, vdev, 1);

    }

    if (s->cmd_vrings) {

        for (i = 0; i < vs->conf.num_queues && s->cmd_vrings[i]; i++) {

            vring_teardown(&s->cmd_vrings[i]->vring, vdev, 2 + i);

        }

        free(s->cmd_vrings);

        s->cmd_vrings = NULL;

    }

}


static void opt_frame_pix_fmt(const char *arg)

{

    if (strcmp(arg, "list"))

        frame_pix_fmt = avcodec_get_pix_fmt(arg);

    else {

        list_fmts(avcodec_pix_fmt_string, PIX_FMT_NB);

        av_exit(0);

    }

}


static int scan_mmco_reset(AVCodecParserContext *s)

{

    H264ParseContext *p = s->priv_data;

    H264Context      *h = &p->h;

    H264SliceContext *sl = &h->slice_ctx[0];

    sl->slice_type_nos = s->pict_type & 3;

    if (h->pps.redundant_pic_cnt_present)

        get_ue_golomb(&sl->gb); // redundant_pic_count

    if (ff_set_ref_count(h, sl) < 0)

        return AVERROR_INVALIDDATA;

    if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {

        int list;

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

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

                int index;

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

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

                    if (reordering_of_pic_nums_idc < 3)

                        get_ue_golomb(&sl->gb);

                    else if (reordering_of_pic_nums_idc > 3) {

                        av_log(h->avctx, AV_LOG_ERROR,

                               "illegal reordering_of_pic_nums_idc %d\n",

                               reordering_of_pic_nums_idc);

                        return AVERROR_INVALIDDATA;

                    } else

                        break;

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

                        av_log(h->avctx, AV_LOG_ERROR,

                               "reference count %d overflow\n", index);

                        return AVERROR_INVALIDDATA;

                    }

                }

            }

        }

    }

    if ((h->pps.weighted_pred && sl->slice_type_nos == AV_PICTURE_TYPE_P) ||

        (h->pps.weighted_bipred_idc == 1 && sl->slice_type_nos == AV_PICTURE_TYPE_B))

        ff_pred_weight_table(h, sl);

    if (get_bits1(&sl->gb)) { // adaptive_ref_pic_marking_mode_flag

        int i;

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

            MMCOOpcode opcode = get_ue_golomb_31(&sl->gb);

            if (opcode > (unsigned) MMCO_LONG) {

                av_log(h->avctx, AV_LOG_ERROR,

                       "illegal memory management control operation %d\n",

                       opcode);

                return AVERROR_INVALIDDATA;

            }

            if (opcode == MMCO_END)

               return 0;

            else if (opcode == MMCO_RESET)

                return 1;

            if (opcode == MMCO_SHORT2UNUSED || opcode == MMCO_SHORT2LONG)

                get_ue_golomb(&sl->gb);

            if (opcode == MMCO_SHORT2LONG || opcode == MMCO_LONG2UNUSED ||

                opcode == MMCO_LONG || opcode == MMCO_SET_MAX_LONG)

                get_ue_golomb_31(&sl->gb);

        }

    }

    return 0;

}


static int qdm2_decode_init(AVCodecContext *avctx)

{

    QDM2Context *s = avctx->priv_data;

    uint8_t *extradata;

    int extradata_size;

    int tmp_val, tmp, size;

    int i;

    float alpha;

    /* extradata parsing

    Structure:

    wave {

        frma (QDM2)

        QDCA

        QDCP

    }

    32  size (including this field)

    32  tag (=frma)

    32  type (=QDM2 or QDMC)

    32  size (including this field, in bytes)

    32  tag (=QDCA) // maybe mandatory parameters

    32  unknown (=1)

    32  channels (=2)

    32  samplerate (=44100)

    32  bitrate (=96000)

    32  block size (=4096)

    32  frame size (=256) (for one channel)

    32  packet size (=1300)

    32  size (including this field, in bytes)

    32  tag (=QDCP) // maybe some tuneable parameters

    32  float1 (=1.0)

    32  zero ?

    32  float2 (=1.0)

    32  float3 (=1.0)

    32  unknown (27)

    32  unknown (8)

    32  zero ?

    */

    if (!avctx->extradata || (avctx->extradata_size < 48)) {

        av_log(avctx, AV_LOG_ERROR, "extradata missing or truncated\n");

        return -1;

    }

    extradata = avctx->extradata;

    extradata_size = avctx->extradata_size;

    while (extradata_size > 7) {

        if (!memcmp(extradata, "frmaQDM", 7))

            break;

        extradata++;

        extradata_size--;

    }

    if (extradata_size < 12) {

        av_log(avctx, AV_LOG_ERROR, "not enough extradata (%i)\n",

               extradata_size);

        return -1;

    }

    if (memcmp(extradata, "frmaQDM", 7)) {

        av_log(avctx, AV_LOG_ERROR, "invalid headers, QDM? not found\n");

        return -1;

    }

    if (extradata[7] == 'C') {

//        s->is_qdmc = 1;

        av_log(avctx, AV_LOG_ERROR, "stream is QDMC version 1, which is not supported\n");

        return -1;

    }

    extradata += 8;

    extradata_size -= 8;

    size = BE_32(extradata);

    if(size > extradata_size){

        av_log(avctx, AV_LOG_ERROR, "extradata size too small, %i < %i\n",

               extradata_size, size);

        return -1;

    }

    extradata += 4;

    av_log(avctx, AV_LOG_DEBUG, "size: %d\n", size);

    if (BE_32(extradata) != MKBETAG('Q','D','C','A')) {

        av_log(avctx, AV_LOG_ERROR, "invalid extradata, expecting QDCA\n");

        return -1;

    }

    extradata += 8;

    avctx->channels = s->nb_channels = s->channels = BE_32(extradata);

    extradata += 4;

    avctx->sample_rate = BE_32(extradata);

    extradata += 4;

    avctx->bit_rate = BE_32(extradata);

    extradata += 4;

    s->group_size = BE_32(extradata);

    extradata += 4;

    s->fft_size = BE_32(extradata);

    extradata += 4;

    s->checksum_size = BE_32(extradata);

    extradata += 4;

    s->fft_order = av_log2(s->fft_size) + 1;

    s->fft_frame_size = 2 * s->fft_size; // complex has two floats

    // something like max decodable tones

    s->group_order = av_log2(s->group_size) + 1;

    s->frame_size = s->group_size / 16; // 16 iterations per super block

    if (s->fft_order == 8)

        s->sub_sampling = 1;

    else

        s->sub_sampling = 2;

    s->frequency_range = 255 / (1 << (2 - s->sub_sampling));

    switch ((s->sub_sampling * 2 + s->channels - 1)) {

        case 0: tmp = 40; break;

        case 1: tmp = 48; break;

        case 2: tmp = 56; break;

        case 3: tmp = 72; break;

        case 4: tmp = 80; break;

        case 5: tmp = 100;break;

        default: tmp=s->sub_sampling; break;

    }

    tmp_val = 0;

    if ((tmp * 1000) < avctx->bit_rate)  tmp_val = 1;

    if ((tmp * 1440) < avctx->bit_rate)  tmp_val = 2;

    if ((tmp * 1760) < avctx->bit_rate)  tmp_val = 3;

    if ((tmp * 2240) < avctx->bit_rate)  tmp_val = 4;

    s->cm_table_select = tmp_val;

    if (s->sub_sampling == 0)

        tmp = 16000;

    else

        tmp = ((-(s->sub_sampling -1)) & 8000) + 20000;

    /*

    0: 16000 -> 1

    1: 20000 -> 2

    2: 28000 -> 2

    */

    if (tmp < 8000)

        s->coeff_per_sb_select = 0;

    else if (tmp <= 16000)

        s->coeff_per_sb_select = 1;

    else

        s->coeff_per_sb_select = 2;

    if (s->fft_order != 8 && s->fft_order != 9)

        av_log(avctx, AV_LOG_ERROR, "Unknown FFT order (%d), contact the developers!\n", s->fft_order);

    ff_fft_init(&s->fft_ctx, s->fft_order - 1, 1);

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

        alpha = 2 * M_PI * (float)i / (float)(1 << (s->fft_order - 1));

        s->exptab[i].re = cos(alpha);

        s->exptab[i].im = sin(alpha);

    }

    qdm2_init(s);

//    dump_context(s);

    return 0;

}


static void new_audio_stream(AVFormatContext *oc)

{

    AVStream *st;

    AVCodec *codec= NULL;

    AVCodecContext *audio_enc;

    enum CodecID codec_id;

    st = av_new_stream(oc, oc->nb_streams < nb_streamid_map ? streamid_map[oc->nb_streams] : 0);

    if (!st) {

        fprintf(stderr, "Could not alloc stream\n");

        ffmpeg_exit(1);

    }

    output_codecs = grow_array(output_codecs, sizeof(*output_codecs), &nb_output_codecs, nb_output_codecs + 1);

    if(!audio_stream_copy){

        if (audio_codec_name) {

            codec_id = find_codec_or_die(audio_codec_name, AVMEDIA_TYPE_AUDIO, 1,

                                         avcodec_opts[AVMEDIA_TYPE_AUDIO]->strict_std_compliance);

            codec = avcodec_find_encoder_by_name(audio_codec_name);

            output_codecs[nb_output_codecs-1] = codec;

        } else {

            codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, AVMEDIA_TYPE_AUDIO);

            codec = avcodec_find_encoder(codec_id);

        }

    }

    avcodec_get_context_defaults3(st->codec, codec);

    bitstream_filters[nb_output_files] =

        grow_array(bitstream_filters[nb_output_files],

                   sizeof(*bitstream_filters[nb_output_files]),

                   &nb_bitstream_filters[nb_output_files], oc->nb_streams);

    bitstream_filters[nb_output_files][oc->nb_streams - 1]= audio_bitstream_filters;

    audio_bitstream_filters= NULL;

    avcodec_thread_init(st->codec, thread_count);

    audio_enc = st->codec;

    audio_enc->codec_type = AVMEDIA_TYPE_AUDIO;

    if(audio_codec_tag)

        audio_enc->codec_tag= audio_codec_tag;

    if (oc->oformat->flags & AVFMT_GLOBALHEADER) {

        audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;

        avcodec_opts[AVMEDIA_TYPE_AUDIO]->flags|= CODEC_FLAG_GLOBAL_HEADER;

    }

    if (audio_stream_copy) {

        st->stream_copy = 1;

        audio_enc->channels = audio_channels;

        audio_enc->sample_rate = audio_sample_rate;

    } else {

        audio_enc->codec_id = codec_id;

        set_context_opts(audio_enc, avcodec_opts[AVMEDIA_TYPE_AUDIO], AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, codec);

        if (audio_qscale > QSCALE_NONE) {

            audio_enc->flags |= CODEC_FLAG_QSCALE;

            audio_enc->global_quality = st->quality = FF_QP2LAMBDA * audio_qscale;

        }

        audio_enc->channels = audio_channels;

        audio_enc->sample_fmt = audio_sample_fmt;

        audio_enc->sample_rate = audio_sample_rate;

        audio_enc->channel_layout = channel_layout;

        if (avcodec_channel_layout_num_channels(channel_layout) != audio_channels)

            audio_enc->channel_layout = 0;

        choose_sample_fmt(st, codec);

        choose_sample_rate(st, codec);

    }

    audio_enc->time_base= (AVRational){1, audio_sample_rate};

    if (audio_language) {

        av_metadata_set2(&st->metadata, "language", audio_language, 0);

        av_freep(&audio_language);

    }

    /* reset some key parameters */

    audio_disable = 0;

    av_freep(&audio_codec_name);

    audio_stream_copy = 0;

}


static void frame_erasure(EVRCContext *e, float *samples)

{

    float ilspf[FILTER_ORDER], ilpc[FILTER_ORDER], idelay[NB_SUBFRAMES],

          tmp[SUBFRAME_SIZE + 6], f;

    int i, j;

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

        if (e->bitrate != RATE_QUANT)

            e->lspf[i] = e->prev_lspf[i] * 0.875 + 0.125 * (i + 1) * 0.048;

        else

            e->lspf[i] = e->prev_lspf[i];

    }

    if (e->prev_error_flag)

        e->avg_acb_gain *= 0.75;

    if (e->bitrate == RATE_FULL)

        memcpy(e->pitch_back, e->pitch, ACB_SIZE * sizeof(float));

    if (e->last_valid_bitrate == RATE_QUANT)

        e->bitrate = RATE_QUANT;

    else

        e->bitrate = RATE_FULL;

    if (e->bitrate == RATE_FULL || e->bitrate == RATE_HALF) {

        e->pitch_delay = e->prev_pitch_delay;

    } else {

        float sum = 0;

        idelay[0] = idelay[1] = idelay[2] = MIN_DELAY;

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

            sum += evrc_energy_quant[e->prev_energy_gain][i];

        sum /= (float) NB_SUBFRAMES;

        sum  = pow(10, sum);

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

            e->energy_vector[i] = sum;

    }

    if (fabs(e->pitch_delay - e->prev_pitch_delay) > 15)

        e->prev_pitch_delay = e->pitch_delay;

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

        int subframe_size = subframe_sizes[i];

        int pitch_lag;

        interpolate_lsp(ilspf, e->lspf, e->prev_lspf, i);

        if (e->bitrate != RATE_QUANT) {

            if (e->avg_acb_gain < 0.3) {

                idelay[0] = estimation_delay[i];

                idelay[1] = estimation_delay[i + 1];

                idelay[2] = estimation_delay[i + 2];

            } else {

                interpolate_delay(idelay, e->pitch_delay, e->prev_pitch_delay, i);

            }

        }

        pitch_lag = lrintf((idelay[1] + idelay[0]) / 2.0);

        decode_predictor_coeffs(ilspf, ilpc);

        if (e->bitrate != RATE_QUANT) {

            acb_excitation(e, e->pitch + ACB_SIZE,

                           e->avg_acb_gain, idelay, subframe_size);

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

                e->pitch[ACB_SIZE + j] *= e->fade_scale;

            e->fade_scale = FFMAX(e->fade_scale - 0.05, 0.0);

        } else {

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

                e->pitch[ACB_SIZE + j] = e->energy_vector[i];

        }

        memcpy(e->pitch, e->pitch + subframe_size, ACB_SIZE * sizeof(float));

        if (e->bitrate != RATE_QUANT && e->avg_acb_gain < 0.4) {

            f = 0.1 * e->avg_fcb_gain;

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

                e->pitch[ACB_SIZE + j] += f;

        } else if (e->bitrate == RATE_QUANT) {

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

                e->pitch[ACB_SIZE + j] = e->energy_vector[i];

        }

        synthesis_filter(e->pitch + ACB_SIZE, ilpc,

                         e->synthesis, subframe_size, tmp);

        postfilter(e, tmp, ilpc, samples, pitch_lag,

                   &postfilter_coeffs[e->bitrate], subframe_size);

        samples += subframe_size;

    }

}


void ff_mdct_calcw_c(FFTContext *s, FFTDouble *out, const FFTSample *input)

{

    int i, j, n, n8, n4, n2, n3;

    FFTDouble re, im;

    const uint16_t *revtab = s->revtab;

    const FFTSample *tcos = s->tcos;

    const FFTSample *tsin = s->tsin;

    FFTComplex *x = s->tmp_buf;

    FFTDComplex *o = (FFTDComplex *)out;

    n = 1 << s->mdct_bits;

    n2 = n >> 1;

    n4 = n >> 2;

    n8 = n >> 3;

    n3 = 3 * n4;

    /* pre rotation */

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

        re = RSCALE(-input[2*i+n3] - input[n3-1-2*i]);

        im = RSCALE(-input[n4+2*i] + input[n4-1-2*i]);

        j = revtab[i];

        CMUL(x[j].re, x[j].im, re, im, -tcos[i], tsin[i]);

        re = RSCALE( input[2*i]    - input[n2-1-2*i]);

        im = RSCALE(-input[n2+2*i] - input[ n-1-2*i]);

        j = revtab[n8 + i];

        CMUL(x[j].re, x[j].im, re, im, -tcos[n8 + i], tsin[n8 + i]);

    }

    s->fft_calc(s, x);

    /* post rotation */

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

        FFTDouble r0, i0, r1, i1;

        CMULL(i1, r0, x[n8-i-1].re, x[n8-i-1].im, -tsin[n8-i-1], -tcos[n8-i-1]);

        CMULL(i0, r1, x[n8+i  ].re, x[n8+i  ].im, -tsin[n8+i  ], -tcos[n8+i  ]);

        o[n8-i-1].re = r0;

        o[n8-i-1].im = i0;

        o[n8+i  ].re = r1;

        o[n8+i  ].im = i1;

    }

}


set_rdt(E1000State *s, int index, uint32_t val)

{

    s->check_rxov = 0;

    s->mac_reg[index] = val & 0xffff;

    if (e1000_has_rxbufs(s, 1)) {

        qemu_flush_queued_packets(&s->nic->nc);

    }

}


unsigned int s390_cpu_set_state(uint8_t cpu_state, S390CPU *cpu)

 {

    trace_cpu_set_state(CPU(cpu)->cpu_index, cpu_state);

    switch (cpu_state) {

    case CPU_STATE_STOPPED:

    case CPU_STATE_CHECK_STOP:

        /* halt the cpu for common infrastructure */

        s390_cpu_halt(cpu);

        break;

    case CPU_STATE_OPERATING:

    case CPU_STATE_LOAD:

        /* unhalt the cpu for common infrastructure */

        s390_cpu_unhalt(cpu);

        break;

    default:

        error_report("Requested CPU state is not a valid S390 CPU state: %u",

                     cpu_state);

        exit(1);

    cpu->env.cpu_state = cpu_state;

    return s390_count_running_cpus();


static int mmap_read_frame(struct video_data *s, void *frame, int64_t *ts)

{

    struct v4l2_buffer buf;

    int res;

    memset(&buf, 0, sizeof(struct v4l2_buffer));

    buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;

    buf.memory = V4L2_MEMORY_MMAP;

    /* FIXME: Some special treatment might be needed in case of loss of signal... */

    while ((res = ioctl(s->fd, VIDIOC_DQBUF, &buf)) < 0 &&

           ((errno == EAGAIN) || (errno == EINTR)));

    if (res < 0) {

        av_log(NULL, AV_LOG_ERROR, "ioctl(VIDIOC_DQBUF): %s\n", strerror(errno));

        return -1;

    }

    assert (buf.index < s->buffers);

    assert(buf.bytesused == s->frame_size);

    /* Image is at s->buff_start[buf.index] */

    memcpy(frame, s->buf_start[buf.index], buf.bytesused);

    *ts = buf.timestamp.tv_sec * int64_t_C(1000000) + buf.timestamp.tv_usec;

    res = ioctl (s->fd, VIDIOC_QBUF, &buf);

    if (res < 0) {

        av_log(NULL, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF)\n");

        return -1;

    }

    return s->buf_len[buf.index];

}


static void avc_luma_midh_qrt_4w_msa(const uint8_t *src, int32_t src_stride,

                                     uint8_t *dst, int32_t dst_stride,

                                     int32_t height, uint8_t horiz_offset)

{

    uint32_t row;

    v16i8 src0, src1, src2, src3, src4, src5, src6;

    v8i16 vt_res0, vt_res1, vt_res2, vt_res3;

    v4i32 hz_res0, hz_res1;

    v8i16 dst0, dst1;

    v8i16 shf_vec0, shf_vec1, shf_vec2, shf_vec3, shf_vec4, shf_vec5;

    v8i16 mask0 = { 0, 5, 1, 6, 2, 7, 3, 8 };

    v8i16 mask1 = { 1, 4, 2, 5, 3, 6, 4, 7 };

    v8i16 mask2 = { 2, 3, 3, 4, 4, 5, 5, 6 };

    v8i16 minus5h = __msa_ldi_h(-5);

    v8i16 plus20h = __msa_ldi_h(20);

    v8i16 zeros = { 0 };

    v16u8 out;

    LD_SB5(src, src_stride, src0, src1, src2, src3, src4);

    src += (5 * src_stride);

    XORI_B5_128_SB(src0, src1, src2, src3, src4);

    for (row = (height >> 1); row--;) {

        LD_SB2(src, src_stride, src5, src6);

        src += (2 * src_stride);

        XORI_B2_128_SB(src5, src6);

        AVC_CALC_DPADD_B_6PIX_2COEFF_SH(src0, src1, src2, src3, src4, src5,

                                        vt_res0, vt_res1);

        AVC_CALC_DPADD_B_6PIX_2COEFF_SH(src1, src2, src3, src4, src5, src6,

                                        vt_res2, vt_res3);

        VSHF_H3_SH(vt_res0, vt_res1, vt_res0, vt_res1, vt_res0, vt_res1,

                   mask0, mask1, mask2, shf_vec0, shf_vec1, shf_vec2);

        VSHF_H3_SH(vt_res2, vt_res3, vt_res2, vt_res3, vt_res2, vt_res3,

                   mask0, mask1, mask2, shf_vec3, shf_vec4, shf_vec5);

        hz_res0 = __msa_hadd_s_w(shf_vec0, shf_vec0);

        DPADD_SH2_SW(shf_vec1, shf_vec2, minus5h, plus20h, hz_res0, hz_res0);

        hz_res1 = __msa_hadd_s_w(shf_vec3, shf_vec3);

        DPADD_SH2_SW(shf_vec4, shf_vec5, minus5h, plus20h, hz_res1, hz_res1);

        SRARI_W2_SW(hz_res0, hz_res1, 10);

        SAT_SW2_SW(hz_res0, hz_res1, 7);

        dst0 = __msa_srari_h(shf_vec2, 5);

        dst1 = __msa_srari_h(shf_vec5, 5);

        SAT_SH2_SH(dst0, dst1, 7);

        if (horiz_offset) {

            dst0 = __msa_ilvod_h(zeros, dst0);

            dst1 = __msa_ilvod_h(zeros, dst1);

        } else {

            ILVEV_H2_SH(dst0, zeros, dst1, zeros, dst0, dst1);

        }

        hz_res0 = __msa_aver_s_w(hz_res0, (v4i32) dst0);

        hz_res1 = __msa_aver_s_w(hz_res1, (v4i32) dst1);

        dst0 = __msa_pckev_h((v8i16) hz_res1, (v8i16) hz_res0);

        out = PCKEV_XORI128_UB(dst0, dst0);

        ST4x2_UB(out, dst, dst_stride);

        dst += (2 * dst_stride);

        src0 = src2;

        src1 = src3;

        src2 = src4;

        src3 = src5;

        src4 = src6;

    }

}


static void e1000_io_write(void *opaque, target_phys_addr_t addr,

                           uint64_t val, unsigned size)

{

    E1000State *s = opaque;

    (void)s;

}


static void omap_clkm_init(MemoryRegion *memory, target_phys_addr_t mpu_base,

                target_phys_addr_t dsp_base, struct omap_mpu_state_s *s)

{

    memory_region_init_io(&s->clkm_iomem, &omap_clkm_ops, s,

                          "omap-clkm", 0x100);

    memory_region_init_io(&s->clkdsp_iomem, &omap_clkdsp_ops, s,

                          "omap-clkdsp", 0x1000);

    s->clkm.arm_idlect1 = 0x03ff;

    s->clkm.arm_idlect2 = 0x0100;

    s->clkm.dsp_idlect1 = 0x0002;

    omap_clkm_reset(s);

    s->clkm.cold_start = 0x3a;

    memory_region_add_subregion(memory, mpu_base, &s->clkm_iomem);

    memory_region_add_subregion(memory, dsp_base, &s->clkdsp_iomem);

}


static uint64_t bonito_pciconf_readl(void *opaque, target_phys_addr_t addr,

                                     unsigned size)

{

    PCIBonitoState *s = opaque;

    PCIDevice *d = PCI_DEVICE(s);

    DPRINTF("bonito_pciconf_readl "TARGET_FMT_plx"\n", addr);

    return d->config_read(d, addr, 4);

}


static void vdi_close(BlockDriverState *bs)

{

    BDRVVdiState *s = bs->opaque;

    g_free(s->bmap);

    migrate_del_blocker(s->migration_blocker);

    error_free(s->migration_blocker);

}


static int handle_instruction(S390CPU *cpu, struct kvm_run *run)

{

    unsigned int ipa0 = (run->s390_sieic.ipa & 0xff00);

    uint8_t ipa1 = run->s390_sieic.ipa & 0x00ff;

    int r = -1;

    DPRINTF("handle_instruction 0x%x 0x%x\n",

            run->s390_sieic.ipa, run->s390_sieic.ipb);

    switch (ipa0) {

    case IPA0_B2:

        r = handle_b2(cpu, run, ipa1);

        break;

    case IPA0_B9:

        r = handle_b9(cpu, run, ipa1);

        break;

    case IPA0_EB:

        r = handle_eb(cpu, run, run->s390_sieic.ipb & 0xff);

        break;

    case IPA0_E3:

        r = handle_e3(cpu, run, run->s390_sieic.ipb & 0xff);

        break;

    case IPA0_DIAG:

        r = handle_diag(cpu, run, run->s390_sieic.ipb);

        break;

    case IPA0_SIGP:

        r = handle_sigp(cpu, ipa1, run->s390_sieic.ipb);

        break;

    }

    if (r < 0) {

        r = 0;

        kvm_s390_program_interrupt(cpu, PGM_OPERATION);

    }

    return r;

}


static int v9fs_synth_fstat(FsContext *fs_ctx, int fid_type,

                            V9fsFidOpenState *fs, struct stat *stbuf)

{

    V9fsSynthOpenState *synth_open = fs->private;

    v9fs_synth_fill_statbuf(synth_open->node, stbuf);

    return 0;

}


static uint32_t virtio_balloon_get_features(VirtIODevice *vdev)

{

    return 0;

}


BlockDriverAIOCB *bdrv_aio_write(BlockDriverState *bs, int64_t sector_num,

                                 const uint8_t *buf, int nb_sectors,

                                 BlockDriverCompletionFunc *cb, void *opaque)

{

    BlockDriver *drv = bs->drv;

    BlockDriverAIOCB *ret;

    if (!drv)

        return NULL;

    if (bs->read_only)

        return NULL;

    if (sector_num == 0 && bs->boot_sector_enabled && nb_sectors > 0) {

        memcpy(bs->boot_sector_data, buf, 512);

    }

    ret = drv->bdrv_aio_write(bs, sector_num, buf, nb_sectors, cb, opaque);

    if (ret) {

	/* Update stats even though technically transfer has not happened. */

	bs->wr_bytes += (unsigned) nb_sectors * SECTOR_SIZE;

	bs->wr_ops ++;

    }

    return ret;

}