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

204 行
23 KiB
C++

- (DYManagedPreviewReadback)encodeManagedPreview:(id<MTLTexture>)texture source:(FxImageTile*)source
entry:(NSMutableDictionary*)entry commands:(id<MTLCommandBuffer>)commands {
if(!commands)return {};
NSSize size=DYLookSampleSize(texture,source.pixelAspect,DYLookPreviewStandardEdge);
@synchronized(_previewLock){if(_exporting||(NSEqualSizes(size,_lastLookPreviewSize)&&CACurrentMediaTime()-_lastPreview<=.5))return {};}
id<MTLComputePipelineState>p=[self computePipeline:@"dyManagedPreview" entry:entry error:nil];if(!p)return {};
id<MTLBuffer>b=[[entry[@"device"]newBufferWithLength:320*180*16 options:MTLResourceStorageModeShared]autorelease];if(!b)return {};
id<MTLComputeCommandEncoder>ce=[commands computeCommandEncoder];if(!ce)return {};
[ce setComputePipelineState:p];[ce setTexture:texture atIndex:0];[ce setBuffer:b offset:0 atIndex:0];[ce dispatchThreads:MTLSizeMake(320,180,1) threadsPerThreadgroup:MTLSizeMake(8,8,1)];[ce endEncoding];
FxImageOrigin origin=source.imageOrigin;
id<MTLBuffer>standard=NSEqualSizes(size,NSMakeSize(320,180))?nil:[self encodeLookPreview:texture inputLUT:nil strength:0 size:size standard:YES origin:origin entry:entry commands:commands];
NSSize highSize=DYLookSampleSize(texture,source.pixelAspect,DYLookPreviewHighEdge);
id<MTLBuffer>high=[self encodeLookPreview:texture inputLUT:nil strength:0 size:highSize standard:NO origin:origin entry:entry commands:commands];
return {b,standard,high,size,highSize,origin};
}
- (void)publishManagedPreview:(DYManagedPreviewReadback)preview {
if(preview.analysis)[self publishPreview:preview.analysis standard:preview.standard size:preview.size high:preview.high highSize:preview.highSize origin:preview.origin];
}
- (NSDictionary*)colorContext {@synchronized(_previewLock){return [[_colorContext retain]autorelease];}}
static BOOL DYColorSpacesMatch(CGColorSpaceRef a,CGColorSpaceRef b){return a==b||(a&&b&&CFEqual(a,b));}
- (void)updateHostColorContextFrom:(FxImageTile*)source to:(FxImageTile*)destination primaries:(NSInteger)primaries {
CGColorSpaceRef a=DYManagedTileSpace(source,primaries),b=DYManagedTileSpace(destination,primaries);
BOOL sourceChanged=!DYColorSpacesMatch(a,_renderSourceSpace);
BOOL destinationChanged=!DYColorSpacesMatch(b,_renderDestinationSpace);
if(!_colorContext||sourceChanged||destinationChanged||primaries!=[_colorContext[@"primaries"]integerValue]){
NSDictionary *context=DYHostColorContext(a,b,primaries);
@synchronized(_previewLock){[_colorContext release];_colorContext=[context copy];}
}
if(sourceChanged){if(_renderSourceSpace)CGColorSpaceRelease(_renderSourceSpace);_renderSourceSpace=a;a=nil;}
if(destinationChanged){
if(_renderDestinationSpace)CGColorSpaceRelease(_renderDestinationSpace);_renderDestinationSpace=b;b=nil;
[_renderOutputProfile release];_renderOutputProfile=nil;
}
if(a)CGColorSpaceRelease(a);if(b)CGColorSpaceRelease(b);
}
- (DYColorProfile*)managedOutputProfile:(NSError**)error {
if(!_renderDestinationSpace){fail(error,@"宿主未提供明确的目标颜色空间。");return nil;}
if(!_renderOutputProfile){
CGColorSpaceRef linear709=CGColorSpaceCreateWithName(kCGColorSpaceExtendedLinearSRGB);
_renderOutputProfile=[[DYColorProfile alloc]initWithSource:linear709 target:_renderDestinationSpace error:error];
if(linear709)CGColorSpaceRelease(linear709);
}
return _renderOutputProfile;
}
- (BOOL)encodeManagedDispatch:(NSString*)name textures:(NSArray*)textures data:(const void*)data length:(NSUInteger)length
extra:(const void*)extra extraLength:(NSUInteger)extraLength entry:(NSMutableDictionary*)entry
commands:(id<MTLCommandBuffer>)commands error:(NSError**)error {
if(!commands)return NO;
id<MTLComputePipelineState>pipeline=[self computePipeline:name entry:entry error:error];if(!pipeline)return NO;
id<MTLComputeCommandEncoder>ce=[commands computeCommandEncoder];if(!ce)return fail(error,@"无法创建调色编码器");
[ce setComputePipelineState:pipeline];
for(NSUInteger i=0;i<textures.count;i++)[ce setTexture:textures[i] atIndex:i];
if(data)[ce setBytes:data length:length atIndex:0];if(extra)[ce setBytes:extra length:extraLength atIndex:1];
id<MTLTexture>t=textures[0];[ce dispatchThreads:MTLSizeMake(t.width,t.height,1) threadsPerThreadgroup:MTLSizeMake(16,16,1)];
[ce endEncoding];return YES;
}
- (BOOL)managedConvert:(dycm::Space)from to:(dycm::Space)to display:(NSInteger)display gamut:(BOOL)gamut input:(id<MTLTexture>)input output:(id<MTLTexture>)output entry:(NSMutableDictionary*)entry commands:(id<MTLCommandBuffer>)commands error:(NSError**)error {
if(!commands)return NO;
static std::mutex guard;static std::map<std::string,dycm::Transform>plans;
std::string key=std::to_string(unsigned(from))+":"+std::to_string(unsigned(to))+":"+std::to_string(display)+":"+std::to_string(gamut);
dycm::Transform transform=[&]{std::lock_guard<std::mutex>lock(guard);auto i=plans.find(key);if(i!=plans.end())return i->second;auto t=display?dycm::Transform::display(from,dycm::Output(display),gamut):dycm::Transform::convert(from,to);if(plans.size()>=48)plans.clear();plans.emplace(key,t);return t;}();
DYColorManagementGPU*p=[[DYColorManagementGPUCache sharedCache]pipelineWithDevice:entry[@"device"] transform:transform resourceBudget:128*1024*1024 error:error];if(!p)return NO;return [p encodeInput:input output:output alpha:dycm::Alpha::Premultiplied commandBuffer:commands workspaceBudget:2ull*1024*1024*1024 error:error];
}
- (BOOL)managedProfile:(DYColorProfile*)profile input:(id<MTLTexture>)input output:(id<MTLTexture>)output entry:(NSMutableDictionary*)entry error:(NSError**)error {
if(!profile)return NO;NSMutableDictionary*cache=entry[@"managedProfiles"];if(!cache){cache=[NSMutableDictionary dictionary];entry[@"managedProfiles"]=cache;}DYColorProfileGPU*p=cache[profile.key];if(!p){p=[[[DYColorProfileGPU alloc]initWithDevice:entry[@"device"] profile:profile error:error]autorelease];if(!p)return NO;if(cache.count>=16)[cache removeAllObjects];cache[profile.key]=p;}return [p renderInput:input output:output alpha:dycm::Alpha::Premultiplied workspaceBudget:2ull*1024*1024*1024 cancelled:nullptr error:error];
}
// Each stamp reads the same original frame. A later stamp may cover an
// earlier one, but overlapping source and destination never feed back.
- (FxImageTile*)sourceByApplyingStamps:(NSArray*)masks source:(FxImageTile*)source registry:(uint64_t)registry error:(NSError**)error{
std::vector<DYCloneStamp> stamps;
FxRect image=source.imagePixelBounds,bounds=source.tilePixelBounds;
if(image.right<=image.left||image.top<=image.bottom)return source;
for(NSDictionary *mask in masks){
NSArray *patch=mask[@"stampSource"];
if(!patch||![mask[@"enabled"]boolValue])continue;
DYMaskParameters p=DYMaskAtTime(mask,kCMTimeInvalid);
if(p.strength<=0)continue;
NSArray *scale=mask[@"stampSamplingScale"];
stamps.push_back({p.centerX,p.centerY,[patch[0]floatValue],[patch[1]floatValue],
scale?[scale[0]floatValue]:1.f,scale?[scale[1]floatValue]:1.f,
2/p.width,2/p.height,p.feather,p.strength,p.inputBlack,p.inputWhite,p.inputGamma,scale?1u:0u});
}
if(stamps.empty())return source;
if(image.left!=bounds.left||image.right!=bounds.right||image.top!=bounds.top||image.bottom!=bounds.bottom){
fail(error,@"仿制图章需要宿主提供完整的源画面。");return nil;
}
NSMutableDictionary *entry=[self device:registry error:error];if(!entry)return nil;
id<MTLComputePipelineState> pipeline=[self computePipeline:@"dyCloneStamps" entry:entry error:error];if(!pipeline)return nil;
id<MTLDevice>device=entry[@"device"];
id<MTLTexture>input=[source metalTextureForDevice:device];
if(!input||input.framebufferOnly){fail(error,@"仿制图章无法读取源画面。");return nil;}
MTLTextureDescriptor *desc=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA32Float width:input.width height:input.height mipmapped:NO];
desc.storageMode=MTLStorageModePrivate;desc.usage=MTLTextureUsageShaderRead|MTLTextureUsageShaderWrite;
id<MTLTexture>output=[[device newTextureWithDescriptor:desc]autorelease];
id<MTLCommandBuffer>commands=[entry[@"queue"]commandBuffer];
id<MTLComputeCommandEncoder>encoder=[commands computeCommandEncoder];
if(!output||!encoder){fail(error,@"无法分配仿制图章缓冲区。");return nil;}
uint32_t count=(uint32_t)stamps.size(),flip=source.imageOrigin==kFxImageOrigin_BOTTOM_LEFT;
[encoder setComputePipelineState:pipeline];
[encoder setTexture:input atIndex:0];[encoder setTexture:output atIndex:1];
[encoder setBytes:stamps.data() length:count*sizeof(DYCloneStamp) atIndex:0];
[encoder setBytes:&count length:sizeof(count) atIndex:1];[encoder setBytes:&flip length:sizeof(flip) atIndex:2];
[encoder dispatchThreads:MTLSizeMake(output.width,output.height,1) threadsPerThreadgroup:MTLSizeMake(16,16,1)];
[encoder endEncoding];[commands commit];[commands waitUntilCompleted];
if(commands.status!=MTLCommandBufferStatusCompleted){fail(error,commands.error.localizedDescription);return nil;}
DYExportTile *tile=[[[DYExportTile alloc]initWithTexture:output registry:registry]autorelease];
[tile setBounds:bounds origin:source.imageOrigin];[tile setPixelAspect:source.pixelAspect];[tile inheritColorSpace:source.colorSpace];
return tile;
}
- (BOOL)renderSource:(FxImageTile*)src destination:(FxImageTile*)dst uniforms:(DYUniforms)u paths:(NSDictionary*)paths spider:(NSData*)spider tools:(NSDictionary*)tools colorManagement:(NSDictionary*)state hostPrimaries:(NSInteger)primaries error:(NSError**)error {
if([tools[@"starterTool"]isEqual:@"cst"])u.cm.basisEnabled=0;
double angle=[tools[@"levelMeasureOnly"]boolValue]?0:[tools[@"levelRotation"] doubleValue];
if(!angle)return [self renderColorSource:src destination:dst uniforms:u paths:paths spider:spider tools:tools colorManagement:state hostPrimaries:primaries error:error];
@synchronized(self){return DYRenderWithPool(error,[&]()->BOOL{
if(!DYValidToolDocument(tools))return fail(error,@"水平校正数据无效");
NSMutableDictionary *entry=[self device:dst.deviceRegistryID error:error];
if(!entry)return NO;
id<MTLDevice>device=entry[@"device"];
FxRect bounds=src.imagePixelBounds;
NSInteger width=bounds.right-bounds.left,height=bounds.top-bounds.bottom;
if(width<=0||height<=0)return fail(error,@"画面尺寸无效");
MTLTextureDescriptor *desc=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA32Float width:width height:height mipmapped:NO];
desc.storageMode=MTLStorageModePrivate;
desc.usage=MTLTextureUsageRenderTarget|MTLTextureUsageShaderRead|MTLTextureUsageShaderWrite;
id<MTLTexture>texture=[device newTextureWithDescriptor:desc];
if(!texture)return fail(error,@"无法分配水平校正缓冲区");
DYExportTile *frame=[[[DYExportTile alloc]initWithTexture:texture registry:device.registryID]autorelease];
[texture release];
[frame setBounds:bounds origin:dst.imageOrigin];
[frame setPixelAspect:src.pixelAspect];
[frame inheritColorSpace:dst.colorSpace];
if(![self renderColorSource:src destination:frame uniforms:u paths:paths spider:spider tools:tools colorManagement:state hostPrimaries:primaries error:error])return NO;
return [self copyTile:frame to:dst rotation:angle entry:entry error:error];
});}
}
- (BOOL)renderColorSource:(FxImageTile*)src destination:(FxImageTile*)dst uniforms:(DYUniforms)u paths:(NSDictionary*)paths spider:(NSData*)spider tools:(NSDictionary*)tools colorManagement:(NSDictionary*)state hostPrimaries:(NSInteger)primaries error:(NSError**)error {@synchronized(self){return DYRenderWithPool(error,[&]()->BOOL{
if(state&&![state isKindOfClass:NSDictionary.class])return fail(error,@"色彩管理状态无效。");
[self updateHostColorContextFrom:src to:dst primaries:primaries];
if([tools[@"mosaic"][@"enabled"]boolValue]){
if(!DYValidToolDocument(tools))return fail(error,@"局部马赛克设置无效。");
FxImageTile *mosaic=[self sourceByApplyingMosaic:tools source:src registry:dst.deviceRegistryID error:error];if(!mosaic)return NO;
NSMutableDictionary *remaining=[[tools mutableCopy]autorelease];[remaining removeObjectForKey:@"mosaic"];[remaining removeObjectForKey:@"mosaicRenderMask"];[remaining removeObjectForKey:@"mosaicRenderMasks"];
return [self renderColorSource:mosaic destination:dst uniforms:u paths:paths spider:spider tools:remaining colorManagement:state hostPrimaries:primaries error:error];
}
if(tools[@"sharedMasks"]){
if(!DYValidToolDocument(tools))return fail(error,@"调色层或蒙版数据无效。");
FxImageTile *stamped=[self sourceByApplyingStamps:DYSharedMasks(tools) source:src registry:dst.deviceRegistryID error:error];if(!stamped)return NO;
return [self renderColorSource:stamped destination:dst uniforms:u paths:paths spider:spider tools:DYResolvedToolDocument(tools) colorManagement:state hostPrimaries:primaries error:error];
}
if(!state.count)return [self renderSource:src destination:dst uniforms:u paths:paths spider:spider tools:tools error:error];
if(!DYManagedColorValid(state,error))return NO;if(!tools)tools=@{@"schema":@2,@"layers":@[],@"baseMasks":@{}};if(!DYValidToolDocument(tools))return fail(error,@"调色层或蒙版数据无效。");
if(tools[@"sharedMasks"])tools=DYResolvedToolDocument(tools);
if(DYUnifiedColorState(state))return [self renderUnifiedSource:src destination:dst uniforms:u paths:paths spider:spider tools:tools hostPrimaries:primaries error:error];
if(DYPrimaryColorState(state))return [self renderPrimarySource:src destination:dst uniforms:u paths:paths spider:spider tools:tools hostPrimaries:primaries error:error];
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,@"色彩管理输入纹理不可用。");
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,@"当前画面超过色彩管理内存预算。");
DYManagedBatch batch{entry[@"queue"],error};
CGColorSpaceRef srcSpace=_renderSourceSpace,dstSpace=_renderDestinationSpace,aces=CGColorSpaceCreateWithName(kCGColorSpaceACESCGLinear),linear709=CGColorSpaceCreateWithName(kCGColorSpaceExtendedLinearSRGB);
NSMutableArray*pool=[NSMutableArray array];id<MTLTexture>current=nil;
auto next=[&](id<MTLTexture>exclude=nil)->id<MTLTexture>{for(id<MTLTexture>t in pool)if(t!=current&&t!=exclude)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 copy=[&](id<MTLTexture>input,id<MTLTexture>output){return input&&output&&[self encodeManagedDispatch:@"dyManagedCopy" textures:@[input,output] data:nullptr length:0 extra:nullptr extraLength:0 entry:entry commands:batch.commands() error:error];};
auto convert=[&](dycm::Space a,dycm::Space b,NSInteger display=0,BOOL gamut=NO){id<MTLTexture>out=next();if(!out)return fail(error,@"无法分配色彩管理缓冲区。");BOOL ok=[self managedConvert:a to:b display:display gamut:gamut input:current output:out entry:entry commands:batch.commands() error:error];if(ok)current=out;return ok;};
auto profile=[&](DYColorProfile*p){if(!p)return NO;if(p.identity)return YES;if(!batch.finish())return NO;id<MTLTexture>out=next();if(!out)return fail(error,@"无法分配颜色配置缓冲区。");BOOL ok=[self managedProfile:p input:current output:out entry:entry error:error];if(ok)current=out;return ok;};
auto tile=[&](id<MTLTexture>texture){DYExportTile*t=[[[DYExportTile alloc]initWithTexture:texture registry:d.registryID]autorelease];[t setBounds:src.tilePixelBounds origin:src.imageOrigin];[t setPixelAspect:src.pixelAspect];return t;};
auto blend=[&](id<MTLTexture>before,NSArray*masks,NSString*type){if(!masks.count)return YES;id<MTLTexture>out=next(before);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];id<MTLComputePipelineState>p=[self computePipeline:@"dyManagedBlend" entry:entry error:error];if(!mb||!p)return NO;id<MTLComputeCommandEncoder>ce=[batch.commands() computeCommandEncoder];if(!ce)return fail(error,@"无法创建蒙版编码器");[ce setComputePipelineState:p];[ce setTexture:before atIndex:0];[ce setTexture:current atIndex:1];[ce setTexture:out atIndex:2];[ce setBuffer:mb offset:0 atIndex:0];[ce setBytes:&h length:sizeof(h) atIndex:1];[ce dispatchThreads:MTLSizeMake(source.width,source.height,1) threadsPerThreadgroup:MTLSizeMake(16,16,1)];[ce endEncoding];current=out;return YES;};
auto basis=[&](DYUniforms values,NSArray*masks){values.cm.inputTransfer=values.cm.workingTransfer=values.cm.outputTransfer=1;values.cm.inputGamut=values.cm.workingGamut=values.cm.outputGamut=2;values.cm.toneMapping=0;values.inputSectionEnabled=values.cm.outputEnabled=0;if(values.primarySectionEnabled<.5||values.cm.basisEnabled<.5||identityCM(values)||values.cm.mix<=0)return YES;id<MTLTexture>before=current,out=next();BasisParams p=DYCMRender(values.cm).basis;float amount=values.cm.mix;if(!out||![self encodeManagedDispatch:@"dyManagedBasis" textures:@[current,out] data:&p length:sizeof(p) extra:&amount extraLength:4 entry:entry commands:batch.commands() error:error])return NO;current=out;return blend(before,masks,@"primary");};
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,out=next();float amount=values.filmPrint.y*values.film.mix;if(!out||![self encodeManagedDispatch:@"dyManagedPrint" textures:@[current,cube,out] data:&amount length:4 extra:nullptr extraLength:0 entry:entry commands:batch.commands() error:error])return NO;current=out;return blend(before,masks,@"film");};
@try{try{
if(!dstSpace||(!srcSpace&&[state[@"mode"]integerValue]==1))return fail(error,@"宿主未提供明确颜色空间,无法使用新版管理。可切回旧版兼容。");
id<MTLTexture>first=next();if(!copy(source,first))return NO;current=first;
NSInteger mode=[state[@"mode"]integerValue],output=[state[@"output"]integerValue];
if(mode==1){DYColorProfile*p=[[[DYColorProfile alloc]initWithSource:srcSpace target:aces error:error]autorelease];if(!profile(p)||!convert(dycm::Space::ACEScg,dycm::Space::ACEScct))return NO;}
else {id<MTLTexture>out=next(),cube=entry[@"identity"];uint32_t useLUT=mode==3;if(useLUT){if(![paths[@"input"]length])return fail(error,@"请选择输入 LUT,并指定 LUT 输出空间。");cube=[self lut:paths[@"input"] entry:entry error:error];if(!cube)return NO;}if(!out||![self encodeManagedDispatch:@"dyManagedCarrier" textures:@[current,out,cube] data:&useLUT length:4 extra:nullptr extraLength:0 entry:entry commands:batch.commands() error:error])return NO;current=out;if(!convert(dycm::Space([state[@"input"]unsignedIntValue]),dycm::Space::ACEScct))return NO;}
DYApplyRemovedBaseTools(&u,tools);if(!basis(u,tools[@"baseMasks"][@"primary"]))return NO;
NSMutableDictionary*finishing=DYMutablePlist(tools);NSMutableSet*sceneLayers=[NSMutableSet set];
for(NSString*ID in DYToolDisplayOrder(tools)){NSDictionary*node=DYToolWithID(tools,ID);if([node[@"type"]isEqual:@"primary"]){if(!basis(DYToolUniforms(node),node[@"masks"]))return NO;[sceneLayers addObject:ID];}}
if(!print(u,tools[@"baseMasks"][@"film"]))return NO;for(NSString*ID in DYToolDisplayOrder(tools)){NSDictionary*node=DYToolWithID(tools,ID);if([node[@"type"]isEqual:@"film"]&&!print(DYToolUniforms(node),node[@"masks"]))return NO;}
for(NSString*ID in sceneLayers)DYRemoveTool(finishing,ID);for(NSMutableDictionary*node in finishing[@"layers"])if([node[@"type"]isEqual:@"film"])node[@"values"][@"filmPrintLook"]=@0;
u.primarySectionEnabled=0;u.cm.configured=-1;u.inputProfile=u.preLUTStrength=0;u.filmPrint.x=0;
if(mode==1){if(!convert(dycm::Space::ACEScct,dycm::Space::Linear709))return NO;}
else {if(!convert(dycm::Space::ACEScct,dycm::Space::ACEScct,output,[state[@"gamutCompression"]boolValue]))return NO;DYColorProfile*p=[[[DYColorProfile alloc]initWithDisplayOutput:dycm::Output(output) target:linear709 error:error]autorelease];if(!profile(p))return NO;}
// Bounded display tools are an explicit SDR finishing branch. HDR delivery
// uses the float32 primary / print / single-ODT core until these tools have
// measured HDR implementations; never silently clip them through old LUTs.
NSDictionary *finishPaths=DYVisibleBaseToolPaths(paths,finishing);
NSArray *activeFinish=DYManagedActiveFinishing(u,finishPaths,spider,finishing);
if(((mode!=1&&(output==6||output==7))||(mode==1&&primaries==kFxColorPrimaries_Rec2020))&&activeFinish.count)return fail(error,@"HDR 输出或跟随 Rec.2020 宿主时,目前支持一级调色与印片。请关闭 SDR 修饰工具;需要这些工具时,请明确选择 SDR 输出。");
auto preview=[self encodeManagedPreview:current source:src entry:entry commands:batch.commands()];
if(activeFinish.count){
if(!batch.finish())return NO;
[self publishManagedPreview:preview];preview={};
id<MTLTexture>out=next();if(!out)return fail(error,@"无法分配显示域修饰缓冲区。");_managedFinishing=YES;BOOL ok=NO;@try{ok=[self renderSource:tile(current) destination:tile(out) uniforms:u paths:finishPaths spider:spider tools:finishing error:error];}@finally{_managedFinishing=NO;}if(!ok)return NO;current=out;
}
if(!profile([self managedOutputProfile:error]))return NO;
_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;}
}catch(const std::exception&e){return fail(error,@(e.what()));}}@finally{if(aces)CGColorSpaceRelease(aces);if(linear709)CGColorSpaceRelease(linear709);}
});}}
- (BOOL)exportLUT:(NSURL*)url uniforms:(DYUniforms)u paths:(NSDictionary*)paths spider:(NSData*)spider tools:(NSDictionary*)tools colorManagement:(NSDictionary*)state error:(NSError**)error {@synchronized(self){if(state&&![state isKindOfClass:NSDictionary.class])return fail(error,@"色彩管理状态无效。");if(state.count&&!DYManagedColorValid(state,error))return NO;if(state.count&&[state[@"mode"]integerValue]!=1&&[@[@6,@7]containsObject:state[@"output"]])return fail(error,@"PQ/HLG 交付需要明确的亮度与范围,请保存完整预设;当前静态 Cube 输出为 sRGB。");if(state.count){auto spatial=[](DYUniforms v){return v.baseSectionEnabled>.5&&((v.textureEnabled>.5&&v.texture!=0)||(v.clarityEnabled>.5&&v.clarity!=0)||(v.dehazeEnabled>.5&&v.dehaze!=0));};BOOL unsupported=spatial(u);for(NSDictionary *node in tools[@"layers"])unsupported|=spatial(DYToolUniforms(node));if(unsupported)return fail(error,@"纹理、清晰度或去朦胧依赖画面内容,不能完整保存到 Cube;请保存完整预设。");}_exportManagedState=state.count?state:nil;@try{return [self exportLUT:url uniforms:u paths:paths spider:spider tools:tools error:error];}@finally{_exportManagedState=nil;}}}