feat: complete FxPlug integration, input-aware auto grade and FCP wrapper
这个提交包含在:
1 父节点
2f11e8bd0f
当前提交
2330eb737e
36 个文件已更改
+4320
-131
没有与搜索条件相匹配的文件
@@ -0,0 +1,10 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
/// Packed float32 RGBA in the sRGB encoding domain, normally 320x180 pixels.
|
||||
/// Nil means malformed input or fewer than 129 usable (alpha > 8/255) pixels.
|
||||
FOUNDATION_EXPORT NSDictionary<NSString *, NSNumber *> * _Nullable DYAutoGrade(NSData * _Nullable frame);
|
||||
/// Finds a table-based neutral correction from low-saturation midtone samples.
|
||||
/// Nil means no suitable neutral samples or unavailable color-table data.
|
||||
FOUNDATION_EXPORT NSDictionary<NSString *, NSNumber *> * _Nullable DYAutoWhiteBalance(NSData * _Nullable frame);
|
||||
NS_ASSUME_NONNULL_END
|
||||
@@ -0,0 +1,92 @@
|
||||
#import "DYAutoGrade.h"
|
||||
#import "DYColorTables.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <vector>
|
||||
|
||||
// Numerical reconstruction of LumiGrade 3.0 (56), arm64 autoGradeResult at
|
||||
// 0x100091d38..0x100092650 and percentile at 0x100091ca4..0x100091d38.
|
||||
// Sources: research/autoGrade.c and autoGrade.asm in this task's analysis cache.
|
||||
// The reference redraws NSImage into 320x180 UInt8 RGBA. Our renderer provides
|
||||
// 320x180 float RGBA samples; quantization recreates that numerical domain.
|
||||
// This does not claim byte-identical NSImage/CoreGraphics resampling.
|
||||
#pragma clang fp contract(off)
|
||||
|
||||
namespace {
|
||||
struct Samples {
|
||||
std::vector<float> luma;
|
||||
std::vector<float> saturation;
|
||||
float neutralR=0, neutralG=0, neutralB=0, neutralWeight=0;
|
||||
};
|
||||
static float byteValue(float value) {
|
||||
return std::round(std::clamp(value,0.f,1.f)*255.f)/255.f;
|
||||
}
|
||||
static bool gather(NSData *frame,Samples& samples) {
|
||||
if(!frame || frame.length==0 || frame.length%(sizeof(float)*4)!=0)return false;
|
||||
const float *pixels=(const float *)frame.bytes;
|
||||
size_t count=frame.length/(sizeof(float)*4);
|
||||
samples.luma.reserve(count);samples.saturation.reserve(count);
|
||||
for(size_t i=0;i<count;++i) {
|
||||
const float *p=pixels+i*4;
|
||||
if(!std::isfinite(p[0])||!std::isfinite(p[1])||!std::isfinite(p[2])||!std::isfinite(p[3]))continue;
|
||||
if(std::round(std::clamp(p[3],0.f,1.f)*255.f)<=8.f)continue;
|
||||
float r=byteValue(p[0]),g=byteValue(p[1]),b=byteValue(p[2]);
|
||||
float maximum=std::max(r,std::max(g,b)),minimum=std::min(r,std::min(g,b));
|
||||
float saturation=maximum>.001f?(maximum-minimum)/maximum:0.f;
|
||||
float luma=(r*.2126f+g*.7152f)+b*.0722f;
|
||||
samples.luma.push_back(luma);samples.saturation.push_back(saturation);
|
||||
if(luma>.18f&&luma<.92f&&saturation<.16f&&maximum<.98f) {
|
||||
float weight=std::max(0.f,.16f-saturation)/.16f*(std::min(luma,.55f)+.45f);
|
||||
samples.neutralR+=r*weight;samples.neutralG+=g*weight;samples.neutralB+=b*weight;samples.neutralWeight+=weight;
|
||||
}
|
||||
}
|
||||
return samples.luma.size()>=129;
|
||||
}
|
||||
static float percentile(const std::vector<float>& sorted,float fraction) {
|
||||
size_t index=(size_t)std::round(std::clamp(fraction,0.f,1.f)*float(sorted.size()-1));
|
||||
return sorted[std::min(index,sorted.size()-1)];
|
||||
}
|
||||
static double rounded(float value) {return std::round(double(value));}
|
||||
}
|
||||
|
||||
NSDictionary<NSString *, NSNumber *> *DYAutoGrade(NSData *frame) {
|
||||
Samples samples;if(!gather(frame,samples))return nil;
|
||||
std::sort(samples.luma.begin(),samples.luma.end());
|
||||
std::sort(samples.saturation.begin(),samples.saturation.end());
|
||||
float p02=percentile(samples.luma,.02f),p05=percentile(samples.luma,.05f);
|
||||
float p10=percentile(samples.luma,.10f),p50=percentile(samples.luma,.50f);
|
||||
float p90=percentile(samples.luma,.90f),p95=percentile(samples.luma,.95f),p98=percentile(samples.luma,.98f);
|
||||
float sumSaturation=0;for(float value:samples.saturation)sumSaturation+=value;
|
||||
float meanSaturation=sumSaturation/float(samples.saturation.size());
|
||||
float range=std::max(.001f,p95-p05);
|
||||
float rawExposure=std::log2(.46f/std::max(p50,.05f))*.72f;
|
||||
double exposure=std::round(std::clamp(double(rawExposure),-1.1,1.1)*100.0)/100.0;
|
||||
float contrast=std::clamp((.7f-range)*82.f,-22.f,34.f);
|
||||
double highlights=double(std::clamp((.84f-p95)*150.f,-55.f,26.f));
|
||||
if(p90>.93f)highlights+=double((p90+(-.93f))*-25.f);
|
||||
float shadows=std::clamp((.18f-p10)*180.f,-22.f,55.f);
|
||||
float whites=std::clamp((.93f-p98)*92.f,-35.f,42.f);
|
||||
float blacks=std::clamp((.045f-p02)*175.f,-36.f,24.f);
|
||||
float vibrance=std::clamp((.28f-meanSaturation)*90.f,-8.f,28.f);
|
||||
float saturation=std::clamp((.22f-meanSaturation)*42.f,-12.f,12.f);
|
||||
double temperature=0,tint=0;
|
||||
if(samples.neutralWeight>float(samples.luma.size())*.003f) {
|
||||
float r=samples.neutralR/samples.neutralWeight,g=samples.neutralG/samples.neutralWeight,b=samples.neutralB/samples.neutralWeight;
|
||||
double confidence=std::min(1.0,(double(samples.neutralWeight)/double(samples.luma.size()))*18.0);
|
||||
temperature=std::clamp(double(b-r)*125.0*confidence,-36.0,36.0);
|
||||
tint=std::clamp(double(g+(b+r)*-.5f)*120.0*confidence,-32.0,32.0);
|
||||
}
|
||||
return @{@"exposure":@(exposure),@"contrast":@(rounded(contrast)),@"highlights":@(std::round(highlights)),
|
||||
@"shadows":@(rounded(shadows)),@"whites":@(rounded(whites)),@"blacks":@(rounded(blacks)),
|
||||
@"vibrance":@(rounded(vibrance)),@"saturation":@(rounded(saturation)),
|
||||
@"temperature":@(std::round(temperature)),@"tint":@(std::round(tint))};
|
||||
}
|
||||
|
||||
NSDictionary<NSString *, NSNumber *> *DYAutoWhiteBalance(NSData *frame) {
|
||||
Samples samples;if(!gather(frame,samples))return nil;
|
||||
if(samples.neutralWeight<=float(samples.luma.size())*.003f)return nil;
|
||||
vector_float3 neutral={samples.neutralR/samples.neutralWeight,samples.neutralG/samples.neutralWeight,samples.neutralB/samples.neutralWeight};
|
||||
float temperature=0,tint=0;
|
||||
if(![DYColorTables neutralizeColor:neutral temperature:&temperature tint:&tint])return nil;
|
||||
return @{@"temperature":@(temperature),@"tint":@(tint)};
|
||||
}
|
||||
@@ -251,7 +251,11 @@ NSData *DYComposeGrading(NSData *tables,const float parameters[14]) {return comp
|
||||
} @finally {[_lock unlock];}
|
||||
}
|
||||
- (id<MTLTexture>)whiteBalanceForDevice:(id<MTLDevice>)device uniforms:(const DYUniforms *)u {
|
||||
float p[2]={u->temperatureEnabled>.5f?safe(u->temperature,-100,100):0,u->tintEnabled>.5f?safe(u->tint,-100,100):0};
|
||||
// The shipped CPU renderer gates white balance with colorSectionEnabled,
|
||||
// while the shader samples the resulting texture unconditionally.
|
||||
bool enabled=u->colorSectionEnabled>.5f;
|
||||
float p[2]={enabled&&u->temperatureEnabled>.5f?safe(u->temperature,-100,100):0,
|
||||
enabled&&u->tintEnabled>.5f?safe(u->tint,-100,100):0};
|
||||
Stages stages;if(std::fabs(p[0])+std::fabs(p[1])>kEpsilon)stages.push_back(whiteBalanceStage(p[0],p[1]));
|
||||
return [self textureForDevice:device kind:@"WhiteBalance" key:[NSData dataWithBytes:p length:sizeof(p)] stages:stages];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
#pragma once
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
/// Headless native model/renderer integration diagnostics. Writes JSON stdout.
|
||||
int DYRunDiagnostics(void);
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,175 @@
|
||||
#import "DYDiagnostics.h"
|
||||
#import "DYModel.h"
|
||||
#import "DYRenderer.h"
|
||||
#import "DYAutoGrade.h"
|
||||
#import <CoreVideo/CoreVideo.h>
|
||||
#import <IOSurface/IOSurface.h>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
// Fake host objects implement the real selectors used by the model and renderer.
|
||||
// They never connect to a host document or enter the FxPrincipal service loop.
|
||||
@interface DYDiagnosticManager : NSObject<PROAPIAccessing> {
|
||||
@public
|
||||
NSMutableDictionary *_values,*_custom;
|
||||
BOOL _duplicate;
|
||||
}
|
||||
@end
|
||||
@implementation DYDiagnosticManager
|
||||
- (instancetype)init {if((self=[super init])){_values=[NSMutableDictionary new];_custom=[NSMutableDictionary new];}return self;}
|
||||
- (void)dealloc {[_values release];[_custom release];[super dealloc];}
|
||||
- (id)apiForProtocol:(Protocol *)protocol {
|
||||
NSString *name=NSStringFromProtocol(protocol);
|
||||
return [@[@"FxParameterCreationAPI_v5",@"FxParameterRetrievalAPI_v6",@"FxParameterSettingAPI_v6"]containsObject:name]?self:nil;
|
||||
}
|
||||
- (BOOL)addFloatSliderWithName:(NSString *)name parameterID:(UInt32)pid defaultValue:(double)value parameterMin:(double)minimum parameterMax:(double)maximum sliderMin:(double)sliderMinimum sliderMax:(double)sliderMaximum delta:(double)delta parameterFlags:(FxParameterFlags)flags {
|
||||
if(_values[@(pid)]||_custom[@(pid)]){_duplicate=YES;return NO;}_values[@(pid)]=@(value);return YES;
|
||||
}
|
||||
- (BOOL)addCustomParameterWithName:(NSString *)name parameterID:(UInt32)pid defaultValue:(NSObject<NSSecureCoding,NSCopying> *)value parameterFlags:(FxParameterFlags)flags {
|
||||
if(_values[@(pid)]||_custom[@(pid)]){_duplicate=YES;return NO;}_custom[@(pid)]=value;return YES;
|
||||
}
|
||||
- (BOOL)getFloatValue:(double *)value fromParameter:(UInt32)pid atTime:(CMTime)time {
|
||||
NSNumber *stored=_values[@(pid)];if(!stored)return NO;if(value)*value=stored.doubleValue;return YES;
|
||||
}
|
||||
- (BOOL)setFloatValue:(double)value toParameter:(UInt32)pid atTime:(CMTime)time {
|
||||
if(!_values[@(pid)])return NO;_values[@(pid)]=@(value);return YES;
|
||||
}
|
||||
- (BOOL)getCustomParameterValue:(NSObject<NSSecureCoding,NSCopying> **)value fromParameter:(UInt32)pid atTime:(CMTime)time {
|
||||
id stored=_custom[@(pid)];if(!stored)return NO;if(value)*value=stored;return YES;
|
||||
}
|
||||
- (BOOL)setCustomParameterValue:(NSObject<NSSecureCoding,NSCopying> *)value toParameter:(UInt32)pid atTime:(CMTime)time {
|
||||
if(!_custom[@(pid)]||!value)return NO;_custom[@(pid)]=[[value copy]autorelease];return YES;
|
||||
}
|
||||
@end
|
||||
|
||||
@interface DYDiagnosticTile : FxImageTile {
|
||||
id<MTLTexture> _texture;
|
||||
IOSurfaceRef _surface;
|
||||
FxRect _bounds;
|
||||
uint64_t _registry;
|
||||
}
|
||||
- (instancetype)initWithDevice:(id<MTLDevice>)device width:(NSUInteger)width height:(NSUInteger)height;
|
||||
@end
|
||||
@implementation DYDiagnosticTile
|
||||
- (instancetype)initWithDevice:(id<MTLDevice>)device width:(NSUInteger)width height:(NSUInteger)height {
|
||||
if((self=[super init])) {
|
||||
NSDictionary *properties=@{(id)kIOSurfaceWidth:@(width),(id)kIOSurfaceHeight:@(height),
|
||||
(id)kIOSurfaceBytesPerElement:@8,(id)kIOSurfaceBytesPerRow:@(width*8),
|
||||
(id)kIOSurfacePixelFormat:@(kCVPixelFormatType_64RGBAHalf)};
|
||||
_surface=IOSurfaceCreate((CFDictionaryRef)properties);
|
||||
MTLTextureDescriptor *d=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA16Float width:width height:height mipmapped:NO];
|
||||
d.storageMode=MTLStorageModeShared;d.usage=MTLTextureUsageShaderRead|MTLTextureUsageShaderWrite|MTLTextureUsageRenderTarget;
|
||||
if(_surface)_texture=[device newTextureWithDescriptor:d iosurface:_surface plane:0];
|
||||
_bounds=(FxRect){0,0,(SInt32)width,(SInt32)height};_registry=device.registryID;
|
||||
if(!_surface||!_texture){[self release];return nil;}
|
||||
}return self;
|
||||
}
|
||||
- (void)dealloc {[_texture release];if(_surface)CFRelease(_surface);[super dealloc];}
|
||||
- (id<MTLTexture>)metalTextureForDevice:(id<MTLDevice>)device {return device.registryID==_registry?_texture:nil;}
|
||||
- (IOSurface *)ioSurface {return (IOSurface *)_surface;}
|
||||
- (FxRect)tilePixelBounds {return _bounds;}
|
||||
- (FxRect)imagePixelBounds {return _bounds;}
|
||||
- (uint64_t)deviceRegistryID {return _registry;}
|
||||
- (FxImageOrigin)imageOrigin {return kFxImageOrigin_TOP_LEFT;}
|
||||
@end
|
||||
|
||||
namespace {
|
||||
using Pixels=std::vector<__fp16>;
|
||||
struct Run {
|
||||
NSMutableArray *rows=[NSMutableArray array];
|
||||
bool passed=true;
|
||||
void record(NSString *name,bool ok,NSDictionary *details=nil) {
|
||||
NSMutableDictionary *row=[NSMutableDictionary dictionaryWithDictionary:details?:@{}];
|
||||
row[@"name"]=name;row[@"pass"]=@(ok);[rows addObject:row];if(!ok)passed=false;
|
||||
}
|
||||
void need(NSString *name,bool ok,NSDictionary *details=nil) {
|
||||
record(name,ok,details);if(!ok)@throw [NSException exceptionWithName:@"DYDiagnosticStop" reason:name userInfo:nil];
|
||||
}
|
||||
};
|
||||
static NSString *reason(NSError *error) {return error.localizedDescription?:@"未提供错误信息";}
|
||||
static Pixels read(DYDiagnosticTile *tile,id<MTLDevice> gpu) {
|
||||
id<MTLTexture> texture=[tile metalTextureForDevice:gpu];Pixels output(texture.width*texture.height*4);
|
||||
[texture getBytes:output.data() bytesPerRow:texture.width*8 fromRegion:MTLRegionMake2D(0,0,texture.width,texture.height) mipmapLevel:0];return output;
|
||||
}
|
||||
struct Difference {double maximum=0;size_t different=0,nonfinite=0,nonzero=0;};
|
||||
static Difference difference(const Pixels& a,const Pixels& b) {
|
||||
Difference found;if(a.size()!=b.size()){found.nonfinite=1;return found;}
|
||||
for(size_t i=0;i<a.size();i++){double x=a[i],y=b[i];if(!std::isfinite(x)||!std::isfinite(y)){found.nonfinite++;continue;}double error=std::fabs(x-y);found.maximum=std::max(found.maximum,error);if(error>1e-5)found.different++;if(y!=0)found.nonzero++;}return found;
|
||||
}
|
||||
static NSDictionary *measure(Difference d) {return @{@"maxAbsoluteError":@(d.maximum),@"changedComponents":@(d.different),@"nonfiniteComponents":@(d.nonfinite),@"nonzeroComponents":@(d.nonzero)};}
|
||||
static Pixels render(Run& run,DYRenderer *renderer,DYDiagnosticTile *source,DYDiagnosticTile *destination,id<MTLDevice> gpu,DYUniforms uniforms,NSDictionary *paths,NSString *name) {
|
||||
NSError *error=nil;BOOL ok=[renderer renderSource:source destination:destination uniforms:uniforms paths:paths error:&error];
|
||||
run.need(name,ok,@{@"error":ok?@"":reason(error)});return read(destination,gpu);
|
||||
}
|
||||
static float *field(DYUniforms *u,NSDictionary *row){return (float *)((uint8_t *)u+[row[@"offset"]unsignedIntegerValue]);}
|
||||
}
|
||||
|
||||
extern "C" int DYRunDiagnostics(void) { @autoreleasepool {
|
||||
Run run;NSString *runtime=nil;NSString *gpuName=@"unavailable";
|
||||
@try {
|
||||
NSError *error=nil;
|
||||
runtime=[@"/Users/mac/Library/Caches/CodexBuilds/com.dayu.color/verification-runtime" stringByAppendingPathComponent:NSUUID.UUID.UUIDString];
|
||||
run.need(@"runtime-directory",[[NSFileManager defaultManager]createDirectoryAtPath:runtime withIntermediateDirectories:YES attributes:nil error:&error],@{@"path":runtime,@"error":reason(error)});
|
||||
NSArray *descriptors=DYDescriptors(),*sections=DYSections();NSMutableSet *pids=[NSMutableSet set],*offsets=[NSMutableSet set],*keys=[NSMutableSet set];bool schema=true;
|
||||
for(NSDictionary *row in descriptors){NSInteger offset=[row[@"offset"]integerValue];NSNumber *pid=row[@"pid"];bool metadata=offset==-1&&pid.unsignedIntValue==8800&&[row[@"key"]isEqual:@"copyAutoGrade"];schema&=(metadata||(offset>=0&&offset%4==0&&offset+4<=sizeof(DYUniforms)&&pid.unsignedIntValue==2000+offset/4&&![offsets containsObject:row[@"offset"]]))&&![pids containsObject:pid]&&![keys containsObject:row[@"key"]];[pids addObject:pid];if(offset>=0)[offsets addObject:row[@"offset"]];[keys addObject:row[@"key"]];}
|
||||
run.need(@"descriptor-unique-id-offset-key",schema,@{@"descriptors":@(descriptors.count),@"sections":@(sections.count),@"uniformBytes":@(sizeof(DYUniforms))});
|
||||
DYUniforms defaults;DYDefaultUniforms(&defaults);bool finite=true,matches=true;
|
||||
// SIMD float3 has a fourth ABI lane that is padding, not a semantic
|
||||
// value. Check every represented control and every matrix component.
|
||||
for(NSDictionary *row in descriptors)if([row[@"offset"]integerValue]>=0){float value=*field(&defaults,row);finite&=std::isfinite(value);matches&=value==[row[@"default"]floatValue];}
|
||||
for(int c=0;c<3;c++)finite&=std::isfinite(defaults.primariesM0[c])&&std::isfinite(defaults.primariesM1[c])&&std::isfinite(defaults.primariesM2[c]);
|
||||
run.need(@"finite-real-model-defaults",finite&&matches);
|
||||
DYDiagnosticManager *manager=[[[DYDiagnosticManager alloc]init]autorelease];error=nil;
|
||||
run.need(@"native-parameter-creation",DYCreateParameters(manager,&error)&&!manager->_duplicate&&manager->_values.count==descriptors.count&&manager->_custom.count==2,@{@"error":reason(error)});
|
||||
id<FxParameterSettingAPI_v6> setter=[manager apiForProtocol:@protocol(FxParameterSettingAPI_v6)];id<FxParameterRetrievalAPI_v6> getter=[manager apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)];
|
||||
[setter setFloatValue:.75 toParameter:2000 atTime:kCMTimeZero];double value=0;[getter getFloatValue:&value fromParameter:2000 atTime:kCMTimeZero];DYUniforms restored;DYReadUniforms(manager,kCMTimeZero,&restored);
|
||||
run.record(@"native-get-set-model-roundtrip",value==.75&&restored.exposure==.75f);
|
||||
[setter setFloatValue:999 toParameter:2000 atTime:kCMTimeZero];DYReadUniforms(manager,kCMTimeZero,&restored);run.record(@"model-clamps-host-out-of-range",restored.exposure==5);
|
||||
[setter setFloatValue:NAN toParameter:2000 atTime:kCMTimeZero];DYReadUniforms(manager,kCMTimeZero,&restored);run.record(@"model-rejects-host-nonfinite",restored.exposure==defaults.exposure);
|
||||
DYAssetState *assets=[[[DYAssetState alloc]init]autorelease];assets.paths=@{@"input":[runtime stringByAppendingPathComponent:@"input.cube"],@"look0":[runtime stringByAppendingPathComponent:@"look.cube"]};
|
||||
error=nil;NSData *archive=[NSKeyedArchiver archivedDataWithRootObject:assets requiringSecureCoding:YES error:&error];DYAssetState *decoded=archive?[NSKeyedUnarchiver unarchivedObjectOfClass:DYAssetState.class fromData:archive error:&error]:nil;
|
||||
run.record(@"secure-asset-archive-roundtrip",decoded&&[assets isEqual:decoded],@{@"archiveBytes":@(archive.length),@"error":reason(error)});
|
||||
BOOL wrote=DYWriteAssets(manager,assets,kCMTimeZero);DYAssetState *readBack=DYReadAssets(manager,kCMTimeZero);run.record(@"native-custom-asset-get-set",wrote&&[readBack isEqual:assets]);
|
||||
DYAssetState *copy=[[assets copy]autorelease];copy.paths=@{};run.record(@"asset-copy-is-independent",assets.paths.count==2&©.paths.count==0);
|
||||
id<MTLDevice> gpu=MTLCreateSystemDefaultDevice();run.need(@"metal-device",gpu!=nil);gpuName=gpu.name;
|
||||
const NSUInteger width=64,height=48;DYDiagnosticTile *source=[[[DYDiagnosticTile alloc]initWithDevice:gpu width:width height:height]autorelease],*destination=[[[DYDiagnosticTile alloc]initWithDevice:gpu width:width height:height]autorelease];
|
||||
run.need(@"real-iosurface-image-tiles",source&&destination&&source.ioSurface&&destination.ioSurface);
|
||||
Pixels input(width*height*4);for(NSUInteger y=0;y<height;y++)for(NSUInteger x=0;x<width;x++){size_t p=(y*width+x)*4;float alpha=float((x+y)%5)/4.f;input[p]=(__fp16)((.08f+.75f*float(x)/(width-1))*alpha);input[p+1]=(__fp16)((.05f+.8f*float(y)/(height-1))*alpha);input[p+2]=(__fp16)((.1f+.65f*float((x*7+y*3)%64)/63.f)*alpha);input[p+3]=(__fp16)alpha;}
|
||||
[[source metalTextureForDevice:gpu]replaceRegion:MTLRegionMake2D(0,0,width,height) mipmapLevel:0 withBytes:input.data() bytesPerRow:width*8];
|
||||
DYRenderer *renderer=[[[DYRenderer alloc]init]autorelease];Pixels neutral=render(run,renderer,source,destination,gpu,defaults,@{},@"renderer-default-pass");Difference neutralDifference=difference(input,neutral);
|
||||
run.record(@"transparent-premultiplied-neutral",neutralDifference.nonfinite==0&&neutralDifference.maximum<=.001,measure(neutralDifference));
|
||||
size_t transparentBad=0;for(size_t i=0;i<input.size();i+=4){if(input[i+3]==0)for(int c=0;c<4;c++)if(neutral[i+c]!=0)transparentBad++;if(neutral[i+3]!=input[i+3])transparentBad++;}
|
||||
run.record(@"renderer-alpha-contract",transparentBad==0,@{@"invalidComponents":@(transparentBad)});
|
||||
NSData *preview=[renderer preview];bool previewFinite=preview.length==320*180*16;if(previewFinite){const float *data=(const float *)preview.bytes;for(NSUInteger i=0;i<preview.length/4;i++)previewFinite&=std::isfinite(data[i]);}
|
||||
run.record(@"renderer-analysis-320x180",previewFinite,@{@"bytes":@(preview.length)});
|
||||
NSDictionary *autoGrade=DYAutoGrade(preview);run.record(@"renderer-auto-grade-integration",autoGrade.count==10,autoGrade?:@{});
|
||||
DYUniforms u=defaults;u.exposure=.8f;Pixels exposed=render(run,renderer,source,destination,gpu,u,@{},@"renderer-exposure-pass");Difference exposureDifference=difference(neutral,exposed);run.record(@"exposure-affects-actual-frame",exposureDifference.nonfinite==0&&exposureDifference.different>100,measure(exposureDifference));
|
||||
u.baseSectionEnabled=0;Pixels bypass=render(run,renderer,source,destination,gpu,u,@{},@"renderer-base-bypass-pass");Difference bypassDifference=difference(neutral,bypass);run.record(@"base-group-bypass",bypassDifference.nonfinite==0&&bypassDifference.maximum==0,measure(bypassDifference));
|
||||
u=defaults;u.temperature=35;u.tint=-20;Pixels wb=render(run,renderer,source,destination,gpu,u,@{},@"renderer-white-balance-pass");Difference wbDifference=difference(neutral,wb);run.record(@"white-balance-real-table-frame",wbDifference.nonfinite==0&&wbDifference.different>100,measure(wbDifference));
|
||||
u.colorSectionEnabled=0;bypass=render(run,renderer,source,destination,gpu,u,@{},@"renderer-color-bypass-pass");bypassDifference=difference(neutral,bypass);run.record(@"color-group-bypass",bypassDifference.nonfinite==0&&bypassDifference.maximum==0,measure(bypassDifference));
|
||||
u=defaults;u.hslHueA.x=28;u.hslSatA.y=45;u.hslLumB.z=-18;Pixels hsl=render(run,renderer,source,destination,gpu,u,@{},@"renderer-hsl-pass");Difference hslDifference=difference(neutral,hsl);run.record(@"hsl-real-table-frame",hslDifference.nonfinite==0&&hslDifference.different>100,measure(hslDifference));
|
||||
u=defaults;u.colorGradingHueSatA.x=210;u.colorGradingHueSatA.y=42;u.colorGradingLuma.x=18;Pixels grading=render(run,renderer,source,destination,gpu,u,@{},@"renderer-grading-pass");Difference gradingDifference=difference(neutral,grading);run.record(@"grading-real-table-frame",gradingDifference.nonfinite==0&&gradingDifference.different>100,measure(gradingDifference));
|
||||
for(int profile=1;profile<=17;profile++){@autoreleasepool{u=defaults;u.inputProfile=profile;Pixels transformed=render(run,renderer,source,destination,gpu,u,@{},[NSString stringWithFormat:@"input-profile-%02d-load-render",profile]);Difference delta=difference(neutral,transformed);run.record([NSString stringWithFormat:@"input-profile-%02d-finite-nonzero",profile],delta.nonfinite==0&&delta.nonzero>100,measure(delta));}}
|
||||
DYRenderer *analysisRenderer=[[[DYRenderer alloc]init]autorelease];u=defaults;u.inputProfile=1;render(run,analysisRenderer,source,destination,gpu,u,@{},@"renderer-input-analysis-pass");
|
||||
NSData *inputPreview=[analysisRenderer preview];bool analysisDifferent=inputPreview.length==preview.length&&preview.length==320*180*16;double analysisMaximum=0;size_t analysisChanges=0;
|
||||
if(analysisDifferent){const float *a=(const float *)preview.bytes,*b=(const float *)inputPreview.bytes;for(NSUInteger i=0;i<preview.length/4;i++){if(!std::isfinite(a[i])||!std::isfinite(b[i])){analysisDifferent=false;break;}if(i%4!=3){double delta=std::fabs(double(a[i])-b[i]);analysisMaximum=std::max(analysisMaximum,delta);if(delta>1e-5)analysisChanges++;}}}
|
||||
run.record(@"analysis-applies-selected-input-LUT",analysisDifferent&&analysisChanges>100,@{@"changedComponents":@(analysisChanges),@"maxAbsoluteError":@(analysisMaximum)});
|
||||
NSString *lookFile=[runtime stringByAppendingPathComponent:@"diagnostic-look.cube"];NSMutableString *cube=[NSMutableString stringWithString:@"TITLE \"Self test look\"\nLUT_3D_SIZE 2\nDOMAIN_MIN 0 0 0\nDOMAIN_MAX 1 1 1\n"];
|
||||
for(int b=0;b<2;b++)for(int g=0;g<2;g++)for(int r=0;r<2;r++)[cube appendFormat:@"%.8f %.8f %.8f\n",.7f*r+.1f,.8f*g+.05f,.85f*b+.02f];error=nil;run.need(@"temporary-look-file",[cube writeToFile:lookFile atomically:YES encoding:NSUTF8StringEncoding error:&error],@{@"error":reason(error)});
|
||||
NSDictionary *paths=@{@"look0":lookFile,@"look1":lookFile,@"look2":lookFile,@"look3":lookFile,@"look4":lookFile};u=defaults;u.postLUTStrength=.35f;u.extraPostLUTStrengths=(DYFloat4){.4f,.5f,.6f,.7f};Pixels looks=render(run,renderer,source,destination,gpu,u,paths,@"renderer-five-look-pass");Difference looksDifference=difference(neutral,looks);run.record(@"five-look-mixes-affect-frame",looksDifference.nonfinite==0&&looksDifference.different>100,measure(looksDifference));
|
||||
NSURL *exportURL=[NSURL fileURLWithPath:[runtime stringByAppendingPathComponent:@"diagnostic-export.cube"]];error=nil;run.need(@"renderer-export-33cube",[renderer exportLUT:exportURL uniforms:u paths:paths error:&error],@{@"error":reason(error),@"path":exportURL.path});
|
||||
NSString *exported=[NSString stringWithContentsOfURL:exportURL encoding:NSUTF8StringEncoding error:&error];NSUInteger triples=0,nonzero=0;bool exportFinite=true;for(NSString *line in [exported componentsSeparatedByCharactersInSet:NSCharacterSet.newlineCharacterSet]){float r,g,b;if(sscanf(line.UTF8String,"%f %f %f",&r,&g,&b)==3){triples++;exportFinite&=std::isfinite(r)&&std::isfinite(g)&&std::isfinite(b);if(r!=0||g!=0||b!=0)nonzero++;}}
|
||||
run.record(@"export-33cube-data-contract",[exported containsString:@"LUT_3D_SIZE 33"]&&triples==33*33*33&&exportFinite&&nonzero>0,@{@"rows":@(triples),@"nonzeroRows":@(nonzero),@"bytes":@([[[NSFileManager defaultManager]attributesOfItemAtPath:exportURL.path error:nil][NSFileSize]unsignedLongLongValue])});
|
||||
[gpu release];
|
||||
} @catch(NSException *exception) {
|
||||
run.record(@"diagnostic-exception",false,@{@"exception":exception.name?:@"unknown",@"message":exception.reason?:@"unknown"});
|
||||
}
|
||||
NSDictionary *report=@{@"pass":@(run.passed),@"checks":@(run.rows.count),@"gpu":gpuName,@"bundlePath":[NSBundle bundleForClass:DYRenderer.class].bundlePath?:@"",
|
||||
@"runtimePath":runtime?:@"",@"results":run.rows,@"scope":@"Native model and renderer integration with real Metal/IOSurface textures and fake FxPlug host selectors; no GUI or live host document.",
|
||||
@"limitations":@[@"Finite states and a 64x48 frame; live FCP discovery, inspector interaction, timeline persistence and real host export require separate acceptance.",@"Input profiles checked for load/render/finite output; independent color accuracy is covered by separate LUT/kernel evidence."]};
|
||||
NSError *error=nil;NSData *json=[NSJSONSerialization dataWithJSONObject:report options:NSJSONWritingPrettyPrinted|NSJSONWritingSortedKeys error:&error];
|
||||
if(json){fwrite(json.bytes,1,json.length,stdout);fputc('\n',stdout);}else{fputs("{\"pass\":false,\"error\":\"Unable to encode diagnostics JSON\"}\n",stdout);run.passed=false;}fflush(stdout);return run.passed?0:1;
|
||||
} }
|
||||
@@ -78,3 +78,35 @@ kernel void dyPreview(texture2d<half> source [[texture(0)]],
|
||||
float3 encoded = select(power, linear * 12.92f, linear <= 0.0031308f);
|
||||
outRGBA[pixel.y * 64 + pixel.x] = float4(encoded, float(sample.a));
|
||||
}
|
||||
|
||||
// Analysis resolution matches the reference auto-grade sample dimensions.
|
||||
kernel void dyAnalysis(texture2d<half> source [[texture(0)]],
|
||||
device float4* outRGBA [[buffer(0)]],
|
||||
uint2 pixel [[thread_position_in_grid]]) {
|
||||
if (pixel.x >= 320 || pixel.y >= 180) return;
|
||||
constexpr sampler sampleFilter(coord::normalized, address::clamp_to_edge, filter::linear);
|
||||
half4 sample = source.sample(sampleFilter, (float2(pixel) + 0.5f) / float2(320.0f, 180.0f));
|
||||
float3 linear = float3(sample.rgb);
|
||||
float3 power = 1.055f * pow(max(linear, float3(0.0f)), float3(1.0f / 2.4f)) - 0.055f;
|
||||
float3 encoded = select(power, linear * 12.92f, linear <= 0.0031308f);
|
||||
outRGBA[pixel.y * 320 + pixel.x] = float4(encoded, float(sample.a));
|
||||
}
|
||||
|
||||
// Native auto-grade statistics consume the input-converted RGB8 preview.
|
||||
// Quantization before and after the LUT mirrors the reference NSImage path.
|
||||
kernel void dyInputAnalysis(texture2d<half> source [[texture(0)]],
|
||||
texture3d<float> inputLUT [[texture(1)]],
|
||||
device float4* outRGBA [[buffer(0)]],
|
||||
constant float& inputStrength [[buffer(1)]],
|
||||
uint2 pixel [[thread_position_in_grid]]) {
|
||||
if (pixel.x >= 320 || pixel.y >= 180) return;
|
||||
constexpr sampler f(coord::normalized,address::clamp_to_edge,filter::linear);
|
||||
half4 sample=source.sample(f,(float2(pixel)+.5f)/float2(320,180));
|
||||
float3 linear=float3(sample.rgb);
|
||||
float3 power=1.055f*pow(max(linear,float3(0)),float3(1.0f/2.4f))-.055f;
|
||||
float3 encoded=round(clamp(select(power,linear*12.92f,linear<=.0031308f),0.0f,1.0f)*255.0f)/255.0f;
|
||||
float strength=clamp(inputStrength,0.0f,1.0f);
|
||||
if(strength>0.0f){float n=float(inputLUT.get_width());float3 coord=encoded*((n-1.0f)/n)+.5f/n;encoded=mix(encoded,inputLUT.sample(f,coord).rgb,strength);}
|
||||
encoded=round(clamp(encoded,0.0f,1.0f)*255.0f)/255.0f;
|
||||
outRGBA[pixel.y*320+pixel.x]=float4(encoded,float(sample.a));
|
||||
}
|
||||
+9
-7
@@ -25,8 +25,10 @@ static void initialize(){static dispatch_once_t once;dispatch_once(&once,^{
|
||||
NSDictionary*e=row([keys[i]stringByAppendingString:@"Enabled"],[names[i]stringByAppendingString:@" 启用"],80+i*4,0,1,1,@"bool");r[@"enabled"]=e[@"pid"];
|
||||
[descriptors replaceObjectAtIndex:[descriptors indexOfObjectPassingTest:^BOOL(id obj,NSUInteger idx,BOOL*stop){return [obj[@"key"]isEqual:keys[i]];}] withObject:r];[base addObject:r];
|
||||
}
|
||||
section(@"base",@"基础调色",136,[base subarrayWithRange:NSMakeRange(0,8)]);
|
||||
section(@"color",@"颜色",140,@[base[9],base[8],base[10],base[11],base[12],row(@"skinProtection",@"肤色保护",464,0,1,0,@"bool"),scalar(@"skinHueRange",@"肤色色相范围",468,5,100,40),scalar(@"skinChromaRange",@"肤色饱和度范围",472,5,100,40)]);
|
||||
NSDictionary*copyAuto=@{@"key":@"copyAutoGrade",@"title":@"复制时自动调色",@"pid":@8800,@"offset":@(-1),@"min":@0,@"max":@1,@"default":@0,@"step":@1,@"kind":@"bool",@"notAnimatable":@YES};[descriptors addObject:copyAuto];
|
||||
section(@"base",@"基础调色",136,[[[base subarrayWithRange:NSMakeRange(0,6)]arrayByAddingObjectsFromArray:[base subarrayWithRange:NSMakeRange(10,3)]]arrayByAddingObject:copyAuto]);
|
||||
section(@"color",@"白平衡与颜色",140,@[base[6],base[7],base[9],base[8]]);
|
||||
section(@"skin",@"肤色保护",464,@[scalar(@"skinStrength",@"保护程度",468,0,100,60),scalar(@"skinHue",@"肤色色相",472,0,60,28)],0);
|
||||
NSMutableArray*look=[NSMutableArray arrayWithObject:scalar(@"postLUTStrength",@"风格 1 强度",60,0,1,1)];
|
||||
for(int i=0;i<4;i++){[look addObject:row([NSString stringWithFormat:@"look%dEnabled",i+2],[NSString stringWithFormat:@"风格 %d 启用",i+2],160+i*4,0,1,1,@"bool")];[look addObject:scalar([NSString stringWithFormat:@"look%dStrength",i+2],[NSString stringWithFormat:@"风格 %d 强度",i+2],64+i*4,0,1,1)];}
|
||||
section(@"look",@"风格 LUT",144,look);
|
||||
@@ -47,15 +49,15 @@ static void initialize(){static dispatch_once_t once;dispatch_once(&once,^{
|
||||
[grade addObject:scalar(@"gradingBlending",@"混合",404,0,100,50)];[grade addObject:scalar(@"gradingBalance",@"平衡",408)];section(@"grading",@"颜色分级",400,grade);
|
||||
NSMutableArray*prim=[NSMutableArray array];for(int c=0;c<3;c++)for(int a=0;a<2;a++)[prim addObject:scalar([NSString stringWithFormat:@"primary%d_%d",c,a],[NSString stringWithFormat:@"%@原色 %@",@[@"红",@"绿",@"蓝"][c],a?@"饱和度":@"色相"],484+c*8+a*4)];section(@"primaries",@"三原色",480,prim);
|
||||
NSMutableArray*levels=[NSMutableArray array];for(int c=0;c<4;c++)for(int a=0;a<5;a++)[levels addObject:scalar([NSString stringWithFormat:@"level%d_%d",c,a],[NSString stringWithFormat:@"%@ %@",@[@"RGB",@"红",@"绿",@"蓝"][c],@[@"输入黑",@"伽马",@"输入白",@"输出黑",@"输出白"][a]],624+a*16+c*4,a==1?.1:0,a==1?10:255,a==1?1:(a==2||a==4)?255:0)];section(@"levels",@"色阶",608,levels);
|
||||
NSMutableArray*bw=[NSMutableArray array];for(int c=0;c<6;c++)[bw addObject:scalar([NSString stringWithFormat:@"bw%d",c],[NSString stringWithFormat:@"黑白 %@",@[@"红",@"黄",@"绿",@"青",@"蓝",@"洋红"][c]],c<4?720+c*4:736+(c-4)*4,0,200,100)];[bw addObject:scalar(@"bwHue",@"着色色相",744,0,360)];[bw addObject:scalar(@"bwSat",@"着色饱和度",748,0,100)];section(@"blackwhite",@"黑白混色",704,bw,0);
|
||||
NSMutableArray*bw=[NSMutableArray array];for(int c=0;c<6;c++)[bw addObject:scalar([NSString stringWithFormat:@"bw%d",c],[NSString stringWithFormat:@"黑白 %@",@[@"红",@"黄",@"绿",@"青",@"蓝",@"洋红"][c]],c<4?720+c*4:736+(c-4)*4,0,200,((double[]){40,60,40,60,20,80})[c])];[bw addObject:scalar(@"bwHue",@"着色色相",744,0,360)];[bw addObject:scalar(@"bwSat",@"着色饱和度",748,0,100)];section(@"blackwhite",@"黑白混色",704,bw,0);
|
||||
NSMutableArray*balance=[NSMutableArray arrayWithObject:row(@"preserveLuma",@"保持明度",756,0,1,1,@"bool")];for(int c=0;c<3;c++)for(int a=0;a<3;a++)[balance addObject:scalar([NSString stringWithFormat:@"balance%d_%d",c,a],[NSString stringWithFormat:@"%@ %@",@[@"阴影",@"中间调",@"高光"][c],@[@"青 ↔ 红",@"洋红 ↔ 绿",@"黄 ↔ 蓝"][a]],768+c*16+a*4)];section(@"balance",@"色彩平衡",752,balance);
|
||||
});}
|
||||
NSArray *DYSections(){initialize();return sections;} NSArray *DYDescriptors(){initialize();return descriptors;}
|
||||
void DYDefaultUniforms(DYUniforms*u){memset(u,0,sizeof(*u));for(NSDictionary*r in DYDescriptors())*(float*)((uint8_t*)u+[r[@"offset"]unsignedIntegerValue])=[r[@"default"]floatValue];u->primariesM0=(DYFloat3){1,0,0};u->primariesM1=(DYFloat3){0,1,0};u->primariesM2=(DYFloat3){0,0,1};}
|
||||
void DYReadUniforms(id<PROAPIAccessing>m,CMTime t,DYUniforms*u){DYDefaultUniforms(u);id<FxParameterRetrievalAPI_v6>g=[m apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)];for(NSDictionary*r in DYDescriptors()){double v=[r[@"default"]doubleValue];if([g getFloatValue:&v fromParameter:[r[@"pid"]unsignedIntValue] atTime:t]&&std::isfinite(v))*(float*)((uint8_t*)u+[r[@"offset"]unsignedIntegerValue])=fmin([r[@"max"]doubleValue],fmax([r[@"min"]doubleValue],v));}}
|
||||
NSArray<NSDictionary*> *DYSections(void){initialize();return sections;} NSArray<NSDictionary*> *DYDescriptors(void){initialize();return descriptors;}
|
||||
void DYDefaultUniforms(DYUniforms*u){memset(u,0,sizeof(*u));for(NSDictionary*r in DYDescriptors())if([r[@"offset"]integerValue]>=0)*(float*)((uint8_t*)u+[r[@"offset"]unsignedIntegerValue])=[r[@"default"]floatValue];u->primariesM0=(DYFloat3){1,0,0};u->primariesM1=(DYFloat3){0,1,0};u->primariesM2=(DYFloat3){0,0,1};}
|
||||
void DYReadUniforms(id<PROAPIAccessing>m,CMTime t,DYUniforms*u){DYDefaultUniforms(u);id<FxParameterRetrievalAPI_v6>g=[m apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)];for(NSDictionary*r in DYDescriptors()){if([r[@"offset"]integerValue]<0)continue;double v=[r[@"default"]doubleValue];if([g getFloatValue:&v fromParameter:[r[@"pid"]unsignedIntValue] atTime:t]&&std::isfinite(v))*(float*)((uint8_t*)u+[r[@"offset"]unsignedIntegerValue])=fmin([r[@"max"]doubleValue],fmax([r[@"min"]doubleValue],v));}}
|
||||
BOOL DYCreateParameters(id<PROAPIAccessing>m,NSError**error){id<FxParameterCreationAPI_v5>a=[m apiForProtocol:@protocol(FxParameterCreationAPI_v5)];BOOL ok=a!=nil;
|
||||
ok=[a addCustomParameterWithName:@"大鱼调色" parameterID:DYInspectorParameterID defaultValue:[[[DYInspectorToken alloc]init]autorelease] parameterFlags:kFxParameterFlag_CUSTOM_UI|kFxParameterFlag_USE_FULL_VIEW_WIDTH|kFxParameterFlag_DONT_DISPLAY_IN_DASHBOARD|kFxParameterFlag_NOT_ANIMATABLE]&&ok;
|
||||
for(NSDictionary*r in DYDescriptors())ok=[a addFloatSliderWithName:r[@"title"] parameterID:[r[@"pid"]unsignedIntValue] defaultValue:[r[@"default"]doubleValue] parameterMin:[r[@"min"]doubleValue] parameterMax:[r[@"max"]doubleValue] sliderMin:[r[@"min"]doubleValue] sliderMax:[r[@"max"]doubleValue] delta:[r[@"step"]doubleValue] parameterFlags:kFxParameterFlag_HIDDEN]&&ok;
|
||||
for(NSDictionary*r in DYDescriptors())ok=[a addFloatSliderWithName:r[@"title"] parameterID:[r[@"pid"]unsignedIntValue] defaultValue:[r[@"default"]doubleValue] parameterMin:[r[@"min"]doubleValue] parameterMax:[r[@"max"]doubleValue] sliderMin:[r[@"min"]doubleValue] sliderMax:[r[@"max"]doubleValue] delta:[r[@"step"]doubleValue] parameterFlags:kFxParameterFlag_HIDDEN|([r[@"notAnimatable"]boolValue]?kFxParameterFlag_NOT_ANIMATABLE:0)]&&ok;
|
||||
ok=[a addCustomParameterWithName:@"LUT 文件" parameterID:DYAssetsParameterID defaultValue:[[[DYAssetState alloc]init]autorelease] parameterFlags:kFxParameterFlag_HIDDEN|kFxParameterFlag_NOT_ANIMATABLE]&&ok;
|
||||
if(!ok&&error)*error=[NSError errorWithDomain:FxPlugErrorDomain code:kFxError_InvalidParameter userInfo:@{NSLocalizedDescriptionKey:@"无法创建大鱼调色参数"}];return ok;}
|
||||
@implementation DYAssetState
|
||||
|
||||
+4
-3
@@ -6,6 +6,7 @@
|
||||
#import "DYAutoGrade.h"
|
||||
@implementation DYPlugIn {
|
||||
DYRenderer *_renderer;
|
||||
BOOL _copyAnalyzed;
|
||||
}
|
||||
- (instancetype)initWithAPIManager:(id<PROAPIAccessing>)manager{if((self=[super init])){_apiManager=manager;_renderer=[DYRenderer new];NSNotificationCenter*n=NSNotificationCenter.defaultCenter;[n addObserver:self selector:@selector(exportRequested:) name:@"DYExportLUT" object:manager];[n addObserver:self selector:@selector(autoRequested:) name:@"DYAutoGrade" object:manager];[n addObserver:self selector:@selector(autoRequested:) name:@"DYAutoWhiteBalance" object:manager];[n addObserver:self selector:@selector(whiteBalanceRequested:) name:@"DYWhiteBalanceColor" object:manager];}return self;}
|
||||
- (void)dealloc{[NSNotificationCenter.defaultCenter removeObserver:self];[_renderer release];[super dealloc];}
|
||||
@@ -13,14 +14,14 @@
|
||||
- (BOOL)addParametersWithError:(NSError**)e{return DYCreateParameters(_apiManager,e);}
|
||||
- (NSSet<Class>*)classesForCustomParameterID:(UInt32)pid{return pid==DYAssetsParameterID?[NSSet setWithObjects:DYAssetState.class,NSDictionary.class,NSString.class,nil]:[NSSet setWithObject:DYInspectorToken.class];}
|
||||
- (NSView*)createViewForParameterID:(UInt32)pid{return pid==DYInspectorParameterID?[[DYInspector alloc]initWithAPIManager:_apiManager]:[[NSView alloc]initWithFrame:NSZeroRect];}
|
||||
- (BOOL)parameterChanged:(UInt32)pid atTime:(CMTime)t error:(NSError**)e{dispatch_async(dispatch_get_main_queue(),^{[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:self.apiManager];});return YES;}
|
||||
- (BOOL)parameterChanged:(UInt32)pid atTime:(CMTime)t error:(NSError**)e{if(pid==2013||pid==2014||pid==DYAssetsParameterID)[_renderer invalidatePreview];dispatch_async(dispatch_get_main_queue(),^{[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:self.apiManager];});return YES;}
|
||||
- (BOOL)pluginState:(NSData**)state atTime:(CMTime)t quality:(FxQuality)q error:(NSError**)e{
|
||||
DYUniforms u;DYReadUniforms(_apiManager,t,&u);DYAssetState*a=DYReadAssets(_apiManager,t);NSDictionary*s=@{@"schema":@1,@"uniforms":[NSData dataWithBytes:&u length:sizeof(u)],@"paths":a.paths?:@{}};*state=[NSPropertyListSerialization dataWithPropertyList:s format:NSPropertyListBinaryFormat_v1_0 options:0 error:e];return *state!=nil;
|
||||
DYUniforms u;DYReadUniforms(_apiManager,t,&u);DYAssetState*a=DYReadAssets(_apiManager,t);double copyAuto=0;[[_apiManager apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)]getFloatValue:©Auto fromParameter:8800 atTime:t];NSDictionary*s=@{@"schema":@1,@"copyAuto":@(copyAuto>.5),@"uniforms":[NSData dataWithBytes:&u length:sizeof(u)],@"paths":a.paths?:@{}};*state=[NSPropertyListSerialization dataWithPropertyList:s format:NSPropertyListBinaryFormat_v1_0 options:0 error:e];return *state!=nil;
|
||||
}
|
||||
- (BOOL)destinationImageRect:(FxRect*)rect sourceImages:(NSArray<FxImageTile*>*)src destinationImage:(FxImageTile*)dst pluginState:(NSData*)s atTime:(CMTime)t error:(NSError**)e{if(!src.count)return NO;*rect=src[0].imagePixelBounds;return YES;}
|
||||
- (BOOL)sourceTileRect:(FxRect*)rect sourceImageIndex:(NSUInteger)i sourceImages:(NSArray<FxImageTile*>*)src destinationTileRect:(FxRect)dstRect destinationImage:(FxImageTile*)dst pluginState:(NSData*)s atTime:(CMTime)t error:(NSError**)e{if(i>=src.count)return NO;*rect=src[i].imagePixelBounds;return YES;}
|
||||
- (BOOL)renderDestinationImage:(FxImageTile*)dst sourceImages:(NSArray<FxImageTile*>*)src pluginState:(NSData*)s atTime:(CMTime)t error:(NSError**)e{
|
||||
if(!src.count||!src[0].ioSurface||!dst.ioSurface||!s.length)return NO;NSDictionary*p=[NSPropertyListSerialization propertyListWithData:s options:NSPropertyListImmutable format:NULL error:e];NSData*b=p[@"uniforms"];if(![p isKindOfClass:NSDictionary.class]||![p[@"schema"]isEqual:@1]||![b isKindOfClass:NSData.class]||b.length!=sizeof(DYUniforms)||![p[@"paths"]isKindOfClass:NSDictionary.class])return NO;DYUniforms u;[b getBytes:&u length:sizeof(u)];return [_renderer renderSource:src[0] destination:dst uniforms:u paths:p[@"paths"] error:e];
|
||||
if(!src.count||!src[0].ioSurface||!dst.ioSurface||!s.length)return NO;NSDictionary*p=[NSPropertyListSerialization propertyListWithData:s options:NSPropertyListImmutable format:NULL error:e];if(![p isKindOfClass:NSDictionary.class])return NO;NSData*b=p[@"uniforms"];if(![p[@"schema"]isEqual:@1]||![b isKindOfClass:NSData.class]||b.length!=sizeof(DYUniforms)||![p[@"paths"]isKindOfClass:NSDictionary.class])return NO;DYUniforms u;[b getBytes:&u length:sizeof(u)];BOOL ok=[_renderer renderSource:src[0] destination:dst uniforms:u paths:p[@"paths"] error:e];if(ok){BOOL analyze=NO;@synchronized(self){if(![p[@"copyAuto"]boolValue])_copyAnalyzed=NO;else if(!_copyAnalyzed){_copyAnalyzed=YES;analyze=YES;}}if(analyze){NSDictionary*values=DYAutoGrade([_renderer preview]);if(values)dispatch_async(dispatch_get_main_queue(),^{[self applyValues:values];});}}return ok;
|
||||
}
|
||||
- (void)alert:(NSString*)message{dispatch_async(dispatch_get_main_queue(),^{NSAlert*a=[NSAlert new];a.messageText=@"大鱼调色";a.informativeText=message?:@"操作未完成";[a runModal];[a release];});}
|
||||
- (void)exportRequested:(NSNotification*)n{
|
||||
|
||||
@@ -6,4 +6,5 @@
|
||||
- (BOOL)renderSource:(FxImageTile*)source destination:(FxImageTile*)destination uniforms:(DYUniforms)uniforms paths:(NSDictionary*)paths error:(NSError**)error;
|
||||
- (BOOL)exportLUT:(NSURL*)url uniforms:(DYUniforms)uniforms paths:(NSDictionary*)paths error:(NSError**)error;
|
||||
- (NSData*)preview;
|
||||
- (void)invalidatePreview;
|
||||
@end
|
||||
@@ -38,6 +38,7 @@ static BOOL loadCube(NSString*path,std::vector<float>&data,NSUInteger&size,NSErr
|
||||
@implementation DYRenderer
|
||||
- (instancetype)init{if((self=[super init])){_devices=[NSMutableDictionary new];_luts=[NSMutableDictionary new];_tables=[DYColorTables new];}return self;}
|
||||
- (void)dealloc{[_devices release];[_luts release];[_tables release];[_preview release];[super dealloc];}
|
||||
- (void)invalidatePreview{@synchronized(self){[_preview release];_preview=nil;_lastPreview=0;}}
|
||||
- (NSData*)preview{@synchronized(self){return [[_preview retain]autorelease];}}
|
||||
- (NSMutableDictionary*)device:(uint64_t)registry error:(NSError**)err{
|
||||
NSNumber*k=@(registry);NSMutableDictionary*entry=_devices[k];if(entry)return entry;
|
||||
@@ -45,7 +46,7 @@ static BOOL loadCube(NSString*path,std::vector<float>&data,NSUInteger&size,NSErr
|
||||
NSURL*url=[[NSBundle bundleForClass:self.class]URLForResource:@"default" withExtension:@"metallib"];
|
||||
id<MTLLibrary>lib=[d newLibraryWithURL:url error:err];if(!lib){[d release];return nil;}
|
||||
id<MTLCommandQueue>q=[d newCommandQueue];entry=[NSMutableDictionary dictionaryWithDictionary:@{@"device":d,@"library":lib,@"queue":q,@"pipelines":[NSMutableDictionary dictionary]}];
|
||||
for(NSString*fn in @[@"dyUnpremultiply",@"dyWhitesSceneStatistics",@"dyLUTExportKernel",@"dyPreview"]){id<MTLFunction>f=[lib newFunctionWithName:fn];if(!f){fail(err,[fn stringByAppendingString:@" 缺失"]);[lib release];[q release];[d release];return nil;}id<MTLComputePipelineState>p=[d newComputePipelineStateWithFunction:f error:err];[f release];if(!p){[lib release];[q release];[d release];return nil;}entry[fn]=p;[p release];}
|
||||
for(NSString*fn in @[@"dyUnpremultiply",@"dyWhitesSceneStatistics",@"dyLUTExportKernel",@"dyInputAnalysis"]){id<MTLFunction>f=[lib newFunctionWithName:fn];if(!f){fail(err,[fn stringByAppendingString:@" 缺失"]);[lib release];[q release];[d release];return nil;}id<MTLComputePipelineState>p=[d newComputePipelineStateWithFunction:f error:err];[f release];if(!p){[lib release];[q release];[d release];return nil;}entry[fn]=p;[p release];}
|
||||
float identity[32];for(int z=0;z<2;z++)for(int y=0;y<2;y++)for(int x=0;x<2;x++){int i=((z*2+y)*2+x)*4;identity[i]=x;identity[i+1]=y;identity[i+2]=z;identity[i+3]=1;}id<MTLTexture>neutral=texture3D(d,identity,2);if(!neutral){fail(err,@"无法分配中性 LUT");return nil;}entry[@"identity"]=neutral;
|
||||
_devices[k]=entry;[d release];[lib release];[q release];return entry;
|
||||
}
|
||||
@@ -62,7 +63,7 @@ static BOOL loadCube(NSString*path,std::vector<float>&data,NSUInteger&size,NSErr
|
||||
NSMutableArray*ts=[NSMutableArray array];id<MTLTexture>t=[self lut:input entry:e error:err];if(!t)return nil;[ts addObject:t];if(!input.length)u->preLUTStrength=0;
|
||||
for(int i=0;i<5;i++){NSString*p=paths[[NSString stringWithFormat:@"look%d",i]];t=[self lut:p entry:e error:err];if(!t)return nil;[ts addObject:t];if(!p.length){if(i==0)u->postLUTStrength=0;else u->extraPostLUTStrengths[i-1]=0;}}
|
||||
[DYColorTables fillPrimaries:u];id<MTLDevice>d=e[@"device"];
|
||||
id<MTLTexture>h=[_tables hslForDevice:d uniforms:u],w=[_tables whiteBalanceForDevice:d uniforms:u],g=[_tables gradingForDevice:d uniforms:u];if(!h||!w||!g){fail(err,@"颜色查表构建失败");return nil;}[ts addObjectsFromArray:@[h,w,g]];return ts;
|
||||
id<MTLTexture>h=[_tables hslForDevice:d uniforms:u],w=[_tables whiteBalanceForDevice:d uniforms:u],g=[_tables gradingForDevice:d uniforms:u];if(!h||!w||!g){fail(err,_tables.lastError?:@"颜色查表构建失败");return nil;}[ts addObjectsFromArray:@[h,w,g]];return ts;
|
||||
}
|
||||
- (BOOL)renderSource:(FxImageTile*)src destination:(FxImageTile*)dst uniforms:(DYUniforms)u paths:(NSDictionary*)paths error:(NSError**)err{@synchronized(self){@autoreleasepool{
|
||||
NSMutableDictionary*e=[self device:dst.deviceRegistryID error:err];if(!e)return NO;id<MTLDevice>d=e[@"device"];id<MTLTexture>input=[src metalTextureForDevice:d],output=[dst metalTextureForDevice:d];if(!input||!output)return fail(err,@"宿主图像纹理不可用");
|
||||
@@ -72,14 +73,14 @@ static BOOL loadCube(NSString*path,std::vector<float>&data,NSUInteger&size,NSErr
|
||||
id<MTLCommandBuffer>cb=[e[@"queue"]commandBuffer];id<MTLComputeCommandEncoder>ce=[cb computeCommandEncoder];[ce setComputePipelineState:e[@"dyUnpremultiply"]];[ce setTexture:input atIndex:0];[ce setTexture:straight atIndex:1];[ce dispatchThreads:MTLSizeMake(input.width,input.height,1) threadsPerThreadgroup:MTLSizeMake(16,16,1)];[ce endEncoding];
|
||||
float level=.5;id<MTLBuffer>scene=[d newBufferWithBytes:&level length:4 options:MTLResourceStorageModeShared];
|
||||
if(u.whites>0&&u.whitesEnabled>.5&&u.baseSectionEnabled>.5){ce=[cb computeCommandEncoder];[ce setComputePipelineState:e[@"dyWhitesSceneStatistics"]];[ce setTexture:straight atIndex:0];[ce setTexture:ts[7] atIndex:1];[ce setBytes:&u length:sizeof(u) atIndex:0];[ce setBuffer:scene offset:0 atIndex:1];[ce dispatchThreadgroups:MTLSizeMake(1,1,1) threadsPerThreadgroup:MTLSizeMake(256,1,1)];[ce endEncoding];}
|
||||
BOOL preview=CACurrentMediaTime()-_lastPreview>.5;id<MTLBuffer>pb=nil;if(preview){pb=[d newBufferWithLength:64*64*16 options:MTLResourceStorageModeShared];ce=[cb computeCommandEncoder];[ce setComputePipelineState:e[@"dyPreview"]];[ce setTexture:straight atIndex:0];[ce setBuffer:pb offset:0 atIndex:0];[ce dispatchThreads:MTLSizeMake(64,64,1) threadsPerThreadgroup:MTLSizeMake(8,8,1)];[ce endEncoding];}
|
||||
BOOL preview=CACurrentMediaTime()-_lastPreview>.5;id<MTLBuffer>pb=nil;if(preview){pb=[d newBufferWithLength:320*180*16 options:MTLResourceStorageModeShared];ce=[cb computeCommandEncoder];[ce setComputePipelineState:e[@"dyInputAnalysis"]];[ce setTexture:straight atIndex:0];[ce setTexture:ts[0] atIndex:1];float inputStrength=u.inputSectionEnabled>.5?u.preLUTStrength:0;[ce setBytes:&inputStrength length:4 atIndex:1];[ce setBuffer:pb offset:0 atIndex:0];[ce dispatchThreads:MTLSizeMake(320,180,1) threadsPerThreadgroup:MTLSizeMake(8,8,1)];[ce endEncoding];}
|
||||
MTLRenderPassDescriptor*rp=[MTLRenderPassDescriptor renderPassDescriptor];rp.colorAttachments[0].texture=output;rp.colorAttachments[0].loadAction=MTLLoadActionDontCare;rp.colorAttachments[0].storeAction=MTLStoreActionStore;id<MTLRenderCommandEncoder>re=[cb renderCommandEncoderWithDescriptor:rp];[re setRenderPipelineState:pipeline];
|
||||
float w=output.width,h=output.height;FxRect s=src.tilePixelBounds,t=dst.tilePixelBounds;float sw=s.right-s.left,sh=s.top-s.bottom;float l=(t.left-s.left)/sw,r=(t.right-s.left)/sw,top=(s.top-t.top)/sh,bottom=(s.top-t.bottom)/sh;
|
||||
if(src.imageOrigin==kFxImageOrigin_BOTTOM_LEFT){top=1-top;bottom=1-bottom;}
|
||||
DYVertex2D vs[]={{{w/2,-h/2},{r,bottom}},{{-w/2,-h/2},{l,bottom}},{{w/2,h/2},{r,top}},{{-w/2,h/2},{l,top}}};
|
||||
if(dst.imageOrigin==kFxImageOrigin_BOTTOM_LEFT)for(int i=0;i<4;i++)vs[i].position.y=-vs[i].position.y;
|
||||
vector_uint2 vp={(unsigned)output.width,(unsigned)output.height};[re setVertexBytes:vs length:sizeof(vs) atIndex:0];[re setVertexBytes:&vp length:sizeof(vp) atIndex:1];[re setViewport:(MTLViewport){0,0,w,h,0,1}];[re setFragmentTexture:straight atIndex:0];for(NSUInteger i=0;i<ts.count;i++)[re setFragmentTexture:ts[i] atIndex:i+1];[re setFragmentBytes:&u length:sizeof(u) atIndex:0];[re setFragmentBuffer:scene offset:0 atIndex:1];DYRenderOptions options={1,0,0,0};[re setFragmentBytes:&options length:sizeof(options) atIndex:2];[re drawPrimitives:MTLPrimitiveTypeTriangleStrip vertexStart:0 vertexCount:4];[re endEncoding];[cb commit];[cb waitUntilCompleted];BOOL ok=cb.status==MTLCommandBufferStatusCompleted;
|
||||
if(ok&&pb){[_preview release];_preview=[[NSData alloc]initWithBytes:pb.contents length:64*64*16];_lastPreview=CACurrentMediaTime();}
|
||||
if(ok&&pb){[_preview release];_preview=[[NSData alloc]initWithBytes:pb.contents length:320*180*16];_lastPreview=CACurrentMediaTime();}
|
||||
if(!ok)fail(err,cb.error.localizedDescription);[pb release];[straight release];[scene release];return ok;
|
||||
}}}
|
||||
- (BOOL)exportLUT:(NSURL*)url uniforms:(DYUniforms)u paths:(NSDictionary*)paths error:(NSError**)err{@synchronized(self){
|
||||
|
||||
+3
-5
@@ -1,6 +1,4 @@
|
||||
#import <FxPlug/FxPlugSDK.h>
|
||||
|
||||
int main(int argc, const char *argv[])
|
||||
{
|
||||
[FxPrincipal startServicePrincipal];
|
||||
}
|
||||
#import "DYDiagnostics.h"
|
||||
#include <string.h>
|
||||
int main(int argc,const char*argv[]){@autoreleasepool{if(argc==2&&strcmp(argv[1],"--self-test")==0)return DYRunDiagnostics();[FxPrincipal startServicePrincipal];return 0;}}
|
||||
@@ -1,27 +1,15 @@
|
||||
//
|
||||
// AppDelegate.m
|
||||
// 大鱼调色
|
||||
//
|
||||
// Created by mac on 2026/10/31.
|
||||
//
|
||||
|
||||
#import "AppDelegate.h"
|
||||
|
||||
@interface AppDelegate ()
|
||||
|
||||
@property (weak) IBOutlet NSWindow *window;
|
||||
@property(weak) IBOutlet NSWindow *window;
|
||||
@end
|
||||
|
||||
@implementation AppDelegate
|
||||
|
||||
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
|
||||
// Insert code here to initialize your application
|
||||
- (void)applicationDidFinishLaunching:(NSNotification*)n{
|
||||
self.window.title=@"大鱼调色";[self.window setContentSize:NSMakeSize(540,280)];[self.window center];
|
||||
NSView*v=[[[NSView alloc]initWithFrame:NSMakeRect(0,0,540,280)]autorelease];v.wantsLayer=YES;v.layer.backgroundColor=[NSColor colorWithSRGBRed:.025 green:.08 blue:.13 alpha:1].CGColor;self.window.contentView=v;
|
||||
NSTextField*title=[NSTextField labelWithString:@"大鱼调色"];title.font=[NSFont boldSystemFontOfSize:28];title.textColor=[NSColor colorWithSRGBRed:.3 green:.75 blue:1 alpha:1];title.frame=NSMakeRect(32,212,460,42);[v addSubview:title];
|
||||
NSTextField*body=[NSTextField wrappingLabelWithString:@"已安装原生 FxPlug 调色效果。\n\n在 Final Cut Pro 的「效果 → 大鱼调色」中应用,或在 Motion 的滤镜中选择「大鱼调色」。\n\n输入转换、光影、曲线、HSL、色轮与 LUT 均在宿主检查器中编辑。"];body.font=[NSFont systemFontOfSize:14];body.textColor=[NSColor colorWithWhite:.86 alpha:1];body.frame=NSMakeRect(34,65,470,140);[v addSubview:body];
|
||||
NSButton*b=[NSButton buttonWithTitle:@"打开 Final Cut Pro" target:self action:@selector(openHost:)];b.frame=NSMakeRect(30,20,170,32);[v addSubview:b];[self.window makeKeyAndOrderFront:nil];
|
||||
}
|
||||
|
||||
|
||||
- (void)applicationWillTerminate:(NSNotification *)aNotification {
|
||||
// Insert code here to tear down your application
|
||||
}
|
||||
|
||||
|
||||
- (void)openHost:(id)sender{NSURL*u=[NSWorkspace.sharedWorkspace URLForApplicationWithBundleIdentifier:@"com.apple.FinalCut"];if(u)[NSWorkspace.sharedWorkspace openApplicationAtURL:u configuration:NSWorkspaceOpenConfiguration.configuration completionHandler:nil];}
|
||||
- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication*)app{return YES;}
|
||||
@end
|
||||
在新工单中引用
屏蔽一个用户