#include #import "DYToolState.h" #include "DYSpiderState.h" #include "DYFilmMath.h" #include #import #import #import static char DYScreenInfoKey; NSDictionary *DYScreenToolCatalog(void){static NSDictionary *catalog;static dispatch_once_t once;dispatch_once(&once,^{catalog=[@{@"curve":@"点击曲线加点,拖动调整;通道、整体强度和精细参数在面板中设置。",@"lens":@"拖动画面网格调整畸变,拖动中心点定位光学中心;缩放与强度在详情中设置。",@"skin":@"切换画面肤色保护区域;保护程度、色相及人脸限定在详情中设置。",@"look":@"在控制面板选择 LUT;整体强度与各风格位置的强度分别调节。",@"whiteBalance":@"点击画面中的中性白色或灰色取样;Esc 取消,色温和色调可在详情中精调。",@"cloneStamp":@"先点击取样中心,再拖出覆盖区域;取样、羽化、参考区域和跟踪在蒙版详情中设置。",@"level":@"点击两点或拖出参考线;水平、垂直、仅测量和重置在详情中设置。",@"mosaic":@"选择人脸或已绘制蒙版,调整方块大小;蒙版跟踪保留在蒙版详情中。",@"rectangle":@"在画面拖出矩形,松开保存;位置、尺寸、羽化、强度及跟踪在蒙版详情中设置。",@"ellipse":@"在画面拖出椭圆,松开保存;位置、尺寸、羽化、强度及跟踪在蒙版详情中设置。",@"pen":@"点击放点,拖出曲柄,点首节点或回车闭合;Esc 取消,删除键撤回最后一点。"}copy];});return catalog;} NSDictionary *DYCurrentScreenToolInfo(id host){return objc_getAssociatedObject(host,&DYScreenInfoKey);} void DYPublishScreenToolInfo(id host,NSString *type,NSString *message){if(!host)return;dispatch_async(dispatch_get_main_queue(),^{NSDictionary *old=DYCurrentScreenToolInfo(host);NSString *kind=type?:old[@"type"]?:@"";NSDictionary *info=@{@"type":kind,@"message":message?:DYScreenToolCatalog()[kind]?:@""};if([old isEqual:info])return;objc_setAssociatedObject(host,&DYScreenInfoKey,info,OBJC_ASSOCIATION_COPY_NONATOMIC);[NSNotificationCenter.defaultCenter postNotificationName:@"DYScreenToolInfo" object:host userInfo:info];});} NSArray *DYToolTypes(void){return @[@"primary",@"spider",@"base",@"skin",@"look",@"hsl",@"curve",@"grading",@"primaries",@"levels",@"blackwhite",@"balance",@"mixer",@"film",@"lens"];} NSDictionary *DYToolSection(NSString *type){for(NSDictionary *s in DYSections())if([s[@"key"]isEqual:type])return s;return nil;} static NSArray *DYBaseToolParts(NSString *type){return [type isEqual:@"primary"]?@[@"input",@"primary",@"output"]:[type isEqual:@"base"]?@[@"base",@"color"]:@[type];} static NSArray *DYBuildBaseToolDescriptors(NSString *type){ if(![DYToolTypes()containsObject:type])return @[];NSMutableSet *pids=[NSMutableSet set]; for(NSString *part in DYBaseToolParts(type)){NSDictionary *section=DYToolSection(part);if(section[@"enabled"])[pids addObject:section[@"enabled"]];for(NSDictionary *row in section[@"rows"]){if(row[@"pid"])[pids addObject:row[@"pid"]];if(row[@"enabled"])[pids addObject:row[@"enabled"]];}} NSMutableArray *result=[NSMutableArray array];for(NSDictionary *d in DYDescriptors()){ NSString *key=d[@"key"];BOOL extra=([type isEqual:@"primary"]&&([key hasPrefix:@"cm"]||[@[@"primaryMasterEnabled",@"inputProfile",@"preLUTStrength"]containsObject:key]))||([type isEqual:@"base"]&&[key isEqual:@"copyAutoGrade"])||([type isEqual:@"look"]&&([key hasPrefix:@"look"]||[key isEqual:@"postLUTStrength"]))||([type isEqual:@"film"]&&[key hasPrefix:@"film"]); if(extra||[pids containsObject:d[@"pid"]])[result addObject:d]; }return [[result copy]autorelease]; } static NSDictionary *DYToolRemovalCatalog(){ static NSDictionary *catalog;static dispatch_once_t once;dispatch_once(&once,^{ NSMutableDictionary *values=[NSMutableDictionary dictionary],*switches=[NSMutableDictionary dictionary]; for(NSString *type in DYToolTypes()){NSArray *owned=DYBuildBaseToolDescriptors(type);values[type]=owned;NSMutableArray *offsets=[NSMutableArray array];for(NSString *part in DYBaseToolParts(type))for(NSDictionary *d in owned)if([d[@"pid"]isEqual:DYToolSection(part)[@"enabled"]])[offsets addObject:d[@"offset"]];switches[type]=[[offsets copy]autorelease];} catalog=[@{@"values":values,@"switches":switches}copy]; });return catalog; } NSArray *DYBaseToolDescriptors(NSString *type){return DYToolRemovalCatalog()[@"values"][type]?:@[];} BOOL DYBaseToolRemoved(NSDictionary *doc,NSString *type){return [doc[@"removedBase"]containsObject:type];} BOOL DYSetBaseToolRemoved(NSMutableDictionary *doc,NSString *type,BOOL removed){ if(!DYValidToolDocument(doc)||![DYToolTypes()containsObject:type])return NO; NSMutableArray *types=[NSMutableArray arrayWithArray:doc[@"removedBase"]?:@[]];[types removeObject:type];if(removed){[types addObject:type];[doc[@"baseMasks"]removeObjectForKey:type];[doc[@"strengths"]removeObjectForKey:[@"base:" stringByAppendingString:type]];} if(types.count)doc[@"removedBase"]=types;else[doc removeObjectForKey:@"removedBase"];return YES; } void DYApplyRemovedBaseTools(DYUniforms *u,NSDictionary *doc){ for(NSString *type in doc[@"removedBase"]){ for(NSDictionary *d in DYBaseToolDescriptors(type))if([d[@"offset"]integerValue]>=0)*(float*)((uint8_t*)u+[d[@"offset"]unsignedIntegerValue])=[d[@"default"]floatValue]; for(NSNumber *offset in DYToolRemovalCatalog()[@"switches"][type])*(float*)((uint8_t*)u+offset.unsignedIntegerValue)=0; if([type isEqual:@"primary"]){u->primarySectionEnabled=0;u->inputProfile=0;u->preLUTStrength=0;} } } NSDictionary *DYVisibleBaseToolPaths(NSDictionary *paths,NSDictionary *doc){ if(!DYBaseToolRemoved(doc,@"primary")&&!DYBaseToolRemoved(doc,@"look"))return paths; NSMutableDictionary *result=[[paths mutableCopy]autorelease]?:[NSMutableDictionary dictionary];if(DYBaseToolRemoved(doc,@"primary"))[result removeObjectForKey:@"input"]; if(DYBaseToolRemoved(doc,@"look"))for(NSInteger i=0;i<5;i++)[result removeObjectForKey:[NSString stringWithFormat:@"look%ld",(long)i]];return result; } BOOL DYResetToolParameters(id host,NSArray *rows,CMTime time,NSError **error){ id animation=[host apiForProtocol:@protocol(FxKeyframeAPI_v3)];NSMutableArray *channels=[NSMutableArray array]; // Query every affected channel before making the first edit. Deleted base // tools also stay excluded by document state if a host lacks this API. if(animation)for(NSDictionary *d in rows)if(![d[@"notAnimatable"]boolValue]){ NSUInteger count=0;NSError *failure=[animation channelCount:&count forParameter:[d[@"pid"]unsignedIntegerValue]];if(failure){if(error)*error=failure;return NO;} for(NSUInteger channel=0;channel set=[host apiForProtocol:@protocol(FxParameterSettingAPI_v6)]; for(NSDictionary *d in rows)if(![set setFloatValue:[d[@"default"]doubleValue] toParameter:[d[@"pid"]unsignedIntValue] atTime:time]){if(error)*error=[NSError errorWithDomain:@"com.dayu.color.ToolReset" code:1 userInfo:@{NSLocalizedDescriptionKey:[NSString stringWithFormat:@"未能还原“%@”,模块已保留。",d[@"title"]?:d[@"key"]]}];return NO;} return YES; } NSMutableDictionary *DYMutablePlist(NSDictionary *value){ if(!value)return [NSMutableDictionary dictionary]; return [(NSMutableDictionary*)CFPropertyListCreateDeepCopy(kCFAllocatorDefault,(CFPropertyListRef)value,kCFPropertyListMutableContainersAndLeaves) autorelease]; } NSDictionary *DYInitialToolDocument(NSString *starter) { NSMutableDictionary *doc=[NSMutableDictionary dictionaryWithDictionary:@{@"schema":@1,@"layers":@[],@"baseMasks":@{}}]; if([DYToolTypes() containsObject:starter]||[starter isEqual:@"cst"]){ NSMutableArray *removed=[NSMutableArray arrayWithArray:DYToolTypes()]; [removed removeObject:[starter isEqual:@"cst"]?@"primary":starter]; doc[@"removedBase"]=removed; doc[@"starterTool"]=starter; } return doc; } static BOOL finiteNumber(id v){return [v isKindOfClass:NSNumber.class]&&std::isfinite([v doubleValue]);} static BOOL validStampValues(id values,NSUInteger count,NSUInteger offsets,double minScale,double maxScale){ if(![values isKindOfClass:NSArray.class]||[values count]!=count)return NO; for(NSUInteger i=0;i1:valuemaxScale)return NO; } return YES; } static BOOL validID(id v){return [v isKindOfClass:NSString.class]&&[[[NSUUID alloc]initWithUUIDString:v]autorelease]!=nil;} static NSData *parameterData(DYMaskParameters p){return [NSData dataWithBytes:&p length:sizeof(p)];} static BOOL readParameters(id data,DYMaskParameters *p){if(![data isKindOfClass:NSData.class]||[data length]!=sizeof(*p))return NO;[data getBytes:p length:sizeof(*p)];return dyValidMaskParameters(*p);} static CMTime keyTime(NSDictionary *key){return CMTimeMakeWithEpoch([key[@"value"]longLongValue],[key[@"scale"]intValue],[key[@"epoch"]longLongValue]);} NSDictionary *DYNewMask(NSInteger kind){if(kind<0||kind>5)return nil;DYMaskParameters p=dyDefaultMaskParameters();p.kind=(DYMaskKind)kind;p.width=.5;p.height=.5;p.sourceStage=DYMaskSourceOriginal;if(kind==DYMaskHSLKey)p.flags=DYMaskHueEnabled;NSData *nodes=[NSData data];if(kind==DYMaskBezier){DYBezierNode n[4]={};float x[4]={-.5,.5,.5,-.5},y[4]={-.5,-.5,.5,.5};for(int i=0;i<4;i++)n[i]={x[i],y[i],x[i],y[i],x[i],y[i]};nodes=[NSData dataWithBytes:n length:sizeof(n)];}return @{@"id":NSUUID.UUID.UUIDString,@"enabled":@YES,@"combine":@0,@"parameters":parameterData(p),@"nodes":nodes,@"keys":@[]};} NSDictionary *DYNewTool(NSString *type){if(![DYToolTypes()containsObject:type])return nil;return @{@"id":NSUUID.UUID.UUIDString,@"type":type,@"values":[type isEqual:@"skin"]?@{@"skinEnabled":@0}:[type isEqual:@"primary"]?@{@"cmtoneMapping":@0}:@{},@"paths":@{},@"spiderLinked":@YES,@"masks":@[]};} BOOL DYValidToolMask(NSDictionary *mask){ if(![mask isKindOfClass:NSDictionary.class]||!validID(mask[@"id"])||!finiteNumber(mask[@"enabled"])||!finiteNumber(mask[@"combine"])||[mask[@"combine"]integerValue]<0||[mask[@"combine"]integerValue]>2)return NO; if(mask[@"label"]&&(![mask[@"label"]isKindOfClass:NSString.class]||[mask[@"label"]length]>100))return NO; DYMaskParameters p;if(!readParameters(mask[@"parameters"],&p))return NO;NSData *nodes=mask[@"nodes"];if(![nodes isKindOfClass:NSData.class]||nodes.length%sizeof(DYBezierNode)||nodes.length>32*sizeof(DYBezierNode))return NO; id source=mask[@"stampSource"]; if(source){ if(p.kind!=DYMaskEllipse||![source isKindOfClass:NSArray.class]||[source count]!=4)return NO; for(NSUInteger i=0;i<4;i++)if(!finiteNumber(source[i])||[source[i] doubleValue]<(i<2?0:.001)||[source[i] doubleValue]>1)return NO; } id samplingScale=mask[@"stampSamplingScale"]; if(samplingScale&&(!source||!validStampValues(samplingScale,2,0,1./256,256)))return NO; id mode=mask[@"stampTrackMode"],reference=mask[@"stampReference"]; if(mode&&(!source||![@[@"linked",@"independent"]containsObject:mode]))return NO; if(reference){ if(!source||![reference isKindOfClass:NSArray.class]||[reference count]!=4)return NO; for(NSUInteger i=0;i<4;i++)if(!finiteNumber(reference[i])|| (i<2?fabs([reference[i]doubleValue])>2048:[reference[i]doubleValue]<.001||[reference[i]doubleValue]>2048))return NO; } if(mask[@"status"]&&(![mask[@"status"]isKindOfClass:NSString.class]||[mask[@"status"]length]>2000))return NO; if(mask[@"trackingStopped"]&&![@[@YES,@NO]containsObject:mask[@"trackingStopped"]])return NO; for(NSString *field in @[@"trackingLastTime",@"trackingStopTime"]){ id value=mask[field];if(value&&(![value isKindOfClass:NSArray.class]||[value count]!=3))return NO; if(value){for(id n in value)if(!finiteNumber(n))return NO;if(!CMTIME_IS_NUMERIC(DYTrackingRecordedTime(mask,field)))return NO;} } const float *n=(const float*)nodes.bytes;for(NSUInteger i=0;i1000)return NO; NSArray *keys=mask[@"keys"];if(![keys isKindOfClass:NSArray.class]||keys.count>DYToolKeyLimit)return NO;CMTime last=kCMTimeInvalid; for(NSDictionary *k in keys){if(![k isKindOfClass:NSDictionary.class]||!finiteNumber(k[@"value"])||!finiteNumber(k[@"scale"])||!finiteNumber(k[@"epoch"])||!finiteNumber(k[@"manual"])||!finiteNumber(k[@"confidence"])||[k[@"confidence"]doubleValue]<0||[k[@"confidence"]doubleValue]>1)return NO;CMTime t=keyTime(k);DYMaskParameters q;if(!CMTIME_IS_NUMERIC(t)||!readParameters(k[@"parameters"],&q)||q.kind!=p.kind||(CMTIME_IS_NUMERIC(last)&&(last.epoch!=t.epoch||CMTimeCompare(last,t)>=0)))return NO; if(k[@"stampMotion"]&&(!source||!validStampValues(k[@"stampMotion"],6,2,1./16,16)))return NO; if(k[@"stampManualSource"]&&(!source||!k[@"stampMotion"]||![k[@"manual"]boolValue]||![@[@YES,@NO]containsObject:k[@"stampManualSource"]]))return NO; last=t; }return YES; } static BOOL validMasks(id masks,NSMutableSet *ids,NSSet *sharedIDs,BOOL references){ if(![masks isKindOfClass:NSArray.class]||[masks count]>DYToolMaskLimit)return NO;NSMutableSet *links=[NSMutableSet set]; for(NSDictionary *m in masks){if(![m isKindOfClass:NSDictionary.class])return NO;id shared=m[@"sharedID"];if(shared){if(!references||m.count!=1||![sharedIDs containsObject:shared]||[links containsObject:shared])return NO;[links addObject:shared];continue;}if(!DYValidToolMask(m)||m[@"stampSource"]||[ids containsObject:m[@"id"]])return NO;[ids addObject:m[@"id"]];}return YES; } static NSData *DYValidatedToolData(NSDictionary *doc){ if(![NSPropertyListSerialization propertyList:doc isValidForFormat:NSPropertyListBinaryFormat_v1_0])return nil; if(![doc isKindOfClass:NSDictionary.class]||(![doc[@"schema"]isEqual:@1]&&![doc[@"schema"]isEqual:@2]&&![doc[@"schema"]isEqual:@3])||![doc[@"layers"]isKindOfClass:NSArray.class]||[doc[@"layers"]count]>DYToolLimit||![doc[@"baseMasks"]isKindOfClass:NSDictionary.class]||[doc[@"baseMasks"]count]>DYToolTypes().count)return nil; id starter=doc[@"starterTool"],level=doc[@"levelRotation"]; id mosaic=doc[@"mosaic"]; if(mosaic){ if(![mosaic isKindOfClass:NSDictionary.class]||!finiteNumber(mosaic[@"enabled"])||![@[@0,@1]containsObject:mosaic[@"enabled"]]||![@[@"face",@"mask"]containsObject:mosaic[@"source"]]||!finiteNumber(mosaic[@"size"])||[mosaic[@"size"]doubleValue]<4||[mosaic[@"size"]doubleValue]>128)return nil; if(mosaic[@"maskID"]&&!validID(mosaic[@"maskID"]))return nil; if(mosaic[@"maskIDs"]){id ids=mosaic[@"maskIDs"];if(![ids isKindOfClass:NSArray.class]||[ids count]>DYSharedMaskLimit)return nil;NSMutableSet *seen=[NSMutableSet set];for(id ID in ids){if(!validID(ID)||[seen containsObject:ID])return nil;[seen addObject:ID];}} } if(doc[@"mosaicRenderMask"]&&!DYValidToolMask(doc[@"mosaicRenderMask"]))return nil; if(doc[@"mosaicRenderMasks"]){if(![doc[@"mosaicRenderMasks"]isKindOfClass:NSArray.class]||[doc[@"mosaicRenderMasks"]count]>DYSharedMaskLimit)return nil;for(id m in doc[@"mosaicRenderMasks"])if(!DYValidToolMask(m))return nil;} if(starter&&![DYToolTypes() containsObject:starter]&&![starter isEqual:@"cst"])return nil; if(level&&(!finiteNumber(level)||fabs([level doubleValue])>M_PI))return nil; id measured=doc[@"levelMeasureOnly"],reference=doc[@"levelReference"]; if(measured&&(!finiteNumber(measured)||([measured doubleValue]!=0&&[measured doubleValue]!=1)))return nil; if(reference){ if(![reference isKindOfClass:NSDictionary.class]||![reference[@"points"]isKindOfClass:NSArray.class]||[reference[@"points"]count]!=4||!finiteNumber(reference[@"aspect"])||[reference[@"aspect"]doubleValue]<=0||[reference[@"aspect"]doubleValue]>100||(![reference[@"mode"]isEqual:@1]&&![reference[@"mode"]isEqual:@2]))return nil; for(id value in reference[@"points"])if(!finiteNumber(value)||fabs([value doubleValue])>4)return nil; } BOOL references=[doc[@"schema"]isEqual:@3];id shared=doc[@"sharedMasks"];NSMutableSet *sharedIDs=[NSMutableSet set],*ids=[NSMutableSet set];if(shared){if(!references||![shared isKindOfClass:NSArray.class]||[shared count]>DYSharedMaskLimit)return nil;for(NSDictionary *mask in shared){if(!DYValidToolMask(mask)||[ids containsObject:mask[@"id"]]||mask[@"sharedID"])return nil;[ids addObject:mask[@"id"]];if(!mask[@"stampSource"])[sharedIDs addObject:mask[@"id"]];}} id removed=doc[@"removedBase"];if(removed){if(![removed isKindOfClass:NSArray.class]||[removed count]>DYToolTypes().count)return nil;NSMutableSet *unique=[NSMutableSet set];for(id type in removed){if(![type isKindOfClass:NSString.class]||![DYToolTypes()containsObject:type]||[unique containsObject:type]||[doc[@"baseMasks"][type]count])return nil;[unique addObject:type];}} for(NSString *key in doc[@"baseMasks"]){if(![DYToolTypes()containsObject:key]||!validMasks(doc[@"baseMasks"][key],ids,sharedIDs,references))return nil;} NSMutableDictionary *descriptors=[NSMutableDictionary dictionary];for(NSDictionary *d in DYDescriptors())descriptors[d[@"key"]]=d; for(NSDictionary *node in doc[@"layers"]){if(![node isKindOfClass:NSDictionary.class]||!validID(node[@"id"])||[ids containsObject:node[@"id"]]||![DYToolTypes()containsObject:node[@"type"]]||![node[@"values"]isKindOfClass:NSDictionary.class]||[node[@"values"]count]>descriptors.count||![node[@"paths"]isKindOfClass:NSDictionary.class]||[node[@"paths"]count]>6)return nil;[ids addObject:node[@"id"]];if(!validMasks(node[@"masks"],ids,sharedIDs,references))return nil; if(node[@"primaryFollow"]&&(![node[@"type"]isEqual:@"primary"]||!finiteNumber(node[@"primaryFollow"])||[node[@"primaryFollow"]doubleValue]!=floor([node[@"primaryFollow"]doubleValue])||[node[@"primaryFollow"]integerValue]<0||[node[@"primaryFollow"]integerValue]>7))return nil; for(NSString *key in node[@"values"]){NSDictionary *d=descriptors[key];id v=node[@"values"][key];if(!d||!finiteNumber(v)||[v doubleValue]<[d[@"min"]doubleValue]||[v doubleValue]>[d[@"max"]doubleValue]||(d[@"values"]&&![d[@"values"]containsObject:@((int)llround([v doubleValue]))]))return nil;} for(id key in node[@"paths"]){id p=node[@"paths"][key];if(![@[@"input",@"look0",@"look1",@"look2",@"look3",@"look4"]containsObject:key]||![p isKindOfClass:NSString.class]||[p length]>8192||![p isAbsolutePath]||![[p pathExtension].lowercaseString isEqual:@"cube"])return nil;}if(node[@"spider"]&&(![node[@"spider"]isKindOfClass:NSData.class]||!DYSpiderMeshIsValid(node[@"spider"])))return nil; } id strengths=doc[@"strengths"];if(strengths){if(![strengths isKindOfClass:NSDictionary.class]||[strengths count]>DYToolLimit+DYToolTypes().count+1)return nil;for(id ID in strengths){id value=strengths[ID];if(![ID isKindOfClass:NSString.class]||!finiteNumber(value)||[value doubleValue]<0||[value doubleValue]>1)return nil;BOOL base=[ID hasPrefix:@"base:"]&&[DYToolTypes()containsObject:[ID substringFromIndex:5]];if(!base&&![ID isEqual:@"output"]&&!DYToolWithID(doc,ID))return nil;}} // Anchors are stable identities, never an array index or a translated title. // Reject unknown anchors/cycles so layout, rendering and undo share one order. for(NSDictionary *node in doc[@"layers"]){id after=node[@"after"];if(!after)continue;if([doc[@"schema"]isEqual:@1]||![after isKindOfClass:NSString.class])return nil;NSMutableSet *seen=[NSMutableSet setWithObject:node[@"id"]];while(after){if([after hasPrefix:@"base:"]){if(![DYToolTypes()containsObject:[after substringFromIndex:5]])return nil;break;}if([seen containsObject:after])return nil;[seen addObject:after];NSDictionary *parent=DYToolWithID(doc,after);if(!parent)return nil;after=parent[@"after"];}} id outputAfter=doc[@"outputAfter"];if(outputAfter&&(![outputAfter isKindOfClass:NSString.class]||(![outputAfter isEqual:@"tail"]&&![DYToolDisplayOrder(doc)containsObject:outputAfter])))return nil; NSUInteger totalKeys=0;for(NSDictionary *mask in shared)totalKeys+=[mask[@"keys"]count];for(NSArray *masks in [doc[@"baseMasks"]allValues])for(NSDictionary *mask in masks)totalKeys+=[mask[@"keys"]count];for(NSDictionary *node in doc[@"layers"])for(NSDictionary *mask in node[@"masks"])totalKeys+=[mask[@"keys"]count];if(totalKeys>65536)return nil;NSData *bounded=[NSPropertyListSerialization dataWithPropertyList:doc format:NSPropertyListBinaryFormat_v1_0 options:0 error:nil];return bounded.length<=24*1024*1024?bounded:nil; } BOOL DYValidToolDocument(NSDictionary *doc){return DYValidatedToolData(doc)!=nil;} @implementation DYToolDocument + (BOOL)supportsSecureCoding{return YES;} - (instancetype)init{if((self=[super init]))_document=[DYInitialToolDocument(nil)copy];return self;} - (void)dealloc{[_document release];[super dealloc];} - (void)setDocument:(NSDictionary *)d{NSData *b=DYValidatedToolData(d);if(!b)return;NSDictionary *immutable=[NSPropertyListSerialization propertyListWithData:b options:NSPropertyListImmutable format:NULL error:nil];[self setImmutableDocument:immutable];} - (void)setImmutableDocument:(NSDictionary*)document{if(document==_document)return;[document retain];[_document release];_document=document;} - (void)encodeWithCoder:(NSCoder*)c{[c encodeObject:_document forKey:@"document"];} - (instancetype)initWithCoder:(NSCoder*)c{if((self=[self init])){NSDictionary *d=[c decodeObjectOfClasses:[NSSet setWithObjects:NSDictionary.class,NSArray.class,NSString.class,NSNumber.class,NSData.class,nil] forKey:@"document"];NSData *data=DYValidatedToolData(d);if(!data){[self release];return nil;}[self setImmutableDocument:[NSPropertyListSerialization propertyListWithData:data options:NSPropertyListImmutable format:NULL error:nil]];}return self;} - (id)copyWithZone:(NSZone*)zone{DYToolDocument *v=[[[self class]allocWithZone:zone]init];[v setImmutableDocument:_document];return v;} - (BOOL)isEqual:(id)o{return [o isKindOfClass:DYToolDocument.class]&&[_document isEqual:[o document]];} - (NSUInteger)hash{return _document.hash;} - (id)interpolateBetween:(id)other withWeight:(float)weight{return [[self copy]autorelease];} @end DYToolDocument *DYReadTools(idm,CMTime t){DYToolDocument *d=nil;[[(id)m apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)]getCustomParameterValue:&d fromParameter:DYToolsParameterID atTime:t];return [d isKindOfClass:DYToolDocument.class]?d:[[[DYToolDocument alloc]init]autorelease];} BOOL DYWriteTools(idm,NSDictionary *d,CMTime t){NSData *data=DYValidatedToolData(d);if(!data)return NO;DYToolDocument *v=[[[DYToolDocument alloc]init]autorelease];[v setImmutableDocument:[NSPropertyListSerialization propertyListWithData:data options:NSPropertyListImmutable format:NULL error:nil]];return [[m apiForProtocol:@protocol(FxParameterSettingAPI_v6)]setCustomParameterValue:v toParameter:DYToolsParameterID atTime:t];} NSDictionary *DYToolWithID(NSDictionary *doc,NSString *ID){for(NSDictionary *n in doc[@"layers"])if([n[@"id"]isEqual:ID])return n;return nil;} double DYToolStrength(NSDictionary *doc,NSString *ID){NSNumber *value=doc[@"strengths"][ID?:@""];return value?value.doubleValue:1;} BOOL DYSetToolStrength(NSMutableDictionary *doc,NSString *ID,double strength){ if(!DYValidToolDocument(doc)||!std::isfinite(strength)||strength<0||strength>1)return NO; BOOL base=[ID hasPrefix:@"base:"]&&[DYToolTypes()containsObject:[ID substringFromIndex:5]]; if(!base&&![ID isEqual:@"output"]&&!DYToolWithID(doc,ID))return NO; NSMutableDictionary *values=[NSMutableDictionary dictionaryWithDictionary:doc[@"strengths"]?:@{}];if(strength==1)[values removeObjectForKey:ID];else values[ID]=@(strength);if(values.count)doc[@"strengths"]=values;else[doc removeObjectForKey:@"strengths"];return YES; } NSArray *DYToolStrengthMasks(NSArray *masks,double strength){ if(strength>=1)return masks?:@[];NSMutableArray *result=[NSMutableArray arrayWithArray:masks?:@[]];DYMaskParameters p=dyDefaultMaskParameters();p.kind=DYMaskRectangle;p.width=p.height=4000;p.feather=0;p.outputBlack=p.outputWhite=1;p.strength=strength; [result addObject:@{@"enabled":@YES,@"combine":@2,@"parameters":parameterData(p),@"nodes":[NSData data],@"keys":@[]}];return result; } static void DYAppendToolChildren(NSDictionary *doc,NSString *parent,NSMutableArray *order,NSMutableSet *seen){for(NSDictionary *node in doc[@"layers"])if([node[@"after"]isEqual:parent]&&![seen containsObject:node[@"id"]]){[seen addObject:node[@"id"]];[order addObject:node[@"id"]];DYAppendToolChildren(doc,node[@"id"],order,seen);}} NSArray *DYToolDisplayOrder(NSDictionary *doc){NSMutableArray *order=[NSMutableArray array];NSMutableSet *seen=[NSMutableSet set];for(NSString *type in DYToolTypes()){NSString *base=[@"base:" stringByAppendingString:type];[order addObject:base];DYAppendToolChildren(doc,base,order,seen);}for(NSDictionary *node in doc[@"layers"])if(!node[@"after"]&&![seen containsObject:node[@"id"]]){[seen addObject:node[@"id"]];[order addObject:node[@"id"]];DYAppendToolChildren(doc,node[@"id"],order,seen);}return order;} NSString *DYToolRootAnchor(NSDictionary *doc,NSString *ID){NSMutableSet *seen=[NSMutableSet set];NSDictionary *node=DYToolWithID(doc,ID);while(node[@"after"]){NSString *after=node[@"after"];if([after hasPrefix:@"base:"])return after;if([seen containsObject:after])return nil;[seen addObject:after];node=DYToolWithID(doc,after);}return @"tail";} NSArray *DYUnifiedRenderOrder(NSDictionary *doc){NSMutableArray *order=[NSMutableArray arrayWithArray:DYToolDisplayOrder(doc)];NSString *after=doc[@"outputAfter"]?:@"tail";NSUInteger index=[order indexOfObject:after];[order insertObject:@"output" atIndex:index==NSNotFound?order.count:index+1];return order;} NSDictionary *DYInsertTool(NSMutableDictionary *doc,NSString *type,NSString *after){if(!DYValidToolDocument(doc)||[doc[@"layers"]count]>=DYToolLimit)return nil;if(!([after hasPrefix:@"base:"]&&[DYToolTypes()containsObject:[after substringFromIndex:5]])&&!DYToolWithID(doc,after))return nil;NSDictionary *fresh=DYNewTool(type);if(!fresh)return nil;NSMutableDictionary *node=DYMutablePlist(fresh);node[@"after"]=after;NSMutableArray *layers=doc[@"layers"];for(NSMutableDictionary *old in layers)if([old[@"after"]isEqual:after])old[@"after"]=node[@"id"];NSUInteger index=0;NSDictionary *parent=DYToolWithID(doc,after);if(parent)index=[layers indexOfObjectIdenticalTo:parent]+1;[layers insertObject:node atIndex:MIN(index,layers.count)];if(![doc[@"schema"]isEqual:@3])doc[@"schema"]=@2;return node;} BOOL DYRemoveTool(NSMutableDictionary *doc,NSString *ID){NSMutableDictionary *node=(id)DYToolWithID(doc,ID);if(!node)return NO;NSString *after=node[@"after"];if([doc[@"outputAfter"]isEqual:ID])doc[@"outputAfter"]=after?:@"tail";for(NSMutableDictionary *child in doc[@"layers"])if([child[@"after"]isEqual:ID]){if(after)child[@"after"]=after;else[child removeObjectForKey:@"after"];}[doc[@"layers"]removeObject:node];[doc[@"strengths"]removeObjectForKey:ID];return YES;} NSArray *DYSharedMasks(NSDictionary *doc){return [doc[@"sharedMasks"]isKindOfClass:NSArray.class]?doc[@"sharedMasks"]:@[];} NSDictionary *DYSharedMaskWithID(NSDictionary *doc,NSString *ID){for(NSDictionary *mask in DYSharedMasks(doc))if([mask[@"id"]isEqual:ID])return mask;return nil;} static NSArray *DYRawMasksForTool(NSDictionary *doc,NSString *ID){return [ID hasPrefix:@"base:"]?doc[@"baseMasks"][[ID substringFromIndex:5]]?:@[]:DYToolWithID(doc,ID)[@"masks"]?:@[];} NSArray *DYMasksForTool(NSDictionary *doc,NSString *ID){ if([ID isEqual:@"shared"])return DYSharedMasks(doc);NSArray *raw=DYRawMasksForTool(doc,ID);BOOL references=NO;for(NSDictionary *mask in raw)references|=mask[@"sharedID"]!=nil;if(!references)return raw; NSMutableArray *resolved=[NSMutableArray arrayWithCapacity:raw.count];for(NSDictionary *mask in raw){NSDictionary *object=mask[@"sharedID"]?DYSharedMaskWithID(doc,mask[@"sharedID"]):mask;if(object)[resolved addObject:object];}return resolved; } static BOOL DYStoreRawMasks(NSMutableDictionary *doc,NSString *ID,NSArray *masks){if([ID hasPrefix:@"base:"]){NSString *type=[ID substringFromIndex:5];if(![DYToolTypes()containsObject:type]||DYBaseToolRemoved(doc,type))return NO;doc[@"baseMasks"][type]=masks;}else{NSMutableDictionary *node=(id)DYToolWithID(doc,ID);if(!node)return NO;node[@"masks"]=masks;}return YES;} BOOL DYSetToolMasks(NSMutableDictionary *doc,NSString *ID,NSArray *masks){ if(![masks isKindOfClass:NSArray.class])return NO; if([ID isEqual:@"shared"]){if(masks.count>DYSharedMaskLimit)return NO;NSMutableSet *kept=[NSMutableSet set];for(NSDictionary *mask in masks){if(!DYValidToolMask(mask)||[kept containsObject:mask[@"id"]])return NO;[kept addObject:mask[@"id"]];}for(NSDictionary *old in [[DYSharedMasks(doc)copy]autorelease])if(![kept containsObject:old[@"id"]])DYRemoveSharedMask(doc,old[@"id"]);doc[@"schema"]=@3;doc[@"sharedMasks"]=[NSMutableArray arrayWithArray:masks];return YES;} if(masks.count>DYToolMaskLimit)return NO;NSMutableArray *raw=[NSMutableArray arrayWithCapacity:masks.count];NSMutableSet *seen=[NSMutableSet set];for(NSDictionary *mask in masks){NSString *shared=mask[@"sharedID"]?:mask[@"id"];if(!shared||[seen containsObject:shared])return NO;[seen addObject:shared];if(DYSharedMaskWithID(doc,shared))[raw addObject:@{@"sharedID":shared}];else if(mask[@"sharedID"]||!DYValidToolMask(mask))return NO;else[raw addObject:mask];}return DYStoreRawMasks(doc,ID,raw); } NSDictionary *DYAddSharedMask(NSMutableDictionary *doc,NSInteger kind){ if(!DYValidToolDocument(doc)||DYSharedMasks(doc).count>=DYSharedMaskLimit)return nil;NSDictionary *fresh=DYNewMask(kind);if(!fresh)return nil;NSMutableDictionary *mask=DYMutablePlist(fresh);NSMutableArray *shared=[NSMutableArray arrayWithArray:DYSharedMasks(doc)];[shared addObject:mask];doc[@"schema"]=@3;doc[@"sharedMasks"]=shared;return mask; } BOOL DYSetSharedMaskAssigned(NSMutableDictionary *doc,NSString *maskID,NSString *nodeID,BOOL assigned){ NSDictionary *mask=DYSharedMaskWithID(doc,maskID);if(!mask||mask[@"stampSource"]||[nodeID isEqual:@"shared"])return NO;if([nodeID hasPrefix:@"base:"]){NSString *type=[nodeID substringFromIndex:5];if(![DYToolTypes()containsObject:type]||DYBaseToolRemoved(doc,type))return NO;}else if(!DYToolWithID(doc,nodeID))return NO; NSMutableArray *raw=[NSMutableArray arrayWithArray:DYRawMasksForTool(doc,nodeID)];NSUInteger index=[raw indexOfObjectPassingTest:^BOOL(NSDictionary *entry,NSUInteger i,BOOL *stop){return [entry[@"sharedID"]isEqual:maskID];}];if(assigned){if(index!=NSNotFound)return YES;if(raw.count>=DYToolMaskLimit)return NO;[raw addObject:@{@"sharedID":maskID}];}else if(index!=NSNotFound)[raw removeObjectAtIndex:index];return DYStoreRawMasks(doc,nodeID,raw); } NSArray *DYToolIDsForSharedMask(NSDictionary *doc,NSString *maskID){NSMutableArray *nodes=[NSMutableArray array];for(NSString *ID in DYToolDisplayOrder(doc))for(NSDictionary *entry in DYRawMasksForTool(doc,ID))if([entry[@"sharedID"]isEqual:maskID]){[nodes addObject:ID];break;}return nodes;} BOOL DYRemoveSharedMask(NSMutableDictionary *doc,NSString *maskID){ if(!DYSharedMaskWithID(doc,maskID))return NO;for(NSString *ID in DYToolIDsForSharedMask(doc,maskID))if(!DYSetSharedMaskAssigned(doc,maskID,ID,NO))return NO;NSMutableArray *shared=[NSMutableArray arrayWithArray:DYSharedMasks(doc)];NSIndexSet *indices=[shared indexesOfObjectsPassingTest:^BOOL(NSDictionary *mask,NSUInteger i,BOOL *stop){return [mask[@"id"]isEqual:maskID];}];[shared removeObjectsAtIndexes:indices];doc[@"sharedMasks"]=shared;return YES; } NSDictionary *DYShareToolMask(NSMutableDictionary *doc,NSString *nodeID,NSString *maskID){ NSDictionary *shared=DYSharedMaskWithID(doc,maskID);if(shared)return shared;if([nodeID isEqual:@"shared"]||!DYValidToolDocument(doc)||DYSharedMasks(doc).count>=DYSharedMaskLimit)return nil; NSMutableArray *raw=[NSMutableArray arrayWithArray:DYRawMasksForTool(doc,nodeID)];NSUInteger index=[raw indexOfObjectPassingTest:^BOOL(NSDictionary *mask,NSUInteger i,BOOL *stop){return [mask[@"id"]isEqual:maskID];}];if(index==NSNotFound)return nil;NSMutableDictionary *mask=DYMutablePlist(raw[index]);NSMutableArray *library=[NSMutableArray arrayWithArray:DYSharedMasks(doc)];[library addObject:mask];raw[index]=@{@"sharedID":maskID};if(!DYStoreRawMasks(doc,nodeID,raw))return nil;doc[@"schema"]=@3;doc[@"sharedMasks"]=library;return mask; } static NSString *DYResolvedMaskID(NSString *maskID,NSString *nodeID){NSData *input=[[NSString stringWithFormat:@"%@/%@",maskID,nodeID]dataUsingEncoding:NSUTF8StringEncoding];unsigned char digest[CC_SHA256_DIGEST_LENGTH];CC_SHA256(input.bytes,(CC_LONG)input.length,digest);digest[6]=(digest[6]&0x0f)|0x50;digest[8]=(digest[8]&0x3f)|0x80;return [[[NSUUID alloc]initWithUUIDBytes:digest]autorelease].UUIDString;} static NSDictionary *DYExpandSharedMasks(NSDictionary *doc,BOOL keepKeys){ if(![doc[@"schema"]isEqual:@3])return doc;NSMutableDictionary *out=[[doc mutableCopy]autorelease],*base=[NSMutableDictionary dictionary]; auto resolve=[&](NSString *nodeID){NSMutableArray *masks=[NSMutableArray array];for(NSDictionary *entry in DYRawMasksForTool(doc,nodeID)){if(entry[@"sharedID"]){NSDictionary *shared=DYSharedMaskWithID(doc,entry[@"sharedID"]);if(!shared)continue;NSMutableDictionary *copy=[[shared mutableCopy]autorelease];copy[@"sourceSharedID"]=shared[@"id"];copy[@"id"]=DYResolvedMaskID(shared[@"id"],nodeID);if(!keepKeys)copy[@"keys"]=@[];[masks addObject:copy];}else[masks addObject:entry];}return masks;}; for(NSString *type in doc[@"baseMasks"])base[type]=resolve([@"base:" stringByAppendingString:type]);out[@"baseMasks"]=base;NSMutableArray *layers=[NSMutableArray array];for(NSDictionary *node in doc[@"layers"]){NSMutableDictionary *copy=[[node mutableCopy]autorelease];copy[@"masks"]=resolve(node[@"id"]);[layers addObject:copy];}out[@"layers"]=layers;out[@"schema"]=@2;[out removeObjectForKey:@"sharedMasks"];return out; } NSDictionary *DYResolvedToolDocument(NSDictionary *doc){return DYExpandSharedMasks(doc,NO);} struct DYMaskKeySpan { NSDictionary *left=nil,*right=nil; float fraction=0; }; static DYMaskKeySpan maskKeySpan(NSDictionary *mask,CMTime time){ NSArray *keys=mask[@"keys"]; if(!keys.count||!CMTIME_IS_NUMERIC(time)||keyTime(keys[0]).epoch!=time.epoch)return {}; NSUInteger low=0,high=keys.count; while(low0?std::clamp(CMTimeGetSeconds(CMTimeSubtract(time,keyTime(left)))/duration,0.,1.):0; return {left,right,fraction}; } static DYStampMotion stampMotionFromKey(NSDictionary *key){ NSArray *v=key[@"stampMotion"]; if(!v)return {}; return {[v[0] floatValue],[v[1] floatValue],[v[2] floatValue], [v[3] floatValue],[v[4] floatValue],[v[5] floatValue],true}; } static DYStampMotion stampMotionInSpan(DYMaskKeySpan span){ auto a=stampMotionFromKey(span.left),b=stampMotionFromKey(span.right); if(span.fraction<=0)return a; if(span.fraction>=1)return b; auto blend=[&](float x,float y){return x+(y-x)*span.fraction;}; return {blend(a.sourceOffsetX,b.sourceOffsetX),blend(a.sourceOffsetY,b.sourceOffsetY), blend(a.sourceScaleX,b.sourceScaleX),blend(a.sourceScaleY,b.sourceScaleY), blend(a.targetScaleX,b.targetScaleX),blend(a.targetScaleY,b.targetScaleY),a.active||b.active}; } DYStampMotion DYStampMotionAtTime(NSDictionary *stamp,CMTime time){return stampMotionInSpan(maskKeySpan(stamp,time));} BOOL DYStampUsesLinkedTracking(NSDictionary *stamp){return stamp[@"stampSource"]&&[stamp[@"stampTrackMode"]isEqual:@"linked"];} CMTime DYTrackingRecordedTime(NSDictionary *mask,NSString *key){ NSArray *v=mask[key];if(![v isKindOfClass:NSArray.class]||v.count!=3)return kCMTimeInvalid; for(id n in v)if(!finiteNumber(n))return kCMTimeInvalid; double scale=[v[1]doubleValue];if(scale<1||scale>INT32_MAX||scale!=std::floor(scale))return kCMTimeInvalid; return CMTimeMakeWithEpoch([v[0]longLongValue],(int32_t)scale,[v[2]longLongValue]); } DYMaskParameters DYStampReferenceAtTime(NSDictionary *stamp,CMTime time){ DYMaskParameters p=DYMaskAtTime(stamp,time);NSArray *ref=stamp[@"stampReference"]; if(ref.count==4){p.centerX+=[ref[0]floatValue]*p.width;p.centerY+=[ref[1]floatValue]*p.height;p.width*=[ref[2]floatValue];p.height*=[ref[3]floatValue];p.kind=DYMaskRectangle;} p.feather=0;p.angle=0;return p; } BOOL DYSetStampReference(NSMutableDictionary *stamp,NSRect rect,CMTime time){ if(!stamp[@"stampSource"]||!CMTIME_IS_NUMERIC(time)||!std::isfinite(NSMidX(rect))||!std::isfinite(NSMidY(rect))|| !std::isfinite(NSWidth(rect))||!std::isfinite(NSHeight(rect))||NSWidth(rect)<.001||NSHeight(rect)<.001|| NSMinX(rect)<0||NSMinY(rect)<0||NSMaxX(rect)>1||NSMaxY(rect)>1)return NO; DYMaskParameters p=DYMaskAtTime(stamp,time); NSArray *ref=@[@((NSMidX(rect)-p.centerX)/p.width),@((NSMidY(rect)-p.centerY)/p.height),@(NSWidth(rect)/p.width),@(NSHeight(rect)/p.height)]; NSMutableDictionary *candidate=DYMutablePlist(stamp);candidate[@"stampReference"]=ref; if(!DYValidToolMask(candidate))return NO;stamp[@"stampReference"]=ref;[stamp removeObjectForKey:@"status"];return YES; } BOOL DYAddStampManualKey(NSMutableDictionary *stamp,CMTime time){ if(!stamp[@"stampSource"]||!CMTIME_IS_NUMERIC(time))return NO; DYMaskParameters p=DYMaskAtTime(stamp,time);DYStampMotion motion=DYStampMotionAtTime(stamp,time);motion.active=true; NSMutableDictionary *candidate=DYMutablePlist(stamp); NSMutableArray *keys=candidate[@"keys"];[keys filterUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(NSDictionary *key,NSDictionary *bindings){return CMTimeCompare(keyTime(key),time)!=0;}]]; if(!DYMergeTracking(candidate,@[DYStampKey(time,p,YES,1,motion)]))return NO; [candidate removeObjectsForKeys:@[@"status",@"trackingStopped",@"trackingLastTime",@"trackingStopTime"]]; [stamp setDictionary:candidate];return YES; } NSArray *DYStampSourceAtTime(NSDictionary *stamp,CMTime time){ NSArray *source=stamp[@"stampSource"]; DYStampMotion motion=DYStampMotionAtTime(stamp,time); if(!source||!motion.active)return source; return @[@(std::clamp([source[0] doubleValue]+motion.sourceOffsetX,0.,1.)), @(std::clamp([source[1] doubleValue]+motion.sourceOffsetY,0.,1.)),source[2],source[3]]; } NSArray *DYStampSamplingScaleAtTime(NSDictionary *stamp,CMTime time){ NSArray *base=stamp[@"stampSamplingScale"]; DYStampMotion motion=DYStampMotionAtTime(stamp,time); if(!motion.active)return base; double x=(base?[base[0] doubleValue]:1)*motion.sourceScaleX/motion.targetScaleX; double y=(base?[base[1] doubleValue]:1)*motion.sourceScaleY/motion.targetScaleY; return @[@(std::clamp(x,1./256,256.)),@(std::clamp(y,1./256,256.))]; } DYMaskParameters DYMaskAtTime(NSDictionary *mask,CMTime time){ DYMaskParameters p=dyDefaultMaskParameters(); readParameters(mask[@"parameters"],&p); BOOL stamp=mask[@"stampSource"]!=nil; if(stamp)p.angle=0; DYMaskKeySpan span=maskKeySpan(mask,time); if(!span.left)return p; DYMaskParameters a,b; readParameters(span.left[@"parameters"],&a);readParameters(span.right[@"parameters"],&b); float *v=&p.centerX,*av=&a.centerX,*bv=&b.centerX; for(int i=0;i<(stamp?2:8);i++)v[i]=av[i]+(bv[i]-av[i])*span.fraction; if(stamp){ DYStampMotion motion=stampMotionInSpan(span); if(motion.active){ p.width=std::clamp(p.width*motion.targetScaleX,.001f,4000.f); p.height=std::clamp(p.height*motion.targetScaleY,.001f,4000.f); } } return p; } NSDictionary *DYMaskKey(CMTime t,DYMaskParameters p,BOOL manual,float confidence){return @{@"value":@(t.value),@"scale":@(t.timescale),@"epoch":@(t.epoch),@"parameters":parameterData(p),@"manual":@(manual),@"confidence":@(confidence)};} NSDictionary *DYStampKey(CMTime time,DYMaskParameters p,BOOL manual,float confidence,DYStampMotion motion){ NSDictionary *key=DYMaskKey(time,p,manual,confidence); if(!motion.active)return key; NSMutableDictionary *paired=[[key mutableCopy]autorelease]; paired[@"stampMotion"]=@[@(motion.sourceOffsetX),@(motion.sourceOffsetY),@(motion.sourceScaleX), @(motion.sourceScaleY),@(motion.targetScaleX),@(motion.targetScaleY)]; if(manual)paired[@"stampManualSource"]=@YES; return paired; } // Analysis supplies a contiguous pass in either time direction. A symmetric // kernel has no phase lag, and shrinking it at the ends keeps the seed and // the last trusted frame fixed. Work in log scale so zoom in/out is symmetric. static NSArray *smoothStampTrackingSamples(NSArray *samples){ if(samples.count<3)return samples; for(NSDictionary *key in samples) if(!key[@"stampMotion"]||[key[@"manual"]boolValue])return samples; NSMutableArray *result=[NSMutableArray arrayWithCapacity:samples.count]; [result addObject:samples.firstObject]; for(NSUInteger i=1;i+1(2,std::min(i,samples.count-1-i)); const double weights[]={1,4,6,4,1}; const double endWeights[]={1,2,1}; double values[8]={}; for(NSUInteger j=0;j<=2*radius;j++){ NSDictionary *neighbor=samples[i-radius+j]; DYMaskParameters p; if(!readParameters(neighbor[@"parameters"],&p))return samples; auto m=stampMotionFromKey(neighbor); double weight=radius==2?weights[j]/16:endWeights[j]/4; const double components[]={p.centerX,p.centerY,m.sourceOffsetX,m.sourceOffsetY, std::log(m.sourceScaleX),std::log(m.sourceScaleY),std::log(m.targetScaleX),std::log(m.targetScaleY)}; for(int k=0;k<8;k++)values[k]+=weight*components[k]; } NSDictionary *original=samples[i]; DYMaskParameters p; if(!readParameters(original[@"parameters"],&p))return samples; p.centerX=values[0];p.centerY=values[1]; auto scale=[&](int index){return float(std::clamp(std::exp(values[index]),1./16,16.));}; DYStampMotion m={float(values[2]),float(values[3]),scale(4),scale(5),scale(6),scale(7),true}; [result addObject:DYStampKey(keyTime(original),p,NO,[original[@"confidence"]floatValue],m)]; } [result addObject:samples.lastObject]; return result; } BOOL DYMosaicTracksMask(NSDictionary *doc,NSString *maskID){ NSDictionary *mosaic=doc[@"mosaic"],*mask=DYSharedMaskWithID(doc,maskID); NSArray *ids=mosaic[@"maskIDs"]?: (mosaic[@"maskID"]?@[mosaic[@"maskID"]]:@[]); DYMaskParameters p=DYMaskAtTime(mask,kCMTimeInvalid); return mask&&(p.kind<=DYMaskBezier)&&!mask[@"stampSource"]&&[mask[@"enabled"]boolValue]&&[mosaic[@"enabled"]boolValue]&&[mosaic[@"source"]isEqual:@"mask"]&&[ids containsObject:maskID]; } BOOL DYRepairObjectTrackingGap(NSMutableArray *samples,DYMaskParameters next,NSUInteger gap){ if(!gap)return YES;if(samples.count<=gap||!dyValidMaskParameters(next))return NO; NSUInteger anchor=samples.count-gap-1;DYMaskParameters left; if(!readParameters(samples[anchor][@"parameters"],&left)||left.kind!=next.kind)return NO; NSMutableArray *repaired=[NSMutableArray arrayWithCapacity:gap]; for(NSUInteger i=1;i<=gap;i++){ NSDictionary *original=samples[anchor+i];if([original[@"manual"]boolValue]||original[@"stampMotion"])return NO; float t=float(i)/float(gap+1);DYMaskParameters p=left; p.centerX=left.centerX+(next.centerX-left.centerX)*t;p.centerY=left.centerY+(next.centerY-left.centerY)*t; p.width=std::exp(std::log(left.width)+(std::log(next.width)-std::log(left.width))*t); p.height=std::exp(std::log(left.height)+(std::log(next.height)-std::log(left.height))*t); p.angle=left.angle+std::remainder(next.angle-left.angle,float(2*M_PI))*t; if(!dyValidMaskParameters(p))return NO; NSMutableDictionary *key=[[original mutableCopy]autorelease];key[@"parameters"]=parameterData(p);key[@"confidence"]=@.35; [repaired addObject:key]; } [samples replaceObjectsInRange:NSMakeRange(anchor+1,gap) withObjectsFromArray:repaired];return YES; } BOOL DYMergeTracking(NSMutableDictionary *m,NSArray *samples,CMTime frameDuration){ if(!samples.count)return YES; NSMutableArray *all=[NSMutableArray array]; NSMutableDictionary *manualByTime=[NSMutableDictionary dictionary]; CMTime lo=keyTime(samples.firstObject),hi=keyTime(samples.lastObject); if(CMTimeCompare(lo,hi)>0)std::swap(lo,hi); if(m[@"stampSource"]&&CMTIME_IS_NUMERIC(frameDuration)&&frameDuration.value>0){ samples=smoothStampTrackingSamples(samples); // FCP can shift analysis timestamps by a fraction of a frame between passes. // Replace an older automatic key belonging to the first or last new frame. CMTime half=CMTimeMultiplyByRatio(frameDuration,1,2); lo=CMTimeSubtract(lo,half);hi=CMTimeAdd(hi,half); } // Normalize equivalent time fractions when preserving authored keys. auto timeID=[](NSDictionary *key){ CMTime time=keyTime(key); int64_t divisor=time.timescale>0?std::gcd(time.value%time.timescale,int64_t(time.timescale)):1; return [NSString stringWithFormat:@"%lld/%lld/%lld",time.value/divisor,time.timescale/divisor,time.epoch]; }; for(NSDictionary *key in m[@"keys"]){ if([key[@"manual"] boolValue]){manualByTime[timeID(key)]=@(all.count);[all addObject:key];} else if(CMTimeCompare(keyTime(key),lo)<0||CMTimeCompare(keyTime(key),hi)>0)[all addObject:key]; } for(NSDictionary *key in samples){ NSNumber *index=manualByTime[timeID(key)]; if(!index){[all addObject:key];continue;} if(key[@"stampMotion"]){ NSUInteger slot=index.unsignedIntegerValue; NSMutableDictionary *authored=[[all[slot] mutableCopy]autorelease]; if([authored[@"stampManualSource"]boolValue]&&![key[@"manual"]boolValue]){ NSMutableArray *motion=[[key[@"stampMotion"]mutableCopy]autorelease]; motion[0]=authored[@"stampMotion"][0];motion[1]=authored[@"stampMotion"][1]; authored[@"stampMotion"]=motion; }else authored[@"stampMotion"]=key[@"stampMotion"]; all[slot]=authored; } } [all sortUsingComparator:^NSComparisonResult(NSDictionary *a,NSDictionary *b){return (NSComparisonResult)CMTimeCompare(keyTime(a),keyTime(b));}]; NSMutableDictionary *candidate=[[m mutableCopy]autorelease]; candidate[@"keys"]=all; if(!DYValidToolMask(candidate))return NO; m[@"keys"]=all; return YES; } NSDictionary *DYToolRenderSnapshot(NSDictionary *doc,CMTime t){ NSArray *shared=DYSharedMasks(doc); doc=DYExpandSharedMasks(doc,YES); auto resolve=[&](NSArray *masks){ NSMutableArray *result=[NSMutableArray arrayWithCapacity:masks.count]; for(NSDictionary *mask in masks){ if(![mask[@"keys"]count]){[result addObject:mask];continue;} NSMutableDictionary *m=[[mask mutableCopy]autorelease];m[@"parameters"]=parameterData(DYMaskAtTime(mask,t));m[@"keys"]=@[]; if(mask[@"stampSource"]){ m[@"stampSource"]=DYStampSourceAtTime(mask,t); m[@"stampSamplingScale"]=DYStampSamplingScaleAtTime(mask,t)?:@[@1,@1]; } [result addObject:m]; } return result; }; NSMutableDictionary *out=[[doc mutableCopy]autorelease],*base=[NSMutableDictionary dictionary]; NSArray *mosaicIDs=doc[@"mosaic"][@"maskIDs"]?: (doc[@"mosaic"][@"maskID"]?@[doc[@"mosaic"][@"maskID"]]:@[]); NSMutableArray *mosaicMasks=[NSMutableArray array];for(NSDictionary *mask in shared)if(!mask[@"stampSource"]&&[mosaicIDs containsObject:mask[@"id"]])[mosaicMasks addObject:mask]; out[@"mosaicRenderMasks"]=resolve(mosaicMasks);[out removeObjectForKey:@"mosaicRenderMask"]; if(CMTIME_IS_NUMERIC(t))out[@"renderTime"]=[(NSDictionary*)CMTimeCopyAsDictionary(t,kCFAllocatorDefault)autorelease]; for(NSString *type in doc[@"baseMasks"])base[type]=resolve(doc[@"baseMasks"][type]);out[@"baseMasks"]=base; NSMutableArray *layers=[NSMutableArray array]; for(NSDictionary *node in doc[@"layers"]){NSMutableDictionary *layer=[[node mutableCopy]autorelease];layer[@"masks"]=resolve(node[@"masks"]);[layers addObject:layer];} out[@"layers"]=layers; NSMutableArray *stamps=[NSMutableArray array];for(NSDictionary *mask in shared)if(mask[@"stampSource"])[stamps addObject:mask]; if(stamps.count){out[@"schema"]=@3;out[@"sharedMasks"]=resolve(stamps);} return out; } DYUniforms DYToolUniforms(NSDictionary *node){DYUniforms u;DYDefaultUniforms(&u);NSString *type=node[@"type"];for(NSDictionary *s in DYSections())for(NSDictionary *d in DYDescriptors())if([d[@"pid"]isEqual:s[@"enabled"]])*(float*)((uint8_t*)&u+[d[@"offset"]unsignedIntegerValue])=0;u.primarySectionEnabled=0;u.cm.configured=-1;u.inputProfile=u.preLUTStrength=0;u.skinProtection.x=0; NSArray *parts=[type isEqual:@"primary"]?@[@"input",@"primary",@"output"]:[type isEqual:@"base"]?@[@"base",@"color"]:@[type];for(NSString *part in parts){NSDictionary *s=DYToolSection(part);for(NSDictionary *d in DYDescriptors())if([d[@"pid"]isEqual:s[@"enabled"]])*(float*)((uint8_t*)&u+[d[@"offset"]unsignedIntegerValue])=1;} // Old independent layers omitted the former zero default. Keep their image; // new layers explicitly disable mapping so adding a neutral layer is identity. if([type isEqual:@"primary"]){u.primarySectionEnabled=1;u.cm.configured=1;u.cm.inputTransfer=u.cm.outputTransfer;u.cm.inputGamut=u.cm.outputGamut;u.cm.toneMapping=0;} for(NSDictionary *d in DYDescriptors()){NSNumber *v=node[@"values"][d[@"key"]];if(v&&[d[@"offset"]integerValue]>=0)*(float*)((uint8_t*)&u+[d[@"offset"]unsignedIntegerValue])=v.floatValue;}return u;} BOOL DYToolIsNeutral(NSDictionary *node){NSString *type=node[@"type"];DYUniforms u=DYToolUniforms(node);NSDictionary *section=DYToolSection(type);BOOL enabled=YES;if([type isEqual:@"primary"])enabled=u.primarySectionEnabled>.5;else if([type isEqual:@"base"])enabled=u.baseSectionEnabled>.5||u.colorSectionEnabled>.5;else for(NSDictionary *d in DYDescriptors())if([d[@"pid"]isEqual:section[@"enabled"]])enabled=*(float*)((uint8_t*)&u+[d[@"offset"]unsignedIntegerValue])>.5;if(!enabled)return YES;if([type isEqual:@"primary"]&&u.cm.toneMapping>.5)return NO;if([type isEqual:@"lens"])return u.lensStrength==0&&u.lensScale==1;if([type isEqual:@"mixer"])return !DYChannelMixerActive(u);if([type isEqual:@"film"])return !DYFilmToolActive(u);if([type isEqual:@"skin"])return u.skinProtection.y==0&&u.skinVisualize<.5;if([node[@"type"]isEqual:@"spider"]&&[node[@"spider"]length]){auto mesh=DYSpiderMesh(node[@"spider"]);for(float v:dy::meshSamples(mesh))if(v!=0)return NO;}if([node[@"paths"]count])return NO;for(NSDictionary *d in DYDescriptors()){NSNumber *v=node[@"values"][d[@"key"]];if([type isEqual:@"primary"]&&[d[@"key"]isEqual:@"cmtoneMapping"]&&v.floatValue==0)continue;if(v&&v.floatValue!=[d[@"default"]floatValue])return NO;}return YES;} @implementation DYToolManager { id _host;NSString *_nodeID,*_type;NSInteger _depth;CMTime _time;NSMutableDictionary *_pending;DYInspectorToken *_token; DYUniforms _readUniforms;BOOL _readUniformsValid; } @synthesize host=_host,nodeID=_nodeID,type=_type; - (instancetype)initWithHost:(id)h node:(NSDictionary*)n{if((self=[super init])){_host=h;_nodeID=[n[@"id"]copy];_type=[n[@"type"]copy];}return self;} - (void)dealloc{[_nodeID release];[_type release];[_pending release];[_token release];[super dealloc];} - (id)apiForProtocol:(Protocol*)p{if(protocol_isEqual(p,@protocol(FxParameterRetrievalAPI_v6))||protocol_isEqual(p,@protocol(FxParameterSettingAPI_v6))||protocol_isEqual(p,@protocol(FxCustomParameterActionAPI_v4)))return self;return [_host apiForProtocol:p];} - (void)startAction:(id)sender{if(_depth++==0){_readUniformsValid=NO;[[_host apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)]startAction:sender];_time=[(id)[_host apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)]currentTime];[_pending release];_pending=[DYMutablePlist(DYReadTools(_host,_time).document)retain];}} - (void)endAction:(id)sender{ if(_depth<=0||--_depth>0)return; @try{ NSDictionary *original=DYReadTools(_host,_time).document; if(![_pending isEqual:original]&&!DYWriteTools(_host,_pending,_time)) os_log_error(OS_LOG_DEFAULT,"dayu_tool_save_rejected kind=document"); if(_token&&![[_host apiForProtocol:@protocol(FxParameterSettingAPI_v6)]setCustomParameterValue:_token toParameter:DYInspectorParameterID atTime:_time]) os_log_error(OS_LOG_DEFAULT,"dayu_tool_save_rejected kind=inspector"); }@finally{ [_token release];_token=nil; [[_host apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)]endAction:sender]; } } - (CMTime)currentTime{return _time;} - (NSDictionary*)node{return DYToolWithID(_depth?_pending:DYReadTools(_host,_time).document,_nodeID);} - (BOOL)getFloatValue:(double*)out fromParameter:(UInt32)pid atTime:(CMTime)t{ // One coherent snapshot per action, invalidated by any authoring write. // Inspector controls previously rebuilt every section for every scalar. if(!_depth||!_readUniformsValid){_readUniforms=DYToolUniforms([self node]?:@{@"type":_type});_readUniformsValid=_depth>0;} for(NSDictionary *d in DYDescriptors())if([d[@"pid"]unsignedIntValue]==pid){if(out)*out=[d[@"offset"]integerValue]>=0?*(float*)((uint8_t*)&_readUniforms+[d[@"offset"]unsignedIntegerValue]):[d[@"default"]doubleValue];return YES;}return NO; } - (BOOL)setFloatValue:(double)v toParameter:(UInt32)pid atTime:(CMTime)t{if(!_depth||!std::isfinite(v))return NO;NSMutableDictionary *n=(id)[self node];if(!n)return NO;for(NSDictionary *d in DYDescriptors())if([d[@"pid"]unsignedIntValue]==pid){NSString *key=d[@"key"];if(n[@"primaryFollow"]&&([key hasSuffix:@"Transfer"]||[key hasSuffix:@"Gamut"])){NSUInteger bit=[key hasPrefix:@"cminput"]?1:[key hasPrefix:@"cmworking"]?2:[key hasPrefix:@"cmoutput"]?4:0;n[@"primaryFollow"]=@([n[@"primaryFollow"]unsignedIntegerValue]&~bit);}n[@"values"][key]=@(v);_readUniformsValid=NO;return YES;}return NO;} - (BOOL)getCustomParameterValue:(id*)out fromParameter:(UInt32)pid atTime:(CMTime)t{if(pid==DYAssetsParameterID){DYAssetState *a=[[[DYAssetState alloc]init]autorelease];NSDictionary *n=[self node];a.paths=n[@"paths"]?:@{};a.spiderMesh=n[@"spider"];a.spiderLinked=[n[@"spiderLinked"]boolValue];*out=a;return YES;}if(pid==DYInspectorParameterID){DYInspectorToken *global=_token; if(!global)[[_host apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)]getCustomParameterValue:&global fromParameter:pid atTime:t];DYInspectorToken *local=[[[DYInspectorToken alloc]init]autorelease];NSMutableDictionary *folds=[NSMutableDictionary dictionary];for(NSString *key in global.folds)if([key hasPrefix:[_nodeID stringByAppendingString:@":"]])folds[[key substringFromIndex:_nodeID.length+1]]=global.folds[key];local.folds=folds;*out=local;return YES;}return NO;} - (BOOL)setCustomParameterValue:(id)v toParameter:(UInt32)pid atTime:(CMTime)t{if(!_depth)return NO;NSMutableDictionary *n=(id)[self node];if(!n)return NO;if(pid==DYAssetsParameterID&&[v isKindOfClass:DYAssetState.class]){n[@"paths"]=DYMutablePlist([v paths]);if([v spiderMesh])n[@"spider"]=[v spiderMesh];else[n removeObjectForKey:@"spider"];n[@"spiderLinked"]=@([v spiderLinked]);return YES;}if(pid==DYInspectorParameterID){DYInspectorToken *old=nil;[[_host apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)]getCustomParameterValue:&old fromParameter:pid atTime:t];[_token release];_token=old?[old copy]:[DYInspectorToken new];NSMutableDictionary *folds=[[_token.folds mutableCopy]autorelease];for(NSString *key in [v folds])folds[[_nodeID stringByAppendingFormat:@":%@",key]]=[v folds][key];_token.folds=folds;return YES;}return NO;} @end #import "DYTheme.h" @interface DYModuleStrengthControl (Gesture) - (void)beginStrengthGesture; - (void)endStrengthGesture; @end @interface DYModuleStrengthSlider : NSSlider @end @implementation DYModuleStrengthSlider - (void)mouseDown:(NSEvent*)event{[self.target performSelector:@selector(beginStrengthGesture)];@try{[super mouseDown:event];}@finally{[self.target performSelector:@selector(endStrengthGesture)];}} @end @implementation DYModuleStrengthControl { id _manager;NSString *_nodeID;NSTextField *_label,*_field;NSSlider *_slider;NSButton *_reset;BOOL _editing,_grouped;CMTime _editTime; } - (BOOL)isFlipped{return YES;} - (instancetype)initWithManager:(id)manager nodeID:(NSString*)nodeID{ if((self=[super initWithFrame:NSMakeRect(0,0,280,30)])){ _manager=manager;_nodeID=[nodeID copy];self.accessibilityLabel=@"模块整体强度"; _label=[NSTextField labelWithString:@"强度"];_label.font=[NSFont systemFontOfSize:11];[self addSubview:_label]; _slider=[[[DYModuleStrengthSlider alloc]initWithFrame:NSZeroRect]autorelease];_slider.minValue=0;_slider.maxValue=100;_slider.continuous=YES;_slider.target=self;_slider.action=@selector(strengthChanged:);_slider.accessibilityLabel=@"模块整体强度百分比";[self addSubview:_slider]; _field=[[[NSTextField alloc]initWithFrame:NSZeroRect]autorelease];_field.font=[NSFont monospacedDigitSystemFontOfSize:11 weight:NSFontWeightRegular];_field.alignment=NSTextAlignmentRight;_field.target=self;_field.action=@selector(strengthChanged:);_field.accessibilityLabel=@"模块整体强度百分比";[self addSubview:_field]; _reset=[NSButton buttonWithTitle:@"↺" target:self action:@selector(resetStrength:)];_reset.bordered=NO;_reset.toolTip=@"还原整体强度为 100%";_reset.accessibilityLabel=_reset.toolTip;[self addSubview:_reset]; [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(strengthModelChanged:) name:DYModelChanged object:manager]; [self strengthModelChanged:nil];[self resizeSubviewsWithOldSize:NSZeroSize]; }return self; } - (void)dealloc{[NSNotificationCenter.defaultCenter removeObserver:self];[_nodeID release];[super dealloc];} - (void)resizeSubviewsWithOldSize:(NSSize)old{CGFloat w=self.bounds.size.width;_label.frame=NSMakeRect(0,7,32,18);_slider.frame=NSMakeRect(38,6,MAX(26,w-126),20);_field.frame=NSMakeRect(MAX(65,w-81),3,54,24);_reset.frame=NSMakeRect(w-24,3,24,24);} - (void)refreshWithDocument:(NSDictionary*)doc{if(_editing)return;double amount=DYToolStrength(doc,_nodeID)*100;_slider.doubleValue=amount;_field.stringValue=[NSString stringWithFormat:@"%.0f%%",amount];_label.textColor=DYThemeColor(@"text");_slider.toolTip=@"0% 旁路本模块,100% 完整应用;保留原参数与蒙版";} - (void)strengthModelChanged:(NSNotification*)note{if(_editing||!_manager)return;ida=[_manager apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];if(!a)return;[a startAction:self];@try{[self refreshWithDocument:DYReadTools(_manager,a.currentTime).document];}@finally{[a endAction:self];}} - (void)beginStrengthGesture{if(_editing)return;ida=[_manager apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];if(!a)return;[a startAction:self];@try{_editTime=a.currentTime;_grouped=[[_manager apiForProtocol:@protocol(FxUndoAPI)]startUndoGroup:@"调整模块整体强度"];_editing=YES;}@finally{[a endAction:self];}} - (void)endStrengthGesture{if(!_editing)return;ida=[_manager apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];[a startAction:self];@try{if(_grouped)[[_manager apiForProtocol:@protocol(FxUndoAPI)]endUndoGroup];_grouped=NO;_editing=NO;}@finally{[a endAction:self];}[self strengthModelChanged:nil];[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:_manager];} - (void)strengthChanged:(NSControl*)sender{ double amount=sender.doubleValue;if(sender==_field){NSString *text=[_field.stringValue stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];if([text hasSuffix:@"%"]||[text hasSuffix:@"%"])text=[text substringToIndex:text.length-1];NSScanner *scanner=[NSScanner scannerWithString:text];if(![scanner scanDouble:&amount]||!scanner.isAtEnd||!std::isfinite(amount)){NSBeep();[self strengthModelChanged:nil];return;}} if(!std::isfinite(amount))return;amount=MAX(0.,MIN(100.,amount));BOOL discrete=!_editing;if(discrete)[self beginStrengthGesture]; ida=[_manager apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];BOOL written=NO;[a startAction:self];@try{if(CMTimeCompare(a.currentTime,_editTime)==0){NSMutableDictionary *doc=DYMutablePlist(DYReadTools(_manager,a.currentTime).document);if(DYSetToolStrength(doc,_nodeID,amount/100))written=DYWriteTools(_manager,doc,a.currentTime);}}@finally{[a endAction:self];} if(written){_slider.doubleValue=amount;_field.stringValue=[NSString stringWithFormat:@"%.0f%%",amount];[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:_manager];}else NSBeep();if(discrete)[self endStrengthGesture]; } - (void)resetStrength:(id)sender{_field.stringValue=@"100%";[self strengthChanged:_field];} @end