From 38e9fb25a21d7ba573f09093ea4ca45a79664cf5 Mon Sep 17 00:00:00 2001 From: mac Date: Mon, 9 Nov 2026 12:05:43 +0800 Subject: [PATCH] =?UTF-8?q?=E5=87=8F=E5=B0=91=E5=A4=9A=E5=B1=82=E8=B0=83?= =?UTF-8?q?=E8=89=B2=20GPU=20=E7=AD=89=E5=BE=85=E4=B8=8E=E6=A3=80=E6=9F=A5?= =?UTF-8?q?=E5=99=A8=E6=8B=96=E5=8A=A8=E5=86=99=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ColorManagement/PROVENANCE.json | 3 +- ColorManagement/Sources/DYColorProfile.mm | 35 +++++- 大鱼调色/Plugin/DYFaceRender.inc.h | 4 +- 大鱼调色/Plugin/DYGrade.metal | 42 +++++-- 大鱼调色/Plugin/DYInspector.mm | 111 ++++++++++++++++--- 大鱼调色/Plugin/DYManagedColor.h | 2 +- 大鱼调色/Plugin/DYManagedColor.mm | 2 +- 大鱼调色/Plugin/DYManagedRender.inc.h | 106 +++++++++++++----- 大鱼调色/Plugin/DYPrimaryKernels.inc.h | 21 +++- 大鱼调色/Plugin/DYPrimaryRender.inc.h | 52 +++++++-- 大鱼调色/Plugin/DYRenderer.mm | 43 ++++++- 大鱼调色/Plugin/DYToolGPU.h | 3 +- 大鱼调色/Plugin/DYToolRender.inc.h | 12 +- 大鱼调色/Plugin/DYUnifiedDiagnostics.inc.h | 22 ++++ 大鱼调色/Plugin/DYUnifiedRender.inc.h | 45 +++++--- 大鱼调色/Plugin/DYWorkspaceDiagnostics.inc.h | 8 +- 大鱼调色/Plugin/Info.plist | 4 +- 大鱼调色/Wrapper Application/Info.plist | 4 +- 开发交接.md | 6 + 19 files changed, 427 insertions(+), 98 deletions(-) diff --git a/ColorManagement/PROVENANCE.json b/ColorManagement/PROVENANCE.json index dd7baf5..4883cd6 100644 --- a/ColorManagement/PROVENANCE.json +++ b/ColorManagement/PROVENANCE.json @@ -42,6 +42,7 @@ "adaptations": [ "Dedicated com.dayu.color runtime cache", "Standalone RGBA/alpha header, excluding unrelated layer engine", - "No dependency on the sibling installed application" + "No dependency on the sibling installed application", + "Batch GPU profile prepare, Core Image and restore on the same command buffer for uncancelled render calls" ] } diff --git a/ColorManagement/Sources/DYColorProfile.mm b/ColorManagement/Sources/DYColorProfile.mm index f28add9..96a0340 100644 --- a/ColorManagement/Sources/DYColorProfile.mm +++ b/ColorManagement/Sources/DYColorProfile.mm @@ -123,9 +123,38 @@ CGColorSpaceRef DYCreateCMSOutputColorSpace(dycm::Output output){ admission(uint64_t(input.width)*input.height,bytes);auto desc=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA32Float width:input.width height:input.height mipmapped:NO];desc.storageMode=MTLStorageModePrivate;desc.usage=MTLTextureUsageShaderRead|MTLTextureUsageShaderWrite; auto opaque=[_device newTextureWithDescriptor:desc],converted=[_device newTextureWithDescriptor:desc];if(!opaque||!converted)throw std::runtime_error("无法分配颜色转换图像");uint64_t actual=input.allocatedSize+output.allocatedSize+opaque.allocatedSize+converted.allocatedSize; if(actual>bytes||2*uint64_t(input.width)*input.height*16>bytes-actual)throw std::runtime_error("颜色转换实际纹理及估算系统工作区超过预算"); - auto dispatch=[&](idpipeline,NSArray*textures){check(cancelled);auto command=[_queue commandBuffer];auto encoder=[command computeCommandEncoder];if(!encoder)throw std::runtime_error("无法建立颜色转换编码器");[encoder setComputePipelineState:pipeline];for(NSUInteger i=0;icommand,idpipeline,NSArray*textures){ + check(cancelled); + auto encoder=[command computeCommandEncoder];if(!encoder)throw std::runtime_error("无法建立颜色转换编码器"); + [encoder setComputePipelineState:pipeline]; + for(NSUInteger i=0;id=entry[@"device"];idbefore=[source metalTextureForDevice:d],output=[destination metalTextureForDevice:d]; id pipeline=[self computePipeline:@"dyLensRepair" entry:entry error:error];if(!pipeline)return NO; - idcb=[entry[@"queue"]commandBuffer];idce=[cb computeCommandEncoder];[ce setComputePipelineState:pipeline];[ce setTexture:before atIndex:0];[ce setTexture:output atIndex:1];[ce setBytes:&u length:sizeof(u) atIndex:0];float aspect=before.width*source.pixelAspect/MAX(1.,(double)before.height);[ce setBytes:&aspect length:sizeof(aspect) atIndex:1];[ce dispatchThreads:MTLSizeMake(output.width,output.height,1)threadsPerThreadgroup:MTLSizeMake(16,16,1)];[ce endEncoding];[cb commit];[cb waitUntilCompleted];if(cb.status!=MTLCommandBufferStatusCompleted)return fail(error,cb.error.localizedDescription); - if(!masks.count)return YES;MTLTextureDescriptor *desc=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:output.pixelFormat width:output.width height:output.height mipmapped:NO];desc.storageMode=MTLStorageModePrivate;desc.usage=MTLTextureUsageShaderRead|MTLTextureUsageShaderWrite|MTLTextureUsageRenderTarget;idblend=[d newTextureWithDescriptor:desc];if(!blend)return fail(error,@"无法分配修复蒙版");DYToolMaskHeader h{};h.section=(int)[DYToolTypes()indexOfObject:@"lens"];idbuffer=[self maskBuffer:@{@"lens":masks}tile:source device:d header:&h];cb=[entry[@"queue"]commandBuffer];if(![self encodeBlend:before after:output output:blend masks:buffer header:h entry:entry commands:cb error:error]){[blend release];return NO;}[cb commit];[cb waitUntilCompleted];DYExportTile *tile=[[DYExportTile alloc]initWithTexture:blend registry:d.registryID];[tile setBounds:destination.tilePixelBounds origin:destination.imageOrigin];[tile setPixelAspect:destination.pixelAspect];BOOL ok=cb.status==MTLCommandBufferStatusCompleted&&[self copyTile:tile to:destination entry:entry error:error];[tile release];[blend release];return ok; + idcb=[entry[@"queue"]commandBuffer];idce=[cb computeCommandEncoder];if(!ce||!before||!output)return fail(error,@"无法创建修复镜头编码器");[ce setComputePipelineState:pipeline];[ce setTexture:before atIndex:0];[ce setTexture:output atIndex:1];[ce setBytes:&u length:sizeof(u) atIndex:0];float aspect=before.width*source.pixelAspect/MAX(1.,(double)before.height);[ce setBytes:&aspect length:sizeof(aspect) atIndex:1];[ce dispatchThreads:MTLSizeMake(output.width,output.height,1)threadsPerThreadgroup:MTLSizeMake(16,16,1)];[ce endEncoding]; + if(!masks.count)return [self completeCommands:cb destination:destination texture:output entry:entry]?YES:fail(error,cb.error.localizedDescription);MTLTextureDescriptor *desc=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:output.pixelFormat width:output.width height:output.height mipmapped:NO];desc.storageMode=MTLStorageModePrivate;desc.usage=MTLTextureUsageShaderRead|MTLTextureUsageShaderWrite|MTLTextureUsageRenderTarget;idblend=[d newTextureWithDescriptor:desc];if(!blend)return fail(error,@"无法分配修复蒙版");DYToolMaskHeader h{};h.section=(int)[DYToolTypes()indexOfObject:@"lens"];idbuffer=[self maskBuffer:@{@"lens":masks}tile:source device:d header:&h];if(![self encodeBlend:before after:output output:blend masks:buffer header:h entry:entry commands:cb error:error]){[blend release];return NO;}DYExportTile *tile=[[DYExportTile alloc]initWithTexture:blend registry:d.registryID];[tile setBounds:destination.tilePixelBounds origin:destination.imageOrigin];[tile setPixelAspect:destination.pixelAspect];BOOL ok=[self copyTile:tile to:destination rotation:0 entry:entry commands:cb error:error];[tile release];[blend release];return ok; } diff --git a/大鱼调色/Plugin/DYGrade.metal b/大鱼调色/Plugin/DYGrade.metal index 46a5059..255a752 100644 --- a/大鱼调色/Plugin/DYGrade.metal +++ b/大鱼调色/Plugin/DYGrade.metal @@ -372,7 +372,13 @@ kernel void dyColorManagement(texture2d source [[texture(0)] // Premultiplication is preserved by mixing the two equally-alpha images. kernel void dyToolBlend(texture2d before [[texture(0)]],texture2d after [[texture(1)]],texture2d output [[texture(2)]],device const DYToolMaskEntry* masks [[buffer(0)]],constant DYToolMaskHeader& h [[buffer(1)]],uint2 pos [[thread_position_in_grid]]){ - if(pos.x>=output.get_width()||pos.y>=output.get_height())return;float4 a=before.read(pos),b=after.read(pos);float2 uv=(float2(pos)+.5f)/float2(output.get_width(),output.get_height());float amount=dyToolCoverage(uv,dyToolEncode(a.a>0?(h.premultiplied?a.rgb/a.a:a.rgb):float3(0)),masks,h,h.section);output.write(half4(h.skinPreview?float4(b.rgb*amount,a.a):mix(a,b,amount)),pos); + if(pos.x>=output.get_width()||pos.y>=output.get_height())return; + float4 a=before.read(pos),b=after.read(pos); + float2 uv=(float2(pos)+.5f)/float2(output.get_width(),output.get_height()); + float3 keyColor=float3(0); + if(h.keySources&&a.a>0)keyColor=dyToolEncode(h.premultiplied?a.rgb/a.a:a.rgb); + float amount=dyToolCoverage(uv,keyColor,masks,h,h.section); + output.write(half4(h.skinPreview?float4(b.rgb*amount,a.a):mix(a,b,amount)),pos); } extern "C" float dy_skinWeight(float3 color,float3 reference,constant DYUniforms& uniforms); extern "C" float3 dy_skinExtra(float3 color,float3 reference,constant DYUniforms& uniforms); @@ -495,12 +501,34 @@ kernel void dyUnifiedBridgeOut(texture2d raw [[texture(0)]], struct DYUnifiedMix {CSTParams toLinear,fromLinear,originalTo709;float amount;}; kernel void dyUnifiedBlend(texture2d before [[texture(0)]],texture2d after [[texture(1)]],texture2d output [[texture(2)]],texture2d original [[texture(3)]],device const DYToolMaskEntry* masks [[buffer(0)]],constant DYToolMaskHeader& h [[buffer(1)]],constant DYUnifiedMix& p [[buffer(2)]],uint2 xy [[thread_position_in_grid]]){ - if(any(xy>=uint2(output.get_width(),output.get_height())))return;float4 a=before.read(xy),b=after.read(xy),o=original.read(xy);if(!(a.a>0)||!(b.a>0)){output.write(a,xy);return;} - float3 ac=cst_float_air(float4(a.rgb/a.a,1),p.toLinear).rgb,bc=cst_float_air(float4(b.rgb/b.a,1),p.toLinear).rgb; - float3 code=dyToolEncode(cst_float_air(float4(ac,1),dyPrimaryAP1To709).rgb),source=o.a>0?dyToolEncode(cst_float_air(float4(o.rgb/o.a,1),p.originalTo709).rgb):float3(0); - float2 uv=(float2(xy)+.5f)/float2(output.get_width(),output.get_height());float x=h.offsetX+uv.x*h.scaleX,y=h.offsetY+uv.y*h.scaleY;float coverage=1;bool found=false; - for(uint i=0;i=1){output.write(b,xy);return;}output.write(float4(cst_float_air(float4(mix(ac,bc,w),1),p.fromLinear).rgb*a.a,a.a),xy); + if(any(xy>=uint2(output.get_width(),output.get_height())))return; + float4 a=before.read(xy),b=after.read(xy); + if(!(a.a>0)||!(b.a>0)){output.write(a,xy);return;} + float3 ac=0,code=0,source=0; + if(h.keySources&DYToolMaskLayerKey){ + ac=cst_float_air(float4(a.rgb/a.a,1),p.toLinear).rgb; + code=dyToolEncode(cst_float_air(float4(ac,1),dyPrimaryAP1To709).rgb); + } + if(h.keySources&DYToolMaskOriginalKey){ + float4 o=original.read(xy); + if(o.a>0)source=dyToolEncode(cst_float_air(float4(o.rgb/o.a,1),p.originalTo709).rgb); + } + float2 uv=(float2(xy)+.5f)/float2(output.get_width(),output.get_height()); + float x=h.offsetX+uv.x*h.scaleX,y=h.offsetY+uv.y*h.scaleY; + float coverage=1;bool found=false; + for(uint i=0;i=1){output.write(b,xy);return;} + if(!(h.keySources&DYToolMaskLayerKey))ac=cst_float_air(float4(a.rgb/a.a,1),p.toLinear).rgb; + float3 bc=cst_float_air(float4(b.rgb/b.a,1),p.toLinear).rgb; + output.write(float4(cst_float_air(float4(mix(ac,bc,w),1),p.fromLinear).rgb*a.a,a.a),xy); } kernel void dyUnifiedExposure(texture2d a [[texture(0)]],texture2d b [[texture(1)]],constant float& gain [[buffer(0)]],uint2 p [[thread_position_in_grid]]){ if(any(p>=uint2(b.get_width(),b.get_height())))return;float4 c=a.read(p);if(c.a>0)c.rgb*=gain;b.write(c,p); diff --git a/大鱼调色/Plugin/DYInspector.mm b/大鱼调色/Plugin/DYInspector.mm index f830155..5952342 100644 --- a/大鱼调色/Plugin/DYInspector.mm +++ b/大鱼调色/Plugin/DYInspector.mm @@ -434,19 +434,28 @@ static NSImage *DYWheelImage(void) { - (void)sendHue:(double)hue saturation:(double)sat { [self setHue:hue saturation:sat];[self.delegate writeGraphicValues:@{[NSString stringWithFormat:@"grade%ld_0",(long)_index]:@(hue),[NSString stringWithFormat:@"grade%ld_1",(long)_index]:@(sat)}]; } -- (void)mouseDown:(NSEvent *)event { +- (void)finishGesture { + if(!_dragging)return; _dragging=NO; + [self.delegate graphicGesture:NO title:nil]; +} +- (void)viewWillMoveToWindow:(NSWindow *)window { + if(!window)[self finishGesture]; + [super viewWillMoveToWindow:window]; +} +- (void)mouseDown:(NSEvent *)event { + [self finishGesture]; NSPoint p=[self convertPoint:event.locationInWindow fromView:nil];NSRect r=[self wheelRect]; if(hypot(p.x-NSMidX(r),p.y-NSMidY(r))>r.size.width*.5)return; if(event.clickCount==2){[self sendHue:0 saturation:0];return;} - _dragging=YES;[self updateAt:p]; + _dragging=YES;[self.delegate graphicGesture:YES title:@"调整颜色分级"];[self updateAt:p]; } - (void)updateAt:(NSPoint)p { NSRect r=[self wheelRect];double dx=p.x-NSMidX(r),dy=NSMidY(r)-p.y,h=atan2(dy,dx)*180/M_PI;if(h<0)h+=360; [self sendHue:h saturation:fmin(100,hypot(dx,dy)/(r.size.width*.5)*100)]; } - (void)mouseDragged:(NSEvent *)event {if(_dragging)[self updateAt:[self convertPoint:event.locationInWindow fromView:nil]];} -- (void)mouseUp:(NSEvent *)event {if(_dragging)[self updateAt:[self convertPoint:event.locationInWindow fromView:nil]];_dragging=NO;} +- (void)mouseUp:(NSEvent *)event {if(_dragging)[self updateAt:[self convertPoint:event.locationInWindow fromView:nil]];[self finishGesture];} @end @interface DYWheelPanel : DYFlippedView { @@ -495,7 +504,9 @@ NSView *DYCreateWorkspaceMaskEditor(id NSMutableDictionary *_tabs; NSInteger _visibleLooks; NSButton *_colorSettings;BOOL _colorSettingsExpanded; - BOOL _refreshing,_graphicUndoOpen,_graphicCancelled;CMTime _graphicTime;NSMutableDictionary *_graphicExpected; + BOOL _refreshing,_graphicUndoOpen,_graphicCancelled,_tearingDown; + CMTime _graphicTime; + NSMutableDictionary *_graphicExpected,*_graphicPending; BOOL _embedded,_workspaceEditor,_unified,_measuringDefaultHeight;NSArray *_renderOrder;NSMutableDictionary *_stackViews;NSArray *_stackOrder;NSDictionary *_stackRoots;CGFloat _stackHeight,_preferredHeight,_maximumViewportHeight; DYSpiderPanel *_spiderPanel; BOOL _spiderEditing,_spiderUndoOpen,_spiderConflict; @@ -599,15 +610,15 @@ NSView *DYCreateWorkspaceMaskEditor(id DYBetaSpanEnd(beta,nil);return self; } - (void)dealloc { - [self graphicGesture:NO title:nil];_spiderPanel.delegate=nil;[self spiderGesture:NO];[_workspace close];[_workspace release];[_workspaceButton release];[_workspaceSelectedNode release]; - for(id graphic in _graphics)if([graphic isKindOfClass:DYPrimaryBalanceWheel.class])[(DYPrimaryBalanceWheel*)graphic setDelegate:nil]; + _tearingDown=YES;[self graphicGesture:NO title:nil];_spiderPanel.delegate=nil;[self spiderGesture:NO];[_workspace close];[_workspace release];[_workspaceButton release];[_workspaceSelectedNode release]; + for(id graphic in _graphics)[graphic setDelegate:nil]; for(NSProgress *p in _assetLoads.allValues)[p cancel];[_assetLoads release];[_assetLoadIDs release];[_menuScan cancel];[_menuScan release];[_pendingAssetMenuCommand release]; [[NSNotificationCenter defaultCenter] removeObserver:self];[NSWorkspace.sharedWorkspace.notificationCenter removeObserver:self]; if(_embedded)[(id)_manager release];[_stackViews release];[_stackOrder release];[_stackRoots release];[_renderOrder release]; [_brand release]; [_subtitle release]; [_websiteLink release]; [_resetAll release]; [_save release]; [_load release]; [_export release];[_colorSettings release];[_addModule release]; [_mosaicButton release];[_managedPanel release];[_scroll release]; [_document release]; [_sections release]; [_cards release]; [_controls release]; [_assetButtons release]; [_graphics release]; [_sampler release]; [_recentBrowser close];[_recentBrowser release];[_recentHost release]; - [_browser close];[_browser release];[_renderer release];[_library release];[_themeButtons release];[_tabs release];[_graphicExpected release]; + [_browser close];[_browser release];[_renderer release];[_library release];[_themeButtons release];[_tabs release];[_graphicExpected release];[_graphicPending release]; [super dealloc]; } - (BOOL)isFlipped { return YES; } @@ -990,7 +1001,7 @@ NSView *DYCreateWorkspaceMaskEditor(id return (roots==1&&[only isEqual:key])||[@[@"primary",@"base",@"spider"]containsObject:key]; } - (void)refresh { - if(_refreshing||_spiderEditing||!_manager)return; + if(_refreshing||_spiderEditing||_graphicUndoOpen||_tearingDown||!_manager)return; id action=[self actionAPI]; if(!action)return; _refreshing=YES; uint64_t beta=DYBetaSpanBegin(@"inspector_refresh",nil); @@ -1129,22 +1140,86 @@ NSView *DYCreateWorkspaceMaskEditor(id [self postChanged]; } - (void)writeGraphicValues:(NSDictionary *)values { - NSMutableDictionary *byKey=[NSMutableDictionary dictionary];for(NSDictionary *d in DYDescriptors())byKey[d[@"key"]]=d; + if(!_graphicUndoOpen){[self commitGraphicValues:values];return;} + if(_graphicCancelled||!values.count)return; + if(!_graphicPending)_graphicPending=[NSMutableDictionary new]; + BOOL schedule=_graphicPending.count==0; + [_graphicPending addEntriesFromDictionary:values]; + if(schedule)[self performSelector:@selector(flushGraphicValues) withObject:nil afterDelay:1.0/60.0 + inModes:@[NSRunLoopCommonModes,NSEventTrackingRunLoopMode]]; +} +- (void)flushGraphicValues { + if(!_graphicPending.count)return; + NSDictionary *values=[[_graphicPending copy]autorelease]; + [_graphicPending removeAllObjects]; + [self commitGraphicValues:values]; +} +- (void)commitGraphicValues:(NSDictionary *)values { + static NSDictionary *byKey; + static dispatch_once_t once; + dispatch_once(&once,^{ + NSMutableDictionary *map=[NSMutableDictionary dictionary]; + for(NSDictionary *descriptor in DYDescriptors())map[descriptor[@"key"]]=descriptor; + byKey=[map copy]; + }); id action=[self actionAPI];if(!action)return; [action startAction:self]; @try { - CMTime t=action.currentTime;id set=[_manager apiForProtocol:@protocol(FxParameterSettingAPI_v6)]; - if(_graphicUndoOpen){if(_graphicCancelled||CMTimeCompare(t,_graphicTime)!=0){_graphicCancelled=YES;return;}idget=[_manager apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)];for(NSString*key in values){NSDictionary*d=byKey[key];double actual=NAN;if(d&&_graphicExpected[key]&&(![get getFloatValue:&actual fromParameter:[d[@"pid"]unsignedIntValue]atTime:t]||!std::isfinite(actual)||fabs(actual-[_graphicExpected[key]doubleValue])>1e-6*MAX(1.,fabs(actual)))){_graphicCancelled=YES;return;}}} - BOOL primaryEdit=NO;for(NSString *key in values) {NSDictionary *d=byKey[key];primaryEdit|=[key hasPrefix:@"cm"];double v=[values[key] doubleValue];if(!d||!std::isfinite(v))continue;v=fmax([d[@"min"]doubleValue],fmin([d[@"max"]doubleValue],v));[set setFloatValue:v toParameter:[d[@"pid"]unsignedIntValue] atTime:t];} - if(_graphicUndoOpen)for(NSString*key in values)_graphicExpected[key]=values[key]; - if(primaryEdit){[set setFloatValue:1 toParameter:2236 atTime:t];[self clearPrimaryBypasses:set time:t];} + CMTime time=action.currentTime; + id set=[_manager apiForProtocol:@protocol(FxParameterSettingAPI_v6)]; + if(_graphicUndoOpen){ + if(_graphicCancelled||CMTimeCompare(time,_graphicTime)!=0){_graphicCancelled=YES;return;} + id get=[_manager apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)]; + for(NSString *key in values){ + NSDictionary *descriptor=byKey[key];double actual=NAN; + NSNumber *expected=_graphicExpected[key]; + if(descriptor&&expected&&(![get getFloatValue:&actual fromParameter:[descriptor[@"pid"]unsignedIntValue] atTime:time]|| + !std::isfinite(actual)||fabs(actual-expected.doubleValue)>1e-6*MAX(1.,fabs(actual)))){ + _graphicCancelled=YES;return; + } + } + } + BOOL primaryEdit=NO; + for(NSString *key in values){ + NSDictionary *descriptor=byKey[key];double v=[values[key]doubleValue]; + if(!descriptor||!std::isfinite(v))continue; + primaryEdit|=[key hasPrefix:@"cm"]; + v=fmax([descriptor[@"min"]doubleValue],fmin([descriptor[@"max"]doubleValue],v)); + if(_graphicUndoOpen&&_graphicExpected[key]&&[_graphicExpected[key]doubleValue]==v)continue; + if([set setFloatValue:v toParameter:[descriptor[@"pid"]unsignedIntValue] atTime:time]&&_graphicUndoOpen) + _graphicExpected[key]=@(v); + } + if(primaryEdit){[set setFloatValue:1 toParameter:2236 atTime:time];[self clearPrimaryBypasses:set time:time];} } @finally {[action endAction:self];} - [self postChanged]; + if(!_graphicUndoOpen&&!_tearingDown)[self postChanged]; } - (void)clearPrimaryBypasses:(id)set time:(CMTime)t{for(NSDictionary *d in DYDescriptors())if([d[@"key"]hasPrefix:@"cmbypass"])[set setFloatValue:0 toParameter:[d[@"pid"]unsignedIntValue] atTime:t];} -- (void)graphicGesture:(BOOL)begin title:(NSString *)title{ - if(begin==_graphicUndoOpen)return;ida=[self actionAPI];if(!a)return;[a startAction:self]; - @try{idundo=[_manager apiForProtocol:@protocol(FxUndoAPI)];if(begin){_graphicTime=a.currentTime;_graphicCancelled=NO;[_graphicExpected release];_graphicExpected=[NSMutableDictionary new];idget=[_manager apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)];for(NSDictionary*r in _controls.allValues){NSDictionary*d=r[@"descriptor"];double value=NAN;if([get getFloatValue:&value fromParameter:[d[@"pid"]unsignedIntValue]atTime:_graphicTime]&&std::isfinite(value))_graphicExpected[d[@"key"]]=@(value);}_graphicUndoOpen=[undo startUndoGroup:title?:@"调整颜色"];}else{[undo endUndoGroup];_graphicUndoOpen=NO;_graphicCancelled=NO;[_graphicExpected removeAllObjects];}}@finally{[a endAction:self];} +- (void)graphicGesture:(BOOL)begin title:(NSString *)title { + if(begin==_graphicUndoOpen)return; + id action=[self actionAPI];if(!action)return; + if(!begin){ + [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(flushGraphicValues) object:nil]; + [self flushGraphicValues]; + } + [action startAction:self]; + @try{ + id undo=[_manager apiForProtocol:@protocol(FxUndoAPI)]; + if(begin){ + _graphicTime=action.currentTime;_graphicCancelled=NO; + [_graphicExpected release];_graphicExpected=[NSMutableDictionary new]; + id get=[_manager apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)]; + for(NSDictionary *record in _controls.allValues){ + NSDictionary *descriptor=record[@"descriptor"];double value=NAN; + if([get getFloatValue:&value fromParameter:[descriptor[@"pid"]unsignedIntValue] atTime:_graphicTime]&&std::isfinite(value)) + _graphicExpected[descriptor[@"key"]]=@(value); + } + _graphicUndoOpen=[undo startUndoGroup:title?:@"调整颜色"]; + }else{ + [undo endUndoGroup];_graphicUndoOpen=_graphicCancelled=NO; + [_graphicExpected removeAllObjects]; + } + }@finally{[action endAction:self];} + if(!begin&&!_tearingDown)[self postChanged]; } - (void)spiderGesture:(BOOL)begin { if(begin==_spiderEditing)return; diff --git a/大鱼调色/Plugin/DYManagedColor.h b/大鱼调色/Plugin/DYManagedColor.h index b63df7a..3ac8623 100644 --- a/大鱼调色/Plugin/DYManagedColor.h +++ b/大鱼调色/Plugin/DYManagedColor.h @@ -13,5 +13,5 @@ FOUNDATION_EXPORT void DYFollowPrimaryWorkingSpace(NSMutableDictionary *document FOUNDATION_EXPORT void DYPrimaryControlChanged(id manager,CMTime time,NSString *key); FOUNDATION_EXPORT NSArray *DYManagedInputSpaces(void); FOUNDATION_EXPORT NSArray *DYManagedOutputSpaces(void); -FOUNDATION_EXPORT NSDictionary *DYHostColorContext(FxImageTile *source,FxImageTile *destination,NSInteger primaries); +FOUNDATION_EXPORT NSDictionary *DYHostColorContext(CGColorSpaceRef source,CGColorSpaceRef destination,NSInteger primaries); FOUNDATION_EXPORT CGColorSpaceRef DYManagedTileSpace(FxImageTile *tile,NSInteger primaries) CF_RETURNS_RETAINED; diff --git a/大鱼调色/Plugin/DYManagedColor.mm b/大鱼调色/Plugin/DYManagedColor.mm index 2e18c9a..bc8174f 100644 --- a/大鱼调色/Plugin/DYManagedColor.mm +++ b/大鱼调色/Plugin/DYManagedColor.mm @@ -43,4 +43,4 @@ static NSString *profileLabel(CGColorSpaceRef space){ return name.length?[name stringByReplacingOccurrencesOfString:@"kCGColorSpace" withString:@""]:@"自定义 RGB 配置"; } static NSString *profileKey(CGColorSpaceRef space){if(!space)return @"unknown";CFPropertyListRef p=CGColorSpaceCopyPropertyList(space);NSData *d=p?[NSPropertyListSerialization dataWithPropertyList:(id)p format:NSPropertyListBinaryFormat_v1_0 options:0 error:nil]:nil;if(p)CFRelease(p);if(!d)return @"unknown";unsigned char hash[CC_SHA256_DIGEST_LENGTH];CC_SHA256(d.bytes,(CC_LONG)d.length,hash);NSMutableString*s=[NSMutableString string];for(auto c:hash)[s appendFormat:@"%02x",c];return s;} -NSDictionary *DYHostColorContext(FxImageTile *source,FxImageTile *destination,NSInteger primaries){CGColorSpaceRef a=DYManagedTileSpace(source,primaries),b=DYManagedTileSpace(destination,primaries);NSString *an=profileLabel(a),*bn=profileLabel(b);NSDictionary *d=@{@"primaries":@(primaries),@"source":an?:(a?@"自定义 RGB 配置":@"未知空间"),@"destination":bn?:(b?@"自定义 RGB 配置":@"未知空间"),@"sourceKey":profileKey(a),@"destinationKey":profileKey(b),@"processing":@"RGB Linear",@"alpha":@"premultiplied"};if(a)CGColorSpaceRelease(a);if(b)CGColorSpaceRelease(b);return d;} +NSDictionary *DYHostColorContext(CGColorSpaceRef a,CGColorSpaceRef b,NSInteger primaries){NSString *an=profileLabel(a),*bn=profileLabel(b);NSDictionary *d=@{@"primaries":@(primaries),@"source":an?:(a?@"自定义 RGB 配置":@"未知空间"),@"destination":bn?:(b?@"自定义 RGB 配置":@"未知空间"),@"sourceKey":profileKey(a),@"destinationKey":profileKey(b),@"processing":@"RGB Linear",@"alpha":@"premultiplied"};return d;} diff --git a/大鱼调色/Plugin/DYManagedRender.inc.h b/大鱼调色/Plugin/DYManagedRender.inc.h index 719b8da..66c3e11 100644 --- a/大鱼调色/Plugin/DYManagedRender.inc.h +++ b/大鱼调色/Plugin/DYManagedRender.inc.h @@ -1,27 +1,65 @@ -- (void)managedPreview:(id)texture source:(FxImageTile*)source entry:(NSMutableDictionary*)entry { +- (DYManagedPreviewReadback)encodeManagedPreview:(id)texture source:(FxImageTile*)source + entry:(NSMutableDictionary*)entry commands:(id)commands { + if(!commands)return {}; NSSize size=DYLookSampleSize(texture,source.pixelAspect,DYLookPreviewStandardEdge); - @synchronized(_previewLock){if(_exporting||(NSEqualSizes(size,_lastLookPreviewSize)&&CACurrentMediaTime()-_lastPreview<=.5))return;} - idp=[self computePipeline:@"dyManagedPreview" entry:entry error:nil];if(!p)return; - idb=[[entry[@"device"]newBufferWithLength:320*180*16 options:MTLResourceStorageModeShared]autorelease];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]; + @synchronized(_previewLock){if(_exporting||(NSEqualSizes(size,_lastLookPreviewSize)&&CACurrentMediaTime()-_lastPreview<=.5))return {};} + idp=[self computePipeline:@"dyManagedPreview" entry:entry error:nil];if(!p)return {}; + idb=[[entry[@"device"]newBufferWithLength:320*180*16 options:MTLResourceStorageModeShared]autorelease];if(!b)return {}; + idce=[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; - idstandard=NSEqualSizes(size,NSMakeSize(320,180))?nil:[self encodeLookPreview:texture inputLUT:nil strength:0 size:size standard:YES origin:origin entry:entry commands:cb]; + idstandard=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); - idhigh=[self encodeLookPreview:texture inputLUT:nil strength:0 size:highSize standard:NO origin:origin entry:entry commands:cb]; - [cb commit];[cb waitUntilCompleted]; - if(cb.status==MTLCommandBufferStatusCompleted)[self publishPreview:b standard:standard size:size high:high highSize:highSize origin:origin]; + idhigh=[self encodeLookPreview:texture inputLUT:nil strength:0 size:highSize standard:NO origin:origin entry:entry commands:commands]; + return {b,standard,high,size,highSize,origin}; } -// Included in DYRenderer. V1 callers and their ABI remain on renderSource:...tools:error:. -- (NSDictionary*)colorContext {@synchronized(_previewLock){return [[_colorContext copy]autorelease];}} -- (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 { +- (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)commands error:(NSError**)error { + if(!commands)return NO; idpipeline=[self computePipeline: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); + idce=[commands computeCommandEncoder];if(!ce)return fail(error,@"无法创建调色编码器"); + [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];return YES; } -- (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 { +- (BOOL)managedConvert:(dycm::Space)from to:(dycm::Space)to display:(NSInteger)display gamut:(BOOL)gamut input:(id)input output:(id)output entry:(NSMutableDictionary*)entry commands:(id)commands error:(NSError**)error { + if(!commands)return NO; 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); + 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)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]; @@ -97,7 +135,7 @@ } - (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,@"色彩管理状态无效。"); - NSDictionary*context=DYHostColorContext(src,dst,primaries);@synchronized(_previewLock){[_colorContext release];_colorContext=[context copy];} + [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; @@ -116,22 +154,23 @@ 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); + DYManagedBatch batch{entry[@"queue"],error}; + CGColorSpaceRef srcSpace=_renderSourceSpace,dstSpace=_renderDestinationSpace,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 copy=[&](idinput,idoutput){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){idout=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;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 computePipeline:@"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");}; + 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 computePipeline:@"dyManagedBlend" entry:entry error:error];if(!mb||!p)return NO;idce=[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;idbefore=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"];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 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,@"宿主未提供明确颜色空间,无法使用新版管理。可切回旧版兼容。"); 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;} + 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 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];}} @@ -146,10 +185,19 @@ 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 source:src 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);} + auto preview=[self encodeManagedPreview:current source:src entry:entry commands:batch.commands()]; + if(activeFinish.count){ + if(!batch.finish())return NO; + [self publishManagedPreview:preview];preview={}; + 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; + } + 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;}}} diff --git a/大鱼调色/Plugin/DYPrimaryKernels.inc.h b/大鱼调色/Plugin/DYPrimaryKernels.inc.h index 436cd6f..f39bd96 100644 --- a/大鱼调色/Plugin/DYPrimaryKernels.inc.h +++ b/大鱼调色/Plugin/DYPrimaryKernels.inc.h @@ -9,9 +9,24 @@ kernel void dyPrimaryGrade(texture2d a [[texture(0)]],textur if(any(xy>=uint2(b.get_width(),b.get_height())))return;float4 c=a.read(xy);if(c.a>0){float4 v=float4(c.rgb/c.a,1);if(p.stages&1)v=cst_float_air(v,p.input);if(p.stages&2){if(p.reserved&8)v=cst_float_air(v,p.basisInput);v=basis_float_air(v,p.basis);if(p.reserved&8)v=cst_float_air(v,p.basisOutput);}if(p.stages&4)v=cst_float_air(v,p.output);if(back.inputTransfer!=back.outputTransfer||back.inputGamut!=back.outputGamut||back.toneMapping)v=cst_float_air(v,back);c.rgb=v.rgb*c.a;}b.write(c,xy); } kernel void dyPrimaryBlend(texture2d before [[texture(0)]],texture2d after [[texture(1)]],texture2d output [[texture(2)]],device const DYToolMaskEntry* masks [[buffer(0)]],constant DYToolMaskHeader& h [[buffer(1)]],constant DYCSTMixParams& p [[buffer(2)]],uint2 xy [[thread_position_in_grid]]){ - if(any(xy>=uint2(output.get_width(),output.get_height())))return;float4 a=before.read(xy),b=after.read(xy);if(!(a.a>0)||!(b.a>0)){output.write(a,xy);return;}float3 ac=cst_float_air(float4(a.rgb/a.a,1),p.toLinear).rgb,bc=cst_float_air(float4(b.rgb/b.a,1),p.toLinear).rgb; - float2 uv=(float2(xy)+.5f)/float2(output.get_width(),output.get_height());float w=p.amount;if(h.count)w*=dyToolCoverage(uv,dyToolEncode(cst_float_air(float4(ac,1),dyPrimaryAP1To709).rgb),masks,h,h.section); - if(w<=0){output.write(a,xy);return;}if(w>=1){output.write(b,xy);return;}output.write(float4(cst_float_air(float4(mix(ac,bc,w),1),p.fromLinear).rgb*a.a,a.a),xy); + if(any(xy>=uint2(output.get_width(),output.get_height())))return; + float4 a=before.read(xy),b=after.read(xy); + if(!(a.a>0)||!(b.a>0)){output.write(a,xy);return;} + float3 ac=0,code=0; + if(h.keySources){ + ac=cst_float_air(float4(a.rgb/a.a,1),p.toLinear).rgb; + code=dyToolEncode(cst_float_air(float4(ac,1),dyPrimaryAP1To709).rgb); + } + float w=p.amount; + if(h.count){ + float2 uv=(float2(xy)+.5f)/float2(output.get_width(),output.get_height()); + w*=dyToolCoverage(uv,code,masks,h,h.section); + } + if(w<=0){output.write(a,xy);return;} + if(w>=1){output.write(b,xy);return;} + if(!h.keySources)ac=cst_float_air(float4(a.rgb/a.a,1),p.toLinear).rgb; + float3 bc=cst_float_air(float4(b.rgb/b.a,1),p.toLinear).rgb; + output.write(float4(cst_float_air(float4(mix(ac,bc,w),1),p.fromLinear).rgb*a.a,a.a),xy); } kernel void dyPrimaryCodeOutput(texture2d a [[texture(0)]],texture2d b [[texture(1)]],uint2 xy [[thread_position_in_grid]]){ if(any(xy>=uint2(b.get_width(),b.get_height())))return;float4 c=a.read(xy);if(c.a>0)c.rgb=dyDecode(c.rgb/c.a)*c.a;b.write(c,xy); diff --git a/大鱼调色/Plugin/DYPrimaryRender.inc.h b/大鱼调色/Plugin/DYPrimaryRender.inc.h index 9ecb8d1..aa4f410 100644 --- a/大鱼调色/Plugin/DYPrimaryRender.inc.h +++ b/大鱼调色/Plugin/DYPrimaryRender.inc.h @@ -5,24 +5,25 @@ // their established unmanaged host workflow rather than inheriting a Log tag. if(u.primarySectionEnabled<.5||DYBaseToolRemoved(tools,@"primary"))return [self renderSource:src destination:dst uniforms:u paths:paths spider:spider tools:tools 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,@"一级 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 内存预算。"); DYApplyRemovedBaseTools(&u,tools);BOOL root=u.primarySectionEnabled>.5;BOOL transparent=identityCM(u)&&!DYFilmPrintActive(u);int wt=lroundf(u.cm.workingTransfer),wg=lroundf(u.cm.workingGamut); NSMutableArray*pool=[NSMutableArray array];NSMutableSet*pinned=[NSMutableSet set];idcurrent=nil; auto next=[&]()->id{for(idt 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;idt=[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){idout=next();if(!out)return fail(error,@"无法分配一级 CST 缓冲区。");BOOL ok=[self managedDispatch:name textures:@[current,out] data:params length:length extra:extra extraLength:extraLength entry:entry error:error];if(ok)current=out;return ok;}; + auto dispatch=[&](NSString*name,const void*params,NSUInteger length,const void*extra=nullptr,NSUInteger extraLength=0){idout=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=[&](idt){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=[&](idbefore,NSArray*masks,float amount,NSString*type){if(!masks.count&&amount>=1)return YES;idout=next();if(!out)return fail(error,@"无法分配一级混合缓冲区。");DYToolMaskHeader h{};idmb=[self maskBuffer:@{type:masks?:@[]} tile:src device:d header:&h];h.section=(int)[DYToolTypes()indexOfObject:type];DYCSTMixParams p={{wg,wt,2,20,0},{2,20,wg,wt,0},amount};idpipeline=[self computePipeline:@"dyPrimaryBlend" entry:entry error:error];if(!pipeline||!mb)return NO;idcb=[entry[@"queue"]commandBuffer];idce=[cb computeCommandEncoder];[ce setComputePipelineState:pipeline];[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 setBytes:&p length:sizeof(p) atIndex:2];[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 blend=[&](idbefore,NSArray*masks,float amount,NSString*type){if(!masks.count&&amount>=1)return YES;idout=next();if(!out)return fail(error,@"无法分配一级混合缓冲区。");DYToolMaskHeader h{};idmb=[self maskBuffer:@{type:masks?:@[]} tile:src device:d header:&h];h.section=(int)[DYToolTypes()indexOfObject:type];DYCSTMixParams p={{wg,wt,2,20,0},{2,20,wg,wt,0},amount};idpipeline=[self computePipeline:@"dyPrimaryBlend" entry:entry error:error];if(!pipeline||!mb)return NO;idcommands=batch.commands();if(!commands)return NO;idce=[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 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;} idbefore=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"];idcube=path?[self lut:path entry:entry error:error]:nil;if(!cube)return fail(error,@"印片资源不可用。");idbefore=current;[pinned addObject:before];BOOL ok=transform({wg,wt,2,1,0});float amount=values.filmPrint.y*values.film.mix;if(ok){idout=next();ok=out&&[self managedDispatch:@"dyManagedPrint" textures:@[current,cube,out] data:&amount length:4 extra:nullptr extraLength:0 entry:entry 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;}; + 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;[pinned addObject:before];BOOL ok=transform({wg,wt,2,1,0});float amount=values.filmPrint.y*values.film.mix;if(ok){idout=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;idcarrier=next();uint32_t noLUT=0;if(!carrier||![self managedDispatch:@"dyManagedCarrier" textures:@[current,carrier,entry[@"identity"]] data:&noLUT length:4 extra:nullptr extraLength:0 entry:entry error:error])return NO;current=carrier; + current=source;idcarrier=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(root&&u.inputSectionEnabled>.5&&!transform({(int)lroundf(u.cm.inputGamut),(int)lroundf(u.cm.inputTransfer),wg,wt,0}))return NO; if(!grade(u,tools[@"baseMasks"][@"primary"],NO))return NO; NSMutableDictionary*finishing=DYMutablePlist(tools);NSMutableSet*scene=[NSMutableSet set];for(NSString*ID in DYToolDisplayOrder(tools)){NSDictionary*node=DYToolWithID(tools,ID);if([node[@"type"]isEqual:@"primary"]){transparent&=identityCM(DYToolUniforms(node));if(!grade(DYToolUniforms(node),node[@"masks"],YES))return NO;[scene addObject:ID];}} @@ -34,9 +35,42 @@ u.primarySectionEnabled=0;u.cm.configured=-1;u.inputProfile=u.preLUTStrength=0;u.filmPrint.x=0;NSDictionary*finishPaths=DYVisibleBaseToolPaths(paths,finishing);NSArray*activeFinish=DYPrimaryActiveFinishing(u,finishPaths,spider,finishing); BOOL display=outputEnabled&&ot>=1001&&ot<=1003; if(!display&&activeFinish.count)return fail(error,@"当前是 Log/线性码值输出。SDR 修饰工具需要显示输出,请选择 Gamma 输出,或关闭这些工具并保存完整预设。"); - if(!display&&transparent&&!activeFinish.count){current=source;[self managedPreview:current source:src entry:entry];}else if(display&&_exporting&&!activeFinish.count){if(!dispatch(@"dyPrimaryCodeOutput",nullptr,0))return NO;}else if(display){if(!transform({og,ot,22,20,0}))return NO;[self managedPreview:current source:src entry:entry]; - if(activeFinish.count){idout=next();if(!out)return fail(error,@"无法分配 SDR 修饰缓冲区。");_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(_exporting){if(!transform({22,20,og,ot,0})||!dispatch(@"dyPrimaryCodeOutput",nullptr,0))return NO;}else{CGColorSpaceRef from=CGColorSpaceCreateWithName(kCGColorSpaceExtendedLinearSRGB),to=DYManagedTileSpace(dst,primaries);DYColorProfile*p=to?[[[DYColorProfile alloc]initWithSource:from target:to error:error]autorelease]:nil;CGColorSpaceRelease(from);if(to)CGColorSpaceRelease(to);if(!p)return fail(error,@"宿主未提供明确的目标颜色空间。");idout=next();if(!out||![self managedProfile:p input:current output:out entry:entry error:error])return NO;current=out;} - }else{if(!dispatch(@"dyPrimaryCodeOutput",nullptr,0))return NO;[self managedPreview:current source:src entry:entry];} - _managedFinishing=YES;@try{return [self copyTile:tile(current) to:dst entry:entry error:error];}@finally{_managedFinishing=NO;} + DYManagedPreviewReadback preview{}; + if(!display&&transparent&&!activeFinish.count){ + current=source; + preview=[self encodeManagedPreview:current source:src entry:entry commands:batch.commands()]; + }else if(display&&_exporting&&!activeFinish.count){ + if(!dispatch(@"dyPrimaryCodeOutput",nullptr,0))return NO; + }else if(display){ + if(!transform({og,ot,22,20,0}))return NO; + preview=[self encodeManagedPreview:current source:src entry:entry commands:batch.commands()]; + if(activeFinish.count){ + if(!batch.finish())return NO; + [self publishManagedPreview:preview];preview={}; + idout=next();if(!out)return fail(error,@"无法分配 SDR 修饰缓冲区。"); + _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(_exporting){ + if(!transform({22,20,og,ot,0})||!dispatch(@"dyPrimaryCodeOutput",nullptr,0))return NO; + }else{ + DYColorProfile *profile=[self managedOutputProfile:error];if(!profile)return NO; + if(!profile.identity){ + if(!batch.finish())return NO; + idout=next();if(!out||![self managedProfile:profile input:current output:out entry:entry error:error])return NO; + current=out; + } + } + }else{ + if(!dispatch(@"dyPrimaryCodeOutput",nullptr,0))return NO; + preview=[self encodeManagedPreview:current source:src entry:entry commands:batch.commands()]; + } + _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;} } diff --git a/大鱼调色/Plugin/DYRenderer.mm b/大鱼调色/Plugin/DYRenderer.mm index e54a6b5..9162222 100644 --- a/大鱼调色/Plugin/DYRenderer.mm +++ b/大鱼调色/Plugin/DYRenderer.mm @@ -27,6 +27,36 @@ #import "DYScopeSample.h" #include "DYLevelGeometry.h" static BOOL fail(NSError**e,NSString*m){if(e)*e=[NSError errorWithDomain:@"com.dayu.color" code:1 userInfo:@{NSLocalizedDescriptionKey:m?:@"Metal 调色失败"}];return NO;} +// Keep a bounded group of ordered GPU passes. A CPU reader or another +// queue finishes the group before accessing its result. +struct DYManagedBatch { + id queue; + NSError **error; + id pending=nil; + unsigned passes=0; + BOOL failed=NO; + + BOOL finish(){ + if(!pending)return !failed; + [pending commit];[pending waitUntilCompleted]; + if(pending.status!=MTLCommandBufferStatusCompleted){failed=YES;fail(error,pending.error.localizedDescription);} + pending=nil;passes=0; + return !failed; + } + + id commands(){ + if(failed||(passes==16&&!finish()))return nil; + if(!pending)pending=[queue commandBuffer]; + if(!pending){failed=YES;fail(error,@"无法分配调色命令缓冲区");return nil;} + ++passes; + return pending; + } +}; +struct DYManagedPreviewReadback { + id analysis,standard,high; + NSSize size,highSize; + FxImageOrigin origin; +}; // 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){ @@ -146,6 +176,8 @@ struct DYScopeReadback { CFTimeInterval _lastPreview; BOOL _exporting; NSDictionary *_toolDocument,*_colorContext,*_exportManagedState; + CGColorSpaceRef _renderSourceSpace,_renderDestinationSpace; + DYColorProfile *_renderOutputProfile; BOOL _managedFinishing;NSData *_faceEntries,*_faceInput,*_faceCachedEntries;CIContext *_faceContext;NSData *_mosaicRaster,*_mosaicEntries;NSDictionary *_mosaicFaceSnapshot; dispatch_queue_t _scopeQueue; BOOL _scopeEnabled,_scopeWorkerRunning,_outputObserved,_outputNotificationPending,_spiderScopeWorkerRunning; @@ -163,6 +195,15 @@ struct DYScopeReadback { DYColorProfile *_scopeProfile; NSObject *_scopeProfileLock; } +- (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)commands error:(NSError**)error; +- (DYManagedPreviewReadback)encodeManagedPreview:(id)texture source:(FxImageTile*)source + entry:(NSMutableDictionary*)entry commands:(id)commands; +- (void)publishManagedPreview:(DYManagedPreviewReadback)preview; +- (DYColorProfile*)managedOutputProfile:(NSError**)error; +- (BOOL)copyTile:(FxImageTile*)source to:(FxImageTile*)dest rotation:(double)angle entry:(NSMutableDictionary*)entry + commands:(id)commands error:(NSError**)error; @end @implementation DYRenderer // The caller holds the renderer lock. Unused tools never load a GPU function. @@ -244,7 +285,7 @@ static NSData *DYLookBufferData(id buffer) { #include "DYFaceRender.inc.h" #include "DYToolRender.inc.h" - (instancetype)init{if((self=[super init])){_previewLock=[NSObject new];_scopeProfileLock=[NSObject new];_scopeQueue=dispatch_queue_create("com.dayu.color.final-output-scopes",DISPATCH_QUEUE_SERIAL);_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{[_mosaicRaster release];[_mosaicEntries release];[_mosaicFaceSnapshot release];[_faceEntries release];[_faceInput release];[_faceCachedEntries release];[_faceContext release];[_scopePending release];[_scopeLatest release];[_spiderScopeRaster release];[_scopePreview release];[_scopeMetadata release];[_scopeProfile release];[_scopeProfileLock release];dispatch_release(_scopeQueue);[_devices release];[_luts release];[_preparedLUTs release];[_activeLUTPaths release];dispatch_release(_lutPreparationQueue);[_tables release];[_preview release];[_lookLUTPreviewFrames release];[_colorContext release];[_previewLock release];[super dealloc];} +- (void)dealloc{[_mosaicRaster release];[_mosaicEntries release];[_mosaicFaceSnapshot release];[_faceEntries release];[_faceInput release];[_faceCachedEntries release];[_faceContext release];[_scopePending release];[_scopeLatest release];[_spiderScopeRaster release];[_scopePreview release];[_scopeMetadata release];[_scopeProfile release];[_scopeProfileLock release];dispatch_release(_scopeQueue);[_devices release];[_luts release];[_preparedLUTs release];[_activeLUTPaths release];dispatch_release(_lutPreparationQueue);[_tables release];[_preview release];[_lookLUTPreviewFrames release];[_renderOutputProfile release];if(_renderSourceSpace)CGColorSpaceRelease(_renderSourceSpace);if(_renderDestinationSpace)CGColorSpaceRelease(_renderDestinationSpace);[_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]; diff --git a/大鱼调色/Plugin/DYToolGPU.h b/大鱼调色/Plugin/DYToolGPU.h index 8ad5878..e31e4d6 100644 --- a/大鱼调色/Plugin/DYToolGPU.h +++ b/大鱼调色/Plugin/DYToolGPU.h @@ -7,7 +7,8 @@ struct DYToolMaskEntry { // Local path coordinates for authored Bézier mosaic masks. float minX,minY,maxX,maxY; }; -struct DYToolMaskHeader {unsigned count;float offsetX,offsetY,scaleX,scaleY;int section,premultiplied,faceOnly,skinPreview;}; +enum DYToolMaskKeySource : unsigned { DYToolMaskLayerKey=1, DYToolMaskOriginalKey=2 }; +struct DYToolMaskHeader {unsigned count;float offsetX,offsetY,scaleX,scaleY;int section,premultiplied,faceOnly,skinPreview;unsigned keySources;}; struct DYToolStageRange {int first,last,suppressBlackWhite;}; // Destination coverage and the source sampling transform are independent. diff --git a/大鱼调色/Plugin/DYToolRender.inc.h b/大鱼调色/Plugin/DYToolRender.inc.h index 3a7e8ab..095da0d 100644 --- a/大鱼调色/Plugin/DYToolRender.inc.h +++ b/大鱼调色/Plugin/DYToolRender.inc.h @@ -13,6 +13,8 @@ if(![m[@"enabled"]boolValue])continue; DYToolMaskEntry entry{};entry.section=(int)section;entry.combine=[m[@"combine"]intValue]; [m[@"parameters"]getBytes:&entry.mask.parameters length:sizeof(DYMaskParameters)];entry.mask.parameters.imageAspect=w/ht; + if(entry.mask.parameters.kind>=DYMaskHSLKey) + h->keySources|=entry.mask.parameters.sourceStage==DYMaskSourceOriginal?DYToolMaskOriginalKey:DYToolMaskLayerKey; NSData *nodes=m[@"nodes"];auto &path=entry.mask.path; path=dyFlattenMask((const DYBezierNode*)nodes.bytes,nodes.length/sizeof(DYBezierNode)); if(mosaic&&entry.mask.parameters.kind==DYMaskBezier&&path.count>=3){ @@ -25,12 +27,18 @@ } - (BOOL)encodeBlend:(id)before after:(id)after output:(id)output masks:(id)masks header:(DYToolMaskHeader)h entry:(NSMutableDictionary*)entry commands:(id)commands error:(NSError**)error { id pipeline=[self computePipeline:@"dyToolBlend" entry:entry error:error];if(!pipeline)return NO; - idencoder=[commands computeCommandEncoder];[encoder setComputePipelineState:pipeline];[encoder setTexture:before atIndex:0];[encoder setTexture:after atIndex:1];[encoder setTexture:output atIndex:2];[encoder setBuffer:masks offset:0 atIndex:0];[encoder setBytes:&h length:sizeof(h) atIndex:1];[encoder dispatchThreads:MTLSizeMake(output.width,output.height,1) threadsPerThreadgroup:MTLSizeMake(16,16,1)];[encoder endEncoding];return YES; + idencoder=masks?[commands computeCommandEncoder]:nil;if(!encoder)return fail(error,@"无法创建蒙版混合编码器");[encoder setComputePipelineState:pipeline];[encoder setTexture:before atIndex:0];[encoder setTexture:after atIndex:1];[encoder setTexture:output atIndex:2];[encoder setBuffer:masks offset:0 atIndex:0];[encoder setBytes:&h length:sizeof(h) atIndex:1];[encoder dispatchThreads:MTLSizeMake(output.width,output.height,1) threadsPerThreadgroup:MTLSizeMake(16,16,1)];[encoder endEncoding];return YES; } - (BOOL)copyTile:(FxImageTile*)source to:(FxImageTile*)dest entry:(NSMutableDictionary*)e error:(NSError**)error { return [self copyTile:source to:dest rotation:0 entry:e error:error]; } - (BOOL)copyTile:(FxImageTile*)source to:(FxImageTile*)dest rotation:(double)angle entry:(NSMutableDictionary*)e error:(NSError**)error { + idcommands=[e[@"queue"] commandBuffer]; + if(!commands)return fail(error,@"无法分配图像输出命令"); + return [self copyTile:source to:dest rotation:angle entry:e commands:commands error:error]; +} +- (BOOL)copyTile:(FxImageTile*)source to:(FxImageTile*)dest rotation:(double)angle entry:(NSMutableDictionary*)e commands:(id)commands error:(NSError**)error { + if(!commands)return NO; iddevice=e[@"device"];ida=[source metalTextureForDevice:device],b=[dest metalTextureForDevice:device]; if(!a||!b)return fail(error,@"宿主图像纹理不可用"); BOOL useFloat=_managedFinishing||angle!=0; @@ -49,7 +57,7 @@ if(source.imageOrigin==kFxImageOrigin_BOTTOM_LEFT)vertex.textureCoordinate.y=1-vertex.textureCoordinate.y; if(dest.imageOrigin==kFxImageOrigin_BOTTOM_LEFT)vertex.position.y=-vertex.position.y; } - vector_uint2 size={(unsigned)b.width,(unsigned)b.height};idcb=[e[@"queue"]commandBuffer];MTLRenderPassDescriptor *pass=[MTLRenderPassDescriptor renderPassDescriptor];pass.colorAttachments[0].texture=b;pass.colorAttachments[0].loadAction=MTLLoadActionDontCare;pass.colorAttachments[0].storeAction=MTLStoreActionStore;idencoder=[cb renderCommandEncoderWithDescriptor:pass];[encoder setRenderPipelineState:pipeline];[encoder setVertexBytes:v length:sizeof(v) atIndex:0];[encoder setVertexBytes:&size length:sizeof(size) atIndex:1];[encoder setFragmentTexture:a atIndex:0];[encoder drawPrimitives:MTLPrimitiveTypeTriangleStrip vertexStart:0 vertexCount:4];[encoder endEncoding];return [self completeCommands:cb destination:dest texture:b entry:e]?YES:fail(error,cb.error.localizedDescription); + vector_uint2 size={(unsigned)b.width,(unsigned)b.height};MTLRenderPassDescriptor *pass=[MTLRenderPassDescriptor renderPassDescriptor];pass.colorAttachments[0].texture=b;pass.colorAttachments[0].loadAction=MTLLoadActionDontCare;pass.colorAttachments[0].storeAction=MTLStoreActionStore;idencoder=[commands renderCommandEncoderWithDescriptor:pass];if(!encoder)return fail(error,@"无法创建图像输出编码器");[encoder setRenderPipelineState:pipeline];[encoder setVertexBytes:v length:sizeof(v) atIndex:0];[encoder setVertexBytes:&size length:sizeof(size) atIndex:1];[encoder setFragmentTexture:a atIndex:0];[encoder drawPrimitives:MTLPrimitiveTypeTriangleStrip vertexStart:0 vertexCount:4];[encoder endEncoding];return [self completeCommands:commands destination:dest texture:b entry:e]?YES:fail(error,commands.error.localizedDescription); } // Extra skin keeps the source reference used by the prior release. All other // extra tools reuse the same isolated native tool path and their own mask group. diff --git a/大鱼调色/Plugin/DYUnifiedDiagnostics.inc.h b/大鱼调色/Plugin/DYUnifiedDiagnostics.inc.h index adfd242..69f0e0e 100644 --- a/大鱼调色/Plugin/DYUnifiedDiagnostics.inc.h +++ b/大鱼调色/Plugin/DYUnifiedDiagnostics.inc.h @@ -18,6 +18,28 @@ NSMutableDictionary *zero=DYMutablePlist(DYNewMask(DYMaskRectangle));DYMaskParameters p=DYMaskAtTime(zero,kCMTimeZero);p.strength=0;zero[@"parameters"]=[NSData dataWithBytes:&p length:sizeof(p)];doc[@"baseMasks"][@"hsl"]=@[zero]; Pixels masked=frame(changed,doc,@"unified-zero-mask");run.record(@"unified-zero-mask-is-exact-neutral",difference(masked,plain).maximum==0);[doc[@"baseMasks"]removeObjectForKey:@"hsl"]; changed.cm.outputTransfer=1002;changed.cm.toneMapping=1;changed.hslSatA.x=40;Pixels last=frame(changed,doc,@"unified-last-output");doc[@"outputAfter"]=@"base:primary";Pixels middle=frame(changed,doc,@"unified-middle-output");run.record(@"unified-moving-output-changes-actual-domain-order",difference(last,middle).maximum>.001,@{@"difference":@(difference(last,middle).maximum)}); + { + Pixels patch(w*h*4); + for(size_t i=0;i.001&& + difference(originalKey,withoutHSL).maximum==0&&difference(layerKey,unmaskedHSL).maximum==0); + } DYDiagnosticManager *host=[[[DYDiagnosticManager alloc]init]autorelease];DYCreateParameters(host,nil);DYAssetState *assets=[[[DYAssetState alloc]init]autorelease];assets.colorManagement=v4;DYWriteAssets(host,assets,kCMTimeZero); DYInspector *view=[[[DYInspector alloc]initWithAPIManager:host]autorelease];[view refresh];[view setFrameSize:NSMakeSize(400,400)];[view layoutSubtreeIfNeeded];NSDictionary *output=nil;for(NSDictionary *card in [view valueForKey:@"cards"])if([card[@"section"][@"key"]isEqual:@"output"])output=card; run.record(@"unified-inspector-output-visible-at-chain-tail",output&&![output[@"view"]isHidden]&&NSMaxY([output[@"view"]frame])>NSMaxY([[[view valueForKey:@"cards"]firstObject][@"view"]frame])); diff --git a/大鱼调色/Plugin/DYUnifiedRender.inc.h b/大鱼调色/Plugin/DYUnifiedRender.inc.h index 71b70d7..8934bc8 100644 --- a/大鱼调色/Plugin/DYUnifiedRender.inc.h +++ b/大鱼调色/Plugin/DYUnifiedRender.inc.h @@ -2,24 +2,25 @@ - (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;idd=entry[@"device"];idsource=[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];idcurrent=nil,originalWorking=nil;int initialGamut=wg,initialTransfer=wt; auto next=[&]()->id{for(idt 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;idt=[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){idout=next();if(!out)return fail(error,@"无法分配一级 CST 缓冲区。");BOOL ok=[self managedDispatch:name textures:@[current,out] data:params length:length extra:extra extraLength:extraLength entry:entry error:error];if(ok)current=out;return ok;}; + auto dispatch=[&](NSString*name,const void*params,NSUInteger length,const void*extra=nullptr,NSUInteger extraLength=0){idout=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=[&](idt){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=[&](idbefore,NSArray*masks,float amount,NSString*type){if(!masks.count&&amount>=1)return YES;idout=next();if(!out)return fail(error,@"无法分配一级混合缓冲区。");DYToolMaskHeader h{};idmb=[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};idpipeline=[self computePipeline:@"dyUnifiedBlend" entry:entry error:error];if(!pipeline||!mb)return NO;idcb=[entry[@"queue"]commandBuffer];idce=[cb computeCommandEncoder];[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];[cb commit];[cb waitUntilCompleted];if(cb.status!=MTLCommandBufferStatusCompleted)return fail(error,cb.error.localizedDescription);current=out;return YES;}; + auto blend=[&](idbefore,NSArray*masks,float amount,NSString*type){if(!masks.count&&amount>=1)return YES;idout=next();if(!out)return fail(error,@"无法分配一级混合缓冲区。");DYToolMaskHeader h{};idmb=[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};idpipeline=[self computePipeline:@"dyUnifiedBlend" entry:entry error:error];if(!pipeline||!mb)return NO;idcommands=batch.commands();if(!commands)return NO;idce=[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;} idbefore=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"];idcube=path?[self lut:path entry:entry error:error]:nil;if(!cube)return fail(error,@"印片资源不可用。");idbefore=current;[pinned addObject:before];BOOL ok=transform({wg,wt,2,1,0});float amount=values.filmPrint.y*values.film.mix;if(ok){idout=next();ok=out&&[self managedDispatch:@"dyManagedPrint" textures:@[current,cube,out] data:&amount length:4 extra:nullptr extraLength:0 entry:entry 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;}; + 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;[pinned addObject:before];BOOL ok=transform({wg,wt,2,1,0});float amount=values.filmPrint.y*values.film.mix;if(ok){idout=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;idcarrier=next();uint32_t noLUT=0;if(!carrier||![self managedDispatch:@"dyManagedCarrier" textures:@[current,carrier,entry[@"identity"]] data:&noLUT length:4 extra:nullptr extraLength:0 entry:entry error:error])return NO;current=carrier; + current=source;idcarrier=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]; @@ -33,7 +34,7 @@ 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"]){idout=next();ok=out&&[self renderLens:tile(current) destination:tile(out) uniforms:values masks:@[] entry:entry error:error];if(ok)current=out;} + else if([type isEqual:@"lens"]){idout=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. @@ -46,10 +47,13 @@ // 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. idreferenceTexture=bounded; - if(ok&&[type isEqual:@"skin"]){if(!_exporting&&(values.skinFaceOnly>.5||values.skinVisualize>.5))[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){idout=next();_managedFinishing=YES;@try{ok=out&&[self renderExtraTool:node source:tile(bounded) original:tile(referenceTexture) destination:tile(out) entry:entry error:error];}@finally{_managedFinishing=NO;}if(ok)current=out;} + 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){idout=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){idout=next();ok=out&&[self managedDispatch:@"dyUnifiedBridgeOut" textures:@[raw,current,out] data:nullptr length:0 extra:nullptr extraLength:0 entry:entry error:error];if(ok)current=out;} + if(ok){idout=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}); } @@ -72,12 +76,23 @@ [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. - if(_exporting){if(!dispatch(@"dyPrimaryCodeOutput",nullptr,0))return NO;} - else { - if(!transform({wg,wt,22,20,0}))return NO;[self managedPreview:current source:src entry:entry]; - CGColorSpaceRef from=CGColorSpaceCreateWithName(kCGColorSpaceExtendedLinearSRGB),to=DYManagedTileSpace(dst,primaries); - DYColorProfile *profile=to?[[[DYColorProfile alloc]initWithSource:from target:to error:error]autorelease]:nil;CGColorSpaceRelease(from);if(to)CGColorSpaceRelease(to); - if(!profile)return fail(error,@"宿主未提供明确的目标颜色空间。");idout=next();if(!out||![self managedProfile:profile input:current output:out entry:entry error:error])return NO;current=out; + 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; + idout=next();if(!out||![self managedProfile:profile input:current output:out entry:entry error:error])return NO; + current=out; + } } - _managedFinishing=YES;@try{return [self copyTile:tile(current) to:dst entry:entry error:error];}@finally{_managedFinishing=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;} } diff --git a/大鱼调色/Plugin/DYWorkspaceDiagnostics.inc.h b/大鱼调色/Plugin/DYWorkspaceDiagnostics.inc.h index d23ec7c..58a02d5 100644 --- a/大鱼调色/Plugin/DYWorkspaceDiagnostics.inc.h +++ b/大鱼调色/Plugin/DYWorkspaceDiagnostics.inc.h @@ -196,7 +196,13 @@ NSUInteger originalLayers=[DYReadTools(stackHost,kCMTimeZero).document[@"layers"]count];int undo=stackHost->_undoStarts; [stack addWorkspaceTool:toolbarButton(@"curve")];workspaceDrain();NSString *curveID=[[[stack valueForKey:@"selectedNode"]copy]autorelease];NSDictionary *tools=DYReadTools(stackHost,kCMTimeZero).document; run.record(@"workspace-toolbar-adds-real-uuid-and-synchronizes-regular-inspector",[tools[@"layers"]count]==originalLayers+1&&[DYToolWithID(tools,curveID)[@"type"]isEqual:@"curve"]&&[[mainInspector valueForKey:@"stackViews"]objectForKey:curveID]&&stackHost->_undoStarts==undo+1&&stackHost->_undoEnds==stackHost->_undoStarts); - DYInspector *curveEditor=[stack valueForKey:@"toolEditor"];undo=stackHost->_undoStarts;[curveEditor graphicGesture:YES title:@"测试曲线手势"];[curveEditor writeGraphicValues:@{@"masterX0":@.3,@"curveY0":@12}];[curveEditor writeGraphicValues:@{@"masterX0":@.35,@"curveY0":@16}];[curveEditor graphicGesture:NO title:nil]; + DYInspector *curveEditor=[stack valueForKey:@"toolEditor"];undo=stackHost->_undoStarts; + NSDictionary *beforeCurve=DYReadTools(stackHost,kCMTimeZero).document; + [curveEditor graphicGesture:YES title:@"测试曲线手势"]; + [curveEditor writeGraphicValues:@{@"masterX0":@.3,@"curveY0":@12}]; + [curveEditor writeGraphicValues:@{@"masterX0":@.35,@"curveY0":@16}]; + run.record(@"workspace-curve-coalesces-pending-samples",[beforeCurve isEqual:DYReadTools(stackHost,kCMTimeZero).document]); + [curveEditor graphicGesture:NO title:nil]; run.record(@"workspace-curve-xy-samples-use-one-undo-and-exact-uuid",stackHost->_undoStarts==undo+1&&stackHost->_undoEnds==stackHost->_undoStarts&&fabs([DYToolWithID(DYReadTools(stackHost,kCMTimeZero).document,curveID)[@"values"][@"curveY0"]doubleValue]-16)<1e-6); [curveEditor graphicGesture:YES title:@"测试播放头变化"];stackHost->_workspaceTime=CMTimeMake(1,25);[curveEditor writeGraphicValues:@{@"curveY0":@33}];[curveEditor graphicGesture:NO title:nil];stackHost->_workspaceTime=kCMTimeZero; run.record(@"workspace-curve-gesture-rejects-a-changed-playhead",[DYToolWithID(DYReadTools(stackHost,kCMTimeZero).document,curveID)[@"values"][@"curveY0"]doubleValue]==16); diff --git a/大鱼调色/Plugin/Info.plist b/大鱼调色/Plugin/Info.plist index 69abbe1..4b4d6c7 100644 --- a/大鱼调色/Plugin/Info.plist +++ b/大鱼调色/Plugin/Info.plist @@ -17,9 +17,9 @@ CFBundlePackageType XPC! CFBundleShortVersionString - 1.21.7 + 1.21.8 CFBundleVersion - 125 + 126 NSHumanReadableCopyright PlugInKit diff --git a/大鱼调色/Wrapper Application/Info.plist b/大鱼调色/Wrapper Application/Info.plist index 8c4a386..bfd111d 100644 --- a/大鱼调色/Wrapper Application/Info.plist +++ b/大鱼调色/Wrapper Application/Info.plist @@ -17,9 +17,9 @@ CFBundlePackageType APPL CFBundleShortVersionString - 1.21.7 + 1.21.8 CFBundleVersion - 125 + 126 LSMinimumSystemVersion $(MACOSX_DEPLOYMENT_TARGET) NSHumanReadableCopyright diff --git a/开发交接.md b/开发交接.md index dd33f9e..d787e8d 100644 --- a/开发交接.md +++ b/开发交接.md @@ -2,6 +2,12 @@ 更新于 2026-11-09(Asia/Shanghai)。这是新对话的接手入口。历史设计和实现细节按需查阅专项交接,复现和交付证据以对应版本的报告为准。 +## 1.21.8(126)多层调色与检查器响应 + +2026-11-09。减少多层色彩管理的 GPU 提交和等待,预览取样随同当前批次编码,保留跨 CPU/GPU 边界的同步。宿主 ICC 配置未变化时复用解析结果,几何蒙版跳过色键转换,部分覆盖继续按原色彩空间混合。曲线、色彩平衡和颜色分级轮按显示节奏合并宿主参数写入,松手提交最后值并结束撤销组。 + +候选 Release 编译通过。首轮 1080p 胶片颗粒与晕光出现回退,已恢复该路径原有的 GPU 提交。正在复测最终候选的 1080p/4K 渲染与像素校验。当前正式安装与 Release 为 1.21.7(125),站点文章与主 APP 更新通道为 1.21.6(124)。下一步完成正式构建、自检、公证、宿主验收与公测发行。 + ## 1.21.7(125)蜘蛛盘跟手优化 2026-11-09。仅分析 Color Finale 2.17.0(632)的 Color Warper。核对了本地网格编辑、位图复用、独立取样、当前节点读数更新和 GPU 查表路径。大鱼移植本地草稿与重活分离的方式,合并检查器/工作台拖动写入,松手补交最终位置并关闭撤销组。画布合并待处理网格,检查外部修改和目标时间。现有蜘蛛盘数学和预设数据结构继续使用。[取证与实现](research/ColorFinaleSpiderFluidity-20261109.md)