#import "DYManagedColor.h" #import "../../ColorManagement/Sources/DYColorManagementGPU.h" #import "../../ColorManagement/Sources/DYColorProfile.h" #include #include #import "DYRenderer.h" #import "../Shared/DYBetaDiagnostics.h" #import "DYModel.h" #include "DYSpiderState.h" #include "DYToolGPU.h" #include "DYFilmMath.h" #import #import #import "DYColorTables.h" #import "DYLUTLibrary.h" #import #include #include #include static BOOL fail(NSError**e,NSString*m){if(e)*e=[NSError errorWithDomain:@"com.dayu.color" code:1 userInfo:@{NSLocalizedDescriptionKey:m?:@"Metal 调色失败"}];return NO;} // MRC NSError out-parameters must outlive every nested render pool. Preserve // the same pointer across nested closures, then autorelease in the caller pool. template static BOOL DYRenderWithPool(NSError **error,F body){ if(error)*error=nil;NSError *held=nil;BOOL ok=NO; @autoreleasepool{@try{ok=body();}@catch(NSException *exception){ok=fail(error,exception.reason?:@"渲染异常");}if(!ok&&error)held=[*error retain];} if(error)*error=[held autorelease];return ok; } static NSArray *inputFiles(){return @[@"",@"apple_log_to_rec709",@"arri_logc3_to_rec709",@"arri_logc4_to_rec709",@"blackmagic_film_gen5_to_rec709",@"canon_clog_bt709_to_rec709",@"canon_clog2_cinema_gamut_to_rec709",@"canon_clog3_cinema_gamut_to_rec709",@"dji_dlog_to_rec709",@"dji_dlog_m_to_rec709",@"fujifilm_flog_to_rec709",@"fujifilm_flog2_to_rec709",@"nikon_nlog_to_rec709",@"panasonic_vlog_vgamut_to_rec709",@"red_log3g10_rwg_to_rec709",@"sony_slog2_sgamut_to_rec709",@"sony_slog3_sgamut3cine_to_rec709",@"sony_hlg_bt2020_to_rec709"];} static id texture3D(idd,const float*values,NSUInteger n){MTLTextureDescriptor*t=[MTLTextureDescriptor new];t.textureType=MTLTextureType3D;t.pixelFormat=MTLPixelFormatRGBA32Float;t.width=n;t.height=n;t.depth=n;t.storageMode=MTLStorageModeShared;t.usage=MTLTextureUsageShaderRead;idx=[d newTextureWithDescriptor:t];[t release];if(x)[x replaceRegion:MTLRegionMake3D(0,0,0,n,n,n) mipmapLevel:0 slice:0 withBytes:values bytesPerRow:n*16 bytesPerImage:n*n*16];return [x autorelease];} // A synthetic texture lattice uses exactly the production render path for Cube export. @interface DYExportTile : FxImageTile { id _tex; uint64_t _registry; FxRect _bounds;FxImageOrigin _origin; double _pixelAspect; } - (instancetype)initWithTexture:(id)texture registry:(uint64_t)registry; - (void)setBounds:(FxRect)bounds origin:(FxImageOrigin)origin; - (void)setPixelAspect:(double)aspect; @end @implementation DYExportTile - (instancetype)initWithTexture:(id)texture registry:(uint64_t)registry{if((self=[super init])){_tex=[texture retain];_registry=registry;_bounds=(FxRect){0,0,(SInt32)texture.width,(SInt32)texture.height};_origin=kFxImageOrigin_TOP_LEFT;_pixelAspect=1;}return self;} - (void)dealloc{[_tex release];[super dealloc];} - (id)metalTextureForDevice:(id)d{return d.registryID==_registry?_tex:nil;} - (void)setBounds:(FxRect)bounds origin:(FxImageOrigin)origin{_bounds=bounds;_origin=origin;} - (CGColorSpaceRef)colorSpace{static CGColorSpaceRef s;static dispatch_once_t once;dispatch_once(&once,^{s=CGColorSpaceCreateWithName(kCGColorSpaceExtendedLinearSRGB);});return s;} - (FxRect)tilePixelBounds{return _bounds;} - (FxRect)imagePixelBounds{return self.tilePixelBounds;} - (uint64_t)deviceRegistryID{return _registry;} - (FxImageOrigin)imageOrigin{return _origin;} - (double)pixelAspect{return _pixelAspect;} - (void)setPixelAspect:(double)aspect{_pixelAspect=aspect>0?aspect:1;} @end static BOOL managed(DYUniforms u,NSDictionary *paths){return u.cm.configured>=0&&(u.cm.configured>.5||(![paths[@"input"]length]&&u.inputProfile<.5));} static BOOL identityCM(DYUniforms u){ DYCMSettings s=u.cm; BOOL neutral=s.basisEnabled<.5||(s.exposure==0&&s.balanceStrength==0&&s.saturation==1&&s.contrast==0&&s.hiContrast==0&&s.shadowContrast==0&&s.white==1&&s.highlights==0&&s.midtones==0&&s.shadows==0&&s.black==0&&s.toe==.5f&&s.shoulder==.5f&&s.chromaMix==.5f); BOOL transforms=(u.inputSectionEnabled>.5)==(s.outputEnabled>.5)&&((u.inputSectionEnabled<.5)||(s.inputTransfer==s.outputTransfer&&s.inputGamut==s.outputGamut&&s.toneMapping<.5)); return neutral&&transforms; } // An enabled but untouched display tool is mathematically neutral. Bypass its // finite-domain lookup so that the default "all eyes on" does not clip CST HDR. static void bypassNeutralTools(DYUniforms *u){ for(NSDictionary *section in DYSections()){ if(![@[@"curve",@"hsl",@"grading",@"primaries",@"levels",@"balance"]containsObject:section[@"key"]])continue; BOOL neutral=YES;for(NSDictionary *row in section[@"rows"]){NSInteger offset=[row[@"offset"]integerValue];if(offset<0)continue;if(*(float*)((uint8_t*)u+offset)!=[row[@"default"]floatValue]){neutral=NO;break;}} if(neutral)for(NSDictionary *row in DYDescriptors())if([row[@"pid"]isEqual:section[@"enabled"]])*(float*)((uint8_t*)u+[row[@"offset"]unsignedIntegerValue])=0; } } static void bypassIdleSkin(DYUniforms *u){ if(u->curveSectionEnabled>.5||u->hslSectionEnabled>.5||u->colorGradingSectionEnabled>.5||u->primariesSectionEnabled>.5||u->levelsSectionEnabled>.5||u->blackWhiteSectionEnabled>.5||u->colorBalanceSectionEnabled>.5)return; if(u->preLUTStrength!=0||u->postLUTStrength!=0||simd_any(u->extraPostLUTStrengths!=0))return; const float *values=&u->exposure,*enabled=&u->exposureEnabled; for(int i=0;i<13;i++){BOOL group=(i>=6&&i<=9)?u->colorSectionEnabled>.5:u->baseSectionEnabled>.5;if(group&&enabled[i]>.5&&values[i]!=0)return;} u->skinProtection.x=0; } // Admission and identity bypass for the explicitly bounded finishing domain. static NSArray *DYManagedActiveFinishing(DYUniforms u,NSDictionary *paths,NSData *spider,NSDictionary *tools){ bypassNeutralTools(&u);bypassIdleSkin(&u);if(u.cm.blackWhiteMix<=0)u.blackWhiteSectionEnabled=0; NSMutableArray *active=[NSMutableArray array]; for(NSString *type in DYToolTypes()){ if([type isEqual:@"primary"])continue; NSMutableDictionary *values=[NSMutableDictionary dictionary],*localPaths=[NSMutableDictionary dictionary]; for(NSDictionary *d in DYBaseToolDescriptors(type))if([d[@"offset"]integerValue]>=0)values[d[@"key"]]=@(*(float*)((uint8_t*)&u+[d[@"offset"]unsignedIntegerValue])); if([type isEqual:@"look"]&&u.lookSectionEnabled>.5)for(NSString *key in paths)if([key hasPrefix:@"look"])localPaths[key]=paths[key]; NSMutableDictionary *node=[NSMutableDictionary dictionaryWithDictionary:@{@"type":type,@"values":values,@"paths":localPaths}];if([type isEqual:@"spider"]&&spider)node[@"spider"]=spider; if(!DYToolIsNeutral(node))[active addObject:type]; } for(NSDictionary *node in tools[@"layers"])if(!DYToolIsNeutral(node))[active addObject:node[@"type"]];return active; } @interface DYRenderer(){ NSMutableDictionary *_devices,*_luts,*_preparedLUTs; NSSet *_activeLUTPaths; dispatch_queue_t _lutPreparationQueue; DYColorTables *_tables; NSObject *_previewLock; NSData *_preview,*_lookLUTPreview; CFTimeInterval _lastPreview; BOOL _exporting; NSDictionary *_toolDocument,*_colorContext,*_exportManagedState; BOOL _managedFinishing; } @end @implementation DYRenderer #include "DYFilmRender.inc.h" #include "DYPrimaryRender.inc.h" #include "DYManagedRender.inc.h" #include "DYToolRender.inc.h" - (instancetype)init{if((self=[super init])){_previewLock=[NSObject new];_devices=[NSMutableDictionary new];_luts=[NSMutableDictionary new];_preparedLUTs=[NSMutableDictionary new];_activeLUTPaths=[NSSet new];_lutPreparationQueue=dispatch_queue_create("com.dayu.color.lut-upload",DISPATCH_QUEUE_SERIAL);dispatch_set_target_queue(_lutPreparationQueue,dispatch_get_global_queue(QOS_CLASS_USER_INITIATED,0));_tables=[DYColorTables new];}return self;} - (void)dealloc{[_devices release];[_luts release];[_preparedLUTs release];[_activeLUTPaths release];dispatch_release(_lutPreparationQueue);[_tables release];[_preview release];[_lookLUTPreview release];[_colorContext release];[_previewLock release];[super dealloc];} - (void)trimPreparedLUTsKeeping:(NSString *)path { if(_preparedLUTs.count<=12)return; for(NSString *key in _preparedLUTs.allKeys)if(![_activeLUTPaths containsObject:key]&&![key isEqualToString:path])[_preparedLUTs removeObjectForKey:key]; } - (id)textureForTable:(DYLUTPreparedTable *)table entry:(NSDictionary *)entry error:(NSError **)error { NSString *key=[NSString stringWithFormat:@"%llu|%@",[entry[@"device"]registryID],table.revision];idtexture=_luts[key]; if(!texture){texture=texture3D(entry[@"device"],table.rgbaValues,table.dimension);if(!texture){fail(error,@"LUT 纹理分配失败");return nil;}if(_luts.count>=12)[_luts removeAllObjects];_luts[key]=texture;}return texture; } - (NSProgress *)prepareLUTPath:(NSString *)path completion:(void (^)(NSError *))completion { NSProgress *progress=[NSProgress discreteProgressWithTotalUnitCount:2];progress.localizedDescription=@"正在载入 LUT…";path=[[path copy]autorelease]; dispatch_async(_lutPreparationQueue,^{@autoreleasepool{ NSError *error=nil;DYLUTPreparedTable *table=progress.cancelled?nil:DYLUTReadPreparedTable(path,progress,&error);progress.completedUnitCount=1; if(table&&!progress.cancelled){@synchronized(self){ if(!_devices.count)[self device:0 error:&error]; if(!_devices.count&&!error)fail(&error,@"没有可用的 LUT 渲染设备"); BOOL ready=error==nil;for(NSDictionary *entry in _devices.allValues)if(!progress.cancelled&&![self textureForTable:table entry:entry error:&error]){ready=NO;break;} if(ready&&!progress.cancelled){_preparedLUTs[path]=table;[self trimPreparedLUTsKeeping:path];} }} if(progress.cancelled)error=[NSError errorWithDomain:NSCocoaErrorDomain code:NSUserCancelledError userInfo:@{NSLocalizedDescriptionKey:@"已取消 LUT 加载"}]; progress.completedUnitCount=2;dispatch_async(dispatch_get_main_queue(),^{NSError *result=progress.cancelled?[NSError errorWithDomain:NSCocoaErrorDomain code:NSUserCancelledError userInfo:nil]:error;if(completion)completion(result);}); }});return progress; } - (void)invalidatePreview{@synchronized(_previewLock){[_preview release];_preview=nil;[_lookLUTPreview release];_lookLUTPreview=nil;_lastPreview=0;}} - (NSData*)preview{@synchronized(_previewLock){return [[_preview retain]autorelease];}} - (NSData*)lookLUTPreview{@synchronized(_previewLock){return [[_lookLUTPreview retain]autorelease];}} - (NSMutableDictionary*)device:(uint64_t)registry error:(NSError**)err{ NSNumber*k=@(registry);NSMutableDictionary*entry=_devices[k];if(entry)return entry; uint64_t beta=DYBetaSpanBegin(@"device_prepare",nil);@try{ idd=nil;NSArray*all=MTLCopyAllDevices();for(idcandidate in all)if(candidate.registryID==registry||!registry){d=[candidate retain];break;}[all release];if(!d){fail(err,@"宿主的 Metal 设备不可用");return nil;} NSURL*url=[[NSBundle bundleForClass:self.class]URLForResource:@"default" withExtension:@"metallib"]; idlib=[d newLibraryWithURL:url error:err];if(!lib){[d release];return nil;} idq=[d newCommandQueue];entry=[NSMutableDictionary dictionaryWithDictionary:@{@"device":d,@"library":lib,@"queue":q,@"pipelines":[NSMutableDictionary dictionary]}]; for(NSString*fn in @[@"dyUnpremultiply",@"dyWhitesSceneStatistics",@"dyLUTExportKernel",@"dyInputAnalysis",@"dyColorManagement",@"dyToolBlend",@"dyToolSkin",@"dyFilmPoint",@"dyFilmNoise",@"dyFilmSparseBlur",@"dyFilmBloomEdges",@"dyFilmMix",@"dyFilmPrint"]){idf=[lib newFunctionWithName:fn];if(!f){fail(err,[fn stringByAppendingString:@" 缺失"]);[lib release];[q release];[d release];return nil;}uint64_t pipelineSpan=DYBetaSpanBegin(@"gpu_pipeline",@{@"pipeline":fn,@"gpu":d.name?:@"unknown"});idp=[d newComputePipelineStateWithFunction:f error:err];DYBetaSpanEnd(pipelineSpan,@{@"status":p?@"passed":@"failed"});[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;}idneutral=texture3D(d,identity,2);if(!neutral){fail(err,@"无法分配中性 LUT");return nil;}entry[@"identity"]=neutral; // Preparing before the first frame may use registry 0. Reuse those pipelines // when the host subsequently supplies that device's actual registry ID. _devices[k]=entry;_devices[@(d.registryID)]=entry;[d release];[lib release];[q release];return entry; }@finally{DYBetaSpanEnd(beta,nil);} } - (id)lut:(NSString*)path entry:(NSDictionary*)e error:(NSError**)err{ if(!path.length)return e[@"identity"]; DYLUTPreparedTable *table=_preparedLUTs[path]; // Restored projects load once on their render worker. Explicit selections // arrive prepared, so neither metadata I/O nor text parsing occurs here. if(!table){table=DYLUTReadPreparedTable(path,nil,err);if(!table)return nil;_preparedLUTs[path]=table;[self trimPreparedLUTsKeeping:path];} return [self textureForTable:table entry:e error:err]; } - (NSArray*)textures:(NSDictionary*)paths uniforms:(DYUniforms*)u entry:(NSDictionary*)e error:(NSError**)err{ // Normalize only this render copy. Disabled groups retain their host parameters // and paths, while inactive LUTs neither load files nor affect any layer. BOOL inputEnabled=u->inputSectionEnabled>.5&&!managed(*u,paths); NSString*input=inputEnabled?paths[@"input"]:nil;int profile=inputEnabled?(int)roundf(u->inputProfile):0; if(!inputEnabled){u->inputProfile=0;u->preLUTStrength=0;} if(!input.length&&profile>0&&profile<(int)inputFiles().count)input=[[NSBundle bundleForClass:self.class]pathForResource:inputFiles()[profile] ofType:@"dylut" inDirectory:@"InputLUTs"]; if(profile>0&&!input.length){fail(err,@"相机输入转换资源缺失");return nil;} NSMutableArray*ts=[NSMutableArray array];idt=[self lut:input entry:e error:err];if(!t)return nil;[ts addObject:t];if(!input.length)u->preLUTStrength=0; BOOL looksEnabled=u->lookSectionEnabled>.5; if(!looksEnabled)u->extraLookSectionEnableds=(DYFloat4){0,0,0,0}; for(int i=0;i<5;i++){BOOL active=looksEnabled&&(i==0||u->extraLookSectionEnableds[i-1]>.5);NSString*p=active?paths[[NSString stringWithFormat:@"look%d",i]]:nil;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];idd=e[@"device"]; idh=[_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{return [self renderSource:src destination:dst uniforms:u paths:paths spider:nil error:err];} - (BOOL)renderSource:(FxImageTile*)src destination:(FxImageTile*)dst uniforms:(DYUniforms)u paths:(NSDictionary*)paths spider:(NSData *)spider error:(NSError**)err{return [self renderSource:src destination:dst uniforms:u paths:paths spider:spider tools:nil error:err];} - (BOOL)renderLegacy:(FxImageTile*)src destination:(FxImageTile*)dst uniforms:(DYUniforms)u paths:(NSDictionary*)paths spider:(NSData *)spider masks:(NSDictionary*)masks error:(NSError**)err{return [self renderLegacy:src destination:dst uniforms:u paths:paths spider:spider masks:masks stageFirst:-1 stageLast:-1 skinReference:nil originalReference:nil captureOriginal:nullptr suppressBlackWhite:NO error:err];} - (BOOL)renderLegacy:(FxImageTile*)src destination:(FxImageTile*)dst uniforms:(DYUniforms)u paths:(NSDictionary*)paths spider:(NSData *)spider masks:(NSDictionary*)masks stageFirst:(NSInteger)stageFirst stageLast:(NSInteger)stageLast skinReference:(FxImageTile*)skinReference originalReference:(FxImageTile*)originalReference captureOriginal:(DYExportTile**)captureOriginal suppressBlackWhite:(BOOL)suppressBlackWhite error:(NSError**)err{@synchronized(self){return DYRenderWithPool(err,[&]()->BOOL{ BOOL segmented=stageFirst>=0;if(segmented&&(stageFirst>stageLast||stageLast>11))return fail(err,@"原生工具分段范围无效"); if(spider.length&&!DYSpiderMeshIsValid(spider))return fail(err,@"蜘蛛盘数据无效"); if(u.primarySectionEnabled<.5){u.inputSectionEnabled=0;u.cm.basisEnabled=0;u.cm.outputEnabled=0;} [_activeLUTPaths release];_activeLUTPaths=[[NSSet alloc]initWithArray:paths.allValues?:@[]]; NSMutableDictionary*e=[self device:dst.deviceRegistryID error:err];if(!e)return NO;idd=e[@"device"];idinput=[src metalTextureForDevice:d],output=[dst metalTextureForDevice:d];if(!input||!output)return fail(err,@"宿主图像纹理不可用"); BOOL useCM=managed(u,paths)&&(!segmented||stageFirst==0);bypassNeutralTools(&u);float bwMix=fmaxf(0,fminf(1,u.cm.blackWhiteMix));if(bwMix<=0)u.blackWhiteSectionEnabled=0; NSArray*ts=[self textures:paths uniforms:&u entry:e error:err];if(!ts)return NO;bypassIdleSkin(&u); // Only a deformed active mesh allocates samples; device entries retain the // current buffer across frames. Neutral grids are exact identity at all densities. simd_int2 spiderSize={0,0};idspiderBuffer=nil; if(u.spiderSectionEnabled>.5&&u.spiderMix>0&&spider.length){ if(![e[@"spiderData"]isEqual:spider]){auto mesh=DYSpiderMesh(spider);auto samples=dy::meshSamples(mesh);BOOL changed=NO;for(float value:samples)changed|=value!=0; e[@"spiderData"]=spider;e[@"spiderActive"]=@(changed);if(changed){idb=[d newBufferWithBytes:samples.data() length:samples.size()*sizeof(float) options:MTLResourceStorageModeShared];if(!b)return fail(err,@"无法分配蜘蛛盘缓冲区");e[@"spiderBuffer"]=b;[b release];e[@"spiderHues"]=@(mesh.hues);e[@"spiderRings"]=@(mesh.rings);}else[e removeObjectForKey:@"spiderBuffer"]; } if([e[@"spiderActive"]boolValue]){spiderBuffer=e[@"spiderBuffer"];spiderSize={ [e[@"spiderHues"]intValue],[e[@"spiderRings"]intValue]};} } DYToolMaskHeader maskHeader{};idmaskBuffer=(masks.count||segmented)?[self maskBuffer:masks tile:src device:d header:&maskHeader]:nil;BOOL hasMasks=maskHeader.count>0;if((hasMasks||segmented)&&!maskBuffer)return fail(err,@"无法分配蒙版缓冲区"); NSMutableDictionary*ps=e[@"pipelines"];NSString*format=[NSString stringWithFormat:@"%lu-%d-%d",(unsigned long)output.pixelFormat,hasMasks,segmented];idpipeline=ps[format];if(!pipeline){MTLRenderPipelineDescriptor*p=[MTLRenderPipelineDescriptor new];p.vertexFunction=[e[@"library"]newFunctionWithName:@"dyVertex"];p.fragmentFunction=[e[@"library"]newFunctionWithName:segmented?@"dySegmentFragment":hasMasks?@"dyMaskedFragment":@"dyFragment"];p.colorAttachments[0].pixelFormat=output.pixelFormat;pipeline=[d newRenderPipelineStateWithDescriptor:p error:err];[p.vertexFunction release];[p.fragmentFunction release];[p release];if(!pipeline)return NO;ps[format]=pipeline;[pipeline release];} MTLTextureDescriptor*td=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA16Float width:input.width height:input.height mipmapped:NO];td.storageMode=MTLStorageModePrivate;td.usage=MTLTextureUsageShaderRead|MTLTextureUsageShaderWrite;idstraight=[d newTextureWithDescriptor:td];if(!straight)return fail(err,@"无法分配调色缓冲区"); idcb=[e[@"queue"]commandBuffer];idce=[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]; if(useCM&&!identityCM(u)&&u.cm.mix>0){ DayuRenderParams cm=DYCMRender(u.cm);cm.stages=(cm.stages&~1)|(u.inputSectionEnabled>.5?1:0); if(cm.stages){idconverted=[d newTextureWithDescriptor:td];if(!converted){[straight release];return fail(err,@"无法分配 CST 缓冲区");} ce=[cb computeCommandEncoder];[ce setComputePipelineState:e[@"dyColorManagement"]];[ce setTexture:straight atIndex:0];[ce setTexture:converted atIndex:1];[ce setBytes:&cm length:sizeof(cm) atIndex:0];[ce setBytes:&u.cm.mix length:4 atIndex:1];[ce dispatchThreads:MTLSizeMake(input.width,input.height,1) threadsPerThreadgroup:MTLSizeMake(16,16,1)];[ce endEncoding];if(hasMasks){idblended=[d newTextureWithDescriptor:td];if(!blended){[converted release];[straight release];return fail(err,@"无法分配一级蒙版缓冲区");}maskHeader.section=0;maskHeader.premultiplied=0;[self encodeBlend:straight after:converted output:blended masks:maskBuffer header:maskHeader entry:e commands:cb];[converted release];converted=blended;}[straight release];straight=converted; } } // Keep the actual post-CST straight source alive across all native segments. // Both native spatial helpers and whites statistics historically read this // source; the current segment's center color is a different input. idnativeSource=segmented&&originalReference?[originalReference metalTextureForDevice:d]:straight; if(!nativeSource){[straight release];return fail(err,@"原生工具参考纹理不可用");} if(segmented&&captureOriginal&&!*captureOriginal){DYExportTile *reference=[[DYExportTile alloc]initWithTexture:nativeSource registry:d.registryID];[reference setBounds:src.tilePixelBounds origin:src.imageOrigin];[reference setPixelAspect:src.pixelAspect];*captureOriginal=reference;} float level=.5;idscene=[d newBufferWithBytes:&level length:4 options:MTLResourceStorageModeShared]; if(!_exporting&&(!segmented||(stageFirst<=2&&stageLast>=2))&&u.whites>0&&u.whitesEnabled>.5&&u.baseSectionEnabled>.5){ce=[cb computeCommandEncoder];[ce setComputePipelineState:e[@"dyWhitesSceneStatistics"]];[ce setTexture:nativeSource 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=NO;@synchronized(_previewLock){preview=(!segmented||stageFirst==0)&&!_exporting&&CACurrentMediaTime()-_lastPreview>.5;}idpb=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;idre=[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;id=e[@"device"];const NSUInteger n=_exportManagedState?65:33,count=n*n*n,width=n*n,height=n; MTLTextureDescriptor *desc=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:(_exportManagedState?MTLPixelFormatRGBA32Float:MTLPixelFormatRGBA16Float) width:width height:height mipmapped:NO];desc.storageMode=MTLStorageModeShared;desc.usage=MTLTextureUsageShaderRead|MTLTextureUsageShaderWrite|MTLTextureUsageRenderTarget; idinput=[d newTextureWithDescriptor:desc],output=[d newTextureWithDescriptor:desc];if(!input||!output){[input release];[output release];return fail(err,@"无法分配 LUT 色格");} std::vector<__fp16>values(count*4);std::vectorprecise(_exportManagedState?count*4:0);for(NSUInteger i=0;i