文件
dayu-color/大鱼调色/Plugin/DYUnifiedRender.inc.h
T

99 行
12 KiB
C

// V4: stable author order, one movable output boundary, explicit node domains.
- (BOOL)renderUnifiedSource:(FxImageTile*)src destination:(FxImageTile*)dst uniforms:(DYUniforms)u paths:(NSDictionary*)paths spider:(NSData*)spider tools:(NSDictionary*)tools hostPrimaries:(NSInteger)primaries error:(NSError**)error {
if(tools[@"sharedMasks"])tools=DYResolvedToolDocument(tools);
NSMutableDictionary*entry=[self device:dst.deviceRegistryID error:error];if(!entry)return NO;id<MTLDevice>d=entry[@"device"];id<MTLTexture>source=[src metalTextureForDevice:d];if(!source)return fail(error,@"一级 CST 输入纹理不可用。");
DYManagedBatch batch{entry[@"queue"],error};
uint64_t pixels=uint64_t(source.width)*source.height;if(!pixels||pixels>64ull*1024*1024||pixels*16*8>MAX(768ull*1024*1024,MIN(2ull*1024*1024*1024,d.recommendedMaxWorkingSetSize/2)))return fail(error,@"当前画面超过一级 CST 内存预算。");
BOOL inputEnabled=u.inputSectionEnabled>.5;DYCMSettings global=u.cm;DYApplyRemovedBaseTools(&u,tools);u.cm=global;int wt=lroundf(u.cm.workingTransfer),wg=lroundf(u.cm.workingGamut);
NSMutableArray*pool=[NSMutableArray array];NSCountedSet*pinned=[NSCountedSet set];id<MTLTexture>current=nil,originalWorking=nil;int initialGamut=wg,initialTransfer=wt;
auto next=[&]()->id<MTLTexture>{for(id<MTLTexture>t in pool)if(t!=current&&![pinned containsObject:t])return t;MTLTextureDescriptor*td=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA32Float width:source.width height:source.height mipmapped:NO];td.storageMode=MTLStorageModePrivate;td.usage=MTLTextureUsageShaderRead|MTLTextureUsageShaderWrite|MTLTextureUsageRenderTarget;id<MTLTexture>t=[d newTextureWithDescriptor:td];if(t){[pool addObject:t];[t release];}return t;};
auto dispatch=[&](NSString*name,const void*params,NSUInteger length,const void*extra=nullptr,NSUInteger extraLength=0){id<MTLTexture>out=next();if(!out)return fail(error,@"无法分配一级 CST 缓冲区。");BOOL ok=[self encodeManagedDispatch:name textures:@[current,out] data:params length:length extra:extra extraLength:extraLength entry:entry commands:batch.commands() error:error];if(ok)current=out;return ok;};
auto transform=[&](CSTParams p){if(p.inputTransfer==p.outputTransfer&&p.inputGamut==p.outputGamut&&!p.toneMapping)return YES;return dispatch(@"dyPrimaryCST",&p,sizeof(p));};
auto tile=[&](id<MTLTexture>t){DYExportTile*v=[[[DYExportTile alloc]initWithTexture:t registry:d.registryID]autorelease];[v setBounds:src.tilePixelBounds origin:src.imageOrigin];[v setPixelAspect:src.pixelAspect];return v;};
auto blend=[&](id<MTLTexture>before,NSArray*masks,float amount,NSString*type){if(!masks.count&&amount>=1)return YES;id<MTLTexture>out=next();if(!out)return fail(error,@"无法分配一级混合缓冲区。");DYToolMaskHeader h{};id<MTLBuffer>mb=[self maskBuffer:@{type:masks?:@[]} tile:src device:d header:&h];h.section=(int)[DYToolTypes()indexOfObject:type];struct {CSTParams toLinear,fromLinear,originalTo709;float amount;}p={{wg,wt,2,20,0},{2,20,wg,wt,0},{initialGamut,initialTransfer,22,20,0},amount};id<MTLComputePipelineState>pipeline=[self computePipeline:@"dyUnifiedBlend" entry:entry error:error];if(!pipeline||!mb)return NO;id<MTLCommandBuffer>commands=batch.commands();if(!commands)return NO;id<MTLComputeCommandEncoder>ce=[commands computeCommandEncoder];if(!ce)return fail(error,@"无法创建一级混合编码器");[ce setComputePipelineState:pipeline];[ce setTexture:before atIndex:0];[ce setTexture:current atIndex:1];[ce setTexture:out atIndex:2];[ce setTexture:originalWorking?:before atIndex:3];[ce setBuffer:mb offset:0 atIndex:0];[ce setBytes:&h length:sizeof(h) atIndex:1];[ce setBytes:&p length:sizeof(p) atIndex:2];[ce dispatchThreads:MTLSizeMake(source.width,source.height,1) threadsPerThreadgroup:MTLSizeMake(16,16,1)];[ce endEncoding];current=out;return YES;};
auto grade=[&](DYUniforms values,NSArray*masks,BOOL local){if(values.primarySectionEnabled<.5||values.cm.mix<=0)return YES;DYUniforms neutral=values;neutral.inputSectionEnabled=neutral.cm.outputEnabled=0;BOOL gradeNeutral=identityCM(neutral);if(!local&&gradeNeutral)return YES;if(local&&identityCM(values))return YES;
DayuRenderParams p=DYCMRender(values.cm);p.input.toneMapping=0;if((int)lroundf(values.cm.workingTransfer)==20){p.reserved|=8;p.basis.colorspace=10;p.basisInput={(int)lroundf(values.cm.workingGamut),20,(int)lroundf(values.cm.workingGamut),10,0};p.basisOutput={(int)lroundf(values.cm.workingGamut),10,(int)lroundf(values.cm.workingGamut),20,0};}CSTParams back={wg,wt,wg,wt,0};
if(local){p.stages=(values.inputSectionEnabled>.5?1:0)|(gradeNeutral?0:2)|(values.cm.outputEnabled>.5?4:0);back={values.cm.outputEnabled>.5?(int)lroundf(values.cm.outputGamut):(int)lroundf(values.cm.workingGamut),values.cm.outputEnabled>.5?(int)lroundf(values.cm.outputTransfer):(int)lroundf(values.cm.workingTransfer),wg,wt,0};}
else{p.stages=2;}
id<MTLTexture>before=current;[pinned addObject:before];BOOL ok=dispatch(@"dyPrimaryGrade",&p,sizeof(p),&back,sizeof(back));if(ok)ok=blend(before,masks,values.cm.mix,@"primary");[pinned removeObject:before];return ok;
};
auto print=[&](DYUniforms values,NSArray*masks){if(!DYFilmPrintActive(values))return YES;NSArray*names=@[@"",@"kodak_2383",@"kodak_2393",@"kodak_2302_bw",@"fuji_3510",@"fuji_3513",@"fuji_3519",@"fuji_3521",@"agfa_cp30"];NSString*path=[[NSBundle bundleForClass:self.class]pathForResource:names[(int)values.filmPrint.x] ofType:@"dylut" inDirectory:@"PrintLooks"];id<MTLTexture>cube=path?[self lut:path entry:entry error:error]:nil;if(!cube)return fail(error,@"印片资源不可用。");id<MTLTexture>before=current;[pinned addObject:before];BOOL ok=transform({wg,wt,2,1,0});float amount=values.filmPrint.y*values.film.mix;if(ok){id<MTLTexture>out=next();ok=out&&[self encodeManagedDispatch:@"dyManagedPrint" textures:@[current,cube,out] data:&amount length:4 extra:nullptr extraLength:0 entry:entry commands:batch.commands() error:error];if(ok)current=out;}if(ok)ok=transform({2,1,wg,wt,0});if(ok)ok=blend(before,masks,1,@"film");[pinned removeObject:before];return ok;};
// Recover only the pre-existing explicit code-value carrier. No display
// transform or host-profile-to-709 conversion precedes the declared input.
current=source;id<MTLTexture>carrier=next();uint32_t noLUT=0;if(!carrier||![self encodeManagedDispatch:@"dyManagedCarrier" textures:@[current,carrier,entry[@"identity"]] data:&noLUT length:4 extra:nullptr extraLength:0 entry:entry commands:batch.commands() error:error])return NO;current=carrier;
if(inputEnabled&&!transform({(int)lroundf(u.cm.inputGamut),(int)lroundf(u.cm.inputTransfer),wg,wt,0}))return NO;
// Preserve the original working image for source-referenced operations.
originalWorking=current;[pinned addObject:originalWorking];
auto isolated=[&](NSString *type,DYUniforms values,NSDictionary *nodePaths,NSData *mesh,NSArray *masks){
NSMutableDictionary *node=[NSMutableDictionary dictionaryWithDictionary:DYNewTool(type)];NSMutableDictionary *v=[NSMutableDictionary dictionary];
for(NSDictionary *descriptor in DYBaseToolDescriptors(type))if([descriptor[@"offset"]integerValue]>=0)v[descriptor[@"key"]]=@(*(float*)((uint8_t*)&values+[descriptor[@"offset"]unsignedIntegerValue]));
node[@"values"]=v;node[@"paths"]=nodePaths?:@{};node[@"masks"]=@[];if(mesh)node[@"spider"]=mesh;
node[@"filmFrameKey"]=@(values.filmFrameKey);
if(DYToolIsNeutral(node))return YES;
id<MTLTexture>before=current;[pinned addObject:before];BOOL ok=YES;
if([type isEqual:@"base"]&&values.baseSectionEnabled>.5&&values.exposureEnabled>.5&&values.exposure!=0){float gain=exp2f(values.exposure);ok=transform({wg,wt,wg,20,0})&&dispatch(@"dyUnifiedExposure",&gain,sizeof(gain))&&transform({wg,20,wg,wt,0});node[@"values"][@"exposure"]=@0;}
if(!ok){[pinned removeObject:before];return NO;}
if(DYToolIsNeutral(node)){}
else if([type isEqual:@"lens"]){id<MTLTexture>out=next();ok=out&&batch.finish()&&[self renderLens:tile(current) destination:tile(out) uniforms:values masks:@[] entry:entry error:error];if(ok)current=out;}
else {
// Creative Rec.709 LUT/film and skin models declare a local reference domain.
// All other legacy controls operate on the current working RGB code values.
BOOL reference=[@[@"look",@"film",@"skin"]containsObject:type];
int domainGamut=reference?22:wg,domainTransfer=reference?1002:wt;
if(reference)ok=transform({wg,wt,domainGamut,domainTransfer,0});
id<MTLTexture>raw=current;[pinned addObject:raw];
if(ok)ok=dispatch(@"dyUnifiedBridgeIn",nullptr,0);
id<MTLTexture>bounded=current;[pinned addObject:bounded];
// A source-referenced skin node compares to the original image in this same
// domain, never to a previous frame or an unrelated cached display image.
id<MTLTexture>referenceTexture=bounded;
if(ok&&[type isEqual:@"skin"]){if(!_exporting&&(values.skinFaceOnly>.5||values.skinVisualize>.5)){
if(!batch.finish())return NO;
[self prepareFaceSupport:tile(bounded)];
}else{[_faceEntries release];_faceEntries=nil;}current=originalWorking;ok=transform({initialGamut,initialTransfer,domainGamut,domainTransfer,0})&&dispatch(@"dyUnifiedBridgeIn",nullptr,0);referenceTexture=current;[pinned addObject:referenceTexture];current=bounded;}
if(ok){id<MTLTexture>out=next();_managedFinishing=YES;@try{ok=out&&batch.finish()&&[self renderExtraTool:node source:tile(bounded) original:tile(referenceTexture) destination:tile(out) entry:entry error:error];}@finally{_managedFinishing=NO;}if(ok)current=out;}
if(referenceTexture!=bounded)[pinned removeObject:referenceTexture];[pinned removeObject:bounded];
if(ok){id<MTLTexture>out=next();ok=out&&[self encodeManagedDispatch:@"dyUnifiedBridgeOut" textures:@[raw,current,out] data:nullptr length:0 extra:nullptr extraLength:0 entry:entry commands:batch.commands() error:error];if(ok)current=out;}
[pinned removeObject:raw];
if(ok&&reference)ok=transform({domainGamut,domainTransfer,wg,wt,0});
}
if(ok)ok=blend(before,masks,1,type);[pinned removeObject:before];return ok;
};
for(NSString *ID in DYUnifiedRenderOrder(tools)){
if([ID isEqual:@"output"]){
if(u.cm.outputEnabled>.5){CSTParams output={wg,wt,(int)lroundf(u.cm.outputGamut),(int)lroundf(u.cm.outputTransfer),0};
if(u.cm.toneMapping>.5)output.toneMapping=(wt>1000?2:0)+(output.outputTransfer>1000?1:0);
if(!transform(output))return NO;wg=output.outputGamut;wt=output.outputTransfer;
}continue;
}
BOOL base=[ID hasPrefix:@"base:"];NSDictionary *node=base?nil:DYToolWithID(tools,ID);NSString *type=base?[ID substringFromIndex:5]:node[@"type"];
if(base&&DYBaseToolRemoved(tools,type))continue;
DYUniforms values=base?u:DYToolUniforms(node);NSArray *masks=base?tools[@"baseMasks"][type]:node[@"masks"];
if([type isEqual:@"primary"]){values.inputSectionEnabled=values.cm.outputEnabled=0;values.cm.workingTransfer=wt;values.cm.workingGamut=wg;if(!grade(values,masks,NO))return NO;continue;}
if([type isEqual:@"film"]){if(!print(values,masks))return NO;values.filmPrint.x=0;}
if(!isolated(type,values,base?DYVisibleBaseToolPaths(paths,tools):node[@"paths"],base?spider:node[@"spider"],masks))return NO;
}
[pinned removeObject:originalWorking];
// Final host adaptation is separate from the movable output node. Cube uses
// the exact current code domain after the same ordered operations.
DYManagedPreviewReadback preview{};
if(_exporting){
if(!dispatch(@"dyPrimaryCodeOutput",nullptr,0))return NO;
}else{
if(!transform({wg,wt,22,20,0}))return NO;
preview=[self encodeManagedPreview:current source:src entry:entry commands:batch.commands()];
DYColorProfile *profile=[self managedOutputProfile:error];if(!profile)return NO;
if(!profile.identity){
if(!batch.finish())return NO;
id<MTLTexture>out=next();if(!out||![self managedProfile:profile input:current output:out entry:entry error:error])return NO;
current=out;
}
}
_managedFinishing=YES;
@try{
BOOL ok=[self copyTile:tile(current) to:dst rotation:0 entry:entry commands:batch.commands() error:error];
if(ok)[self publishManagedPreview:preview];
return ok;
}@finally{_managedFinishing=NO;}
}