static int filter_frame(AVFilterLink *inlink, AVFrame *insamplesref)

{

    AResampleContext *aresample = inlink->dst->priv;

    const int n_in  = insamplesref->nb_samples;

    int64_t delay;

    int n_out       = n_in * aresample->ratio + 32;

    AVFilterLink *const outlink = inlink->dst->outputs[0];

    AVFrame *outsamplesref;

    int ret;

    delay = swr_get_delay(aresample->swr, outlink->sample_rate);

    if (delay > 0)

        n_out += FFMIN(delay, FFMAX(4096, n_out));

    outsamplesref = ff_get_audio_buffer(outlink, n_out);

    if(!outsamplesref)

        return AVERROR(ENOMEM);

    av_frame_copy_props(outsamplesref, insamplesref);

    outsamplesref->format                = outlink->format;

    av_frame_set_channels(outsamplesref, outlink->channels);

    outsamplesref->channel_layout        = outlink->channel_layout;

    outsamplesref->sample_rate           = outlink->sample_rate;

    if(insamplesref->pts != AV_NOPTS_VALUE) {

        int64_t inpts = av_rescale(insamplesref->pts, inlink->time_base.num * (int64_t)outlink->sample_rate * inlink->sample_rate, inlink->time_base.den);

        int64_t outpts= swr_next_pts(aresample->swr, inpts);

        aresample->next_pts =

        outsamplesref->pts  = ROUNDED_DIV(outpts, inlink->sample_rate);

    } else {

        outsamplesref->pts  = AV_NOPTS_VALUE;

    }

    n_out = swr_convert(aresample->swr, outsamplesref->extended_data, n_out,

                                 (void *)insamplesref->extended_data, n_in);

    if (n_out <= 0) {

        av_frame_free(&outsamplesref);

        av_frame_free(&insamplesref);

        return 0;

    }

    aresample->more_data = outsamplesref->nb_samples == n_out; // Indicate that there is probably more data in our buffers

    outsamplesref->nb_samples  = n_out;

    ret = ff_filter_frame(outlink, outsamplesref);

    aresample->req_fullfilled= 1;

    av_frame_free(&insamplesref);

    return ret;

}


int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)

{

    MOVMuxContext *mov = s->priv_data;

    AVIOContext *pb = s->pb;

    MOVTrack *trk = &mov->tracks[pkt->stream_index];

    AVCodecContext *enc = trk->enc;

    unsigned int samples_in_chunk = 0;

    int size = pkt->size, ret = 0;

    uint8_t *reformatted_data = NULL;

    if (trk->entry) {

        int64_t duration = pkt->dts - trk->cluster[trk->entry - 1].dts;

        if (duration < 0 || duration > INT_MAX) {

            av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",

                duration, pkt->dts

            );

            pkt->dts = trk->cluster[trk->entry - 1].dts + 1;

            pkt->pts = AV_NOPTS_VALUE;

        }

        if (pkt->duration < 0) {

            av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration);

            return AVERROR(EINVAL);

        }

    }

    if (mov->flags & FF_MOV_FLAG_FRAGMENT) {

        int ret;

        if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {

            if (mov->frag_interleave && mov->fragments > 0) {

                if (trk->entry - trk->entries_flushed >= mov->frag_interleave) {

                    if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0)

                        return ret;

                }

            }

            if (!trk->mdat_buf) {

                if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)

                    return ret;

            }

            pb = trk->mdat_buf;

        } else {

            if (!mov->mdat_buf) {

                if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)

                    return ret;

            }

            pb = mov->mdat_buf;

        }

    }

    if (enc->codec_id == AV_CODEC_ID_AMR_NB) {

        /* We must find out how many AMR blocks there are in one packet */

        static const uint16_t packed_size[16] =

            {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};

        int len = 0;

        while (len < size && samples_in_chunk < 100) {

            len += packed_size[(pkt->data[len] >> 3) & 0x0F];

            samples_in_chunk++;

        }

        if (samples_in_chunk > 1) {

            av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");

            return -1;

        }

    } else if (enc->codec_id == AV_CODEC_ID_ADPCM_MS ||

               enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {

        samples_in_chunk = enc->frame_size;

    } else if (trk->sample_size)

        samples_in_chunk = size / trk->sample_size;

    else

        samples_in_chunk = 1;

    /* copy extradata if it exists */

    if (trk->vos_len == 0 && enc->extradata_size > 0 &&

        !TAG_IS_AVCI(trk->tag) &&

        (enc->codec_id != AV_CODEC_ID_DNXHD)) {

        trk->vos_len  = enc->extradata_size;

        trk->vos_data = av_malloc(trk->vos_len);

        if (!trk->vos_data) {

            ret = AVERROR(ENOMEM);

            goto err;

        }

        memcpy(trk->vos_data, enc->extradata, trk->vos_len);

    }

    if (enc->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&

        (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {

        if (!s->streams[pkt->stream_index]->nb_frames) {

            av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "

                   "use the audio bitstream filter 'aac_adtstoasc' to fix it "

                   "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");

            return -1;

        }

        av_log(s, AV_LOG_WARNING, "aac bitstream error\n");

    }

    if (enc->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {

        /* from x264 or from bytestream h264 */

        /* nal reformating needed */

        if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {

            ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,

                                       &size);

            avio_write(pb, reformatted_data, size);

        } else {

            if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {

                size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size);

                if (size < 0) {

                    ret = size;

                    goto err;

                }

            } else {

                size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);

            }

        }

    } else if (enc->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&

               (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {

        /* extradata is Annex B, assume the bitstream is too and convert it */

        if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {

            ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);

            avio_write(pb, reformatted_data, size);

        } else {

            size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);

        }

#if CONFIG_AC3_PARSER

    } else if (enc->codec_id == AV_CODEC_ID_EAC3) {

        size = handle_eac3(mov, pkt, trk);

        if (size < 0)

            return size;

        else if (!size)

            goto end;

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

#endif

    } else {

        if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {

            if (enc->codec_id == AV_CODEC_ID_H264 && enc->extradata_size > 4) {

                int nal_size_length = (enc->extradata[4] & 0x3) + 1;

                ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size);

            } else {

                ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size);

            }

            if (ret) {

                goto err;

            }

        } else {

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

        }

    }

    if ((enc->codec_id == AV_CODEC_ID_DNXHD ||

         enc->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {

        /* copy frame to create needed atoms */

        trk->vos_len  = size;

        trk->vos_data = av_malloc(size);

        if (!trk->vos_data) {

            ret = AVERROR(ENOMEM);

            goto err;

        }

        memcpy(trk->vos_data, pkt->data, size);

    }

    if (trk->entry >= trk->cluster_capacity) {

        unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);

        if (av_reallocp_array(&trk->cluster, new_capacity,

                              sizeof(*trk->cluster))) {

            ret = AVERROR(ENOMEM);

            goto err;

        }

        trk->cluster_capacity = new_capacity;

    }

    trk->cluster[trk->entry].pos              = avio_tell(pb) - size;

    trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;

    trk->cluster[trk->entry].chunkNum         = 0;

    trk->cluster[trk->entry].size             = size;

    trk->cluster[trk->entry].entries          = samples_in_chunk;

    trk->cluster[trk->entry].dts              = pkt->dts;

    if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {

        if (!trk->frag_discont) {

            /* First packet of a new fragment. We already wrote the duration

             * of the last packet of the previous fragment based on track_duration,

             * which might not exactly match our dts. Therefore adjust the dts

             * of this packet to be what the previous packets duration implies. */

            trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;

            /* We also may have written the pts and the corresponding duration

             * in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with

             * the next fragment. This means the cts of the first sample must

             * be the same in all fragments. */

            if ((mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)) ||

                mov->mode == MODE_ISM)

                pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts;

        } else {

            /* New fragment, but discontinuous from previous fragments.

             * Pretend the duration sum of the earlier fragments is

             * pkt->dts - trk->start_dts. */

            trk->frag_start = pkt->dts - trk->start_dts;

            trk->end_pts = AV_NOPTS_VALUE;

            trk->frag_discont = 0;

        }

    }

    if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&

        s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {

        /* Not using edit lists and shifting the first track to start from zero.

         * If the other streams start from a later timestamp, we won't be able

         * to signal the difference in starting time without an edit list.

         * Thus move the timestamp for this first sample to 0, increasing

         * its duration instead. */

        trk->cluster[trk->entry].dts = trk->start_dts = 0;

    }

    if (trk->start_dts == AV_NOPTS_VALUE) {

        trk->start_dts = pkt->dts;

        if (trk->frag_discont) {

            if (mov->use_editlist) {

                /* Pretend the whole stream started at pts=0, with earlier fragments

                 * already written. If the stream started at pts=0, the duration sum

                 * of earlier fragments would have been pkt->pts. */

                trk->frag_start = pkt->pts;

                trk->start_dts  = pkt->dts - pkt->pts;

            } else {

                /* Pretend the whole stream started at dts=0, with earlier fragments

                 * already written, with a duration summing up to pkt->dts. */

                trk->frag_start = pkt->dts;

                trk->start_dts  = 0;

            }

            trk->frag_discont = 0;

        } else if (pkt->dts && mov->moov_written)

            av_log(s, AV_LOG_WARNING,

                   "Track %d starts with a nonzero dts %"PRId64", while the moov "

                   "already has been written. Set the delay_moov flag to handle "

                   "this case.\n",

                   pkt->stream_index, pkt->dts);

    }

    trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;

    trk->last_sample_is_subtitle_end = 0;

    if (pkt->pts == AV_NOPTS_VALUE) {

        av_log(s, AV_LOG_WARNING, "pts has no value\n");

        pkt->pts = pkt->dts;

    }

    if (pkt->dts != pkt->pts)

        trk->flags |= MOV_TRACK_CTTS;

    trk->cluster[trk->entry].cts   = pkt->pts - pkt->dts;

    trk->cluster[trk->entry].flags = 0;

    if (trk->start_cts == AV_NOPTS_VALUE)

        trk->start_cts = pkt->pts - pkt->dts;

    if (trk->end_pts == AV_NOPTS_VALUE)

        trk->end_pts = trk->cluster[trk->entry].dts +

                       trk->cluster[trk->entry].cts + pkt->duration;

    else

        trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts +

                                           trk->cluster[trk->entry].cts +

                                           pkt->duration);

    if (enc->codec_id == AV_CODEC_ID_VC1) {

        mov_parse_vc1_frame(pkt, trk);

    } else if (pkt->flags & AV_PKT_FLAG_KEY) {

        if (mov->mode == MODE_MOV && enc->codec_id == AV_CODEC_ID_MPEG2VIDEO &&

            trk->entry > 0) { // force sync sample for the first key frame

            mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);

            if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)

                trk->flags |= MOV_TRACK_STPS;

        } else {

            trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;

        }

        if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)

            trk->has_keyframes++;

    }

    trk->entry++;

    trk->sample_count += samples_in_chunk;

    mov->mdat_size    += size;

    if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)

        ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,

                                 reformatted_data, size);

end:

err:

    av_free(reformatted_data);

    return ret;

}


static int decode_cabac_mb_chroma_pre_mode( H264Context *h) {

    const int mba_xy = h->left_mb_xy[0];

    const int mbb_xy = h->top_mb_xy;

    int ctx = 0;

    /* No need to test for IS_INTRA4x4 and IS_INTRA16x16, as we set chroma_pred_mode_table to 0 */

    if( h->slice_table[mba_xy] == h->slice_num && h->chroma_pred_mode_table[mba_xy] != 0 )

        ctx++;

    if( h->slice_table[mbb_xy] == h->slice_num && h->chroma_pred_mode_table[mbb_xy] != 0 )

        ctx++;

    if( get_cabac( &h->cabac, &h->cabac_state[64+ctx] ) == 0 )

        return 0;

    if( get_cabac( &h->cabac, &h->cabac_state[64+3] ) == 0 )

        return 1;

    if( get_cabac( &h->cabac, &h->cabac_state[64+3] ) == 0 )

        return 2;

    else

        return 3;

}


static av_cold int psy_3gpp_init(FFPsyContext *ctx) {

    AacPsyContext *pctx;

    float bark;

    int i, j, g, start;

    float prev, minscale, minath;

    ctx->model_priv_data = av_mallocz(sizeof(AacPsyContext));

    pctx = (AacPsyContext*) ctx->model_priv_data;

    minath = ath(3410, ATH_ADD);

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

        AacPsyCoeffs *coeffs = &pctx->psy_coef[j];

        float line_to_frequency = ctx->avctx->sample_rate / (j ? 256.f : 2048.0f);

        i = 0;

        prev = 0.0;

        for (g = 0; g < ctx->num_bands[j]; g++) {

            i += ctx->bands[j][g];

            bark = calc_bark((i-1) * line_to_frequency);

            coeffs->barks[g] = (bark + prev) / 2.0;

            prev = bark;

        }

        for (g = 0; g < ctx->num_bands[j] - 1; g++) {

            coeffs->spread_low[g] = pow(10.0, -(coeffs->barks[g+1] - coeffs->barks[g]) * PSY_3GPP_SPREAD_LOW);

            coeffs->spread_hi [g] = pow(10.0, -(coeffs->barks[g+1] - coeffs->barks[g]) * PSY_3GPP_SPREAD_HI);

        }

        start = 0;

        for (g = 0; g < ctx->num_bands[j]; g++) {

            minscale = ath(start * line_to_frequency, ATH_ADD);

            for (i = 1; i < ctx->bands[j][g]; i++)

                minscale = FFMIN(minscale, ath((start + i) * line_to_frequency, ATH_ADD));

            coeffs->ath[g] = minscale - minath;

            start += ctx->bands[j][g];

        }

    }

    pctx->ch = av_mallocz(sizeof(AacPsyChannel) * ctx->avctx->channels);

    lame_window_init(pctx, ctx->avctx);

    return 0;

}


static void test_tco_second_timeout_reset(void)

{

    TestData td;

    const uint16_t ticks = TCO_SECS_TO_TICKS(16);

    QDict *ad;

    td.args = "-watchdog-action reset";

    td.noreboot = false;

    test_init(&td);

    stop_tco(&td);

    clear_tco_status(&td);

    reset_on_second_timeout(true);

    set_tco_timeout(&td, TCO_SECS_TO_TICKS(16));

    load_tco(&td);

    start_tco(&td);

    clock_step(ticks * TCO_TICK_NSEC * 2);

    ad = get_watchdog_action();

    g_assert(!strcmp(qdict_get_str(ad, "action"), "reset"));

    QDECREF(ad);

    stop_tco(&td);

    qtest_end();

}


static void e1000e_macreg_write(e1000e_device *d, uint32_t reg, uint32_t val)

{

    qpci_io_writel(d->pci_dev, d->mac_regs + reg, val);

}


static void fdctrl_handle_drive_specification_command(FDCtrl *fdctrl, int direction)

{

    FDrive *cur_drv = get_cur_drv(fdctrl);

    if (fdctrl->fifo[fdctrl->data_pos - 1] & 0x80) {

        /* Command parameters done */

        if (fdctrl->fifo[fdctrl->data_pos - 1] & 0x40) {

            fdctrl->fifo[0] = fdctrl->fifo[1];

            fdctrl->fifo[2] = 0;

            fdctrl->fifo[3] = 0;

            fdctrl_set_fifo(fdctrl, 4);

        } else {

            fdctrl_reset_fifo(fdctrl);

        }

    } else if (fdctrl->data_len > 7) {

        /* ERROR */

        fdctrl->fifo[0] = 0x80 |

            (cur_drv->head << 2) | GET_CUR_DRV(fdctrl);

        fdctrl_set_fifo(fdctrl, 1);

    }

}


uint64_t helper_addqv(CPUAlphaState *env, uint64_t op1, uint64_t op2)

{

    uint64_t tmp = op1;

    op1 += op2;

    if (unlikely((tmp ^ op2 ^ (-1ULL)) & (tmp ^ op1) & (1ULL << 63))) {

        arith_excp(env, GETPC(), EXC_M_IOV, 0);

    }

    return op1;

}


pvscsi_on_cmd_setup_msg_ring(PVSCSIState *s)

{

    PVSCSICmdDescSetupMsgRing *rc =

        (PVSCSICmdDescSetupMsgRing *) s->curr_cmd_data;

    trace_pvscsi_on_cmd_arrived("PVSCSI_CMD_SETUP_MSG_RING");

    if (!s->use_msg) {

        return PVSCSI_COMMAND_PROCESSING_FAILED;

    }

    if (s->rings_info_valid) {

        pvscsi_ring_init_msg(&s->rings, rc);

        s->msg_ring_info_valid = TRUE;

    }

    return sizeof(PVSCSICmdDescSetupMsgRing) / sizeof(uint32_t);

}


dispatcher_wait(Dispatcher *dispr, uint32_t timeout)

{

    struct timeval tv;

    tv.tv_sec = timeout / 1000000;

    tv.tv_usec = timeout % 1000000;

    fd_set fdset = dispr->fdset;

    /* wait until some of sockets become readable. */

    int rc = select(dispr->max_sock + 1, &fdset, 0, 0, &tv);

    if (rc == -1) {

        vubr_die("select");

    }

    /* Timeout */

    if (rc == 0) {

        return 0;

    }

    /* Now call callback for every ready socket. */

    int sock;

    for (sock = 0; sock < dispr->max_sock + 1; sock++)

        if (FD_ISSET(sock, &fdset)) {

            Event *e = &dispr->events[sock];

            e->callback(sock, e->ctx);

        }

    return 0;

}


int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res)

{

    if (bs->drv->bdrv_check == NULL) {

        return -ENOTSUP;

    }

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

    res->corruptions = bs->drv->bdrv_check(bs);

    return res->corruptions < 0 ? res->corruptions : 0;

}


static int nsv_parse_NSVf_header(AVFormatContext *s)

{

    NSVContext *nsv = s->priv_data;

    AVIOContext *pb = s->pb;

    unsigned int av_unused file_size;

    unsigned int size;

    int64_t duration;

    int strings_size;

    int table_entries;

    int table_entries_used;

    av_dlog(s, "%s()\n", __FUNCTION__);

    nsv->state = NSV_UNSYNC; /* in case we fail */

    size = avio_rl32(pb);

    if (size < 28)

        return -1;

    nsv->NSVf_end = size;

    //s->file_size = (uint32_t)avio_rl32(pb);

    file_size = (uint32_t)avio_rl32(pb);

    av_dlog(s, "NSV NSVf chunk_size %u\n", size);

    av_dlog(s, "NSV NSVf file_size %u\n", file_size);

    nsv->duration = duration = avio_rl32(pb); /* in ms */

    av_dlog(s, "NSV NSVf duration %"PRId64" ms\n", duration);

    // XXX: store it in AVStreams

    strings_size = avio_rl32(pb);

    table_entries = avio_rl32(pb);

    table_entries_used = avio_rl32(pb);

    av_dlog(s, "NSV NSVf info-strings size: %d, table entries: %d, bis %d\n",

            strings_size, table_entries, table_entries_used);

    if (pb->eof_reached)

        return -1;

    av_dlog(s, "NSV got header; filepos %"PRId64"\n", avio_tell(pb));

    if (strings_size > 0) {

        char *strings; /* last byte will be '\0' to play safe with str*() */

        char *p, *endp;

        char *token, *value;

        char quote;

        p = strings = av_mallocz(strings_size + 1);

        endp = strings + strings_size;

        avio_read(pb, strings, strings_size);

        while (p < endp) {

            while (*p == ' ')

                p++; /* strip out spaces */

            if (p >= endp-2)

                break;

            token = p;

            p = strchr(p, '=');

            if (!p || p >= endp-2)

                break;

            *p++ = '\0';

            quote = *p++;

            value = p;

            p = strchr(p, quote);

            if (!p || p >= endp)

                break;

            *p++ = '\0';

            av_dlog(s, "NSV NSVf INFO: %s='%s'\n", token, value);

            av_dict_set(&s->metadata, token, value, 0);

        }

        av_free(strings);

    }

    if (pb->eof_reached)

        return -1;

    av_dlog(s, "NSV got infos; filepos %"PRId64"\n", avio_tell(pb));

    if (table_entries_used > 0) {

        int i;

        nsv->index_entries = table_entries_used;

        if((unsigned)table_entries_used >= UINT_MAX / sizeof(uint32_t))

            return -1;

        nsv->nsvs_file_offset = av_malloc((unsigned)table_entries_used * sizeof(uint32_t));

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

            nsv->nsvs_file_offset[i] = avio_rl32(pb) + size;

        if(table_entries > table_entries_used &&

           avio_rl32(pb) == MKTAG('T','O','C','2')) {

            nsv->nsvs_timestamps = av_malloc((unsigned)table_entries_used*sizeof(uint32_t));

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

                nsv->nsvs_timestamps[i] = avio_rl32(pb);

            }

        }

    }

    av_dlog(s, "NSV got index; filepos %"PRId64"\n", avio_tell(pb));

#ifdef DEBUG_DUMP_INDEX

#define V(v) ((v<0x20 || v > 127)?'.':v)

    /* dump index */

    av_dlog(s, "NSV %d INDEX ENTRIES:\n", table_entries);

    av_dlog(s, "NSV [dataoffset][fileoffset]\n", table_entries);

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

        unsigned char b[8];

        avio_seek(pb, size + nsv->nsvs_file_offset[i], SEEK_SET);

        avio_read(pb, b, 8);

        av_dlog(s, "NSV [0x%08lx][0x%08lx]: %02x %02x %02x %02x %02x %02x %02x %02x"

           "%c%c%c%c%c%c%c%c\n",

           nsv->nsvs_file_offset[i], size + nsv->nsvs_file_offset[i],

           b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7],

           V(b[0]), V(b[1]), V(b[2]), V(b[3]), V(b[4]), V(b[5]), V(b[6]), V(b[7]) );

    }

    //avio_seek(pb, size, SEEK_SET); /* go back to end of header */

#undef V

#endif

    avio_seek(pb, nsv->base_offset + size, SEEK_SET); /* required for dumbdriving-271.nsv (2 extra bytes) */

    if (pb->eof_reached)

        return -1;

    nsv->state = NSV_HAS_READ_NSVF;

    return 0;

}


static int flac_decode_frame(AVCodecContext *avctx,

                            void *data, int *data_size,

                            const uint8_t *buf, int buf_size)

{

    FLACContext *s = avctx->priv_data;

    int tmp = 0, i, j = 0, input_buf_size = 0;

    int16_t *samples_16 = data;

    int32_t *samples_32 = data;

    int alloc_data_size= *data_size;

    *data_size=0;

    if (s->max_framesize == 0) {

        s->max_framesize= FFMAX(4, buf_size); // should hopefully be enough for the first header

        s->bitstream= av_fast_realloc(s->bitstream, &s->allocated_bitstream_size, s->max_framesize);

    }

    if (1 && s->max_framesize) { //FIXME truncated

        if (s->bitstream_size < 4 || AV_RL32(s->bitstream) != MKTAG('f','L','a','C'))

            buf_size= FFMIN(buf_size, s->max_framesize - FFMIN(s->bitstream_size, s->max_framesize));

        input_buf_size= buf_size;

        if (s->bitstream_size + buf_size < buf_size || s->bitstream_index + s->bitstream_size + buf_size < s->bitstream_index)

            return -1;

        if (s->allocated_bitstream_size < s->bitstream_size + buf_size)

            s->bitstream= av_fast_realloc(s->bitstream, &s->allocated_bitstream_size, s->bitstream_size + buf_size);

        if (s->bitstream_index + s->bitstream_size + buf_size > s->allocated_bitstream_size) {

            memmove(s->bitstream, &s->bitstream[s->bitstream_index],

                    s->bitstream_size);

            s->bitstream_index=0;

        }

        memcpy(&s->bitstream[s->bitstream_index + s->bitstream_size],

               buf, buf_size);

        buf= &s->bitstream[s->bitstream_index];

        buf_size += s->bitstream_size;

        s->bitstream_size= buf_size;

        if (buf_size < s->max_framesize && input_buf_size) {

            return input_buf_size;

        }

    }

    init_get_bits(&s->gb, buf, buf_size*8);

    if (metadata_parse(s))

        goto end;

    tmp = show_bits(&s->gb, 16);

    if ((tmp & 0xFFFE) != 0xFFF8) {

        av_log(s->avctx, AV_LOG_ERROR, "FRAME HEADER not here\n");

        while (get_bits_count(&s->gb)/8+2 < buf_size && (show_bits(&s->gb, 16) & 0xFFFE) != 0xFFF8)

            skip_bits(&s->gb, 8);

        goto end; // we may not have enough bits left to decode a frame, so try next time

    }

    skip_bits(&s->gb, 16);

    if (decode_frame(s, alloc_data_size) < 0) {

        av_log(s->avctx, AV_LOG_ERROR, "decode_frame() failed\n");

        s->bitstream_size=0;

        s->bitstream_index=0;

        return -1;

    }

#define DECORRELATE(left, right)\

            assert(s->channels == 2);\

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

                int a= s->decoded[0][i];\

                int b= s->decoded[1][i];\

                if (s->is32) {\

                    *samples_32++ = (left)  << s->sample_shift;\

                    *samples_32++ = (right) << s->sample_shift;\

                } else {\

                    *samples_16++ = (left)  << s->sample_shift;\

                    *samples_16++ = (right) << s->sample_shift;\

                }\

            }\

            break;

    switch (s->decorrelation) {

    case INDEPENDENT:

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

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

                if (s->is32)

                    *samples_32++ = s->decoded[i][j] << s->sample_shift;

                else

                    *samples_16++ = s->decoded[i][j] << s->sample_shift;

            }

        }

        break;

    case LEFT_SIDE:

        DECORRELATE(a,a-b)

    case RIGHT_SIDE:

        DECORRELATE(a+b,b)

    case MID_SIDE:

        DECORRELATE( (a-=b>>1) + b, a)

    }

    *data_size = s->blocksize * s->channels * (s->is32 ? 4 : 2);

end:

    i= (get_bits_count(&s->gb)+7)/8;

    if (i > buf_size) {

        av_log(s->avctx, AV_LOG_ERROR, "overread: %d\n", i - buf_size);

        s->bitstream_size=0;

        s->bitstream_index=0;

        return -1;

    }

    if (s->bitstream_size) {

        s->bitstream_index += i;

        s->bitstream_size  -= i;

        return input_buf_size;

    } else

        return i;

}


static int cfhd_decode(AVCodecContext *avctx, void *data, int *got_frame,

                       AVPacket *avpkt)

{

    CFHDContext *s = avctx->priv_data;

    GetByteContext gb;

    ThreadFrame frame = { .f = data };

    AVFrame *pic = data;

    int ret = 0, i, j, planes, plane, got_buffer = 0;

    int16_t *coeff_data;

    s->coded_format = AV_PIX_FMT_YUV422P10;

    init_frame_defaults(s);

    planes = av_pix_fmt_count_planes(s->coded_format);

    bytestream2_init(&gb, avpkt->data, avpkt->size);

    while (bytestream2_get_bytes_left(&gb) > 4) {

        /* Bit weird but implement the tag parsing as the spec says */

        uint16_t tagu   = bytestream2_get_be16(&gb);

        int16_t tag     = (int16_t)tagu;

        int8_t tag8     = (int8_t)(tagu >> 8);

        uint16_t abstag = abs(tag);

        int8_t abs_tag8 = abs(tag8);

        uint16_t data   = bytestream2_get_be16(&gb);

        if (abs_tag8 >= 0x60 && abs_tag8 <= 0x6f) {

            av_log(avctx, AV_LOG_DEBUG, "large len %x\n", ((tagu & 0xff) << 16) | data);

        } else if (tag == 20) {

            av_log(avctx, AV_LOG_DEBUG, "Width %"PRIu16"\n", data);

            s->coded_width = data;

        } else if (tag == 21) {

            av_log(avctx, AV_LOG_DEBUG, "Height %"PRIu16"\n", data);

            s->coded_height = data;

        } else if (tag == 101) {

            av_log(avctx, AV_LOG_DEBUG, "Bits per component: %"PRIu16"\n", data);

            if (data < 1 || data > 31) {

                av_log(avctx, AV_LOG_ERROR, "Bits per component %d is invalid\n", data);

                ret = AVERROR(EINVAL);

                break;

            }

            s->bpc = data;

        } else if (tag == 12) {

            av_log(avctx, AV_LOG_DEBUG, "Channel Count: %"PRIu16"\n", data);

            s->channel_cnt = data;

            if (data > 4) {

                av_log(avctx, AV_LOG_ERROR, "Channel Count of %"PRIu16" is unsupported\n", data);

                ret = AVERROR_PATCHWELCOME;

                break;

            }

        } else if (tag == 14) {

            av_log(avctx, AV_LOG_DEBUG, "Subband Count: %"PRIu16"\n", data);

            if (data != SUBBAND_COUNT) {

                av_log(avctx, AV_LOG_ERROR, "Subband Count of %"PRIu16" is unsupported\n", data);

                ret = AVERROR_PATCHWELCOME;

                break;

            }

        } else if (tag == 62) {

            s->channel_num = data;

            av_log(avctx, AV_LOG_DEBUG, "Channel number %"PRIu16"\n", data);

            if (s->channel_num >= planes) {

                av_log(avctx, AV_LOG_ERROR, "Invalid channel number\n");

                ret = AVERROR(EINVAL);

                break;

            }

            init_plane_defaults(s);

        } else if (tag == 48) {

            if (s->subband_num != 0 && data == 1)  // hack

                s->level++;

            av_log(avctx, AV_LOG_DEBUG, "Subband number %"PRIu16"\n", data);

            s->subband_num = data;

            if (s->level >= DWT_LEVELS) {

                av_log(avctx, AV_LOG_ERROR, "Invalid level\n");

                ret = AVERROR(EINVAL);

                break;

            }

            if (s->subband_num > 3) {

                av_log(avctx, AV_LOG_ERROR, "Invalid subband number\n");

                ret = AVERROR(EINVAL);

                break;

            }

        } else if (tag == 51) {

            av_log(avctx, AV_LOG_DEBUG, "Subband number actual %"PRIu16"\n", data);

            s->subband_num_actual = data;

            if (s->subband_num_actual >= 10) {

                av_log(avctx, AV_LOG_ERROR, "Invalid subband number actual\n");

                ret = AVERROR(EINVAL);

                break;

            }

        } else if (tag == 35)

            av_log(avctx, AV_LOG_DEBUG, "Lowpass precision bits: %"PRIu16"\n", data);

        else if (tag == 53) {

            s->quantisation = data;

            av_log(avctx, AV_LOG_DEBUG, "Quantisation: %"PRIu16"\n", data);

        } else if (tag == 109) {

            s->prescale_shift[0] = (data >> 0) & 0x7;

            s->prescale_shift[1] = (data >> 3) & 0x7;

            s->prescale_shift[2] = (data >> 6) & 0x7;

            av_log(avctx, AV_LOG_DEBUG, "Prescale shift (VC-5): %x\n", data);

        } else if (tag == 27) {

            av_log(avctx, AV_LOG_DEBUG, "Lowpass width %"PRIu16"\n", data);

            if (data < 3 || data > s->plane[s->channel_num].band[0][0].a_width) {

                av_log(avctx, AV_LOG_ERROR, "Invalid lowpass width\n");

                ret = AVERROR(EINVAL);

                break;

            }

            s->plane[s->channel_num].band[0][0].width  = data;

            s->plane[s->channel_num].band[0][0].stride = data;

        } else if (tag == 28) {

            av_log(avctx, AV_LOG_DEBUG, "Lowpass height %"PRIu16"\n", data);

            if (data < 3 || data > s->plane[s->channel_num].band[0][0].height) {

                av_log(avctx, AV_LOG_ERROR, "Invalid lowpass height\n");

                ret = AVERROR(EINVAL);

                break;

            }

            s->plane[s->channel_num].band[0][0].height = data;

        } else if (tag == 1)

            av_log(avctx, AV_LOG_DEBUG, "Sample type? %"PRIu16"\n", data);

        else if (tag == 10) {

            if (data != 0) {

                avpriv_report_missing_feature(avctx, "Transform type of %"PRIu16, data);

                ret = AVERROR_PATCHWELCOME;

                break;

            }

            av_log(avctx, AV_LOG_DEBUG, "Transform-type? %"PRIu16"\n", data);

        } else if (abstag >= 0x4000 && abstag <= 0x40ff) {

            av_log(avctx, AV_LOG_DEBUG, "Small chunk length %d %s\n", data * 4, tag < 0 ? "optional" : "required");

            bytestream2_skipu(&gb, data * 4);

        } else if (tag == 23) {

            av_log(avctx, AV_LOG_DEBUG, "Skip frame\n");

            avpriv_report_missing_feature(avctx, "Skip frame");

            ret = AVERROR_PATCHWELCOME;

            break;

        } else if (tag == 2) {

            av_log(avctx, AV_LOG_DEBUG, "tag=2 header - skipping %i tag/value pairs\n", data);

            if (data > bytestream2_get_bytes_left(&gb) / 4) {

                av_log(avctx, AV_LOG_ERROR, "too many tag/value pairs (%d)\n", data);

                ret = AVERROR_INVALIDDATA;

                break;

            }

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

                uint16_t tag2 = bytestream2_get_be16(&gb);

                uint16_t val2 = bytestream2_get_be16(&gb);

                av_log(avctx, AV_LOG_DEBUG, "Tag/Value = %x %x\n", tag2, val2);

            }

        } else if (tag == 41) {

            av_log(avctx, AV_LOG_DEBUG, "Highpass width %i channel %i level %i subband %i\n", data, s->channel_num, s->level, s->subband_num);

            if (data < 3) {

                av_log(avctx, AV_LOG_ERROR, "Invalid highpass width\n");

                ret = AVERROR(EINVAL);

                break;

            }

            s->plane[s->channel_num].band[s->level][s->subband_num].width  = data;

            s->plane[s->channel_num].band[s->level][s->subband_num].stride = FFALIGN(data, 8);

        } else if (tag == 42) {

            av_log(avctx, AV_LOG_DEBUG, "Highpass height %i\n", data);

            if (data < 3) {

                av_log(avctx, AV_LOG_ERROR, "Invalid highpass height\n");

                ret = AVERROR(EINVAL);

                break;

            }

            s->plane[s->channel_num].band[s->level][s->subband_num].height = data;

        } else if (tag == 49) {

            av_log(avctx, AV_LOG_DEBUG, "Highpass width2 %i\n", data);

            if (data < 3) {

                av_log(avctx, AV_LOG_ERROR, "Invalid highpass width2\n");

                ret = AVERROR(EINVAL);

                break;

            }

            s->plane[s->channel_num].band[s->level][s->subband_num].width  = data;

            s->plane[s->channel_num].band[s->level][s->subband_num].stride = FFALIGN(data, 8);

        } else if (tag == 50) {

            av_log(avctx, AV_LOG_DEBUG, "Highpass height2 %i\n", data);

            if (data < 3) {

                av_log(avctx, AV_LOG_ERROR, "Invalid highpass height2\n");

                ret = AVERROR(EINVAL);

                break;

            }

            s->plane[s->channel_num].band[s->level][s->subband_num].height = data;

        } else if (tag == 71) {

            s->codebook = data;

            av_log(avctx, AV_LOG_DEBUG, "Codebook %i\n", s->codebook);

        } else if (tag == 72) {

            s->codebook = data;

            av_log(avctx, AV_LOG_DEBUG, "Other codebook? %i\n", s->codebook);

        } else if (tag == 70) {

            av_log(avctx, AV_LOG_DEBUG, "Subsampling or bit-depth flag? %i\n", data);

            if (!(data == 10 || data == 12)) {

                av_log(avctx, AV_LOG_ERROR, "Invalid bits per channel\n");

                ret = AVERROR(EINVAL);

                break;

            }

            s->bpc = data;

        } else if (tag == 84) {

            av_log(avctx, AV_LOG_DEBUG, "Sample format? %i\n", data);

            if (data == 1)

                s->coded_format = AV_PIX_FMT_YUV422P10;

            else if (data == 3)

                s->coded_format = AV_PIX_FMT_GBRP12;

            else if (data == 4)

                s->coded_format = AV_PIX_FMT_GBRAP12;

            else {

                avpriv_report_missing_feature(avctx, "Sample format of %"PRIu16, data);

                ret = AVERROR_PATCHWELCOME;

                break;

            }

            planes = av_pix_fmt_count_planes(s->coded_format);

        } else

            av_log(avctx, AV_LOG_DEBUG,  "Unknown tag %i data %x\n", tag, data);

        /* Some kind of end of header tag */

        if (tag == 4 && data == 0x1a4a && s->coded_width && s->coded_height &&

            s->coded_format != AV_PIX_FMT_NONE) {

            if (s->a_width != s->coded_width || s->a_height != s->coded_height ||

                s->a_format != s->coded_format) {

                free_buffers(avctx);

                if ((ret = alloc_buffers(avctx)) < 0) {

                    free_buffers(avctx);

                    return ret;

                }

            }

            ret = ff_set_dimensions(avctx, s->coded_width, s->coded_height);

            if (ret < 0)

                return ret;

            frame.f->width =

            frame.f->height = 0;

            if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0)

                return ret;

            s->coded_width = 0;

            s->coded_height = 0;

            s->coded_format = AV_PIX_FMT_NONE;

            got_buffer = 1;

        }

        coeff_data = s->plane[s->channel_num].subband[s->subband_num_actual];

        /* Lowpass coefficients */

        if (tag == 4 && data == 0xf0f && s->a_width && s->a_height) {

            int lowpass_height = s->plane[s->channel_num].band[0][0].height;

            int lowpass_width  = s->plane[s->channel_num].band[0][0].width;

            int lowpass_a_height = s->plane[s->channel_num].band[0][0].a_height;

            int lowpass_a_width  = s->plane[s->channel_num].band[0][0].a_width;

            if (!got_buffer) {

                av_log(avctx, AV_LOG_ERROR, "No end of header tag found\n");

                ret = AVERROR(EINVAL);

                goto end;

            }

            if (lowpass_height > lowpass_a_height || lowpass_width > lowpass_a_width ||

                lowpass_a_width * lowpass_a_height * sizeof(int16_t) > bytestream2_get_bytes_left(&gb)) {

                av_log(avctx, AV_LOG_ERROR, "Too many lowpass coefficients\n");

                ret = AVERROR(EINVAL);

                goto end;

            }

            av_log(avctx, AV_LOG_DEBUG, "Start of lowpass coeffs component %d height:%d, width:%d\n", s->channel_num, lowpass_height, lowpass_width);

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

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

                    coeff_data[j] = bytestream2_get_be16u(&gb);

                coeff_data += lowpass_width;

            }

            /* Align to mod-4 position to continue reading tags */

            bytestream2_seek(&gb, bytestream2_tell(&gb) & 3, SEEK_CUR);

            /* Copy last line of coefficients if odd height */

            if (lowpass_height & 1) {

                memcpy(&coeff_data[lowpass_height * lowpass_width],

                       &coeff_data[(lowpass_height - 1) * lowpass_width],

                       lowpass_width * sizeof(*coeff_data));

            }

            av_log(avctx, AV_LOG_DEBUG, "Lowpass coefficients %d\n", lowpass_width * lowpass_height);

        }

        if (tag == 55 && s->subband_num_actual != 255 && s->a_width && s->a_height) {

            int highpass_height = s->plane[s->channel_num].band[s->level][s->subband_num].height;

            int highpass_width  = s->plane[s->channel_num].band[s->level][s->subband_num].width;

            int highpass_a_width = s->plane[s->channel_num].band[s->level][s->subband_num].a_width;

            int highpass_a_height = s->plane[s->channel_num].band[s->level][s->subband_num].a_height;

            int highpass_stride = s->plane[s->channel_num].band[s->level][s->subband_num].stride;

            int expected;

            int a_expected = highpass_a_height * highpass_a_width;

            int level, run, coeff;

            int count = 0, bytes;

            if (!got_buffer) {

                av_log(avctx, AV_LOG_ERROR, "No end of header tag found\n");

                ret = AVERROR(EINVAL);

                goto end;

            }

            if (highpass_height > highpass_a_height || highpass_width > highpass_a_width || a_expected < highpass_height * (uint64_t)highpass_stride) {

                av_log(avctx, AV_LOG_ERROR, "Too many highpass coefficients\n");

                ret = AVERROR(EINVAL);

                goto end;

            }

            expected = highpass_height * highpass_stride;

            av_log(avctx, AV_LOG_DEBUG, "Start subband coeffs plane %i level %i codebook %i expected %i\n", s->channel_num, s->level, s->codebook, expected);

            init_get_bits(&s->gb, gb.buffer, bytestream2_get_bytes_left(&gb) * 8);

            {

                OPEN_READER(re, &s->gb);

                if (!s->codebook) {

                    while (1) {

                        UPDATE_CACHE(re, &s->gb);

                        GET_RL_VLC(level, run, re, &s->gb, s->table_9_rl_vlc,

                                   VLC_BITS, 3, 1);

                        /* escape */

                        if (level == 64)

                            break;

                        count += run;

                        if (count > expected)

                            break;

                        coeff = dequant_and_decompand(level, s->quantisation);

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

                            *coeff_data++ = coeff;

                    }

                } else {

                    while (1) {

                        UPDATE_CACHE(re, &s->gb);

                        GET_RL_VLC(level, run, re, &s->gb, s->table_18_rl_vlc,

                                   VLC_BITS, 3, 1);

                        /* escape */

                        if (level == 255 && run == 2)

                            break;

                        count += run;

                        if (count > expected)

                            break;

                        coeff = dequant_and_decompand(level, s->quantisation);

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

                            *coeff_data++ = coeff;

                    }

                }

                CLOSE_READER(re, &s->gb);

            }

            if (count > expected) {

                av_log(avctx, AV_LOG_ERROR, "Escape codeword not found, probably corrupt data\n");

                ret = AVERROR(EINVAL);

                goto end;

            }

            bytes = FFALIGN(FF_CEIL_RSHIFT(get_bits_count(&s->gb), 3), 4);

            if (bytes > bytestream2_get_bytes_left(&gb)) {

                av_log(avctx, AV_LOG_ERROR, "Bitstream overread error\n");

                ret = AVERROR(EINVAL);

                goto end;

            } else

                bytestream2_seek(&gb, bytes, SEEK_CUR);

            av_log(avctx, AV_LOG_DEBUG, "End subband coeffs %i extra %i\n", count, count - expected);

            s->codebook = 0;

            /* Copy last line of coefficients if odd height */

            if (highpass_height & 1) {

                memcpy(&coeff_data[highpass_height * highpass_stride],

                       &coeff_data[(highpass_height - 1) * highpass_stride],

                       highpass_stride * sizeof(*coeff_data));

            }

        }

    }

    if (!s->a_width || !s->a_height || s->a_format == AV_PIX_FMT_NONE ||

        s->coded_width || s->coded_height || s->coded_format != AV_PIX_FMT_NONE) {

        av_log(avctx, AV_LOG_ERROR, "Invalid dimensions\n");

        ret = AVERROR(EINVAL);

        goto end;

    }

    if (!got_buffer) {

        av_log(avctx, AV_LOG_ERROR, "No end of header tag found\n");

        ret = AVERROR(EINVAL);

        goto end;

    }

    planes = av_pix_fmt_count_planes(avctx->pix_fmt);

    for (plane = 0; plane < planes && !ret; plane++) {

        /* level 1 */

        int lowpass_height  = s->plane[plane].band[0][0].height;

        int lowpass_width   = s->plane[plane].band[0][0].width;

        int highpass_stride = s->plane[plane].band[0][1].stride;

        int act_plane = plane == 1 ? 2 : plane == 2 ? 1 : plane;

        int16_t *low, *high, *output, *dst;

        if (lowpass_height > s->plane[plane].band[0][0].a_height || lowpass_width > s->plane[plane].band[0][0].a_width ||

            !highpass_stride || s->plane[plane].band[0][1].width > s->plane[plane].band[0][1].a_width) {

            av_log(avctx, AV_LOG_ERROR, "Invalid plane dimensions\n");

            ret = AVERROR(EINVAL);

            goto end;

        }

        av_log(avctx, AV_LOG_DEBUG, "Decoding level 1 plane %i %i %i %i\n", plane, lowpass_height, lowpass_width, highpass_stride);

        low    = s->plane[plane].subband[0];

        high   = s->plane[plane].subband[2];

        output = s->plane[plane].l_h[0];

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

            vert_filter(output, lowpass_width, low, lowpass_width, high, highpass_stride, lowpass_height);

            low++;

            high++;

            output++;

        }

        low    = s->plane[plane].subband[1];

        high   = s->plane[plane].subband[3];

        output = s->plane[plane].l_h[1];

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

            // note the stride of "low" is highpass_stride

            vert_filter(output, lowpass_width, low, highpass_stride, high, highpass_stride, lowpass_height);

            low++;

            high++;

            output++;

        }

        low    = s->plane[plane].l_h[0];

        high   = s->plane[plane].l_h[1];

        output = s->plane[plane].subband[0];

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

            horiz_filter(output, low, high, lowpass_width);

            low    += lowpass_width;

            high   += lowpass_width;

            output += lowpass_width * 2;

        }

        if (s->bpc == 12) {

            output = s->plane[plane].subband[0];

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

                for (j = 0; j < lowpass_width * 2; j++)

                    output[j] *= 4;

                output += lowpass_width * 2;

            }

        }

        /* level 2 */

        lowpass_height  = s->plane[plane].band[1][1].height;

        lowpass_width   = s->plane[plane].band[1][1].width;

        highpass_stride = s->plane[plane].band[1][1].stride;

        if (lowpass_height > s->plane[plane].band[1][1].a_height || lowpass_width > s->plane[plane].band[1][1].a_width ||

            !highpass_stride || s->plane[plane].band[1][1].width > s->plane[plane].band[1][1].a_width) {

            av_log(avctx, AV_LOG_ERROR, "Invalid plane dimensions\n");

            ret = AVERROR(EINVAL);

            goto end;

        }

        av_log(avctx, AV_LOG_DEBUG, "Level 2 plane %i %i %i %i\n", plane, lowpass_height, lowpass_width, highpass_stride);

        low    = s->plane[plane].subband[0];

        high   = s->plane[plane].subband[5];

        output = s->plane[plane].l_h[3];

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

            vert_filter(output, lowpass_width, low, lowpass_width, high, highpass_stride, lowpass_height);

            low++;

            high++;

            output++;

        }

        low    = s->plane[plane].subband[4];

        high   = s->plane[plane].subband[6];

        output = s->plane[plane].l_h[4];

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

            vert_filter(output, lowpass_width, low, highpass_stride, high, highpass_stride, lowpass_height);

            low++;

            high++;

            output++;

        }

        low    = s->plane[plane].l_h[3];

        high   = s->plane[plane].l_h[4];

        output = s->plane[plane].subband[0];

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

            horiz_filter(output, low, high, lowpass_width);

            low    += lowpass_width;

            high   += lowpass_width;

            output += lowpass_width * 2;

        }

        output = s->plane[plane].subband[0];

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

            for (j = 0; j < lowpass_width * 2; j++)

                output[j] *= 4;

            output += lowpass_width * 2;

        }

        /* level 3 */

        lowpass_height  = s->plane[plane].band[2][1].height;

        lowpass_width   = s->plane[plane].band[2][1].width;

        highpass_stride = s->plane[plane].band[2][1].stride;

        if (lowpass_height > s->plane[plane].band[2][1].a_height || lowpass_width > s->plane[plane].band[2][1].a_width ||

            !highpass_stride || s->plane[plane].band[2][1].width > s->plane[plane].band[2][1].a_width) {

            av_log(avctx, AV_LOG_ERROR, "Invalid plane dimensions\n");

            ret = AVERROR(EINVAL);

            goto end;

        }

        av_log(avctx, AV_LOG_DEBUG, "Level 3 plane %i %i %i %i\n", plane, lowpass_height, lowpass_width, highpass_stride);

        low    = s->plane[plane].subband[0];

        high   = s->plane[plane].subband[8];

        output = s->plane[plane].l_h[6];

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

            vert_filter(output, lowpass_width, low, lowpass_width, high, highpass_stride, lowpass_height);

            low++;

            high++;

            output++;

        }

        low    = s->plane[plane].subband[7];

        high   = s->plane[plane].subband[9];

        output = s->plane[plane].l_h[7];

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

            vert_filter(output, lowpass_width, low, highpass_stride, high, highpass_stride, lowpass_height);

            low++;

            high++;

            output++;

        }

        dst = (int16_t *)pic->data[act_plane];

        low  = s->plane[plane].l_h[6];

        high = s->plane[plane].l_h[7];

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

            horiz_filter_clip(dst, low, high, lowpass_width, s->bpc);

            low  += lowpass_width;

            high += lowpass_width;

            dst  += pic->linesize[act_plane] / 2;

        }

    }

end:

    if (ret < 0)

        return ret;

    *got_frame = 1;

    return avpkt->size;

}


static void vc1_inv_trans_8x8_altivec(DCTELEM block[64])

{

    vector signed short src0, src1, src2, src3, src4, src5, src6, src7;

    vector signed int s0, s1, s2, s3, s4, s5, s6, s7;

    vector signed int s8, s9, sA, sB, sC, sD, sE, sF;

    vector signed int t0, t1, t2, t3, t4, t5, t6, t7;

    const vector signed int vec_64 = vec_sl(vec_splat_s32(4), vec_splat_u32(4));

    const vector unsigned int vec_7 = vec_splat_u32(7);

    const vector unsigned int vec_4 = vec_splat_u32(4);

    const vector  signed int vec_4s = vec_splat_s32(4);

    const vector unsigned int vec_3 = vec_splat_u32(3);

    const vector unsigned int vec_2 = vec_splat_u32(2);

    const vector  signed int vec_1s = vec_splat_s32(1);

    const vector unsigned int vec_1 = vec_splat_u32(1);

    src0 = vec_ld(  0, block);

    src1 = vec_ld( 16, block);

    src2 = vec_ld( 32, block);

    src3 = vec_ld( 48, block);

    src4 = vec_ld( 64, block);

    src5 = vec_ld( 80, block);

    src6 = vec_ld( 96, block);

    src7 = vec_ld(112, block);

    s0 = vec_unpackl(src0);

    s1 = vec_unpackl(src1);

    s2 = vec_unpackl(src2);

    s3 = vec_unpackl(src3);

    s4 = vec_unpackl(src4);

    s5 = vec_unpackl(src5);

    s6 = vec_unpackl(src6);

    s7 = vec_unpackl(src7);

    s8 = vec_unpackh(src0);

    s9 = vec_unpackh(src1);

    sA = vec_unpackh(src2);

    sB = vec_unpackh(src3);

    sC = vec_unpackh(src4);

    sD = vec_unpackh(src5);

    sE = vec_unpackh(src6);

    sF = vec_unpackh(src7);

    STEP8(s0, s1, s2, s3, s4, s5, s6, s7, vec_4s);

    SHIFT_HOR8(s0, s1, s2, s3, s4, s5, s6, s7);

    STEP8(s8, s9, sA, sB, sC, sD, sE, sF, vec_4s);

    SHIFT_HOR8(s8, s9, sA, sB, sC, sD, sE, sF);

    src0 = vec_pack(s8, s0);

    src1 = vec_pack(s9, s1);

    src2 = vec_pack(sA, s2);

    src3 = vec_pack(sB, s3);

    src4 = vec_pack(sC, s4);

    src5 = vec_pack(sD, s5);

    src6 = vec_pack(sE, s6);

    src7 = vec_pack(sF, s7);

    TRANSPOSE8(src0, src1, src2, src3, src4, src5, src6, src7);

    s0 = vec_unpackl(src0);

    s1 = vec_unpackl(src1);

    s2 = vec_unpackl(src2);

    s3 = vec_unpackl(src3);

    s4 = vec_unpackl(src4);

    s5 = vec_unpackl(src5);

    s6 = vec_unpackl(src6);

    s7 = vec_unpackl(src7);

    s8 = vec_unpackh(src0);

    s9 = vec_unpackh(src1);

    sA = vec_unpackh(src2);

    sB = vec_unpackh(src3);

    sC = vec_unpackh(src4);

    sD = vec_unpackh(src5);

    sE = vec_unpackh(src6);

    sF = vec_unpackh(src7);

    STEP8(s0, s1, s2, s3, s4, s5, s6, s7, vec_64);

    SHIFT_VERT8(s0, s1, s2, s3, s4, s5, s6, s7);

    STEP8(s8, s9, sA, sB, sC, sD, sE, sF, vec_64);

    SHIFT_VERT8(s8, s9, sA, sB, sC, sD, sE, sF);

    src0 = vec_pack(s8, s0);

    src1 = vec_pack(s9, s1);

    src2 = vec_pack(sA, s2);

    src3 = vec_pack(sB, s3);

    src4 = vec_pack(sC, s4);

    src5 = vec_pack(sD, s5);

    src6 = vec_pack(sE, s6);

    src7 = vec_pack(sF, s7);

    vec_st(src0,  0, block);

    vec_st(src1, 16, block);

    vec_st(src2, 32, block);

    vec_st(src3, 48, block);

    vec_st(src4, 64, block);

    vec_st(src5, 80, block);

    vec_st(src6, 96, block);

    vec_st(src7,112, block);

}


static int decode_tilehdr(WmallDecodeCtx *s)

{

    uint16_t num_samples[WMALL_MAX_CHANNELS] = { 0 }; /* sum of samples for all currently known subframes of a channel */

    uint8_t  contains_subframe[WMALL_MAX_CHANNELS];   /* flag indicating if a channel contains the current subframe */

    int channels_for_cur_subframe = s->num_channels;  /* number of channels that contain the current subframe */

    int fixed_channel_layout = 0;                     /* flag indicating that all channels use the same subfra2me offsets and sizes */

    int min_channel_len = 0;                          /* smallest sum of samples (channels with this length will be processed first) */

    int c, tile_aligned;

    /* reset tiling information */

    for (c = 0; c < s->num_channels; c++)

        s->channel[c].num_subframes = 0;

    tile_aligned = get_bits1(&s->gb);

    if (s->max_num_subframes == 1 || tile_aligned)

        fixed_channel_layout = 1;

    /* loop until the frame data is split between the subframes */

    do {

        int subframe_len, in_use = 0;

        /* check which channels contain the subframe */

        for (c = 0; c < s->num_channels; c++) {

            if (num_samples[c] == min_channel_len) {

                if (fixed_channel_layout || channels_for_cur_subframe == 1 ||

                   (min_channel_len == s->samples_per_frame - s->min_samples_per_subframe)) {

                    contains_subframe[c] = in_use = 1;

                } else {

                    if (get_bits1(&s->gb))

                        contains_subframe[c] = in_use = 1;

                }

            } else

                contains_subframe[c] = 0;

        }

        if (!in_use) {

            av_log(s->avctx, AV_LOG_ERROR,

                   "Found empty subframe\n");

            return AVERROR_INVALIDDATA;

        }

        /* get subframe length, subframe_len == 0 is not allowed */

        if ((subframe_len = decode_subframe_length(s, min_channel_len)) <= 0)

            return AVERROR_INVALIDDATA;

        /* add subframes to the individual channels and find new min_channel_len */

        min_channel_len += subframe_len;

        for (c = 0; c < s->num_channels; c++) {

            WmallChannelCtx *chan = &s->channel[c];

            if (contains_subframe[c]) {

                if (chan->num_subframes >= MAX_SUBFRAMES) {

                    av_log(s->avctx, AV_LOG_ERROR,

                           "broken frame: num subframes > 31\n");

                    return AVERROR_INVALIDDATA;

                }

                chan->subframe_len[chan->num_subframes] = subframe_len;

                num_samples[c] += subframe_len;

                ++chan->num_subframes;

                if (num_samples[c] > s->samples_per_frame) {

                    av_log(s->avctx, AV_LOG_ERROR, "broken frame: "

                           "channel len(%d) > samples_per_frame(%d)\n",

                           num_samples[c], s->samples_per_frame);

                    return AVERROR_INVALIDDATA;

                }

            } else if (num_samples[c] <= min_channel_len) {

                if (num_samples[c] < min_channel_len) {

                    channels_for_cur_subframe = 0;

                    min_channel_len = num_samples[c];

                }

                ++channels_for_cur_subframe;

            }

        }

    } while (min_channel_len < s->samples_per_frame);

    for (c = 0; c < s->num_channels; c++) {

        int i, offset = 0;

        for (i = 0; i < s->channel[c].num_subframes; i++) {

            s->channel[c].subframe_offsets[i] = offset;

            offset += s->channel[c].subframe_len[i];

        }

    }

    return 0;

}


uart_write(void *opaque, hwaddr addr,

           uint64_t val64, unsigned int size)

{

    XilinxUARTLite *s = opaque;

    uint32_t value = val64;

    unsigned char ch = value;

    addr >>= 2;

    switch (addr)

    {

        case R_STATUS:

            hw_error("write to UART STATUS?\n");

            break;

        case R_CTRL:

            if (value & CONTROL_RST_RX) {

                s->rx_fifo_pos = 0;

                s->rx_fifo_len = 0;

            }

            s->regs[addr] = value;

            break;

        case R_TX:

            if (s->chr)

                qemu_chr_fe_write(s->chr, &ch, 1);

            s->regs[addr] = value;

            /* hax.  */

            s->regs[R_STATUS] |= STATUS_IE;

            break;

        default:

            DUART(printf("%s addr=%x v=%x\n", __func__, addr, value));

            if (addr < ARRAY_SIZE(s->regs))

                s->regs[addr] = value;

            break;

    }

    uart_update_status(s);

    uart_update_irq(s);

}


static CharDriverState *net_vhost_parse_chardev(const NetdevVhostUserOptions *opts)

{

    CharDriverState *chr = qemu_chr_find(opts->chardev);

    VhostUserChardevProps props;

    if (chr == NULL) {

        error_report("chardev \"%s\" not found", opts->chardev);

        return NULL;

    }

    /* inspect chardev opts */

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

    if (qemu_opt_foreach(chr->opts, net_vhost_chardev_opts, &props, NULL)) {

        return NULL;

    }

    if (!props.is_socket || !props.is_unix) {

        error_report("chardev \"%s\" is not a unix socket",

                     opts->chardev);

        return NULL;

    }

    qemu_chr_fe_claim_no_fail(chr);

    return chr;

}


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

{

    int ret, size;

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

    size= MP3_PACKET_SIZE;

    ret= av_get_packet(s->pb, pkt, size);

    pkt->stream_index = 0;

    if (ret <= 0) {

        if(ret<0)

            return ret;

        return AVERROR_EOF;

    }

    if (ret > ID3v1_TAG_SIZE &&

        memcmp(&pkt->data[ret - ID3v1_TAG_SIZE], "TAG", 3) == 0)

        ret -= ID3v1_TAG_SIZE;

    /* note: we need to modify the packet size here to handle the last

       packet */

    pkt->size = ret;

    return ret;

}


static int pcx_decode_frame(AVCodecContext *avctx, void *data, int *got_frame,

                            AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size       = avpkt->size;

    AVFrame *const p   = data;

    int compressed, xmin, ymin, xmax, ymax;

    unsigned int w, h, bits_per_pixel, bytes_per_line, nplanes, stride, y, x,

                 bytes_per_scanline;

    uint8_t *ptr;

    const uint8_t *buf_end = buf + buf_size;

    const uint8_t *bufstart = buf;

    uint8_t *scanline;

    int ret = -1;

    if (buf[0] != 0x0a || buf[1] > 5) {

        av_log(avctx, AV_LOG_ERROR, "this is not PCX encoded data\n");

        return AVERROR_INVALIDDATA;

    }

    compressed = buf[2];

    xmin       = AV_RL16(buf + 4);

    ymin       = AV_RL16(buf + 6);

    xmax       = AV_RL16(buf + 8);

    ymax       = AV_RL16(buf + 10);

    if (xmax < xmin || ymax < ymin) {

        av_log(avctx, AV_LOG_ERROR, "invalid image dimensions\n");

        return AVERROR_INVALIDDATA;

    }

    w = xmax - xmin + 1;

    h = ymax - ymin + 1;

    bits_per_pixel     = buf[3];

    bytes_per_line     = AV_RL16(buf + 66);

    nplanes            = buf[65];

    bytes_per_scanline = nplanes * bytes_per_line;

    if (bytes_per_scanline < (w * bits_per_pixel * nplanes + 7) / 8 ||

        (!compressed && bytes_per_scanline > buf_size / h)) {

        av_log(avctx, AV_LOG_ERROR, "PCX data is corrupted\n");

        return AVERROR_INVALIDDATA;

    }

    switch ((nplanes << 8) + bits_per_pixel) {

    case 0x0308:

        avctx->pix_fmt = AV_PIX_FMT_RGB24;

        break;

    case 0x0108:

    case 0x0104:

    case 0x0102:

    case 0x0101:

    case 0x0401:

    case 0x0301:

    case 0x0201:

        avctx->pix_fmt = AV_PIX_FMT_PAL8;

        break;

    default:

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

        return AVERROR_INVALIDDATA;

    }

    buf += 128;

    if ((ret = ff_set_dimensions(avctx, w, h)) < 0)

        return ret;

    if ((ret = ff_get_buffer(avctx, p, 0)) < 0) {

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

        return ret;

    }

    p->pict_type = AV_PICTURE_TYPE_I;

    ptr    = p->data[0];

    stride = p->linesize[0];

    scanline = av_malloc(bytes_per_scanline);

    if (!scanline)

        return AVERROR(ENOMEM);

    if (nplanes == 3 && bits_per_pixel == 8) {

        for (y = 0; y < h; y++) {

            buf = pcx_rle_decode(buf, buf_end,

                                 scanline, bytes_per_scanline, compressed);

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

                ptr[3 * x]     = scanline[x];

                ptr[3 * x + 1] = scanline[x + bytes_per_line];

                ptr[3 * x + 2] = scanline[x + (bytes_per_line << 1)];

            }

            ptr += stride;

        }

    } else if (nplanes == 1 && bits_per_pixel == 8) {

        const uint8_t *palstart = bufstart + buf_size - 769;

        if (buf_size < 769) {

            av_log(avctx, AV_LOG_ERROR, "File is too short\n");

            ret = avctx->err_recognition & AV_EF_EXPLODE ?

                  AVERROR_INVALIDDATA : buf_size;

            goto end;

        }

        for (y = 0; y < h; y++, ptr += stride) {

            buf = pcx_rle_decode(buf, buf_end,

                                 scanline, bytes_per_scanline, compressed);

            memcpy(ptr, scanline, w);

        }

        if (buf != palstart) {

            av_log(avctx, AV_LOG_WARNING, "image data possibly corrupted\n");

            buf = palstart;

        }

        if (*buf++ != 12) {

            av_log(avctx, AV_LOG_ERROR, "expected palette after image data\n");

            ret = avctx->err_recognition & AV_EF_EXPLODE ?

                  AVERROR_INVALIDDATA : buf_size;

            goto end;

        }

    } else if (nplanes == 1) {   /* all packed formats, max. 16 colors */

        GetBitContext s;

        for (y = 0; y < h; y++) {

            init_get_bits(&s, scanline, bytes_per_scanline << 3);

            buf = pcx_rle_decode(buf, buf_end,

                                 scanline, bytes_per_scanline, compressed);

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

                ptr[x] = get_bits(&s, bits_per_pixel);

            ptr += stride;

        }

    } else {    /* planar, 4, 8 or 16 colors */

        int i;

        for (y = 0; y < h; y++) {

            buf = pcx_rle_decode(buf, buf_end,

                                 scanline, bytes_per_scanline, compressed);

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

                int m = 0x80 >> (x & 7), v = 0;

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

                    v <<= 1;

                    v  += !!(scanline[i * bytes_per_line + (x >> 3)] & m);

                }

                ptr[x] = v;

            }

            ptr += stride;

        }

    }

    if (nplanes == 1 && bits_per_pixel == 8) {

        pcx_palette(&buf, (uint32_t *)p->data[1], 256);

    } else if (bits_per_pixel < 8) {

        const uint8_t *palette = bufstart + 16;

        pcx_palette(&palette, (uint32_t *)p->data[1], 16);

    }

    *got_frame = 1;

    ret = buf - bufstart;

end:

    av_free(scanline);

    return ret;

}


static int mkv_write_trailer(AVFormatContext *s)

{

    MatroskaMuxContext *mkv = s->priv_data;

    AVIOContext *pb = s->pb;

    int64_t currentpos, cuespos;

    int ret;

    // check if we have an audio packet cached

    if (mkv->cur_audio_pkt.size > 0) {

        ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);

        mkv->cur_audio_pkt.size = 0;

        if (ret < 0) {

            av_log(s, AV_LOG_ERROR, "Could not write cached audio packet ret:%d\n", ret);

            return ret;

        }

    }

    if (mkv->dyn_bc) {

        end_ebml_master(mkv->dyn_bc, mkv->cluster);

        mkv_flush_dynbuf(s);

    } else if (mkv->cluster_pos) {

        end_ebml_master(pb, mkv->cluster);

    }

    if (pb->seekable) {

        if (mkv->cues->num_entries) {

            cuespos = mkv_write_cues(pb, mkv->cues, s->nb_streams);

            ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CUES, cuespos);

            if (ret < 0) return ret;

        }

        mkv_write_seekhead(pb, mkv->main_seekhead);

        // update the duration

        av_log(s, AV_LOG_DEBUG, "end duration = %" PRIu64 "\n", mkv->duration);

        currentpos = avio_tell(pb);

        avio_seek(pb, mkv->duration_offset, SEEK_SET);

        put_ebml_float(pb, MATROSKA_ID_DURATION, mkv->duration);

        avio_seek(pb, currentpos, SEEK_SET);

    }

    end_ebml_master(pb, mkv->segment);

    av_free(mkv->tracks);

    av_freep(&mkv->cues->entries);

    av_freep(&mkv->cues);

    av_destruct_packet(&mkv->cur_audio_pkt);

    avio_flush(pb);

    return 0;

}


int is_adx(const unsigned char *buf,size_t bufsize)

{

	int	offset;

	if (buf[0]!=0x80) return 0;

	offset = (read_long(buf)^0x80000000)+4;

	if (bufsize<offset || memcmp(buf+offset-6,"(c)CRI",6)) return 0;

	return offset;

}


rfc3986_parse_port(URI *uri, const char **str)

{

    const char *cur = *str;

    if (ISA_DIGIT(cur)) {

	if (uri != NULL)

	    uri->port = 0;

	while (ISA_DIGIT(cur)) {

	    if (uri != NULL)

		uri->port = uri->port * 10 + (*cur - '0');

	    cur++;

	}

	*str = cur;

	return(0);

    }

    return(1);

}


static int usb_net_handle_dataout(USBNetState *s, USBPacket *p)

{

    int ret = p->len;

    int sz = sizeof(s->out_buf) - s->out_ptr;

    struct rndis_packet_msg_type *msg =

            (struct rndis_packet_msg_type *) s->out_buf;

    uint32_t len;

#ifdef TRAFFIC_DEBUG

    fprintf(stderr, "usbnet: data out len %u\n", p->len);

    {

        int i;

        fprintf(stderr, ":");

        for (i = 0; i < p->len; i++) {

            if (!(i & 15))

                fprintf(stderr, "\n%04x:", i);

            fprintf(stderr, " %02x", p->data[i]);

        }

        fprintf(stderr, "\n\n");

    }

#endif

    if (sz > ret)

        sz = ret;

    memcpy(&s->out_buf[s->out_ptr], p->data, sz);

    s->out_ptr += sz;

    if (!is_rndis(s)) {

        if (ret < 64) {

            qemu_send_packet(&s->nic->nc, s->out_buf, s->out_ptr);

            s->out_ptr = 0;

        }

        return ret;

    }

    len = le32_to_cpu(msg->MessageLength);

    if (s->out_ptr < 8 || s->out_ptr < len)

        return ret;

    if (le32_to_cpu(msg->MessageType) == RNDIS_PACKET_MSG) {

        uint32_t offs = 8 + le32_to_cpu(msg->DataOffset);

        uint32_t size = le32_to_cpu(msg->DataLength);

        if (offs + size <= len)

            qemu_send_packet(&s->nic->nc, s->out_buf + offs, size);

    }

    s->out_ptr -= len;

    memmove(s->out_buf, &s->out_buf[len], s->out_ptr);

    return ret;

}