static void nvdimm_build_nfit(GSList *device_list, GArray *table_offsets,

                              GArray *table_data, BIOSLinker *linker)

{

    GArray *structures = nvdimm_build_device_structure(device_list);

    unsigned int header;

    acpi_add_table(table_offsets, table_data);

    /* NFIT header. */

    header = table_data->len;

    acpi_data_push(table_data, sizeof(NvdimmNfitHeader));

    /* NVDIMM device structures. */

    g_array_append_vals(table_data, structures->data, structures->len);

    build_header(linker, table_data,

                 (void *)(table_data->data + header), "NFIT",

                 sizeof(NvdimmNfitHeader) + structures->len, 1, NULL, NULL);

    g_array_free(structures, true);

}


const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src,

                                  int *dst_length, int *consumed, int length)

{

    int i, si, di;

    uint8_t *dst;

    int bufidx;

    // src[0]&0x80; // forbidden bit

    h->nal_ref_idc   = src[0] >> 5;

    h->nal_unit_type = src[0] & 0x1F;

    src++;

    length--;

#define STARTCODE_TEST                                                  \

    if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) {         \

        if (src[i + 2] != 3) {                                          \

            /* startcode, so we must be past the end */                 \

            length = i;                                                 \

        }                                                               \

        break;                                                          \

    }

#if HAVE_FAST_UNALIGNED

#define FIND_FIRST_ZERO                                                 \

    if (i > 0 && !src[i])                                               \

        i--;                                                            \

    while (src[i])                                                      \

        i++

#if HAVE_FAST_64BIT

    for (i = 0; i + 1 < length; i += 9) {

        if (!((~AV_RN64A(src + i) &

               (AV_RN64A(src + i) - 0x0100010001000101ULL)) &

              0x8000800080008080ULL))

            continue;

        FIND_FIRST_ZERO;

        STARTCODE_TEST;

        i -= 7;

    }

#else

    for (i = 0; i + 1 < length; i += 5) {

        if (!((~AV_RN32A(src + i) &

               (AV_RN32A(src + i) - 0x01000101U)) &

              0x80008080U))

            continue;

        FIND_FIRST_ZERO;

        STARTCODE_TEST;

        i -= 3;

    }

#endif

#else

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

        if (src[i])

            continue;

        if (i > 0 && src[i - 1] == 0)

            i--;

        STARTCODE_TEST;

    }

#endif

    if (i >= length - 1) { // no escaped 0

        *dst_length = length;

        *consumed   = length + 1; // +1 for the header

        return src;

    }

    // use second escape buffer for inter data

    bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0;

    av_fast_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx],

                   length + FF_INPUT_BUFFER_PADDING_SIZE);

    dst = h->rbsp_buffer[bufidx];

    if (dst == NULL)

        return NULL;

    memcpy(dst, src, i);

    si = di = i;

    while (si + 2 < length) {

        // remove escapes (very rare 1:2^22)

        if (src[si + 2] > 3) {

            dst[di++] = src[si++];

            dst[di++] = src[si++];

        } else if (src[si] == 0 && src[si + 1] == 0) {

            if (src[si + 2] == 3) { // escape

                dst[di++]  = 0;

                dst[di++]  = 0;

                si        += 3;

                continue;

            } else // next start code

                goto nsc;

        }

        dst[di++] = src[si++];

    }

    while (si < length)

        dst[di++] = src[si++];

nsc:

    memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);

    *dst_length = di;

    *consumed   = si + 1; // +1 for the header

    /* FIXME store exact number of bits in the getbitcontext

     * (it is needed for decoding) */

    return dst;

}


static coroutine_fn int qcow2_co_writev(BlockDriverState *bs,

                           int64_t sector_num,

                           int remaining_sectors,

                           QEMUIOVector *qiov)

{

    BDRVQcowState *s = bs->opaque;

    int index_in_cluster;

    int ret;

    int cur_nr_sectors; /* number of sectors in current iteration */

    uint64_t cluster_offset;

    QEMUIOVector hd_qiov;

    uint64_t bytes_done = 0;

    uint8_t *cluster_data = NULL;

    QCowL2Meta *l2meta = NULL;

    trace_qcow2_writev_start_req(qemu_coroutine_self(), sector_num,

                                 remaining_sectors);

    qemu_iovec_init(&hd_qiov, qiov->niov);

    s->cluster_cache_offset = -1; /* disable compressed cache */

    qemu_co_mutex_lock(&s->lock);

    while (remaining_sectors != 0) {

        l2meta = NULL;

        trace_qcow2_writev_start_part(qemu_coroutine_self());

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

        cur_nr_sectors = remaining_sectors;

        if (s->crypt_method &&

            cur_nr_sectors >

            QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster) {

            cur_nr_sectors =

                QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster;

        }

        ret = qcow2_alloc_cluster_offset(bs, sector_num << 9,

            &cur_nr_sectors, &cluster_offset, &l2meta);

        if (ret < 0) {

            goto fail;

        }

        assert((cluster_offset & 511) == 0);

        qemu_iovec_reset(&hd_qiov);

        qemu_iovec_concat(&hd_qiov, qiov, bytes_done,

            cur_nr_sectors * 512);

        if (s->crypt_method) {

            if (!cluster_data) {

                cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS *

                                                 s->cluster_size);

            }

            assert(hd_qiov.size <=

                   QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);

            qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);

            qcow2_encrypt_sectors(s, sector_num, cluster_data,

                cluster_data, cur_nr_sectors, 1, &s->aes_encrypt_key);

            qemu_iovec_reset(&hd_qiov);

            qemu_iovec_add(&hd_qiov, cluster_data,

                cur_nr_sectors * 512);

        }

        ret = qcow2_pre_write_overlap_check(bs, 0,

                cluster_offset + index_in_cluster * BDRV_SECTOR_SIZE,

                cur_nr_sectors * BDRV_SECTOR_SIZE);

        if (ret < 0) {

            goto fail;

        }

        qemu_co_mutex_unlock(&s->lock);

        BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);

        trace_qcow2_writev_data(qemu_coroutine_self(),

                                (cluster_offset >> 9) + index_in_cluster);

        ret = bdrv_co_writev(bs->file,

                             (cluster_offset >> 9) + index_in_cluster,

                             cur_nr_sectors, &hd_qiov);

        qemu_co_mutex_lock(&s->lock);

        if (ret < 0) {

            goto fail;

        }

        while (l2meta != NULL) {

            QCowL2Meta *next;

            ret = qcow2_alloc_cluster_link_l2(bs, l2meta);

            if (ret < 0) {

                goto fail;

            }

            /* Take the request off the list of running requests */

            if (l2meta->nb_clusters != 0) {

                QLIST_REMOVE(l2meta, next_in_flight);

            }

            qemu_co_queue_restart_all(&l2meta->dependent_requests);

            next = l2meta->next;

            g_free(l2meta);

            l2meta = next;

        }

        remaining_sectors -= cur_nr_sectors;

        sector_num += cur_nr_sectors;

        bytes_done += cur_nr_sectors * 512;

        trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_nr_sectors);

    }

    ret = 0;

fail:

    qemu_co_mutex_unlock(&s->lock);

    while (l2meta != NULL) {

        QCowL2Meta *next;

        if (l2meta->nb_clusters != 0) {

            QLIST_REMOVE(l2meta, next_in_flight);

        }

        qemu_co_queue_restart_all(&l2meta->dependent_requests);

        next = l2meta->next;

        g_free(l2meta);

        l2meta = next;

    }

    qemu_iovec_destroy(&hd_qiov);

    qemu_vfree(cluster_data);

    trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);

    return ret;

}


do_send_recv(int sockfd, struct iovec *iov, unsigned iov_cnt, bool do_send)

{

#if defined CONFIG_IOVEC && defined CONFIG_POSIX

    ssize_t ret;

    struct msghdr msg;

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

    msg.msg_iov = iov;

    msg.msg_iovlen = iov_cnt;

    do {

        ret = do_send

            ? sendmsg(sockfd, &msg, 0)

            : recvmsg(sockfd, &msg, 0);

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

    return ret;

#else

    /* else send piece-by-piece */

    /*XXX Note: windows has WSASend() and WSARecv() */

    unsigned i = 0;

    ssize_t ret = 0;

    while (i < iov_cnt) {

        ssize_t r = do_send

            ? send(sockfd, iov[i].iov_base, iov[i].iov_len, 0)

            : recv(sockfd, iov[i].iov_base, iov[i].iov_len, 0);

        if (r > 0) {

            ret += r;

        } else if (!r) {

            break;

        } else if (errno == EINTR) {

            continue;

        } else {

            /* else it is some "other" error,

             * only return if there was no data processed. */

            if (ret == 0) {

                ret = -1;

            }

            break;

        }

        i++;

    }

    return ret;

#endif

}


START_TEST(keyword_literal)

{

    QObject *obj;

    QBool *qbool;

    QString *str;

    obj = qobject_from_json("true");

    fail_unless(obj != NULL);

    fail_unless(qobject_type(obj) == QTYPE_QBOOL);

    qbool = qobject_to_qbool(obj);

    fail_unless(qbool_get_int(qbool) != 0);

    str = qobject_to_json(obj);

    fail_unless(strcmp(qstring_get_str(str), "true") == 0);

    QDECREF(str);

    QDECREF(qbool);

    obj = qobject_from_json("false");

    fail_unless(obj != NULL);

    fail_unless(qobject_type(obj) == QTYPE_QBOOL);

    qbool = qobject_to_qbool(obj);

    fail_unless(qbool_get_int(qbool) == 0);

    str = qobject_to_json(obj);

    fail_unless(strcmp(qstring_get_str(str), "false") == 0);

    QDECREF(str);

    QDECREF(qbool);

    obj = qobject_from_jsonf("%i", false);

    fail_unless(obj != NULL);

    fail_unless(qobject_type(obj) == QTYPE_QBOOL);

    qbool = qobject_to_qbool(obj);

    fail_unless(qbool_get_int(qbool) == 0);

    QDECREF(qbool);

    obj = qobject_from_jsonf("%i", true);

    fail_unless(obj != NULL);

    fail_unless(qobject_type(obj) == QTYPE_QBOOL);

    qbool = qobject_to_qbool(obj);

    fail_unless(qbool_get_int(qbool) != 0);

    QDECREF(qbool);

}


static int handle_sigp_single_dst(S390CPU *dst_cpu, uint8_t order,

                                  uint64_t param, uint64_t *status_reg)

{

    SigpInfo si = {

        .param = param,

        .status_reg = status_reg,

    };

    /* cpu available? */

    if (dst_cpu == NULL) {

        return SIGP_CC_NOT_OPERATIONAL;

    }

    /* only resets can break pending orders */

    if (dst_cpu->env.sigp_order != 0 &&

        order != SIGP_CPU_RESET &&

        order != SIGP_INITIAL_CPU_RESET) {

        return SIGP_CC_BUSY;

    }

    switch (order) {

    case SIGP_START:

        run_on_cpu(CPU(dst_cpu), sigp_start, RUN_ON_CPU_HOST_PTR(&si));

        break;

    case SIGP_STOP:

        run_on_cpu(CPU(dst_cpu), sigp_stop, RUN_ON_CPU_HOST_PTR(&si));

        break;

    case SIGP_RESTART:

        run_on_cpu(CPU(dst_cpu), sigp_restart, RUN_ON_CPU_HOST_PTR(&si));

        break;

    case SIGP_STOP_STORE_STATUS:

        run_on_cpu(CPU(dst_cpu), sigp_stop_and_store_status, RUN_ON_CPU_HOST_PTR(&si));

        break;

    case SIGP_STORE_STATUS_ADDR:

        run_on_cpu(CPU(dst_cpu), sigp_store_status_at_address, RUN_ON_CPU_HOST_PTR(&si));

        break;

    case SIGP_STORE_ADTL_STATUS:

        run_on_cpu(CPU(dst_cpu), sigp_store_adtl_status, RUN_ON_CPU_HOST_PTR(&si));

        break;

    case SIGP_SET_PREFIX:

        run_on_cpu(CPU(dst_cpu), sigp_set_prefix, RUN_ON_CPU_HOST_PTR(&si));

        break;

    case SIGP_INITIAL_CPU_RESET:

        run_on_cpu(CPU(dst_cpu), sigp_initial_cpu_reset, RUN_ON_CPU_HOST_PTR(&si));

        break;

    case SIGP_CPU_RESET:

        run_on_cpu(CPU(dst_cpu), sigp_cpu_reset, RUN_ON_CPU_HOST_PTR(&si));

        break;

    default:

        set_sigp_status(&si, SIGP_STAT_INVALID_ORDER);

    }

    return si.cc;

}


static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,

                           GetBitContext *gb)

{

    if (get_bits1(gb)) {

        av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n");

        return AVERROR_INVALIDDATA;

    }

    ics->window_sequence[1] = ics->window_sequence[0];

    ics->window_sequence[0] = get_bits(gb, 2);

    ics->use_kb_window[1]   = ics->use_kb_window[0];

    ics->use_kb_window[0]   = get_bits1(gb);

    ics->num_window_groups  = 1;

    ics->group_len[0]       = 1;

    if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {

        int i;

        ics->max_sfb = get_bits(gb, 4);

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

            if (get_bits1(gb)) {

                ics->group_len[ics->num_window_groups - 1]++;

            } else {

                ics->num_window_groups++;

                ics->group_len[ics->num_window_groups - 1] = 1;

            }

        }

        ics->num_windows       = 8;

        ics->swb_offset        =    ff_swb_offset_128[ac->m4ac.sampling_index];

        ics->num_swb           =   ff_aac_num_swb_128[ac->m4ac.sampling_index];

        ics->tns_max_bands     = ff_tns_max_bands_128[ac->m4ac.sampling_index];

        ics->predictor_present = 0;

    } else {

        ics->max_sfb               = get_bits(gb, 6);

        ics->num_windows           = 1;

        ics->swb_offset            =    ff_swb_offset_1024[ac->m4ac.sampling_index];

        ics->num_swb               =   ff_aac_num_swb_1024[ac->m4ac.sampling_index];

        ics->tns_max_bands         = ff_tns_max_bands_1024[ac->m4ac.sampling_index];

        ics->predictor_present     = get_bits1(gb);

        ics->predictor_reset_group = 0;

        if (ics->predictor_present) {

            if (ac->m4ac.object_type == AOT_AAC_MAIN) {

                if (decode_prediction(ac, ics, gb)) {

                    return AVERROR_INVALIDDATA;

                }

            } else if (ac->m4ac.object_type == AOT_AAC_LC) {

                av_log(ac->avctx, AV_LOG_ERROR, "Prediction is not allowed in AAC-LC.\n");

                return AVERROR_INVALIDDATA;

            } else {

                if ((ics->ltp.present = get_bits(gb, 1)))

                    decode_ltp(ac, &ics->ltp, gb, ics->max_sfb);

            }

        }

    }

    if (ics->max_sfb > ics->num_swb) {

        av_log(ac->avctx, AV_LOG_ERROR,

               "Number of scalefactor bands in group (%d) exceeds limit (%d).\n",

               ics->max_sfb, ics->num_swb);

        return AVERROR_INVALIDDATA;

    }

    return 0;

}


long do_rt_sigreturn(CPUAlphaState *env)

{

    abi_ulong frame_addr = env->ir[IR_A0];

    struct target_rt_sigframe *frame;

    sigset_t set;

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

        goto badframe;

    }

    target_to_host_sigset(&set, &frame->uc.tuc_sigmask);

    do_sigprocmask(SIG_SETMASK, &set, NULL);

    if (restore_sigcontext(env, &frame->uc.tuc_mcontext)) {

        goto badframe;

    }

    if (do_sigaltstack(frame_addr + offsetof(struct target_rt_sigframe,

                                             uc.tuc_stack),

                       0, env->ir[IR_SP]) == -EFAULT) {

        goto badframe;

    }

    unlock_user_struct(frame, frame_addr, 0);

    return env->ir[IR_V0];

 badframe:

    unlock_user_struct(frame, frame_addr, 0);

    force_sig(TARGET_SIGSEGV);

}


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

{

    char tmp_key[5];

    char key2[32], language[4] = {0};

    char *str = NULL;

    const char *key = NULL;

    uint16_t langcode = 0;

    uint32_t data_type = 0, str_size, str_size_alloc;

    int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;

    int raw = 0;

    int num = 0;

    switch (atom.type) {

    case MKTAG( '@','P','R','M'): key = "premiere_version"; raw = 1; break;

    case MKTAG( '@','P','R','Q'): key = "quicktime_version"; raw = 1; break;

    case MKTAG( 'X','M','P','_'):

        if (c->export_xmp) { key = "xmp"; raw = 1; } break;

    case MKTAG( 'a','A','R','T'): key = "album_artist";    break;

    case MKTAG( 'a','k','I','D'): key = "account_type";

        parse = mov_metadata_int8_no_padding; break;

    case MKTAG( 'a','p','I','D'): key = "account_id"; break;

    case MKTAG( 'c','a','t','g'): key = "category"; break;

    case MKTAG( 'c','p','i','l'): key = "compilation";

        parse = mov_metadata_int8_no_padding; break;

    case MKTAG( 'c','p','r','t'): key = "copyright"; break;

    case MKTAG( 'd','e','s','c'): key = "description"; break;

    case MKTAG( 'd','i','s','k'): key = "disc";

        parse = mov_metadata_track_or_disc_number; break;

    case MKTAG( 'e','g','i','d'): key = "episode_uid";

        parse = mov_metadata_int8_no_padding; break;

    case MKTAG( 'g','n','r','e'): key = "genre";

        parse = mov_metadata_gnre; break;

    case MKTAG( 'h','d','v','d'): key = "hd_video";

        parse = mov_metadata_int8_no_padding; break;

    case MKTAG( 'k','e','y','w'): key = "keywords";  break;

    case MKTAG( 'l','d','e','s'): key = "synopsis";  break;

    case MKTAG( 'l','o','c','i'):

        return mov_metadata_loci(c, pb, atom.size);

    case MKTAG( 'p','c','s','t'): key = "podcast";

        parse = mov_metadata_int8_no_padding; break;

    case MKTAG( 'p','g','a','p'): key = "gapless_playback";

        parse = mov_metadata_int8_no_padding; break;

    case MKTAG( 'p','u','r','d'): key = "purchase_date"; break;

    case MKTAG( 'r','t','n','g'): key = "rating";

        parse = mov_metadata_int8_no_padding; break;

    case MKTAG( 's','o','a','a'): key = "sort_album_artist"; break;

    case MKTAG( 's','o','a','l'): key = "sort_album";   break;

    case MKTAG( 's','o','a','r'): key = "sort_artist";  break;

    case MKTAG( 's','o','c','o'): key = "sort_composer"; break;

    case MKTAG( 's','o','n','m'): key = "sort_name";    break;

    case MKTAG( 's','o','s','n'): key = "sort_show";    break;

    case MKTAG( 's','t','i','k'): key = "media_type";

        parse = mov_metadata_int8_no_padding; break;

    case MKTAG( 't','r','k','n'): key = "track";

        parse = mov_metadata_track_or_disc_number; break;

    case MKTAG( 't','v','e','n'): key = "episode_id"; break;

    case MKTAG( 't','v','e','s'): key = "episode_sort";

        parse = mov_metadata_int8_bypass_padding; break;

    case MKTAG( 't','v','n','n'): key = "network";   break;

    case MKTAG( 't','v','s','h'): key = "show";      break;

    case MKTAG( 't','v','s','n'): key = "season_number";

        parse = mov_metadata_int8_bypass_padding; break;

    case MKTAG(0xa9,'A','R','T'): key = "artist";    break;

    case MKTAG(0xa9,'P','R','D'): key = "producer";  break;

    case MKTAG(0xa9,'a','l','b'): key = "album";     break;

    case MKTAG(0xa9,'a','u','t'): key = "artist";    break;

    case MKTAG(0xa9,'c','h','p'): key = "chapter";   break;

    case MKTAG(0xa9,'c','m','t'): key = "comment";   break;

    case MKTAG(0xa9,'c','o','m'): key = "composer";  break;

    case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;

    case MKTAG(0xa9,'d','a','y'): key = "date";      break;

    case MKTAG(0xa9,'d','i','r'): key = "director";  break;

    case MKTAG(0xa9,'d','i','s'): key = "disclaimer"; break;

    case MKTAG(0xa9,'e','d','1'): key = "edit_date"; break;

    case MKTAG(0xa9,'e','n','c'): key = "encoder";   break;

    case MKTAG(0xa9,'f','m','t'): key = "original_format"; break;

    case MKTAG(0xa9,'g','e','n'): key = "genre";     break;

    case MKTAG(0xa9,'g','r','p'): key = "grouping";  break;

    case MKTAG(0xa9,'h','s','t'): key = "host_computer"; break;

    case MKTAG(0xa9,'i','n','f'): key = "comment";   break;

    case MKTAG(0xa9,'l','y','r'): key = "lyrics";    break;

    case MKTAG(0xa9,'m','a','k'): key = "make";      break;

    case MKTAG(0xa9,'m','o','d'): key = "model";     break;

    case MKTAG(0xa9,'n','a','m'): key = "title";     break;

    case MKTAG(0xa9,'o','p','e'): key = "original_artist"; break;

    case MKTAG(0xa9,'p','r','d'): key = "producer";  break;

    case MKTAG(0xa9,'p','r','f'): key = "performers"; break;

    case MKTAG(0xa9,'r','e','q'): key = "playback_requirements"; break;

    case MKTAG(0xa9,'s','r','c'): key = "original_source"; break;

    case MKTAG(0xa9,'s','t','3'): key = "subtitle";  break;

    case MKTAG(0xa9,'s','w','r'): key = "encoder";   break;

    case MKTAG(0xa9,'t','o','o'): key = "encoder";   break;

    case MKTAG(0xa9,'t','r','k'): key = "track";     break;

    case MKTAG(0xa9,'u','r','l'): key = "URL";       break;

    case MKTAG(0xa9,'w','r','n'): key = "warning";   break;

    case MKTAG(0xa9,'w','r','t'): key = "composer";  break;

    case MKTAG(0xa9,'x','y','z'): key = "location";  break;

    }

retry:

    if (c->itunes_metadata && atom.size > 8) {

        int data_size = avio_rb32(pb);

        int tag = avio_rl32(pb);

        if (tag == MKTAG('d','a','t','a') && data_size <= atom.size) {

            data_type = avio_rb32(pb); // type

            avio_rb32(pb); // unknown

            str_size = data_size - 16;

            atom.size -= 16;

            if (atom.type == MKTAG('c', 'o', 'v', 'r')) {

                int ret = mov_read_covr(c, pb, data_type, str_size);

                if (ret < 0) {

                    av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");

                }

                return ret;

            } else if (!key && c->found_hdlr_mdta && c->meta_keys) {

                uint32_t index = AV_RB32(&atom.type);

                if (index < c->meta_keys_count) {

                    key = c->meta_keys[index];

                } else {

                    av_log(c->fc, AV_LOG_WARNING,

                           "The index of 'data' is out of range: %d >= %d.\n",

                           index, c->meta_keys_count);

                }

            }

        } else return 0;

    } else if (atom.size > 4 && key && !c->itunes_metadata && !raw) {

        str_size = avio_rb16(pb); // string length

        if (str_size > atom.size) {

            raw = 1;

            avio_seek(pb, -2, SEEK_CUR);

            av_log(c->fc, AV_LOG_WARNING, "UDTA parsing failed retrying raw\n");

            goto retry;

        }

        langcode = avio_rb16(pb);

        ff_mov_lang_to_iso639(langcode, language);

        atom.size -= 4;

    } else

        str_size = atom.size;

    if (c->export_all && !key) {

        snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);

        key = tmp_key;

    }

    if (!key)

        return 0;

    if (atom.size < 0 || str_size >= INT_MAX/2)

        return AVERROR_INVALIDDATA;

    // Allocates enough space if data_type is a float32 number, otherwise

    // worst-case requirement for output string in case of utf8 coded input

    num = (data_type == 23);

    str_size_alloc = (num ? 512 : (raw ? str_size : str_size * 2)) + 1;

    str = av_mallocz(str_size_alloc);

    if (!str)

        return AVERROR(ENOMEM);

    if (parse)

        parse(c, pb, str_size, key);

    else {

        if (!raw && (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff)))) { // MAC Encoded

            mov_read_mac_string(c, pb, str_size, str, str_size_alloc);

        } else if (data_type == 23 && str_size >= 4) {  // BE float32

            float val = av_int2float(avio_rb32(pb));

            if (snprintf(str, str_size_alloc, "%f", val) >= str_size_alloc) {

                av_log(c->fc, AV_LOG_ERROR,

                       "Failed to store the float32 number (%f) in string.\n", val);

                return AVERROR_INVALIDDATA;

            }

        } else {

            int ret = ffio_read_size(pb, str, str_size);

            if (ret < 0) {

                return ret;

            }

            str[str_size] = 0;

        }

        c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;

        av_dict_set(&c->fc->metadata, key, str, 0);

        if (*language && strcmp(language, "und")) {

            snprintf(key2, sizeof(key2), "%s-%s", key, language);

            av_dict_set(&c->fc->metadata, key2, str, 0);

        }

    }

    av_log(c->fc, AV_LOG_TRACE, "lang \"%3s\" ", language);

    av_log(c->fc, AV_LOG_TRACE, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",

            key, str, (char*)&atom.type, str_size_alloc, atom.size);

    av_freep(&str);

    return 0;

}


static void cortex_a9_initfn(Object *obj)

{

    ARMCPU *cpu = ARM_CPU(obj);

    cpu->dtb_compatible = "arm,cortex-a9";

    set_feature(&cpu->env, ARM_FEATURE_V7);

    set_feature(&cpu->env, ARM_FEATURE_VFP3);

    set_feature(&cpu->env, ARM_FEATURE_VFP_FP16);

    set_feature(&cpu->env, ARM_FEATURE_NEON);

    set_feature(&cpu->env, ARM_FEATURE_THUMB2EE);

    /* Note that A9 supports the MP extensions even for

     * A9UP and single-core A9MP (which are both different

     * and valid configurations; we don't model A9UP).

     */

    set_feature(&cpu->env, ARM_FEATURE_V7MP);

    set_feature(&cpu->env, ARM_FEATURE_CBAR);

    cpu->midr = 0x410fc090;

    cpu->reset_fpsid = 0x41033090;

    cpu->mvfr0 = 0x11110222;

    cpu->mvfr1 = 0x01111111;

    cpu->ctr = 0x80038003;

    cpu->reset_sctlr = 0x00c50078;

    cpu->id_pfr0 = 0x1031;

    cpu->id_pfr1 = 0x11;

    cpu->id_dfr0 = 0x000;

    cpu->id_afr0 = 0;

    cpu->id_mmfr0 = 0x00100103;

    cpu->id_mmfr1 = 0x20000000;

    cpu->id_mmfr2 = 0x01230000;

    cpu->id_mmfr3 = 0x00002111;

    cpu->id_isar0 = 0x00101111;

    cpu->id_isar1 = 0x13112111;

    cpu->id_isar2 = 0x21232041;

    cpu->id_isar3 = 0x11112131;

    cpu->id_isar4 = 0x00111142;

    cpu->dbgdidr = 0x35141000;

    cpu->clidr = (1 << 27) | (1 << 24) | 3;

    cpu->ccsidr[0] = 0xe00fe015; /* 16k L1 dcache. */

    cpu->ccsidr[1] = 0x200fe015; /* 16k L1 icache. */

    define_arm_cp_regs(cpu, cortexa9_cp_reginfo);

}


static void bt_hci_reset(struct bt_hci_s *hci)

{

    hci->acl_len = 0;

    hci->last_cmd = 0;

    hci->lm.connecting = 0;

    hci->event_mask[0] = 0xff;

    hci->event_mask[1] = 0xff;

    hci->event_mask[2] = 0xff;

    hci->event_mask[3] = 0xff;

    hci->event_mask[4] = 0xff;

    hci->event_mask[5] = 0x1f;

    hci->event_mask[6] = 0x00;

    hci->event_mask[7] = 0x00;

    hci->device.inquiry_scan = 0;

    hci->device.page_scan = 0;

    if (hci->device.lmp_name)

        g_free((void *) hci->device.lmp_name);

    hci->device.lmp_name = NULL;

    hci->device.class[0] = 0x00;

    hci->device.class[1] = 0x00;

    hci->device.class[2] = 0x00;

    hci->voice_setting = 0x0000;

    hci->conn_accept_tout = 0x1f40;

    hci->lm.inquiry_mode = 0x00;

    hci->psb_handle = 0x000;

    hci->asb_handle = 0x000;

    /* XXX: timer_del(sl->acl_mode_timer); for all links */

    timer_del(hci->lm.inquiry_done);

    timer_del(hci->lm.inquiry_next);

    timer_del(hci->conn_accept_timer);

}


static void net_tx_pkt_do_sw_csum(struct NetTxPkt *pkt)

{

    struct iovec *iov = &pkt->vec[NET_TX_PKT_L2HDR_FRAG];

    uint32_t csum_cntr;

    uint16_t csum = 0;

    /* num of iovec without vhdr */

    uint32_t iov_len = pkt->payload_frags + NET_TX_PKT_PL_START_FRAG - 1;

    uint16_t csl;

    struct ip_header *iphdr;

    size_t csum_offset = pkt->virt_hdr.csum_start + pkt->virt_hdr.csum_offset;

    /* Put zero to checksum field */

    iov_from_buf(iov, iov_len, csum_offset, &csum, sizeof csum);

    /* Calculate L4 TCP/UDP checksum */

    csl = pkt->payload_len;

    /* data checksum */

    csum_cntr =

        net_checksum_add_iov(iov, iov_len, pkt->virt_hdr.csum_start, csl);

    /* add pseudo header to csum */

    iphdr = pkt->vec[NET_TX_PKT_L3HDR_FRAG].iov_base;

    csum_cntr += eth_calc_pseudo_hdr_csum(iphdr, csl);

    /* Put the checksum obtained into the packet */

    csum = cpu_to_be16(net_checksum_finish(csum_cntr));

    iov_from_buf(iov, iov_len, csum_offset, &csum, sizeof csum);

}


void apic_reset_irq_delivered(void)

{

    trace_apic_reset_irq_delivered(apic_irq_delivered);

    apic_irq_delivered = 0;

}


static TAPState *net_tap_fd_init(VLANState *vlan, int fd)

{

    TAPState *s;

    s = qemu_mallocz(sizeof(TAPState));

    if (!s)

        return NULL;

    s->fd = fd;

    s->vc = qemu_new_vlan_client(vlan, tap_receive, s);

    qemu_set_fd_handler(s->fd, tap_send, NULL, s);

    snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);

    return s;

}


static void mov_text_style_cb(void *priv, const char style, int close)

{

    MovTextContext *s = priv;

    if (!close) {

        if (!(s->box_flags & STYL_BOX)) {   //first style entry

            s->style_attributes_temp = av_malloc(sizeof(*s->style_attributes_temp));

            if (!s->style_attributes_temp) {

                av_bprint_clear(&s->buffer);

                s->box_flags &= ~STYL_BOX;

            }

            s->style_attributes_temp->style_flag = 0;

            s->style_attributes_temp->style_start = AV_RB16(&s->text_pos);

        } else {

            if (s->style_attributes_temp->style_flag) { //break the style record here and start a new one

                s->style_attributes_temp->style_end = AV_RB16(&s->text_pos);

                av_dynarray_add(&s->style_attributes, &s->count, s->style_attributes_temp);

                s->style_attributes_temp = av_malloc(sizeof(*s->style_attributes_temp));

                if (!s->style_attributes_temp) {

                    mov_text_cleanup(s);

                    av_bprint_clear(&s->buffer);

                    s->box_flags &= ~STYL_BOX;

                }

                s->style_attributes_temp->style_flag = s->style_attributes[s->count - 1]->style_flag;

                s->style_attributes_temp->style_start = AV_RB16(&s->text_pos);

            } else {

                s->style_attributes_temp->style_flag = 0;

                s->style_attributes_temp->style_start = AV_RB16(&s->text_pos);

            }

        }

        switch (style){

        case 'b':

            s->style_attributes_temp->style_flag |= STYLE_FLAG_BOLD;

            break;

        case 'i':

            s->style_attributes_temp->style_flag |= STYLE_FLAG_ITALIC;

            break;

        case 'u':

            s->style_attributes_temp->style_flag |= STYLE_FLAG_UNDERLINE;

            break;

        }

    } else {

        s->style_attributes_temp->style_end = AV_RB16(&s->text_pos);

        av_dynarray_add(&s->style_attributes, &s->count, s->style_attributes_temp);

        s->style_attributes_temp = av_malloc(sizeof(*s->style_attributes_temp));

        if (!s->style_attributes_temp) {

            mov_text_cleanup(s);

            av_bprint_clear(&s->buffer);

            s->box_flags &= ~STYL_BOX;

        }

        s->style_attributes_temp->style_flag = s->style_attributes[s->count - 1]->style_flag;

        switch (style){

        case 'b':

            s->style_attributes_temp->style_flag &= ~STYLE_FLAG_BOLD;

            break;

        case 'i':

            s->style_attributes_temp->style_flag &= ~STYLE_FLAG_ITALIC;

            break;

        case 'u':

            s->style_attributes_temp->style_flag &= ~STYLE_FLAG_UNDERLINE;

            break;

        }

        if (s->style_attributes_temp->style_flag) { //start of new style record

            s->style_attributes_temp->style_start = AV_RB16(&s->text_pos);

        }

    }

    s->box_flags |= STYL_BOX;

}


int qcow2_check_metadata_overlap(BlockDriverState *bs, int chk, int64_t offset,

                                 int64_t size)

{

    BDRVQcowState *s = bs->opaque;

    int i, j;

    if (!size) {

        return 0;

    }

    if (chk & QCOW2_OL_MAIN_HEADER) {

        if (offset < s->cluster_size) {

            return QCOW2_OL_MAIN_HEADER;

        }

    }

    /* align range to test to cluster boundaries */

    size = align_offset(offset_into_cluster(s, offset) + size, s->cluster_size);

    offset = start_of_cluster(s, offset);

    if ((chk & QCOW2_OL_ACTIVE_L1) && s->l1_size) {

        if (overlaps_with(s->l1_table_offset, s->l1_size * sizeof(uint64_t))) {

            return QCOW2_OL_ACTIVE_L1;

        }

    }

    if ((chk & QCOW2_OL_REFCOUNT_TABLE) && s->refcount_table_size) {

        if (overlaps_with(s->refcount_table_offset,

            s->refcount_table_size * sizeof(uint64_t))) {

            return QCOW2_OL_REFCOUNT_TABLE;

        }

    }

    if ((chk & QCOW2_OL_SNAPSHOT_TABLE) && s->snapshots_size) {

        if (overlaps_with(s->snapshots_offset, s->snapshots_size)) {

            return QCOW2_OL_SNAPSHOT_TABLE;

        }

    }

    if ((chk & QCOW2_OL_INACTIVE_L1) && s->snapshots) {

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

            if (s->snapshots[i].l1_size &&

                overlaps_with(s->snapshots[i].l1_table_offset,

                s->snapshots[i].l1_size * sizeof(uint64_t))) {

                return QCOW2_OL_INACTIVE_L1;

            }

        }

    }

    if ((chk & QCOW2_OL_ACTIVE_L2) && s->l1_table) {

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

            if ((s->l1_table[i] & L1E_OFFSET_MASK) &&

                overlaps_with(s->l1_table[i] & L1E_OFFSET_MASK,

                s->cluster_size)) {

                return QCOW2_OL_ACTIVE_L2;

            }

        }

    }

    if ((chk & QCOW2_OL_REFCOUNT_BLOCK) && s->refcount_table) {

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

            if ((s->refcount_table[i] & REFT_OFFSET_MASK) &&

                overlaps_with(s->refcount_table[i] & REFT_OFFSET_MASK,

                s->cluster_size)) {

                return QCOW2_OL_REFCOUNT_BLOCK;

            }

        }

    }

    if ((chk & QCOW2_OL_INACTIVE_L2) && s->snapshots) {

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

            uint64_t l1_ofs = s->snapshots[i].l1_table_offset;

            uint32_t l1_sz  = s->snapshots[i].l1_size;

            uint64_t l1_sz2 = l1_sz * sizeof(uint64_t);

            uint64_t *l1 = g_malloc(l1_sz2);

            int ret;

            ret = bdrv_pread(bs->file, l1_ofs, l1, l1_sz2);

            if (ret < 0) {

                g_free(l1);

                return ret;

            }

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

                uint64_t l2_ofs = be64_to_cpu(l1[j]) & L1E_OFFSET_MASK;

                if (l2_ofs && overlaps_with(l2_ofs, s->cluster_size)) {

                    g_free(l1);

                    return QCOW2_OL_INACTIVE_L2;

                }

            }

            g_free(l1);

        }

    }

    return 0;

}


static int compute_pkt_fields2(AVStream *st, AVPacket *pkt){

    int delay = FFMAX(st->codec->has_b_frames, !!st->codec->max_b_frames);

    int num, den, frame_size, i;

//    av_log(st->codec, AV_LOG_DEBUG, "av_write_frame: pts:%"PRId64" dts:%"PRId64" cur_dts:%"PRId64" b:%d size:%d st:%d\n", pkt->pts, pkt->dts, st->cur_dts, delay, pkt->size, pkt->stream_index);

/*    if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)

        return -1;*/

    /* duration field */

    if (pkt->duration == 0) {

        compute_frame_duration(&num, &den, st, NULL, pkt);

        if (den && num) {

            pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);

        }

    }

    if(pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay==0)

        pkt->pts= pkt->dts;

    //XXX/FIXME this is a temporary hack until all encoders output pts

    if((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay){

        pkt->dts=

//        pkt->pts= st->cur_dts;

        pkt->pts= st->pts.val;

    }

    //calculate dts from pts

    if(pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE){

        st->pts_buffer[0]= pkt->pts;

        for(i=1; i<delay+1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)

            st->pts_buffer[i]= (i-delay-1) * pkt->duration;

        for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)

            FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);

        pkt->dts= st->pts_buffer[0];

    }

    if(st->cur_dts && st->cur_dts != AV_NOPTS_VALUE && st->cur_dts >= pkt->dts){

        av_log(st->codec, AV_LOG_ERROR, "error, non monotone timestamps %"PRId64" >= %"PRId64"\n", st->cur_dts, pkt->dts);

        return -1;

    }

    if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts){

        av_log(st->codec, AV_LOG_ERROR, "error, pts < dts\n");

        return -1;

    }

//    av_log(NULL, AV_LOG_DEBUG, "av_write_frame: pts2:%"PRId64" dts2:%"PRId64"\n", pkt->pts, pkt->dts);

    st->cur_dts= pkt->dts;

    st->pts.val= pkt->dts;

    /* update pts */

    switch (st->codec->codec_type) {

    case CODEC_TYPE_AUDIO:

        frame_size = get_audio_frame_size(st->codec, pkt->size);

        /* HACK/FIXME, we skip the initial 0 size packets as they are most

           likely equal to the encoder delay, but it would be better if we

           had the real timestamps from the encoder */

        if (frame_size >= 0 && (pkt->size || st->pts.num!=st->pts.den>>1 || st->pts.val)) {

            av_frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);

        }

        break;

    case CODEC_TYPE_VIDEO:

        av_frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);

        break;

    default:

        break;

    }

    return 0;

}


static int dnxhd_encode_fast(AVCodecContext *avctx, DNXHDEncContext *ctx)

{

    int max_bits = 0;

    int ret, x, y;

    if ((ret = dnxhd_find_qscale(ctx)) < 0)

        return ret;

    for (y = 0; y < ctx->m.mb_height; y++) {

        for (x = 0; x < ctx->m.mb_width; x++) {

            int mb = y * ctx->m.mb_width + x;

            int rc = (ctx->qscale * ctx->m.mb_num ) + mb;

            int delta_bits;

            ctx->mb_qscale[mb] = ctx->qscale;

            ctx->mb_bits[mb] = ctx->mb_rc[rc].bits;

            max_bits += ctx->mb_rc[rc].bits;

            if (!RC_VARIANCE) {

                delta_bits = ctx->mb_rc[rc].bits -

                             ctx->mb_rc[rc + ctx->m.mb_num].bits;

                ctx->mb_cmp[mb].mb = mb;

                ctx->mb_cmp[mb].value =

                    delta_bits ? ((ctx->mb_rc[rc].ssd -

                                   ctx->mb_rc[rc + ctx->m.mb_num].ssd) * 100) /

                                  delta_bits

                               : INT_MIN; // avoid increasing qscale

            }

        }

        max_bits += 31; // worst padding

    }

    if (!ret) {

        if (RC_VARIANCE)

            avctx->execute2(avctx, dnxhd_mb_var_thread,

                            NULL, NULL, ctx->m.mb_height);

        radix_sort(ctx->mb_cmp, ctx->m.mb_num);

        for (x = 0; x < ctx->m.mb_num && max_bits > ctx->frame_bits; x++) {

            int mb = ctx->mb_cmp[x].mb;

            int rc = (ctx->qscale * ctx->m.mb_num ) + mb;

            max_bits -= ctx->mb_rc[rc].bits -

                        ctx->mb_rc[rc + ctx->m.mb_num].bits;

            ctx->mb_qscale[mb] = ctx->qscale + 1;

            ctx->mb_bits[mb]   = ctx->mb_rc[rc + ctx->m.mb_num].bits;

        }

    }

    return 0;

}


static int img_read_header(AVFormatContext *s1, AVFormatParameters *ap)

{

    VideoData *s = s1->priv_data;

    int ret, first_index, last_index;

    char buf[1024];

    ByteIOContext pb1, *f = &pb1;

    AVStream *st;

    st = av_new_stream(s1, 0);

    if (!st) {

        av_free(s);

        return -ENOMEM;

    }

    if (ap && ap->image_format)

        s->img_fmt = ap->image_format;

    strcpy(s->path, s1->filename);

    s->img_number = 0;

    /* find format */

    if (s1->iformat->flags & AVFMT_NOFILE)

        s->is_pipe = 0;

    else

        s->is_pipe = 1;

    if (!ap || !ap->frame_rate) {

        st->codec.frame_rate      = 25;

        st->codec.frame_rate_base = 1;

    } else {

        st->codec.frame_rate      = ap->frame_rate;

        st->codec.frame_rate_base = ap->frame_rate_base;

    }

    if (!s->is_pipe) {

        if (find_image_range(&first_index, &last_index, s->path) < 0)

            goto fail;

        s->img_number = first_index;

        /* compute duration */

        st->start_time = 0;

        st->duration = ((int64_t)AV_TIME_BASE *

                        (last_index - first_index + 1) *

                        st->codec.frame_rate_base) / st->codec.frame_rate;

        if (get_frame_filename(buf, sizeof(buf), s->path, s->img_number) < 0)

            goto fail;

        if (url_fopen(f, buf, URL_RDONLY) < 0)

            goto fail;

    } else {

        f = &s1->pb;

    }

    ret = av_read_image(f, s1->filename, s->img_fmt, read_header_alloc_cb, s);

    if (ret < 0)

        goto fail1;

    if (!s->is_pipe) {

        url_fclose(f);

    } else {

        url_fseek(f, 0, SEEK_SET);

    }

    st->codec.codec_type = CODEC_TYPE_VIDEO;

    st->codec.codec_id = CODEC_ID_RAWVIDEO;

    st->codec.width = s->width;

    st->codec.height = s->height;

    st->codec.pix_fmt = s->pix_fmt;

    s->img_size = avpicture_get_size(s->pix_fmt, s->width, s->height);

    return 0;

 fail1:

    if (!s->is_pipe)

        url_fclose(f);

 fail:

    av_free(s);

    return -EIO;

}


static ram_addr_t s390_virtio_device_num_vq(VirtIOS390Device *dev)

{

    VirtIODevice *vdev = dev->vdev;

    int num_vq;

    for (num_vq = 0; num_vq < VIRTIO_PCI_QUEUE_MAX; num_vq++) {

        if (!virtio_queue_get_num(vdev, num_vq)) {

            break;

        }

    }

    return num_vq;

}


static int kvm_get_xsave(X86CPU *cpu)

{

    CPUX86State *env = &cpu->env;

    struct kvm_xsave* xsave = env->kvm_xsave_buf;

    int ret, i;

    const uint8_t *xmm, *ymmh, *zmmh;

    uint16_t cwd, swd, twd;

    if (!kvm_has_xsave()) {

        return kvm_get_fpu(cpu);

    }

    ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XSAVE, xsave);

    if (ret < 0) {

        return ret;

    }

    cwd = (uint16_t)xsave->region[XSAVE_FCW_FSW];

    swd = (uint16_t)(xsave->region[XSAVE_FCW_FSW] >> 16);

    twd = (uint16_t)xsave->region[XSAVE_FTW_FOP];

    env->fpop = (uint16_t)(xsave->region[XSAVE_FTW_FOP] >> 16);

    env->fpstt = (swd >> 11) & 7;

    env->fpus = swd;

    env->fpuc = cwd;

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

        env->fptags[i] = !((twd >> i) & 1);

    }

    memcpy(&env->fpip, &xsave->region[XSAVE_CWD_RIP], sizeof(env->fpip));

    memcpy(&env->fpdp, &xsave->region[XSAVE_CWD_RDP], sizeof(env->fpdp));

    env->mxcsr = xsave->region[XSAVE_MXCSR];

    memcpy(env->fpregs, &xsave->region[XSAVE_ST_SPACE],

            sizeof env->fpregs);

    env->xstate_bv = *(uint64_t *)&xsave->region[XSAVE_XSTATE_BV];

    memcpy(env->bnd_regs, &xsave->region[XSAVE_BNDREGS],

            sizeof env->bnd_regs);

    memcpy(&env->bndcs_regs, &xsave->region[XSAVE_BNDCSR],

            sizeof(env->bndcs_regs));

    memcpy(env->opmask_regs, &xsave->region[XSAVE_OPMASK],

            sizeof env->opmask_regs);

    xmm = (const uint8_t *)&xsave->region[XSAVE_XMM_SPACE];

    ymmh = (const uint8_t *)&xsave->region[XSAVE_YMMH_SPACE];

    zmmh = (const uint8_t *)&xsave->region[XSAVE_ZMM_Hi256];

    for (i = 0; i < CPU_NB_REGS; i++, xmm += 16, ymmh += 16, zmmh += 32) {

        env->xmm_regs[i].XMM_Q(0) = ldq_p(xmm);

        env->xmm_regs[i].XMM_Q(1) = ldq_p(xmm+8);

        env->xmm_regs[i].XMM_Q(2) = ldq_p(ymmh);

        env->xmm_regs[i].XMM_Q(3) = ldq_p(ymmh+8);

        env->xmm_regs[i].XMM_Q(4) = ldq_p(zmmh);

        env->xmm_regs[i].XMM_Q(5) = ldq_p(zmmh+8);

        env->xmm_regs[i].XMM_Q(6) = ldq_p(zmmh+16);

        env->xmm_regs[i].XMM_Q(7) = ldq_p(zmmh+24);

    }

#ifdef TARGET_X86_64

    memcpy(&env->xmm_regs[16], &xsave->region[XSAVE_Hi16_ZMM],

           16 * sizeof env->xmm_regs[16]);

#endif

    return 0;

}


static int jazz_led_init(SysBusDevice *dev)

{

    LedState *s = FROM_SYSBUS(LedState, dev);

    memory_region_init_io(&s->iomem, &led_ops, s, "led", 1);

    sysbus_init_mmio(dev, &s->iomem);

    s->con = graphic_console_init(jazz_led_update_display,

                                  jazz_led_invalidate_display,

                                  NULL,

                                  jazz_led_text_update, s);

    return 0;

}


static uint32_t hpet_ram_readb(void *opaque, target_phys_addr_t addr)

{

    printf("qemu: hpet_read b at %" PRIx64 "\n", addr);

    return 0;

}


static int read_restart_header(MLPDecodeContext *m, BitstreamContext *bc,

                               const uint8_t *buf, unsigned int substr)

{

    SubStream *s = &m->substream[substr];

    unsigned int ch;

    int sync_word, tmp;

    uint8_t checksum;

    uint8_t lossless_check;

    int start_count = bitstream_tell(bc);

    int min_channel, max_channel, max_matrix_channel;

    const int std_max_matrix_channel = m->avctx->codec_id == AV_CODEC_ID_MLP

                                     ? MAX_MATRIX_CHANNEL_MLP

                                     : MAX_MATRIX_CHANNEL_TRUEHD;

    sync_word = bitstream_read(bc, 13);

    if (sync_word != 0x31ea >> 1) {

        av_log(m->avctx, AV_LOG_ERROR,

               "restart header sync incorrect (got 0x%04x)\n", sync_word);

        return AVERROR_INVALIDDATA;

    }

    s->noise_type = bitstream_read_bit(bc);

    if (m->avctx->codec_id == AV_CODEC_ID_MLP && s->noise_type) {

        av_log(m->avctx, AV_LOG_ERROR, "MLP must have 0x31ea sync word.\n");

        return AVERROR_INVALIDDATA;

    }

    bitstream_skip(bc, 16); /* Output timestamp */

    min_channel        = bitstream_read(bc, 4);

    max_channel        = bitstream_read(bc, 4);

    max_matrix_channel = bitstream_read(bc, 4);

    if (max_matrix_channel > std_max_matrix_channel) {

        av_log(m->avctx, AV_LOG_ERROR,

               "Max matrix channel cannot be greater than %d.\n",

               max_matrix_channel);

        return AVERROR_INVALIDDATA;

    }

    if (max_channel != max_matrix_channel) {

        av_log(m->avctx, AV_LOG_ERROR,

               "Max channel must be equal max matrix channel.\n");

        return AVERROR_INVALIDDATA;

    }

    /* This should happen for TrueHD streams with >6 channels and MLP's noise

     * type. It is not yet known if this is allowed. */

    if (s->max_channel > MAX_MATRIX_CHANNEL_MLP && !s->noise_type) {

        avpriv_request_sample(m->avctx,

                              "%d channels (more than the "

                              "maximum supported by the decoder)",

                              s->max_channel + 2);

        return AVERROR_PATCHWELCOME;

    }

    if (min_channel > max_channel) {

        av_log(m->avctx, AV_LOG_ERROR,

               "Substream min channel cannot be greater than max channel.\n");

        return AVERROR_INVALIDDATA;

    }

    s->min_channel        = min_channel;

    s->max_channel        = max_channel;

    s->max_matrix_channel = max_matrix_channel;

    if (m->avctx->request_channel_layout && (s->mask & m->avctx->request_channel_layout) ==

        m->avctx->request_channel_layout && m->max_decoded_substream > substr) {

        av_log(m->avctx, AV_LOG_DEBUG,

               "Extracting %d-channel downmix (0x%"PRIx64") from substream %d. "

               "Further substreams will be skipped.\n",

               s->max_channel + 1, s->mask, substr);

        m->max_decoded_substream = substr;

    }

    s->noise_shift   = bitstream_read(bc,  4);

    s->noisegen_seed = bitstream_read(bc, 23);

    bitstream_skip(bc, 19);

    s->data_check_present = bitstream_read_bit(bc);

    lossless_check = bitstream_read(bc, 8);

    if (substr == m->max_decoded_substream

        && s->lossless_check_data != 0xffffffff) {

        tmp = xor_32_to_8(s->lossless_check_data);

        if (tmp != lossless_check)

            av_log(m->avctx, AV_LOG_WARNING,

                   "Lossless check failed - expected %02x, calculated %02x.\n",

                   lossless_check, tmp);

    }

    bitstream_skip(bc, 16);

    memset(s->ch_assign, 0, sizeof(s->ch_assign));

    for (ch = 0; ch <= s->max_matrix_channel; ch++) {

        int ch_assign = bitstream_read(bc, 6);

        if (m->avctx->codec_id == AV_CODEC_ID_TRUEHD) {

            uint64_t channel = thd_channel_layout_extract_channel(s->mask,

                                                                  ch_assign);

            ch_assign = av_get_channel_layout_channel_index(s->mask,

                                                            channel);

        }

        if (ch_assign < 0 || ch_assign > s->max_matrix_channel) {

            avpriv_request_sample(m->avctx,

                                  "Assignment of matrix channel %d to invalid output channel %d",

                                  ch, ch_assign);

            return AVERROR_PATCHWELCOME;

        }

        s->ch_assign[ch_assign] = ch;

    }

    checksum = ff_mlp_restart_checksum(buf, bitstream_tell(bc) - start_count);

    if (checksum != bitstream_read(bc, 8))

        av_log(m->avctx, AV_LOG_ERROR, "restart header checksum error\n");

    /* Set default decoding parameters. */

    s->param_presence_flags   = 0xff;

    s->num_primitive_matrices = 0;

    s->blocksize              = 8;

    s->lossless_check_data    = 0;

    memset(s->output_shift   , 0, sizeof(s->output_shift   ));

    memset(s->quant_step_size, 0, sizeof(s->quant_step_size));

    for (ch = s->min_channel; ch <= s->max_channel; ch++) {

        ChannelParams *cp = &s->channel_params[ch];

        cp->filter_params[FIR].order = 0;

        cp->filter_params[IIR].order = 0;

        cp->filter_params[FIR].shift = 0;

        cp->filter_params[IIR].shift = 0;

        /* Default audio coding is 24-bit raw PCM. */

        cp->huff_offset      = 0;

        cp->sign_huff_offset = -(1 << 23);

        cp->codebook         = 0;

        cp->huff_lsbs        = 24;

    }

    if (substr == m->max_decoded_substream) {

        m->avctx->channels       = s->max_matrix_channel + 1;

        m->avctx->channel_layout = s->mask;

        m->dsp.mlp_pack_output = m->dsp.mlp_select_pack_output(s->ch_assign,

                                                               s->output_shift,

                                                               s->max_matrix_channel,

                                                               m->avctx->sample_fmt == AV_SAMPLE_FMT_S32);

    }

    return 0;

}


static bool x86_cpu_has_work(CPUState *cs)

{

    X86CPU *cpu = X86_CPU(cs);

    CPUX86State *env = &cpu->env;

    return ((cs->interrupt_request & (CPU_INTERRUPT_HARD |

                                      CPU_INTERRUPT_POLL)) &&

            (env->eflags & IF_MASK)) ||

           (cs->interrupt_request & (CPU_INTERRUPT_NMI |

                                     CPU_INTERRUPT_INIT |

                                     CPU_INTERRUPT_SIPI |

                                     CPU_INTERRUPT_MCE));

}


static void sd_reset(SDState *sd, BlockBackend *blk)

{

    uint64_t size;

    uint64_t sect;

    if (blk) {

        blk_get_geometry(blk, &sect);

    } else {

        sect = 0;

    }

    size = sect << 9;

    sect = sd_addr_to_wpnum(size) + 1;

    sd->state = sd_idle_state;

    sd->rca = 0x0000;

    sd_set_ocr(sd);

    sd_set_scr(sd);

    sd_set_cid(sd);

    sd_set_csd(sd, size);

    sd_set_cardstatus(sd);

    sd_set_sdstatus(sd);

    sd->blk = blk;

    if (sd->wp_groups)

        g_free(sd->wp_groups);

    sd->wp_switch = blk ? blk_is_read_only(blk) : false;

    sd->wpgrps_size = sect;

    sd->wp_groups = bitmap_new(sd->wpgrps_size);

    memset(sd->function_group, 0, sizeof(sd->function_group));

    sd->erase_start = 0;

    sd->erase_end = 0;

    sd->size = size;

    sd->blk_len = 0x200;

    sd->pwd_len = 0;

    sd->expecting_acmd = false;

}


static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)

{

    OutputFile *of = output_files[ost->file_index];

    int64_t ost_tb_start_time = av_rescale_q(of->start_time, AV_TIME_BASE_Q, ost->st->time_base);

    AVPacket opkt;

    av_init_packet(&opkt);

    if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&

        !ost->copy_initial_nonkeyframes)

        return;

    if (of->recording_time != INT64_MAX &&

        ist->last_dts >= of->recording_time + of->start_time) {

        ost->finished = 1;

        return;

    }

    /* force the input stream PTS */

    if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)

        audio_size += pkt->size;

    else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {

        video_size += pkt->size;

        ost->sync_opts++;

    }

    if (pkt->pts != AV_NOPTS_VALUE)

        opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;

    else

        opkt.pts = AV_NOPTS_VALUE;

    if (pkt->dts == AV_NOPTS_VALUE)

        opkt.dts = av_rescale_q(ist->last_dts, AV_TIME_BASE_Q, ost->st->time_base);

    else

        opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);

    opkt.dts -= ost_tb_start_time;

    opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);

    opkt.flags    = pkt->flags;

    // FIXME remove the following 2 lines they shall be replaced by the bitstream filters

    if (  ost->st->codec->codec_id != AV_CODEC_ID_H264

       && ost->st->codec->codec_id != AV_CODEC_ID_MPEG1VIDEO

       && ost->st->codec->codec_id != AV_CODEC_ID_MPEG2VIDEO

       && ost->st->codec->codec_id != AV_CODEC_ID_VC1

       ) {

        if (av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY)) {

            opkt.buf = av_buffer_create(opkt.data, opkt.size, av_buffer_default_free, NULL, 0);

            if (!opkt.buf)

                exit(1);

        }

    } else {

        opkt.data = pkt->data;

        opkt.size = pkt->size;

    }

    write_frame(of->ctx, &opkt, ost);

    ost->st->codec->frame_number++;

}


struct GuestAgentInfo *qmp_guest_info(Error **errp)

{

    GuestAgentInfo *info = g_malloc0(sizeof(GuestAgentInfo));

    info->version = g_strdup(QEMU_VERSION);

    qmp_for_each_command(qmp_command_info, info);

    return info;

}


static int init_pass2(MpegEncContext *s)

{

    RateControlContext *rcc = &s->rc_context;

    AVCodecContext *a       = s->avctx;

    int i, toobig;

    double fps             = get_fps(s->avctx);

    double complexity[5]   = { 0 }; // approximate bits at quant=1

    uint64_t const_bits[5] = { 0 }; // quantizer independent bits

    uint64_t all_const_bits;

    uint64_t all_available_bits = (uint64_t)(s->bit_rate *

                                             (double)rcc->num_entries / fps);

    double rate_factor          = 0;

    double step;

    const int filter_size = (int)(a->qblur * 4) | 1;

    double expected_bits;

    double *qscale, *blurred_qscale, qscale_sum;

    /* find complexity & const_bits & decide the pict_types */

    for (i = 0; i < rcc->num_entries; i++) {

        RateControlEntry *rce = &rcc->entry[i];

        rce->new_pict_type                = rce->pict_type;

        rcc->i_cplx_sum[rce->pict_type]  += rce->i_tex_bits * rce->qscale;

        rcc->p_cplx_sum[rce->pict_type]  += rce->p_tex_bits * rce->qscale;

        rcc->mv_bits_sum[rce->pict_type] += rce->mv_bits;

        rcc->frame_count[rce->pict_type]++;

        complexity[rce->new_pict_type] += (rce->i_tex_bits + rce->p_tex_bits) *

                                          (double)rce->qscale;

        const_bits[rce->new_pict_type] += rce->mv_bits + rce->misc_bits;

    }

    all_const_bits = const_bits[AV_PICTURE_TYPE_I] +

                     const_bits[AV_PICTURE_TYPE_P] +

                     const_bits[AV_PICTURE_TYPE_B];

    if (all_available_bits < all_const_bits) {

        av_log(s->avctx, AV_LOG_ERROR, "requested bitrate is too low\n");

        return -1;

    }

    qscale         = av_malloc(sizeof(double) * rcc->num_entries);

    blurred_qscale = av_malloc(sizeof(double) * rcc->num_entries);

    toobig = 0;

    for (step = 256 * 256; step > 0.0000001; step *= 0.5) {

        expected_bits = 0;

        rate_factor  += step;

        rcc->buffer_index = s->avctx->rc_buffer_size / 2;

        /* find qscale */

        for (i = 0; i < rcc->num_entries; i++) {

            RateControlEntry *rce = &rcc->entry[i];

            qscale[i] = get_qscale(s, &rcc->entry[i], rate_factor, i);

            rcc->last_qscale_for[rce->pict_type] = qscale[i];

        }

        assert(filter_size % 2 == 1);

        /* fixed I/B QP relative to P mode */

        for (i = FFMAX(0, rcc->num_entries - 300); i < rcc->num_entries; i++) {

            RateControlEntry *rce = &rcc->entry[i];

            qscale[i] = get_diff_limited_q(s, rce, qscale[i]);

        }

        for (i = rcc->num_entries - 1; i >= 0; i--) {

            RateControlEntry *rce = &rcc->entry[i];

            qscale[i] = get_diff_limited_q(s, rce, qscale[i]);

        }

        /* smooth curve */

        for (i = 0; i < rcc->num_entries; i++) {

            RateControlEntry *rce = &rcc->entry[i];

            const int pict_type   = rce->new_pict_type;

            int j;

            double q = 0.0, sum = 0.0;

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

                int index    = i + j - filter_size / 2;

                double d     = index - i;

                double coeff = a->qblur == 0 ? 1.0 : exp(-d * d / (a->qblur * a->qblur));

                if (index < 0 || index >= rcc->num_entries)

                    continue;

                if (pict_type != rcc->entry[index].new_pict_type)

                    continue;

                q   += qscale[index] * coeff;

                sum += coeff;

            }

            blurred_qscale[i] = q / sum;

        }

        /* find expected bits */

        for (i = 0; i < rcc->num_entries; i++) {

            RateControlEntry *rce = &rcc->entry[i];

            double bits;

            rce->new_qscale = modify_qscale(s, rce, blurred_qscale[i], i);

            bits  = qp2bits(rce, rce->new_qscale) + rce->mv_bits + rce->misc_bits;

            bits += 8 * ff_vbv_update(s, bits);

            rce->expected_bits = expected_bits;

            expected_bits     += bits;

        }

        av_dlog(s->avctx,

                "expected_bits: %f all_available_bits: %d rate_factor: %f\n",

                expected_bits, (int)all_available_bits, rate_factor);

        if (expected_bits > all_available_bits) {

            rate_factor -= step;

            ++toobig;

        }

    }

    av_free(qscale);

    av_free(blurred_qscale);

    /* check bitrate calculations and print info */

    qscale_sum = 0.0;

    for (i = 0; i < rcc->num_entries; i++) {

        av_dlog(s, "[lavc rc] entry[%d].new_qscale = %.3f  qp = %.3f\n",

                i,

                rcc->entry[i].new_qscale,

                rcc->entry[i].new_qscale / FF_QP2LAMBDA);

        qscale_sum += av_clip(rcc->entry[i].new_qscale / FF_QP2LAMBDA,

                              s->avctx->qmin, s->avctx->qmax);

    }

    assert(toobig <= 40);

    av_log(s->avctx, AV_LOG_DEBUG,

           "[lavc rc] requested bitrate: %d bps  expected bitrate: %d bps\n",

           s->bit_rate,

           (int)(expected_bits / ((double)all_available_bits / s->bit_rate)));

    av_log(s->avctx, AV_LOG_DEBUG,

           "[lavc rc] estimated target average qp: %.3f\n",

           (float)qscale_sum / rcc->num_entries);

    if (toobig == 0) {

        av_log(s->avctx, AV_LOG_INFO,

               "[lavc rc] Using all of requested bitrate is not "

               "necessary for this video with these parameters.\n");

    } else if (toobig == 40) {

        av_log(s->avctx, AV_LOG_ERROR,

               "[lavc rc] Error: bitrate too low for this video "

               "with these parameters.\n");

        return -1;

    } else if (fabs(expected_bits / all_available_bits - 1.0) > 0.01) {

        av_log(s->avctx, AV_LOG_ERROR,

               "[lavc rc] Error: 2pass curve failed to converge\n");

        return -1;

    }

    return 0;

}


void replay_configure(QemuOpts *opts)

{

    const char *fname;

    const char *rr;

    ReplayMode mode = REPLAY_MODE_NONE;

    Location loc;

    if (!opts) {

        return;

    }

    loc_push_none(&loc);

    qemu_opts_loc_restore(opts);

    rr = qemu_opt_get(opts, "rr");

    if (!rr) {

        /* Just enabling icount */

        return;

    } else if (!strcmp(rr, "record")) {

        mode = REPLAY_MODE_RECORD;

    } else if (!strcmp(rr, "replay")) {

        mode = REPLAY_MODE_PLAY;

    } else {

        error_report("Invalid icount rr option: %s", rr);

        exit(1);

    }

    fname = qemu_opt_get(opts, "rrfile");

    if (!fname) {

        error_report("File name not specified for replay");

        exit(1);

    }

    replay_enable(fname, mode);

    loc_pop(&loc);

}


static void paint_mouse_pointer(XImage *image, AVFormatContext *s1)

{

    X11GrabContext *s = s1->priv_data;

    int x_off    = s->x_off;

    int y_off    = s->y_off;

    int width    = s->width;

    int height   = s->height;

    Display *dpy = s->dpy;

    XFixesCursorImage *xcim;

    int x, y;

    int line, column;

    int to_line, to_column;

    int pixstride = image->bits_per_pixel >> 3;

    /* Warning: in its insanity, xlib provides unsigned image data through a

     * char* pointer, so we have to make it uint8_t to make things not break.

     * Anyone who performs further investigation of the xlib API likely risks

     * permanent brain damage. */

    uint8_t *pix = image->data;

    Window root;

    XSetWindowAttributes attr;

    /* Code doesn't currently support 16-bit or PAL8 */

    if (image->bits_per_pixel != 24 && image->bits_per_pixel != 32)

        return;

    if (!s->c)

        s->c = XCreateFontCursor(dpy, XC_left_ptr);

    root = DefaultRootWindow(dpy);

    attr.cursor = s->c;

    XChangeWindowAttributes(dpy, root, CWCursor, &attr);

    xcim = XFixesGetCursorImage(dpy);

    if (!xcim) {

        av_log(s1, AV_LOG_WARNING,

               "XFixes extension not available, impossible to draw cursor\n");

        s->draw_mouse = 0;

        return;

    }

    x = xcim->x - xcim->xhot;

    y = xcim->y - xcim->yhot;

    to_line   = FFMIN((y + xcim->height), (height + y_off));

    to_column = FFMIN((x + xcim->width),  (width  + x_off));

    for (line = FFMAX(y, y_off); line < to_line; line++) {

        for (column = FFMAX(x, x_off); column < to_column; column++) {

            int xcim_addr  = (line  - y)     * xcim->width + column - x;

            int image_addr = ((line - y_off) * width       + column - x_off) * pixstride;

            int r          = (uint8_t)(xcim->pixels[xcim_addr] >>  0);

            int g          = (uint8_t)(xcim->pixels[xcim_addr] >>  8);

            int b          = (uint8_t)(xcim->pixels[xcim_addr] >> 16);

            int a          = (uint8_t)(xcim->pixels[xcim_addr] >> 24);

            if (a == 255) {

                pix[image_addr + 0] = r;

                pix[image_addr + 1] = g;

                pix[image_addr + 2] = b;

            } else if (a) {

                /* pixel values from XFixesGetCursorImage come premultiplied by alpha */

                pix[image_addr + 0] = r + (pix[image_addr + 0] * (255 - a) + 255 / 2) / 255;

                pix[image_addr + 1] = g + (pix[image_addr + 1] * (255 - a) + 255 / 2) / 255;

                pix[image_addr + 2] = b + (pix[image_addr + 2] * (255 - a) + 255 / 2) / 255;

            }

        }

    }

    XFree(xcim);

    xcim = NULL;

}


void scsi_req_dequeue(SCSIRequest *req)

{

    trace_scsi_req_dequeue(req->dev->id, req->lun, req->tag);

    if (req->enqueued) {

        QTAILQ_REMOVE(&req->dev->requests, req, next);

        req->enqueued = false;

        scsi_req_unref(req);

    }

}


static int pci_rocker_init(PCIDevice *dev)

{

    Rocker *r = to_rocker(dev);

    const MACAddr zero = { .a = { 0, 0, 0, 0, 0, 0 } };

    const MACAddr dflt = { .a = { 0x52, 0x54, 0x00, 0x12, 0x35, 0x01 } };

    static int sw_index;

    int i, err = 0;

    /* allocate worlds */

    r->worlds[ROCKER_WORLD_TYPE_OF_DPA] = of_dpa_world_alloc(r);

    if (!r->world_name) {

        r->world_name = g_strdup(world_name(r->worlds[ROCKER_WORLD_TYPE_OF_DPA]));

    }

    r->world_dflt = rocker_world_type_by_name(r, r->world_name);

    if (!r->world_dflt) {

        fprintf(stderr,

                "rocker: requested world \"%s\" does not exist\n",

                r->world_name);

        err = -EINVAL;

        goto err_world_type_by_name;

    }

    /* set up memory-mapped region at BAR0 */

    memory_region_init_io(&r->mmio, OBJECT(r), &rocker_mmio_ops, r,

                          "rocker-mmio", ROCKER_PCI_BAR0_SIZE);

    pci_register_bar(dev, ROCKER_PCI_BAR0_IDX,

                     PCI_BASE_ADDRESS_SPACE_MEMORY, &r->mmio);

    /* set up memory-mapped region for MSI-X */

    memory_region_init(&r->msix_bar, OBJECT(r), "rocker-msix-bar",

                       ROCKER_PCI_MSIX_BAR_SIZE);

    pci_register_bar(dev, ROCKER_PCI_MSIX_BAR_IDX,

                     PCI_BASE_ADDRESS_SPACE_MEMORY, &r->msix_bar);

    /* MSI-X init */

    err = rocker_msix_init(r);

    if (err) {

        goto err_msix_init;

    }

    /* validate switch properties */

    if (!r->name) {

        r->name = g_strdup(ROCKER);

    }

    if (rocker_find(r->name)) {

        err = -EEXIST;

        goto err_duplicate;

    }

    /* Rocker name is passed in port name requests to OS with the intention

     * that the name is used in interface names. Limit the length of the

     * rocker name to avoid naming problems in the OS. Also, adding the

     * port number as p# and unganged breakout b#, where # is at most 2

     * digits, so leave room for it too (-1 for string terminator, -3 for

     * p# and -3 for b#)

     */

#define ROCKER_IFNAMSIZ 16

#define MAX_ROCKER_NAME_LEN  (ROCKER_IFNAMSIZ - 1 - 3 - 3)

    if (strlen(r->name) > MAX_ROCKER_NAME_LEN) {

        fprintf(stderr,

                "rocker: name too long; please shorten to at most %d chars\n",

                MAX_ROCKER_NAME_LEN);

        return -EINVAL;

    }

    if (memcmp(&r->fp_start_macaddr, &zero, sizeof(zero)) == 0) {

        memcpy(&r->fp_start_macaddr, &dflt, sizeof(dflt));

        r->fp_start_macaddr.a[4] += (sw_index++);

    }

    if (!r->switch_id) {

        memcpy(&r->switch_id, &r->fp_start_macaddr,

               sizeof(r->fp_start_macaddr));

    }

    if (r->fp_ports > ROCKER_FP_PORTS_MAX) {

        r->fp_ports = ROCKER_FP_PORTS_MAX;

    }

    r->rings = g_new(DescRing *, rocker_pci_ring_count(r));

    /* Rings are ordered like this:

     * - command ring

     * - event ring

     * - port0 tx ring

     * - port0 rx ring

     * - port1 tx ring

     * - port1 rx ring

     * .....

     */

    for (i = 0; i < rocker_pci_ring_count(r); i++) {

        DescRing *ring = desc_ring_alloc(r, i);

        if (i == ROCKER_RING_CMD) {

            desc_ring_set_consume(ring, cmd_consume, ROCKER_MSIX_VEC_CMD);

        } else if (i == ROCKER_RING_EVENT) {

            desc_ring_set_consume(ring, NULL, ROCKER_MSIX_VEC_EVENT);

        } else if (i % 2 == 0) {

            desc_ring_set_consume(ring, tx_consume,

                                  ROCKER_MSIX_VEC_TX((i - 2) / 2));

        } else if (i % 2 == 1) {

            desc_ring_set_consume(ring, NULL, ROCKER_MSIX_VEC_RX((i - 3) / 2));

        }

        r->rings[i] = ring;

    }

    for (i = 0; i < r->fp_ports; i++) {

        FpPort *port =

            fp_port_alloc(r, r->name, &r->fp_start_macaddr,

                          i, &r->fp_ports_peers[i]);

        r->fp_port[i] = port;

        fp_port_set_world(port, r->world_dflt);

    }

    QLIST_INSERT_HEAD(&rockers, r, next);

    return 0;

err_duplicate:

    rocker_msix_uninit(r);

err_msix_init:

    object_unparent(OBJECT(&r->msix_bar));

    object_unparent(OBJECT(&r->mmio));

err_world_type_by_name:

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

        if (r->worlds[i]) {

            world_free(r->worlds[i]);

        }

    }

    return err;

}


static int cow_test_bit(int64_t bitnum, const uint8_t *bitmap)

{

    return (bitmap[bitnum / 8] & (1 << (bitnum & 7))) != 0;

}


static void create_gic(VirtBoardInfo *vbi, qemu_irq *pic)

{

    /* We create a standalone GIC v2 */

    DeviceState *gicdev;

    SysBusDevice *gicbusdev;

    const char *gictype;

    int i;

    gictype = gic_class_name();

    gicdev = qdev_create(NULL, gictype);

    qdev_prop_set_uint32(gicdev, "revision", 2);

    qdev_prop_set_uint32(gicdev, "num-cpu", smp_cpus);

    /* Note that the num-irq property counts both internal and external

     * interrupts; there are always 32 of the former (mandated by GIC spec).

     */

    qdev_prop_set_uint32(gicdev, "num-irq", NUM_IRQS + 32);

    qdev_init_nofail(gicdev);

    gicbusdev = SYS_BUS_DEVICE(gicdev);

    sysbus_mmio_map(gicbusdev, 0, vbi->memmap[VIRT_GIC_DIST].base);

    sysbus_mmio_map(gicbusdev, 1, vbi->memmap[VIRT_GIC_CPU].base);

    /* Wire the outputs from each CPU's generic timer to the

     * appropriate GIC PPI inputs, and the GIC's IRQ output to

     * the CPU's IRQ input.

     */

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

        DeviceState *cpudev = DEVICE(qemu_get_cpu(i));

        int ppibase = NUM_IRQS + i * GIC_INTERNAL + GIC_NR_SGIS;

        /* physical timer; we wire it up to the non-secure timer's ID,

         * since a real A15 always has TrustZone but QEMU doesn't.

         */

        qdev_connect_gpio_out(cpudev, 0,

                              qdev_get_gpio_in(gicdev,

                                             ppibase + ARCH_TIMER_NS_EL1_IRQ));

        /* virtual timer */

        qdev_connect_gpio_out(cpudev, 1,

                              qdev_get_gpio_in(gicdev,

                                               ppibase + ARCH_TIMER_VIRT_IRQ));

        /* Hypervisor timer.  */

        qdev_connect_gpio_out(cpudev, 2,

                              qdev_get_gpio_in(gicdev,

                                             ppibase + ARCH_TIMER_NS_EL2_IRQ));

        sysbus_connect_irq(gicbusdev, i, qdev_get_gpio_in(cpudev, ARM_CPU_IRQ));

        sysbus_connect_irq(gicbusdev, i + smp_cpus,

                           qdev_get_gpio_in(cpudev, ARM_CPU_FIQ));

    }

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

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

    }

    fdt_add_gic_node(vbi);

    create_v2m(vbi, pic);

}


static void kvmppc_host_cpu_class_init(ObjectClass *oc, void *data)

{

    DeviceClass *dc = DEVICE_CLASS(oc);

    PowerPCCPUClass *pcc = POWERPC_CPU_CLASS(oc);

    uint32_t vmx = kvmppc_get_vmx();

    uint32_t dfp = kvmppc_get_dfp();

    uint32_t dcache_size = kvmppc_read_int_cpu_dt("d-cache-size");

    uint32_t icache_size = kvmppc_read_int_cpu_dt("i-cache-size");

    /* Now fix up the class with information we can query from the host */

    pcc->pvr = mfpvr();

    if (vmx != -1) {

        /* Only override when we know what the host supports */

        alter_insns(&pcc->insns_flags, PPC_ALTIVEC, vmx > 0);

        alter_insns(&pcc->insns_flags2, PPC2_VSX, vmx > 1);

    }

    if (dfp != -1) {

        /* Only override when we know what the host supports */

        alter_insns(&pcc->insns_flags2, PPC2_DFP, dfp);

    }

    if (dcache_size != -1) {

        pcc->l1_dcache_size = dcache_size;

    }

    if (icache_size != -1) {

        pcc->l1_icache_size = icache_size;

    }

    /* Reason: kvmppc_host_cpu_initfn() dies when !kvm_enabled() */

    dc->cannot_destroy_with_object_finalize_yet = true;

}


static float128 addFloat128Sigs( float128 a, float128 b, flag zSign STATUS_PARAM)

{

    int32 aExp, bExp, zExp;

    uint64_t aSig0, aSig1, bSig0, bSig1, zSig0, zSig1, zSig2;

    int32 expDiff;

    aSig1 = extractFloat128Frac1( a );

    aSig0 = extractFloat128Frac0( a );

    aExp = extractFloat128Exp( a );

    bSig1 = extractFloat128Frac1( b );

    bSig0 = extractFloat128Frac0( b );

    bExp = extractFloat128Exp( b );

    expDiff = aExp - bExp;

    if ( 0 < expDiff ) {

        if ( aExp == 0x7FFF ) {

            if ( aSig0 | aSig1 ) return propagateFloat128NaN( a, b STATUS_VAR );

            return a;

        }

        if ( bExp == 0 ) {

            --expDiff;

        }

        else {

            bSig0 |= LIT64( 0x0001000000000000 );

        }

        shift128ExtraRightJamming(

            bSig0, bSig1, 0, expDiff, &bSig0, &bSig1, &zSig2 );

        zExp = aExp;

    }

    else if ( expDiff < 0 ) {

        if ( bExp == 0x7FFF ) {

            if ( bSig0 | bSig1 ) return propagateFloat128NaN( a, b STATUS_VAR );

            return packFloat128( zSign, 0x7FFF, 0, 0 );

        }

        if ( aExp == 0 ) {

            ++expDiff;

        }

        else {

            aSig0 |= LIT64( 0x0001000000000000 );

        }

        shift128ExtraRightJamming(

            aSig0, aSig1, 0, - expDiff, &aSig0, &aSig1, &zSig2 );

        zExp = bExp;

    }

    else {

        if ( aExp == 0x7FFF ) {

            if ( aSig0 | aSig1 | bSig0 | bSig1 ) {

                return propagateFloat128NaN( a, b STATUS_VAR );

            }

            return a;

        }

        add128( aSig0, aSig1, bSig0, bSig1, &zSig0, &zSig1 );

        if ( aExp == 0 ) {

            if ( STATUS(flush_to_zero) ) return packFloat128( zSign, 0, 0, 0 );

            return packFloat128( zSign, 0, zSig0, zSig1 );

        }

        zSig2 = 0;

        zSig0 |= LIT64( 0x0002000000000000 );

        zExp = aExp;

        goto shiftRight1;

    }

    aSig0 |= LIT64( 0x0001000000000000 );

    add128( aSig0, aSig1, bSig0, bSig1, &zSig0, &zSig1 );

    --zExp;

    if ( zSig0 < LIT64( 0x0002000000000000 ) ) goto roundAndPack;

    ++zExp;

 shiftRight1:

    shift128ExtraRightJamming(

        zSig0, zSig1, zSig2, 1, &zSig0, &zSig1, &zSig2 );

 roundAndPack:

    return roundAndPackFloat128( zSign, zExp, zSig0, zSig1, zSig2 STATUS_VAR );

}


static void test_acpi_one(const char *params)

{

    char *args;

    uint8_t signature_low;

    uint8_t signature_high;

    uint16_t signature;

    int i;

    uint32_t off;

    args = g_strdup_printf("-net none -display none %s %s",

                           params ? params : "", disk);

    qtest_start(args);

   /* Wait at most 1 minute */

#define TEST_DELAY (1 * G_USEC_PER_SEC / 10)

#define TEST_CYCLES MAX((60 * G_USEC_PER_SEC / TEST_DELAY), 1)

    /* Poll until code has run and modified memory.  Once it has we know BIOS

     * initialization is done.  TODO: check that IP reached the halt

     * instruction.

     */

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

        signature_low = readb(BOOT_SECTOR_ADDRESS + SIGNATURE_OFFSET);

        signature_high = readb(BOOT_SECTOR_ADDRESS + SIGNATURE_OFFSET + 1);

        signature = (signature_high << 8) | signature_low;

        if (signature == SIGNATURE) {

            break;

        }

        g_usleep(TEST_DELAY);

    }

    g_assert_cmphex(signature, ==, SIGNATURE);

    /* OK, now find RSDP */

    for (off = 0xf0000; off < 0x100000; off += 0x10)

    {

        uint8_t sig[] = "RSD PTR ";

        int i;

        for (i = 0; i < sizeof sig - 1; ++i) {

            sig[i] = readb(off + i);

        }

        if (!memcmp(sig, "RSD PTR ", sizeof sig)) {

            break;

        }

    }

    g_assert_cmphex(off, <, 0x100000);

    qtest_quit(global_qtest);

    g_free(args);

}


static FFPsyWindowInfo psy_3gpp_window(FFPsyContext *ctx,

                                       const int16_t *audio, const int16_t *la,

                                       int channel, int prev_type)

{

    int i, j;

    int br               = ctx->avctx->bit_rate / ctx->avctx->channels;

    int attack_ratio     = br <= 16000 ? 18 : 10;

    Psy3gppContext *pctx = (Psy3gppContext*) ctx->model_priv_data;

    Psy3gppChannel *pch  = &pctx->ch[channel];

    uint8_t grouping     = 0;

    FFPsyWindowInfo wi;

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

    if (la) {

        float s[8], v;

        int switch_to_eight = 0;

        float sum = 0.0, sum2 = 0.0;

        int attack_n = 0;

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

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

                v = iir_filter(la[(i*128+j)*ctx->avctx->channels], pch->iir_state);

                sum += v*v;

            }

            s[i]  = sum;

            sum2 += sum;

        }

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

            if (s[i] > pch->win_energy * attack_ratio) {

                attack_n        = i + 1;

                switch_to_eight = 1;

                break;

            }

        }

        pch->win_energy = pch->win_energy*7/8 + sum2/64;

        wi.window_type[1] = prev_type;

        switch (prev_type) {

        case ONLY_LONG_SEQUENCE:

            wi.window_type[0] = switch_to_eight ? LONG_START_SEQUENCE : ONLY_LONG_SEQUENCE;

            break;

        case LONG_START_SEQUENCE:

            wi.window_type[0] = EIGHT_SHORT_SEQUENCE;

            grouping = pch->next_grouping;

            break;

        case LONG_STOP_SEQUENCE:

            wi.window_type[0] = ONLY_LONG_SEQUENCE;

            break;

        case EIGHT_SHORT_SEQUENCE:

            wi.window_type[0] = switch_to_eight ? EIGHT_SHORT_SEQUENCE : LONG_STOP_SEQUENCE;

            grouping = switch_to_eight ? pch->next_grouping : 0;

            break;

        }

        pch->next_grouping = window_grouping[attack_n];

    } else {

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

            wi.window_type[i] = prev_type;

        grouping = (prev_type == EIGHT_SHORT_SEQUENCE) ? window_grouping[0] : 0;

    }

    wi.window_shape   = 1;

    if (wi.window_type[0] != EIGHT_SHORT_SEQUENCE) {

        wi.num_windows = 1;

        wi.grouping[0] = 1;

    } else {

        int lastgrp = 0;

        wi.num_windows = 8;

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

            if (!((grouping >> i) & 1))

                lastgrp = i;

            wi.grouping[lastgrp]++;

        }

    }

    return wi;

}


void kqemu_set_phys_mem(uint64_t start_addr, ram_addr_t size,

                        ram_addr_t phys_offset)

{

    struct kqemu_phys_mem kphys_mem1, *kphys_mem = &kphys_mem1;

    uint64_t end;

    int ret, io_index;

    end = (start_addr + size + TARGET_PAGE_SIZE - 1) & TARGET_PAGE_MASK;

    start_addr &= TARGET_PAGE_MASK;

    kphys_mem->phys_addr = start_addr;

    kphys_mem->size = end - start_addr;

    kphys_mem->ram_addr = phys_offset & TARGET_PAGE_MASK;

    io_index = phys_offset & ~TARGET_PAGE_MASK;

    switch(io_index) {

    case IO_MEM_RAM:

        kphys_mem->io_index = KQEMU_IO_MEM_RAM;

        break;

    case IO_MEM_ROM:

        kphys_mem->io_index = KQEMU_IO_MEM_ROM;

        break;

    default:

        if (qpi_io_memory == io_index) {

            kphys_mem->io_index = KQEMU_IO_MEM_COMM;

        } else {

            kphys_mem->io_index = KQEMU_IO_MEM_UNASSIGNED;

        }

        break;

    }

#ifdef _WIN32

    {

        DWORD temp;

        ret = DeviceIoControl(kqemu_fd, KQEMU_SET_PHYS_MEM,

                              kphys_mem, sizeof(*kphys_mem),

                              NULL, 0, &temp, NULL) == TRUE ? 0 : -1;

    }

#else

    ret = ioctl(kqemu_fd, KQEMU_SET_PHYS_MEM, kphys_mem);

#endif

    if (ret < 0) {

        fprintf(stderr, "kqemu: KQEMU_SET_PHYS_PAGE error=%d: start_addr=0x%016" PRIx64 " size=0x%08lx phys_offset=0x%08lx\n",

                ret, start_addr,

                (unsigned long)size, (unsigned long)phys_offset);

    }

}


static void omap_dpll_write(void *opaque, target_phys_addr_t addr,

                            uint64_t value, unsigned size)

{

    struct dpll_ctl_s *s = (struct dpll_ctl_s *) opaque;

    uint16_t diff;

    static const int bypass_div[4] = { 1, 2, 4, 4 };

    int div, mult;

    if (size != 2) {

        return omap_badwidth_write16(opaque, addr, value);

    }

    if (addr == 0x00) {	/* CTL_REG */

        /* See omap_ulpd_pm_write() too */

        diff = s->mode & value;

        s->mode = value & 0x2fff;

        if (diff & (0x3ff << 2)) {

            if (value & (1 << 4)) {			/* PLL_ENABLE */

                div = ((value >> 5) & 3) + 1;		/* PLL_DIV */

                mult = MIN((value >> 7) & 0x1f, 1);	/* PLL_MULT */

            } else {

                div = bypass_div[((value >> 2) & 3)];	/* BYPASS_DIV */

                mult = 1;

            }

            omap_clk_setrate(s->dpll, div, mult);

        }

        /* Enter the desired mode.  */

        s->mode = (s->mode & 0xfffe) | ((s->mode >> 4) & 1);

        /* Act as if the lock is restored.  */

        s->mode |= 2;

    } else {

        OMAP_BAD_REG(addr);

    }

}


static inline void gen_evfsneg(DisasContext *ctx)

{

    if (unlikely(!ctx->spe_enabled)) {

        gen_exception(ctx, POWERPC_EXCP_APU);

        return;

    }

#if defined(TARGET_PPC64)

    tcg_gen_xori_tl(cpu_gpr[rD(ctx->opcode)], cpu_gpr[rA(ctx->opcode)], 0x8000000080000000LL);

#else

    tcg_gen_xori_tl(cpu_gpr[rD(ctx->opcode)], cpu_gpr[rA(ctx->opcode)], 0x80000000);

    tcg_gen_xori_tl(cpu_gprh[rD(ctx->opcode)], cpu_gprh[rA(ctx->opcode)], 0x80000000);

#endif

}


static void qmp_input_start_list(Visitor *v, const char *name, Error **errp)

{

    QmpInputVisitor *qiv = to_qiv(v);

    QObject *qobj = qmp_input_get_object(qiv, name, true);

    if (!qobj || qobject_type(qobj) != QTYPE_QLIST) {

        error_setg(errp, QERR_INVALID_PARAMETER_TYPE, name ? name : "null",

                   "list");

        return;

    }

    qmp_input_push(qiv, qobj, errp);

}


static void nvic_sysreg_write(void *opaque, target_phys_addr_t addr,

                              uint64_t value, unsigned size)

{

    uint32_t offset = addr;

    if (size == 4) {

        nvic_writel(opaque, offset, value);

        return;

    }

    hw_error("NVIC: Bad write of size %d at offset 0x%x\n", size, offset);

}


static void pci_init_bus_master(PCIDevice *pci_dev)

{

    AddressSpace *dma_as = pci_device_iommu_address_space(pci_dev);

    memory_region_init_alias(&pci_dev->bus_master_enable_region,

                             OBJECT(pci_dev), "bus master",

                             dma_as->root, 0, memory_region_size(dma_as->root));

    memory_region_set_enabled(&pci_dev->bus_master_enable_region, false);

    address_space_init(&pci_dev->bus_master_as,

                       &pci_dev->bus_master_enable_region, pci_dev->name);

}


void aio_set_event_notifier_poll(AioContext *ctx,

                                 EventNotifier *notifier,

                                 EventNotifierHandler *io_poll_begin,

                                 EventNotifierHandler *io_poll_end)

{

    aio_set_fd_poll(ctx, event_notifier_get_fd(notifier),

                    (IOHandler *)io_poll_begin,

                    (IOHandler *)io_poll_end);

}


static uint64_t m5208_sys_read(void *opaque, target_phys_addr_t addr,

                               unsigned size)

{

    switch (addr) {

    case 0x110: /* SDCS0 */

        {

            int n;

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

                if (ram_size < (2u << n))

                    break;

            }

            return (n - 1)  | 0x40000000;

        }

    case 0x114: /* SDCS1 */

        return 0;

    default:

        hw_error("m5208_sys_read: Bad offset 0x%x\n", (int)addr);

        return 0;

    }

}


static int vhost_user_set_vring_addr(struct vhost_dev *dev,

                                     struct vhost_vring_addr *addr)

{

    VhostUserMsg msg = {

        .request = VHOST_USER_SET_VRING_ADDR,

        .flags = VHOST_USER_VERSION,

        .payload.addr = *addr,

        .size = sizeof(msg.payload.addr),

    };

    vhost_user_write(dev, &msg, NULL, 0);

    return 0;

}


static int amr_read_packet(AVFormatContext *s,

                          AVPacket *pkt)

{

    AVCodecContext *enc = s->streams[0]->codec;

    int read, size, toc, mode;

    if (url_feof(&s->pb))

    {

        return AVERROR_IO;

    }

//FIXME this is wrong, this should rather be in a AVParset

    toc=get_byte(&s->pb);

    mode = (toc >> 3) & 0x0F;

    if (enc->codec_id == CODEC_ID_AMR_NB)

    {

        static const uint8_t packed_size[16] = {12, 13, 15, 17, 19, 20, 26, 31, 5, 0, 0, 0, 0, 0, 0, 0};

        size=packed_size[mode]+1;

    }

    else if(enc->codec_id == CODEC_ID_AMR_WB)

    {

        static uint8_t packed_size[16] = {18, 24, 33, 37, 41, 47, 51, 59, 61, 6, 6, 0, 0, 0, 1, 1};

        size=packed_size[mode];

    }

    else

    {

        assert(0);

    }

    if ( (size==0) || av_new_packet(pkt, size))

    {

        return AVERROR_IO;

    }

    pkt->stream_index = 0;

    pkt->pos= url_ftell(&s->pb);

    pkt->data[0]=toc;

    pkt->duration= enc->codec_id == CODEC_ID_AMR_NB ? 160 : 320;

    read = get_buffer(&s->pb, pkt->data+1, size-1);

    if (read != size-1)

    {

        av_free_packet(pkt);

        return AVERROR_IO;

    }

    return 0;

}


static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)

{

    int i;

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

        PerThreadContext *p = &fctx->threads[i];

        if (p->state != STATE_INPUT_READY) {

            pthread_mutex_lock(&p->progress_mutex);

            while (p->state != STATE_INPUT_READY)

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

            pthread_mutex_unlock(&p->progress_mutex);

        }

    }

}


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

{

    NUTContext *nut = s->priv_data;

    ByteIOContext *bc = &s->pb;

    int i, frame_code=0, ret, skip;

    int64_t ts, back_ptr;

    for(;;){

        int64_t pos= url_ftell(bc);

        uint64_t tmp= nut->next_startcode;

        nut->next_startcode=0;

        if (url_feof(bc))

            return -1;

        if(tmp){

            pos-=8;

        }else{

            frame_code = get_byte(bc);

            if(frame_code == 'N'){

                tmp= frame_code;

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

                    tmp = (tmp<<8) + get_byte(bc);

            }

        }

        switch(tmp){

        case MAIN_STARTCODE:

        case STREAM_STARTCODE:

        case INDEX_STARTCODE:

            skip= get_packetheader(nut, bc, 0);

            url_fseek(bc, skip, SEEK_CUR);

            break;

        case INFO_STARTCODE:

            if(decode_info_header(nut)<0)

                goto resync;

            break;

        case SYNCPOINT_STARTCODE:

            if(decode_syncpoint(nut, &ts, &back_ptr)<0)

                goto resync;

            frame_code = get_byte(bc);

        case 0:

            ret= decode_frame(nut, pkt, frame_code);

            if(ret==0)

                return 0;

            else if(ret==1) //ok but discard packet

                break;

        default:

resync:

av_log(s, AV_LOG_DEBUG, "syncing from %"PRId64"\n", pos);

            tmp= find_any_startcode(bc, nut->last_syncpoint_pos+1);

            if(tmp==0)

                return -1;

av_log(s, AV_LOG_DEBUG, "sync\n");

            nut->next_startcode= tmp;

        }

    }

}


void rgb8tobgr8(const uint8_t *src, uint8_t *dst, long src_size)

{

	long i;

	long num_pixels = src_size;

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

	{

	    unsigned b,g,r;

	    register uint8_t rgb;

	    rgb = src[i];

	    r = (rgb&0x07);

	    g = (rgb&0x38)>>3;

	    b = (rgb&0xC0)>>6;

	    dst[i] = ((b<<1)&0x07) | ((g&0x07)<<3) | ((r&0x03)<<6);

	}

}