// VideoPane 实现
#include "display/video_pane.h"

#include "common/log.h"
#include "common/time_utils.h"

#include <cstring>

namespace hwdisplay {

VideoPane::~VideoPane() {
    if (canvas_) canvas_ = nullptr;   // LVGL 对象由父对象树释放
    dma_buf_free(&buf_);
    dma_buf_free(&tmp_);
}

void VideoPane::SetMirror(bool on) {
    if (on == mirror_) return;
    if (on && tmp_.fd < 0) {
        // 镜像需要一块同尺寸中转缓冲(blit → 翻转拷贝)
        if (!dma_buf_alloc_auto((size_t)dst_.width * dst_.height * 4, &tmp_)) {
            HW_ERR("pane[%s]: 镜像中转缓冲分配失败", tag_.c_str());
            return;
        }
    }
    mirror_ = on;
    HW_LOG("pane[%s]: 镜像显示 %s", tag_.c_str(), on ? "开" : "关");
}

bool VideoPane::Init(lv_obj_t* parent, std::string tag, int x, int y, int w, int h, RgaFit fit) {
    tag_ = std::move(tag);
    fit_ = fit;

    if (!dma_buf_alloc_auto((size_t)w * h * 4, &buf_)) {
        HW_ERR("pane[%s]: 画布分配失败 (%dx%d)", tag_.c_str(), w, h);
        return false;
    }
    // 画布初始化为黑色(RGA 首帧前可见)
    std::memset(buf_.va, 0, (size_t)w * h * 4);
    dst_ = RgaImage::Xrgb8888(buf_.fd, buf_.va, (uint32_t)w, (uint32_t)h);

    canvas_ = lv_canvas_create(parent);
    if (!canvas_) {
        HW_ERR("pane[%s]: 创建 LVGL canvas 失败", tag_.c_str());
        return false;
    }
    lv_canvas_set_buffer(canvas_, buf_.va, w, h, LV_COLOR_FORMAT_XRGB8888);
    lv_obj_set_pos(canvas_, x, y);
    lv_obj_remove_flag(canvas_, LV_OBJ_FLAG_SCROLLABLE);
    HW_LOG("pane[%s]: %dx%d @(%d,%d) canvas_fd=%d va=%p fit=%s", tag_.c_str(), w, h, x, y,
           buf_.fd, buf_.va, fit_ == RgaFit::Letterbox ? "letterbox" : "crop");
    return true;
}

bool VideoPane::Push(const CameraFrame& f) {
    stats_.frames_in++;
    src_w_.store((int)f.width);
    src_h_.store((int)f.height);
    RgaImage src = RgaImage::Nv12(f.dmabuf_fd, f.vaddr, f.width, f.height, f.wstride);

    double t0 = hwtime::now_ms();
    bool   ok;
    if (mirror_ && tmp_.fd >= 0) {
        // 先缩放进中转缓冲, 再水平镜像拷贝到画布(2 次 RGA)
        RgaImage mid = RgaImage::Xrgb8888(tmp_.fd, tmp_.va, dst_.width, dst_.height);
        ok = RgaFitBlit(src, mid, fit_, 0x00000000u) && RgaFlipH(mid, dst_);
    } else {
        ok = RgaFitBlit(src, dst_, fit_, 0x00000000u);
    }
    double dt = hwtime::now_ms() - t0;

    if (!ok) {
        stats_.errors++;
        return false;
    }
    stats_.pushed++;
    stats_.rga_ms_avg = stats_.rga_ms_avg == 0 ? dt : stats_.rga_ms_avg * 0.9 + dt * 0.1;
    dirty_.store(true, std::memory_order_release);
    return true;
}

void VideoPane::MapPoint(float cx, float cy, float* out_x, float* out_y) const {
    const float dw = (float)dst_.width, dh = (float)dst_.height;
    const float sw = (float)src_w_.load(), sh = (float)src_h_.load();
    float x = cx, y = cy;

    if (sw > 0 && sh > 0) {
        if (fit_ == RgaFit::Letterbox) {
            // 与 RgaLetterbox 一致: 等比缩放 + 居中留边
            const float s     = std::min(dw / sw, dh / sh);
            const float off_x = (dw - sw * s) * 0.5f;
            const float off_y = (dh - sh * s) * 0.5f;
            x = cx * s + off_x;
            y = cy * s + off_y;
        } else {
            // 与 RgaFitBlit(CropCenter) 一致: 居中裁切后缩放铺满
            const float s = std::max(dw / sw, dh / sh);
            x = cx * s - (sw * s - dw) * 0.5f;
            y = cy * s - (sh * s - dh) * 0.5f;
        }
    }
    if (mirror_) x = dw - 1.f - x;
    *out_x = x;
    *out_y = y;
}

}  // namespace hwdisplay
