// pipeline_demo — 帧源抽象演示: 同一套上层代码, V4L2 / rockit 后端可切换
//
// 用法:
//   pipeline_demo --source v4l2|rockit [--w 1280] [--h 720] [--frames 60]
//                 [--out-prefix /root/handwash/pipe_out]
//
// 流程(上层管线骨架, 与具体帧源解耦):
//   FrameSource::GetFrame → RGA letterbox(192/224) → [下一阶段: RKNN 推理] → PutFrame
//
// 输出: 帧率 / 各段时延统计 + 两张 RGB 文件(可直接喂 model_bench 验证推理)。
#include "camera/camera.h"
#include "camera/vi_camera.h"
#include "common/dma_buffer.h"
#include "common/log.h"
#include "common/time_utils.h"
#include "pipeline/frame_source.h"
#include "rga/rga_utils.h"

#include <cstdio>
#include <fstream>
#include <memory>
#include <string>

namespace {
using hwtime::now_ms;   // 统一时间源(common/time_utils.h)
bool write_file(const std::string& fn, const void* data, size_t size) {
    std::ofstream of(fn, std::ios::binary);
    if (!of) return false;
    of.write(static_cast<const char*>(data), (std::streamsize)size);
    return (bool)of;
}

// 帧源工厂(应用层完成选择 → 上层管线只见 FrameSource 接口)
std::unique_ptr<FrameSource> MakeFrameSource(const std::string& type) {
    if (type == "rockit") return std::unique_ptr<FrameSource>(new ViCamera());
    if (type == "v4l2")   return std::unique_ptr<FrameSource>(new Camera());
    return nullptr;
}
}  // namespace

int main(int argc, char** argv) {
    std::string source = "v4l2";
    uint32_t w = 1280, h = 720;
    int frames = 60;
    std::string out_prefix = "/root/handwash/pipe_out";

    for (int i = 1; i < argc; ++i) {
        std::string a = argv[i];
        if (a == "--source" && i + 1 < argc) source = argv[++i];
        else if (a == "--w" && i + 1 < argc) w = (uint32_t)atoi(argv[++i]);
        else if (a == "--h" && i + 1 < argc) h = (uint32_t)atoi(argv[++i]);
        else if (a == "--frames" && i + 1 < argc) frames = atoi(argv[++i]);
        else if (a == "--out-prefix" && i + 1 < argc) out_prefix = argv[++i];
        else {
            HW_LOG("用法: %s --source v4l2|rockit [--w W] [--h H] [--frames N] "
                   "[--out-prefix P]", argv[0]);
            return 1;
        }
    }

    // ---- 帧源(抽象)----
    auto src = MakeFrameSource(source);
    if (!src) {
        HW_ERR("未知帧源: %s", source.c_str());
        return 1;
    }
    CameraConfig cfg;
    cfg.width     = w;
    cfg.height    = h;
    cfg.buf_count = 6;
    if (!src->Open(cfg)) return 2;
    if (!src->Start()) return 2;
    HW_LOG("帧源已启动: %s (%ux%u)", src->name(), w, h);

    // ---- 预处理缓冲(dma-buf, 零拷贝给后续推理)----
    DmaBuffer out192, out224;
    if (!dma_buf_alloc_auto(192 * 192 * 3, &out192)) return 3;
    if (!dma_buf_alloc_auto(224 * 224 * 3, &out224)) return 3;
    RgaImage dst192 = RgaImage::Rgb888(out192.fd, out192.va, 192, 192);
    RgaImage dst224 = RgaImage::Rgb888(out224.fd, out224.va, 224, 224);

    // ---- 主循环: 取帧 → 预处理 → (推理占位) → 归还 ----
    double t_begin = now_ms();
    double sum_rga192 = 0, sum_rga224 = 0;
    int got = 0, timeout = 0, saved = 0;
    uint64_t last_ts = 0;
    double sum_interval = 0;

    for (int i = 0; i < frames; ++i) {
        CameraFrame f;
        if (!src->GetFrame(&f, 2000)) {
            timeout++;
            continue;
        }
        got++;
        if (last_ts) sum_interval += (double)(f.timestamp_us - last_ts) / 1000.0;
        last_ts = f.timestamp_us;

        // 预处理: 帧(dma-buf fd) → letterbox RGB(每一步都是 fd→fd 零拷贝)
        RgaImage frame = RgaImage::Nv12(f.dmabuf_fd, f.vaddr, f.width, f.height, f.wstride);
        double t0 = now_ms();
        if (!RgaLetterbox(frame, dst192, 0x72727272)) { src->PutFrame(f); return 3; }
        double t1 = now_ms();
        if (!RgaLetterbox(frame, dst224, 0x72727272)) { src->PutFrame(f); return 3; }
        double t2 = now_ms();
        sum_rga192 += t1 - t0;
        sum_rga224 += t2 - t1;

        // [下一阶段接口点]: Detector.Process(dst192) -> boxes; Landmarks.Process(...) -> kpts

        if (saved < 2) {   // 存前两帧预处理结果供检查
            dma_buf_sync_start(out192.fd);
            dma_buf_sync_start(out224.fd);
            write_file(out_prefix + "_det192.rgb", out192.va, 192 * 192 * 3);
            write_file(out_prefix + "_lm224.rgb", out224.va, 224 * 224 * 3);
            saved++;
        }
        src->PutFrame(f);
    }

    double elapsed = now_ms() - t_begin;
    HW_LOG("==== PIPELINE RESULT ====");
    HW_LOG("source=%s frames=%d timeout=%d wall=%.1f ms", src->name(), got, timeout, elapsed);
    if (got > 0) {
        HW_LOG("fps=%.2f avg_interval=%.2f ms",
               got * 1000.0 / elapsed, sum_interval / (got - 1 > 0 ? got - 1 : 1));
        HW_LOG("rga_192=%.2f ms/frame  rga_224=%.2f ms/frame", sum_rga192 / got, sum_rga224 / got);
    }

    src->Stop();
    src->Close();
    return got > 0 ? 0 : 2;
}
