diff --git a/大鱼调色/Plugin/DYFaceRender.inc.h b/大鱼调色/Plugin/DYFaceRender.inc.h index 37c0c2c..86fa1df 100644 --- a/大鱼调色/Plugin/DYFaceRender.inc.h +++ b/大鱼调色/Plugin/DYFaceRender.inc.h @@ -35,7 +35,12 @@ [handler release];[request release];_faceEntries=[[NSData alloc]initWithBytes:entries.data() length:entries.size()*sizeof(DYToolMaskEntry)];[_faceCachedEntries release];_faceCachedEntries=[_faceEntries copy]; } - (BOOL)renderSource:(FxImageTile*)src destination:(FxImageTile*)dst uniforms:(DYUniforms)u paths:(NSDictionary*)paths spider:(NSData*)spider tools:(NSDictionary*)tools error:(NSError**)error {@synchronized(self){ - DYUniforms effective=DYEffectiveFaceUniforms(u,paths,tools);BOOL face=effective.skinProtection.x>.5&&(effective.skinProtection.y>0||effective.skinVisualize>.5)&&(effective.skinFaceOnly>.5||effective.skinVisualize>.5);for(NSDictionary *node in tools[@"layers"]){DYUniforms layer=DYToolUniforms(node);face|=[node[@"type"]isEqual:@"skin"]&&!DYToolIsNeutral(node)&&layer.skinProtection.x>.5&&(layer.skinFaceOnly>.5||layer.skinVisualize>.5);} + DYUniforms effective=DYEffectiveFaceUniforms(u,paths,tools);BOOL face=effective.skinProtection.x>.5&&(effective.skinProtection.y>0||effective.skinVisualize>.5)&&(effective.skinFaceOnly>.5||effective.skinVisualize>.5);for(NSDictionary *node in tools[@"layers"]){ + if(face)break; + if(![node[@"type"]isEqual:@"skin"]||DYToolIsNeutral(node))continue; + DYUniforms layer=DYToolUniforms(node); + face=layer.skinProtection.x>.5&&(layer.skinFaceOnly>.5||layer.skinVisualize>.5); + } if(face&&!_exporting)[self prepareFaceSupport:src];else{[_faceEntries release];_faceEntries=nil;} BOOL ok=[self renderToolsSource:src destination:dst uniforms:u paths:paths spider:spider tools:tools error:error]; return ok; @@ -43,6 +48,7 @@ - (BOOL)renderLens:(FxImageTile*)source destination:(FxImageTile*)destination uniforms:(DYUniforms)u masks:(NSArray*)masks entry:(NSDictionary*)entry error:(NSError**)error { if(source.imageOrigin==kFxImageOrigin_BOTTOM_LEFT)u.lensCenterY=1-u.lensCenterY; idd=entry[@"device"];idbefore=[source metalTextureForDevice:d],output=[destination metalTextureForDevice:d]; - idcb=[entry[@"queue"]commandBuffer];idce=[cb computeCommandEncoder];[ce setComputePipelineState:entry[@"dyLensRepair"]];[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];[self encodeBlend:before after:output output:blend masks:buffer header:h entry:entry commands:cb];[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; + 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; } diff --git a/大鱼调色/Plugin/DYFilmRender.inc.h b/大鱼调色/Plugin/DYFilmRender.inc.h index 3b27ce3..ed85107 100644 --- a/大鱼调色/Plugin/DYFilmRender.inc.h +++ b/大鱼调色/Plugin/DYFilmRender.inc.h @@ -20,6 +20,14 @@ ci=[[ci imageByApplyingFilter:@"CIGaussianBlur" withInputParameters:@{kCIInputRadiusKey:@(radius)}]imageByCroppingToRect:bounds]; [context render:ci toMTLTexture:output commandBuffer:commands bounds:bounds colorSpace:nil];return YES; }; + NSMutableArray *needed=[NSMutableArray arrayWithObject:@"dyFilmPoint"]; + if(!mixer){ + if(DYFilmBloomActive(u.film))[needed addObjectsFromArray:@[@"dyFilmSparseBlur",@"dyFilmBloomEdges"]]; + if(DYFilmGrainActive(u.film))[needed addObject:@"dyFilmNoise"]; + if(DYFilmPrintActive(u))[needed addObject:@"dyFilmPrint"]; + if(u.film.mix<1)[needed addObject:@"dyFilmMix"]; + } + for(NSString *name in needed)if(![self computePipeline:name entry:entry error:error])return NO; auto encode=[&](NSString *name,ida,idb,idout,const void *data,NSUInteger length){ idce=[commands computeCommandEncoder];[ce setComputePipelineState:entry[name]];[ce setTexture:a atIndex:0];if(b)[ce setTexture:b atIndex:1];[ce setTexture:out atIndex:b?2:1];if(data)[ce setBytes:data length:length atIndex:0];[ce dispatchThreads:MTLSizeMake(out.width,out.height,1) threadsPerThreadgroup:MTLSizeMake(16,16,1)];[ce endEncoding]; }; @@ -61,7 +69,7 @@ } // Finish the effect before the module's existing mask blend. Source and // result retain identical alpha, and an empty mask group means full coverage. - if(masks.count){idout=texture(current==slots[0]?1:0);if(!out)return fail(error,@"无法分配胶片蒙版缓冲区");DYToolMaskHeader header{};header.section=(int)[DYToolTypes()indexOfObject:type];idbuffer=[self maskBuffer:@{type:masks} tile:source device:d header:&header];[self encodeBlend:before after:current output:out masks:buffer header:header entry:entry commands:commands];current=out;} + if(masks.count){idout=texture(current==slots[0]?1:0);if(!out)return fail(error,@"无法分配胶片蒙版缓冲区");DYToolMaskHeader header{};header.section=(int)[DYToolTypes()indexOfObject:type];idbuffer=[self maskBuffer:@{type:masks} tile:source device:d header:&header];if(![self encodeBlend:before after:current output:out masks:buffer header:header entry:entry commands:commands error:error])return NO;current=out;} [commands commit];[commands waitUntilCompleted];if(commands.status!=MTLCommandBufferStatusCompleted)return fail(error,commands.error.localizedDescription); DYExportTile *result=[[[DYExportTile alloc]initWithTexture:current registry:d.registryID]autorelease];[result setBounds:source.tilePixelBounds origin:source.imageOrigin];[result setPixelAspect:source.pixelAspect];return [self copyTile:result to:destination entry:entry error:error]; }@catch(NSException *exception){return fail(error,[@"胶片处理失败:" stringByAppendingString:exception.reason?:@""]);} diff --git a/大鱼调色/Plugin/DYGrade.metal b/大鱼调色/Plugin/DYGrade.metal index 29b4aa0..c5f62f9 100644 --- a/大鱼调色/Plugin/DYGrade.metal +++ b/大鱼调色/Plugin/DYGrade.metal @@ -232,16 +232,30 @@ fragment half4 dySegmentFragment(DYRaster in [[stage_in]], // Optional boundary conversion. Use this before both statistics and grading // when the host supplies premultiplied RGB; all neighborhood samples then see // the same straight RGB representation. Source and destination must differ. +inline half4 dyStraightSample(float4 sample) { + if (!(sample.a > 0.0f) || !all(isfinite(sample))) return half4(0.0h); + return half4(half3(sample.rgb / sample.a), half(sample.a)); +} + kernel void dyUnpremultiply(texture2d source [[texture(0)]], texture2d destination [[texture(1)]], uint2 pixel [[thread_position_in_grid]]) { if (pixel.x >= destination.get_width() || pixel.y >= destination.get_height()) return; - float4 sample = source.read(pixel); - if (!(sample.a > 0.0f) || !all(isfinite(sample))) { - destination.write(half4(0.0h), pixel); - return; - } - destination.write(half4(half3(sample.rgb / sample.a), half(sample.a)), pixel); + destination.write(dyStraightSample(source.read(pixel)), pixel); +} + +// Match the historical half-precision alpha round trip without an intermediate +// texture when source and destination cover the same pixel grid. +fragment half4 dyNeutralInputFragment(DYRaster in [[stage_in]],texture2d source [[texture(0)]]) { + uint2 size(source.get_width(),source.get_height()); + half4 c=dyStraightSample(source.read(min(uint2(in.uv*float2(size)),size-1))); + return c.a>0.0h?half4(c.rgb*c.a,c.a):half4(0.0h); +} + +fragment half4 dyNeutralOutputFragment(DYRaster in [[stage_in]],texture2d source [[texture(0)]]) { + constexpr sampler f(coord::normalized,address::clamp_to_edge,filter::linear); + half4 c=source.sample(f,in.uv); + return c.a>0.0h?half4(c.rgb*c.a,c.a):half4(0.0h); } // Per-instance CPU analysis thumbnail. Host dispatches exactly 64x64 threads; @@ -314,9 +328,12 @@ inline float3 dyDecode(float3 encoded) { } kernel void dyColorManagement(texture2d source [[texture(0)]], texture2d destination [[texture(1)]], - constant DayuRenderParams& p [[buffer(0)]],constant float& amount [[buffer(1)]],uint2 pos [[thread_position_in_grid]]) { + constant DayuRenderParams& p [[buffer(0)]],constant float& amount [[buffer(1)]], + constant uint& premultiplied [[buffer(2)]],uint2 pos [[thread_position_in_grid]]) { if(pos.x>=source.get_width()||pos.y>=source.get_height())return; - float4 sample=source.read(pos);if(!(sample.a>0)){destination.write(half4(0),pos);return;} + float4 sample=source.read(pos); + if(premultiplied)sample=float4(dyStraightSample(sample)); + if(!(sample.a>0)){destination.write(half4(0),pos);return;} float4 raw=float4(dyEncode(sample.rgb),sample.a),c=raw; if(p.stages&1)c=cst_air(half4(c),p.input); if(p.stages&2){if(p.reserved&8)c=cst_air(half4(c),p.basisInput);c=basis_air(half4(c),p.basis);if(p.reserved&8)c=cst_air(half4(c),p.basisOutput);} diff --git a/大鱼调色/Plugin/DYIdlePreviewDiagnostics.inc.h b/大鱼调色/Plugin/DYIdlePreviewDiagnostics.inc.h index e0953d5..a77f573 100644 --- a/大鱼调色/Plugin/DYIdlePreviewDiagnostics.inc.h +++ b/大鱼调色/Plugin/DYIdlePreviewDiagnostics.inc.h @@ -23,3 +23,28 @@ NSError *idleError=nil;BOOL idleOK=[probe renderSource:source destination:destination uniforms:fresh paths:@{} spider:nil tools:doc error:&idleError]; run.record(@"idle-preview-empty-extra-skin-does-not-trigger-face-work",idleOK&&probe->faceCalls==3); } +{ + DYRenderer *fast=[[[DYRenderer alloc]init]autorelease]; + DYUniforms untouched=defaults;untouched.primarySectionEnabled=0; + Pixels wide=input; + for(NSUInteger i=0;i texture=[source metalTextureForDevice:gpu]; + MTLRegion region=MTLRegionMake2D(0,0,width,height); + [texture replaceRegion:region withBytes:wide.data() bytesPerRow:width*8]; + Pixels previewFrame=render(run,fast,source,destination,gpu,untouched,@{},@"neutral-preview-frame"); + NSError *fastError=nil;CMTime time=CMTimeMake(5,24); + BOOL rendered=[fast renderHostSource:source destination:destination uniforms:untouched paths:@{} spider:nil tools:nil colorManagement:nil hostPrimaries:-1 atTime:time error:&fastError]; + Difference delta=difference(previewFrame,read(destination,gpu)); + BOOL direct=NO,lazy=YES; + for(NSDictionary *entry in [[fast valueForKey:@"devices"]allValues]){ + for(NSString *key in entry[@"pipelines"])direct|=[key hasPrefix:@"dyNeutralInputFragment-"]; + lazy&=!entry[@"dyFilmNoise"]&&!entry[@"dyCloneStamps"]&&!entry[@"dyLensRepair"]; + } + run.record(@"neutral-direct-preserves-hdr-negative-and-alpha",rendered&&direct&&delta.maximum==0&&delta.nonfinite==0,measure(delta)); + run.record(@"neutral-render-defers-unused-gpu-pipelines",lazy); + DYScopeSample *sample=[[[fast valueForKey:@"scopeLatest"]retain]autorelease]; + run.record(@"final-scope-captured-with-neutral-output",[sample.metadata[@"timeValue"]integerValue]==5&&[sample.metadata[@"timeScale"]integerValue]==24&&sample.pixels.length==320*180*16); + [fast captureScopeTile:destination atTime:time]; + run.record(@"final-scope-inline-matches-separate-capture",[sample.pixels isEqual:[[fast valueForKey:@"scopeLatest"]pixels]]); + [texture replaceRegion:region withBytes:input.data() bytesPerRow:width*8]; +} diff --git a/大鱼调色/Plugin/DYInspector.mm b/大鱼调色/Plugin/DYInspector.mm index ff7f35b..fd94f9f 100644 --- a/大鱼调色/Plugin/DYInspector.mm +++ b/大鱼调色/Plugin/DYInspector.mm @@ -975,7 +975,7 @@ NSView *DYCreateWorkspaceMaskEditor(id id action=[self actionAPI]; if(!action)return; _refreshing=YES; uint64_t beta=DYBetaSpanBegin(@"inspector_refresh",nil); - BOOL groupingChanged=NO;NSString *recentPath=nil; + BOOL groupingChanged=NO;NSString *recentPath=nil;NSDictionary *stackDocument=nil; [action startAction:self]; @try { CMTime t=action.currentTime; @@ -985,23 +985,31 @@ NSView *DYCreateWorkspaceMaskEditor(id NSDictionary *cms=_embedded?DYReadAssets(maskHost,t).colorManagement:assets.colorManagement; NSDictionary *tools=DYReadTools(maskHost,t).document; DYInspectorToken *oldToken=nil;[get getCustomParameterValue:&oldToken fromParameter:DYInspectorParameterID atTime:t]; + BOOL wasUnified=_unified; _unified=DYUnifiedColorState(cms); + groupingChanged=wasUnified!=_unified; if(!_embedded&&!_workspaceEditor){ - [_renderOrder release];_renderOrder=[DYUnifiedRenderOrder(tools)copy]; - NSMutableDictionary *primary=nil,*output=nil;for(NSMutableDictionary *card in _cards){if([card[@"section"][@"key"]isEqual:@"primary"])primary=card;if([card[@"section"][@"key"]isEqual:@"output"])output=card;} + if(!_renderOrder||groupingChanged){ + NSMutableDictionary *primary=nil,*output=nil;for(NSMutableDictionary *card in _cards){if([card[@"section"][@"key"]isEqual:@"primary"])primary=card;if([card[@"section"][@"key"]isEqual:@"output"])output=card;} NSMutableArray *body=[NSMutableArray arrayWithArray:primary[@"body"]]; for(NSView *row in output[@"body"]){if([row.identifier isEqual:@"toolMasks"])continue;[body removeObjectIdenticalTo:row];[(_unified?output:primary)[@"view"]addSubview:row];if(!_unified)[body addObject:row];} - primary[@"body"]=body; + primary[@"body"]=body; + } + NSArray *order=DYUnifiedRenderOrder(tools); + if(![_renderOrder isEqualToArray:order]){[_renderOrder release];_renderOrder=[order copy];} } - NSDictionary *initialTools=tools; - for(NSMutableDictionary *card in _cards){NSString *type=card[@"section"][@"key"];card[@"removed"]=@([type isEqual:@"output"]?!_unified:!_embedded&&DYBaseToolRemoved(initialTools,type));} - NSMutableDictionary *graphicValues=[NSMutableDictionary dictionary]; + NSMutableDictionary *graphicValues=[NSMutableDictionary dictionary],*readValues=[NSMutableDictionary dictionary]; + auto readValue=[&](NSNumber *pid,double fallback){ + if(!pid)return fallback; + NSNumber *cached=readValues[pid];if(cached)return cached.doubleValue; + double value=fallback;[get getFloatValue:&value fromParameter:pid.unsignedIntValue atTime:t]; + if(!std::isfinite(value))value=fallback; + readValues[pid]=@(value);return value; + }; for(NSNumber *pid in _controls) { - NSDictionary *r=_controls[pid],*d=r[@"descriptor"]; double v=[d[@"default"] doubleValue]; - [get getFloatValue:&v fromParameter:pid.unsignedIntValue atTime:t]; - if(!std::isfinite(v))v=[d[@"default"] doubleValue]; + NSDictionary *r=_controls[pid],*d=r[@"descriptor"];double v=readValue(pid,[d[@"default"]doubleValue]); graphicValues[d[@"key"]]=@(v); - if(d[@"enabled"]) {double enabled=1;[get getFloatValue:&enabled fromParameter:[d[@"enabled"] unsignedIntValue] atTime:t];[r[@"itemEnabled"] setState:enabled>=.5?NSControlStateValueOn:NSControlStateValueOff];[r[@"itemEnabled"] setImage:[NSImage imageWithSystemSymbolName:enabled>=.5?@"eye":@"eye.slash" accessibilityDescription:enabled>=.5?@"启用":@"旁路"]];for(NSString *control in @[@"slider",@"field",@"popup"]) [r[control] setAlphaValue:enabled>=.5?1:.45];} + if(d[@"enabled"]) {double enabled=readValue(d[@"enabled"],1);[r[@"itemEnabled"] setState:enabled>=.5?NSControlStateValueOn:NSControlStateValueOff];[r[@"itemEnabled"] setImage:[NSImage imageWithSystemSymbolName:enabled>=.5?@"eye":@"eye.slash" accessibilityDescription:enabled>=.5?@"启用":@"旁路"]];for(NSString *control in @[@"slider",@"field",@"popup"]) [r[control] setAlphaValue:enabled>=.5?1:.45];} [r[@"slider"] setDoubleValue:v]; [r[@"field"] setStringValue:DYNumber(v,d)]; [r[@"toggle"] setState:v>=.5?NSControlStateValueOn:NSControlStateValueOff]; NSPopUpButton *popup=r[@"popup"]; if(popup.numberOfItems>0){NSArray *values=d[@"values"];NSInteger index=values?[values indexOfObject:@((int)llround(v))]:(NSInteger)llround(v);[popup selectItemAtIndex:index==NSNotFound?0:MAX(0,MIN(index,popup.numberOfItems-1))];} @@ -1010,9 +1018,8 @@ NSView *DYCreateWorkspaceMaskEditor(id for(id graphic in _graphics)[graphic setValues:graphicValues]; for(NSMutableDictionary *c in _cards) { NSNumber *pid=c[@"section"][@"enabled"]; - double v=[c[@"section"][@"defaultEnabled"]doubleValue];if(pid)[get getFloatValue:&v fromParameter:pid.unsignedIntValue atTime:t]; - NSNumber *extra=c[@"section"][@"extraEnabled"];double extraValue=0; - if(extra)[get getFloatValue:&extraValue fromParameter:extra.unsignedIntValue atTime:t]; + double v=readValue(pid,[c[@"section"][@"defaultEnabled"]doubleValue]); + double extraValue=readValue(c[@"section"][@"extraEnabled"],0); BOOL enabled=v>=.5||extraValue>=.5; NSNumber *saved=[oldToken isKindOfClass:DYInspectorToken.class]?oldToken.folds[c[@"section"][@"key"]]:nil; BOOL collapsed=_workspaceEditor?NO:saved?saved.boolValue:![self initiallyExpandedSection:c[@"section"][@"key"]]; @@ -1036,24 +1043,25 @@ NSView *DYCreateWorkspaceMaskEditor(id _tabs[@"managedColor"]=@(cms.count>0&&!DYPrimaryColorState(cms));_tabs[@"primaryCMS"]=@(DYPrimaryColorState(cms));[_managedPanel refreshWithState:assets.colorManagement context:[_renderer colorContext]];[_managedPanel setInputLUTPath:assets.paths[@"input"]];for(NSDictionary *r in _controls.allValues)if([r[@"descriptor"][@"key"]isEqual:@"cmmix"])[r[@"label"]setStringValue:([_tabs[@"managedColor"]boolValue]||[_tabs[@"primaryCMS"]boolValue])?@"调色混合":@"CST 混合"]; for(NSDictionary *c in _cards)if([c[@"section"][@"key"]isEqual:@"primary"]){[c[@"enabled"]setToolTip:([_tabs[@"managedColor"]boolValue]||_unified)?@"启停此层一级调色;全局色彩管理保持当前方式":@"启停此层输入、一级调色与输出转换"];[c[@"enabled"]setAccessibilityHelp:[c[@"enabled"]toolTip]];} [_spiderPanel setMesh:assets.spiderMesh linked:assets.spiderLinked]; - double profile=0,configured=0;[get getFloatValue:&profile fromParameter:2013 atTime:t];[get getFloatValue:&configured fromParameter:2236 atTime:t]; + double profile=readValue(@2013,0),configured=readValue(@2236,0); _tabs[@"legacyInput"]=@(configured<.5&&(configured<0||profile>.5||[assets.paths[@"input"]length]||oldToken.schema<2)); for(NSString *key in _assetButtons) { NSString *path=assets.paths[key]; NSButton *button=_assetButtons[key][@"choose"]; NSString *name=path.length?path.lastPathComponent.stringByDeletingPathExtension:@"无"; - if([key isEqual:@"input"]&&!path.length){double profile=0;[get getFloatValue:&profile fromParameter:2013 atTime:t];for(NSDictionary *d in DYDescriptors())if([d[@"key"]isEqual:@"inputProfile"]){NSArray *options=d[@"options"];NSInteger index=MAX(0,MIN((NSInteger)llround(profile),(NSInteger)options.count-1));name=options[index];break;}} + if([key isEqual:@"input"]&&!path.length){for(NSDictionary *d in DYDescriptors())if([d[@"key"]isEqual:@"inputProfile"]){NSArray *options=d[@"options"];NSInteger index=MAX(0,MIN((NSInteger)llround(profile),(NSInteger)options.count-1));name=options[index];break;}} button.title=_assetLoads[key]?@"正在载入…":name; button.toolTip=path.length?path:@"选择输入转换或 LUT;点击网格图标浏览缩略图"; [_assetButtons[key][@"remove"] setEnabled:path.length>0]; - NSButton *eye=_assetButtons[key][@"eye"];if(eye){NSInteger slot=[[key substringFromIndex:4]integerValue];double enabled=1;[get getFloatValue:&enabled fromParameter:2040+(UInt32)slot-1 atTime:t];eye.state=enabled>=.5?NSControlStateValueOn:NSControlStateValueOff;eye.image=[NSImage imageWithSystemSymbolName:enabled>=.5?@"eye":@"eye.slash" accessibilityDescription:enabled>=.5?@"启用":@"旁路"];} + NSButton *eye=_assetButtons[key][@"eye"];if(eye){NSInteger slot=[[key substringFromIndex:4]integerValue];double enabled=readValue(@(2040+(UInt32)slot-1),1);eye.state=enabled>=.5?NSControlStateValueOn:NSControlStateValueOff;eye.image=[NSImage imageWithSystemSymbolName:enabled>=.5?@"eye":@"eye.slash" accessibilityDescription:enabled>=.5?@"启用":@"旁路"];} } if(_recentBrowser)recentPath=[assets.paths[@"look0"]copy]; for(NSInteger i=1;i<5;i++)if([assets.paths[[NSString stringWithFormat:@"look%ld",(long)i]]length])_visibleLooks=MAX(_visibleLooks,i+1); [self setNeedsLayout:YES]; + if(!_embedded&&!_workspaceEditor)stackDocument=[[tools copy]autorelease]; } @finally { [action endAction:self]; _refreshing=NO; } [_recentBrowser refreshRecentSelection:recentPath];[recentPath release]; // Remote layout/accessibility can re-enter the host. Let the parameter // action and current callback unwind before notifying the remote view. - if(!_embedded&&!_workspaceEditor)[self synchronizeTools]; + if(stackDocument)[self synchronizeTools:stackDocument]; DYBetaSpanEnd(beta,nil); if(groupingChanged)dispatch_async(dispatch_get_main_queue(),^{NSAccessibilityPostNotification(self,NSAccessibilityLayoutChangedNotification);}); } diff --git a/大鱼调色/Plugin/DYManagedRender.inc.h b/大鱼调色/Plugin/DYManagedRender.inc.h index 5c1cc89..d9bee86 100644 --- a/大鱼调色/Plugin/DYManagedRender.inc.h +++ b/大鱼调色/Plugin/DYManagedRender.inc.h @@ -1,18 +1,14 @@ - (void)managedPreview:(id)texture origin:(FxImageOrigin)origin entry:(NSMutableDictionary*)entry { @synchronized(_previewLock){if(_exporting||CACurrentMediaTime()-_lastPreview<=.5)return;} - idp=[self managedKernel:@"dyManagedPreview" entry:entry error:nil];if(!p)return; + idp=[self computePipeline:@"dyManagedPreview" entry:entry error:nil];if(!p)return; idb=[entry[@"device"]newBufferWithLength:320*180*16 options:MTLResourceStorageModeShared];if(!b)return; idcb=[entry[@"queue"]commandBuffer];idce=[cb computeCommandEncoder];[ce setComputePipelineState:p];[ce setTexture:texture atIndex:0];[ce setBuffer:b offset:0 atIndex:0];[ce dispatchThreads:MTLSizeMake(320,180,1) threadsPerThreadgroup:MTLSizeMake(8,8,1)];[ce endEncoding];[cb commit];[cb waitUntilCompleted]; if(cb.status==MTLCommandBufferStatusCompleted){@synchronized(_previewLock){[_preview release];_preview=[[NSData alloc]initWithBytes:b.contents length:b.length];[_lookLUTPreview release];if(origin==kFxImageOrigin_BOTTOM_LEFT){NSMutableData *flipped=[NSMutableData dataWithLength:b.length];for(NSUInteger y=0;y<180;y++)memcpy((uint8_t*)flipped.mutableBytes+y*320*16,(uint8_t*)b.contents+(179-y)*320*16,320*16);_lookLUTPreview=[flipped copy];}else _lookLUTPreview=[_preview retain];_lastPreview=CACurrentMediaTime();}dispatch_async(dispatch_get_main_queue(),^{[NSNotificationCenter.defaultCenter postNotificationName:@"DYPreviewDidChange" object:self];});}[b release]; } // Included in DYRenderer. V1 callers and their ABI remain on renderSource:...tools:error:. - (NSDictionary*)colorContext {@synchronized(_previewLock){return [[_colorContext copy]autorelease];}} -- (id)managedKernel:(NSString*)name entry:(NSMutableDictionary*)entry error:(NSError**)error { - NSMutableDictionary *cache=entry[@"managedKernels"];if(!cache){cache=[NSMutableDictionary dictionary];entry[@"managedKernels"]=cache;} - idpipeline=cache[name];if(!pipeline){idf=[entry[@"library"]newFunctionWithName:name];if(!f){fail(error,[@"色彩管理内核缺失:" stringByAppendingString:name]);return nil;}pipeline=[entry[@"device"]newComputePipelineStateWithFunction:f error:error];[f release];if(!pipeline)return nil;cache[name]=pipeline;[pipeline release];}return pipeline; -} - (BOOL)managedDispatch:(NSString*)name textures:(NSArray*)textures data:(const void*)data length:(NSUInteger)length extra:(const void*)extra extraLength:(NSUInteger)extraLength entry:(NSMutableDictionary*)entry error:(NSError**)error { - idpipeline=[self managedKernel:name entry:entry error:error];if(!pipeline)return NO; + 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); } - (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 { @@ -44,7 +40,8 @@ if(image.left!=bounds.left||image.right!=bounds.right||image.top!=bounds.top||image.bottom!=bounds.bottom){ fail(error,@"仿制图章需要宿主提供完整的源画面。");return nil; } - NSDictionary *entry=[self device:registry error:error];if(!entry)return nil; + NSMutableDictionary *entry=[self device:registry error:error];if(!entry)return nil; + id pipeline=[self computePipeline:@"dyCloneStamps" entry:entry error:error];if(!pipeline)return nil; iddevice=entry[@"device"]; idinput=[source metalTextureForDevice:device]; if(!input||input.framebufferOnly){fail(error,@"仿制图章无法读取源画面。");return nil;} @@ -55,7 +52,7 @@ idencoder=[commands computeCommandEncoder]; if(!output||!encoder){fail(error,@"无法分配仿制图章缓冲区。");return nil;} uint32_t count=(uint32_t)stamps.size(),flip=source.imageOrigin==kFxImageOrigin_BOTTOM_LEFT; - [encoder setComputePipelineState:entry[@"dyCloneStamps"]]; + [encoder setComputePipelineState:pipeline]; [encoder setTexture:input atIndex:0];[encoder setTexture:output atIndex:1]; [encoder setBytes:stamps.data() length:count*sizeof(DYCloneStamp) atIndex:0]; [encoder setBytes:&count length:sizeof(count) atIndex:1];[encoder setBytes:&flip length:sizeof(flip) atIndex:2]; @@ -120,7 +117,7 @@ auto convert=[&](dycm::Space a,dycm::Space b,NSInteger display=0,BOOL gamut=NO){idout=next();if(!out)return fail(error,@"无法分配色彩管理缓冲区。");BOOL ok=[self managedConvert:a to:b display:display gamut:gamut input:current output:out entry:entry error:error];if(ok)current=out;return ok;}; auto profile=[&](DYColorProfile*p){idout=next();if(!out)return fail(error,@"无法分配颜色配置缓冲区。");BOOL ok=[self managedProfile:p input:current output:out entry:entry error:error];if(ok)current=out;return ok;}; auto tile=[&](idtexture){DYExportTile*t=[[[DYExportTile alloc]initWithTexture:texture registry:d.registryID]autorelease];[t setBounds:src.tilePixelBounds origin:src.imageOrigin];[t setPixelAspect:src.pixelAspect];return t;}; - auto blend=[&](idbefore,NSArray*masks,NSString*type){if(!masks.count)return YES;idout=next(before);if(!out)return fail(error,@"无法分配工作空间蒙版缓冲区。");DYToolMaskHeader h{};idmb=[self maskBuffer:@{type:masks} tile:src device:d header:&h];h.section=(int)[DYToolTypes()indexOfObject:type];idp=[self managedKernel:@"dyManagedBlend" entry:entry error:error];if(!mb||!p)return NO;idcb=[entry[@"queue"]commandBuffer];idce=[cb computeCommandEncoder];[ce setComputePipelineState:p];[ce setTexture:before atIndex:0];[ce setTexture:current atIndex:1];[ce setTexture:out atIndex:2];[ce setBuffer:mb offset:0 atIndex:0];[ce setBytes:&h length:sizeof(h) atIndex:1];[ce dispatchThreads:MTLSizeMake(source.width,source.height,1) threadsPerThreadgroup:MTLSizeMake(16,16,1)];[ce endEncoding];[cb commit];[cb waitUntilCompleted];if(cb.status!=MTLCommandBufferStatusCompleted)return fail(error,cb.error.localizedDescription);current=out;return YES;}; + auto 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");}; @try{try{ diff --git a/大鱼调色/Plugin/DYMosaicRender.inc.h b/大鱼调色/Plugin/DYMosaicRender.inc.h index 2627fcb..7408f3c 100644 --- a/大鱼调色/Plugin/DYMosaicRender.inc.h +++ b/大鱼调色/Plugin/DYMosaicRender.inc.h @@ -52,7 +52,7 @@ idbuffer=[self maskBuffer:face?@{}:@{@"primary":masks} tile:src device:device header:&header];_faceEntries=skinEntries; MTLTextureDescriptor *desc=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA32Float width:input.width height:input.height mipmapped:NO];desc.storageMode=MTLStorageModePrivate;desc.usage=MTLTextureUsageShaderRead|MTLTextureUsageShaderWrite; idoutput=[[device newTextureWithDescriptor:desc]autorelease]; - idpipeline=[self managedKernel:@"dyLocalMosaic" entry:entry error:error]; + idpipeline=[self computePipeline:@"dyLocalMosaic" entry:entry error:error]; if(!input||!buffer||!output||!pipeline){fail(error,@"局部马赛克缓冲区不可用。");return nil;} // Size is in 1080-line reference pixels, stable under proxy/viewer scaling. uint32_t block=(uint32_t)MAX(2,round([settings[@"size"]doubleValue]*input.height/1080.)); diff --git a/大鱼调色/Plugin/DYPlugIn.mm b/大鱼调色/Plugin/DYPlugIn.mm index d53166f..2873ba2 100644 --- a/大鱼调色/Plugin/DYPlugIn.mm +++ b/大鱼调色/Plugin/DYPlugIn.mm @@ -44,13 +44,46 @@ if(!_modelRefreshPending.exchange(true)){id host=_apiManager;dispatch_async(dispatch_get_main_queue(),^{self->_modelRefreshPending.store(false);[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:host];});}return YES;} - (BOOL)pluginState:(NSData**)state atTime:(CMTime)t quality:(FxQuality)q error:(NSError**)e{ uint64_t stateSpan=DYBetaSpanBegin(@"plugin_state",nil);@try{ - DYUniforms u;DYReadUniforms(_apiManager,t,&u);CMTime frameDuration=kCMTimeInvalid,origin=kCMTimeZero;idtiming=[_apiManager apiForProtocol:@protocol(FxTimingAPI_v4)];if([timing respondsToSelector:@selector(frameDuration:)])[timing frameDuration:&frameDuration];if([timing respondsToSelector:@selector(startTimeForEffect:)])[timing startTimeForEffect:&origin];int64_t frame=DYFilmFrameIndex(t,frameDuration,origin);u.filmFrameKey=DYFilmFrameKey(frame,u.film.grainHold,u.film.grainSeed);DYAssetState*a=DYReadAssets(_apiManager,t);DYToolDocument *tools=DYReadTools(_apiManager,t);[self adoptToolCanvasDocument:tools.document];[_viewerParameterBridge publishUniforms:&u document:tools.document atTime:t];[_viewerParameterBridge publishAssets:a atTime:t];double copyAuto=0;[[_apiManager apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)]getFloatValue:©Auto fromParameter:8800 atTime:t];NSDictionary *snapshot=DYToolRenderSnapshot(tools.document,t);for(NSMutableDictionary *node in snapshot[@"layers"])if([node[@"type"]isEqual:@"film"]){DYUniforms layer=DYToolUniforms(node);node[@"filmFrameKey"]=@(DYFilmFrameKey(frame,layer.film.grainHold,layer.film.grainSeed));}NSInteger primaries=-1;idgamut=[_apiManager apiForProtocol:@protocol(FxColorGamutAPI_v2)];if([gamut respondsToSelector:@selector(colorPrimaries)])primaries=gamut.colorPrimaries;NSDictionary*s=@{@"colorManagement":a.colorManagement?:@{},@"hostPrimaries":@(primaries),@"schema":@2,@"tools":snapshot,@"copyAuto":@(copyAuto>.5),@"uniforms":[NSData dataWithBytes:&u length:sizeof(u)],@"paths":a.paths?:@{},@"spider":a.spiderMesh?:[NSData data]};*state=[NSPropertyListSerialization dataWithPropertyList:s format:NSPropertyListBinaryFormat_v1_0 options:0 error:e];return *state!=nil; + DYUniforms u;DYReadUniforms(_apiManager,t,&u); + DYAssetState *assets=DYReadAssets(_apiManager,t); + DYToolDocument *tools=DYReadTools(_apiManager,t); + [self adoptToolCanvasDocument:tools.document]; + [_viewerParameterBridge publishUniforms:&u document:tools.document atTime:t]; + [_viewerParameterBridge publishAssets:assets atTime:t]; + double copyAuto=0; + [[_apiManager apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)]getFloatValue:©Auto fromParameter:8800 atTime:t]; + NSDictionary *snapshot=DYToolRenderSnapshot(tools.document,t); + // Host timing is needed only for an active time-varying grain pass. + BOOL hasFilmFrame=NO; + int64_t frame=0; + auto filmFrame=[&]{ + if(!hasFilmFrame){ + CMTime duration=kCMTimeInvalid,origin=kCMTimeZero; + id timing=[_apiManager apiForProtocol:@protocol(FxTimingAPI_v4)]; + if([timing respondsToSelector:@selector(frameDuration:)])[timing frameDuration:&duration]; + if([timing respondsToSelector:@selector(startTimeForEffect:)])[timing startTimeForEffect:&origin]; + frame=DYFilmFrameIndex(t,duration,origin);hasFilmFrame=YES; + } + return frame; + }; + if(!DYBaseToolRemoved(snapshot,@"film")&&u.film.enabled>.5&&u.film.mix>0&&DYFilmGrainActive(u.film)) + u.filmFrameKey=DYFilmFrameKey(filmFrame(),u.film.grainHold,u.film.grainSeed); + for(NSMutableDictionary *node in snapshot[@"layers"])if([node[@"type"]isEqual:@"film"]){ + DYFilmSettings film=DYToolUniforms(node).film; + if(film.enabled>.5&&film.mix>0&&DYFilmGrainActive(film))node[@"filmFrameKey"]=@(DYFilmFrameKey(filmFrame(),film.grainHold,film.grainSeed)); + } + NSInteger primaries=-1; + id gamut=[_apiManager apiForProtocol:@protocol(FxColorGamutAPI_v2)]; + if([gamut respondsToSelector:@selector(colorPrimaries)])primaries=gamut.colorPrimaries; + NSDictionary *s=@{@"colorManagement":assets.colorManagement?:@{},@"hostPrimaries":@(primaries),@"schema":@2,@"tools":snapshot,@"copyAuto":@(copyAuto>.5),@"uniforms":[NSData dataWithBytes:&u length:sizeof(u)],@"paths":assets.paths?:@{},@"spider":assets.spiderMesh?:[NSData data]}; + *state=[NSPropertyListSerialization dataWithPropertyList:s format:NSPropertyListBinaryFormat_v1_0 options:0 error:e]; + return *state!=nil; }@finally{DYBetaSpanEnd(stateSpan,nil);} } - (BOOL)destinationImageRect:(FxRect*)rect sourceImages:(NSArray*)src destinationImage:(FxImageTile*)dst pluginState:(NSData*)s atTime:(CMTime)t error:(NSError**)e{if(!src.count)return NO;*rect=src[0].imagePixelBounds;return YES;} - (BOOL)sourceTileRect:(FxRect*)rect sourceImageIndex:(NSUInteger)i sourceImages:(NSArray*)src destinationTileRect:(FxRect)dstRect destinationImage:(FxImageTile*)dst pluginState:(NSData*)s atTime:(CMTime)t error:(NSError**)e{if(i>=src.count)return NO;*rect=src[i].imagePixelBounds;return YES;} - (BOOL)renderDestinationImage:(FxImageTile*)dst sourceImages:(NSArray*)src pluginState:(NSData*)s atTime:(CMTime)t error:(NSError**)e{ - if(!src.count||!src[0].ioSurface||!dst.ioSurface||!s.length)return NO;NSDictionary*p=[NSPropertyListSerialization propertyListWithData:s options:NSPropertyListImmutable format:NULL error:e];if(![p isKindOfClass:NSDictionary.class])return NO;NSData*b=p[@"uniforms"];if(![@[@1,@2]containsObject:p[@"schema"]]||![b isKindOfClass:NSData.class]||b.length!=sizeof(DYUniforms)||![p[@"paths"]isKindOfClass:NSDictionary.class])return NO;DYUniforms u;[b getBytes:&u length:sizeof(u)];uint64_t renderSpan=DYBetaSpanBegin(@"render",@{@"width":@(src[0].ioSurface.width),@"height":@(src[0].ioSurface.height),@"layer_count":@([p[@"tools"][@"layers"]count])});uint64_t beta=!_betaFirstRenderStarted.exchange(true)?DYBetaSpanBegin(@"first_render",nil):0;BOOL ok=NO;@try{ok=[_renderer renderSource:src[0] destination:dst uniforms:u paths:p[@"paths"] spider:p[@"spider"] tools:p[@"tools"] colorManagement:p[@"colorManagement"] hostPrimaries:p[@"hostPrimaries"]?[p[@"hostPrimaries"]integerValue]:-1 error:e];}@finally{DYBetaSpanEnd(renderSpan,@{@"status":ok?@"passed":@"failed"});}DYBetaSpanEnd(beta,@{@"status":ok?@"passed":@"failed"});if(!ok)DYBetaEvent(@"render_error",DYBetaErrorFields((e&&*e)?*e:nil,@"render_source"));if(ok){[_renderer captureScopeTile:dst atTime:t];@synchronized(self){ + if(!src.count||!src[0].ioSurface||!dst.ioSurface||!s.length)return NO;NSDictionary*p=[NSPropertyListSerialization propertyListWithData:s options:NSPropertyListImmutable format:NULL error:e];if(![p isKindOfClass:NSDictionary.class])return NO;NSData*b=p[@"uniforms"];if(![@[@1,@2]containsObject:p[@"schema"]]||![b isKindOfClass:NSData.class]||b.length!=sizeof(DYUniforms)||![p[@"paths"]isKindOfClass:NSDictionary.class])return NO;DYUniforms u;[b getBytes:&u length:sizeof(u)];uint64_t renderSpan=DYBetaSpanBegin(@"render",@{@"width":@(src[0].ioSurface.width),@"height":@(src[0].ioSurface.height),@"layer_count":@([p[@"tools"][@"layers"]count])});uint64_t beta=!_betaFirstRenderStarted.exchange(true)?DYBetaSpanBegin(@"first_render",nil):0;BOOL ok=NO;@try{ok=[_renderer renderHostSource:src[0] destination:dst uniforms:u paths:p[@"paths"] spider:p[@"spider"] tools:p[@"tools"] colorManagement:p[@"colorManagement"] hostPrimaries:p[@"hostPrimaries"]?[p[@"hostPrimaries"]integerValue]:-1 atTime:t error:e];}@finally{DYBetaSpanEnd(renderSpan,@{@"status":ok?@"passed":@"failed"});}DYBetaSpanEnd(beta,@{@"status":ok?@"passed":@"failed"});if(!ok)DYBetaEvent(@"render_error",DYBetaErrorFields((e&&*e)?*e:nil,@"render_source"));if(ok){@synchronized(self){ FxRect image=src[0].imagePixelBounds; double aspect=src[0].pixelAspect,height=image.top-image.bottom,width=image.right-image.left; _toolSourceAspect=width>0&&height>0&&std::isfinite(aspect)&&aspect>0?width*aspect/height:0; diff --git a/大鱼调色/Plugin/DYPrimaryRender.inc.h b/大鱼调色/Plugin/DYPrimaryRender.inc.h index 2679ddf..25a2fa6 100644 --- a/大鱼调色/Plugin/DYPrimaryRender.inc.h +++ b/大鱼调色/Plugin/DYPrimaryRender.inc.h @@ -12,7 +12,7 @@ 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 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 managedKernel:@"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;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 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};} diff --git a/大鱼调色/Plugin/DYRenderer.h b/大鱼调色/Plugin/DYRenderer.h index b3b519c..e91a623 100644 --- a/大鱼调色/Plugin/DYRenderer.h +++ b/大鱼调色/Plugin/DYRenderer.h @@ -43,5 +43,6 @@ - (NSDictionary *)scopeMetadata; - (NSDictionary*)colorContext; - (BOOL)renderSource:(FxImageTile*)source destination:(FxImageTile*)destination uniforms:(DYUniforms)uniforms paths:(NSDictionary*)paths spider:(NSData*)spider tools:(NSDictionary*)tools colorManagement:(NSDictionary*)state hostPrimaries:(NSInteger)primaries error:(NSError**)error; +- (BOOL)renderHostSource:(FxImageTile*)source destination:(FxImageTile*)destination uniforms:(DYUniforms)uniforms paths:(NSDictionary*)paths spider:(NSData*)spider tools:(NSDictionary*)tools colorManagement:(NSDictionary*)state hostPrimaries:(NSInteger)primaries atTime:(CMTime)time error:(NSError**)error; - (BOOL)exportLUT:(NSURL*)url uniforms:(DYUniforms)uniforms paths:(NSDictionary*)paths spider:(NSData*)spider tools:(NSDictionary*)tools colorManagement:(NSDictionary*)state error:(NSError**)error; @end diff --git a/大鱼调色/Plugin/DYRenderer.mm b/大鱼调色/Plugin/DYRenderer.mm index c538716..53f0dae 100644 --- a/大鱼调色/Plugin/DYRenderer.mm +++ b/大鱼调色/Plugin/DYRenderer.mm @@ -70,13 +70,15 @@ static void bypassNeutralTools(DYUniforms *u){ if(neutral)for(NSDictionary *row in DYDescriptors())if([row[@"pid"]isEqual:section[@"enabled"]])*(float*)((uint8_t*)u+[row[@"offset"]unsignedIntegerValue])=0; } } +static BOOL hasLegacyGrade(const DYUniforms &u){ + if(u.curveSectionEnabled>.5||u.hslSectionEnabled>.5||u.colorGradingSectionEnabled>.5||u.primariesSectionEnabled>.5||u.levelsSectionEnabled>.5||u.blackWhiteSectionEnabled>.5||u.colorBalanceSectionEnabled>.5)return YES; + if(u.preLUTStrength!=0||u.postLUTStrength!=0||simd_any(u.extraPostLUTStrengths!=0))return YES; + const float *values=&u.exposure,*enabled=&u.exposureEnabled; + for(int i=0;i<13;i++){BOOL group=(i>=6&&i<=9)?u.colorSectionEnabled>.5:u.baseSectionEnabled>.5;if(group&&enabled[i]>.5&&values[i]!=0)return YES;} + return NO; +} static void bypassIdleSkin(DYUniforms *u){ - if(u->skinVisualize>.5)return; - if(u->curveSectionEnabled>.5||u->hslSectionEnabled>.5||u->colorGradingSectionEnabled>.5||u->primariesSectionEnabled>.5||u->levelsSectionEnabled>.5||u->blackWhiteSectionEnabled>.5||u->colorBalanceSectionEnabled>.5)return; - if(u->preLUTStrength!=0||u->postLUTStrength!=0||simd_any(u->extraPostLUTStrengths!=0))return; - const float *values=&u->exposure,*enabled=&u->exposureEnabled; - for(int i=0;i<13;i++){BOOL group=(i>=6&&i<=9)?u->colorSectionEnabled>.5:u->baseSectionEnabled>.5;if(group&&enabled[i]>.5&&values[i]!=0)return;} - u->skinProtection.x=0; + if(u->skinVisualize<=.5&&!hasLegacyGrade(*u))u->skinProtection.x=0; } // Decide face work from the same effective operations that textures: and the // legacy renderer actually execute. Saved strengths remain 1 for empty LUT @@ -124,6 +126,11 @@ static NSArray *DYPrimaryActiveFinishing(DYUniforms u,NSDictionary *paths,NSData NSDictionary*rootPaths=visiblePaths(paths,u);u=normalize(u);NSMutableDictionary*doc=DYMutablePlist(tools);for(NSMutableDictionary*node in doc[@"layers"]){DYUniforms original=DYToolUniforms(node),v=normalize(original);NSMutableDictionary*values=[NSMutableDictionary dictionary];for(NSDictionary*d in DYBaseToolDescriptors(node[@"type"]))if([d[@"offset"]integerValue]>=0)values[d[@"key"]]=@(*(float*)((uint8_t*)&v+[d[@"offset"]unsignedIntegerValue]));node[@"values"]=values;node[@"paths"]=visiblePaths(node[@"paths"],original);} return DYManagedActiveFinishing(u,rootPaths,spider,doc); } +struct DYScopeReadback { + id buffer; + NSUInteger generation; + uint64_t serial; +}; @interface DYRenderer(){ NSMutableDictionary *_devices,*_luts,*_preparedLUTs; NSSet *_activeLUTPaths; @@ -142,6 +149,9 @@ static NSArray *DYPrimaryActiveFinishing(DYUniforms u,NSDictionary *paths,NSData NSUInteger _scopeGeneration; DYScopeSample *_scopePending,*_scopeLatest; uint64_t _scopeCaptureSerial,_scopeLatestSerial;CMTime _scopeRequestedTime; + FxImageTile *_scopeDestination; // borrowed for one locked host render + CMTime _scopeRenderTime; + BOOL _scopeCaptured; NSData *_scopePreview; NSDictionary *_scopeMetadata; DYColorProfile *_scopeProfile; @@ -149,6 +159,22 @@ static NSArray *DYPrimaryActiveFinishing(DYUniforms u,NSDictionary *paths,NSData } @end @implementation DYRenderer +// The caller holds the renderer lock. Unused tools never load a GPU function. +- (id)computePipeline:(NSString *)name entry:(NSMutableDictionary *)entry error:(NSError **)error { + id pipeline=entry[name]; + if(pipeline)return pipeline; + id library=entry[@"library"]; + id device=entry[@"device"]; + id function=[library newFunctionWithName:name]; + if(!function){fail(error,[name stringByAppendingString:@" 缺失"]);return nil;} + uint64_t span=DYBetaSpanBegin(@"gpu_pipeline",@{@"pipeline":name,@"gpu":device.name?:@"unknown"}); + pipeline=[device newComputePipelineStateWithFunction:function error:error]; + DYBetaSpanEnd(span,@{@"status":pipeline?@"passed":@"failed"}); + [function release]; + if(!pipeline)return nil; + entry[name]=pipeline; + return [pipeline autorelease]; +} #include "DYScopeCapture.inc.h" #include "DYFilmRender.inc.h" #include "DYPrimaryRender.inc.h" @@ -192,7 +218,6 @@ static NSArray *DYPrimaryActiveFinishing(DYUniforms u,NSDictionary *paths,NSData NSURL*url=[[NSBundle bundleForClass:self.class]URLForResource:@"default" withExtension:@"metallib"]; idlib=[d newLibraryWithURL:url error:err];if(!lib){[d release];return nil;} idq=[d newCommandQueue];entry=[NSMutableDictionary dictionaryWithDictionary:@{@"device":d,@"library":lib,@"queue":q,@"pipelines":[NSMutableDictionary dictionary]}]; - for(NSString*fn in @[@"dyLensRepair",@"dyUnpremultiply",@"dyWhitesSceneStatistics",@"dyLUTExportKernel",@"dyInputAnalysis",@"dyScopeSample",@"dyCloneStamps",@"dyColorManagement",@"dyToolBlend",@"dyToolSkin",@"dyFilmPoint",@"dyFilmNoise",@"dyFilmSparseBlur",@"dyFilmBloomEdges",@"dyFilmMix",@"dyFilmPrint"]){idf=[lib newFunctionWithName:fn];if(!f){fail(err,[fn stringByAppendingString:@" 缺失"]);[lib release];[q release];[d release];return nil;}uint64_t pipelineSpan=DYBetaSpanBegin(@"gpu_pipeline",@{@"pipeline":fn,@"gpu":d.name?:@"unknown"});idp=[d newComputePipelineStateWithFunction:f error:err];DYBetaSpanEnd(pipelineSpan,@{@"status":p?@"passed":@"failed"});[f release];if(!p){[lib release];[q release];[d release];return nil;}entry[fn]=p;[p release];} float identity[32];for(int z=0;z<2;z++)for(int y=0;y<2;y++)for(int x=0;x<2;x++){int i=((z*2+y)*2+x)*4;identity[i]=x;identity[i+1]=y;identity[i+2]=z;identity[i+3]=1;}idneutral=texture3D(d,identity,2);if(!neutral){fail(err,@"无法分配中性 LUT");return nil;}entry[@"identity"]=neutral; // Preparing before the first frame may use registry 0. Reuse those pipelines // when the host subsequently supplies that device's actual registry ID. @@ -210,7 +235,7 @@ static NSArray *DYPrimaryActiveFinishing(DYUniforms u,NSDictionary *paths,NSData - (NSArray*)textures:(NSDictionary*)paths uniforms:(DYUniforms*)u entry:(NSDictionary*)e error:(NSError**)err{ // Normalize only this render copy. Disabled groups retain their host parameters // and paths, while inactive LUTs neither load files nor affect any layer. - BOOL inputEnabled=u->inputSectionEnabled>.5&&!managed(*u,paths); + BOOL inputEnabled=u->inputSectionEnabled>.5&&!managed(*u,paths)&&u->preLUTStrength>0; NSString*input=inputEnabled?paths[@"input"]:nil;int profile=inputEnabled?(int)roundf(u->inputProfile):0; if(!inputEnabled){u->inputProfile=0;u->preLUTStrength=0;} if(!input.length&&profile>0&&profile<(int)inputFiles().count)input=[[NSBundle bundleForClass:self.class]pathForResource:inputFiles()[profile] ofType:@"dylut" inDirectory:@"InputLUTs"]; @@ -218,10 +243,20 @@ static NSArray *DYPrimaryActiveFinishing(DYUniforms u,NSDictionary *paths,NSData NSMutableArray*ts=[NSMutableArray array];idt=[self lut:input entry:e error:err];if(!t)return nil;[ts addObject:t];if(!input.length)u->preLUTStrength=0; BOOL looksEnabled=u->lookSectionEnabled>.5; if(!looksEnabled)u->extraLookSectionEnableds=(DYFloat4){0,0,0,0}; - for(int i=0;i<5;i++){BOOL active=looksEnabled&&(i==0||u->extraLookSectionEnableds[i-1]>.5);NSString*p=active?paths[[NSString stringWithFormat:@"look%d",i]]:nil;t=[self lut:p entry:e error:err];if(!t)return nil;[ts addObject:t];if(!p.length){if(i==0)u->postLUTStrength=0;else u->extraPostLUTStrengths[i-1]=0;}} + for(int i=0;i<5;i++){BOOL active=looksEnabled&&(i==0?u->postLUTStrength>0:u->extraLookSectionEnableds[i-1]>.5&&u->extraPostLUTStrengths[i-1]>0);NSString*p=active?paths[[NSString stringWithFormat:@"look%d",i]]:nil;t=[self lut:p entry:e error:err];if(!t)return nil;[ts addObject:t];if(!p.length){if(i==0)u->postLUTStrength=0;else u->extraPostLUTStrengths[i-1]=0;}} [DYColorTables fillPrimaries:u];idd=e[@"device"]; idh=[_tables hslForDevice:d uniforms:u],w=[_tables whiteBalanceForDevice:d uniforms:u],g=[_tables gradingForDevice:d uniforms:u];if(!h||!w||!g){fail(err,_tables.lastError?:@"颜色查表构建失败");return nil;}[ts addObjectsFromArray:@[h,w,g]];return ts; } +- (BOOL)renderHostSource:(FxImageTile*)src destination:(FxImageTile*)dst uniforms:(DYUniforms)u paths:(NSDictionary*)paths spider:(NSData*)spider tools:(NSDictionary*)tools colorManagement:(NSDictionary*)state hostPrimaries:(NSInteger)primaries atTime:(CMTime)time error:(NSError**)error { + @synchronized(self){ + _scopeDestination=dst;_scopeRenderTime=time;_scopeCaptured=NO; + @try{ + BOOL ok=[self renderSource:src destination:dst uniforms:u paths:paths spider:spider tools:tools colorManagement:state hostPrimaries:primaries error:error]; + if(ok&&!_scopeCaptured)[self captureScopeTile:dst atTime:time]; + return ok; + }@finally{_scopeDestination=nil;} + } +} - (BOOL)renderSource:(FxImageTile*)src destination:(FxImageTile*)dst uniforms:(DYUniforms)u paths:(NSDictionary*)paths error:(NSError**)err{return [self renderSource:src destination:dst uniforms:u paths:paths spider:nil error:err];} - (BOOL)renderSource:(FxImageTile*)src destination:(FxImageTile*)dst uniforms:(DYUniforms)u paths:(NSDictionary*)paths spider:(NSData *)spider error:(NSError**)err{return [self renderSource:src destination:dst uniforms:u paths:paths spider:spider tools:nil error:err];} - (BOOL)renderLegacy:(FxImageTile*)src destination:(FxImageTile*)dst uniforms:(DYUniforms)u paths:(NSDictionary*)paths spider:(NSData *)spider masks:(NSDictionary*)masks error:(NSError**)err{return [self renderLegacy:src destination:dst uniforms:u paths:paths spider:spider masks:masks stageFirst:-1 stageLast:-1 skinReference:nil originalReference:nil captureOriginal:nullptr suppressBlackWhite:NO error:err];} @@ -232,8 +267,9 @@ static NSArray *DYPrimaryActiveFinishing(DYUniforms u,NSDictionary *paths,NSData [_activeLUTPaths release];_activeLUTPaths=[[NSSet alloc]initWithArray:paths.allValues?:@[]]; NSMutableDictionary*e=[self device:dst.deviceRegistryID error:err];if(!e)return NO;idd=e[@"device"];idinput=[src metalTextureForDevice:d],output=[dst metalTextureForDevice:d];if(!input||!output)return fail(err,@"宿主图像纹理不可用"); - BOOL useCM=managed(u,paths)&&(!segmented||stageFirst==0);bypassNeutralTools(&u);float bwMix=fmaxf(0,fminf(1,u.cm.blackWhiteMix));if(bwMix<=0)u.blackWhiteSectionEnabled=0; - NSArray*ts=[self textures:paths uniforms:&u entry:e error:err];if(!ts)return NO;bypassIdleSkin(&u); + BOOL useCM=managed(u,paths)&&(!segmented||stageFirst==0)&&!identityCM(u)&&u.cm.mix>0; + u=DYEffectiveFaceUniforms(u,paths,nil); + float bwMix=u.blackWhiteSectionEnabled>.5?fmaxf(0,fminf(1,u.cm.blackWhiteMix)):0; // Only a deformed active mesh allocates samples; device entries retain the // current buffer across frames. Neutral grids are exact identity at all densities. simd_int2 spiderSize={0,0};idspiderBuffer=nil; @@ -245,30 +281,100 @@ static NSArray *DYPrimaryActiveFinishing(DYUniforms u,NSDictionary *paths,NSData } BOOL faceOnly=u.skinProtection.x>.5&&(u.skinProtection.y>0||u.skinVisualize>.5)&&u.skinFaceOnly>.5; DYToolMaskHeader maskHeader{};idmaskBuffer=(masks.count||segmented||faceOnly||_faceEntries.length)?[self maskBuffer:masks tile:src device:d header:&maskHeader]:nil;maskHeader.faceOnly=faceOnly;BOOL hasMasks=maskHeader.count>0||maskHeader.faceOnly;if((hasMasks||segmented)&&!maskBuffer)return fail(err,@"无法分配蒙版缓冲区"); - NSMutableDictionary*ps=e[@"pipelines"];NSString*format=[NSString stringWithFormat:@"%lu-%d-%d",(unsigned long)output.pixelFormat,hasMasks,segmented];idpipeline=ps[format];if(!pipeline){MTLRenderPipelineDescriptor*p=[MTLRenderPipelineDescriptor new];p.vertexFunction=[e[@"library"]newFunctionWithName:@"dyVertex"];p.fragmentFunction=[e[@"library"]newFunctionWithName:segmented?@"dySegmentFragment":hasMasks?@"dyMaskedFragment":@"dyFragment"];p.colorAttachments[0].pixelFormat=output.pixelFormat;pipeline=[d newRenderPipelineStateWithDescriptor:p error:err];[p.vertexFunction release];[p.fragmentFunction release];[p release];if(!pipeline)return NO;ps[format]=pipeline;[pipeline release];} - MTLTextureDescriptor*td=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA16Float width:input.width height:input.height mipmapped:NO];td.storageMode=MTLStorageModePrivate;td.usage=MTLTextureUsageShaderRead|MTLTextureUsageShaderWrite;idstraight=[d newTextureWithDescriptor:td];if(!straight)return fail(err,@"无法分配调色缓冲区"); - idcb=[e[@"queue"]commandBuffer];idce=[cb computeCommandEncoder];[ce setComputePipelineState:e[@"dyUnpremultiply"]];[ce setTexture:input atIndex:0];[ce setTexture:straight atIndex:1];[ce dispatchThreads:MTLSizeMake(input.width,input.height,1) threadsPerThreadgroup:MTLSizeMake(16,16,1)];[ce endEncoding]; - if(useCM&&!identityCM(u)&&u.cm.mix>0){ - DayuRenderParams cm=DYCMRender(u.cm);cm.stages=(cm.stages&~1)|(u.inputSectionEnabled>.5?1:0); - if(cm.stages){idconverted=[d newTextureWithDescriptor:td];if(!converted){[straight release];return fail(err,@"无法分配 CST 缓冲区");} - ce=[cb computeCommandEncoder];[ce setComputePipelineState:e[@"dyColorManagement"]];[ce setTexture:straight atIndex:0];[ce setTexture:converted atIndex:1];[ce setBytes:&cm length:sizeof(cm) atIndex:0];[ce setBytes:&u.cm.mix length:4 atIndex:1];[ce dispatchThreads:MTLSizeMake(input.width,input.height,1) threadsPerThreadgroup:MTLSizeMake(16,16,1)];[ce endEncoding];if(hasMasks){idblended=[d newTextureWithDescriptor:td];if(!blended){[converted release];[straight release];return fail(err,@"无法分配一级蒙版缓冲区");}maskHeader.section=0;maskHeader.premultiplied=0;[self encodeBlend:straight after:converted output:blended masks:maskBuffer header:maskHeader entry:e commands:cb];[converted release];converted=blended;}[straight release];straight=converted; + BOOL preview=NO; + @synchronized(_previewLock){preview=(!segmented||stageFirst==0)&&!_exporting&&CACurrentMediaTime()-_lastPreview>.5;} + BOOL neutral=!segmented&&!hasMasks&&!spiderBuffer&&u.skinVisualize<.5&&!hasLegacyGrade(u); + FxRect s=src.tilePixelBounds,t=dst.tilePixelBounds; + BOOL sameGrid=input.width==output.width&&input.height==output.height&&s.left==t.left&&s.right==t.right&&s.top==t.top&&s.bottom==t.bottom; + BOOL direct=neutral&&!useCM&&!preview&&sameGrid&&input!=output; + NSString *fragment=direct?@"dyNeutralInputFragment":neutral?@"dyNeutralOutputFragment":segmented?@"dySegmentFragment":hasMasks?@"dyMaskedFragment":@"dyFragment"; + NSMutableDictionary *ps=e[@"pipelines"]; + NSString *format=[NSString stringWithFormat:@"%lu-%d-%d",(unsigned long)output.pixelFormat,hasMasks,segmented]; + if(neutral)format=[NSString stringWithFormat:@"%@-%lu",fragment,(unsigned long)output.pixelFormat]; + id pipeline=ps[format]; + if(!pipeline){ + MTLRenderPipelineDescriptor *desc=[[[MTLRenderPipelineDescriptor alloc]init]autorelease]; + id library=e[@"library"]; + desc.vertexFunction=[[library newFunctionWithName:@"dyVertex"]autorelease]; + desc.fragmentFunction=[[library newFunctionWithName:fragment]autorelease]; + desc.colorAttachments[0].pixelFormat=output.pixelFormat; + pipeline=[[d newRenderPipelineStateWithDescriptor:desc error:err]autorelease]; + if(!pipeline)return NO; + ps[format]=pipeline; + } + NSArray *ts=neutral?nil:[self textures:paths uniforms:&u entry:e error:err]; + if(!neutral&&!ts)return NO; + id cb=[e[@"queue"]commandBuffer]; + id straight=input; + if(!direct){ + MTLTextureDescriptor *td=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA16Float width:input.width height:input.height mipmapped:NO]; + td.storageMode=MTLStorageModePrivate;td.usage=MTLTextureUsageShaderRead|MTLTextureUsageShaderWrite; + straight=segmented?nil:e[@"legacyStraight"]; + if(straight.width!=input.width||straight.height!=input.height){ + straight=[[d newTextureWithDescriptor:td]autorelease]; + if(straight&&!segmented)e[@"legacyStraight"]=straight; + } + if(!straight)return fail(err,@"无法分配调色缓冲区"); + MTLSize grid=MTLSizeMake(input.width,input.height,1),group=MTLSizeMake(16,16,1); + BOOL fused=useCM&&!hasMasks; + if(!fused){ + id unpremultiply=[self computePipeline:@"dyUnpremultiply" entry:e error:err];if(!unpremultiply)return NO; + id ce=[cb computeCommandEncoder]; + [ce setComputePipelineState:unpremultiply];[ce setTexture:input atIndex:0];[ce setTexture:straight atIndex:1]; + [ce dispatchThreads:grid threadsPerThreadgroup:group];[ce endEncoding]; + } + if(useCM){ + DayuRenderParams cm=DYCMRender(u.cm);cm.stages=(cm.stages&~1)|(u.inputSectionEnabled>.5?1:0); + id cst=[self computePipeline:@"dyColorManagement" entry:e error:err];if(!cst)return NO; + id converted=fused?straight:[[d newTextureWithDescriptor:td]autorelease]; + if(!converted)return fail(err,@"无法分配 CST 缓冲区"); + uint32_t premultiplied=fused; + id ce=[cb computeCommandEncoder]; + [ce setComputePipelineState:cst];[ce setTexture:fused?input:straight atIndex:0];[ce setTexture:converted atIndex:1]; + [ce setBytes:&cm length:sizeof(cm) atIndex:0];[ce setBytes:&u.cm.mix length:4 atIndex:1];[ce setBytes:&premultiplied length:4 atIndex:2]; + [ce dispatchThreads:grid threadsPerThreadgroup:group];[ce endEncoding]; + if(hasMasks){ + id blended=[[d newTextureWithDescriptor:td]autorelease];if(!blended)return fail(err,@"无法分配一级蒙版缓冲区"); + maskHeader.section=0;maskHeader.premultiplied=0; + if(![self encodeBlend:straight after:converted output:blended masks:maskBuffer header:maskHeader entry:e commands:cb error:err])return NO; + converted=blended; + } + straight=converted; } } - // Keep the actual post-CST straight source alive across all native segments. - // Both native spatial helpers and whites statistics historically read this - // source; the current segment's center color is a different input. - idnativeSource=segmented&&originalReference?[originalReference metalTextureForDevice:d]:straight; - if(!nativeSource){[straight release];return fail(err,@"原生工具参考纹理不可用");} + // Segments retain the original straight source for spatial tools and statistics. + id nativeSource=segmented&&originalReference?[originalReference metalTextureForDevice:d]:straight; + if(!nativeSource)return fail(err,@"原生工具参考纹理不可用"); if(segmented&&captureOriginal&&!*captureOriginal){DYExportTile *reference=[[DYExportTile alloc]initWithTexture:nativeSource registry:d.registryID];[reference setBounds:src.tilePixelBounds origin:src.imageOrigin];[reference setPixelAspect:src.pixelAspect];*captureOriginal=reference;} - float level=.5;idscene=[d newBufferWithBytes:&level length:4 options:MTLResourceStorageModeShared]; - if(!_exporting&&(!segmented||(stageFirst<=2&&stageLast>=2))&&u.whites>0&&u.whitesEnabled>.5&&u.baseSectionEnabled>.5){ce=[cb computeCommandEncoder];[ce setComputePipelineState:e[@"dyWhitesSceneStatistics"]];[ce setTexture:nativeSource atIndex:0];[ce setTexture:ts[7] atIndex:1];[ce setBytes:&u length:sizeof(u) atIndex:0];[ce setBuffer:scene offset:0 atIndex:1];[ce dispatchThreadgroups:MTLSizeMake(1,1,1) threadsPerThreadgroup:MTLSizeMake(256,1,1)];[ce endEncoding];} - BOOL preview=NO;@synchronized(_previewLock){preview=(!segmented||stageFirst==0)&&!_exporting&&CACurrentMediaTime()-_lastPreview>.5;}idpb=nil;if(preview){pb=[d newBufferWithLength:320*180*16 options:MTLResourceStorageModeShared];ce=[cb computeCommandEncoder];[ce setComputePipelineState:e[@"dyInputAnalysis"]];[ce setTexture:straight atIndex:0];[ce setTexture:ts[0] atIndex:1];float inputStrength=u.inputSectionEnabled>.5?u.preLUTStrength:0;[ce setBytes:&inputStrength length:4 atIndex:1];[ce setBuffer:pb offset:0 atIndex:0];[ce dispatchThreads:MTLSizeMake(320,180,1) threadsPerThreadgroup:MTLSizeMake(8,8,1)];[ce endEncoding];} + id scene=nil; + if(!neutral){ + float level=.5; + scene=[[d newBufferWithBytes:&level length:4 options:MTLResourceStorageModeShared]autorelease]; + if(!scene)return fail(err,@"无法分配调色统计缓冲区"); + if(!_exporting&&(!segmented||(stageFirst<=2&&stageLast>=2))&&u.whites>0&&u.whitesEnabled>.5&&u.baseSectionEnabled>.5){ + id stats=[self computePipeline:@"dyWhitesSceneStatistics" entry:e error:err];if(!stats)return NO; + id ce=[cb computeCommandEncoder]; + [ce setComputePipelineState:stats];[ce setTexture:nativeSource atIndex:0];[ce setTexture:ts[7] atIndex:1];[ce setBytes:&u length:sizeof(u) atIndex:0];[ce setBuffer:scene offset:0 atIndex:0]; + [ce dispatchThreadgroups:MTLSizeMake(1,1,1) threadsPerThreadgroup:MTLSizeMake(256,1,1)];[ce endEncoding]; + } + } + id pb=nil; + if(preview){ + id analysis=[self computePipeline:@"dyInputAnalysis" entry:e error:err];if(!analysis)return NO; + pb=[[d newBufferWithLength:320*180*16 options:MTLResourceStorageModeShared]autorelease]; + if(!pb)return fail(err,@"无法分配输入预览缓冲区"); + id ce=[cb computeCommandEncoder]; + [ce setComputePipelineState:analysis];[ce setTexture:straight atIndex:0];[ce setTexture:neutral?e[@"identity"]:ts[0] atIndex:1]; + float inputStrength=u.inputSectionEnabled>.5?u.preLUTStrength:0; + [ce setBytes:&inputStrength length:4 atIndex:1];[ce setBuffer:pb offset:0 atIndex:0]; + [ce dispatchThreads:MTLSizeMake(320,180,1) threadsPerThreadgroup:MTLSizeMake(8,8,1)];[ce endEncoding]; + } MTLRenderPassDescriptor*rp=[MTLRenderPassDescriptor renderPassDescriptor];rp.colorAttachments[0].texture=output;rp.colorAttachments[0].loadAction=MTLLoadActionDontCare;rp.colorAttachments[0].storeAction=MTLStoreActionStore;idre=[cb renderCommandEncoderWithDescriptor:rp];[re setRenderPipelineState:pipeline]; - float w=output.width,h=output.height;FxRect s=src.tilePixelBounds,t=dst.tilePixelBounds;float sw=s.right-s.left,sh=s.top-s.bottom;float l=(t.left-s.left)/sw,r=(t.right-s.left)/sw,top=(s.top-t.top)/sh,bottom=(s.top-t.bottom)/sh; + float w=output.width,h=output.height;float sw=s.right-s.left,sh=s.top-s.bottom;float l=(t.left-s.left)/sw,r=(t.right-s.left)/sw,top=(s.top-t.top)/sh,bottom=(s.top-t.bottom)/sh; if(src.imageOrigin==kFxImageOrigin_BOTTOM_LEFT){top=1-top;bottom=1-bottom;} DYVertex2D vs[]={{{w/2,-h/2},{r,bottom}},{{-w/2,-h/2},{l,bottom}},{{w/2,h/2},{r,top}},{{-w/2,h/2},{l,top}}}; if(dst.imageOrigin==kFxImageOrigin_BOTTOM_LEFT)for(int i=0;i<4;i++)vs[i].position.y=-vs[i].position.y; - vector_uint2 vp={(unsigned)output.width,(unsigned)output.height};[re setVertexBytes:vs length:sizeof(vs) atIndex:0];[re setVertexBytes:&vp length:sizeof(vp) atIndex:1];[re setViewport:(MTLViewport){0,0,w,h,0,1}];[re setFragmentTexture:straight atIndex:0];for(NSUInteger i=0;idevice=entry[@"device"];idtexture=[tile metalTextureForDevice:device]; - if(!entry||!texture||!texture.width||!texture.height||texture.framebufferOnly){[entry release];[context release];return;} - idbuffer=[device newBufferWithLength:dyscope::Width*dyscope::Height*sizeof(dyscope::RGBA) options:MTLResourceStorageModeShared]; - idcommand=[entry[@"queue"]commandBuffer];idencoder=[command computeCommandEncoder]; - if(!buffer||!encoder){[buffer release];[entry release];[context release];return;} - uint32_t flip=tile.imageOrigin==kFxImageOrigin_BOTTOM_LEFT;[encoder setComputePipelineState:entry[@"dyScopeSample"]];[encoder setTexture:texture atIndex:0];[encoder setBuffer:buffer offset:0 atIndex:0];[encoder setBytes:&flip length:sizeof(flip) atIndex:1]; - [encoder dispatchThreads:MTLSizeMake(dyscope::Width,dyscope::Height,1) threadsPerThreadgroup:MTLSizeMake(8,8,1)];[encoder endEncoding];[command commit]; - // The host may recycle its destination as soon as render returns. Complete - // only this 320x180 readback while that ownership is still guaranteed. - // CPU profile conversion, plotting and UI notification do not block render. - [command waitUntilCompleted]; - if(command.status!=MTLCommandBufferStatusCompleted){[buffer release];[entry release];[context release];return;} - DYScopeSample *sample=[DYScopeSample new];sample.pixels=[NSData dataWithBytes:buffer.contents length:buffer.length];sample.generation=generation; - CGColorSpaceRef sourceSpace=DYManagedTileSpace(tile,[context[@"primaries"]integerValue]);sample.space=sourceSpace;if(sourceSpace)CGColorSpaceRelease(sourceSpace); - FxRect bounds=tile.tilePixelBounds,image=tile.imagePixelBounds;BOOL whole=bounds.left==image.left&&bounds.right==image.right&&bounds.top==image.top&&bounds.bottom==image.bottom; - sample.metadata=@{@"time":@(CMTimeGetSeconds(time)),@"timeValue":@(time.value),@"timeScale":@(time.timescale),@"timeEpoch":@(time.epoch),@"source":context[@"destination"]?:@"宿主 RGB",@"wholeImage":@(whole),@"region":whole?@"整帧取样":@"仅当前宿主输出分块",@"width":@(dyscope::Width),@"height":@(dyscope::Height)}; - [buffer release];[entry release];[context release]; - BOOL start=NO,notifyOutput=NO;@synchronized(_previewLock){ - if(serial>=_scopeLatestSerial){ - [_scopeLatest release];_scopeLatest=[sample retain];_scopeLatestSerial=serial; +// The caller owns the destination until command completion. Only the small +// result buffer is copied out of that lifetime, even when the scope is closed. +- (DYScopeReadback)encodeScopeTile:(FxImageTile *)tile texture:(id)texture entry:(NSMutableDictionary *)entry commands:(id)command { + if(_exporting||!tile||!texture.width||!texture.height||texture.framebufferOnly)return {}; + id pipeline=[self computePipeline:@"dyScopeSample" entry:entry error:nil]; + if(!pipeline)return {}; + id buffer=entry[@"scopeBuffer"]; + if(!buffer){ + id device=entry[@"device"]; + buffer=[[device newBufferWithLength:dyscope::Width*dyscope::Height*sizeof(dyscope::RGBA) options:MTLResourceStorageModeShared]autorelease]; + if(!buffer)return {}; + entry[@"scopeBuffer"]=buffer; + } + id encoder=[command computeCommandEncoder]; + if(!encoder)return {}; + uint32_t flip=tile.imageOrigin==kFxImageOrigin_BOTTOM_LEFT; + [encoder setComputePipelineState:pipeline];[encoder setTexture:texture atIndex:0]; + [encoder setBuffer:buffer offset:0 atIndex:0];[encoder setBytes:&flip length:sizeof(flip) atIndex:1]; + [encoder dispatchThreads:MTLSizeMake(dyscope::Width,dyscope::Height,1) threadsPerThreadgroup:MTLSizeMake(8,8,1)]; + [encoder endEncoding]; + @synchronized(_previewLock){return {buffer,_scopeGeneration,++_scopeCaptureSerial};} +} +- (void)publishScopeReadback:(DYScopeReadback)readback tile:(FxImageTile *)tile atTime:(CMTime)time { + if(!readback.buffer)return; + @try{ + DYScopeSample *sample=[[[DYScopeSample alloc]init]autorelease]; + sample.pixels=[NSData dataWithBytes:readback.buffer.contents length:readback.buffer.length]; + sample.generation=readback.generation; + CGColorSpaceRef space=DYManagedTileSpace(tile,[_colorContext[@"primaries"]integerValue]); + sample.space=space;if(space)CGColorSpaceRelease(space); + FxRect bounds=tile.tilePixelBounds,image=tile.imagePixelBounds; + BOOL whole=bounds.left==image.left&&bounds.right==image.right&&bounds.top==image.top&&bounds.bottom==image.bottom; + sample.metadata=@{@"time":@(CMTimeGetSeconds(time)),@"timeValue":@(time.value),@"timeScale":@(time.timescale),@"timeEpoch":@(time.epoch),@"source":_colorContext[@"destination"]?:@"宿主 RGB",@"wholeImage":@(whole),@"region":whole?@"整帧取样":@"仅当前宿主输出分块",@"width":@(dyscope::Width),@"height":@(dyscope::Height)}; + BOOL start=NO,notifyOutput=NO; + @synchronized(_previewLock){ + if(readback.serial>=_scopeLatestSerial){ + [_scopeLatest release];_scopeLatest=[sample retain];_scopeLatestSerial=readback.serial; if(_outputObserved&&!_outputNotificationPending){_outputNotificationPending=YES;notifyOutput=YES;} } - if(_scopeEnabled&&serial==_scopeLatestSerial&&(generation==_scopeGeneration||!CMTIME_IS_NUMERIC(_scopeRequestedTime)||CMTimeCompare(time,_scopeRequestedTime)==0)){sample.generation=_scopeGeneration;[_scopePending release];_scopePending=[sample retain];if(!_scopeWorkerRunning){_scopeWorkerRunning=YES;start=YES;}} - }[sample release]; + if(_scopeEnabled&&readback.serial==_scopeLatestSerial&&(readback.generation==_scopeGeneration||!CMTIME_IS_NUMERIC(_scopeRequestedTime)||CMTimeCompare(time,_scopeRequestedTime)==0)){ + sample.generation=_scopeGeneration;[_scopePending release];_scopePending=[sample retain]; + if(!_scopeWorkerRunning){_scopeWorkerRunning=YES;start=YES;} + } + } if(notifyOutput)[self queueOutputNotification]; if(start)dispatch_async(_scopeQueue,^{[self processPendingScopeSamples];}); - }@catch(NSException *exception){/* Scope diagnostics must never fail rendering. */}} + }@catch(NSException *exception){/* Scope diagnostics must never fail rendering. */} +} +- (BOOL)completeCommands:(id)command destination:(FxImageTile *)destination texture:(id)texture entry:(NSMutableDictionary *)entry { + DYScopeReadback readback{}; + if(destination==_scopeDestination){ + @try{readback=[self encodeScopeTile:destination texture:texture entry:entry commands:command];} + @catch(NSException *exception){/* Fall back to separate sampling. */} + } + [command commit];[command waitUntilCompleted]; + if(command.status!=MTLCommandBufferStatusCompleted)return NO; + if(readback.buffer){[self publishScopeReadback:readback tile:destination atTime:_scopeRenderTime];_scopeCaptured=YES;} + return YES; +} +- (void)captureScopeTile:(FxImageTile *)tile atTime:(CMTime)time { + @synchronized(self){@autoreleasepool{@try{ + if(!tile||_exporting)return; + NSMutableDictionary *entry=[self device:tile.deviceRegistryID error:nil]; + id texture=[tile metalTextureForDevice:entry[@"device"]]; + id command=[entry[@"queue"]commandBuffer]; + DYScopeReadback readback=[self encodeScopeTile:tile texture:texture entry:entry commands:command]; + if(!readback.buffer)return; + [command commit];[command waitUntilCompleted]; + if(command.status==MTLCommandBufferStatusCompleted)[self publishScopeReadback:readback tile:tile atTime:time]; + }@catch(NSException *exception){/* Scope diagnostics must never fail rendering. */}}} } - (void)processPendingScopeSamples{ for(;;){@autoreleasepool{ diff --git a/大鱼调色/Plugin/DYToolInspector.inc.h b/大鱼调色/Plugin/DYToolInspector.inc.h index 9c3ed3c..3fc30b2 100644 --- a/大鱼调色/Plugin/DYToolInspector.inc.h +++ b/大鱼调色/Plugin/DYToolInspector.inc.h @@ -1,13 +1,12 @@ -- (void)synchronizeTools { - ida=[self actionAPI];if(!a)return;[a startAction:self];NSDictionary *document=nil;@try{document=[DYReadTools(_manager,a.currentTime).document copy];}@finally{[a endAction:self];} +- (void)synchronizeTools:(NSDictionary *)document { NSMutableArray *order=[NSMutableArray array];NSMutableDictionary *numbers=[NSMutableDictionary dictionary],*roots=[NSMutableDictionary dictionary]; for(NSString *orderedID in DYToolDisplayOrder(document)){NSDictionary *node=DYToolWithID(document,orderedID);if(!node)continue;NSString *ID=node[@"id"],*type=node[@"type"];[order addObject:ID];roots[ID]=DYToolRootAnchor(document,ID)?:@"tail";NSInteger number=(numbers[type]?[numbers[type]integerValue]:(DYBaseToolRemoved(document,type)?0:1))+1;numbers[type]=@(number); - DYInspector *view=_stackViews[ID];if(!view){DYToolManager *manager=[[[DYToolManager alloc]initWithHost:_manager node:node]autorelease];view=[[[DYInspector alloc]initWithAPIManager:manager renderer:_renderer]autorelease];_stackViews[ID]=view;[_document addSubview:view];} + DYInspector *view=_stackViews[ID];BOOL existed=view!=nil;if(!view){DYToolManager *manager=[[[DYToolManager alloc]initWithHost:_manager node:node]autorelease];view=[[[DYInspector alloc]initWithAPIManager:manager renderer:_renderer]autorelease];_stackViews[ID]=view;[_document addSubview:view];} if(view->_cards.count){NSDictionary *section=view->_cards[0][@"section"];NSString *title=[NSString stringWithFormat:@"%@ %ld",section[@"title"],(long)number];[view->_cards[0][@"header"]setTitle:title];[view->_cards[0][@"removeButton"]setAccessibilityLabel:[title stringByAppendingString:@"删除此层"]];} - [view refresh];[view setNeedsLayout:YES]; + if(existed)[view refresh]; } for(NSString *ID in [[_stackViews.allKeys copy]autorelease])if(![order containsObject:ID]){[_stackViews[ID]removeFromSuperview];[_stackViews removeObjectForKey:ID];} - [_stackOrder release];_stackOrder=[order copy];[_stackRoots release];_stackRoots=[roots copy];[document release];[self setNeedsLayout:YES]; + [_stackOrder release];_stackOrder=[order copy];[_stackRoots release];_stackRoots=[roots copy];[self setNeedsLayout:YES]; } - (void)toolMask:(NSButton*)sender{if(sender.tag<0||sender.tag>=_cards.count)return;id host=_embedded?[(DYToolManager*)_manager host]:_manager;NSString *node=_embedded?[(DYToolManager*)_manager nodeID]:[@"base:" stringByAppendingString:_cards[sender.tag][@"section"][@"key"]];[NSNotificationCenter.defaultCenter postNotificationName:@"DYWorkspaceToolSelection" object:host userInfo:@{@"node":node,@"source":@"inspector"}];[(DYToolMaskPanel*)_cards[sender.tag][@"maskPanel"]addMenu:sender];} - (void)repeatTool:(NSButton*)sender{ diff --git a/大鱼调色/Plugin/DYToolRender.inc.h b/大鱼调色/Plugin/DYToolRender.inc.h index d7f814a..052812f 100644 --- a/大鱼调色/Plugin/DYToolRender.inc.h +++ b/大鱼调色/Plugin/DYToolRender.inc.h @@ -9,8 +9,9 @@ for(NSDictionary *m in groups[type]){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;NSData *nodes=m[@"nodes"];entry.mask.path=dyFlattenMask((const DYBezierNode*)nodes.bytes,nodes.length/sizeof(DYBezierNode));entries.push_back(entry);} }if(_faceEntries.length){const DYToolMaskEntry *faces=(const DYToolMaskEntry*)_faceEntries.bytes;entries.insert(entries.end(),faces,faces+_faceEntries.length/sizeof(DYToolMaskEntry));}h->count=(unsigned)entries.size();if(entries.empty())entries.push_back({});return [[device newBufferWithBytes:entries.data() length:entries.size()*sizeof(DYToolMaskEntry) options:MTLResourceStorageModeShared]autorelease]; } -- (void)encodeBlend:(id)before after:(id)after output:(id)output masks:(id)masks header:(DYToolMaskHeader)h entry:(NSDictionary*)entry commands:(id)commands { - idencoder=[commands computeCommandEncoder];[encoder setComputePipelineState:entry[@"dyToolBlend"]];[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]; +- (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; } - (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]; @@ -34,7 +35,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];[cb commit];[cb waitUntilCompleted];return cb.status==MTLCommandBufferStatusCompleted?YES:fail(error,cb.error.localizedDescription); + 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); } // 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. @@ -50,10 +51,11 @@ if([type isEqual:@"mixer"]||[type isEqual:@"film"]){layer.filmFrameKey=[node[@"filmFrameKey"]unsignedIntValue];return [self renderFilmTool:type source:source destination:destination uniforms:layer masks:node[@"masks"] entry:entry error:error];} if(![type isEqual:@"skin"])return [self renderLegacy:source destination:destination uniforms:layer paths:node[@"paths"] spider:node[@"spider"] masks:@{type:node[@"masks"]} error:error]; idd=entry[@"device"];idbefore=[source metalTextureForDevice:d],input=[original metalTextureForDevice:d],after=[destination metalTextureForDevice:d]; - idcb=[entry[@"queue"]commandBuffer];idce=[cb computeCommandEncoder];[ce setComputePipelineState:entry[@"dyToolSkin"]];[ce setTexture:before atIndex:0];[ce setTexture:input atIndex:1];[ce setTexture:after atIndex:2];[ce setBytes:&layer length:sizeof(layer) atIndex:0];[ce dispatchThreads:MTLSizeMake(after.width,after.height,1) threadsPerThreadgroup:MTLSizeMake(16,16,1)];[ce endEncoding];[cb commit];[cb waitUntilCompleted];if(cb.status!=MTLCommandBufferStatusCompleted)return fail(error,cb.error.localizedDescription); + id pipeline=[self computePipeline:@"dyToolSkin" 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:input atIndex:1];[ce setTexture:after atIndex:2];[ce setBytes:&layer length:sizeof(layer) atIndex:0];[ce dispatchThreads:MTLSizeMake(after.width,after.height,1) threadsPerThreadgroup:MTLSizeMake(16,16,1)];[ce endEncoding];[cb commit];[cb waitUntilCompleted];if(cb.status!=MTLCommandBufferStatusCompleted)return fail(error,cb.error.localizedDescription); if(![node[@"masks"]count]&&layer.skinFaceOnly<.5&&layer.skinVisualize<.5)return YES; MTLTextureDescriptor *desc=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA16Float width:after.width height:after.height mipmapped:NO];desc.storageMode=MTLStorageModePrivate;desc.usage=MTLTextureUsageRenderTarget|MTLTextureUsageShaderRead|MTLTextureUsageShaderWrite;idblend=[d newTextureWithDescriptor:desc];if(!blend)return fail(error,@"无法分配新增工具蒙版缓冲区"); - DYToolMaskHeader h{};h.section=3;h.faceOnly=layer.skinFaceOnly>.5;h.skinPreview=layer.skinProtection.x>.5&&layer.skinVisualize>.5;idbuffer=[self maskBuffer:@{type:node[@"masks"]} tile:source device:d header:&h];cb=[entry[@"queue"]commandBuffer];[self encodeBlend:before after:after output:blend masks:buffer header:h entry:entry commands:cb];[cb commit];[cb waitUntilCompleted];BOOL ok=cb.status==MTLCommandBufferStatusCompleted; + DYToolMaskHeader h{};h.section=3;h.faceOnly=layer.skinFaceOnly>.5;h.skinPreview=layer.skinProtection.x>.5&&layer.skinVisualize>.5;idbuffer=[self maskBuffer:@{type:node[@"masks"]} tile:source device:d header:&h];cb=[entry[@"queue"]commandBuffer];if(![self encodeBlend:before after:after output:blend masks:buffer header:h entry:entry commands:cb error:error]){[blend release];return NO;}[cb commit];[cb waitUntilCompleted];BOOL ok=cb.status==MTLCommandBufferStatusCompleted; DYExportTile *blended=[[DYExportTile alloc]initWithTexture:blend registry:d.registryID];[blended setBounds:source.tilePixelBounds origin:source.imageOrigin];[blended setPixelAspect:source.pixelAspect];[blend release];if(ok)ok=[self copyTile:blended to:destination entry:entry error:error];else fail(error,cb.error.localizedDescription);[blended release];return ok; } - (BOOL)renderToolsSource:(FxImageTile*)src destination:(FxImageTile*)dst uniforms:(DYUniforms)u paths:(NSDictionary*)paths spider:(NSData*)spider tools:(NSDictionary*)tools error:(NSError**)error {@synchronized(self){return DYRenderWithPool(error,[&]()->BOOL{ @@ -99,7 +101,7 @@ if(branch==0)bwTile=[tile retain]; } DYExportTile *mixed=makeTile();if(!mixed)return fail(error,@"无法分配黑白混合缓冲区");DYToolMaskEntry constant{};constant.section=0;constant.combine=0;constant.mask.parameters=dyDefaultMaskParameters();constant.mask.parameters.kind=DYMaskRectangle;constant.mask.parameters.width=constant.mask.parameters.height=4000;constant.mask.parameters.feather=0;constant.mask.parameters.outputBlack=constant.mask.parameters.outputWhite=1;constant.mask.parameters.strength=bwMix; - idweight=[[d newBufferWithBytes:&constant length:sizeof(constant) options:MTLResourceStorageModeShared]autorelease];if(!weight){[mixed release];return fail(error,@"无法分配黑白混合权重");}DYToolMaskHeader h{};h.count=1;h.section=0;h.premultiplied=1;h.scaleX=h.scaleY=1;idcommands=[entry[@"queue"]commandBuffer];[self encodeBlend:[tile metalTextureForDevice:d] after:[bwTile metalTextureForDevice:d] output:[mixed metalTextureForDevice:d] masks:weight header:h entry:entry commands:commands];[commands commit];[commands waitUntilCompleted];if(commands.status!=MTLCommandBufferStatusCompleted){[mixed release];return fail(error,commands.error.localizedDescription);}replace(mixed); + idweight=[[d newBufferWithBytes:&constant length:sizeof(constant) options:MTLResourceStorageModeShared]autorelease];if(!weight){[mixed release];return fail(error,@"无法分配黑白混合权重");}DYToolMaskHeader h{};h.count=1;h.section=0;h.premultiplied=1;h.scaleX=h.scaleY=1;idcommands=[entry[@"queue"]commandBuffer];if(![self encodeBlend:[tile metalTextureForDevice:d] after:[bwTile metalTextureForDevice:d] output:[mixed metalTextureForDevice:d] masks:weight header:h entry:entry commands:commands error:error]){[mixed release];return NO;}[commands commit];[commands waitUntilCompleted];if(commands.status!=MTLCommandBufferStatusCompleted){[mixed release];return fail(error,commands.error.localizedDescription);}replace(mixed); }@finally{[prefix release];[bwTile release];} // An extra skin tool follows the original skin and B&W mixture once. if(!apply(@"base:skin"))return NO; diff --git a/大鱼调色/Plugin/DYUnifiedRender.inc.h b/大鱼调色/Plugin/DYUnifiedRender.inc.h index 79757c0..63b27d2 100644 --- a/大鱼调色/Plugin/DYUnifiedRender.inc.h +++ b/大鱼调色/Plugin/DYUnifiedRender.inc.h @@ -9,7 +9,7 @@ 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 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 managedKernel:@"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;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 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};} diff --git a/大鱼调色/Plugin/Info.plist b/大鱼调色/Plugin/Info.plist index a4d409f..66c8a62 100644 --- a/大鱼调色/Plugin/Info.plist +++ b/大鱼调色/Plugin/Info.plist @@ -17,9 +17,9 @@ CFBundlePackageType XPC! CFBundleShortVersionString - 1.20.2 + 1.21.0 CFBundleVersion - 113 + 114 NSHumanReadableCopyright PlugInKit diff --git a/大鱼调色/Wrapper Application/Info.plist b/大鱼调色/Wrapper Application/Info.plist index 93f0019..a06d1c2 100644 --- a/大鱼调色/Wrapper Application/Info.plist +++ b/大鱼调色/Wrapper Application/Info.plist @@ -17,9 +17,9 @@ CFBundlePackageType APPL CFBundleShortVersionString - 1.20.2 + 1.21.0 CFBundleVersion - 113 + 114 LSMinimumSystemVersion $(MACOSX_DEPLOYMENT_TARGET) NSHumanReadableCopyright diff --git a/开发交接.md b/开发交接.md index 2684870..a23e0ee 100644 --- a/开发交接.md +++ b/开发交接.md @@ -2,6 +2,12 @@ 更新于 2026-11-08(Asia/Shanghai)。这是新对话的接手入口。历史设计和实现细节按需查阅专项交接,复现和交付证据以对应版本的报告为准。 +## 1.21.0(114)流畅性优化 + +按首帧、连续渲染和检查器刷新优化。Metal 管线首次使用才创建,中性画面跳过通用调色与查找纹理,保留原来的半精度透明度规则;无蒙版 CST 将解除预乘并入原转换内核。最终画面取样合并进输出命令并复用小缓冲,仍保留暂停帧的示波器样本。检查器复用本轮的宿主读参和工具文档,只在切换色彩管理模式时移动输出控件。胶片颗粒未参与时省去宿主帧时序查询。 + +入口为 `DYRenderer.mm`、`DYGrade.metal`、`DYScopeCapture.inc.h`、`DYPlugIn.mm` 与 `DYInspector.mm`。正在进行像素回归、正式构建和宿主验收。此检查点的正式安装仍是 1.20.2(113)。接手先核对构建与回归状态,再完成 APP、PKG 与 Release 验证。 + ## 2026-11-08 默认参数渲染排查 核对正式安装 1.20.2(113)、编译提交 `046411ba8b2c2bf8549601b2e5a080fd9dccd31b`。整合版、HSL、一级调色和 CST 独立效果的已安装模板、APP 内置模板和源码逐字节一致。整合模板没有额外工具层、LUT 或变形网格,默认执行 Sony S-Log3 / S-Gamut3.Cine 到 Gamma 2.4 / Rec.709 的 CST,自动色调映射开启。独立 HSL 的工具文档移除了一级调色。