文件
dayu-color/research/cms-audit-20261103/probe.mm
T

125 行
11 KiB
Plaintext

// Bounded, headless observations of the user-selected installed shaders.
// No vendor source, shader code, LUT data, app launch or host document is copied.
// Build instructions and interpretation limits are in report.md.
#import <Foundation/Foundation.h>
#import <Metal/Metal.h>
#include <simd/simd.h>
#include <cmath>
#include <cstring>
#include <vector>
#include <CommonCrypto/CommonDigest.h>
struct CSTParams { int inputGamut,inputTransfer,outputGamut,outputTransfer,toneMapping; };
struct BasisParams {
int colorspace;
float exposure,balanceTarget,balanceStrength,contrast,pivot,highlights,midtones,shadows;
float trimLow,trimHigh,trimToeStrength,trimShoulderStrength,shadowContrast,shadowPivot,hiContrast,hiPivot,chromaMix;
unsigned char bypassBalance,bypassTone,bypassExposure,bypassContrast;
float saturation;
};
struct DayuRenderParams { CSTParams input,output;BasisParams basis;int stages,sourceLinear,destinationLinear,reserved;CSTParams basisInput,basisOutput; };
static_assert(sizeof(CSTParams)==20 && sizeof(BasisParams)==80);
static_assert(sizeof(DayuRenderParams)==176);
struct Vertex { simd_float2 position,uv; };
static void need(bool value,NSString *reason) {
if(!value) @throw [NSException exceptionWithName:@"CMSAudit" reason:reason userInfo:nil];
}
static NSString *digest(NSString *path) {
NSData *data=[NSData dataWithContentsOfFile:path];need(data!=nil,path);
unsigned char hash[CC_SHA256_DIGEST_LENGTH];CC_SHA256(data.bytes,(CC_LONG)data.length,hash);
NSMutableString *s=[NSMutableString string];for(auto v:hash)[s appendFormat:@"%02x",v];return s;
}
static double encodeDI(double v) {
return v<=.00262409?v*10.44426855:(std::log2(v+.0075)+7)*.07329248;
}
static double decodeDI(double v) {
return v<=.02740668?v/10.44426855:std::exp2(v/.07329248-7)-.0075;
}
static std::vector<float> render(id<MTLDevice>device,id<MTLCommandQueue>queue,
id<MTLRenderPipelineState>pipeline,const std::vector<float>&input,const void *params,NSUInteger length) {
NSUInteger width=input.size()/4;need(width>0 && input.size()%4==0,@"invalid input");
auto desc=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA32Float width:width height:1 mipmapped:NO];
desc.storageMode=MTLStorageModeShared;desc.usage=MTLTextureUsageShaderRead|MTLTextureUsageRenderTarget;
id<MTLTexture>source=[device newTextureWithDescriptor:desc],output=[device newTextureWithDescriptor:desc];
need(source && output,@"texture allocation");
[source replaceRegion:MTLRegionMake2D(0,0,width,1) mipmapLevel:0 withBytes:input.data() bytesPerRow:width*16];
float w=width,h=1;Vertex vertices[]={{{-w/2,-h/2},{0,1}},{{w/2,-h/2},{1,1}},{{-w/2,h/2},{0,0}},{{w/2,h/2},{1,0}}};
simd_uint2 dims={(unsigned)width,1};
auto pass=[MTLRenderPassDescriptor renderPassDescriptor];pass.colorAttachments[0].texture=output;
pass.colorAttachments[0].loadAction=MTLLoadActionDontCare;pass.colorAttachments[0].storeAction=MTLStoreActionStore;
auto cb=[queue commandBuffer];auto enc=[cb renderCommandEncoderWithDescriptor:pass];
[enc setRenderPipelineState:pipeline];[enc setVertexBytes:vertices length:sizeof(vertices) atIndex:0];
[enc setVertexBytes:&dims length:sizeof(dims) atIndex:1];[enc setFragmentTexture:source atIndex:0];
[enc setFragmentBytes:params length:length atIndex:0];[enc drawPrimitives:MTLPrimitiveTypeTriangleStrip vertexStart:0 vertexCount:4];
[enc endEncoding];[cb commit];[cb waitUntilCompleted];need(cb.status==MTLCommandBufferStatusCompleted,cb.error.description?:@"GPU failure");
std::vector<float>result(input.size());[output getBytes:result.data() bytesPerRow:width*16 fromRegion:MTLRegionMake2D(0,0,width,1) mipmapLevel:0];return result;
}
static id<MTLRenderPipelineState> pipeline(id<MTLDevice>device,id<MTLLibrary>library) {
auto d=[MTLRenderPipelineDescriptor new];d.vertexFunction=[library newFunctionWithName:@"vertexShader"];
d.fragmentFunction=[library newFunctionWithName:@"fragmentShader"];d.colorAttachments[0].pixelFormat=MTLPixelFormatRGBA32Float;
NSError *error=nil;auto result=[device newRenderPipelineStateWithDescriptor:d error:&error];need(result!=nil,error.description);return result;
}
static NSArray *rgb(const std::vector<float>&v,NSUInteger pixel) {
NSMutableArray *a=[NSMutableArray array];for(int c=0;c<3;c++){
float x=v[pixel*4+c];[a addObject:std::isfinite(x)?(id)@(x):(id)[NSString stringWithFormat:@"%g",x]];
}return a;
}
int main(int argc,const char *argv[]) { @autoreleasepool { @try {
need(argc==2,@"usage: probe /absolute/report.json");
NSString *cstPath=@"/Library/Plug-Ins/FxPlug/Colour Space Transform.app/Contents/PlugIns/Colour Space Transform XPC Service.pluginkit/Contents/Resources/default.metallib";
NSString *basisPath=@"/Library/Plug-Ins/FxPlug/BASIS.app/Contents/PlugIns/Basis XPC Service.pluginkit/Contents/Resources/default.metallib";
need([digest(cstPath)isEqual:@"b38165dd86bb6e038f7835373dadb51a54a0ad266c67672ff8fcd9548641c2d3"],@"CST identity changed; re-inspect before probing");
need([digest(basisPath)isEqual:@"e164080db3a6d553a0e75d377ac3c5bd28455bddd8a97640d9de6c74e0d105f3"],@"BASIS identity changed; re-inspect before probing");
auto device=MTLCreateSystemDefaultDevice();need(device!=nil,@"Metal device unavailable");auto queue=[device newCommandQueue];
NSError *error=nil;auto cst=[device newLibraryWithURL:[NSURL fileURLWithPath:cstPath] error:&error];need(cst!=nil,error.description);
auto basis=[device newLibraryWithURL:[NSURL fileURLWithPath:basisPath] error:&error];need(basis!=nil,error.description);
auto cp=pipeline(device,cst),bp=pipeline(device,basis);
const float levels[]={0,.001f,.01f,.18f,1,2,4,16,64};std::vector<float>gray;
for(auto v:levels)gray.insert(gray.end(),{v,v,v,1});
CSTParams forward={22,20,22,1002,1},reverse={22,1002,22,20,2};
auto mapped=render(device,queue,cp,gray,&forward,sizeof(forward));
auto restored=render(device,queue,cp,mapped,&reverse,sizeof(reverse));
NSMutableArray *mapping=[NSMutableArray array];for(NSUInteger i=0;i<sizeof(levels)/sizeof(float);i++)
[mapping addObject:@{@"sourceLinear709":@(levels[i]),@"displayGamma24":rgb(mapped,i),@"reverseToLinear709":rgb(restored,i)}];
std::vector<float>codes;for(double v:{.001,.01,.18,1.0,4.0}){float c=(float)encodeDI(v);codes.insert(codes.end(),{c,c,c,1});}
BasisParams b={};b.colorspace=10;b.exposure=2;b.contrast=b.pivot=b.trimLow=b.trimHigh=b.shadowPivot=b.hiPivot=b.saturation=1;
b.trimToeStrength=8.5;b.trimShoulderStrength=4.5;b.chromaMix=.5;
// Isolate the exposure operation rather than asserting a whole tone stack is neutral.
b.bypassBalance=b.bypassTone=b.bypassContrast=1;
auto exposed=render(device,queue,bp,codes,&b,sizeof(b));NSMutableArray *exposure=[NSMutableArray array];unsigned maximumHalfULP=0;
for(NSUInteger i=0;i<codes.size()/4;i++){
float inputHalf=(float)(__fp16)codes[i*4];double expected=encodeDI(decodeDI(inputHalf)*2);
__fp16 reference=(__fp16)expected,actual=(__fp16)exposed[i*4];uint16_t referenceBits,actualBits;
std::memcpy(&referenceBits,&reference,2);std::memcpy(&actualBits,&actual,2);
unsigned halfULP=unsigned(std::abs(int(referenceBits)-int(actualBits)));maximumHalfULP=std::max(maximumHalfULP,halfULP);
[exposure addObject:@{@"inputCode":@(codes[i*4]),@"shaderInputHalf":@(inputHalf),@"expectedCodeDouble":@(expected),@"actualCode":rgb(exposed,i),@"absoluteCodeError":@(std::fabs(expected-exposed[i*4])),@"halfULPAgainstRoundedReference":@(halfULP)}];
}
NSString *dayuPath=@"/Library/Plug-Ins/FxPlug/大鱼调色.app/Contents/PlugIns/大鱼调色 XPC Service.pluginkit/Contents/Resources/default.metallib";
need([digest(dayuPath)isEqual:@"6ec98b85aeb841f9988a4b66e3e5fba9e34d5ab3d7542c9205b0480c77f9ac6d"],@"Dayu identity changed; re-inspect before probing");
auto dayu=[device newLibraryWithURL:[NSURL fileURLWithPath:dayuPath] error:&error];need(dayu!=nil,error.description);
auto dp=[device newComputePipelineStateWithFunction:[dayu newFunctionWithName:@"dyColorManagement"] error:&error];need(dp!=nil,error.description);
// Matches DYToolUniforms(new primary) + DYCMRender at the audited source revision.
// It does not simulate the tool scheduler, masks, or the full host render.
DayuRenderParams p={};p.input={22,1002,16,10,2};p.output={16,10,22,1002,1};p.basis=b;
p.basis.exposure=1;p.basis.bypassBalance=p.basis.bypassTone=p.basis.bypassContrast=0;p.stages=7;
const float hostLevels[]={.01f,.18f,.5f,1,2};std::vector<float>host;
for(float level:hostLevels)host.insert(host.end(),{(float)(__fp16)level,(float)(__fp16)level,(float)(__fp16)level,1});
auto td=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA32Float width:5 height:1 mipmapped:NO];td.storageMode=MTLStorageModeShared;td.usage=MTLTextureUsageShaderRead|MTLTextureUsageShaderWrite;
auto source=[device newTextureWithDescriptor:td],dest=[device newTextureWithDescriptor:td];
[source replaceRegion:MTLRegionMake2D(0,0,5,1) mipmapLevel:0 withBytes:host.data() bytesPerRow:80];
auto cb=[queue commandBuffer];auto e=[cb computeCommandEncoder];[e setComputePipelineState:dp];[e setTexture:source atIndex:0];[e setTexture:dest atIndex:1];
[e setBytes:&p length:sizeof(p) atIndex:0];float amount=1;[e setBytes:&amount length:sizeof(amount) atIndex:1];
[e dispatchThreads:MTLSizeMake(5,1,1) threadsPerThreadgroup:MTLSizeMake(5,1,1)];[e endEncoding];[cb commit];[cb waitUntilCompleted];need(cb.status==MTLCommandBufferStatusCompleted,cb.error.description?:@"Dayu GPU failure");
std::vector<float>dayuResult(20);[dest getBytes:dayuResult.data() bytesPerRow:80 fromRegion:MTLRegionMake2D(0,0,5,1) mipmapLevel:0];
NSMutableArray *dayuRows=[NSMutableArray array];for(NSUInteger i=0;i<5;i++)[dayuRows addObject:@{@"hostLinearInput":@(host[i*4]),@"newPrimaryDefaultMappingOutput":rgb(dayuResult,i)}];
NSDictionary *report=@{@"schema":@1,@"date":@"2026-11-03",@"device":device.name,
@"authority":@"controlled shader execution; original installed Metal libraries",
@"cstSHA256":digest(cstPath),@"basisSHA256":digest(basisPath),
@"cstForwardThenReverse":mapping,@"basisDIExposurePlusOneStop":exposure,@"basisExposureMaximumHalfULP":@(maximumHalfULP),
@"dayuSHA256":digest(dayuPath),@"dayuNewPrimaryDefaultMapping":dayuRows,
@"limitations":@[@"Not a Final Cut Pro render, camera import test or whole-application CMS certification.",@"RGBA32Float transport; target shaders can quantize samples/results internally to half.",@"CST inverse display mapping is not assumed to be an inverse of the forward DRT.",@"DI formula follows Blackmagic public specification; finite samples and exposure-isolation bypasses only.",@"Dayu primary rows test the actual installed color kernel with source-derived new-layer parameters, not the whole scheduler/UI."]};
NSData *json=[NSJSONSerialization dataWithJSONObject:report options:NSJSONWritingPrettyPrinted|NSJSONWritingSortedKeys error:&error];need(json!=nil,error.description);
need([json writeToFile:[NSString stringWithUTF8String:argv[1]] options:NSDataWritingAtomic error:&error],error.description);
puts([[NSString alloc]initWithData:json encoding:NSUTF8StringEncoding].UTF8String);return 0;
} @catch(NSException *e) {fputs(e.reason.UTF8String,stderr);return 1;} }}