- (void)managedPreview:(id)texture origin:(FxImageOrigin)origin entry:(NSMutableDictionary*)entry { @synchronized(_previewLock){if(_exporting||CACurrentMediaTime()-_lastPreview<=.5)return;} idp=[self managedKernel:@"dyManagedPreview" entry:entry error:nil];if(!p)return; idb=[entry[@"device"]newBufferWithLength:320*180*16 options:MTLResourceStorageModeShared];if(!b)return; idcb=[entry[@"queue"]commandBuffer];idce=[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];[_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)managedKernel:(NSString*)name entry:(NSMutableDictionary*)entry error:(NSError**)error { NSMutableDictionary *cache=entry[@"managedKernels"];if(!cache){cache=[NSMutableDictionary dictionary];entry[@"managedKernels"]=cache;} idpipeline=cache[name];if(!pipeline){idf=[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 { idpipeline=[self managedKernel:name entry:entry error:error];if(!pipeline)return NO; idcb=[entry[@"queue"]commandBuffer];idce=[cb computeCommandEncoder];[ce setComputePipelineState:pipeline];for(NSUInteger i=0;it=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)input output:(id)output entry:(NSMutableDictionary*)entry error:(NSError**)error { static std::mutex guard;static std::mapplans; 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_guardlock(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;idcb=[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)input output:(id)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 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}); } 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; } NSDictionary *entry=[self device:registry error:error];if(!entry)return nil; iddevice=entry[@"device"]; idinput=[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; idoutput=[[device newTextureWithDescriptor:desc]autorelease]; idcommands=[entry[@"queue"]commandBuffer]; idencoder=[commands computeCommandEncoder]; if(!output||!encoder){fail(error,@"无法分配仿制图章缓冲区。");return nil;} uint32_t count=(uint32_t)stamps.size(),flip=source.imageOrigin==kFxImageOrigin_BOTTOM_LEFT; [encoder setComputePipelineState:entry[@"dyCloneStamps"]]; [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 {@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(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 renderSource: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(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;idd=entry[@"device"];idsource=[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];idcurrent=nil; auto next=[&](idexclude=nil)->id{for(idt 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;idt=[d newTextureWithDescriptor:td];if(t){[pool addObject:t];[t release];}return t;}; auto copy=[&](idinput,idoutput){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){idout=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){idout=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=[&](idtexture){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=[&](idbefore,NSArray*masks,NSString*type){if(!masks.count)return YES;idout=next(before);if(!out)return fail(error,@"无法分配工作空间蒙版缓冲区。");DYToolMaskHeader h{};idmb=[self maskBuffer:@{type:masks} tile:src device:d header:&h];h.section=(int)[DYToolTypes()indexOfObject:type];idp=[self managedKernel:@"dyManagedBlend" entry:entry error:error];if(!mb||!p)return NO;idcb=[entry[@"queue"]commandBuffer];idce=[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;idbefore=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"];idcube=path?[self lut:path entry:entry error:error]:nil;if(!cube)return fail(error,@"印片资源不可用。");idbefore=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,@"宿主未提供明确颜色空间,无法使用新版管理。可切回旧版兼容。"); idfirst=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 {idout=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){idout=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;}}}