#include "display/board_video_player.h"

#include "common/log.h"
#include "rga/rga_utils.h"

#include <rk_mpi_mb.h>
#include <rk_mpi_sys.h>
#include <rk_mpi_vdec.h>

#include <algorithm>
#include <cstring>
#include <fstream>
#include <sstream>

namespace hwdisplay {
namespace {

constexpr size_t kMaxMediaBytes = 32u * 1024 * 1024;
constexpr uint64_t kMicrosPerSecond = 1000000;

}  // namespace

bool BoardAnimationCatalog::Load(const std::string& directory) {
    directory_ = directory;
    files_.clear();
    std::ifstream input(directory + "/catalog.tsv");
    if (!input) return false;
    std::string line;
    std::getline(input, line);  // 表头
    while (std::getline(input, line)) {
        std::istringstream row(line);
        std::string id, key, instruction, video;
        if (!std::getline(row, id, '\t') || !std::getline(row, key, '\t') ||
            !std::getline(row, instruction, '\t') || !std::getline(row, video, '\t'))
            return false;
        if (id.empty() || video.empty()) return false;
        const size_t dot = video.rfind('.');
        if (dot != std::string::npos) video.resize(dot);
        files_[id] = video + ".h264";
    }
    return !files_.empty();
}

std::string BoardAnimationCatalog::PathFor(const std::string& id) const {
    const auto it = files_.find(id);
    return it == files_.end() ? std::string{} : directory_ + "/" + it->second;
}

BoardVideoPlayer::~BoardVideoPlayer() { Close(); }

bool BoardVideoPlayer::ReadAccessUnits(const std::string& path) {
    data_.clear();
    access_units_.clear();
    std::ifstream input(path, std::ios::binary | std::ios::ate);
    if (!input) {
        HW_ERR("video: 无法打开 %s", path.c_str());
        return false;
    }
    const std::streamoff size = input.tellg();
    if (size <= 0 || static_cast<uint64_t>(size) > kMaxMediaBytes) {
        HW_ERR("video: 素材大小无效 %s (%lldB)", path.c_str(), (long long)size);
        return false;
    }
    data_.resize(static_cast<size_t>(size));
    input.seekg(0);
    if (!input.read(reinterpret_cast<char*>(data_.data()), size)) return false;

    // 素材生成脚本给每个访问单元插入 AUD (NAL type 9)。首个 AUD 之前
    // 如果还有 SPS/PPS，则一起归入首个访问单元。
    for (size_t i = 0; i + 4 < data_.size();) {
        size_t prefix = 0;
        if (data_[i] == 0 && data_[i + 1] == 0) {
            if (data_[i + 2] == 1) prefix = 3;
            else if (data_[i + 2] == 0 && data_[i + 3] == 1) prefix = 4;
        }
        if (prefix && i + prefix < data_.size()) {
            if ((data_[i + prefix] & 31) == 9)
                access_units_.push_back(access_units_.empty() ? 0 : i);
            i += prefix + 1;
        } else {
            ++i;
        }
    }
    if (access_units_.empty()) {
        HW_ERR("video: 找不到 AUD，素材必须由 gen_board_animations.sh 生成: %s", path.c_str());
        return false;
    }
    access_units_.push_back(data_.size());
    for (size_t i = 0; i + 1 < access_units_.size(); ++i) {
        if (access_units_[i + 1] <= access_units_[i] ||
            access_units_[i + 1] - access_units_[i] > 512u * 1024) {
            HW_ERR("video: 访问单元大小异常: %s #%zu", path.c_str(), i);
            return false;
        }
    }
    return true;
}

bool BoardVideoPlayer::Open(const std::string& path, const Config& config) {
    Close();
    if (config.fps == 0 || config.fps > 60 || config.source_width == 0 ||
        config.source_height == 0 || config.output_width == 0 || config.output_height == 0 ||
        (config.source_width & 3) || (config.source_height & 1)) {
        HW_ERR("video: 配置无效 (%ux%u -> %ux%u, %u fps)", config.source_width,
               config.source_height, config.output_width, config.output_height, config.fps);
        return false;
    }
    config_ = config;
    if (!ReadAccessUnits(path)) return false;
    if (!system_ready_) {
        const int ret = RK_MPI_SYS_Init();
        if (ret != RK_SUCCESS) {
            HW_ERR("video: RK_MPI_SYS_Init = 0x%x", ret);
            return false;
        }
        system_ready_ = true;
    }
    if (!dma_buf_alloc_auto(static_cast<size_t>(config.output_width) * config.output_height * 4,
                            &output_)) {
        HW_ERR("video: RGA 输出缓冲分配失败");
        return false;
    }

    VDEC_CHN_ATTR_S attr {};
    attr.enMode = VIDEO_MODE_FRAME;
    attr.enType = RK_VIDEO_ID_AVC;
    attr.u32PicWidth = config.source_width;
    attr.u32PicHeight = config.source_height;
    attr.u32PicVirWidth = (config.source_width + 15) & ~15u;
    attr.u32PicVirHeight = (config.source_height + 15) & ~15u;
    attr.u32StreamBufSize = 512 * 1024;
    attr.u32StreamBufCnt = 4;
    attr.u32FrameBufSize = attr.u32PicVirWidth * attr.u32PicVirHeight * 3 / 2;
    attr.u32FrameBufCnt = 8;
    attr.u32FrameBufDepth = 4;
    attr.enPixelFormat = RK_FMT_YUV420P;
    attr.enCompressMode = COMPRESS_MODE_NONE;
    attr.enLib = VDEC_LIB_CODEC;
    int ret = RK_MPI_VDEC_CreateChn(kChannel, &attr);
    if (ret != RK_SUCCESS) {
        HW_ERR("video: RK_MPI_VDEC_CreateChn = 0x%x", ret);
        Close();
        return false;
    }
    channel_open_ = true;
    ret = RK_MPI_VDEC_StartRecvStream(kChannel);
    if (ret != RK_SUCCESS) {
        HW_ERR("video: RK_MPI_VDEC_StartRecvStream = 0x%x", ret);
        Close();
        return false;
    }
    started_us_ = 0;
    clock_started_ = false;
    sent_ = decoded_ = 0;
    stride_ = attr.u32PicVirWidth;
    pixel_format_ = RK_FMT_YUV420P;
    stats_ = Stats{};
    HW_LOG("video: 打开 %s (%zu 帧, %u fps, %ux%u -> %ux%u)", path.c_str(),
           access_units_.size() - 1, config.fps, config.source_width, config.source_height,
           config.output_width, config.output_height);
    return true;
}

bool BoardVideoPlayer::SendOne() {
    const size_t frame = static_cast<size_t>(sent_ % (access_units_.size() - 1));
    const size_t offset = access_units_[frame];
    const size_t length = access_units_[frame + 1] - offset;
    MB_BLK mb = nullptr;
    int ret = RK_MPI_SYS_Malloc(&mb, length);
    if (ret != RK_SUCCESS) {
        HW_ERR("video: RK_MPI_SYS_Malloc(%zu) = 0x%x", length, ret);
        ++stats_.errors;
        return false;
    }
    void* dst = RK_MPI_MB_Handle2VirAddr(mb);
    if (!dst) {
        RK_MPI_SYS_Free(mb);
        HW_ERR("video: 无法映射码流缓冲");
        ++stats_.errors;
        return false;
    }
    std::memcpy(dst, data_.data() + offset, length);
    VDEC_STREAM_S stream {};
    stream.pMbBlk = mb;
    stream.u32Len = static_cast<RK_U32>(length);
    stream.u64PTS = sent_ * kMicrosPerSecond / config_.fps;
    stream.bEndOfFrame = RK_TRUE;
    ret = RK_MPI_VDEC_SendStream(kChannel, &stream, 0);
    RK_MPI_SYS_Free(mb);
    if (ret == RK_ERR_VDEC_BUF_FULL) return false;  // 下次显示 tick 重试
    if (ret != RK_SUCCESS) {
        HW_ERR("video: RK_MPI_VDEC_SendStream = 0x%x", ret);
        ++stats_.errors;
        return false;
    }
    ++sent_;
    ++stats_.sent;
    if (frame + 1 == access_units_.size() - 1) ++stats_.loops;
    return true;
}

void BoardVideoPlayer::Update(uint64_t now_us, const FrameSink& on_frame) {
    if (!channel_open_ || !on_frame) return;
    if (!clock_started_) {
        started_us_ = now_us;
        clock_started_ = true;
    }
    const uint64_t elapsed = now_us >= started_us_ ? now_us - started_us_ : 0;
    const uint64_t due_index = elapsed * config_.fps / kMicrosPerSecond;

    // 固定帧率时间轴；不跳过输入的 P 帧。积压时最多每轮送/取 4 帧，
    // 避免显示主线程长时间被解码任务占住。
    for (int i = 0; i < 4 && sent_ <= due_index &&
                    sent_ >= decoded_ && sent_ - decoded_ < 4; ++i)
        if (!SendOne()) break;

    for (int i = 0; i < 4; ++i) {
        VIDEO_FRAME_INFO_S frame {};
        const int ret = RK_MPI_VDEC_GetFrame(kChannel, &frame, 0);
        if (ret == RK_ERR_VDEC_BUF_EMPTY) break;
        if (ret != RK_SUCCESS) {
            HW_ERR("video: RK_MPI_VDEC_GetFrame = 0x%x", ret);
            ++stats_.errors;
            break;
        }
        if (frame.stVFrame.u32FrameFlag & FRAME_FLAG_EOS) {
            RK_MPI_VDEC_ReleaseFrame(kChannel, &frame);
            break;
        }
        const uint64_t frame_index = decoded_++;
        ++stats_.decoded;
        if (frame.stVFrame.u32VirWidth) {
            stride_ = frame.stVFrame.u32VirWidth;
            pixel_format_ = static_cast<int>(frame.stVFrame.enPixelFormat);
        }
        if (frame_index + 1 < due_index) {
            ++stats_.late;
            RK_MPI_VDEC_ReleaseFrame(kChannel, &frame);
            continue;
        }

        const int fd = RK_MPI_MB_Handle2Fd(frame.stVFrame.pMbBlk);
        void* va = RK_MPI_MB_Handle2VirAddr(frame.stVFrame.pMbBlk);
        const uint32_t width = frame.stVFrame.u32Width ? frame.stVFrame.u32Width : config_.source_width;
        const uint32_t height = frame.stVFrame.u32Height ? frame.stVFrame.u32Height : config_.source_height;
        if (fd < 0 || !va ||
            (pixel_format_ != RK_FMT_YUV420P && pixel_format_ != RK_FMT_YUV420SP)) {
            HW_ERR("video: 不支持的解码帧格式=%d fd=%d va=%p", pixel_format_, fd, va);
            ++stats_.errors;
            RK_MPI_VDEC_ReleaseFrame(kChannel, &frame);
            continue;
        }
        const RgaImage src = pixel_format_ == RK_FMT_YUV420P
            ? RgaImage::Yuv420P(fd, va, width, height, stride_)
            : RgaImage::Nv12(fd, va, width, height, stride_);
        const RgaImage dst = RgaImage::Xrgb8888(output_.fd, output_.va,
                                                config_.output_width, config_.output_height);
        if (RgaConvert(src, dst) && dma_buf_sync_start(output_.fd) == 0) {
            on_frame(static_cast<const uint8_t*>(output_.va), output_.size);
            dma_buf_sync_end(output_.fd);
            ++stats_.shown;
        } else {
            ++stats_.errors;
        }
        RK_MPI_VDEC_ReleaseFrame(kChannel, &frame);
    }
}

void BoardVideoPlayer::Close() {
    if (channel_open_) {
        RK_MPI_VDEC_StopRecvStream(kChannel);
        RK_MPI_VDEC_DestroyChn(kChannel);
        channel_open_ = false;
    }
    if (output_.fd >= 0) dma_buf_free(&output_);
    data_.clear();
    access_units_.clear();
    sent_ = decoded_ = 0;
    clock_started_ = false;
}

}  // namespace hwdisplay
