// test_camera — 摄像头采集单测(可独立运行)
//
// 用法:
//   test_camera [--dev /dev/video22] [--width 1280] [--height 720]
//               [--frames 100] [--save-count 2] [--save /root/handwash/cam_save]
//
// 功能:
//   1) 打开摄像头连续采集 N 帧, 统计 FPS / 帧间隔 / 超时次数(内核时间戳);
//   2) 前 save-count 帧存 NV12 原始文件(供 test_rga 离线复用);
//   3) 打印 dma-buf fd 导出状态(零拷贝链路可用性)。
//
// 前置: 板端需先启动 3A 服务:  /oem/usr/bin/rkaiq_3A_server &
#include "camera/camera.h"
#include "common/log.h"
#include "common/time_utils.h"

#include <cstdio>
#include <cstring>
#include <fstream>
#include <string>

namespace {
using hwtime::now_ms;   // 统一时间源(common/time_utils.h)
}  // namespace

int main(int argc, char** argv) {
    CameraConfig cfg;
    int frames      = 100;
    int save_count  = 2;
    std::string save_prefix = "/root/handwash/cam_save";

    for (int i = 1; i < argc; ++i) {
        std::string a = argv[i];
        if (a == "--dev" && i + 1 < argc) cfg.device = argv[++i];
        else if (a == "--width" && i + 1 < argc) cfg.width = (uint32_t)atoi(argv[++i]);
        else if (a == "--height" && i + 1 < argc) cfg.height = (uint32_t)atoi(argv[++i]);
        else if (a == "--frames" && i + 1 < argc) frames = atoi(argv[++i]);
        else if (a == "--save-count" && i + 1 < argc) save_count = atoi(argv[++i]);
        else if (a == "--save" && i + 1 < argc) save_prefix = argv[++i];
        else if (a == "--no-dmabuf") cfg.export_dmabuf = false;
        else {
            HW_LOG("用法: %s [--dev /dev/video22] [--width W] [--height H] [--frames N] "
                   "[--save-count N] [--save PREFIX] [--no-dmabuf]",
                   argv[0]);
            return 1;
        }
    }

    Camera cam;
    if (!cam.Open(cfg)) return 1;
    if (!cam.Start()) return 1;
    HW_LOG("camera 开始采集: %ux%u, 目标 %d 帧", cfg.width, cfg.height, frames);

    double t_begin = now_ms();
    uint64_t last_ts = 0, first_ts = 0;
    double sum_interval = 0;
    int got = 0, timeout = 0, saved = 0;
    bool printed_fd = false;

    for (int i = 0; i < frames; ++i) {
        CameraFrame f;
        if (!cam.GetFrame(&f, 2000)) {
            timeout++;
            continue;
        }
        got++;
        if (!printed_fd) {
            printed_fd = true;
            HW_LOG("帧信息: vaddr=%p dmabuf_fd=%d size=%zu wstride=%u", f.vaddr, f.dmabuf_fd,
                   f.size, f.wstride);
        }
        if (first_ts == 0) first_ts = f.timestamp_us;
        if (last_ts) {
            sum_interval += (double)(f.timestamp_us - last_ts) / 1000.0;
        }
        last_ts = f.timestamp_us;

        if (saved < save_count) {
            char fn[256];
            snprintf(fn, sizeof(fn), "%s_%d.nv12", save_prefix.c_str(), saved);
            std::ofstream of(fn, std::ios::binary);
            if (of) {
                of.write(static_cast<const char*>(f.vaddr), (std::streamsize)f.size);
                HW_LOG("已保存 %s (%zu bytes)", fn, f.size);
                saved++;
            } else {
                HW_ERR("无法写 %s", fn);
            }
        }
        cam.PutFrame(f);
    }

    double elapsed = now_ms() - t_begin;
    HW_LOG("==== CAMERA RESULT ====");
    if (got > 0) {
        double kernel_span = (double)(last_ts - first_ts) / 1000.0;  // ms
        HW_LOG("frames=%d timeout=%d", got, timeout);
        HW_LOG("wall=%.1f ms, kernel_span=%.1f ms", elapsed, kernel_span);
        if (kernel_span > 0) HW_LOG("fps=%.2f (kernel), avg_interval=%.2f ms",
                                    got * 1000.0 / kernel_span, sum_interval / (got - 1 > 0 ? got - 1 : 1));
        HW_LOG("wall_fps=%.2f", got * 1000.0 / elapsed);
    } else {
        HW_ERR("一帧都没取到 (timeout=%d) — 检查 3A 服务是否运行", timeout);
    }

    cam.Stop();
    cam.Close();
    return got > 0 ? 0 : 2;
}
