diff --git a/tools/verify_lut_responsiveness.mm b/tools/verify_lut_responsiveness.mm index f5b98ca..68f6ebd 100644 --- a/tools/verify_lut_responsiveness.mm +++ b/tools/verify_lut_responsiveness.mm @@ -77,7 +77,7 @@ int main(int argc,const char *argv[]) {@autoreleasepool { }require(catalogOK,@"3000 catalog files in independent folders created"); [NSApplication sharedApplication];[NSApp setActivationPolicy:NSApplicationActivationPolicyProhibited]; NSMutableArray *selected=[NSMutableArray array]; - DYLUTBrowser *browser=[[DYLUTBrowser alloc]initWithLibrary:library preview:nil selectedPath:nil palette:@{} selection:^(NSString *path){[selected addObject:path?:@""];}]; + DYLUTBrowser *browser=[[DYLUTBrowser alloc]initWithLibrary:library preview:nil selectedPath:nil palette:@{} selection:^NSProgress *(NSString *path,void (^completion)(NSError *)){if(path.length)return DYLUTPrepareAsync(path,^(NSError *error){if(!error)[selected addObject:path];completion(error);});[selected addObject:@""];dispatch_async(dispatch_get_main_queue(),^{completion(nil);});return [NSProgress discreteProgressWithTotalUnitCount:1];}]; pump(^{return [browser valueForKey:@"libraryTask"]==nil;}); NSUInteger visible=[[browser valueForKey:@"visibleEntries"]count],tileCount=[[browser valueForKey:@"tiles"]count]; require([[browser valueForKey:@"folderPaths"]count]>3000&&[[browser valueForKey:@"folderButtons"]count]<30,@"large directory list creates only visible folder controls"); diff --git a/verification/ExternalLUTActivation.json b/verification/ExternalLUTActivation.json new file mode 100644 index 0000000..a630a69 --- /dev/null +++ b/verification/ExternalLUTActivation.json @@ -0,0 +1,77 @@ +{ + "date": "2026-11-01", + "status": "development-preflight-passed-formal-host-verification-pending", + "version": "1.1.4", + "build": "15", + "reportedTrigger": "External LUT imported successfully, then thumbnail clicked to apply", + "baselineCommit": "a2c8dfafcfe8c1974ec560b9586b78052356a0e4", + "finding": "A preview-cache preheat did not pin the selected table or GPU texture; frame rendering still performed path metadata queries and could parse external text again. Browser acknowledged selection before the inspector finished application.", + "changes": [ + "Decode and upload on the renderer preparation queue before committing the host path.", + "Retain immutable selected snapshots independently of preview caches; no file metadata or parsing on prepared frame paths.", + "Acknowledge browser selection only after preparation and accepted host write.", + "Cancel stale requests before they can overwrite a newer host selection." + ], + "nativeChecks": 92, + "nativePassed": true, + "externalChecks": [ + { + "name": "external-large-cube-written", + "pass": true + }, + { + "error": "未提供错误信息", + "name": "external-decode-and-gpu-upload-complete", + "pass": true + }, + { + "heartbeats": 4, + "maximumGapMS": 5.996874999254942, + "name": "external-activation-main-loop-responsive", + "pass": true + }, + { + "error": "", + "name": "external-first-frame-after-preparation", + "pass": true + }, + { + "name": "external-lut-affects-frame", + "pass": true + }, + { + "name": "external-source-removed-for-no-io-check", + "pass": true + }, + { + "name": "external-preview-and-gpu-cache-churn", + "pass": true + }, + { + "error": "", + "name": "external-render-with-source-unavailable-after-cache-churn", + "pass": true + }, + { + "changedComponents": 0, + "maxAbsoluteError": 0, + "name": "external-snapshot-is-independent-of-file-and-preview-cache", + "nonfiniteComponents": 0, + "nonzeroComponents": 9832, + "pass": true + }, + { + "name": "external-preparation-cancellation", + "pass": true + } + ], + "browserChecks": 56, + "browserPassed": true, + "browserMainMaxGapMS": 7.393208332359791, + "libraryChecks": 92, + "libraryPassed": true, + "limitations": [ + "No failing user-supplied LUT file was available in this run; the original user hang is not yet independently reproduced.", + "These preflight cases use synthetic local files and actual Metal/IOSurface rendering; live formal FCP acceptance remains a separate gate." + ] +} diff --git a/大鱼调色/Plugin/DYDiagnostics.mm b/大鱼调色/Plugin/DYDiagnostics.mm index 7ff23a1..033a9ac 100644 --- a/大鱼调色/Plugin/DYDiagnostics.mm +++ b/大鱼调色/Plugin/DYDiagnostics.mm @@ -2,6 +2,8 @@ #import "DYModel.h" #import "DYRenderer.h" #import "DYAutoGrade.h" +#import "DYLUTLibrary.h" +#include #import #import #include @@ -207,6 +209,46 @@ extern "C" int DYRunDiagnostics(void) { @autoreleasepool { NSURL *exportURL=[NSURL fileURLWithPath:[runtime stringByAppendingPathComponent:@"diagnostic-export.cube"]];error=nil;run.need(@"renderer-export-33cube",[renderer exportLUT:exportURL uniforms:u paths:paths error:&error],@{@"error":reason(error),@"path":exportURL.path}); NSString *exported=[NSString stringWithContentsOfURL:exportURL encoding:NSUTF8StringEncoding error:&error];NSUInteger triples=0,nonzero=0;bool exportFinite=true;for(NSString *line in [exported componentsSeparatedByCharactersInSet:NSCharacterSet.newlineCharacterSet]){float r,g,b;if(sscanf(line.UTF8String,"%f %f %f",&r,&g,&b)==3){triples++;exportFinite&=std::isfinite(r)&&std::isfinite(g)&&std::isfinite(b);if(r!=0||g!=0||b!=0)nonzero++;}} run.record(@"export-33cube-data-contract",[exported containsString:@"LUT_3D_SIZE 33"]&&triples==33*33*33&&exportFinite&&nonzero>0,@{@"rows":@(triples),@"nonzeroRows":@(nonzero),@"bytes":@([[[NSFileManager defaultManager]attributesOfItemAtPath:exportURL.path error:nil][NSFileSize]unsignedLongLongValue])}); + // A selected external table must outlive preview-cache churn and must + // not consult the file system again on the frame-render path. + NSString *external=[runtime stringByAppendingPathComponent:@"external-65.cube"]; + std::string externalCube="TITLE \"External activation fixture\"\nLUT_3D_SIZE 65\n";char row[128]; + for(int z=0;z<65;z++)for(int y=0;y<65;y++)for(int x=0;x<65;x++){snprintf(row,sizeof(row),"%.8f %.8f %.8f\n",x/64.f*.82f,y/64.f,z/64.f*1.12f);externalCube+=row;} + run.need(@"external-large-cube-written",[[NSData dataWithBytes:externalCube.data() length:externalCube.size()]writeToFile:external options:NSDataWritingAtomic error:&error]); + DYRenderer *externalRenderer=[[[DYRenderer alloc]init]autorelease]; + __block BOOL prepared=NO;__block NSError *preparationError=nil;__block NSUInteger beats=0;__block double last=NSProcessInfo.processInfo.systemUptime,maxGap=0; + NSTimer *heartbeat=[NSTimer scheduledTimerWithTimeInterval:.005 repeats:YES block:^(NSTimer *timer){double now=NSProcessInfo.processInfo.systemUptime;maxGap=std::max(maxGap,now-last);last=now;beats++;}]; + [externalRenderer prepareLUTPath:external completion:^(NSError *failure){preparationError=[failure retain];prepared=YES;}]; + double deadline=NSProcessInfo.processInfo.systemUptime+30; + while(!prepared&&NSProcessInfo.processInfo.systemUptime0&&maxGap<.15,@{@"heartbeats":@(beats),@"maximumGapMS":@(maxGap*1000)}); + DYUniforms externalUniforms=defaults;externalUniforms.lookSectionEnabled=1;externalUniforms.postLUTStrength=1; + NSDictionary *externalPaths=@{@"look0":external}; + Pixels externalFrame=render(run,externalRenderer,source,destination,gpu,externalUniforms,externalPaths,@"external-first-frame-after-preparation"); + run.record(@"external-lut-affects-frame",difference(neutral,externalFrame).different>100); + run.need(@"external-source-removed-for-no-io-check",[[NSFileManager defaultManager]removeItemAtPath:external error:&error]); + BOOL churnOK=YES; + for(int i=0;i<14;i++){@autoreleasepool{ + NSString *other=[runtime stringByAppendingPathComponent:[NSString stringWithFormat:@"eviction-%02d.cube",i]]; + NSString *text=@"LUT_3D_SIZE 2\n0 0 0\n1 0 0\n0 1 0\n1 1 0\n0 0 1\n1 0 1\n0 1 1\n1 1 1\n"; + churnOK&=[text writeToFile:other atomically:YES encoding:NSUTF8StringEncoding error:&error]; + __block BOOL ready=NO;__block BOOL success=NO; + [externalRenderer prepareLUTPath:other completion:^(NSError *failure){success=failure==nil;ready=YES;}]; + double until=NSProcessInfo.processInfo.systemUptime+10; + while(!ready&&NSProcessInfo.processInfo.systemUptime a=[self actionAPI];if(!a)return;[a startAction:self];NSString *selected=nil;@try{selected=[DYReadAssets(_manager,a.currentTime).paths[sender.identifier]copy];}@finally{[a endAction:self];} __block DYInspector *owner=self;NSString *key=[[sender.identifier copy]autorelease]; - _browser=[[DYLUTBrowser alloc]initWithLibrary:_library preview:[_renderer lookLUTPreview] selectedPath:selected palette:DYThemePalette() selection:^(NSString *path){[owner setAssetPath:path forKey:key];}];[selected release]; + _browser=[[DYLUTBrowser alloc]initWithLibrary:_library preview:[_renderer lookLUTPreview] selectedPath:selected palette:DYThemePalette() selection:^NSProgress *(NSString *path,void (^completion)(NSError *)){return [owner setAssetPath:path forKey:key completion:completion];}];[selected release]; id remote=[_manager apiForProtocol:@protocol(FxRemoteWindowAPI_v3)]; if(!remote)remote=[_manager apiForProtocol:@protocol(FxRemoteWindowAPI_v2)];if(!remote)remote=[_manager apiForProtocol:@protocol(FxRemoteWindowAPI)]; DYLUTBrowser *browser=_browser;id closer=[_manager apiForProtocol:@protocol(FxRemoteWindowAPI_v3)]; @@ -885,30 +887,44 @@ static NSImage *DYWheelImage(void) { NSError *error=nil;if(![[NSFileManager defaultManager]createDirectoryAtURL:_library.rootURL withIntermediateDirectories:YES attributes:nil error:&error]){[self showError:error.localizedDescription];return;}[[NSWorkspace sharedWorkspace]openURL:_library.rootURL]; } - (void)removeAsset:(NSButton *)sender { [self setAssetPath:nil forKey:sender.identifier]; } -- (void)setAssetPath:(NSString *)path forKey:(NSString *)key { +- (void)setAssetPath:(NSString *)path forKey:(NSString *)key {[self setAssetPath:path forKey:key completion:nil];} +- (NSProgress *)setAssetPath:(NSString *)path forKey:(NSString *)key completion:(void (^)(NSError *))completion { [_assetLoads[key]cancel];[_assetLoads removeObjectForKey:key];[_assetLoadIDs removeObjectForKey:key]; - if(!path.length){[self commitAssetPath:nil forKey:key];return;} + if(!path.length){ + NSError *error=nil;[self commitAssetPath:nil forKey:key error:&error]; + NSProgress *done=[NSProgress discreteProgressWithTotalUnitCount:1];done.completedUnitCount=1; + dispatch_async(dispatch_get_main_queue(),^{if(completion)completion(error);});return done; + } NSUInteger requestID=++_nextAssetLoadID;_assetLoadIDs[key]=@(requestID); - NSProgress *task=DYLUTPrepareAsync(path,^(NSError *error){ - if([_assetLoadIDs[key]unsignedIntegerValue]!=requestID||!self.window)return;[_assetLoads removeObjectForKey:key];[_assetLoadIDs removeObjectForKey:key]; - if(error){[self refresh];[_assetButtons[key][@"choose"]setTitle:@"载入失败"];[_assetButtons[key][@"choose"]setToolTip:error.localizedDescription];return;} - [self commitAssetPath:path forKey:key]; - });_assetLoads[key]=task;[_assetButtons[key][@"choose"]setTitle:@"正在载入…"]; + void (^prepared)(NSError *)=^(NSError *error){ + if([_assetLoadIDs[key]unsignedIntegerValue]!=requestID||!self.window){ + if(completion)completion([NSError errorWithDomain:NSCocoaErrorDomain code:NSUserCancelledError userInfo:nil]);return; + } + [_assetLoads removeObjectForKey:key];[_assetLoadIDs removeObjectForKey:key]; + NSError *result=error; + if(!result)[self commitAssetPath:path forKey:key error:&result]; + if(result){[self refresh];[_assetButtons[key][@"choose"]setTitle:@"载入失败"];[_assetButtons[key][@"choose"]setToolTip:result.localizedDescription];} + if(completion)completion(result); + }; + NSProgress *task=_renderer?[_renderer prepareLUTPath:path completion:prepared]:DYLUTPrepareAsync(path,prepared); + _assetLoads[key]=task;[_assetButtons[key][@"choose"]setTitle:@"正在载入…"];return task; } - (void)cancelAssetLoads { for(NSProgress *p in _assetLoads.allValues)[p cancel];[_assetLoads removeAllObjects];[_assetLoadIDs removeAllObjects]; } -- (void)commitAssetPath:(NSString *)path forKey:(NSString *)key { - id action=[self actionAPI];if(!action)return; - [action startAction:self]; +- (BOOL)commitAssetPath:(NSString *)path forKey:(NSString *)key error:(NSError **)error { + id action=[self actionAPI]; + if(!action){if(error)*error=[NSError errorWithDomain:@"com.dayu.color" code:1 userInfo:@{NSLocalizedDescriptionKey:@"宿主暂时无法应用 LUT,请重试"}];return NO;} + BOOL written=NO;[action startAction:self]; @try { CMTime t=action.currentTime;DYAssetState *assets=[[DYReadAssets(_manager,t) copy] autorelease]; if(!assets)assets=[[[DYAssetState alloc] init] autorelease]; NSMutableDictionary *paths=[[assets.paths mutableCopy] autorelease];if(!paths)paths=[NSMutableDictionary dictionary]; if(path.length)paths[key]=path;else [paths removeObjectForKey:key]; - assets.paths=paths;DYWriteAssets(_manager,assets,t); + assets.paths=paths;written=DYWriteAssets(_manager,assets,t); } @finally {[action endAction:self];} - [self postChanged]; + if(written)[self postChanged];else if(error)*error=[NSError errorWithDomain:@"com.dayu.color" code:1 userInfo:@{NSLocalizedDescriptionKey:@"宿主未接受此 LUT,原来的选择已保留"}]; + return written; } - (void)showError:(NSString *)message { NSAlert *a=[[[NSAlert alloc] init] autorelease];a.messageText=@"大鱼调色";a.informativeText=message?:@"操作未完成";[a addButtonWithTitle:@"好"];[a runModal]; diff --git a/大鱼调色/Plugin/DYLUTBrowser.h b/大鱼调色/Plugin/DYLUTBrowser.h index 5a95138..caebbd3 100644 --- a/大鱼调色/Plugin/DYLUTBrowser.h +++ b/大鱼调色/Plugin/DYLUTBrowser.h @@ -2,15 +2,16 @@ @class DYLUTLibrary; -/// A nonmodal browser. Selecting a validated thumbnail applies that LUT. -/// All UI and selection callbacks run on the main thread. +typedef NSProgress * (^DYLUTSelectionHandler)(NSString *path,void (^completion)(NSError *error)); +/// A nonmodal browser. The handler finishes asynchronously on the main thread +/// after decoding, GPU preparation and the host edit have actually succeeded. @interface DYLUTBrowser : NSWindowController @property(nonatomic,readonly) BOOL visible; - (instancetype)initWithLibrary:(DYLUTLibrary *)library preview:(NSData *)rgba selectedPath:(NSString *)path palette:(NSDictionary *)palette - selection:(void (^)(NSString *path))selection; + selection:(DYLUTSelectionHandler)selection; - (void)showRelativeToView:(NSView *)view; /// Attach to the FxRemoteWindow API's supplied parent; the caller owns that API. /// Completion, double-click and close dismiss through closeAction exactly once. diff --git a/大鱼调色/Plugin/DYLUTBrowser.mm b/大鱼调色/Plugin/DYLUTBrowser.mm index f47bb7e..bf7aad6 100644 --- a/大鱼调色/Plugin/DYLUTBrowser.mm +++ b/大鱼调色/Plugin/DYLUTBrowser.mm @@ -105,7 +105,7 @@ static NSString *const DYBrowserFolderPreference=@"com.dayu.color.lookLUTPreview NSData *_preview; NSString *_selectedPath,*_folder; NSDictionary *_palette; - void (^_selection)(NSString *); + DYLUTSelectionHandler _selection; void (^_closeAction)(void); NSPopover *_popover; DYBrowserCanvas *_root,*_folderDocument,*_gridDocument; @@ -133,7 +133,7 @@ static NSString *const DYBrowserFolderPreference=@"com.dayu.color.lookLUTPreview @implementation DYLUTBrowser static NSTextField *BrowserLabel(NSString *title,CGFloat size){NSTextField *label=[NSTextField labelWithString:title];label.font=[NSFont systemFontOfSize:size];label.lineBreakMode=NSLineBreakByTruncatingTail;return label;} static NSButton *BrowserButton(NSString *title,id target,SEL action){NSButton *button=[NSButton buttonWithTitle:title target:target action:action];button.font=[NSFont systemFontOfSize:11];button.bezelStyle=NSBezelStyleRounded;return button;} -- (instancetype)initWithLibrary:(DYLUTLibrary *)library preview:(NSData *)rgba selectedPath:(NSString *)path palette:(NSDictionary *)palette selection:(void (^)(NSString *))selection{ +- (instancetype)initWithLibrary:(DYLUTLibrary *)library preview:(NSData *)rgba selectedPath:(NSString *)path palette:(NSDictionary *)palette selection:(DYLUTSelectionHandler)selection{ NSPanel *panel=[[[NSPanel alloc]initWithContentRect:NSMakeRect(0,0,760,560) styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskClosable|NSWindowStyleMaskResizable backing:NSBackingStoreBuffered defer:NO]autorelease]; if((self=[super initWithWindow:panel])){ NSString *savedFolder=[[NSUserDefaults standardUserDefaults]stringForKey:DYBrowserFolderPreference]; @@ -397,19 +397,26 @@ static NSButton *BrowserButton(NSString *title,id target,SEL action){NSButton *b if(!sender.enabled||sender.failure.length)return; [_selectionTask cancel];[_selectionTask release];NSUInteger generation=++_selectionGeneration; NSString *path=sender.identifier,*name=sender.displayName;BOOL closeAfter=sender.doubleClicked;[self setStatus:[@"正在载入 " stringByAppendingString:name]]; - _selectionTask=[DYLUTPrepareAsync(path,^(NSError *error){ + void (^applied)(NSError *)=^(NSError *error){ if(_closed||generation!=_selectionGeneration)return;[_selectionTask release];_selectionTask=nil; if(error){[self setStatus:error.localizedDescription];return;} [_selectedPath release];_selectedPath=[path copy]; for(DYBrowserTile *tile in _tiles.allValues){tile.chosen=[tile.identifier isEqualToString:path];[tile setNeedsDisplay:YES];} - if(_selection)_selection(path);[self setStatus:[@"已选择 " stringByAppendingString:name]];if(closeAfter)[self close]; - })retain]; + [self setStatus:[@"已选择 " stringByAppendingString:name]];if(closeAfter)[self close]; + }; + _selectionTask=[(_selection?_selection(path,applied):DYLUTPrepareAsync(path,applied))retain]; } - (void)clearSelection:(id)sender{ - ++_selectionGeneration;[_selectionTask cancel];[_selectionTask release];_selectionTask=nil; - [_selectedPath release];_selectedPath=nil; - for(DYBrowserTile *tile in _tiles.allValues){tile.chosen=NO;[tile setNeedsDisplay:YES];} - if(_selection)_selection(nil);[self setStatus:@"已移除 LUT"]; + NSUInteger generation=++_selectionGeneration;[_selectionTask cancel];[_selectionTask release];_selectionTask=nil; + [self setStatus:@"正在移除 LUT…"]; + void (^cleared)(NSError *)=^(NSError *error){ + if(_closed||generation!=_selectionGeneration)return;[_selectionTask release];_selectionTask=nil; + if(error){[self setStatus:error.localizedDescription];return;} + [_selectedPath release];_selectedPath=nil; + for(DYBrowserTile *tile in _tiles.allValues){tile.chosen=NO;[tile setNeedsDisplay:YES];} + [self setStatus:@"已移除 LUT"]; + }; + if(_selection)_selectionTask=[_selection(nil,cleared)retain];else cleared(nil); } - (void)done:(id)sender{[self close];} - (void)showImportError:(NSError *)error{if(error&&!_closed)[self setStatus:error.localizedDescription];} diff --git a/大鱼调色/Plugin/DYLUTLibrary.h b/大鱼调色/Plugin/DYLUTLibrary.h index 5e51c96..88523ca 100644 --- a/大鱼调色/Plugin/DYLUTLibrary.h +++ b/大鱼调色/Plugin/DYLUTLibrary.h @@ -6,6 +6,19 @@ NS_ASSUME_NONNULL_BEGIN +/// Immutable decoded contents. A retained snapshot survives preview-cache +/// eviction and does not consult the source file while a frame is rendered. +@interface DYLUTPreparedTable : NSObject +@property(nonatomic,readonly) NSUInteger dimension; +@property(nonatomic,readonly,copy) NSString *path; +@property(nonatomic,readonly,copy) NSString *revision; +- (const float *)rgbaValues; +@end + +/// Synchronous worker-only entry; do not call it from an inspector action. +FOUNDATION_EXPORT DYLUTPreparedTable * _Nullable DYLUTReadPreparedTable(NSString *path, + NSProgress * _Nullable progress, NSError * _Nullable * _Nullable error); + #ifdef __cplusplus /// Same red-fastest 3D Cube table and DOMAIN resampling used by the renderer. /// Output is cleared on failure. Built-in .dylut tables are also supported. diff --git a/大鱼调色/Plugin/DYLUTLibrary.mm b/大鱼调色/Plugin/DYLUTLibrary.mm index 2508ce2..b823d2a 100644 --- a/大鱼调色/Plugin/DYLUTLibrary.mm +++ b/大鱼调色/Plugin/DYLUTLibrary.mm @@ -32,12 +32,19 @@ static BOOL DYLUTFail(NSError **error,NSString *message) { return NO; } -@interface DYLUTTable : NSObject { +@interface DYLUTPreparedTable () { @public std::vector values; -@public NSUInteger dimension; +@public NSUInteger _dimension; +@public NSString *_path,*_revision; } @end -@implementation DYLUTTable @end +@implementation DYLUTPreparedTable +- (void)dealloc {[_path release];[_revision release];[super dealloc];} +- (NSUInteger)dimension {return _dimension;} +- (NSString *)path {return _path;} +- (NSString *)revision {return _revision;} +- (const float *)rgbaValues {return values.data();} +@end static NSCache *DYLUTTableCache(void) { static NSCache *cache;static dispatch_once_t once; @@ -137,19 +144,24 @@ static BOOL DYLUTParse(NSString *path,std::vector& data,NSUInteger& size, return YES; } -static BOOL DYLUTReadCancellable(NSString *path,std::vector& data,NSUInteger& size,NSProgress *progress,NSError **error) { - data.clear();size=0; - if(!path.length)return DYLUTFail(error,@"未选择 LUT 文件"); +DYLUTPreparedTable *DYLUTReadPreparedTable(NSString *path,NSProgress *progress,NSError **error) { + if(DYLUTCancelled(progress,error))return nil; + if(!path.length){DYLUTFail(error,@"未选择 LUT 文件");return nil;} NSDictionary *a=[[NSFileManager defaultManager]attributesOfItemAtPath:path error:error]; - if(!a)return NO; + if(!a)return nil; NSString *key=[NSString stringWithFormat:@"%@|%.9f|%@|%@",path.stringByStandardizingPath,[a[NSFileModificationDate]timeIntervalSinceReferenceDate],a[NSFileSize],a[NSFileSystemFileNumber]]; - DYLUTTable *cached=[DYLUTTableCache()objectForKey:key]; - if(cached){data=cached->values;size=cached->dimension;return YES;} + DYLUTPreparedTable *cached=[DYLUTTableCache()objectForKey:key]; + if(cached)return cached; std::vector parsed;NSUInteger n=0; - if(DYLUTCancelled(progress,error)||!DYLUTParse(path,parsed,n,progress,error))return NO; - DYLUTTable *table=[[[DYLUTTable alloc]init]autorelease];table->values=std::move(parsed);table->dimension=n; + if(DYLUTCancelled(progress,error)||!DYLUTParse(path,parsed,n,progress,error))return nil; + DYLUTPreparedTable *table=[[[DYLUTPreparedTable alloc]init]autorelease];table->values=std::move(parsed);table->_dimension=n; + table->_path=[path copy];table->_revision=[key copy]; [DYLUTTableCache()setObject:table forKey:key cost:table->values.size()*sizeof(float)]; - data=table->values;size=n;return YES; + return table; +} +static BOOL DYLUTReadCancellable(NSString *path,std::vector& data,NSUInteger& size,NSProgress *progress,NSError **error) { + data.clear();size=0;DYLUTPreparedTable *table=DYLUTReadPreparedTable(path,progress,error); + if(!table)return NO;data=table->values;size=table.dimension;return YES; } BOOL DYLUTReadCube(NSString *path,std::vector& data,NSUInteger& size,NSError **error) { @@ -162,7 +174,7 @@ NSProgress *DYLUTPrepareAsync(NSString *path,void (^completion)(NSError *)) { dispatch_async(queue,^{@autoreleasepool{ NSError *error=nil;std::vector values;NSUInteger n=0; DYLUTReadCancellable(path,values,n,progress,&error);DYLUTCancelled(progress,&error);progress.completedUnitCount=1; - dispatch_async(dispatch_get_main_queue(),^{if(completion)completion(error);}); + dispatch_async(dispatch_get_main_queue(),^{NSError *result=error;DYLUTCancelled(progress,&result);if(completion)completion(result);}); }});return progress; } diff --git a/大鱼调色/Plugin/DYRenderer.h b/大鱼调色/Plugin/DYRenderer.h index 6d08d63..470a8de 100644 --- a/大鱼调色/Plugin/DYRenderer.h +++ b/大鱼调色/Plugin/DYRenderer.h @@ -3,6 +3,9 @@ #import #import "DYUniforms.h" @interface DYRenderer : NSObject +/// Decode and upload before committing a host parameter. The renderer retains +/// the immutable selected contents independently of the thumbnail cache. +- (NSProgress *)prepareLUTPath:(NSString *)path completion:(void (^)(NSError *error))completion; - (BOOL)renderSource:(FxImageTile*)source destination:(FxImageTile*)destination uniforms:(DYUniforms)uniforms paths:(NSDictionary*)paths error:(NSError**)error; - (BOOL)exportLUT:(NSURL*)url uniforms:(DYUniforms)uniforms paths:(NSDictionary*)paths error:(NSError**)error; - (NSData*)preview; diff --git a/大鱼调色/Plugin/DYRenderer.mm b/大鱼调色/Plugin/DYRenderer.mm index 293990f..9571832 100644 --- a/大鱼调色/Plugin/DYRenderer.mm +++ b/大鱼调色/Plugin/DYRenderer.mm @@ -9,7 +9,9 @@ static BOOL fail(NSError**e,NSString*m){if(e)*e=[NSError errorWithDomain:@"com.d static NSArray *inputFiles(){return @[@"",@"apple_log_to_rec709",@"arri_logc3_to_rec709",@"arri_logc4_to_rec709",@"blackmagic_film_gen5_to_rec709",@"canon_clog_bt709_to_rec709",@"canon_clog2_cinema_gamut_to_rec709",@"canon_clog3_cinema_gamut_to_rec709",@"dji_dlog_to_rec709",@"dji_dlog_m_to_rec709",@"fujifilm_flog_to_rec709",@"fujifilm_flog2_to_rec709",@"nikon_nlog_to_rec709",@"panasonic_vlog_vgamut_to_rec709",@"red_log3g10_rwg_to_rec709",@"sony_slog2_sgamut_to_rec709",@"sony_slog3_sgamut3cine_to_rec709",@"sony_hlg_bt2020_to_rec709"];} static id texture3D(idd,const float*values,NSUInteger n){MTLTextureDescriptor*t=[MTLTextureDescriptor new];t.textureType=MTLTextureType3D;t.pixelFormat=MTLPixelFormatRGBA32Float;t.width=n;t.height=n;t.depth=n;t.storageMode=MTLStorageModeShared;t.usage=MTLTextureUsageShaderRead;idx=[d newTextureWithDescriptor:t];[t release];if(x)[x replaceRegion:MTLRegionMake3D(0,0,0,n,n,n) mipmapLevel:0 slice:0 withBytes:values bytesPerRow:n*16 bytesPerImage:n*n*16];return [x autorelease];} @interface DYRenderer(){ - NSMutableDictionary *_devices,*_luts; + NSMutableDictionary *_devices,*_luts,*_preparedLUTs; + NSSet *_activeLUTPaths; + dispatch_queue_t _lutPreparationQueue; DYColorTables *_tables; NSObject *_previewLock; NSData *_preview,*_lookLUTPreview; @@ -17,8 +19,30 @@ static id texture3D(idd,const float*values,NSUInteger n){ } @end @implementation DYRenderer -- (instancetype)init{if((self=[super init])){_previewLock=[NSObject new];_devices=[NSMutableDictionary new];_luts=[NSMutableDictionary new];_tables=[DYColorTables new];}return self;} -- (void)dealloc{[_devices release];[_luts release];[_tables release];[_preview release];[_lookLUTPreview release];[_previewLock release];[super dealloc];} +- (instancetype)init{if((self=[super init])){_previewLock=[NSObject new];_devices=[NSMutableDictionary new];_luts=[NSMutableDictionary new];_preparedLUTs=[NSMutableDictionary new];_activeLUTPaths=[NSSet new];_lutPreparationQueue=dispatch_queue_create("com.dayu.color.lut-upload",DISPATCH_QUEUE_SERIAL);_tables=[DYColorTables new];}return self;} +- (void)dealloc{[_devices release];[_luts release];[_preparedLUTs release];[_activeLUTPaths release];dispatch_release(_lutPreparationQueue);[_tables release];[_preview release];[_lookLUTPreview release];[_previewLock release];[super dealloc];} +- (void)trimPreparedLUTsKeeping:(NSString *)path { + if(_preparedLUTs.count<=12)return; + for(NSString *key in _preparedLUTs.allKeys)if(![_activeLUTPaths containsObject:key]&&![key isEqualToString:path])[_preparedLUTs removeObjectForKey:key]; +} +- (id)textureForTable:(DYLUTPreparedTable *)table entry:(NSDictionary *)entry error:(NSError **)error { + NSString *key=[NSString stringWithFormat:@"%llu|%@",[entry[@"device"]registryID],table.revision];idtexture=_luts[key]; + if(!texture){texture=texture3D(entry[@"device"],table.rgbaValues,table.dimension);if(!texture){fail(error,@"LUT 纹理分配失败");return nil;}if(_luts.count>=12)[_luts removeAllObjects];_luts[key]=texture;}return texture; +} +- (NSProgress *)prepareLUTPath:(NSString *)path completion:(void (^)(NSError *))completion { + NSProgress *progress=[NSProgress discreteProgressWithTotalUnitCount:2];progress.localizedDescription=@"正在载入 LUT…";path=[[path copy]autorelease]; + dispatch_async(_lutPreparationQueue,^{@autoreleasepool{ + NSError *error=nil;DYLUTPreparedTable *table=progress.cancelled?nil:DYLUTReadPreparedTable(path,progress,&error);progress.completedUnitCount=1; + if(table&&!progress.cancelled){@synchronized(self){ + if(!_devices.count)[self device:0 error:&error]; + if(!_devices.count&&!error)fail(&error,@"没有可用的 LUT 渲染设备"); + BOOL ready=error==nil;for(NSDictionary *entry in _devices.allValues)if(!progress.cancelled&&![self textureForTable:table entry:entry error:&error]){ready=NO;break;} + if(ready&&!progress.cancelled){_preparedLUTs[path]=table;[self trimPreparedLUTsKeeping:path];} + }} + if(progress.cancelled)error=[NSError errorWithDomain:NSCocoaErrorDomain code:NSUserCancelledError userInfo:@{NSLocalizedDescriptionKey:@"已取消 LUT 加载"}]; + progress.completedUnitCount=2;dispatch_async(dispatch_get_main_queue(),^{NSError *result=progress.cancelled?[NSError errorWithDomain:NSCocoaErrorDomain code:NSUserCancelledError userInfo:nil]:error;if(completion)completion(result);}); + }});return progress; +} - (void)invalidatePreview{@synchronized(_previewLock){[_preview release];_preview=nil;[_lookLUTPreview release];_lookLUTPreview=nil;_lastPreview=0;}} - (NSData*)preview{@synchronized(_previewLock){return [[_preview retain]autorelease];}} - (NSData*)lookLUTPreview{@synchronized(_previewLock){return [[_lookLUTPreview retain]autorelease];}} @@ -34,9 +58,11 @@ static id texture3D(idd,const float*values,NSUInteger n){ } - (id)lut:(NSString*)path entry:(NSDictionary*)e error:(NSError**)err{ if(!path.length)return e[@"identity"]; - NSDictionary*attrs=[[NSFileManager defaultManager]attributesOfItemAtPath:path error:err];if(!attrs)return nil; - NSString*key=[NSString stringWithFormat:@"%llu|%@|%.9f|%@|%@",[e[@"device"]registryID],path,[attrs[NSFileModificationDate]timeIntervalSinceReferenceDate],attrs[NSFileSize],attrs[NSFileSystemFileNumber]];idt=_luts[key];if(t)return t; - std::vectorv;NSUInteger n=0;if(!DYLUTReadCube(path,v,n,err))return nil;t=texture3D(e[@"device"],v.data(),n);if(!t){fail(err,@"LUT 纹理分配失败");return nil;}if(_luts.count>=12)[_luts removeAllObjects];_luts[key]=t;return t; + DYLUTPreparedTable *table=_preparedLUTs[path]; + // Restored projects load once on their render worker. Explicit selections + // arrive prepared, so neither metadata I/O nor text parsing occurs here. + if(!table){table=DYLUTReadPreparedTable(path,nil,err);if(!table)return nil;_preparedLUTs[path]=table;[self trimPreparedLUTsKeeping:path];} + return [self textureForTable:table entry:e error:err]; } - (NSArray*)textures:(NSDictionary*)paths uniforms:(DYUniforms*)u entry:(NSDictionary*)e error:(NSError**)err{ // Normalize only this render copy. Folded groups retain their host parameters @@ -54,6 +80,7 @@ static id texture3D(idd,const float*values,NSUInteger n){ 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)renderSource:(FxImageTile*)src destination:(FxImageTile*)dst uniforms:(DYUniforms)u paths:(NSDictionary*)paths error:(NSError**)err{@synchronized(self){@autoreleasepool{ + [_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,@"宿主图像纹理不可用"); NSArray*ts=[self textures:paths uniforms:&u entry:e error:err];if(!ts)return NO; NSMutableDictionary*ps=e[@"pipelines"];NSNumber*format=@(output.pixelFormat);idpipeline=ps[format];if(!pipeline){MTLRenderPipelineDescriptor*p=[MTLRenderPipelineDescriptor new];p.vertexFunction=[e[@"library"]newFunctionWithName:@"dyVertex"];p.fragmentFunction=[e[@"library"]newFunctionWithName:@"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];} diff --git a/大鱼调色/Plugin/Info.plist b/大鱼调色/Plugin/Info.plist index 7b5a938..bd40292 100644 --- a/大鱼调色/Plugin/Info.plist +++ b/大鱼调色/Plugin/Info.plist @@ -17,9 +17,9 @@ CFBundlePackageType XPC! CFBundleShortVersionString - 1.1.3 + 1.1.4 CFBundleVersion - 14 + 15 NSHumanReadableCopyright PlugInKit diff --git a/大鱼调色/Wrapper Application/Info.plist b/大鱼调色/Wrapper Application/Info.plist index b8f443e..5fdf45b 100644 --- a/大鱼调色/Wrapper Application/Info.plist +++ b/大鱼调色/Wrapper Application/Info.plist @@ -17,9 +17,9 @@ CFBundlePackageType APPL CFBundleShortVersionString - 1.1.3 + 1.1.4 CFBundleVersion - 14 + 15 LSMinimumSystemVersion $(MACOSX_DEPLOYMENT_TARGET) NSHumanReadableCopyright