#pragma once

// RV1106 教学视频播放器。素材是带 AUD 的 Annex-B H.264 裸流，帧率由配置给定。
// 所有方法都在显示主线程调用；Rockit 负责解码，RGA 负责 I420 -> BGRA。

#include "common/dma_buffer.h"

#include <cstddef>
#include <cstdint>
#include <functional>
#include <string>
#include <unordered_map>
#include <vector>

namespace hwdisplay {

class BoardAnimationCatalog {
public:
    bool Load(const std::string& directory);
    std::string PathFor(const std::string& id) const;

private:
    std::string directory_;
    std::unordered_map<std::string, std::string> files_;
};

class BoardVideoPlayer {
public:
    struct Config {
        uint32_t source_width = 392;
        uint32_t source_height = 260;
        uint32_t output_width = 394;
        uint32_t output_height = 260;
        uint32_t fps = 30;
    };

    struct Stats {
        uint64_t sent = 0;
        uint64_t decoded = 0;
        uint64_t shown = 0;
        uint64_t late = 0;
        uint64_t loops = 0;
        uint64_t errors = 0;
    };

    using FrameSink = std::function<void(const uint8_t* bgra, size_t bytes)>;

    ~BoardVideoPlayer();
    bool Open(const std::string& path, const Config& config);
    void Update(uint64_t now_us, const FrameSink& on_frame);
    void Close();

    bool is_open() const { return channel_open_; }
    const Stats& stats() const { return stats_; }

private:
    bool ReadAccessUnits(const std::string& path);
    bool SendOne();

    static constexpr int kChannel = 0;
    Config config_;
    std::vector<uint8_t> data_;
    std::vector<size_t> access_units_;
    DmaBuffer output_;
    uint64_t started_us_ = 0;
    bool clock_started_ = false;
    uint64_t sent_ = 0;
    uint64_t decoded_ = 0;
    uint32_t stride_ = 0;
    int pixel_format_ = -1;
    bool system_ready_ = false;
    bool channel_open_ = false;
    Stats stats_;
};

}  // namespace hwdisplay
