feat: complete FxPlug integration, input-aware auto grade and FCP wrapper
这个提交包含在:
1 父节点
2f11e8bd0f
当前提交
2330eb737e
36 个文件已更改
+4320
-131
没有与搜索条件相匹配的文件
@@ -0,0 +1,162 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Rebuild the single-filter native FCP wrapper from versioned native samples.
|
||||
|
||||
The helper exports this product's actual DYDescriptors and Foundation archives;
|
||||
it never loads or launches the vendor application. No GUI actions are performed.
|
||||
"""
|
||||
from pathlib import Path
|
||||
import argparse,base64,copy,hashlib,json,plistlib,subprocess,tempfile,xml.etree.ElementTree as E
|
||||
|
||||
ROOT=Path(__file__).resolve().parent.parent
|
||||
TEMPLATE=ROOT/'template'
|
||||
SOURCES=TEMPLATE/'sources'
|
||||
PROJECT_UUID='7d468273c013498e9806a0d7bc32fddf'
|
||||
PLUGIN_UUID='1C17B73B-F229-4C09-A434-EAF6DFF5F22A'
|
||||
NATIVE_ALPHABET='*-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
|
||||
STANDARD_ALPHABET='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
|
||||
CONTENT_TAGS={'scenenode','layer','group','filter','behavior','mask'}
|
||||
|
||||
|
||||
def sha(data):return hashlib.sha256(data).hexdigest()
|
||||
|
||||
def model_identity():
|
||||
files=['大鱼调色/Plugin/DYModel.h','大鱼调色/Plugin/DYModel.mm','大鱼调色/Plugin/DYUniforms.h','template/tools/dump_model.mm']
|
||||
return {name:sha((ROOT/name).read_bytes()) for name in files}
|
||||
|
||||
def refresh_metadata():
|
||||
cache=Path('/Users/mac/Library/Caches/CodexBuilds/com.dayu.color/template-model')
|
||||
cache.mkdir(parents=True,exist_ok=True)
|
||||
executable=cache/'dump_model'
|
||||
command=['xcrun','clang++','-std=c++17','-fno-objc-arc','-fblocks','-F','/Library/Developer/SDKs/FxPlug.sdk/Library/Frameworks','-F','/Library/Developer/Frameworks','-framework','Foundation','-framework','AppKit','-framework','FxPlug','-Wl,-rpath,/Library/Developer/Frameworks','-I',str(ROOT/'大鱼调色/Plugin'),str(TEMPLATE/'tools/dump_model.mm'),str(ROOT/'大鱼调色/Plugin/DYModel.mm'),'-o',str(executable)]
|
||||
subprocess.run(command,check=True)
|
||||
result=json.loads(subprocess.check_output([str(executable)],text=True))
|
||||
result['sourceSHA256']=model_identity()
|
||||
(SOURCES/'RegisteredParameters.json').write_text(json.dumps(result,ensure_ascii=False,indent=2,sort_keys=True)+'\n')
|
||||
executable.unlink()
|
||||
return result
|
||||
|
||||
|
||||
def metadata():
|
||||
result=json.loads((SOURCES/'RegisteredParameters.json').read_text())
|
||||
if result['sourceSHA256']!=model_identity():raise ValueError('DYModel changed. Review it, then regenerate metadata with --refresh-model.')
|
||||
pids=[str(p['pid']) for p in result['parameters']]
|
||||
if len(pids)!=len(set(pids)):raise ValueError('Duplicate native parameter ID')
|
||||
return result
|
||||
|
||||
|
||||
def custom_archive(encoded):
|
||||
# Motion custom data carrier = big-endian length, '*', NSKeyedArchive, zero.
|
||||
data=base64.b64decode(encoded)
|
||||
count=int.from_bytes(data[:8],'big')
|
||||
if data[8]!=42 or data[9+count:]!=b'\0':raise ValueError('Unexpected native custom data carrier')
|
||||
outer=plistlib.loads(data[9:9+count]);inner=plistlib.loads(outer['$objects'][1])
|
||||
obj=inner['$objects'][1];name=inner['$objects'][obj['$class'].data]['$classname']
|
||||
text=encoded.rstrip('=').translate(str.maketrans(STANDARD_ALPHABET,NATIVE_ALPHABET))
|
||||
return text,name
|
||||
|
||||
|
||||
def build(model):
|
||||
root=E.parse(SOURCES/'NativeEffectSource.moef').getroot()
|
||||
scene=root.find('scene');project=scene.find('scenenode[@factoryID="4"]')
|
||||
source=scene.find('.//scenenode[@name="效果源"]')
|
||||
if source is None or root.get('version')!='5.13' or root.findtext('displayversion')!='5.6.7':raise ValueError('Unexpected native EffectSource source')
|
||||
if source.find('parameter[@id="2"]/parameter[@id="321"]').get('value')!='3':raise ValueError('Expected native EffectSource type 3')
|
||||
native_factories=E.parse(SOURCES/'NativeFactories.xml').getroot()
|
||||
lookup={f.get('uuid'):f for f in native_factories}
|
||||
factory_ids={'deca4859b16011d7a12d0003936f6f92':'5','402246385249454b90e08b2ee1b6bf06':'6','e35c74f01d5042f6b468eb530169bfb7':'7'}
|
||||
insert_at=list(root).index(root.findall('factory')[-1])+1
|
||||
for uuid,fid in factory_ids.items():
|
||||
factory=copy.deepcopy(lookup[uuid]);factory.set('id',fid);root.insert(insert_at,factory);insert_at+=1
|
||||
filt=E.parse(SOURCES/'NativeFxPlugShell.xml').getroot()
|
||||
# Keep the original native host mix/flip/input-point/OSC parameters, replace
|
||||
# the product's entire registered parameter set and custom archives.
|
||||
host=list(filt.findall('parameter'))
|
||||
for node in host:filt.remove(node)
|
||||
for pid,name in [('9000','大鱼调色'),('9001','LUT 文件')]:
|
||||
text,class_name=custom_archive(model['archivesBase64'][pid])
|
||||
expected='DYInspectorToken' if pid=='9000' else 'DYAssetState'
|
||||
if class_name!=expected:raise ValueError('Wrong custom parameter class')
|
||||
flags='12884901888' if pid=='9000' else '12889161776'
|
||||
param=E.SubElement(filt,'parameter',name=name,id=pid,flags=flags)
|
||||
E.SubElement(param,'numberOfKeypoints').text='0'
|
||||
E.SubElement(param,'defaultVal').text=text;E.SubElement(param,'dataValue').text=text
|
||||
for row in model['parameters']:
|
||||
value=format(float(row['default']),'.17g')
|
||||
E.SubElement(filt,'parameter',name=row['title'],id=str(row['pid']),flags='12889161760',default=value,value=value)
|
||||
for node in host:filt.append(node)
|
||||
source.append(filt)
|
||||
copyright=E.parse(SOURCES/'CopyrightRig.xml').getroot()
|
||||
entity_map={'3356608241':'10080','3356608243':'10081','3356608245':'10082'}
|
||||
for node in copyright.iter('scenenode'):
|
||||
node.set('id',entity_map[node.get('id')]);node.set('factoryID','6' if node.get('factoryID')=='1' else '7')
|
||||
# Native Rig stays directly below scene, after its native project.
|
||||
scene.insert(list(scene).index(project)+1,copyright)
|
||||
pub=scene.find('publishSettings')
|
||||
for node in list(pub):
|
||||
if node.tag!='version':pub.remove(node)
|
||||
for object_id,name in [('10081','FCP 版本作者→'),('10082','更多模板浏览器访问→')]:
|
||||
E.SubElement(pub,'target',object=object_id,channel='./2/100',name=name)
|
||||
E.SubElement(pub,'target',object='10060',channel='./9000',name='大鱼调色')
|
||||
E.SubElement(pub,'target',object='10060',channel='./10001',name='混合')
|
||||
current=scene.find('currentObject')
|
||||
if current is None:
|
||||
current=E.Element('currentObject');scene.insert(list(scene).index(scene.find('currentFrame'))+1,current)
|
||||
current.text=project.get('id');scene.find('currentFrame').text='0 1 1 0'
|
||||
for node in scene.iter():
|
||||
flag=node.find('baseFlags')
|
||||
if flag is not None and node.tag in CONTENT_TAGS:
|
||||
value=int(flag.text);flag.text=str(value|0x10000001 if node is project else value&~0x10000001)
|
||||
scene.find('sceneSettings/backgroundColor').set('alpha','0')
|
||||
E.indent(root,space='\t')
|
||||
data=b'<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE ozxmlscene>\n'+E.tostring(root,encoding='utf-8')+b'\n'
|
||||
return data
|
||||
|
||||
|
||||
def verify(data,model):
|
||||
root=E.fromstring(data);scene=root.find('scene');factories={f.get('id'):f.get('uuid') for f in root.findall('factory')}
|
||||
filters=root.findall('.//filter')
|
||||
assert len(filters)==1 and filters[0].get('pluginUUID')==PLUGIN_UUID
|
||||
f=filters[0];params={p.get('id'):p for p in f.findall('parameter')}
|
||||
assert len(params)==len(list(f.findall('parameter')))
|
||||
for row in model['parameters']:
|
||||
p=params[str(row['pid'])];assert float(p.get('default'))==float(row['default'])==float(p.get('value'))
|
||||
assert all(not v in data for v in (b'LumiGrade',b'CameraRawTables',b'1.png',b'relativeURL'))
|
||||
assert len(root.findall('.//behavior'))==0 and len(root.findall('.//keypoint'))==0
|
||||
assert scene.find('.//scenenode[@name="效果源"]/parameter[@id="2"]/parameter[@id="321"]').get('value')=='3'
|
||||
urls=[n.text for n in root.iter() if n.tag in ('pathURL','relativeURL')]
|
||||
assert urls==['Drop Zone.tiff']
|
||||
projects=[n for n in scene.findall('scenenode') if factories.get(n.get('factoryID'))==PROJECT_UUID];assert len(projects)==1
|
||||
project=projects[0];selected=[]
|
||||
for node in scene.iter():
|
||||
if node.tag in CONTENT_TAGS and node is not project and node.find('baseFlags') is not None and int(node.findtext('baseFlags'))&0x10000001:selected.append(node.get('id'))
|
||||
assert not selected and scene.findtext('currentObject')==project.get('id')
|
||||
pub=scene.find('publishSettings').findall('target')
|
||||
assert [(t.get('object'),t.get('channel'),t.get('name')) for t in pub]==[('10081','./2/100','FCP 版本作者→'),('10082','./2/100','更多模板浏览器访问→'),('10060','./9000','大鱼调色'),('10060','./10001','混合')]
|
||||
# Compare every native Rig/widget field after reversing entity/factory IDs.
|
||||
rig=scene.find('scenenode[@id="10080"]');assert factories[rig.get('factoryID')]=='402246385249454b90e08b2ee1b6bf06'
|
||||
reverse=copy.deepcopy(rig)
|
||||
entity_map={'10080':'3356608241','10081':'3356608243','10082':'3356608245'}
|
||||
for node in reverse.iter('scenenode'):
|
||||
node.set('id',entity_map[node.get('id')]);node.set('factoryID','1' if node.get('factoryID')=='6' else '6')
|
||||
def structure(node):return (node.tag,dict(node.attrib),(node.text or '').strip(),[structure(child) for child in node])
|
||||
assert structure(reverse)==structure(E.parse(SOURCES/'CopyrightRig.xml').getroot())
|
||||
assert not any(f.get('uuid')=='dd0036f96c9e4bfdadb82f71fbf5c9d8' for f in root.findall('factory'))
|
||||
for widget_id,title,flags in [('10081','大鱼先森Media','16842768'),('10082','dayu.media','16842769')]:
|
||||
widget=rig.find('scenenode[@id="'+widget_id+'"]');assert factories[widget.get('factoryID')]=='e35c74f01d5042f6b468eb530169bfb7'
|
||||
menu=widget.find('parameter[@id="2"]/parameter[@id="100"]')
|
||||
assert menu.attrib=={'name':'弹出式菜单','id':'100','flags':flags,'default':'2','value':'2'}
|
||||
assert [entry.attrib for entry in menu.findall('entry')]==[{'name':title,'tag':'2'}]
|
||||
assert widget.findtext('affecting')=='2' and widget.findtext('snapshot')=='3'
|
||||
assert len({n.get('id') for n in scene.iter() if n.tag in CONTENT_TAGS})==len([n for n in scene.iter() if n.tag in CONTENT_TAGS])
|
||||
return {'passed':True,'sha256':sha(data),'version':root.get('version'),'displayversion':root.findtext('displayversion'),'filterCount':1,'nativeFloatParameters':len(model['parameters']),'customParameters':2,'publications':[dict(t.attrib) for t in pub],'effectSourceType':3,'externalMediaRequired':False,'placeholder':'native Drop Zone.tiff','animationObjects':0,'copyright':{'passed':True,'rig':'10080','author':'10081','site':'10082','unbound':True},'savedSelection':{'passed':True,'selectedContentCount':0,'currentObjectIsProject':True},'hostUIVerified':False,'hostRenderVerified':False}
|
||||
|
||||
|
||||
def main():
|
||||
p=argparse.ArgumentParser(description=__doc__);p.add_argument('--output',type=Path,default=TEMPLATE/'大鱼调色.moef');p.add_argument('--overwrite',action='store_true');p.add_argument('--refresh-model',action='store_true');args=p.parse_args()
|
||||
if args.output.exists() and not args.overwrite:raise FileExistsError('Output exists; choose another file or explicitly --overwrite')
|
||||
model=refresh_metadata() if args.refresh_model else metadata()
|
||||
data=build(model);report=verify(data,model)
|
||||
args.output.parent.mkdir(parents=True,exist_ok=True);args.output.write_bytes(data)
|
||||
(TEMPLATE/'verification/StaticContract.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n')
|
||||
print(json.dumps(report,ensure_ascii=False,indent=2))
|
||||
if __name__=='__main__':main()
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Single-install Release delivery; keeps a product lock through host acceptance."""
|
||||
from pathlib import Path
|
||||
import subprocess,os,json,shutil,plistlib,uuid,sys,datetime,hashlib
|
||||
ROOT=Path(__file__).resolve().parent.parent
|
||||
CACHE=Path('/Users/mac/Library/Caches/CodexBuilds/com.dayu.color')
|
||||
LOCK=Path('/Users/mac/.codex/app-delivery-locks/com.dayu.color.lock')
|
||||
DEST=Path('/Library/Plug-Ins/FxPlug/大鱼调色.app')
|
||||
APP=CACHE/'DerivedData/Build/Products/Release/大鱼调色.app'
|
||||
LOOSE=CACHE/'DerivedData/Build/Products/Release/大鱼调色 XPC Service.pluginkit'
|
||||
PLUGIN='Contents/PlugIns/大鱼调色 XPC Service.pluginkit'
|
||||
TEMPLATE=Path.home()/'Movies/Motion Templates.localized/Effects.localized/大鱼调色/大鱼调色/大鱼调色.moef'
|
||||
IDENTITY='Developer ID Application: zhong luo (B3W25FX5H5)'
|
||||
PROFILE='codex-dayu-notary-B3W25FX5H5'
|
||||
KEYCHAIN='/Users/mac/Library/Keychains/login.keychain-db'
|
||||
|
||||
def run(*args,log=None):
|
||||
if log:
|
||||
with Path(log).open('w') as f:subprocess.run(args,cwd=ROOT,stdout=f,stderr=subprocess.STDOUT,check=True)
|
||||
return ''
|
||||
return subprocess.check_output(args,cwd=ROOT,text=True,stderr=subprocess.STDOUT).strip()
|
||||
def hosts_closed():
|
||||
lines=run('ps','-axo','pid=,comm=').splitlines()
|
||||
live=[l for l in lines if l.endswith(('/Contents/MacOS/Final Cut Pro','/Contents/MacOS/Motion'))]
|
||||
if live:raise RuntimeError('请先正常退出宿主,再继续交付:'+str(live))
|
||||
def identity(path,expected):
|
||||
p=plistlib.loads((path/'Contents/Info.plist').read_bytes())
|
||||
if p['CFBundleIdentifier']!=expected:raise RuntimeError('产品身份不匹配: '+str(path))
|
||||
def unregister(path):
|
||||
reg=run('pluginkit','-m','-A','-D','-v','-i','com.dayu.color.XPC')
|
||||
if any(l.rstrip().endswith('\t'+str(path)) for l in reg.splitlines()):run('pluginkit','-r',str(path))
|
||||
def main():
|
||||
hosts_closed();CACHE.mkdir(parents=True,exist_ok=True);LOCK.parent.mkdir(parents=True,exist_ok=True);LOCK.mkdir()
|
||||
(LOCK/'owner.json').write_text(json.dumps(dict(PID=os.getpid(),cwd=str(ROOT),product='大鱼调色',started=datetime.datetime.now(datetime.timezone.utc).isoformat())))
|
||||
old=None;stage=None
|
||||
try:
|
||||
ids=run('security','find-identity','-v','-p','codesigning')
|
||||
if IDENTITY not in ids:raise RuntimeError('有效发布证书或私钥不可用')
|
||||
print('Building final Release',flush=True)
|
||||
run('xcodebuild','-project','大鱼调色.xcodeproj','-scheme','Wrapper Application','-configuration','Release','-derivedDataPath',str(CACHE/'DerivedData'),'build',log=CACHE/'release-build.log')
|
||||
b=APP/'Contents/Resources/FCP Templates/大鱼调色.moef';b.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(ROOT/'template/大鱼调色.moef',b)
|
||||
identity(APP,'com.dayu.color');plugin=APP/PLUGIN;identity(plugin,'com.dayu.color.XPC')
|
||||
for name in ['FxPlug','PluginManager']:run('codesign','--force','--timestamp','--options','runtime','--sign',IDENTITY,str(plugin/'Contents/Frameworks'/(name+'.framework')))
|
||||
run('codesign','--force','--timestamp','--options','runtime','--sign',IDENTITY,str(plugin))
|
||||
run('codesign','--force','--timestamp','--options','runtime','--entitlements',str(ROOT/'大鱼调色/Wrapper Application/SandboxEntitlements.entitlements'),'--sign',IDENTITY,str(APP))
|
||||
run('codesign','--verify','--deep','--strict',str(APP))
|
||||
details=run('codesign','-dvvv',str(APP))
|
||||
if 'TeamIdentifier=B3W25FX5H5' not in details or 'Timestamp=' not in details or 'runtime' not in details:raise RuntimeError('签名身份/时间戳/runtime未通过')
|
||||
archive=CACHE/'notarization-submission.zip'
|
||||
if archive.exists():archive.unlink()
|
||||
run('ditto','-c','-k','--keepParent',str(APP),str(archive));print('Submitting signed Release to Apple',flush=True)
|
||||
result=json.loads(run('xcrun','notarytool','submit',str(archive),'--keychain-profile',PROFILE,'--keychain',KEYCHAIN,'--wait','--output-format','json'));(CACHE/'notary-result.json').write_text(json.dumps(result,indent=2))
|
||||
if result.get('status')!='Accepted':
|
||||
if result.get('id'):run('xcrun','notarytool','log',result['id'],'--keychain-profile',PROFILE,'--keychain',KEYCHAIN,str(CACHE/'notary-rejection.json'))
|
||||
raise RuntimeError('Apple未Accepted,正式旧版未替换')
|
||||
run('xcrun','stapler','staple',str(APP));run('xcrun','stapler','validate',str(APP));hosts_closed()
|
||||
stage=DEST.parent/('.dayu-color-staging-'+uuid.uuid4().hex+'.app');run('ditto',str(APP),str(stage))
|
||||
if DEST.exists():
|
||||
identity(DEST,'com.dayu.color');old=DEST.parent/('.dayu-color-previous-'+uuid.uuid4().hex+'.app');os.replace(DEST,old)
|
||||
os.replace(stage,DEST);stage=None
|
||||
try:
|
||||
identity(DEST,'com.dayu.color');run('codesign','--verify','--deep','--strict',str(DEST));run('xcrun','stapler','validate',str(DEST));gate=run('spctl','--assess','--type','execute','--verbose=2',str(DEST))
|
||||
except Exception:
|
||||
failed=DEST.parent/('.dayu-color-failed-'+uuid.uuid4().hex+'.app');os.replace(DEST,failed)
|
||||
if old:os.replace(old,DEST);old=None
|
||||
raise
|
||||
TEMPLATE.parent.mkdir(parents=True,exist_ok=True)
|
||||
if TEMPLATE.exists():shutil.copy2(TEMPLATE,CACHE/'previous-template.moef')
|
||||
tmp=TEMPLATE.with_name('.dayu-color-template-stage.moef');shutil.copy2(DEST/'Contents/Resources/FCP Templates/大鱼调色.moef',tmp);os.replace(tmp,TEMPLATE)
|
||||
# All generated copies are removed before final registry/host verification.
|
||||
for copy,expected in [(APP,'com.dayu.color'),(LOOSE,'com.dayu.color.XPC')]+([(old,'com.dayu.color')] if old else []):
|
||||
if copy.exists():identity(copy,expected);unregister(copy/PLUGIN if copy.suffix=='.app' else copy);shutil.rmtree(copy)
|
||||
old=None;archive.unlink();backup=CACHE/'previous-template.moef'
|
||||
if backup.exists():backup.unlink()
|
||||
run('pluginkit','-a',str(DEST/PLUGIN));registry=run('pluginkit','-m','-A','-D','-v','-i','com.dayu.color.XPC')
|
||||
entries=[l for l in registry.splitlines() if 'com.dayu.color.XPC(' in l]
|
||||
if len(entries)!=1 or not entries[0].rstrip().endswith('\t'+str(DEST/PLUGIN)):raise RuntimeError('PluginKit发现多份/错误版本: '+registry)
|
||||
record=dict(status='installed-awaiting-host-verification',path=str(DEST),bundleID='com.dayu.color',version='1.0.0',build=plistlib.loads((DEST/'Contents/Info.plist').read_bytes())['CFBundleVersion'],team='B3W25FX5H5',notaryID=result['id'],notaryStatus=result['status'],gatekeeper=gate,sourceCommit=run('git','rev-parse','HEAD'),templatePath=str(TEMPLATE),templateSHA256=hashlib.sha256(TEMPLATE.read_bytes()).hexdigest(),shaderSHA256=hashlib.sha256((DEST/PLUGIN/'Contents/Resources/default.metallib').read_bytes()).hexdigest())
|
||||
output=ROOT/'verification/Delivery.json';output.write_text(json.dumps(record,ensure_ascii=False,indent=2)+'\n')
|
||||
run('open',str(DEST));print('FORMAL_INSTALLED. Run installed self-test and host verification; type complete only after success. Type leave to preserve pending state.',flush=True)
|
||||
for decision in sys.stdin:
|
||||
if decision.strip()=='complete':record['status']='verified';output.write_text(json.dumps(record,ensure_ascii=False,indent=2)+'\n');break
|
||||
if decision.strip()=='leave':break
|
||||
finally:
|
||||
if stage and stage.exists():shutil.rmtree(stage)
|
||||
(LOCK/'owner.json').unlink();LOCK.rmdir()
|
||||
if __name__=='__main__':main()
|
||||
@@ -25,6 +25,8 @@ fragment buffer0 为 `DYUniforms`,buffer1 为 `float sceneLevel`,buffer2 必
|
||||
|
||||
`dyPreview` 为每实例缩略采样核:texture0 straight linear source、buffer0 写 `float4[4096]`;调度64×64,每格按归一化中心采样,RGB使用标准sRGB分段编码,alpha原样保留。不夹断HDR或负值;CPU用途自行决定显示、统计的有效范围。
|
||||
|
||||
`dyAnalysis` 使用相同契约,尺寸为320×180、buffer0写`float4[57600]`,匹配自动调色参考算法的分析分辨率。自动调色将样本量化至UInt8域再计算分位数和灰样本权重;Metal双线性采样与NSImage/CoreGraphics重采样不声称逐字节相同。
|
||||
|
||||
局部滤镜最大采样半径 18×1.7=30.6 像素;tile 请求至少 32 像素 halo,并设置正确的 UV。自适应白场必须采用全帧统计;不能逐 tile 算独立白场。
|
||||
|
||||
`dyWhitesSceneStatistics` 绑定 texture0 source、texture1 白平衡 LUT、buffer0 uniforms、buffer1 写 float。必须只调度 1 个 threadgroup、每组 256 个线程。固定取 256×256 均匀网格,跳过 alpha<=0;统计 96%–99.5% 亮度区间,结果钳制 0.35–1。此路径按参考行为不执行输入 LUT/三原色矩阵。
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "../大鱼调色/Plugin/DYAutoGrade.h"
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
|
||||
static size_t checks=0;
|
||||
static void require(bool condition,const char *message){++checks;if(!condition){fprintf(stderr,"FAIL: %s\n",message);exit(1);}}
|
||||
static NSMutableData *solid(size_t count,float r,float g,float b,float a=1){
|
||||
NSMutableData *data=[NSMutableData dataWithLength:count*16];float *p=(float *)data.mutableBytes;
|
||||
for(size_t i=0;i<count;i++){p[i*4]=r;p[i*4+1]=g;p[i*4+2]=b;p[i*4+3]=a;}return data;
|
||||
}
|
||||
static void value(NSDictionary *result,NSString *key,double expected){
|
||||
require(result[key]!=nil,key.UTF8String);require(std::fabs([result[key] doubleValue]-expected)<1e-9,key.UTF8String);
|
||||
}
|
||||
static void equalResults(NSDictionary *a,NSDictionary *b,const char *message){require(a&&b&&[a isEqualToDictionary:b],message);}
|
||||
|
||||
int main(){@autoreleasepool{
|
||||
require(DYAutoGrade(nil)==nil,"nil input");require(DYAutoGrade([NSData data])==nil,"empty input");
|
||||
require(DYAutoGrade([NSMutableData dataWithLength:15])==nil,"malformed float RGBA");
|
||||
require(DYAutoGrade(solid(128,.5f,.5f,.5f))==nil,"minimum 129 usable pixels");
|
||||
require(DYAutoGrade(solid(129,.5f,.5f,.5f))!=nil,"129 usable pixels accepted");
|
||||
require(DYAutoGrade(solid(4096,.5f,.5f,.5f,8.f/255))==nil,"alpha byte 8 excluded");
|
||||
require(DYAutoGrade(solid(4096,.5f,.5f,.5f,9.f/255))!=nil,"alpha byte 9 included");
|
||||
require(DYAutoGrade(solid(4096,NAN,.5f,.5f))==nil,"NaN excluded");
|
||||
require(DYAutoGrade(solid(4096,.5f,INFINITY,.5f))==nil,"infinite RGB excluded");
|
||||
require(DYAutoGrade(solid(4096,.5f,.5f,.5f,NAN))==nil,"NaN alpha excluded");
|
||||
// Closed-form golden values from the documented original coefficients.
|
||||
NSDictionary *black=DYAutoGrade(solid(320*180,0,0,0));
|
||||
value(black,@"exposure",1.1);value(black,@"contrast",34);value(black,@"highlights",26);value(black,@"shadows",32);
|
||||
value(black,@"whites",42);value(black,@"blacks",8);value(black,@"vibrance",25);value(black,@"saturation",9);
|
||||
value(black,@"temperature",0);value(black,@"tint",0);
|
||||
NSDictionary *white=DYAutoGrade(solid(320*180,1,1,1));
|
||||
value(white,@"exposure",-.81);value(white,@"contrast",34);value(white,@"highlights",-26);value(white,@"shadows",-22);
|
||||
value(white,@"whites",-6);value(white,@"blacks",-36);value(white,@"vibrance",25);value(white,@"saturation",9);
|
||||
NSDictionary *gray=DYAutoGrade(solid(4096,128.f/255,128.f/255,128.f/255));
|
||||
value(gray,@"exposure",-.09);value(gray,@"contrast",34);value(gray,@"highlights",26);value(gray,@"shadows",-22);
|
||||
value(gray,@"whites",39);value(gray,@"blacks",-36);value(gray,@"temperature",0);value(gray,@"tint",0);
|
||||
equalResults(black,DYAutoGrade(solid(4096,-3,-3,-3)),"negative float samples become UInt8 black");
|
||||
equalResults(white,DYAutoGrade(solid(4096,5,5,5)),"HDR float samples become UInt8 white");
|
||||
equalResults(black,DYAutoGrade(solid(4096,0,0,0)),"sample count invariance for uniform image");
|
||||
NSMutableData *outlier=solid(320*180,0,0,0);float *p=(float *)outlier.mutableBytes;p[0]=p[1]=p[2]=1;
|
||||
equalResults(black,DYAutoGrade(outlier),"single bright outlier excluded by percentiles");
|
||||
NSDictionary *red=DYAutoGrade(solid(4096,1,0,0));value(red,@"vibrance",-8);value(red,@"saturation",-12);
|
||||
require(DYAutoWhiteBalance(solid(4096,1,0,0))==nil,"saturated image has no neutral candidate");
|
||||
require(DYAutoWhiteBalance(solid(4096,0,0,0))==nil,"black image has no neutral candidate");
|
||||
require(DYAutoWhiteBalance(solid(4096,1,1,1))==nil,"clipped white excluded from WB");
|
||||
require(DYAutoWhiteBalance(solid(128,.5f,.5f,.5f))==nil,"WB insufficient samples");
|
||||
NSDictionary *wb=DYAutoWhiteBalance(solid(4096,.5f,.5f,.5f));
|
||||
require(wb!=nil,"WB table resource available to CLI bundle");value(wb,@"temperature",0);value(wb,@"tint",0);
|
||||
wb=DYAutoWhiteBalance(solid(4096,.52f,.5f,.48f));require(wb!=nil,"low-saturation cast has neutral estimate");
|
||||
require(std::isfinite([wb[@"temperature"] doubleValue])&&std::fabs([wb[@"temperature"] doubleValue])<=100,"WB temperature finite and bounded");
|
||||
require(std::isfinite([wb[@"tint"] doubleValue])&&std::fabs([wb[@"tint"] doubleValue])<=100,"WB tint finite and bounded");
|
||||
require([wb[@"temperature"] floatValue]!=0||[wb[@"tint"] floatValue]!=0,"WB corrects a measured cast");
|
||||
printf("PASS: %zu auto-grade and white-balance boundary assertions\n",checks);return 0;
|
||||
}}
|
||||
@@ -10,6 +10,12 @@
|
||||
static void require(bool condition,const char *message){if(!condition){fprintf(stderr,"FAIL: %s\n",message);exit(1);}}
|
||||
static void closeColor(vector_float3 a,vector_float3 b,const char *message,float tolerance=3e-6f){require(simd_reduce_max(simd_abs(a-b))<=tolerance,message);}
|
||||
static vector_float3 cubeColor(NSData *data,int r,int g,int b){auto p=(const vector_float4 *)data.bytes;vector_float4 c=p[(b*33+g)*33+r];return {c.x,c.y,c.z};}
|
||||
static NSData *textureBytes(id<MTLTexture>texture){
|
||||
require(texture!=nil,"CPU table interface creates Metal texture");
|
||||
NSMutableData *data=[NSMutableData dataWithLength:33*33*33*16];
|
||||
[texture getBytes:data.mutableBytes bytesPerRow:33*16 bytesPerImage:33*33*16 fromRegion:MTLRegionMake3D(0,0,0,33,33,33) mipmapLevel:0 slice:0];
|
||||
return data;
|
||||
}
|
||||
static vector_float3 referenceSample(NSData *tables,int table,vector_float3 c){
|
||||
const uint8_t *bytes=(const uint8_t *)tables.bytes;
|
||||
int cell[3];double f[3],sum[3]={0,0,0};
|
||||
@@ -74,5 +80,28 @@ int main(int argc,const char *argv[]){@autoreleasepool{
|
||||
closeColor(v.primariesM0+v.primariesM1+v.primariesM2,(vector_float3){1,1,1},"primaries preserves the D65 white point",2e-5f);
|
||||
require(simd_reduce_max(simd_abs(v.primariesM0-(vector_float3){1,0,0}))+simd_reduce_max(simd_abs(v.primariesM1-(vector_float3){0,1,0}))+simd_reduce_max(simd_abs(v.primariesM2-(vector_float3){0,0,1}))>1e-4f,"all six primary controls change the matrix");
|
||||
}
|
||||
// Optional integration mode runs the actual public interface with a CLI
|
||||
// bundle's resources, testing bypass after non-neutral values were cached.
|
||||
if([[NSProcessInfo processInfo].environment[@"DY_TABLES_INTERFACE_TEST"]boolValue]) {
|
||||
id<MTLDevice>device=MTLCreateSystemDefaultDevice();require(device!=nil,"Metal test device");
|
||||
DYColorTables *builder=[DYColorTables new];DYUniforms v={};
|
||||
v.temperature=75;v.tint=-50;v.temperatureEnabled=1;v.tintEnabled=1;v.colorSectionEnabled=1;
|
||||
NSData *enabled=textureBytes([builder whiteBalanceForDevice:device uniforms:&v]);
|
||||
require(![enabled isEqualToData:neutral],"enabled WB changes the LUT");
|
||||
v.colorSectionEnabled=0;
|
||||
require([textureBytes([builder whiteBalanceForDevice:device uniforms:&v])isEqualToData:neutral],"color section bypass neutralizes cached WB");
|
||||
v.colorSectionEnabled=1;v.temperatureEnabled=0;v.tintEnabled=0;
|
||||
require([textureBytes([builder whiteBalanceForDevice:device uniforms:&v])isEqualToData:neutral],"single WB toggles neutralize their cached values");
|
||||
v.hslHueA.x=100;v.hslSectionEnabled=1;
|
||||
require(![textureBytes([builder hslForDevice:device uniforms:&v])isEqualToData:neutral],"enabled HSL changes the LUT");
|
||||
v.hslSectionEnabled=0;
|
||||
require([textureBytes([builder hslForDevice:device uniforms:&v])isEqualToData:neutral],"HSL section bypass neutralizes cached controls");
|
||||
v.colorGradingSectionEnabled=1;v.colorGradingHueSatA.y=100;v.colorGradingBlending=50;
|
||||
require(![textureBytes([builder gradingForDevice:device uniforms:&v])isEqualToData:neutral],"enabled grading changes the LUT");
|
||||
v.colorGradingSectionEnabled=0;
|
||||
require([textureBytes([builder gradingForDevice:device uniforms:&v])isEqualToData:neutral],"grading section bypass neutralizes cached controls");
|
||||
require(builder.lastError==nil,"public interface has no resource/GPU error");
|
||||
[builder release];[device release];printf("PASS: public Metal table interface, WB item toggles and cached WB/HSL/grading section bypass\n");
|
||||
}
|
||||
printf("PASS: resource integrity, rejection, trilinear oracle, WB blend, 24 HSL endpoints, 4 grading wheels, hue wrapping, 4 luminance endpoints and 6 primaries\n");
|
||||
}}
|
||||
+8
-6
@@ -142,18 +142,19 @@ static Pixels unpremultiply(id<MTLLibrary> library,id<MTLTexture> source) {
|
||||
[e dispatchThreads:MTLSizeMake(source.width,source.height,1) threadsPerThreadgroup:MTLSizeMake(16,16,1)];[e endEncoding];finish(cb);
|
||||
Pixels output(source.width*source.height*4);[destination getBytes:output.data() bytesPerRow:source.width*8 fromRegion:MTLRegionMake2D(0,0,source.width,source.height) mipmapLevel:0];return output;
|
||||
}
|
||||
static NSDictionary* preview(id<MTLLibrary> library) {
|
||||
NSError* error=nil;auto pipeline=[gpu newComputePipelineStateWithFunction:[library newFunctionWithName:@"dyPreview"] error:&error];need(pipeline!=nil,error.description);
|
||||
static NSDictionary* preview(id<MTLLibrary> library,bool analysis=false) {
|
||||
const size_t width=analysis?320:64,height=analysis?180:64;
|
||||
NSError* error=nil;auto pipeline=[gpu newComputePipelineStateWithFunction:[library newFunctionWithName:analysis?@"dyAnalysis":@"dyPreview"] error:&error];need(pipeline!=nil,error.description);
|
||||
size_t compared=0,different=0;double maxError=0;
|
||||
for(float level:{-.1f,0.f,.0031308f,.18f,1.f,2.f}) {
|
||||
Pixels input(8*8*4);for(size_t p=0;p<input.size();p+=4){input[p]=input[p+1]=input[p+2]=(__fp16)level;input[p+3]=(__fp16).375f;}
|
||||
auto source=image(input,8,8);auto output=[gpu newBufferWithLength:64*64*16 options:MTLResourceStorageModeShared];
|
||||
auto source=image(input,8,8);auto output=[gpu newBufferWithLength:width*height*16 options:MTLResourceStorageModeShared];
|
||||
auto cb=[queue commandBuffer];auto e=[cb computeCommandEncoder];[e setComputePipelineState:pipeline];[e setTexture:source atIndex:0];[e setBuffer:output offset:0 atIndex:0];
|
||||
[e dispatchThreads:MTLSizeMake(64,64,1) threadsPerThreadgroup:MTLSizeMake(16,16,1)];[e endEncoding];finish(cb);
|
||||
[e dispatchThreads:MTLSizeMake(width,height,1) threadsPerThreadgroup:MTLSizeMake(16,16,1)];[e endEncoding];finish(cb);
|
||||
float value=float((__fp16)level),encoded=value<=.0031308f?value*12.92f:1.055f*std::pow(value,1.f/2.4f)-.055f;
|
||||
const float* actual=(const float*)output.contents;for(size_t p=0;p<64*64*4;++p){float target=p%4==3?.375f:encoded;double d=std::abs(double(actual[p])-target);need(std::isfinite(d),@"nonfinite preview");++compared;if(d>2e-6)++different;maxError=std::max(maxError,d);}
|
||||
const float* actual=(const float*)output.contents;for(size_t p=0;p<width*height*4;++p){float target=p%4==3?.375f:encoded;double d=std::abs(double(actual[p])-target);need(std::isfinite(d),@"nonfinite preview");++compared;if(d>2e-6)++different;maxError=std::max(maxError,d);}
|
||||
}
|
||||
return @{@"name":@"64x64-preview-sRGB-alpha-HDR-negative",@"components":@(compared),@"differentAboveTolerance":@(different),@"maxAbsoluteError":@(maxError),@"tolerance":@(2e-6),@"pass":@(different==0)};
|
||||
return @{@"name":analysis?@"320x180-analysis-sRGB-alpha-HDR-negative":@"64x64-preview-sRGB-alpha-HDR-negative",@"components":@(compared),@"differentAboveTolerance":@(different),@"maxAbsoluteError":@(maxError),@"tolerance":@(2e-6),@"pass":@(different==0)};
|
||||
}
|
||||
|
||||
int main(int argc,const char* argv[]) { @autoreleasepool { @try {
|
||||
@@ -207,6 +208,7 @@ int main(int argc,const char* argv[]) { @autoreleasepool { @try {
|
||||
Pixels recovered=unpremultiply(ours,image(premultInput,w,h));[cases addObject:compare(@"unpremultiply-compute-boundary",unpremultExpected,recovered)];
|
||||
Pixels neutralPremult=render(dp,true,image(recovered,w,h),textures,u,w,h,0,1,true);[cases addObject:compare(@"neutral-premultiplied-roundtrip",premultInput,neutralPremult,false,.001)];
|
||||
[cases addObject:preview(ours)];
|
||||
[cases addObject:preview(ours,true)];
|
||||
bool passed=true;for(NSDictionary* row in cases)if(![row[@"pass"] boolValue])passed=false;
|
||||
NSDictionary* report=@{@"pass":@(passed),@"gpu":gpu.name,@"os":[NSProcessInfo processInfo].operatingSystemVersionString,
|
||||
@"referenceMetallibSHA256":digest(original),@"reconstructedMetallibSHA256":digest(current),@"imageSize":@[@(w),@(h)],
|
||||
|
||||
在新工单中引用
屏蔽一个用户