WIP: add pinned public CMS runtime and versioned color state; renderer integration pending

这个提交包含在:
mac 于 2026-11-03 12:37:59 +08:00 提交
1 父节点 5b8ef04f7e
当前提交 70a50ab445
42 个文件已更改
+1317 -9

没有与搜索条件相匹配的文件

@@ -0,0 +1,221 @@
#include "../Core/DYColorManagement.hpp"
#include <OpenColorIO/OpenColorIO.h>
#include <array>
#include <algorithm>
#include <stdexcept>
namespace O = OCIO_NAMESPACE;
namespace dycm {
namespace {
constexpr SpaceInfo spaceTable[] = {
{Space::ACES2065,"ACES2065-1 / AP0 线性","ACES2065-1"},
{Space::ACEScg,"ACEScg / AP1 线性","ACEScg"},
{Space::ACEScc,"ACEScc","ACEScc"}, {Space::ACEScct,"ACEScct","ACEScct"},
{Space::Linear709,"Rec.709 线性","Linear Rec.709 (sRGB)"},
{Space::Gamma22_709,"Rec.709 Gamma 2.2","Gamma 2.2 Encoded Rec.709"},
{Space::SRGB,"sRGB","sRGB Encoded Rec.709 (sRGB)"},
{Space::Linear2020,"Rec.2020 线性","Linear Rec.2020"},
{Space::AppleLog,"Apple Log","Apple Log"},
{Space::ARRI_LogC3,"ARRI LogC3 / EI800","ARRI LogC3 (EI800)"},
{Space::ARRI_LogC4,"ARRI LogC4","ARRI LogC4"},
{Space::BMD_Gen5,"Blackmagic Film Gen 5 / Wide Gamut","BMDFilm WideGamut Gen5"},
{Space::CanonLog2,"Canon Log2 / Cinema Gamut D55","CanonLog2 CinemaGamut D55"},
{Space::CanonLog3,"Canon Log3 / Cinema Gamut D55","CanonLog3 CinemaGamut D55"},
{Space::PanasonicVLog,"Panasonic V-Log / V-Gamut","V-Log V-Gamut"},
{Space::REDLog3G10,"RED Log3G10 / REDWideGamutRGB","Log3G10 REDWideGamutRGB"},
{Space::SonySLog3,"Sony S-Log3 / S-Gamut3","S-Log3 S-Gamut3"},
{Space::SonySLog3Cine,"Sony S-Log3 / S-Gamut3.Cine","S-Log3 S-Gamut3.Cine"},
{Space::SonyVeniceSLog3,"Sony Venice S-Log3 / S-Gamut3","S-Log3 Venice S-Gamut3"},
{Space::SonyVeniceSLog3Cine,"Sony Venice S-Log3 / S-Gamut3.Cine","S-Log3 Venice S-Gamut3.Cine"},
{Space::DaVinciIntermediate,"DaVinci Intermediate / Wide Gamut","DaVinci Intermediate WideGamut"}
};
constexpr OutputInfo outputTable[] = {
{Output::Rec709_100,"Rec.709 / 100 nit","Rec.1886 Rec.709 - Display","ACES 1.0 - SDR Video"},
{Output::SRGB_100,"sRGB / 100 nit","sRGB - Display","ACES 1.0 - SDR Video"},
{Output::DisplayP3_100,"Display P3 / 100 nit","Display P3 - Display","ACES 1.0 - SDR Video"},
{Output::Rec709D60_100,"Rec.709 / D60 模拟 / 100 nit","Rec.1886 Rec.709 - Display","ACES 1.0 - SDR Video (D60 sim on D65)"},
{Output::Rec2020_100,"Rec.2020 SDR / 100 nit","Rec.1886 Rec.2020 - Display","ACES 1.0 - SDR Video"},
{Output::Rec2020PQ_1000,"Rec.2020 PQ / 1000 nit","Rec.2100-PQ - Display","ACES 1.1 - HDR Video (1000 nits & Rec.2020 lim)"},
{Output::Rec2020HLG_1000,"Rec.2020 HLG / 1000 nit","Rec.2100-HLG - Display","ACES 1.1 - HDR Video (1000 nits & Rec.2020 lim)"},
{Output::P3D60_48,"P3 D60 / 48 nit","P3-D60 - Display","ACES 1.0 - SDR Cinema"},
{Output::P3DCI_48,"P3 DCI / 48 nit","P3-DCI - Display","ACES 1.0 - SDR Cinema (D60 sim on DCI)"},
{Output::P3D65_48,"P3 D65 / 48 nit","P3-D65 - Display","ACES 1.0 - SDR Cinema"}
};
O::ConstConfigRcPtr config() {
static const auto value=[] {auto c=O::Config::CreateFromBuiltinConfig(Config);c->validate();return c;}();
return value;
}
std::string prefix(){return std::string("dayu-cms:")+std::to_string(Version)+":"+Engine+":"+Config+":";}
}
std::span<const SpaceInfo> spaces(){return spaceTable;}
std::span<const OutputInfo> outputs(){return outputTable;}
const SpaceInfo &spaceInfo(Space id){for(auto &s:spaceTable)if(s.id==id)return s;throw std::invalid_argument("Unknown color space ID");}
const OutputInfo &outputInfo(Output id){for(auto &s:outputTable)if(s.id==id)return s;throw std::invalid_argument("Unknown output transform ID");}
void Settings::validate() const {
if(version!=Version)throw std::invalid_argument("Unsupported color management version");
spaceInfo(input);spaceInfo(working);outputInfo(output);
if(working!=Space::ACEScc&&working!=Space::ACEScct&&working!=Space::ACEScg)
throw std::invalid_argument("Unsupported ACES grading space");
}
std::string Settings::key() const {
validate();return prefix()+std::to_string(enabled)+":"+std::to_string(unsigned(input))+":"+
std::to_string(unsigned(working))+":"+std::to_string(unsigned(output))+":"+std::to_string(referenceGamutCompression);
}
struct Transform::Impl {
std::string key;
std::vector<O::ConstProcessorRcPtr> processors;
std::vector<O::ConstCPUProcessorRcPtr> cpus;
bool identity=true;
bool decodeCC=false,encodeCC=false;
Impl(std::string k,std::vector<O::ConstProcessorRcPtr> steps={},bool decode=false,bool encode=false):key(std::move(k)),processors(std::move(steps)),decodeCC(decode),encodeCC(encode) {
identity=!decode&&!encode;
for(auto &p:processors){auto cpu=p->getOptimizedCPUProcessor(O::OPTIMIZATION_LOSSLESS);identity=identity&&cpu->isNoOp();cpus.push_back(cpu);}
}
};
// Academy ACEScc analytic encoding. The pinned OCIO config's cc entry uses a
// 4096-sample LUT; use AP1 linear at that boundary to avoid LUT approximation.
static float encodeCC(float x){return x<=0?float((-16.+9.72)/17.52):float((std::log2(x<1.f/32768?1./65536+double(x)*.5:double(x))+9.72)/17.52);}
static float decodeCC(float x){return x<float((9.72-15.)/17.52)?float((std::exp2(double(x)*17.52-9.72)-1./65536)*2):float(std::min(std::exp2(double(x)*17.52-9.72),65504.));}
Transform::Transform(std::shared_ptr<const Impl> value):impl(std::move(value)){}
Transform Transform::identity(){return Transform(std::make_shared<Impl>(prefix()+"identity"));}
Transform Transform::convert(Space from,Space to) {
auto &source=spaceInfo(from);auto &destination=spaceInfo(to);
if(from==to)return identity();
return Transform(std::make_shared<Impl>(prefix()+"space:"+std::to_string(unsigned(from))+":"+std::to_string(unsigned(to)),
std::vector<O::ConstProcessorRcPtr>{config()->getProcessor(from==Space::ACEScc?"ACEScg":source.ocioName,"ACEScg"),
config()->getProcessor("ACEScg",to==Space::ACEScc?"ACEScg":destination.ocioName)},from==Space::ACEScc,to==Space::ACEScc));
}
Transform Transform::display(Space from,Output to,bool gamutCompression) {
auto &source=spaceInfo(from);auto &destination=outputInfo(to);const char *sourceName=from==Space::ACEScc?"ACEScg":source.ocioName;
auto group=O::GroupTransform::Create();
if(gamutCompression){
auto look=O::LookTransform::Create();look->setSrc("ACEScg");look->setDst("ACEScg");
look->setLooks("ACES 1.3 Reference Gamut Compression");group->appendTransform(look);
}
auto view=O::DisplayViewTransform::Create();view->setSrc("ACEScg");view->setDisplay(destination.display);view->setView(destination.view);
group->appendTransform(view);
return Transform(std::make_shared<Impl>(prefix()+"display:"+std::to_string(unsigned(from))+":"+std::to_string(unsigned(to))+":"+std::to_string(gamutCompression),
std::vector<O::ConstProcessorRcPtr>{config()->getProcessor(sourceName,"ACEScg"),config()->getProcessor(group)},from==Space::ACEScc));
}
bool Transform::isIdentity() const{return impl->identity;}
const std::string &Transform::key() const{return impl->key;}
void Transform::apply(std::span<DYCompositeRGBA> pixels,Alpha alpha) const {
if(alpha!=Alpha::Straight&&alpha!=Alpha::Premultiplied)throw std::invalid_argument("Unknown alpha representation");
if(isIdentity()||pixels.empty())return;
std::array<DYCompositeRGBA,4096> scratch;
std::array<float,4096> originalAlpha;
for(size_t offset=0;offset<pixels.size();offset+=scratch.size()){
size_t count=std::min(scratch.size(),pixels.size()-offset);
for(size_t i=0;i<count;i++){
auto p=dyPMFinite(pixels[offset+i]);originalAlpha[i]=p.a;
if(alpha==Alpha::Premultiplied)p=dyPMUnpremultiply(p);
if(impl->decodeCC){p.r=decodeCC(p.r);p.g=decodeCC(p.g);p.b=decodeCC(p.b);}
p.a=1;scratch[i]=p;
}
O::PackedImageDesc image(scratch.data(),long(count),1,4);
for(auto &cpu:impl->cpus){cpu->apply(image);for(size_t i=0;i<count;i++)scratch[i]=dyPMFinite(scratch[i]);}
for(size_t i=0;i<count;i++){
auto p=dyPMFinite(scratch[i]);p.a=originalAlpha[i];
if(impl->encodeCC){p.r=encodeCC(p.r);p.g=encodeCC(p.g);p.b=encodeCC(p.b);}
pixels[offset+i]=alpha==Alpha::Premultiplied?dyPMPremultiply(p):p;
}
}
}
MetalProgram Transform::metalProgram() const {
if(isIdentity())return {"float4 dyOCIO(float4 p) { return p; }\n",{}};
MetalProgram program;auto &source=program.source;std::string calls;
for(size_t step=0;step<impl->processors.size();step++){
auto desc=O::GpuShaderDesc::CreateShaderDesc();desc->setLanguage(O::GPU_LANGUAGE_MSL_2_0);
std::string function="dyCMSBase"+std::to_string(step),prefix="dyCMS"+std::to_string(step)+"_";
desc->setFunctionName(function.c_str());desc->setResourcePrefix(prefix.c_str());
impl->processors[step]->getOptimizedGPUProcessor(O::OPTIMIZATION_LOSSLESS)->extractGpuShaderInfo(desc);
if(desc->getNumUniforms())throw std::runtime_error("Fixed CMS transform unexpectedly requires dynamic uniforms: "+key());
source+=desc->getShaderText();size_t firstTexture=program.textures.size();
// OCIO's generic shader blends camera-log branches arithmetically. In MSL,
// 0 * an overflowing inactive linear branch becomes NaN. Select the branch
// as the CPU does, without changing the active curve or clamping HDR.
const std::string branch="isAboveBreak * logSeg + ( float3(1., 1., 1.) - isAboveBreak ) * linSeg";
for(size_t pos=0;(pos=source.find(branch,pos))!=std::string::npos;){
const std::string replacement="select(linSeg, logSeg, isAboveBreak > float3(0.5))";
source.replace(pos,branch.size(),replacement);pos+=replacement.size();
}
for(const char *boundary:{"linear_break","log_break"})for(int component=0;component<3;component++){
auto c=std::to_string(component);
std::string match="(outColor.rgb["+c+"] > "+boundary+"["+c+"]) ? 1.0 : 0.0";
std::string replacement="(outColor.rgb["+c+"] < "+boundary+"["+c+"]) ? 0.0 : 1.0";
for(size_t pos=0;(pos=source.find(match,pos))!=std::string::npos;){source.replace(pos,match.size(),replacement);pos+=replacement.size();}
}
// The public MSL wrapper takes 3D textures/samplers first, then 1D/2D pairs.
auto copyTexture=[&](ShaderTexture t,const float *values,O::Interpolation interpolation){
uint64_t count=uint64_t(t.width)*t.height*t.depth*t.channels;
if(!values||!count||count>32*1024*1024||(interpolation!=O::INTERP_NEAREST&&interpolation!=O::INTERP_LINEAR&&interpolation!=O::INTERP_TETRAHEDRAL))
throw std::runtime_error("Unsupported CMS shader texture: "+key());
t.linear=interpolation==O::INTERP_LINEAR;t.values.assign(values,values+count);program.textures.push_back(std::move(t));
};
for(unsigned i=0;i<desc->getNum3DTextures();i++){
const char *name=nullptr,*sampler=nullptr;unsigned edge=0;O::Interpolation interpolation;const float *values=nullptr;
desc->get3DTexture(i,name,sampler,edge,interpolation);desc->get3DTextureValues(i,values);
if(edge>256)throw std::runtime_error("CMS 3D texture is too large");
copyTexture({3,edge,edge,edge,3,false,{}},values,interpolation);
}
for(unsigned i=0;i<desc->getNumTextures();i++){
const char *name=nullptr,*sampler=nullptr;unsigned width=0,height=0;O::GpuShaderDesc::TextureType channels;O::GpuShaderDesc::TextureDimensions dimensions;O::Interpolation interpolation;const float *values=nullptr;
desc->getTexture(i,name,sampler,width,height,channels,dimensions,interpolation);desc->getTextureValues(i,values);
if(width>16384||height>16384)throw std::runtime_error("CMS texture is too large");
unsigned dim=dimensions==O::GpuShaderDesc::TEXTURE_1D?1:2;
copyTexture({dim,width,height,1,channels==O::GpuShaderDesc::TEXTURE_RED_CHANNEL?1u:3u,false,{}},values,interpolation);
if(interpolation==O::INTERP_LINEAR){
// Hardware samplers quantize the interpolation fraction. Near the
// ACEScc toe this becomes measurable; interpolate fetched float
// texels explicitly using the same LUT values as the CPU.
std::string helper="dyCMSLookup"+std::to_string(program.textures.size()-1),text;
if(dim==1)text="float4 "+helper+"(texture1d<float> t,float uv){float q=clamp(uv*float(t.get_width())-0.5f,0.f,float(t.get_width()-1));uint a=uint(floor(q)),b=min(a+1,t.get_width()-1);return mix(t.read(a),t.read(b),q-float(a));}\n";
else text="float4 "+helper+"(texture2d<float> t,float2 uv){uint2 size=uint2(t.get_width(),t.get_height());float2 q=clamp(uv*float2(size)-0.5f,float2(0),float2(size-1));uint2 a=uint2(floor(q)),b=min(a+1,size-1);float2 f=q-float2(a);return mix(mix(t.read(a),t.read(uint2(b.x,a.y)),f.x),mix(t.read(uint2(a.x,b.y)),t.read(b),f.x),f.y);}\n";
std::string match=std::string(name)+".sample("+sampler+", ",replacement=helper+"("+name+", ";
for(size_t pos=0;(pos=source.find(match,pos))!=std::string::npos;){source.replace(pos,match.size(),replacement);pos+=replacement.size();}
source=text+source;
}
}
calls+="p="+function+"(";
for(size_t i=firstTexture;i<program.textures.size();i++){auto suffix=std::to_string(i);calls+="dyBound"+suffix+",dySampler"+suffix+",";}
calls+="p);p=select(float4(0),p,isfinite(p));\n";
}
source+="\nfloat dyCCEncode(float x) {return x<=0?((-16.f+9.72f)/17.52f):((log2(x<1.f/32768.f?1.f/65536.f+x*.5f:x)+9.72f)/17.52f);}\n";
source+="float dyCCDecode(float x) {return x<((9.72f-15.f)/17.52f)?((exp2(x*17.52f-9.72f)-1.f/65536.f)*2.f):min(exp2(x*17.52f-9.72f),65504.f);}\nfloat4 dyOCIO(";
for(size_t i=0;i<program.textures.size();i++){
auto suffix=std::to_string(i);source+="texture"+std::to_string(program.textures[i].dimensions)+"d<float> dyBound"+suffix+", sampler dySampler"+suffix+", ";
}
source+="float4 p) {\n";
if(impl->decodeCC)source+="p.rgb=float3(dyCCDecode(p.r),dyCCDecode(p.g),dyCCDecode(p.b));\n";
source+=calls;
if(impl->encodeCC)source+="p=select(float4(0),p,isfinite(p));p.rgb=float3(dyCCEncode(p.r),dyCCEncode(p.g),dyCCEncode(p.b));\n";
source+="return p;}\n";return program;
}
Plan Plan::compile(const Settings &s){
s.validate();return {s,s.enabled?Transform::convert(s.input,s.working):Transform::identity(),
s.enabled?Transform::display(s.working,s.output,s.referenceGamutCompression):Transform::identity()};
}
std::string Plan::key()const{return settings.key();}
namespace {
class CompiledFramePipeline final : public FramePipeline {
Plan plan;
Transform toLinear,fromLinear;
public:
explicit CompiledFramePipeline(const Settings&s):plan(Plan::compile(s)),
toLinear(Transform::convert(s.working,Space::ACEScg)),
fromLinear(Transform::convert(Space::ACEScg,s.working)){validate();}
void validate()const override {plan.settings.validate();if(!plan.settings.enabled)throw std::invalid_argument("A frame CMS pipeline must be enabled");}
const Settings&settings()const override{return plan.settings;}
const Transform&transform(FrameStage stage)const override{
switch(stage){case FrameStage::Input:return plan.input;case FrameStage::Output:return plan.output;
case FrameStage::ToLinear:return toLinear;case FrameStage::FromLinear:return fromLinear;
default:throw std::invalid_argument("Invalid frame CMS stage");}
}
bool isIdentity(FrameStage stage)const override{return transform(stage).isIdentity();}
void apply(FrameStage stage,std::span<DYCompositeRGBA>pixels,Alpha alpha)const override{transform(stage).apply(pixels,alpha);}
std::string key()const override{return plan.key();}
};
}
std::shared_ptr<const FramePipeline> compileFramePipeline(const Settings&s){
s.validate();return s.enabled?std::make_shared<const CompiledFramePipeline>(s):nullptr;
}
} // namespace dycm
@@ -0,0 +1,33 @@
#pragma once
#import <Foundation/Foundation.h>
#import <Metal/Metal.h>
#include "../Core/DYColorManagement.hpp"
// Own one immutable pipeline per transform/device. The caller commits and checks
// its frame command buffer, so CMS joins the existing frame transaction.
@interface DYColorManagementGPU : NSObject
@property(nonatomic,readonly,copy) NSString *transformKey;
@property(nonatomic,readonly) uint64_t retainedTextureBytes;
- (instancetype)initWithDevice:(id<MTLDevice>)device transform:(const dycm::Transform&)transform error:(NSError**)error;
- (instancetype)initWithDevice:(id<MTLDevice>)device transform:(const dycm::Transform&)transform
resourceBudget:(uint64_t)bytes error:(NSError**)error;
- (BOOL)encodeInput:(id<MTLTexture>)input output:(id<MTLTexture>)output
alpha:(dycm::Alpha)alpha commandBuffer:(id<MTLCommandBuffer>)command
workspaceBudget:(uint64_t)bytes error:(NSError**)error;
@end
struct DYColorManagementCacheStatistics {
NSUInteger entries=0;
uint64_t retainedTextureBytes=0, builds=0, hits=0, evictions=0;
};
// Immutable device/transform resources shared by independent frame requests.
// Limits bound cache ownership, not resources still leased by active frames.
// Every frame must also charge its leased tables to its own resource budget.
@interface DYColorManagementGPUCache : NSObject
+ (instancetype)sharedCache;
- (instancetype)initWithCountLimit:(NSUInteger)count textureByteLimit:(uint64_t)bytes;
- (DYColorManagementGPU*)pipelineWithDevice:(id<MTLDevice>)device
transform:(const dycm::Transform&)transform resourceBudget:(uint64_t)bytes error:(NSError**)error;
- (DYColorManagementCacheStatistics)statistics;
- (void)removeAllObjects;
@end
@@ -0,0 +1,130 @@
#import "DYColorManagementGPU.h"
#include <stdexcept>
namespace {
NSError *failure(NSString *text){return [NSError errorWithDomain:@"com.dayu.colorplate.cms" code:1 userInfo:@{NSLocalizedDescriptionKey:text}];}
}
@implementation DYColorManagementGPU {
id<MTLDevice> _device;
id<MTLComputePipelineState> _pipeline;
NSString *_transformKey;
NSArray *_textures,*_samplers;
uint64_t _lutBytes;
}
- (NSString*)transformKey{return _transformKey;}
- (uint64_t)retainedTextureBytes{return _lutBytes;}
- (instancetype)initWithDevice:(id<MTLDevice>)device transform:(const dycm::Transform&)transform error:(NSError**)error {
return [self initWithDevice:device transform:transform resourceBudget:128*1024*1024 error:error];
}
- (instancetype)initWithDevice:(id<MTLDevice>)device transform:(const dycm::Transform&)transform resourceBudget:(uint64_t)bytes error:(NSError**)error {
if(!(self=[super init]))return nil;
try {
if(!device)throw std::invalid_argument("色彩管理需要可用的显卡");
_device=device;_transformKey=[NSString stringWithUTF8String:transform.key().c_str()];
auto program=transform.metalProgram();NSMutableArray *textures=[NSMutableArray new],*samplers=[NSMutableArray new];
if(program.textures.size()>16)throw std::runtime_error("色彩管理查找表数量超过限制");
std::string source="#include <metal_stdlib>\nusing namespace metal;\n"+program.source;
source+="\nkernel void dyCMSFrame(texture2d<float,access::read> src [[texture(0)]], texture2d<float,access::write> dst [[texture(1)]], ";std::string arguments;
for(size_t i=0;i<program.textures.size();i++){
auto &t=program.textures[i];auto suffix=std::to_string(i);
source+="texture"+std::to_string(t.dimensions)+"d<float> dyBound"+suffix+" [[texture("+std::to_string(i+2)+")]], sampler dySampler"+suffix+" [[sampler("+suffix+")]], ";
arguments+="dyBound"+suffix+",dySampler"+suffix+",";
auto d=[MTLTextureDescriptor new];d.pixelFormat=MTLPixelFormatRGBA32Float;d.textureType=t.dimensions==3?MTLTextureType3D:(t.dimensions==1?MTLTextureType1D:MTLTextureType2D);d.width=t.width;d.height=t.height;d.depth=t.depth;d.storageMode=MTLStorageModeShared;d.usage=MTLTextureUsageShaderRead;
uint64_t limit=std::min(bytes,uint64_t(128)*1024*1024);
if(_lutBytes>limit||uint64_t(t.width)*t.height*t.depth*16>limit-_lutBytes)throw std::runtime_error("色彩管理查找表超过预算");
id<MTLTexture> texture=[device newTextureWithDescriptor:d];if(!texture)throw std::runtime_error("无法分配色彩查找表");_lutBytes+=texture.allocatedSize;if(_lutBytes>limit)throw std::runtime_error("色彩管理查找表超过预算");
std::vector<float> rgba(uint64_t(t.width)*t.height*t.depth*4,1);
for(size_t p=0;p<t.values.size()/t.channels;p++)for(unsigned c=0;c<3;c++)rgba[p*4+c]=t.values[p*t.channels+(t.channels==1?0:c)];
if(t.dimensions==3)[texture replaceRegion:MTLRegionMake3D(0,0,0,t.width,t.height,t.depth) mipmapLevel:0 slice:0 withBytes:rgba.data() bytesPerRow:t.width*16 bytesPerImage:t.width*t.height*16];
else [texture replaceRegion:MTLRegionMake2D(0,0,t.width,t.height) mipmapLevel:0 withBytes:rgba.data() bytesPerRow:t.dimensions==1?0:t.width*16];
MTLSamplerDescriptor *sd=[MTLSamplerDescriptor new];sd.minFilter=sd.magFilter=t.linear?MTLSamplerMinMagFilterLinear:MTLSamplerMinMagFilterNearest;sd.sAddressMode=sd.tAddressMode=sd.rAddressMode=MTLSamplerAddressModeClampToEdge;sd.normalizedCoordinates=YES;
id<MTLSamplerState> sampler=[device newSamplerStateWithDescriptor:sd];if(!sampler)throw std::runtime_error("无法分配色彩查找表采样器");[textures addObject:texture];[samplers addObject:sampler];
}
_textures=[textures copy];_samplers=[samplers copy];
source+="constant uint &premult [[buffer(0)]], uint2 xy [[thread_position_in_grid]]) {\nif(any(xy >= uint2(src.get_width(),src.get_height()))) return;\nfloat4 p=src.read(xy);\n";
if(!transform.isIdentity()){
// Same finite and alpha-floor contract as Core/DYPremultiplied.h.
// Alpha is excluded from the OCIO processor, including gamma ops.
source+="p=select(float4(0),p,isfinite(p));float a=p.a;\nif(premult) { p.rgb/=max(a,1e-5f);p=select(float4(0),p,isfinite(p)); }\np=dyOCIO("+arguments+"float4(p.rgb,1));p=select(float4(0),p,isfinite(p));p.a=a;\nif(premult){p.rgb*=a;p=select(float4(0),p,isfinite(p));}\n";
}
source+="dst.write(p,xy);}\n";
MTLCompileOptions *options=[MTLCompileOptions new];options.languageVersion=MTLLanguageVersion3_1;options.fastMathEnabled=NO;
id<MTLLibrary> library=[device newLibraryWithSource:[NSString stringWithUTF8String:source.c_str()] options:options error:error];
if(!library)return nil;
id<MTLFunction> function=[library newFunctionWithName:@"dyCMSFrame"];
if(!function)throw std::runtime_error("色彩管理显卡函数缺失");
_pipeline=[device newComputePipelineStateWithFunction:function error:error];
if(!_pipeline)return nil;
return self;
}catch(const std::exception &e){if(error)*error=failure([NSString stringWithUTF8String:e.what()]);return nil;}
}
- (BOOL)encodeInput:(id<MTLTexture>)input output:(id<MTLTexture>)output alpha:(dycm::Alpha)alpha commandBuffer:(id<MTLCommandBuffer>)command workspaceBudget:(uint64_t)bytes error:(NSError**)error {
try {
if(alpha!=dycm::Alpha::Straight&&alpha!=dycm::Alpha::Premultiplied)throw std::invalid_argument("色彩管理透明度表示无效");
auto valid=[&](id<MTLTexture> t){return t&&t.device.registryID==_device.registryID&&t.pixelFormat==MTLPixelFormatRGBA32Float&&t.textureType==MTLTextureType2D&&t.sampleCount==1&&t.mipmapLevelCount==1&&t.width&&t.height&&t.width<=16384&&t.height<=16384&&uint64_t(t.width)*t.height<=uint64_t(64)*1024*1024;};
if(!valid(input)||!valid(output)||input==output||input.width!=output.width||input.height!=output.height)
throw std::invalid_argument("色彩管理需要独立、同尺寸的 RGBA32Float 纹理");
if((input.usage!=MTLTextureUsageUnknown&&!(input.usage&MTLTextureUsageShaderRead))||(output.usage!=MTLTextureUsageUnknown&&!(output.usage&MTLTextureUsageShaderWrite)))
throw std::invalid_argument("色彩管理纹理缺少读写用途");
if(!command||command.commandQueue.device.registryID!=_device.registryID||command.status!=MTLCommandBufferStatusNotEnqueued)
throw std::invalid_argument("色彩管理帧命令不可写入");
if(_lutBytes>bytes||input.allocatedSize>bytes-_lutBytes||output.allocatedSize>bytes-_lutBytes-input.allocatedSize)
throw std::runtime_error("色彩管理超过图像预算");
id<MTLComputeCommandEncoder> encoder=[command computeCommandEncoder];
if(!encoder)throw std::runtime_error("色彩管理显卡编码器不可用");
uint32_t pm=alpha==dycm::Alpha::Premultiplied;
[encoder setComputePipelineState:_pipeline];[encoder setTexture:input atIndex:0];[encoder setTexture:output atIndex:1];[encoder setBytes:&pm length:sizeof(pm) atIndex:0];
for(NSUInteger i=0;i<_textures.count;i++){[encoder setTexture:_textures[i] atIndex:i+2];[encoder setSamplerState:_samplers[i] atIndex:i];}
NSUInteger x=_pipeline.threadExecutionWidth,y=std::min(NSUInteger(8),_pipeline.maxTotalThreadsPerThreadgroup/x);
[encoder dispatchThreads:MTLSizeMake(input.width,input.height,1) threadsPerThreadgroup:MTLSizeMake(x,y,1)];[encoder endEncoding];
return YES;
}catch(const std::exception &e){if(error)*error=failure([NSString stringWithUTF8String:e.what()]);return NO;}
}
@end
@implementation DYColorManagementGPUCache {
NSMutableDictionary<NSString*,DYColorManagementGPU*> *_entries;
NSMutableArray<NSString*> *_order;
NSUInteger _countLimit;
uint64_t _byteLimit;
DYColorManagementCacheStatistics _statistics;
}
+ (instancetype)sharedCache {
static DYColorManagementGPUCache *cache;static dispatch_once_t once;
dispatch_once(&once,^{cache=[[self alloc]initWithCountLimit:32 textureByteLimit:uint64_t(128)*1024*1024];});
return cache;
}
- (instancetype)init {return [self initWithCountLimit:32 textureByteLimit:uint64_t(128)*1024*1024];}
- (instancetype)initWithCountLimit:(NSUInteger)count textureByteLimit:(uint64_t)bytes {
if((self=[super init])){_entries=[NSMutableDictionary new];_order=[NSMutableArray new];_countLimit=count;_byteLimit=bytes;}
return self;
}
- (DYColorManagementGPU*)pipelineWithDevice:(id<MTLDevice>)device transform:(const dycm::Transform&)transform resourceBudget:(uint64_t)bytes error:(NSError**)error {
if(!device){if(error)*error=failure(@"色彩管理需要可用的显卡");return nil;}
NSString *key=[NSString stringWithFormat:@"%llu:%s",(unsigned long long)device.registryID,transform.key().c_str()];
// Coalesce simultaneous first frames. Compilation happens on the caller's
// render queue; the cache never calls back into a frame or holds its buffers.
@synchronized(self){
DYColorManagementGPU *pipeline=_entries[key];
if(pipeline){
if(pipeline.retainedTextureBytes>bytes){if(error)*error=failure(@"色彩管理查找表超过预算");return nil;}
[_order removeObject:key];[_order addObject:key];_statistics.hits++;return pipeline;
}
pipeline=[[DYColorManagementGPU alloc]initWithDevice:device transform:transform resourceBudget:bytes error:error];
if(!pipeline)return nil;_statistics.builds++;
uint64_t cost=pipeline.retainedTextureBytes;
if(!_countLimit||cost>_byteLimit)return pipeline;
while(_order.count&&(_order.count>=_countLimit||cost>_byteLimit-_statistics.retainedTextureBytes)){
NSString *old=_order.firstObject;_statistics.retainedTextureBytes-=_entries[old].retainedTextureBytes;
[_entries removeObjectForKey:old];[_order removeObjectAtIndex:0];_statistics.evictions++;
}
_entries[key]=pipeline;[_order addObject:key];_statistics.retainedTextureBytes+=cost;
return pipeline;
}
}
- (DYColorManagementCacheStatistics)statistics {
@synchronized(self){auto value=_statistics;value.entries=_entries.count;return value;}
}
- (void)removeAllObjects {
@synchronized(self){[_entries removeAllObjects];[_order removeAllObjects];_statistics.retainedTextureBytes=0;}
}
@end
@@ -0,0 +1,17 @@
#pragma once
#import <Foundation/Foundation.h>
#include "../Core/DYColorManagement.hpp"
NS_ASSUME_NONNULL_BEGIN
typedef NS_ENUM(NSInteger,DYCMSInputMode){DYCMSInputDeclared=0,DYCMSInputHostProfile=1};
// Root-level authoring state. Integration must explicitly whitelist this class;
// missing state in older documents means the unchanged unmanaged pipeline.
@interface DYColorManagementState : NSObject <NSSecureCoding,NSCopying>
@property(nonatomic) NSInteger version,inputSpace,workingSpace,outputTransform;
@property(nonatomic) DYCMSInputMode inputMode;
@property(nonatomic) BOOL enabled,referenceGamutCompression;
@property(nonatomic,copy) NSString *engineIdentifier,*configIdentifier;
- (BOOL)getSettings:(dycm::Settings*)settings error:(NSError* _Nullable * _Nullable)error;
- (nullable NSData*)archiveDataWithError:(NSError* _Nullable * _Nullable)error;
+ (nullable instancetype)stateFromArchiveData:(NSData*)data error:(NSError* _Nullable * _Nullable)error;
@end
NS_ASSUME_NONNULL_END
@@ -0,0 +1,77 @@
#import "DYColorManagementState.h"
#include <limits>
#include <stdexcept>
namespace {
NSError *failure(NSString *message){return [NSError errorWithDomain:@"com.dayu.colorplate.cms-state" code:1 userInfo:@{NSLocalizedDescriptionKey:message}];}
NSArray<NSString*> *keys(){return @[@"version",@"inputMode",@"inputSpace",@"workingSpace",@"outputTransform",@"enabled",@"referenceGamutCompression",@"engineIdentifier",@"configIdentifier"];}
}
@implementation DYColorManagementState
+ (BOOL)supportsSecureCoding{return YES;}
- (instancetype)init {
if((self=[super init])){dycm::Settings s;_version=2;_inputMode=DYCMSInputDeclared;_inputSpace=NSInteger(s.input);_workingSpace=NSInteger(s.working);_outputTransform=NSInteger(s.output);_enabled=s.enabled;_referenceGamutCompression=s.referenceGamutCompression;
_engineIdentifier=[NSString stringWithUTF8String:dycm::Engine];_configIdentifier=[NSString stringWithUTF8String:dycm::Config];}
return self;
}
- (BOOL)getSettings:(dycm::Settings*)settings error:(NSError**)error {
try {
if(!settings)throw std::invalid_argument("色彩管理参数目的地缺失");
if(![_engineIdentifier isKindOfClass:NSString.class]||![_configIdentifier isKindOfClass:NSString.class]||![_engineIdentifier isEqualToString:[NSString stringWithUTF8String:dycm::Engine]]||![_configIdentifier isEqualToString:[NSString stringWithUTF8String:dycm::Config]])
throw std::invalid_argument("工程使用了不支持的色彩转换组件版本");
for(NSNumber *value in @[@(_version),@(_inputSpace),@(_workingSpace),@(_outputTransform)])
if(value.longLongValue<0||value.unsignedLongLongValue>std::numeric_limits<unsigned>::max())throw std::invalid_argument("色彩管理标识超出范围");
if((_version!=1&&_version!=2)||(_inputMode!=DYCMSInputDeclared&&_inputMode!=DYCMSInputHostProfile)||(_version==1&&_inputMode!=DYCMSInputDeclared))throw std::invalid_argument("色彩管理输入方式或归档版本无效");
dycm::Settings s;s.enabled=_enabled;s.input=dycm::Space(_inputSpace);s.working=dycm::Space(_workingSpace);s.output=dycm::Output(_outputTransform);s.referenceGamutCompression=_referenceGamutCompression;
s.validate();if(_inputMode==DYCMSInputHostProfile)s.input=dycm::Space::ACEScg;*settings=s;return YES;
}catch(const std::exception &e){if(error)*error=failure([NSString stringWithUTF8String:e.what()]);return NO;}
}
- (void)encodeWithCoder:(NSCoder*)coder {
dycm::Settings s;NSError *error=nil;if(![self getSettings:&s error:&error]){[coder failWithError:error];return;}
for(NSString *key in @[@"version",@"inputSpace",@"workingSpace",@"outputTransform"])[coder encodeInteger:[[self valueForKey:key]integerValue] forKey:key];
if(_version>=2)[coder encodeInteger:_inputMode forKey:@"inputMode"];
[coder encodeBool:_enabled forKey:@"enabled"];[coder encodeBool:_referenceGamutCompression forKey:@"referenceGamutCompression"];
[coder encodeObject:_engineIdentifier forKey:@"engineIdentifier"];[coder encodeObject:_configIdentifier forKey:@"configIdentifier"];
}
- (instancetype)initWithCoder:(NSCoder*)coder {
if(!(self=[self init]))return nil;
for(NSString *key in keys())if(![key isEqual:@"inputMode"]&&![coder containsValueForKey:key]){[coder failWithError:failure(@"色彩管理归档不完整")];return nil;}
for(NSString *key in @[@"version",@"inputSpace",@"workingSpace",@"outputTransform"])[self setValue:@([coder decodeIntegerForKey:key]) forKey:key];
if((_version>=2)!=[coder containsValueForKey:@"inputMode"]){[coder failWithError:failure(@"色彩管理输入方式与归档版本不一致")];return nil;}
_inputMode=_version>=2?DYCMSInputMode([coder decodeIntegerForKey:@"inputMode"]):DYCMSInputDeclared;
// Keyed archives distinguish CFBoolean from integer NSNumber. The boolean
// decoder already rejects integer 0/1/2; an integer decoder rejects our own
// valid encodeBool fields. Do not coerce either representation via KVC.
_enabled=[coder decodeBoolForKey:@"enabled"];
_referenceGamutCompression=[coder decodeBoolForKey:@"referenceGamutCompression"];
if(coder.error)return nil;
_engineIdentifier=[[coder decodeObjectOfClass:NSString.class forKey:@"engineIdentifier"]copy];_configIdentifier=[[coder decodeObjectOfClass:NSString.class forKey:@"configIdentifier"]copy];
dycm::Settings s;NSError *error=nil;if(![self getSettings:&s error:&error]){[coder failWithError:error];return nil;}return self;
}
- (id)copyWithZone:(NSZone*)zone {
DYColorManagementState *copy=[[[self class]allocWithZone:zone]init];
for(NSString *key in keys())[copy setValue:[self valueForKey:key] forKey:key];return copy;
}
- (BOOL)isEqual:(id)object {
if(object==self)return YES;if(![object isMemberOfClass:self.class])return NO;
for(NSString *key in keys()){id a=[self valueForKey:key],b=[object valueForKey:key];if(a!=b&&![a isEqual:b])return NO;}return YES;
}
- (NSUInteger)hash {
NSUInteger value=1469598103934665603ull;
for(NSString *key in keys())value=(value^[[self valueForKey:key]hash])*1099511628211ull;return value;
}
- (NSData*)archiveDataWithError:(NSError**)error {
dycm::Settings s;if(![self getSettings:&s error:error])return nil;
@try{return [NSKeyedArchiver archivedDataWithRootObject:self requiringSecureCoding:YES error:error];}
@catch(NSException *exception){if(error)*error=failure(@"无法保存色彩管理设置");return nil;}
}
+ (instancetype)stateFromArchiveData:(NSData*)data error:(NSError**)error {
if(![data isKindOfClass:NSData.class]||!data.length||data.length>16384){if(error)*error=failure(@"色彩管理归档大小无效");return nil;}
@try{
id decoded=[NSKeyedUnarchiver unarchivedObjectOfClass:self fromData:data error:error];
// Foundation permits some scalar classes even with a specific root
// whitelist. Check the returned root before exposing typed state.
if(![decoded isMemberOfClass:self]){if(error)*error=failure(@"色彩管理归档根对象无效");return nil;}
dycm::Settings s;if(![decoded getSettings:&s error:error])return nil;return decoded;
}
@catch(NSException *exception){if(error)*error=failure(@"无法读取色彩管理设置");return nil;}
}
@end
+42
查看文件
@@ -0,0 +1,42 @@
#pragma once
#import <Foundation/Foundation.h>
#import <CoreGraphics/CoreGraphics.h>
#import <Metal/Metal.h>
#include "../Core/DYColorManagement.hpp"
#include <optional>
#include <atomic>
// A physical RGB profile conversion, separate from a declared camera encoding
// or an ACES display rendering transform. Profiles and keys are immutable.
@interface DYColorProfile : NSObject
- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)new NS_UNAVAILABLE;
- (instancetype)initWithSource:(CGColorSpaceRef)source target:(CGColorSpaceRef)target error:(NSError**)error;
// Encoded ACES ODT values to a real host/display profile. In particular, HLG
// uses the BT.2100 reference EOTF before the physical profile conversion.
- (instancetype)initWithDisplayOutput:(dycm::Output)output target:(CGColorSpaceRef)target error:(NSError**)error;
@property(nonatomic,readonly) CGColorSpaceRef source;
@property(nonatomic,readonly) CGColorSpaceRef target;
@property(nonatomic,readonly) BOOL identity;
@property(nonatomic,readonly,copy) NSString*key;
// Opaque fingerprint metadata only, never decoded as an authoring field.
@property(nonatomic,readonly,copy) NSData*sourceDescription;
@property(nonatomic,readonly,copy) NSData*targetDescription;
// No additional display tone mapping or [0,1] clipping. The selected physical
// profile still defines its own transfer-function range and extrapolation.
// Output storage is private. Input remains untouched on success or failure.
- (std::optional<std::vector<DYCompositeRGBA>>)convertPixels:(std::span<const DYCompositeRGBA>)input
alpha:(dycm::Alpha)alpha budget:(uint64_t)bytes cancelled:(const std::atomic_bool*)cancelled error:(NSError**)error;
@end
@interface DYColorProfileGPU : NSObject
- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)new NS_UNAVAILABLE;
- (instancetype)initWithDevice:(id<MTLDevice>)device profile:(DYColorProfile*)profile error:(NSError**)error;
- (BOOL)renderInput:(id<MTLTexture>)input output:(id<MTLTexture>)output alpha:(dycm::Alpha)alpha
workspaceBudget:(uint64_t)bytes cancelled:(const std::atomic_bool*)cancelled error:(NSError**)error;
@end
// Nominal output profile. For conversion use initWithDisplayOutput:target:;
// Apple's HLG profile alone is not the reference BT.2100 chromatic EOTF.
CGColorSpaceRef DYCreateCMSOutputColorSpace(dycm::Output output) CF_RETURNS_RETAINED;
+132
查看文件
@@ -0,0 +1,132 @@
#import "DYColorProfile.h"
#import <CoreImage/CoreImage.h>
#import <CommonCrypto/CommonDigest.h>
#include <mutex>
#include <stdexcept>
#include <simd/simd.h>
namespace {
struct CacheClear {CIContext*context;~CacheClear(){[context clearCaches];}};
NSError*failure(NSString*message){return [NSError errorWithDomain:@"com.dayu.colorplate.profile" code:1 userInfo:@{NSLocalizedDescriptionKey:message}];}
void check(const std::atomic_bool*cancelled){if(cancelled&&cancelled->load())throw std::runtime_error("颜色配置转换已取消");}
void validAlpha(dycm::Alpha alpha){if(alpha!=dycm::Alpha::Straight&&alpha!=dycm::Alpha::Premultiplied)throw std::invalid_argument("颜色配置透明度表示无效");}
void admission(uint64_t pixels,uint64_t bytes){if(!pixels||pixels>uint64_t(64)*1024*1024||pixels>bytes/(6*sizeof(DYCompositeRGBA)))throw std::runtime_error("颜色配置转换的估算工作集超过预算");}
NSData*description(CGColorSpaceRef space){
if(!space||CGColorSpaceGetModel(space)!=kCGColorSpaceModelRGB)throw std::invalid_argument("颜色转换需要明确的 RGB 配置");
CGColorSpaceRef device=CGColorSpaceCreateDeviceRGB();bool unspecified=CFEqual(space,device);CGColorSpaceRelease(device);if(unspecified)throw std::invalid_argument("Device RGB 没有明确的原色和传递函数");
CFPropertyListRef plist=CGColorSpaceCopyPropertyList(space);if(!plist)throw std::runtime_error("无法保存颜色配置描述");
NSData*data=[NSPropertyListSerialization dataWithPropertyList:CFBridgingRelease(plist) format:NSPropertyListBinaryFormat_v1_0 options:0 error:nil];
if(!data.length||data.length>16*1024*1024)throw std::runtime_error("颜色配置描述无效或超过限制");
return data;
}
NSString*fingerprint(NSData*data){unsigned char digest[CC_SHA256_DIGEST_LENGTH];CC_SHA256(data.bytes,(CC_LONG)data.length,digest);NSMutableString*result=[NSMutableString new];for(auto c:digest)[result appendFormat:@"%02x",c];return result;}
NSDictionary*options(bool software){
CGColorSpaceRef working=CGColorSpaceCreateWithName(kCGColorSpaceACESCGLinear);if(!working)throw std::runtime_error("无法建立线性颜色转换空间");
NSMutableDictionary*value=[@{kCIContextWorkingColorSpace:CFBridgingRelease(working),kCIContextWorkingFormat:@(kCIFormatRGBAf),kCIContextOutputPremultiplied:@YES,kCIContextCacheIntermediates:@NO}mutableCopy];if(software)value[kCIContextUseSoftwareRenderer]=@YES;return value;
}
void configure(CIRenderDestination*d,CGColorSpaceRef target){d.colorSpace=target;d.alphaMode=CIRenderDestinationAlphaPremultiplied;d.clamped=NO;d.dithered=NO;d.flipped=NO;}
bool render(CIContext*context,CIImage*image,CIRenderDestination*destination,size_t width,size_t height,NSError**error){
NSError*underlying=nil;auto task=[context startTaskToRender:image fromRect:CGRectMake(0,0,width,height) toDestination:destination atPoint:CGPointZero error:&underlying];
if(!task||![task waitUntilCompletedAndReturnError:&underlying]){if(error)*error=underlying?:failure(@"系统颜色配置转换未完成");return false;}return true;
}
id<MTLTexture>rootTexture(id<MTLTexture>t){while(t.parentTexture)t=t.parentTexture;return t;}
bool aliases(id<MTLTexture>a,id<MTLTexture>b){a=rootTexture(a);b=rootTexture(b);return a==b||(a.buffer&&a.buffer==b.buffer)||(a.iosurface&&a.iosurface==b.iosurface)||(a.heap&&a.heap==b.heap);}
CGColorSpaceRef calibrated(double rx,double ry,double gx,double gy,double bx,double by,double wx,double wy,double gamma){
simd_double3 white={wx/wy,1,(1-wx-wy)/wy};simd_double3x3 primaries={simd_double3{rx/ry,1,(1-rx-ry)/ry},simd_double3{gx/gy,1,(1-gx-gy)/gy},simd_double3{bx/by,1,(1-bx-by)/by}};auto scales=simd_mul(simd_inverse(primaries),white);
CGFloat w[3]={white.x,white.y,white.z},g[3]={gamma,gamma,gamma},matrix[9];for(int c=0;c<3;c++)for(int r=0;r<3;r++)matrix[c*3+r]=primaries.columns[c][r]*scales[c];return CGColorSpaceCreateCalibratedRGB(w,nullptr,g,matrix);
}
DYCompositeRGBA decodeHLG(DYCompositeRGBA p){
// BT.2100 reference display: 1000 cd/m2, gamma 1.2, black 0. Apple's
// physical linear profile uses ISO HDR reference white 203 cd/m2.
// Signed extension is explicit; finite values are not clipped to [0,1].
auto inverse=[](float c){float v=fabsf(c);return copysignf(v<=.5f?v*v/3.f:(expf((v-.55991073f)/.17883277f)+.28466892f)/12.f,c);};p.r=inverse(p.r);p.g=inverse(p.g);p.b=inverse(p.b);
float scale=(1000.f/203.f)*powf(fabsf(.2627f*p.r+.6780f*p.g+.0593f*p.b),.2f);p.r*=scale;p.g*=scale;p.b*=scale;return dyPMFinite(p);
}
}
@interface DYColorProfile ()
@property(nonatomic,readonly) CGColorSpaceRef conversionSource;
@property(nonatomic,readonly) BOOL decodeHLG;
@end
CGColorSpaceRef DYCreateCMSOutputColorSpace(dycm::Output output){
switch(output){
case dycm::Output::Rec709_100:case dycm::Output::Rec709D60_100:return calibrated(.64,.33,.30,.60,.15,.06,.3127,.3290,2.4);
case dycm::Output::SRGB_100:return CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
case dycm::Output::DisplayP3_100:return CGColorSpaceCreateWithName(kCGColorSpaceDisplayP3);
case dycm::Output::Rec2020_100:return calibrated(.708,.292,.170,.797,.131,.046,.3127,.3290,2.4);
case dycm::Output::Rec2020PQ_1000:return CGColorSpaceCreateWithName(kCGColorSpaceITUR_2100_PQ);
case dycm::Output::Rec2020HLG_1000:return CGColorSpaceCreateWithName(kCGColorSpaceITUR_2100_HLG);
case dycm::Output::P3D60_48:return calibrated(.68,.32,.265,.69,.15,.06,.32168,.33767,2.6);
case dycm::Output::P3DCI_48:return CGColorSpaceCreateWithName(kCGColorSpaceDCIP3);
case dycm::Output::P3D65_48:return calibrated(.68,.32,.265,.69,.15,.06,.3127,.3290,2.6);
}return nullptr;
}
@implementation DYColorProfile {
CGColorSpaceRef _source,_target,_conversionSource;BOOL _identity,_decodeHLG;NSString*_key;NSData*_sourceDescription,*_targetDescription;CIContext*_cpu;std::mutex _mutex;
}
- (CGColorSpaceRef)source{return _source;}
- (CGColorSpaceRef)target{return _target;}
- (BOOL)identity{return _identity;}
- (NSString*)key{return _key;}
- (NSData*)sourceDescription{return _sourceDescription;}
- (NSData*)targetDescription{return _targetDescription;}
- (CGColorSpaceRef)conversionSource{return _conversionSource?:_source;}
- (BOOL)decodeHLG{return _decodeHLG;}
- (instancetype)initWithSource:(CGColorSpaceRef)source target:(CGColorSpaceRef)target error:(NSError**)error {
if(!(self=[super init]))return nil;try{_sourceDescription=description(source);_targetDescription=description(target);_source=CGColorSpaceRetain(source);_target=CGColorSpaceRetain(target);_identity=CFEqual(source,target);_key=[NSString stringWithFormat:@"dayu-profile:1:%@:%@",fingerprint(_sourceDescription),fingerprint(_targetDescription)];return self;}catch(const std::exception&e){if(error)*error=failure(@(e.what()));return nil;}
}
- (instancetype)initWithDisplayOutput:(dycm::Output)output target:(CGColorSpaceRef)target error:(NSError**)error {
CGColorSpaceRef source=DYCreateCMSOutputColorSpace(output);self=[self initWithSource:source target:target error:error];if(source)CGColorSpaceRelease(source);if(!self)return nil;
if(output==dycm::Output::Rec2020HLG_1000){_conversionSource=CGColorSpaceCreateWithName(kCGColorSpaceExtendedLinearITUR_2020);if(!_conversionSource){if(error)*error=failure(@"无法建立 HLG 参考输出空间");return nil;}_decodeHLG=YES;_identity=NO;_key=[_key stringByAppendingString:@":reference-hlg:1000:203:v1"];}
return self;
}
- (void)dealloc{if(_source)CGColorSpaceRelease(_source);if(_target)CGColorSpaceRelease(_target);if(_conversionSource)CGColorSpaceRelease(_conversionSource);}
- (std::optional<std::vector<DYCompositeRGBA>>)convertPixels:(std::span<const DYCompositeRGBA>)input alpha:(dycm::Alpha)alpha budget:(uint64_t)bytes cancelled:(const std::atomic_bool*)cancelled error:(NSError**)error {
try{validAlpha(alpha);check(cancelled);if(input.empty()||input.size()>uint64_t(64)*1024*1024)throw std::invalid_argument("颜色转换输入大小无效");if(input.size()>bytes/(2*sizeof(DYCompositeRGBA)))throw std::runtime_error("颜色转换副本超过预算");if(_identity)return std::vector<DYCompositeRGBA>(input.begin(),input.end());admission(input.size(),bytes);
std::lock_guard<std::mutex>lock(_mutex);check(cancelled);@autoreleasepool{@try{
if(!_cpu)_cpu=[CIContext contextWithOptions:options(true)];if(!_cpu)throw std::runtime_error("无法建立 CPU 颜色转换");
CacheClear cleanup{_cpu};std::vector<DYCompositeRGBA>result(input.size());std::vector<DYCompositeRGBA>opaque(std::min(size_t(4096),input.size()));
for(size_t offset=0;offset<input.size();offset+=opaque.size()){
check(cancelled);size_t count=std::min(opaque.size(),input.size()-offset);
for(size_t i=0;i<count;i++){auto p=dyPMFinite(input[offset+i]);if(alpha==dycm::Alpha::Premultiplied)p=dyPMUnpremultiply(p);if(_decodeHLG)p=decodeHLG(p);p.a=1;opaque[i]=p;}
NSData*data=[NSData dataWithBytesNoCopy:opaque.data() length:count*sizeof(DYCompositeRGBA) freeWhenDone:NO];auto image=[CIImage imageWithBitmapData:data bytesPerRow:count*16 size:CGSizeMake(count,1) format:kCIFormatRGBAf colorSpace:self.conversionSource];
auto destination=[[CIRenderDestination alloc]initWithBitmapData:result.data()+offset width:count height:1 bytesPerRow:count*16 format:kCIFormatRGBAf];configure(destination,_target);
if(!image||!render(_cpu,image,destination,count,1,error)){[_cpu clearCaches];return std::nullopt;}
for(size_t i=0;i<count;i++){auto p=dyPMFinite(result[offset+i]);p.a=dyPMFinite(input[offset+i]).a;result[offset+i]=alpha==dycm::Alpha::Premultiplied?dyPMPremultiply(p):p;}
}[_cpu clearCaches];check(cancelled);return result;
}@catch(NSException*e){[_cpu clearCaches];if(error)*error=failure(e.reason?:@"CPU 颜色转换异常");return std::nullopt;}}
}catch(const std::exception&e){if(error)*error=failure(@(e.what()));return std::nullopt;}
}
@end
@implementation DYColorProfileGPU {
id<MTLDevice>_device;id<MTLCommandQueue>_queue;DYColorProfile*_profile;CIContext*_context;
id<MTLComputePipelineState>_prepare,_restore;std::mutex _mutex;
}
- (instancetype)initWithDevice:(id<MTLDevice>)device profile:(DYColorProfile*)profile error:(NSError**)error {
if(!(self=[super init]))return nil;try{
if(!device||!profile)throw std::invalid_argument("颜色配置或显卡缺失");_device=device;_profile=profile;_queue=[device newCommandQueue];if(!_queue)throw std::runtime_error("无法建立颜色转换队列");
if(profile.identity)return self;_context=[CIContext contextWithMTLCommandQueue:_queue options:options(false)];if(!_context)throw std::runtime_error("无法建立显卡颜色转换");
NSString*source=@"#include <metal_stdlib>\nusing namespace metal;\nfloat4 safe(float4 p){return select(float4(0),p,isfinite(p));}\nkernel void prepare(texture2d<float,access::read> src [[texture(0)]],texture2d<float,access::write> dst [[texture(1)]],constant uint2& options [[buffer(0)]],uint2 p [[thread_position_in_grid]]){if(any(p>=uint2(src.get_width(),src.get_height())))return;float4 c=safe(src.read(p));if(options.x)c=safe(float4(c.rgb/max(c.a,1e-5f),c.a));if(options.y){float3 v=abs(c.rgb);c.rgb=sign(c.rgb)*select((exp((v-.55991073f)/.17883277f)+.28466892f)/12.f,v*v/3.f,v<=.5f);c.rgb*=1000.f/203.f*pow(abs(dot(c.rgb,float3(.2627f,.6780f,.0593f))),.2f);c=safe(c);}dst.write(float4(c.rgb,1),p);}\nkernel void restore(texture2d<float,access::read> original [[texture(0)]],texture2d<float,access::read> converted [[texture(1)]],texture2d<float,access::write> dst [[texture(2)]],constant uint2& options [[buffer(0)]],uint2 p [[thread_position_in_grid]]){if(any(p>=uint2(dst.get_width(),dst.get_height())))return;float a=safe(original.read(p)).a;float3 rgb=safe(converted.read(p)).rgb;if(options.x)rgb*=a;dst.write(safe(float4(rgb,a)),p);}";
auto options=[MTLCompileOptions new];options.languageVersion=MTLLanguageVersion3_1;options.fastMathEnabled=NO;auto library=[device newLibraryWithSource:source options:options error:error];if(!library)return nil;
_prepare=[device newComputePipelineStateWithFunction:[library newFunctionWithName:@"prepare"] error:error];_restore=[device newComputePipelineStateWithFunction:[library newFunctionWithName:@"restore"] error:error];if(!_prepare||!_restore)return nil;return self;
}catch(const std::exception&e){if(error)*error=failure(@(e.what()));return nil;}
}
- (BOOL)renderInput:(id<MTLTexture>)input output:(id<MTLTexture>)output alpha:(dycm::Alpha)alpha workspaceBudget:(uint64_t)bytes cancelled:(const std::atomic_bool*)cancelled error:(NSError**)error {
try{validAlpha(alpha);check(cancelled);auto valid=[&](id<MTLTexture>t){return t&&t.device.registryID==_device.registryID&&t.textureType==MTLTextureType2D&&t.pixelFormat==MTLPixelFormatRGBA32Float&&t.width&&t.height&&t.width<=16384&&t.height<=16384&&t.sampleCount==1&&t.mipmapLevelCount==1&&!t.framebufferOnly&&t.storageMode!=MTLStorageModeMemoryless;};
if(!valid(input)||!valid(output)||input.width!=output.width||input.height!=output.height||aliases(input,output))throw std::invalid_argument("颜色转换需要同设备、同尺寸且独立的 RGBA32Float 纹理");
if((input.usage!=MTLTextureUsageUnknown&&!(input.usage&MTLTextureUsageShaderRead))||(output.usage!=MTLTextureUsageUnknown&&!(output.usage&MTLTextureUsageShaderWrite)))throw std::invalid_argument("颜色转换纹理缺少读写用途");
if(uint64_t(input.width)*input.height>uint64_t(64)*1024*1024)throw std::invalid_argument("颜色转换图像过大");
if(input.allocatedSize>bytes||output.allocatedSize>bytes-input.allocatedSize)throw std::runtime_error("颜色转换纹理超过预算");
std::lock_guard<std::mutex>lock(_mutex);check(cancelled);@autoreleasepool{@try{
CacheClear cleanup{_context};auto finish=[&](id<MTLCommandBuffer>b){if(!b)throw std::runtime_error("颜色转换命令缺失");[b commit];[b waitUntilCompleted];if(b.status!=MTLCommandBufferStatusCompleted)throw std::runtime_error(b.error.localizedDescription.UTF8String?:"颜色转换命令未完成");check(cancelled);};
if(_profile.identity){auto command=[_queue commandBuffer];auto blit=[command blitCommandEncoder];if(!blit)throw std::runtime_error("无法复制恒等颜色图像");[blit copyFromTexture:input sourceSlice:0 sourceLevel:0 sourceOrigin:MTLOriginMake(0,0,0) sourceSize:MTLSizeMake(input.width,input.height,1) toTexture:output destinationSlice:0 destinationLevel:0 destinationOrigin:MTLOriginMake(0,0,0)];[blit endEncoding];finish(command);return YES;}
admission(uint64_t(input.width)*input.height,bytes);auto desc=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA32Float width:input.width height:input.height mipmapped:NO];desc.storageMode=MTLStorageModePrivate;desc.usage=MTLTextureUsageShaderRead|MTLTextureUsageShaderWrite;
auto opaque=[_device newTextureWithDescriptor:desc],converted=[_device newTextureWithDescriptor:desc];if(!opaque||!converted)throw std::runtime_error("无法分配颜色转换图像");uint64_t actual=input.allocatedSize+output.allocatedSize+opaque.allocatedSize+converted.allocatedSize;
if(actual>bytes||2*uint64_t(input.width)*input.height*16>bytes-actual)throw std::runtime_error("颜色转换实际纹理及估算系统工作区超过预算");
auto dispatch=[&](id<MTLComputePipelineState>pipeline,NSArray*textures){check(cancelled);auto command=[_queue commandBuffer];auto encoder=[command computeCommandEncoder];if(!encoder)throw std::runtime_error("无法建立颜色转换编码器");[encoder setComputePipelineState:pipeline];for(NSUInteger i=0;i<textures.count;i++)[encoder setTexture:textures[i] atIndex:i];uint32_t parameters[2]={alpha==dycm::Alpha::Premultiplied,uint32_t(_profile.decodeHLG)};[encoder setBytes:parameters length:sizeof(parameters) atIndex:0];NSUInteger x=pipeline.threadExecutionWidth,y=std::min(NSUInteger(8),pipeline.maxTotalThreadsPerThreadgroup/x);[encoder dispatchThreads:MTLSizeMake(input.width,input.height,1) threadsPerThreadgroup:MTLSizeMake(x,y,1)];[encoder endEncoding];finish(command);};
dispatch(_prepare,@[input,opaque]);auto image=[CIImage imageWithMTLTexture:opaque options:@{kCIImageColorSpace:(__bridge id)_profile.conversionSource,kCIImageToneMapHDRtoSDR:@NO}];auto destination=[[CIRenderDestination alloc]initWithMTLTexture:converted commandBuffer:nil];configure(destination,_profile.target);
if(!image||!render(_context,image,destination,input.width,input.height,error)){[_context clearCaches];return NO;}check(cancelled);dispatch(_restore,@[input,converted,output]);[_context clearCaches];return YES;
}@catch(NSException*e){[_context clearCaches];if(error)*error=failure(e.reason?:@"显卡颜色转换异常");return NO;}}
}catch(const std::exception&e){if(error)*error=failure(@(e.what()));return NO;}
}
@end