文件
dayu-color/大鱼调色/Plugin/DYScopeCapture.inc.h
T

135 行
10 KiB
C
原始文件 Blame 文件历史

此文件含有模棱两可的 Unicode 字符
此文件含有可能会与其他字符混淆的 Unicode 字符。 如果您是想特意这样的,可以安全地忽略该警告。 使用 Escape 按钮显示他们。
// Included in DYRenderer's implementation; final destination sampling is kept
// separate from the earlier input-analysis thumbnail used by auto-grade/LUTs.
- (BOOL)scopeEnabled{@synchronized(_previewLock){return _scopeEnabled;}}
- (void)setScopeEnabled:(BOOL)enabled{[self setScopeEnabled:enabled atTime:kCMTimeInvalid];}
- (void)setScopeEnabled:(BOOL)enabled atTime:(CMTime)time{
BOOL start=NO;@synchronized(_previewLock){if(_scopeEnabled==enabled)return;_scopeEnabled=enabled;_scopeGeneration++;[_scopePending release];_scopePending=nil;
if(enabled){_scopeRequestedTime=time;[_scopePreview release];_scopePreview=nil;[_scopeMetadata release];_scopeMetadata=nil;
CMTime cached=_scopeLatest?CMTimeMakeWithEpoch([_scopeLatest.metadata[@"timeValue"]longLongValue],[_scopeLatest.metadata[@"timeScale"]intValue],[_scopeLatest.metadata[@"timeEpoch"]longLongValue]):kCMTimeInvalid;
os_log(OS_LOG_DEFAULT,"dayu_scope_open requested=%{public}.9f cached=%{public}.9f",CMTimeGetSeconds(time),CMTimeGetSeconds(cached));
// Replay only this instance's actual final output at the requested host time.
// A panel opening must not require a parameter mutation or a fresh render.
if(_scopeLatest&&(!CMTIME_IS_NUMERIC(time)||(CMTIME_IS_NUMERIC(cached)&&CMTimeCompare(cached,time)==0))){DYScopeSample *sample=[DYScopeSample new];sample.pixels=_scopeLatest.pixels;sample.space=_scopeLatest.space;sample.metadata=_scopeLatest.metadata;sample.generation=_scopeGeneration;_scopePending=sample;if(!_scopeWorkerRunning){_scopeWorkerRunning=YES;start=YES;}}
}
}
if(start)dispatch_async(_scopeQueue,^{[self processPendingScopeSamples];});
}
- (NSData *)scopePreview{@synchronized(_previewLock){return [[_scopePreview retain]autorelease];}}
- (NSDictionary *)scopeMetadata{@synchronized(_previewLock){return [[_scopeMetadata retain]autorelease];}}
- (NSData*)outputHistogram{
DYScopeSample *sample=nil;
@synchronized(_previewLock){_outputObserved=YES;sample=[[_scopeLatest retain]autorelease];}
return sample.canvasHistogram;
}
- (void)queueOutputNotification{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW,NSEC_PER_SEC/30),dispatch_get_main_queue(),^{
@synchronized(_previewLock){_outputNotificationPending=NO;}
[NSNotificationCenter.defaultCenter postNotificationName:@"DYFinalOutputDidChange" object:self];
});
}
- (DYScopeSample *)finalSampleAtTime:(CMTime)time{
if(!CMTIME_IS_NUMERIC(time))return nil;
DYScopeSample *sample=nil;
@synchronized(_previewLock){sample=[_scopeLatest retain];}
NSDictionary *metadata=sample.metadata;
CMTime captured=CMTimeMakeWithEpoch([metadata[@"timeValue"]longLongValue],[metadata[@"timeScale"]intValue],[metadata[@"timeEpoch"]longLongValue]);
if(metadata&&CMTimeCompare(time,captured)==0)return [sample autorelease];
[sample release];
return nil;
}
- (NSData *)canvasHistogramAtTime:(CMTime)time {
return [self finalSampleAtTime:time].canvasHistogram;
}
- (DYColorProfile *)scopeProfileForSpace:(CGColorSpaceRef)space {
if(!space)return nil;
@synchronized(_scopeProfileLock){
if(!_scopeProfile||!CFEqual(_scopeProfile.source,space)){
CGColorSpaceRef target=CGColorSpaceCreateWithName(kCGColorSpaceExtendedSRGB);
if(!target)return nil;
[_scopeProfile release];
_scopeProfile=[[DYColorProfile alloc]initWithSource:space target:target error:nil];
CGColorSpaceRelease(target);
}
return [[_scopeProfile retain]autorelease];
}
}
- (NSData *)canvasSpiderScopeAtTime:(CMTime)time {
DYScopeSample *sample=[self finalSampleAtTime:time];
return sample?[sample spiderScopeWithProfile:[self scopeProfileForSpace:sample.space]]:nil;
}
- (NSData *)outputSpiderScope {
NSData *raster=nil;
@synchronized(_previewLock){
_outputObserved=YES;
raster=[[_spiderScopeRaster retain]autorelease];
if(!_scopeLatest||_spiderScopeWorkerRunning||_spiderScopeSerial==_scopeLatestSerial)return raster;
_spiderScopeWorkerRunning=YES;
}
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED,0),^{@autoreleasepool{
DYScopeSample *sample=nil;uint64_t serial;
@synchronized(_previewLock){sample=[_scopeLatest retain];serial=_scopeLatestSerial;}
NSData *measured=[sample spiderScopeWithProfile:[self scopeProfileForSpace:sample.space]];
@synchronized(_previewLock){
[_spiderScopeRaster release];_spiderScopeRaster=[measured retain];_spiderScopeSerial=serial;
_spiderScopeWorkerRunning=NO;
}
[sample release];
dispatch_async(dispatch_get_main_queue(),^{
[NSNotificationCenter.defaultCenter postNotificationName:@"DYSpiderScopeDidChange" object:self];
});
}});
return raster;
}
- (void)captureScopeTile:(FxImageTile *)tile atTime:(CMTime)time{
NSUInteger generation;uint64_t serial;@synchronized(_previewLock){if(_exporting||!tile)return;generation=_scopeGeneration;serial=++_scopeCaptureSerial;}
@autoreleasepool{@try{
NSDictionary *entry=nil,*context=nil;@synchronized(self){entry=[[self device:tile.deviceRegistryID error:nil]retain];context=[_colorContext copy];}
id<MTLDevice>device=entry[@"device"];id<MTLTexture>texture=[tile metalTextureForDevice:device];
if(!entry||!texture||!texture.width||!texture.height||texture.framebufferOnly){[entry release];[context release];return;}
id<MTLBuffer>buffer=[device newBufferWithLength:dyscope::Width*dyscope::Height*sizeof(dyscope::RGBA) options:MTLResourceStorageModeShared];
id<MTLCommandBuffer>command=[entry[@"queue"]commandBuffer];id<MTLComputeCommandEncoder>encoder=[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;
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(notifyOutput)[self queueOutputNotification];
if(start)dispatch_async(_scopeQueue,^{[self processPendingScopeSamples];});
}@catch(NSException *exception){/* Scope diagnostics must never fail rendering. */}}
}
- (void)processPendingScopeSamples{
for(;;){@autoreleasepool{
DYScopeSample *sample=nil;@synchronized(_previewLock){sample=_scopePending;_scopePending=nil;if(!sample){_scopeWorkerRunning=NO;return;}}
@synchronized(_previewLock){if(!_scopeEnabled||sample.generation!=_scopeGeneration){[sample release];continue;}}
auto reference=[sample displayReferenceWithProfile:[self scopeProfileForSpace:sample.space]];
const auto &pixels=reference->pixels;
uint64_t invalid=reference->invalid;
BOOL converted=reference->converted;
auto measurements=dyscope::measure(pixels);measurements.nonfinite+=invalid;
auto wave=dyscope::densityImage(measurements.wave,false),parade=dyscope::densityImage(measurements.parade,true),vectors=dyscope::vectorImage(measurements.vectors);
NSMutableDictionary *metadata=[[sample.metadata mutableCopy]autorelease];
metadata[@"domain"]=converted?@"sRGB 显示参考":@"宿主 RGB(未换算)";
metadata[@"note"]=converted?@"最终输出 · ICC 转扩展 sRGB · R′G′B′ 百分比;非 HDR / IRE 精密测量":@"最终输出 · 未完成颜色空间换算;RGB 原值 / 709 权重波形参考,非显示 / HDR / IRE 测量";
metadata[@"converted"]=@(converted);metadata[@"minimum"]=@(measurements.minimum);metadata[@"maximum"]=@(measurements.maximum);metadata[@"valid"]=@(measurements.valid);metadata[@"transparent"]=@(measurements.transparent>=invalid?measurements.transparent-invalid:0);metadata[@"nonfinite"]=@(measurements.nonfinite);metadata[@"below"]=@(measurements.below);metadata[@"above"]=@(measurements.above);
metadata[@"waveform"]=[NSData dataWithBytes:wave.data() length:wave.size()];metadata[@"parade"]=[NSData dataWithBytes:parade.data() length:parade.size()];metadata[@"histogram"]=[NSData dataWithBytes:measurements.histogram.data() length:sizeof(measurements.histogram)];metadata[@"vectorscope"]=[NSData dataWithBytes:vectors.data() length:vectors.size()];
BOOL publish=NO;@synchronized(_previewLock){if(_scopeEnabled&&sample.generation==_scopeGeneration){[_scopePreview release];_scopePreview=[[NSData alloc]initWithBytes:pixels.data() length:pixels.size()*sizeof(DYCompositeRGBA)];[_scopeMetadata release];_scopeMetadata=[metadata copy];publish=YES;}}
NSUInteger generation=sample.generation;[sample release];
if(publish)dispatch_async(dispatch_get_main_queue(),^{BOOL active=NO;@synchronized(_previewLock){active=_scopeEnabled&&generation==_scopeGeneration;}if(active)[NSNotificationCenter.defaultCenter postNotificationName:@"DYScopeDidChange" object:self];});
}}
}