文件
dayu-color/大鱼调色/Plugin/DYLUTLibrary.mm
T

546 行
37 KiB
Plaintext
原始文件 Blame 文件历史

此文件含有模棱两可的 Unicode 字符
此文件含有可能会与其他字符混淆的 Unicode 字符。 如果您是想特意这样的,可以安全地忽略该警告。 使用 Escape 按钮显示他们。
#import "DYLUTLibrary.h"
#include <algorithm>
#include <charconv>
#include <string_view>
#include <string>
#include <xlocale.h>
#include <cmath>
#include <cstring>
#include <limits>
#include <limits.h>
#include <stdlib.h>
#include <zlib.h>
static NSString *const DYLUTLibraryErrorDomain=@"com.dayu.color.LUTLibrary";
static NSURL *DYLUTCanonicalURL(NSURL *url) {
// Foundation deliberately abbreviates /private/var back to /var in some
// URL normalization APIs; its enumerator returns the POSIX canonical path.
NSString *path=url.path.stringByStandardizingPath;
NSMutableArray *missing=[NSMutableArray array];char resolved[PATH_MAX];
while(path.length&&!realpath(path.fileSystemRepresentation,resolved)) {
NSString *parent=path.stringByDeletingLastPathComponent;
if([parent isEqual:path])return [NSURL fileURLWithPath:url.path.stringByStandardizingPath];
[missing insertObject:path.lastPathComponent atIndex:0];path=parent;
}
NSString *canonical=[[NSFileManager defaultManager]stringWithFileSystemRepresentation:resolved length:strlen(resolved)];
for(NSString *component in missing)canonical=[canonical stringByAppendingPathComponent:component];
return [NSURL fileURLWithPath:canonical];
}
static BOOL DYLUTFail(NSError **error,NSString *message) {
if(error)*error=[NSError errorWithDomain:DYLUTLibraryErrorDomain code:1
userInfo:@{NSLocalizedDescriptionKey:message?:@"LUT 操作未完成"}];
return NO;
}
@interface DYLUTPreparedTable () {
@public std::vector<float> values;
@public NSUInteger _dimension;
@public NSString *_path,*_revision;
}
@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;
dispatch_once(&once,^{cache=[NSCache new];cache.countLimit=12;cache.totalCostLimit=96*1024*1024;});
return cache;
}
static void DYLUTSample(const std::vector<float>& table,NSUInteger n,const float rgb[3],float out[3]) {
float fraction[3];NSUInteger index[3];
for(int c=0;c<3;c++) {
float scaled=std::min(1.f,std::max(0.f,rgb[c]))*float(n-1);
index[c]=std::min(n-2,(NSUInteger)scaled);fraction[c]=scaled-float(index[c]);
}
for(int c=0;c<3;c++) {
float sum=0;
for(int k=0;k<8;k++) {
int x=k&1,y=(k>>1)&1,z=(k>>2)&1;
sum+=table[(((index[2]+z)*n+index[1]+y)*n+index[0]+x)*4+c]
*(x?fraction[0]:1-fraction[0])*(y?fraction[1]:1-fraction[1])*(z?fraction[2]:1-fraction[2]);
}
out[c]=sum;
}
}
static BOOL DYLUTCancelled(NSProgress *progress,NSError **error) {
if(!progress.cancelled)return NO;
if(error)*error=[NSError errorWithDomain:NSCocoaErrorDomain code:NSUserCancelledError userInfo:@{NSLocalizedDescriptionKey:@"已取消 LUT 加载"}];
return YES;
}
static NSError *DYLUTFileError(NSError *error,NSURL *url) {
if(error.code==NSUserCancelledError&&[error.domain isEqual:NSCocoaErrorDomain])return error;
NSMutableDictionary *info=[NSMutableDictionary dictionaryWithDictionary:error.userInfo?:@{}];
info[NSLocalizedDescriptionKey]=[NSString stringWithFormat:@"%@:%@",url.lastPathComponent,error.localizedDescription?:@"无法读取此 LUT"];
info[NSFilePathErrorKey]=url.path;if(error)info[NSUnderlyingErrorKey]=error;
return [NSError errorWithDomain:error.domain?:DYLUTLibraryErrorDomain code:error?error.code:1 userInfo:info];
}
static bool DYLUTUnicodeSpace(uint32_t c) {
return c==0x20||(c>=9&&c<=13)||c==0x85||c==0xa0||c==0x1680||
(c>=0x2000&&c<=0x200a)||c==0x2028||c==0x2029||c==0x202f||c==0x205f||c==0x3000;
}
static void DYLUTAppendScalar(std::string& text,uint32_t c) {
if(DYLUTUnicodeSpace(c)) {
text+=char(c==13?'\r':c==10||c==0x85||c==0x2028||c==0x2029?'\n':' ');return;
}
if(c<0x80)text+=char(c);
else if(c<0x800){text+=char(0xc0|(c>>6));text+=char(0x80|(c&63));}
else if(c<0x10000){text+=char(0xe0|(c>>12));text+=char(0x80|((c>>6)&63));text+=char(0x80|(c&63));}
else {text+=char(0xf0|(c>>18));text+=char(0x80|((c>>12)&63));text+=char(0x80|((c>>6)&63));text+=char(0x80|(c&63));}
}
// Normalize only the working copy. Imports retain their original bytes. Narrow
// files remain byte-transparent so legacy TITLE/comment encodings still work.
static BOOL DYLUTText(NSData *bytes,std::string& text,NSProgress *progress,NSError **error) {
const uint8_t *p=(const uint8_t *)bytes.bytes;size_t length=bytes.length,offset=0,width=1;bool little=true;
if(!length)return DYLUTFail(error,@"LUT 文件为空");
auto unit=[&](size_t at,size_t w,bool le){uint32_t c=0;for(size_t k=0;k<w;k++)c|=uint32_t(p[at+k])<<(8*(le?k:w-1-k));return c;};
if(length>=4&&unit(0,4,true)==0x0000feff){width=4;offset=4;}
else if(length>=4&&unit(0,4,false)==0x0000feff){width=4;offset=4;little=false;}
else if(length>=2&&unit(0,2,true)==0xfeff){width=2;offset=2;}
else if(length>=2&&unit(0,2,false)==0xfeff){width=2;offset=2;little=false;}
else if(length>=3&&!memcmp(p,"\xef\xbb\xbf",3))offset=3;
else {
// Without a BOM, infer byte order only from a recognizable Cube prefix.
// Never remove arbitrary NUL bytes or guess an encoding from the title.
auto prefix=[&](size_t w,bool le){bool whitespace=false;
for(size_t at=0;at+w<=length&&at<128;at+=w){uint32_t c=unit(at,w,le);
if(DYLUTUnicodeSpace(c)||c==0xfeff){whitespace=true;continue;}
return c=='#'||(c>='A'&&c<='Z')||(c>='a'&&c<='z')||(c>='0'&&c<='9')||c=='+'||c=='-'||c=='.';
}return whitespace;
};
for(size_t w:{size_t(4),size_t(2)}) {
if(prefix(w,true)){width=w;break;}
if(prefix(w,false)){width=w;little=false;break;}
}
}
if(width==1){text.assign((const char *)p+offset,length-offset);return !DYLUTCancelled(progress,error);}
NSString *encoding=[NSString stringWithFormat:@"UTF-%lu%@",(unsigned long)(width*8),little?@"LE":@"BE"];
auto invalid=[&](NSString *detail){return DYLUTFail(error,[NSString stringWithFormat:@"%@ 编码损坏:%@",encoding,detail]);};
if((length-offset)%width)return invalid(@"文件结尾不完整");
text.clear();text.reserve((length-offset)/width);
size_t nextCancellationCheck=offset;
for(size_t at=offset;at<length;at+=width){
if(at>=nextCancellationCheck){if(DYLUTCancelled(progress,error))return NO;nextCancellationCheck=at+16384;}
uint32_t c=unit(at,width,little);
if(width==2&&c>=0xd800&&c<=0xdbff){
if(at+4>length)return invalid(@"缺少配对字符");uint32_t next=unit(at+2,2,little);
if(next<0xdc00||next>0xdfff)return invalid(@"字符配对无效");c=0x10000+((c-0xd800)<<10)+(next-0xdc00);at+=2;
}else if(c>=0xd800&&c<=0xdfff)return invalid(@"孤立的配对字符");
if(c>0x10ffff||c==0)return invalid(@"含无效字符");
DYLUTAppendScalar(text,c);
}
return !DYLUTCancelled(progress,error);
}
static std::string_view DYLUTTrim(std::string_view v) {
while(!v.empty()) {
unsigned char c=v.front();size_t count=0;
if(c<0x80){if(c==' '||(c>=9&&c<=13))count=1;else break;}
else if(c==0xc2&&v.size()>=2&&v[1]=='\xa0')count=2;
else if((c==0xe1||c==0xe2||c==0xe3)&&v.size()>=3&&(v.substr(0,3)=="\xe1\x9a\x80"||v.substr(0,3)=="\xe2\x80\xaf"||v.substr(0,3)=="\xe2\x81\x9f"||v.substr(0,3)=="\xe3\x80\x80"||(v.substr(0,2)=="\xe2\x80"&&(unsigned char)v[2]>=0x80&&(unsigned char)v[2]<=0x8a)))count=3;
if(!count)break;v.remove_prefix(count);
}return v;
}
static bool DYLUTTextNote(std::string_view text,locale_t numericLocale) {
if(text.empty())return false;
// A note must be separated from the preceding number and start with real
// text. Do not reinterpret malformed bytes or NaN/Inf as an annotation.
char *end=nullptr;strtof_l(text.data(),&end,numericLocale);
if(end!=text.data())return false;
NSString *note=[[[NSString alloc]initWithBytes:text.data() length:text.size()
encoding:NSUTF8StringEncoding]autorelease];
return note.length&&[NSCharacterSet.letterCharacterSet characterIsMember:[note characterAtIndex:0]];
}
static BOOL DYLUTParse(NSString *path,std::vector<float>& data,NSUInteger& size,NSProgress *progress,NSError **error) {
data.clear();size=0;
NSDictionary *attributes=[[NSFileManager defaultManager]attributesOfItemAtPath:path error:error];
if(!attributes)return NO;
if(![attributes[NSFileType]isEqual:NSFileTypeRegular])return DYLUTFail(error,@"LUT 必须是普通文件");
if([attributes[NSFileSize]unsignedLongLongValue]>256ULL*1024*1024)return DYLUTFail(error,@"LUT 文件超过 256 MB 限制");
NSData *bytes=[NSData dataWithContentsOfFile:path options:NSDataReadingMappedIfSafe error:error];
if(!bytes)return NO;
if([path.pathExtension.lowercaseString isEqual:@"dylut"]) {
if(bytes.length<36||memcmp(bytes.bytes,"DYLT",4))return DYLUTFail(error,@"输入 LUT 格式损坏");
uint32_t n=0,count=0;memcpy(&n,(const uint8_t *)bytes.bytes+4,4);memcpy(&count,(const uint8_t *)bytes.bytes+8,4);
if(n<2||n>128||count!=n*n*n*16)return DYLUTFail(error,@"输入 LUT 尺寸无效");
data.resize(count/4);uLongf length=count;
if(uncompress((Bytef *)data.data(),&length,(const Bytef *)bytes.bytes+36,bytes.length-36)!=Z_OK||length!=count)
return DYLUTFail(error,@"输入 LUT 解压失败");
for(float v:data)if(!std::isfinite(v))return DYLUTFail(error,@"输入 LUT 含无效数字");
size=n;return YES;
}
std::string storage;if(!DYLUTText(bytes,storage,progress,error))return NO;
static locale_t numericLocale;static dispatch_once_t localeOnce;dispatch_once(&localeOnce,^{numericLocale=newlocale(LC_NUMERIC_MASK,"C",NULL);});
float domainMin[3]={0,0,0},domainMax[3]={1,1,1};BOOL foundSize=NO;
std::string_view remaining(storage);NSUInteger rows=0;
if(remaining.size()>=3&&remaining.substr(0,3)=="\xef\xbb\xbf")remaining.remove_prefix(3);
auto trim=DYLUTTrim;
auto number=[&](std::string_view& v,float& value){v=trim(v);if(v.empty())return false;char *end=nullptr;value=strtof_l(v.data(),&end,numericLocale);if(end==v.data()||end>v.data()+v.size())return false;v.remove_prefix(end-v.data());return true;};
while(!remaining.empty()) {
if((rows++&1023)==0&&DYLUTCancelled(progress,error))return NO;
size_t end=remaining.find_first_of("\r\n");std::string_view line=remaining.substr(0,end);
if(end==std::string_view::npos)remaining={};else {size_t count=end+1;if(remaining[end]=='\r'&&count<remaining.size()&&remaining[count]=='\n')count++;remaining.remove_prefix(count);}
line=line.substr(0,line.find('#'));line=trim(line);if(line.empty())continue;
float r=0,g=0,b=0;
auto starts=[&](std::string_view prefix){return line.substr(0,prefix.size())==prefix;};
if(starts("LUT_3D_SIZE")) {
auto v=trim(line.substr(11));int n=0;auto result=std::from_chars(v.data(),v.data()+v.size(),n);
if(result.ec!=std::errc{}||!trim(v.substr(result.ptr-v.data())).empty()||foundSize||n<2||n>128)return DYLUTFail(error,@"LUT 尺寸应为 2–128,且只能声明一次");
size=n;foundSize=YES;data.reserve(size*size*size*4);
} else if(starts("DOMAIN_MIN")||starts("DOMAIN_MAX")) {
auto v=line.substr(10);if(!number(v,r)||!number(v,g)||!number(v,b)||!trim(v).empty())return DYLUTFail(error,@"LUT DOMAIN 范围无效");
float *domain=starts("DOMAIN_MIN")?domainMin:domainMax;domain[0]=r;domain[1]=g;domain[2]=b;
} else if(starts("TITLE")||starts("LUT_3D_INPUT_RANGE"))continue;
else if(starts("LUT_1D_SIZE"))return DYLUTFail(error,@"请选择三维 .cube LUT");
else {
auto v=line;float rgb[3]={0,0,0};bool valid=true;
for(int c=0;c<3;c++) {
auto token=trim(v);
if(!number(v,rgb[c])) {
// Custom LUT compatibility: retain the numeric prefix,
// zero unread channels, and keep this row's table position.
// Never search annotations for digits or skip a table row.
valid=c>0&&DYLUTTextNote(token,numericLocale);v={};break;
}
if(!std::isfinite(rgb[c])||(!v.empty()&&trim(v).size()==v.size())){valid=false;break;}
}
auto tail=trim(v);
if(!valid||(!tail.empty()&&!DYLUTTextNote(tail,numericLocale)))return DYLUTFail(error,[NSString stringWithFormat:@"LUT 第 %lu 行含无效数字或多余内容",(unsigned long)rows]);
r=rgb[0];g=rgb[1];b=rgb[2];
data.insert(data.end(),{r,g,b,1});if(data.size()>128*128*128*4)return DYLUTFail(error,@"LUT 数据过多");
}
}
if(size<2||data.size()!=size*size*size*4)return DYLUTFail(error,@"LUT 数据数量与尺寸不符");
bool resample=false;
for(int c=0;c<3;c++) {
if(!std::isfinite(domainMin[c])||!std::isfinite(domainMax[c])||domainMax[c]<=domainMin[c])return DYLUTFail(error,@"LUT DOMAIN 范围无效");
resample|=domainMin[c]!=0||domainMax[c]!=1;
}
if(resample) {
std::vector<float> original=data;
for(NSUInteger z=0;z<size;z++)for(NSUInteger y=0;y<size;y++)for(NSUInteger x=0;x<size;x++) {
if(x==0&&DYLUTCancelled(progress,error))return NO;
float rgb[3]={(float(x)/(size-1)-domainMin[0])/(domainMax[0]-domainMin[0]),
(float(y)/(size-1)-domainMin[1])/(domainMax[1]-domainMin[1]),
(float(z)/(size-1)-domainMin[2])/(domainMax[2]-domainMin[2])};
float sample[3];DYLUTSample(original,size,rgb,sample);
size_t dest=((z*size+y)*size+x)*4;for(int c=0;c<3;c++)data[dest+c]=sample[c];
}
}
return YES;
}
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 nil;
NSString *key=[NSString stringWithFormat:@"%@|%.9f|%@|%@",path.stringByStandardizingPath,[a[NSFileModificationDate]timeIntervalSinceReferenceDate],a[NSFileSize],a[NSFileSystemFileNumber]];
DYLUTPreparedTable *cached=[DYLUTTableCache()objectForKey:key];
if(cached)return cached;
std::vector<float> parsed;NSUInteger n=0;
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)];
return table;
}
static BOOL DYLUTReadCancellable(NSString *path,std::vector<float>& 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<float>& data,NSUInteger& size,NSError **error) {
return DYLUTReadCancellable(path,data,size,nil,error);
}
NSProgress *DYLUTPrepareAsync(NSString *path,void (^completion)(NSError *)) {
static dispatch_queue_t queue;static dispatch_once_t once;
dispatch_once(&once,^{queue=dispatch_queue_create("com.dayu.color.lut-selection",DISPATCH_QUEUE_SERIAL);dispatch_set_target_queue(queue,dispatch_get_global_queue(QOS_CLASS_USER_INITIATED,0));});
NSProgress *progress=[NSProgress discreteProgressWithTotalUnitCount:1];progress.localizedDescription=@"正在载入 LUT…";
dispatch_async(queue,^{@autoreleasepool{
NSError *error=nil;std::vector<float> values;NSUInteger n=0;
DYLUTReadCancellable(path,values,n,progress,&error);DYLUTCancelled(progress,&error);progress.completedUnitCount=1;
dispatch_async(dispatch_get_main_queue(),^{NSError *result=error;DYLUTCancelled(progress,&result);if(completion)completion(result);});
}});return progress;
}
NSData *DYLUTTransformRGBA(NSData *source,NSUInteger width,NSUInteger height,NSString *path,NSError **error) {
if(!width||!height||width>8192||height>8192||width*height>8192*8192||source.length!=width*height*16) {
DYLUTFail(error,@"缩略图源必须是有效的 float RGBA 图像");return nil;
}
std::vector<float> table;NSUInteger n=0;
if(path.length&&!DYLUTReadCube(path,table,n,error))return nil;
NSMutableData *result=[NSMutableData dataWithLength:source.length];
const float *input=(const float *)source.bytes;float *output=(float *)result.mutableBytes;
for(NSUInteger i=0;i<width*height;i++) {
const float *p=input+i*4;float *q=output+i*4;
if(!std::isfinite(p[0])||!std::isfinite(p[1])||!std::isfinite(p[2])||!std::isfinite(p[3])||p[3]<=0)continue;
if(n)DYLUTSample(table,n,p,q);else for(int c=0;c<3;c++)q[c]=p[c];
q[3]=std::min(1.f,std::max(0.f,p[3]));
}
return result;
}
static NSData *DYLUTFallback(void) {
static NSData *chart;static dispatch_once_t once;
dispatch_once(&once,^{
NSMutableData *data=[NSMutableData dataWithLength:320*180*16];float *p=(float *)data.mutableBytes;
const float swatches[][3]={{.74,.43,.33},{.49,.31,.25},{.95,.80,.67},{.82,.71,.51},{.16,.51,.75},{.24,.67,.35},{.94,.22,.18},{.14,.18,.33}};
for(NSUInteger y=0;y<180;y++)for(NSUInteger x=0;x<320;x++) {
float t=float(x)/319;float *q=p+(y*320+x)*4;
if(y<45)q[0]=q[1]=q[2]=t;
else if(y<90){q[0]=t;q[1]=1-t;q[2]=.31;}
else if(y<135){for(int c=0;c<3;c++)q[c]=swatches[std::min((NSUInteger)7,x*8/320)][c];}
else{q[0]=t;q[1]=t*t;q[2]=sqrtf(t);}
q[3]=1;
}
chart=[data copy];
});return chart;
}
static inline uint8_t DYLUTPreviewByte(float value) {
return (uint8_t)lroundf(std::max(0.f,std::min(1.f,value))*255);
}
NSImage *DYLUTThumbnail(NSString *path,NSData *source,NSUInteger sourceWidth,NSUInteger sourceHeight,NSSize outputSize,NSError **error) {
if(!std::isfinite(outputSize.width)||!std::isfinite(outputSize.height)||outputSize.width<1||outputSize.height<1||outputSize.width>2048||outputSize.height>2048) {
DYLUTFail(error,@"缩略图尺寸无效");return nil;
}
if(!source){source=DYLUTFallback();sourceWidth=320;sourceHeight=180;}
NSData *transformed=DYLUTTransformRGBA(source,sourceWidth,sourceHeight,path,error);if(!transformed)return nil;
NSUInteger width=(NSUInteger)llround(outputSize.width),height=(NSUInteger)llround(outputSize.height);
NSBitmapImageRep *bitmap=[[[NSBitmapImageRep alloc]initWithBitmapDataPlanes:NULL pixelsWide:width pixelsHigh:height
bitsPerSample:8 samplesPerPixel:4 hasAlpha:YES isPlanar:NO colorSpaceName:NSDeviceRGBColorSpace
bitmapFormat:NSBitmapFormatAlphaNonpremultiplied bytesPerRow:width*4 bitsPerPixel:32]autorelease];
if(!bitmap){DYLUTFail(error,@"无法分配缩略图位图");return nil;}
const float *p=(const float *)transformed.bytes;uint8_t *q=bitmap.bitmapData;
if(width==sourceWidth&&height==sourceHeight){
for(NSUInteger i=0;i<width*height*4;i++)q[i]=DYLUTPreviewByte(p[i]);
}else for(NSUInteger y=0;y<height;y++)for(NSUInteger x=0;x<width;x++) {
// Center-aligned bilinear scaling, independent of NSGraphicsContext.
float fx=(float(x)+.5f)*sourceWidth/width-.5f,fy=(float(y)+.5f)*sourceHeight/height-.5f;
fx=std::max(0.f,std::min(float(sourceWidth-1),fx));fy=std::max(0.f,std::min(float(sourceHeight-1),fy));
NSUInteger x0=(NSUInteger)fx,y0=(NSUInteger)fy,x1=std::min(sourceWidth-1,x0+1),y1=std::min(sourceHeight-1,y0+1);
float tx=fx-x0,ty=fy-y0;
for(int c=0;c<4;c++) {
float v=(p[(y0*sourceWidth+x0)*4+c]*(1-tx)+p[(y0*sourceWidth+x1)*4+c]*tx)*(1-ty)
+(p[(y1*sourceWidth+x0)*4+c]*(1-tx)+p[(y1*sourceWidth+x1)*4+c]*tx)*ty;
q[(y*width+x)*4+c]=DYLUTPreviewByte(v);
}
}
NSImage *image=[[[NSImage alloc]initWithSize:NSMakeSize(width,height)]autorelease];[image addRepresentation:bitmap];return image;
}
static NSString *DYLUTRelativeFolder(NSString *path,NSString *root) {
NSString *parent=path.stringByDeletingLastPathComponent;
if([parent isEqual:root])return @"";
NSString *prefix=[root stringByAppendingString:@"/"];
return [parent hasPrefix:prefix]?[parent substringFromIndex:prefix.length]:@"";
}
static NSDictionary *DYLUTEntry(NSURL *url,NSURL *root) {
NSString *path=url.path,*base=root.path;
NSString *relative=[path hasPrefix:[base stringByAppendingString:@"/"]]?[path substringFromIndex:base.length+1]:path.lastPathComponent;
return @{@"name":path.lastPathComponent.stringByDeletingPathExtension,@"path":path,
@"relativeFolder":DYLUTRelativeFolder(path,base),@"relativePath":relative};
}
static BOOL DYLUTOrdinaryURL(NSURL *url,BOOL *directory,NSError **error) {
NSNumber *isDirectory=nil,*isRegular=nil,*isLink=nil;
if(![url getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:error]||
![url getResourceValue:&isRegular forKey:NSURLIsRegularFileKey error:error]||
![url getResourceValue:&isLink forKey:NSURLIsSymbolicLinkKey error:error])return NO;
if(isLink.boolValue||(!isDirectory.boolValue&&!isRegular.boolValue))return DYLUTFail(error,@"不导入符号链接或特殊文件");
if(directory)*directory=isDirectory.boolValue;return YES;
}
static BOOL DYLUTEnsureDirectory(NSURL *directory,NSURL *root,NSError **error) {
NSString *prefix=[root.path stringByAppendingString:@"/"];
if(![directory.path isEqual:root.path]&&![directory.path hasPrefix:prefix])return DYLUTFail(error,@"LUT 目标路径超出目录边界");
NSFileManager *fm=NSFileManager.defaultManager;
if(![fm fileExistsAtPath:root.path]&&![fm createDirectoryAtURL:root withIntermediateDirectories:YES attributes:nil error:error])return NO;
NSDictionary *attributes=[fm attributesOfItemAtPath:root.path error:error];
if(![attributes[NSFileType]isEqual:NSFileTypeDirectory])return DYLUTFail(error,@"LUT 库根目录不是普通文件夹");
NSString *relative=[directory.path isEqual:root.path]?@"":[directory.path substringFromIndex:prefix.length];
NSURL *current=root;
for(NSString *component in relative.pathComponents) {
if(!component.length)continue;
current=[current URLByAppendingPathComponent:component isDirectory:YES];
NSDictionary *existing=[fm attributesOfItemAtPath:current.path error:NULL];
if(existing) {
if(![existing[NSFileType]isEqual:NSFileTypeDirectory])return DYLUTFail(error,@"LUT 目标文件夹含符号链接或非目录项");
} else if(![fm createDirectoryAtURL:current withIntermediateDirectories:NO attributes:nil error:error])return NO;
}
return YES;
}
@interface DYLUTLibrary () {
NSURL *_rootURL;
NSArray *_entries,*_folders;
NSMutableSet *_favoritePaths;
NSObject *_fileLock;
dispatch_queue_t _fileQueue;
}
@end
@implementation DYLUTLibrary
+ (NSURL *)defaultRootURL {return [NSURL fileURLWithPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Movies/大鱼调色LUT/look LUTs"] isDirectory:YES];}
- (instancetype)init {return [self initWithRootURL:self.class.defaultRootURL];}
- (instancetype)initWithRootURL:(NSURL *)rootURL {
if(!rootURL.isFileURL||!rootURL.path.length){[self release];return nil;}
if((self=[super init])) {
_fileLock=[NSObject new];_fileQueue=dispatch_queue_create("com.dayu.color.lut-files",DISPATCH_QUEUE_SERIAL);dispatch_set_target_queue(_fileQueue,dispatch_get_global_queue(QOS_CLASS_UTILITY,0));
_rootURL=[DYLUTCanonicalURL(rootURL)copy];_entries=[@[]copy];_folders=[@[@""]copy];_favoritePaths=[NSMutableSet new];
NSDictionary *saved=[NSDictionary dictionaryWithContentsOfURL:[_rootURL URLByAppendingPathComponent:@".favorites.plist"]];
NSArray *relativePaths=[saved[@"relativePaths"]isKindOfClass:NSArray.class]?saved[@"relativePaths"]:@[];
for(NSString *path in relativePaths)if([path isKindOfClass:NSString.class]&&![path isAbsolutePath]&&![path.pathComponents containsObject:@".."]) [_favoritePaths addObject:[_rootURL.path stringByAppendingPathComponent:path]];
}return self;
}
- (void)dealloc {[_rootURL release];[_entries release];[_folders release];[_favoritePaths release];[_fileLock release];dispatch_release(_fileQueue);[super dealloc];}
- (NSURL *)rootURL {return [[_rootURL copy]autorelease];}
- (NSArray *)entries {@synchronized(self){return [[_entries copy]autorelease];}}
- (NSArray *)folders {@synchronized(self){return [[_folders copy]autorelease];}}
- (NSSet *)favoritePaths {@synchronized(self){return [[_favoritePaths copy]autorelease];}}
- (NSString *)recentPreferenceKey {return [@"com.dayu.color.lookLUTPreview.recentPaths|" stringByAppendingString:_rootURL.path];}
- (NSArray *)recentPaths {
id saved=[[NSUserDefaults standardUserDefaults]objectForKey:[self recentPreferenceKey]];
NSMutableArray *paths=[NSMutableArray array];
if([saved isKindOfClass:NSArray.class])for(id path in saved){
if([path isKindOfClass:NSString.class]&&[path isAbsolutePath]&&[[path pathExtension]caseInsensitiveCompare:@"cube"]==NSOrderedSame&&![paths containsObject:path])[paths addObject:path];
if(paths.count==40)break;
}
return [[paths copy]autorelease];
}
- (NSArray *)recentEntries {return [self recentEntriesForPaths:self.recentPaths];}
- (NSArray *)recentEntriesForPaths:(NSArray *)paths {
NSMutableDictionary *known=[NSMutableDictionary dictionary];for(NSDictionary *entry in self.entries)known[entry[@"path"]]=entry;
NSMutableArray *entries=[NSMutableArray array];for(NSString *path in paths){
NSDictionary *entry=known[path];
if(!entry)entry=@{@"name":path.lastPathComponent.stringByDeletingPathExtension,@"path":path,@"relativePath":path,@"relativeFolder":@""};
[entries addObject:entry];
}
return [[entries copy]autorelease];
}
- (void)recordUsedPath:(NSString *)path {
if(![path isKindOfClass:NSString.class]||!path.isAbsolutePath||[path.pathExtension caseInsensitiveCompare:@"cube"]!=NSOrderedSame)return;
@synchronized(NSUserDefaults.class){
NSArray *saved=self.recentPaths;NSMutableArray *next=[[saved mutableCopy]autorelease];[next removeObject:path];[next insertObject:path atIndex:0];
if(next.count>40)[next removeObjectsInRange:NSMakeRange(40,next.count-40)];
if(![next isEqual:saved])[[NSUserDefaults standardUserDefaults]setObject:next forKey:[self recentPreferenceKey]];
}
}
- (BOOL)reload:(NSError **)error {return [self reloadProgress:nil error:error];}
- (BOOL)reloadProgress:(NSProgress *)progress error:(NSError **)error {@synchronized(_fileLock){
BOOL isDirectory=NO;NSFileManager *fm=NSFileManager.defaultManager;
if(DYLUTCancelled(progress,error))return NO;
if(![fm fileExistsAtPath:_rootURL.path isDirectory:&isDirectory]){@synchronized(self){[_entries release];_entries=[@[]copy];[_folders release];_folders=[@[@""]copy];}return YES;}
if(!isDirectory||!DYLUTOrdinaryURL(_rootURL,NULL,error))return DYLUTFail(error,@"LUT 库目录无效");
NSMutableArray *entries=[NSMutableArray array];NSMutableSet *folders=[NSMutableSet setWithObject:@""];
__block NSError *scanError=nil;
NSDirectoryEnumerator *enumerator=[fm enumeratorAtURL:_rootURL includingPropertiesForKeys:@[NSURLIsDirectoryKey,NSURLIsRegularFileKey,NSURLIsSymbolicLinkKey] options:NSDirectoryEnumerationSkipsHiddenFiles|NSDirectoryEnumerationSkipsPackageDescendants errorHandler:^BOOL(NSURL *url,NSError *e){(void)url;scanError=e;return NO;}];
for(NSURL *url in enumerator) {
if(DYLUTCancelled(progress,error))return NO;
progress.completedUnitCount++;
NSNumber *link=nil;[url getResourceValue:&link forKey:NSURLIsSymbolicLinkKey error:NULL];
if(link.boolValue){[enumerator skipDescendants];continue;}
BOOL directory=NO;if(!DYLUTOrdinaryURL(url,&directory,NULL))continue;
if(![url.path hasPrefix:[_rootURL.path stringByAppendingString:@"/"]])return DYLUTFail(error,@"LUT 库文件路径超出目录边界");
if(directory){NSString *relative=[url.path substringFromIndex:_rootURL.path.length+1];[folders addObject:relative];continue;}
if([url.pathExtension.lowercaseString isEqual:@"cube"])[entries addObject:DYLUTEntry(url,_rootURL)];
if(entries.count>10000)return DYLUTFail(error,@"LUT 库超过 10,000 个文件限制");
}
if(scanError){if(error)*error=scanError;return NO;}
[entries sortUsingComparator:^NSComparisonResult(NSDictionary *a,NSDictionary *b){return [a[@"relativePath"]localizedStandardCompare:b[@"relativePath"]];}];
if(DYLUTCancelled(progress,error))return NO;
NSArray *sortedFolders=[folders.allObjects sortedArrayUsingSelector:@selector(localizedStandardCompare:)];
@synchronized(self){[_entries release];_entries=[entries copy];[_folders release];_folders=[sortedFolders copy];}return YES;
}}
- (NSArray *)importURLs:(NSArray<NSURL *> *)urls error:(NSError **)error {return [self importURLs:urls progress:nil error:error];}
- (NSArray *)importURLs:(NSArray<NSURL *> *)urls progress:(NSProgress *)progress error:(NSError **)error {@synchronized(_fileLock){
NSFileManager *fm=NSFileManager.defaultManager;NSMutableArray *plans=[NSMutableArray array];
NSString *root=_rootURL.path;
for(NSURL *sourceURL in urls) {
if(DYLUTCancelled(progress,error))return nil;
if(!sourceURL.isFileURL){DYLUTFail(error,@"只能导入本机 LUT 文件");return nil;}
NSURL *source=[sourceURL URLByStandardizingPath];BOOL directory=NO;
if(!DYLUTOrdinaryURL(source,&directory,error))return nil;
// NSDirectoryEnumerator canonicalizes /var to /private/var on macOS.
// Canonicalize both sides before calculating a relative path.
source=DYLUTCanonicalURL(source);
if([source.path isEqual:root]||[source.path hasPrefix:[root stringByAppendingString:@"/"]]){DYLUTFail(error,@"此 LUT 已位于浏览库中");return nil;}
if(!directory) {
if(![source.pathExtension.lowercaseString isEqual:@"cube"]){DYLUTFail(error,@"请选择 .cube 文件或包含它们的文件夹");return nil;}
[plans addObject:@{@"source":source,@"relative":source.lastPathComponent}];
} else {
__block NSError *scanError=nil;
NSDirectoryEnumerator *enumerator=[fm enumeratorAtURL:source includingPropertiesForKeys:@[NSURLIsSymbolicLinkKey,NSURLIsDirectoryKey,NSURLIsRegularFileKey] options:NSDirectoryEnumerationSkipsHiddenFiles|NSDirectoryEnumerationSkipsPackageDescendants errorHandler:^BOOL(NSURL *url,NSError *e){(void)url;scanError=e;return NO;}];
for(NSURL *file in enumerator) {
if(DYLUTCancelled(progress,error))return nil;
NSNumber *link=nil;[file getResourceValue:&link forKey:NSURLIsSymbolicLinkKey error:NULL];
if(link.boolValue){[enumerator skipDescendants];continue;}
BOOL subdirectory=NO;if(!DYLUTOrdinaryURL(file,&subdirectory,NULL)||subdirectory||![file.pathExtension.lowercaseString isEqual:@"cube"])continue;
if(![file.path hasPrefix:[source.path stringByAppendingString:@"/"]]){DYLUTFail(error,@"导入文件路径超出目录边界");return nil;}
NSString *relative=[source.lastPathComponent stringByAppendingPathComponent:[file.path substringFromIndex:source.path.length+1]];
[plans addObject:@{@"source":file,@"relative":relative}];
if(plans.count>10000){DYLUTFail(error,@"单次导入超过 10,000 个 LUT 限制");return nil;}
}
if(scanError){if(error)*error=scanError;return nil;}
}
}
if(!plans.count){DYLUTFail(error,@"没有找到可导入的 .cube 文件");return nil;}
// Validate every source before writing the library, preserving existing files.
progress.totalUnitCount=plans.count*2;progress.completedUnitCount=0;
for(NSDictionary *plan in plans){
NSError *itemError=nil;BOOL valid=NO;
@autoreleasepool{
progress.localizedDescription=[NSString stringWithFormat:@"正在校验 %lld/%lu",progress.completedUnitCount+1,(unsigned long)plans.count];progress.localizedAdditionalDescription=[plan[@"source"]lastPathComponent];
std::vector<float> values;NSUInteger n=0;valid=!DYLUTCancelled(progress,&itemError)&&DYLUTReadCancellable([plan[@"source"]path],values,n,progress,&itemError);if(!valid)itemError=DYLUTFileError(itemError,plan[@"source"]);[itemError retain];
}
if(!valid){if(error)*error=[itemError autorelease];else[itemError release];return nil;}[itemError release];progress.completedUnitCount++;
}
if(!DYLUTEnsureDirectory(_rootURL,_rootURL,error))return nil;
NSMutableArray *created=[NSMutableArray array],*imported=[NSMutableArray array];BOOL success=YES;
for(NSDictionary *plan in plans){
NSError *itemError=nil;BOOL copied=NO;
@autoreleasepool{
copied=[&]()->BOOL{
if(DYLUTCancelled(progress,&itemError))return NO;
progress.localizedDescription=[NSString stringWithFormat:@"正在导入 %lu/%lu",(unsigned long)imported.count+1,(unsigned long)plans.count];progress.localizedAdditionalDescription=[plan[@"source"]lastPathComponent];
NSURL *destination=[_rootURL URLByAppendingPathComponent:plan[@"relative"]];
if(!DYLUTEnsureDirectory(destination.URLByDeletingLastPathComponent,_rootURL,&itemError))return NO;
NSString *stem=destination.path.stringByDeletingPathExtension,*extension=destination.pathExtension;NSUInteger suffix=1;
while([fm fileExistsAtPath:destination.path])destination=[NSURL fileURLWithPath:[NSString stringWithFormat:@"%@ %lu.%@",stem,(unsigned long)++suffix,extension]];
if(![fm copyItemAtURL:plan[@"source"] toURL:destination error:&itemError])return NO;[created addObject:destination];
std::vector<float> values;NSUInteger n=0;if(!DYLUTReadCancellable(destination.path,values,n,progress,&itemError))return NO;
[imported addObject:DYLUTEntry(destination,_rootURL)];return YES;
}();if(!copied)itemError=DYLUTFileError(itemError,plan[@"source"]);[itemError retain];
}
if(!copied){if(error)*error=[itemError autorelease];else[itemError release];success=NO;break;}[itemError release];progress.completedUnitCount++;
}
if(success)success=!DYLUTCancelled(progress,error)&&[self reload:error];
if(!success){for(NSURL *url in created)[fm removeItemAtURL:url error:NULL];return nil;}
return imported;
}}
- (NSProgress *)reloadAsync:(void (^)(NSError *))completion {
NSProgress *progress=[NSProgress discreteProgressWithTotalUnitCount:-1];progress.localizedDescription=@"正在扫描 LUT 文件夹…";
dispatch_async(_fileQueue,^{@autoreleasepool{NSError *error=nil;[self reloadProgress:progress error:&error];progress.totalUnitCount=MAX(1,progress.completedUnitCount);progress.completedUnitCount=progress.totalUnitCount;dispatch_async(dispatch_get_main_queue(),^{if(completion)completion(error);});}});return progress;
}
- (NSProgress *)importURLsAsync:(NSArray<NSURL *> *)urls completion:(void (^)(NSArray<NSDictionary *> *,NSError *))completion {
NSProgress *progress=[NSProgress discreteProgressWithTotalUnitCount:-1];progress.localizedDescription=@"正在查找 LUT 文件…";NSArray *sources=[[urls copy]autorelease];
dispatch_async(_fileQueue,^{@autoreleasepool{NSError *error=nil;NSArray *imported=[self importURLs:sources progress:progress error:&error];dispatch_async(dispatch_get_main_queue(),^{if(completion)completion(imported,error);});}});return progress;
}
- (BOOL)isFavoritePath:(NSString *)path {@synchronized(self){return [_favoritePaths containsObject:path];}}
- (BOOL)setFavorite:(BOOL)favorite forPath:(NSString *)path error:(NSError **)error {@synchronized(self){
NSString *prefix=[_rootURL.path stringByAppendingString:@"/"];
if(![path hasPrefix:prefix]||[path.pathComponents containsObject:@".."])return DYLUTFail(error,@"只能收藏浏览库中的 LUT");
NSMutableSet *next=[[_favoritePaths mutableCopy]autorelease];if(favorite)[next addObject:path];else[next removeObject:path];
NSMutableArray *relative=[NSMutableArray array];for(NSString *p in next)[relative addObject:[p substringFromIndex:prefix.length]];
[relative sortUsingSelector:@selector(localizedStandardCompare:)];
if(!DYLUTEnsureDirectory(_rootURL,_rootURL,error))return NO;
NSData *data=[NSPropertyListSerialization dataWithPropertyList:@{@"relativePaths":relative} format:NSPropertyListXMLFormat_v1_0 options:0 error:error];
if(!data||![data writeToURL:[_rootURL URLByAppendingPathComponent:@".favorites.plist"] options:NSDataWritingAtomic error:error])return NO;
[_favoritePaths release];_favoritePaths=[next mutableCopy];return YES;
}}
@end