185 行
13 KiB
C++
185 行
13 KiB
C++
// 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 frameDuration:kCMTimeInvalid exclusiveEnd:NO];}
|
||
- (void)setScopeEnabled:(BOOL)enabled atTime:(CMTime)time frameDuration:(CMTime)frameDuration exclusiveEnd:(BOOL)exclusiveEnd{
|
||
BOOL start=NO;@synchronized(_previewLock){if(_scopeEnabled==enabled)return;_scopeEnabled=enabled;_scopeGeneration++;[_scopePending release];_scopePending=nil;
|
||
if(enabled){
|
||
_scopeRequestedTime=time;_scopeRequestedFrameDuration=frameDuration;_scopeRequestedExclusiveEnd=exclusiveEnd;[_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;
|
||
BOOL replay=_scopeLatest&&(!CMTIME_IS_NUMERIC(time)||DYScopeFrameContainsTime(cached,time,frameDuration,exclusiveEnd));
|
||
os_log(OS_LOG_DEFAULT,"dayu_scope_open requested=%{public}.9f cached=%{public}.9f frame=%{public}.9f out=%{public}d replay=%{public}d",CMTimeGetSeconds(time),CMTimeGetSeconds(cached),CMTimeGetSeconds(frameDuration),exclusiveEnd,replay);
|
||
// Reuse this instance's final output when the host is still on that frame.
|
||
if(replay){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;
|
||
}
|
||
- (NSColor *)canvasColorAtPoint:(NSPoint)point atTime:(CMTime)time {
|
||
if(!std::isfinite(point.x)||!std::isfinite(point.y)||point.x<0||point.x>1||point.y<0||point.y>1)return nil;
|
||
DYScopeSample *sample=[self finalSampleAtTime:time];if(!sample||![sample.metadata[@"wholeImage"]boolValue])return nil;
|
||
auto reference=[sample displayReferenceWithProfile:[self scopeProfileForSpace:sample.space]];
|
||
if(!reference->converted||reference->pixels.size()!=dyscope::Width*dyscope::Height)return nil;
|
||
size_t x=MIN(dyscope::Width-1,(size_t)(point.x*dyscope::Width)),y=MIN(dyscope::Height-1,(size_t)(point.y*dyscope::Height));
|
||
const auto &p=reference->pixels[y*dyscope::Width+x];
|
||
if(!std::isfinite(p.r)||!std::isfinite(p.g)||!std::isfinite(p.b)||p.a<=1e-6f)return nil;
|
||
return [NSColor colorWithSRGBRed:std::clamp(p.r,0.f,1.f) green:std::clamp(p.g,0.f,1.f) blue:std::clamp(p.b,0.f,1.f) alpha:1];
|
||
}
|
||
- (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;
|
||
}
|
||
// 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<MTLTexture>)texture entry:(NSMutableDictionary *)entry commands:(id<MTLCommandBuffer>)command {
|
||
if(_exporting||!tile||!texture.width||!texture.height||texture.framebufferOnly)return {};
|
||
id<MTLComputePipelineState> pipeline=[self computePipeline:@"dyScopeSample" entry:entry error:nil];
|
||
if(!pipeline)return {};
|
||
id<MTLBuffer> buffer=entry[@"scopeBuffer"];
|
||
if(!buffer){
|
||
id<MTLDevice> device=entry[@"device"];
|
||
buffer=[[device newBufferWithLength:dyscope::Width*dyscope::Height*sizeof(dyscope::RGBA) options:MTLResourceStorageModeShared]autorelease];
|
||
if(!buffer)return {};
|
||
entry[@"scopeBuffer"]=buffer;
|
||
}
|
||
id<MTLComputeCommandEncoder> 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&&readback.serial==_scopeLatestSerial&&(readback.generation==_scopeGeneration||!CMTIME_IS_NUMERIC(_scopeRequestedTime)||DYScopeFrameContainsTime(time,_scopeRequestedTime,_scopeRequestedFrameDuration,_scopeRequestedExclusiveEnd))){
|
||
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. */}
|
||
}
|
||
- (BOOL)completeCommands:(id<MTLCommandBuffer>)command destination:(FxImageTile *)destination texture:(id<MTLTexture>)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<MTLTexture> texture=[tile metalTextureForDevice:entry[@"device"]];
|
||
id<MTLCommandBuffer> 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{
|
||
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];});
|
||
}}
|
||
}
|