//
//  CaptureUtil.h
//  AVCapture2
//
//  Created by magewell on 2025/8/21.
//  Copyright © 2025 magewell. All rights reserved.
//

#ifndef CaptureUtil_h
#define CaptureUtil_h

#import <mach/mach.h>
#import <mach/mach_time.h>

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;
}

static uint32_t CVPixelFormat_to_fourcc(uint32_t cvPixel) {
    uint32_t fourcc = 0;
    
    for (int j = 0; j < sizeof(g_fourccMap)/sizeof(g_fourccMap[0]); j++) {
        if (g_fourccMap[j].cvPixel == cvPixel) {
            fourcc = g_fourccMap[j].fourcc;
            break;
        }
    }
    
    return fourcc;
}

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;
}

#endif /* CaptureUtil_h */
