static int read_packet(AVFormatContext *avctx, AVPacket *pkt)
{
    MlvContext *mlv = avctx->priv_data;
    AVIOContext *pb;
    AVStream *st = avctx->streams[mlv->stream_index];
    int index, ret;
    unsigned int size, space;

    if (mlv->pts >= st->duration)
        return AVERROR_EOF;

    index = av_index_search_timestamp(st, mlv->pts, AVSEEK_FLAG_ANY);
    if (index < 0) {
        av_log(avctx, AV_LOG_ERROR, "could not find index entry for frame %"PRId64"\n", mlv->pts);
        return AVERROR(EIO);
    }

    pb = mlv->pb[st->index_entries[index].size];
    avio_seek(pb, st->index_entries[index].pos, SEEK_SET);

    avio_skip(pb, 4); // blockType
    size = avio_rl32(pb);
    if (size < 16)
        return AVERROR_INVALIDDATA;
    avio_skip(pb, 12); //timestamp, frameNumber
    if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
        avio_skip(pb, 8); // cropPosX, cropPosY, panPosX, panPosY
    space = avio_rl32(pb);
    avio_skip(pb, space);

    if ((mlv->class[st->id] & (MLV_CLASS_FLAG_DELTA|MLV_CLASS_FLAG_LZMA))) {
        ret = AVERROR_PATCHWELCOME;
    } else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
        ret = av_get_packet(pb, pkt, (st->codec->width * st->codec->height * st->codec->bits_per_coded_sample + 7) >> 3);
    } else { // AVMEDIA_TYPE_AUDIO
        if (space > UINT_MAX - 24 || size < (24 + space))
            return AVERROR_INVALIDDATA;
        ret = av_get_packet(pb, pkt, size - (24 + space));
    }

    if (ret < 0)
        return ret;

    pkt->stream_index = mlv->stream_index;
    pkt->pts = mlv->pts;

    mlv->stream_index++;
    if (mlv->stream_index == avctx->nb_streams) {
        mlv->stream_index = 0;
        mlv->pts++;
    }
    return 0;
}