73 行
16 KiB
C++
73 行
16 KiB
C++
- (void)managedPreview:(id<MTLTexture>)texture origin:(FxImageOrigin)origin entry:(NSMutableDictionary*)entry {
|
|
@synchronized(_previewLock){if(_exporting||CACurrentMediaTime()-_lastPreview<=.5)return;}
|
|
id<MTLComputePipelineState>p=[self managedKernel:@"dyManagedPreview" entry:entry error:nil];if(!p)return;
|
|
id<MTLBuffer>b=[entry[@"device"]newBufferWithLength:320*180*16 options:MTLResourceStorageModeShared];if(!b)return;
|
|
id<MTLCommandBuffer>cb=[entry[@"queue"]commandBuffer];id<MTLComputeCommandEncoder>ce=[cb computeCommandEncoder];[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];[cb commit];[cb waitUntilCompleted];
|
|
if(cb.status==MTLCommandBufferStatusCompleted){@synchronized(_previewLock){[_preview release];_preview=[[NSData alloc]initWithBytes:b.contents length:b.length];[_histogram release];_histogram=[DYHistogramFromRGBA(_preview) retain];[_lookLUTPreview release];if(origin==kFxImageOrigin_BOTTOM_LEFT){NSMutableData *flipped=[NSMutableData dataWithLength:b.length];for(NSUInteger y=0;y<180;y++)memcpy((uint8_t*)flipped.mutableBytes+y*320*16,(uint8_t*)b.contents+(179-y)*320*16,320*16);_lookLUTPreview=[flipped copy];}else _lookLUTPreview=[_preview retain];_lastPreview=CACurrentMediaTime();}dispatch_async(dispatch_get_main_queue(),^{[NSNotificationCenter.defaultCenter postNotificationName:@"DYPreviewDidChange" object:self];});}[b release];
|
|
}
|
|
// Included in DYRenderer. V1 callers and their ABI remain on renderSource:...tools:error:.
|
|
- (NSDictionary*)colorContext {@synchronized(_previewLock){return [[_colorContext copy]autorelease];}}
|
|
- (id<MTLComputePipelineState>)managedKernel:(NSString*)name entry:(NSMutableDictionary*)entry error:(NSError**)error {
|
|
NSMutableDictionary *cache=entry[@"managedKernels"];if(!cache){cache=[NSMutableDictionary dictionary];entry[@"managedKernels"]=cache;}
|
|
id<MTLComputePipelineState>pipeline=cache[name];if(!pipeline){id<MTLFunction>f=[entry[@"library"]newFunctionWithName:name];if(!f){fail(error,[@"色彩管理内核缺失:" stringByAppendingString:name]);return nil;}pipeline=[entry[@"device"]newComputePipelineStateWithFunction:f error:error];[f release];if(!pipeline)return nil;cache[name]=pipeline;[pipeline release];}return pipeline;
|
|
}
|
|
- (BOOL)managedDispatch:(NSString*)name textures:(NSArray*)textures data:(const void*)data length:(NSUInteger)length extra:(const void*)extra extraLength:(NSUInteger)extraLength entry:(NSMutableDictionary*)entry error:(NSError**)error {
|
|
id<MTLComputePipelineState>pipeline=[self managedKernel:name entry:entry error:error];if(!pipeline)return NO;
|
|
id<MTLCommandBuffer>cb=[entry[@"queue"]commandBuffer];id<MTLComputeCommandEncoder>ce=[cb computeCommandEncoder];[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];[cb commit];[cb waitUntilCompleted];return cb.status==MTLCommandBufferStatusCompleted?YES:fail(error,cb.error.localizedDescription);
|
|
}
|
|
- (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 error:(NSError**)error {
|
|
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;id<MTLCommandBuffer>cb=[entry[@"queue"]commandBuffer];if(![p encodeInput:input output:output alpha:dycm::Alpha::Premultiplied commandBuffer:cb workspaceBudget:2ull*1024*1024*1024 error:error])return NO;[cb commit];[cb waitUntilCompleted];return cb.status==MTLCommandBufferStatusCompleted?YES:fail(error,cb.error.localizedDescription);
|
|
}
|
|
- (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];
|
|
}
|
|
- (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 {@synchronized(self){return DYRenderWithPool(error,[&]()->BOOL{
|
|
if(state&&![state isKindOfClass:NSDictionary.class])return fail(error,@"色彩管理状态无效。");
|
|
NSDictionary*context=DYHostColorContext(src,dst,primaries);@synchronized(_previewLock){[_colorContext release];_colorContext=[context copy];}
|
|
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(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,@"当前画面超过色彩管理内存预算。");
|
|
CGColorSpaceRef srcSpace=DYManagedTileSpace(src,primaries),dstSpace=DYManagedTileSpace(dst,primaries),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 managedDispatch:@"dyManagedCopy" textures:@[input,output] data:nullptr length:0 extra:nullptr extraLength:0 entry:entry 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 error:error];if(ok)current=out;return ok;};
|
|
auto profile=[&](DYColorProfile*p){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 managedKernel:@"dyManagedBlend" entry:entry error:error];if(!mb||!p)return NO;id<MTLCommandBuffer>cb=[entry[@"queue"]commandBuffer];id<MTLComputeCommandEncoder>ce=[cb computeCommandEncoder];[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];[cb commit];[cb waitUntilCompleted];if(cb.status!=MTLCommandBufferStatusCompleted)return fail(error,cb.error.localizedDescription);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 managedDispatch:@"dyManagedBasis" textures:@[current,out] data:&p length:sizeof(p) extra:&amount extraLength:4 entry:entry 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 managedDispatch:@"dyManagedPrint" textures:@[current,cube,out] data:&amount length:4 extra:nullptr extraLength:0 entry:entry 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 managedDispatch:@"dyManagedCarrier" textures:@[current,out,cube] data:&useLUT length:4 extra:nullptr extraLength:0 entry:entry 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 输出。");
|
|
[self managedPreview:current origin:src.imageOrigin entry:entry];
|
|
if(activeFinish.count){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;}
|
|
DYColorProfile*returnProfile=[[[DYColorProfile alloc]initWithSource:linear709 target:dstSpace error:error]autorelease];if(!profile(returnProfile))return NO;
|
|
_managedFinishing=YES;@try{return [self copyTile:tile(current) to:dst entry:entry error:error];}@finally{_managedFinishing=NO;}
|
|
}catch(const std::exception&e){return fail(error,@(e.what()));}}@finally{if(srcSpace)CGColorSpaceRelease(srcSpace);if(dstSpace)CGColorSpaceRelease(dstSpace);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;}}}
|