131 行
11 KiB
C++
131 行
11 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];}
|
||
- (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;
|
||
}
|
||
- (NSData *)canvasSpiderScopeAtTime:(CMTime)time {
|
||
return [self finalSampleAtTime:time].spiderScope;
|
||
}
|
||
- (NSData *)outputSpiderScope {
|
||
NSData *raster=nil;
|
||
@synchronized(_previewLock){
|
||
_outputObserved=YES;
|
||
raster=[[_spiderScopeRaster retain]autorelease];
|
||
if(!_scopeLatest||_spiderScopeWorkerRunning||_spiderScopeSerial==_scopeLatestSerial)return raster;
|
||
_spiderScopeWorkerRunning=YES;
|
||
}
|
||
dispatch_async(_scopeQueue,^{@autoreleasepool{
|
||
DYScopeSample *sample=nil;uint64_t serial;
|
||
@synchronized(_previewLock){sample=[_scopeLatest retain];serial=_scopeLatestSerial;}
|
||
NSData *measured=sample.spiderScope;
|
||
@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;}}
|
||
const auto *raw=(const dyscope::RGBA*)sample.pixels.bytes;size_t count=sample.pixels.length/sizeof(dyscope::RGBA);std::vector<DYCompositeRGBA> pixels(count);uint64_t invalid=0;
|
||
for(size_t i=0;i<count;i++){
|
||
const auto&p=raw[i];BOOL finite=std::isfinite(p.r)&&std::isfinite(p.g)&&std::isfinite(p.b)&&std::isfinite(p.a);
|
||
if(!finite){invalid++;pixels[i]={0,0,0,0};continue;}
|
||
if(p.a<=1e-6f){pixels[i]={0,0,0,0};continue;}
|
||
pixels[i]={p.r/p.a,p.g/p.a,p.b/p.a,p.a};
|
||
if(!(std::isfinite(pixels[i].r)&&std::isfinite(pixels[i].g)&&std::isfinite(pixels[i].b))){invalid++;pixels[i]={0,0,0,0};}
|
||
}
|
||
NSError *error=nil;BOOL converted=NO;CGColorSpaceRef target=CGColorSpaceCreateWithName(kCGColorSpaceExtendedSRGB);
|
||
if(sample.space&&target){
|
||
if(!_scopeProfile||!CFEqual(_scopeProfile.source,sample.space)){[_scopeProfile release];_scopeProfile=[[DYColorProfile alloc]initWithSource:sample.space target:target error:&error];}
|
||
if(_scopeProfile){auto result=[_scopeProfile convertPixels:pixels alpha:dycm::Alpha::Straight budget:32ull*1024*1024 cancelled:nullptr error:&error];if(result){pixels=std::move(*result);converted=YES;}}
|
||
}if(target)CGColorSpaceRelease(target);
|
||
std::vector<dyscope::RGBA> reference;reference.reserve(pixels.size());for(const auto&p:pixels)reference.push_back({p.r,p.g,p.b,p.a});
|
||
auto measurements=dyscope::measure(reference);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 精密测量":(error?[NSString stringWithFormat:@"RGB 原值参考 · %@;波形按 709 权重参考,非 IRE",error.localizedDescription]:@"最终输出 · 空间未知;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];});
|
||
}}
|
||
}
|