//
//  MWCaptureUtil.h
//  AVCapture
//
//  Created by magewell on 2025/9/25.
//  Copyright © 2025 magewell. All rights reserved.
//

#ifndef MWCaptureUtil_h
#define MWCaptureUtil_h

struct PixelBufferFrame {
    PixelBufferFrame(): pixelBuffer(NULL), timestamp(0), discard(NULL), param(NULL) {
    }
    
    ~PixelBufferFrame() {
        if (discard) { discard(this, param); }
    }
    
    CVPixelBufferRef pixelBuffer;
    uint64_t timestamp;
    
    void (*discard)(PixelBufferFrame *frame, void *param);
    void *param;
};

static uint64_t getTimestamp() {
    uint64_t time = mach_absolute_time();
    static mach_timebase_info_data_t sTimebaseInfo;
    
    if (sTimebaseInfo.denom == 0) {
        mach_timebase_info(&sTimebaseInfo);
    }
    
    long double ret = 1.L * time / 1000 * sTimebaseInfo.numer / sTimebaseInfo.denom;
    return ret / 1000;
}

struct FourccCVPixelFormatPair {
    uint32_t fourcc;
    FourCharCode cvPixel;
};

static const struct FourccCVPixelFormatPair g_fourccMap[] = {
    { MWFOURCC_BGRA,  kCVPixelFormatType_32BGRA},
    { MWFOURCC_ARGB,  kCVPixelFormatType_32ARGB },
    { MWFOURCC_YUYV,  kCVPixelFormatType_422YpCbCr8_yuvs},
    { MWFOURCC_UYVY,  kCVPixelFormatType_422YpCbCr8 },
    { MWFOURCC_NV12,  kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange},
    { MWFOURCC_I420,  kCVPixelFormatType_420YpCbCr8Planar},
};

static FourCharCode fourcc_to_CVPixelFormat(uint32_t fourcc) {
    FourCharCode cvPixel = 0;
    
    for (int j = 0; j < sizeof(g_fourccMap)/sizeof(g_fourccMap[0]); j++) {
        if (g_fourccMap[j].fourcc == fourcc) {
            cvPixel = g_fourccMap[j].cvPixel;
            break;
        }
    }
    
    return cvPixel;
}
#endif /* MWCaptureUtil_h */
