diff --git a/ColorManagement/Core/DYColorManagement.hpp b/ColorManagement/Core/DYColorManagement.hpp new file mode 100644 index 0000000..1210d88 --- /dev/null +++ b/ColorManagement/Core/DYColorManagement.hpp @@ -0,0 +1,104 @@ +#pragma once +#include "DYPremultiplied.h" +#include +#include +#include +#include + +// Independent from the frozen grade ABI. Values are Dayu-owned, append-only IDs. +namespace dycm { +inline constexpr unsigned Version = 1; +inline constexpr const char *Engine = "OpenColorIO-2.5.2"; +inline constexpr const char *Config = "studio-config-v2.2.0_aces-v1.3_ocio-v2.4"; +enum class Space : unsigned { + ACES2065=1, ACEScg=2, ACEScc=3, ACEScct=4, + Linear709=10, Gamma22_709=11, SRGB=12, Linear2020=13, + AppleLog=100, ARRI_LogC3=101, ARRI_LogC4=102, BMD_Gen5=103, + CanonLog2=104, CanonLog3=105, PanasonicVLog=106, REDLog3G10=107, + SonySLog3=108, SonySLog3Cine=109, SonyVeniceSLog3=110, SonyVeniceSLog3Cine=111, + DaVinciIntermediate=112 +}; +enum class Output : unsigned { + Rec709_100=1, SRGB_100=2, DisplayP3_100=3, Rec709D60_100=4, + Rec2020_100=5, Rec2020PQ_1000=6, Rec2020HLG_1000=7, + P3D60_48=8, P3DCI_48=9, P3D65_48=10 +}; +enum class Alpha { Straight, Premultiplied }; +struct SpaceInfo { Space id; const char *label; const char *ocioName; }; +struct OutputInfo { Output id; const char *label; const char *display; const char *view; }; +std::span spaces(); +std::span outputs(); +const SpaceInfo &spaceInfo(Space); +const OutputInfo &outputInfo(Output); + +struct Settings { + unsigned version=Version; + bool enabled=false; + Space input=Space::ACEScg, working=Space::ACEScct; + Output output=Output::Rec709_100; + // Explicit scene-domain LMT, before the display/output transform. + bool referenceGamutCompression=false; + void validate() const; + std::string key() const; +}; +struct ShaderTexture { + unsigned dimensions=0,width=0,height=0,depth=0,channels=0; + bool linear=false; + std::vector values; +}; +struct MetalProgram {std::string source;std::vector textures;}; + +// Immutable processor, independent of OCIO environment variables and monitor state. +// A no-op never normalizes or unpremultiplies pixels (including hidden RGB). +class Transform { +public: + static Transform identity(); + static Transform convert(Space from, Space to); + static Transform display(Space from, Output to, bool gamutCompression=false); + bool isIdentity() const; + const std::string &key() const; + void apply(std::span pixels, Alpha alpha) const; + // Shader resources are copied from the fixed built-in config; no filesystem + // LUT loading, process-global config, or dynamic uniform is allowed here. + MetalProgram metalProgram() const; +private: + struct Impl; + std::shared_ptr impl; + explicit Transform(std::shared_ptr); +}; + +struct Plan { + Settings settings; + Transform input, output; + static Plan compile(const Settings &); + std::string key() const; +}; + +enum class FrameStage : unsigned { Input, Output, ToLinear, FromLinear, Count }; +enum class ToolDomain : unsigned { Working, Linear, Segmented }; +// An immutable platform profile conversion at a frame boundary. This interface +// keeps host ICC objects out of archives and the portable grading engine. +class PhysicalTransform { +public: + virtual ~PhysicalTransform() = default; + virtual bool isIdentity() const = 0; + virtual void apply(std::span, Alpha) const = 0; + virtual std::string key() const = 0; +}; +// The frame executor depends on this immutable contract, not on OCIO itself. +// Header-only legacy render tests therefore do not acquire a runtime dependency. +class FramePipeline { +public: + virtual ~FramePipeline() = default; + virtual void validate() const = 0; + virtual const Settings &settings() const = 0; + virtual const Transform &transform(FrameStage) const = 0; + virtual bool isIdentity(FrameStage) const = 0; + virtual void apply(FrameStage, std::span, Alpha) const = 0; + virtual std::string key() const = 0; + // Input boundary runs before the declared input transform; Output runs + // after the complete ODT. Intermediate tool domains have no ICC boundary. + virtual std::shared_ptr physicalBoundary(FrameStage) const {return {};} +}; +std::shared_ptr compileFramePipeline(const Settings &); +} // namespace dycm diff --git a/ColorManagement/Core/DYPremultiplied.h b/ColorManagement/Core/DYPremultiplied.h new file mode 100644 index 0000000..47c62d4 --- /dev/null +++ b/ColorManagement/Core/DYPremultiplied.h @@ -0,0 +1,6 @@ +#pragma once +#include +struct DYCompositeRGBA {float r,g,b,a;}; +inline DYCompositeRGBA dyPMFinite(DYCompositeRGBA p){return {std::isfinite(p.r)?p.r:0,std::isfinite(p.g)?p.g:0,std::isfinite(p.b)?p.b:0,std::isfinite(p.a)?p.a:0};} +inline DYCompositeRGBA dyPMUnpremultiply(DYCompositeRGBA p){float a=p.a>1e-5f?p.a:1e-5f;return dyPMFinite({p.r/a,p.g/a,p.b/a,p.a});} +inline DYCompositeRGBA dyPMPremultiply(DYCompositeRGBA p){return dyPMFinite({p.r*p.a,p.g*p.a,p.b*p.a,p.a});} diff --git a/ColorManagement/PROVENANCE.json b/ColorManagement/PROVENANCE.json new file mode 100644 index 0000000..dd7baf5 --- /dev/null +++ b/ColorManagement/PROVENANCE.json @@ -0,0 +1,47 @@ +{ + "sourceRepository": "https://dayu.media/git/dayu/dayu-colorplate.git", + "sourceCommit": "f8950384e514685c8809fe8e8ee2dd5f16ad0bd7", + "files": [ + { + "path": "Core/DYColorManagement.hpp", + "sourceSHA256": "78f6c2d5acdb611368370c3c9050d02d3a807f79b6f409906a4be7680a0c3746" + }, + { + "path": "Sources/DYColorManagement.cpp", + "sourceSHA256": "68648a1d2b1e4be8d3c59679e47d4b07de239ec2b5196dc1eb99b59af2ba6306" + }, + { + "path": "Sources/DYColorManagementGPU.h", + "sourceSHA256": "ed724b0cc73e27d8e238862bad120570939401e27f127d7afaf48c0e198cc4d7" + }, + { + "path": "Sources/DYColorManagementGPU.mm", + "sourceSHA256": "dd2c68a3b29baae0cd19b86e224d70a49c222010e6232a56e13d7500285ff1c5" + }, + { + "path": "Sources/DYColorManagementState.h", + "sourceSHA256": "5c39f949d83c160977b2cf6793ace991c0d66c81846c29dfd3bc705703b1c514" + }, + { + "path": "Sources/DYColorManagementState.mm", + "sourceSHA256": "2e0035b59d0ff028530b0766c07c143b76f12c4b785d404fd7aff1e46ed8d9eb" + }, + { + "path": "Sources/DYColorProfile.h", + "sourceSHA256": "38685ea23cbfe5686c1ade7ae8cf2eff231fd222e9d480245d3732ce5fecf7bb" + }, + { + "path": "Sources/DYColorProfile.mm", + "sourceSHA256": "ccf1d6bf401c7d11fb4a2a745ee1e399d45cc99b62eba61e3818a582ab8c672c" + }, + { + "path": "Tools/build_ocio.py", + "sourceSHA256": "ba1004e4d788590a44ae8ce2e124dcd65ee3b6b50d834cd615013d6355e6500b" + } + ], + "adaptations": [ + "Dedicated com.dayu.color runtime cache", + "Standalone RGBA/alpha header, excluding unrelated layer engine", + "No dependency on the sibling installed application" + ] +} diff --git a/ColorManagement/Sources/DYColorManagement.cpp b/ColorManagement/Sources/DYColorManagement.cpp new file mode 100644 index 0000000..d0f69f5 --- /dev/null +++ b/ColorManagement/Sources/DYColorManagement.cpp @@ -0,0 +1,221 @@ +#include "../Core/DYColorManagement.hpp" +#include +#include +#include +#include +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 spaces(){return spaceTable;} +std::span 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 processors; + std::vector cpus; + bool identity=true; + bool decodeCC=false,encodeCC=false; + Impl(std::string k,std::vector 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 value):impl(std::move(value)){} +Transform Transform::identity(){return Transform(std::make_shared(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(prefix()+"space:"+std::to_string(unsigned(from))+":"+std::to_string(unsigned(to)), + std::vector{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(prefix()+"display:"+std::to_string(unsigned(from))+":"+std::to_string(unsigned(to))+":"+std::to_string(gamutCompression), + std::vector{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 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 scratch; + std::array originalAlpha; + for(size_t offset=0;offsetdecodeCC){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;iencodeCC){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;stepprocessors.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;igetNum3DTextures();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;igetNumTextures();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 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 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 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::spanpixels,Alpha alpha)const override{transform(stage).apply(pixels,alpha);} + std::string key()const override{return plan.key();} +}; +} +std::shared_ptr compileFramePipeline(const Settings&s){ + s.validate();return s.enabled?std::make_shared(s):nullptr; +} +} // namespace dycm diff --git a/ColorManagement/Sources/DYColorManagementGPU.h b/ColorManagement/Sources/DYColorManagementGPU.h new file mode 100644 index 0000000..eafc00e --- /dev/null +++ b/ColorManagement/Sources/DYColorManagementGPU.h @@ -0,0 +1,33 @@ +#pragma once +#import +#import +#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)device transform:(const dycm::Transform&)transform error:(NSError**)error; +- (instancetype)initWithDevice:(id)device transform:(const dycm::Transform&)transform + resourceBudget:(uint64_t)bytes error:(NSError**)error; +- (BOOL)encodeInput:(id)input output:(id)output + alpha:(dycm::Alpha)alpha commandBuffer:(id)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)device + transform:(const dycm::Transform&)transform resourceBudget:(uint64_t)bytes error:(NSError**)error; +- (DYColorManagementCacheStatistics)statistics; +- (void)removeAllObjects; +@end diff --git a/ColorManagement/Sources/DYColorManagementGPU.mm b/ColorManagement/Sources/DYColorManagementGPU.mm new file mode 100644 index 0000000..4c9e1c6 --- /dev/null +++ b/ColorManagement/Sources/DYColorManagementGPU.mm @@ -0,0 +1,130 @@ +#import "DYColorManagementGPU.h" +#include +namespace { +NSError *failure(NSString *text){return [NSError errorWithDomain:@"com.dayu.colorplate.cms" code:1 userInfo:@{NSLocalizedDescriptionKey:text}];} +} +@implementation DYColorManagementGPU { + id _device; + id _pipeline; + NSString *_transformKey; + NSArray *_textures,*_samplers; + uint64_t _lutBytes; +} +- (NSString*)transformKey{return _transformKey;} +- (uint64_t)retainedTextureBytes{return _lutBytes;} +- (instancetype)initWithDevice:(id)device transform:(const dycm::Transform&)transform error:(NSError**)error { + return [self initWithDevice:device transform:transform resourceBudget:128*1024*1024 error:error]; +} +- (instancetype)initWithDevice:(id)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 \nusing namespace metal;\n"+program.source; + source+="\nkernel void dyCMSFrame(texture2d src [[texture(0)]], texture2d dst [[texture(1)]], ";std::string arguments; + for(size_t i=0;i 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 texture=[device newTextureWithDescriptor:d];if(!texture)throw std::runtime_error("无法分配色彩查找表");_lutBytes+=texture.allocatedSize;if(_lutBytes>limit)throw std::runtime_error("色彩管理查找表超过预算"); + std::vector rgba(uint64_t(t.width)*t.height*t.depth*4,1); + for(size_t p=0;p 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 library=[device newLibraryWithSource:[NSString stringWithUTF8String:source.c_str()] options:options error:error]; + if(!library)return nil; + id 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)input output:(id)output alpha:(dycm::Alpha)alpha commandBuffer:(id)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 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 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 *_entries; + NSMutableArray *_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)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 diff --git a/ColorManagement/Sources/DYColorManagementState.h b/ColorManagement/Sources/DYColorManagementState.h new file mode 100644 index 0000000..1cbcc58 --- /dev/null +++ b/ColorManagement/Sources/DYColorManagementState.h @@ -0,0 +1,17 @@ +#pragma once +#import +#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 +@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 diff --git a/ColorManagement/Sources/DYColorManagementState.mm b/ColorManagement/Sources/DYColorManagementState.mm new file mode 100644 index 0000000..de80462 --- /dev/null +++ b/ColorManagement/Sources/DYColorManagementState.mm @@ -0,0 +1,77 @@ +#import "DYColorManagementState.h" +#include +#include +namespace { +NSError *failure(NSString *message){return [NSError errorWithDomain:@"com.dayu.colorplate.cms-state" code:1 userInfo:@{NSLocalizedDescriptionKey:message}];} +NSArray *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::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 diff --git a/ColorManagement/Sources/DYColorProfile.h b/ColorManagement/Sources/DYColorProfile.h new file mode 100644 index 0000000..aefb38a --- /dev/null +++ b/ColorManagement/Sources/DYColorProfile.h @@ -0,0 +1,42 @@ +#pragma once +#import +#import +#import +#include "../Core/DYColorManagement.hpp" +#include +#include + +// 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>)convertPixels:(std::span)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)device profile:(DYColorProfile*)profile error:(NSError**)error; +- (BOOL)renderInput:(id)input output:(id)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; diff --git a/ColorManagement/Sources/DYColorProfile.mm b/ColorManagement/Sources/DYColorProfile.mm new file mode 100644 index 0000000..f28add9 --- /dev/null +++ b/ColorManagement/Sources/DYColorProfile.mm @@ -0,0 +1,132 @@ +#import "DYColorProfile.h" +#import +#import +#include +#include +#include + +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; +} +idrootTexture(idt){while(t.parentTexture)t=t.parentTexture;return t;} +bool aliases(ida,idb){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>)convertPixels:(std::span)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(input.begin(),input.end());admission(input.size(),bytes); + std::lock_guardlock(_mutex);check(cancelled);@autoreleasepool{@try{ + if(!_cpu)_cpu=[CIContext contextWithOptions:options(true)];if(!_cpu)throw std::runtime_error("无法建立 CPU 颜色转换"); + CacheClear cleanup{_cpu};std::vectorresult(input.size());std::vectoropaque(std::min(size_t(4096),input.size())); + for(size_t offset=0;offset_device;id_queue;DYColorProfile*_profile;CIContext*_context; + id_prepare,_restore;std::mutex _mutex; +} +- (instancetype)initWithDevice:(id)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 \nusing namespace metal;\nfloat4 safe(float4 p){return select(float4(0),p,isfinite(p));}\nkernel void prepare(texture2d src [[texture(0)]],texture2d 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 original [[texture(0)]],texture2d converted [[texture(1)]],texture2d 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)input output:(id)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=[&](idt){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_guardlock(_mutex);check(cancelled);@autoreleasepool{@try{ + CacheClear cleanup{_context};auto finish=[&](idb){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=[&](idpipeline,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 before [[texture(0)]],textu fragment half4 dyToolCopyFragment(DYRaster in [[stage_in]],texture2d source [[texture(0)]]){constexpr sampler f(coord::normalized,address::clamp_to_edge,filter::linear);return source.sample(f,in.uv);} #include "DYFilmKernels.inc.h" +#include "DYManagedKernels.inc.h" diff --git a/大鱼调色/Plugin/DYManagedColor.h b/大鱼调色/Plugin/DYManagedColor.h new file mode 100644 index 0000000..8468966 --- /dev/null +++ b/大鱼调色/Plugin/DYManagedColor.h @@ -0,0 +1,10 @@ +#pragma once +#import +#import +// Separate authoring state; absent state always selects the unchanged v1 renderer. +FOUNDATION_EXPORT NSDictionary *DYManagedColorDefaults(void); +FOUNDATION_EXPORT BOOL DYManagedColorValid(id state,NSError **error); +FOUNDATION_EXPORT NSArray *DYManagedInputSpaces(void); +FOUNDATION_EXPORT NSArray *DYManagedOutputSpaces(void); +FOUNDATION_EXPORT NSDictionary *DYHostColorContext(FxImageTile *source,FxImageTile *destination,NSInteger primaries); +FOUNDATION_EXPORT CGColorSpaceRef DYManagedTileSpace(FxImageTile *tile,NSInteger primaries) CF_RETURNS_RETAINED; diff --git a/大鱼调色/Plugin/DYManagedColor.mm b/大鱼调色/Plugin/DYManagedColor.mm new file mode 100644 index 0000000..94d6d7f --- /dev/null +++ b/大鱼调色/Plugin/DYManagedColor.mm @@ -0,0 +1,22 @@ +#import "DYManagedColor.h" +#include "../../ColorManagement/Core/DYColorManagement.hpp" +#include +#include +NSDictionary *DYManagedColorDefaults(void){return @{@"version":@2,@"mode":@1,@"input":@109,@"output":@1,@"gamutCompression":@YES,@"engine":@"OpenColorIO-2.5.2",@"config":@"studio-config-v2.2.0_aces-v1.3_ocio-v2.4"};} +NSArray *DYManagedInputSpaces(void){NSMutableArray *a=[NSMutableArray array];for(const auto&s:dycm::spaces())[a addObject:@{@"id":@(unsigned(s.id)),@"name":@(s.label)}];return a;} +NSArray *DYManagedOutputSpaces(void){NSMutableArray *a=[NSMutableArray array];for(const auto&s:dycm::outputs())[a addObject:@{@"id":@(unsigned(s.id)),@"name":@(s.label)}];return a;} +BOOL DYManagedColorValid(id state,NSError **error){ + BOOL valid=[state isKindOfClass:NSDictionary.class]&&[state count]<=8&&[state[@"version"]isEqual:@2]&&[state[@"engine"]isEqual:@"OpenColorIO-2.5.2"]&&[state[@"config"]isEqual:@"studio-config-v2.2.0_aces-v1.3_ocio-v2.4"]; + for(NSString *key in @[@"mode",@"input",@"output",@"gamutCompression"]){id v=[state isKindOfClass:NSDictionary.class]?state[key]:nil;double n=[v isKindOfClass:NSNumber.class]?[v doubleValue]:NAN;valid&=std::isfinite(n)&&n==floor(n);} + if(valid){valid=[@[@1,@2,@3]containsObject:state[@"mode"]]&&[@[@0,@1]containsObject:state[@"gamutCompression"]];BOOL input=NO,output=NO;for(NSDictionary *s in DYManagedInputSpaces())input|=[s[@"id"]isEqual:state[@"input"]];for(NSDictionary *s in DYManagedOutputSpaces())output|=[s[@"id"]isEqual:state[@"output"]];valid&=input&&output;} + if(!valid&&error)*error=[NSError errorWithDomain:@"com.dayu.color.cms" code:1 userInfo:@{NSLocalizedDescriptionKey:@"色彩管理设置无效或组件版本不匹配,未修改工程。"}];return valid; +} +CGColorSpaceRef DYManagedTileSpace(FxImageTile *tile,NSInteger primaries){ + CGColorSpaceRef space=nil;@try{space=tile.colorSpace;}@catch(NSException *exception){} + if(space&&CGColorSpaceGetModel(space)==kCGColorSpaceModelRGB){CGColorSpaceRef device=CGColorSpaceCreateDeviceRGB();BOOL unspecified=CFEqual(space,device);CGColorSpaceRelease(device);if(!unspecified)return CGColorSpaceRetain(space);} + if(primaries==kFxColorPrimaries_Rec709)return CGColorSpaceCreateWithName(kCGColorSpaceExtendedLinearSRGB); + if(primaries==kFxColorPrimaries_Rec2020)return CGColorSpaceCreateWithName(kCGColorSpaceExtendedLinearITUR_2020); + return nil; +} +static NSString *profileKey(CGColorSpaceRef space){if(!space)return @"unknown";CFPropertyListRef p=CGColorSpaceCopyPropertyList(space);NSData *d=p?[NSPropertyListSerialization dataWithPropertyList:(id)p format:NSPropertyListBinaryFormat_v1_0 options:0 error:nil]:nil;if(p)CFRelease(p);if(!d)return @"unknown";unsigned char hash[CC_SHA256_DIGEST_LENGTH];CC_SHA256(d.bytes,(CC_LONG)d.length,hash);NSMutableString*s=[NSMutableString string];for(auto c:hash)[s appendFormat:@"%02x",c];return s;} +NSDictionary *DYHostColorContext(FxImageTile *source,FxImageTile *destination,NSInteger primaries){CGColorSpaceRef a=DYManagedTileSpace(source,primaries),b=DYManagedTileSpace(destination,primaries);NSString *an=a?[(id)CGColorSpaceCopyName(a)autorelease]:nil,*bn=b?[(id)CGColorSpaceCopyName(b)autorelease]:nil;NSDictionary *d=@{@"primaries":@(primaries),@"source":an?:@"未知空间",@"destination":bn?:@"未知空间",@"sourceKey":profileKey(a),@"destinationKey":profileKey(b),@"processing":@"RGB Linear",@"alpha":@"premultiplied"};if(a)CGColorSpaceRelease(a);if(b)CGColorSpaceRelease(b);return d;} diff --git a/大鱼调色/Plugin/DYManagedKernels.inc.h b/大鱼调色/Plugin/DYManagedKernels.inc.h new file mode 100644 index 0000000..611e7a7 --- /dev/null +++ b/大鱼调色/Plugin/DYManagedKernels.inc.h @@ -0,0 +1,24 @@ +// V2 working images store premultiplied ACEScct/AP1 code values in float32. +inline float3 dyManagedDecode(float3 c){return float3(dyPrintCCTDecode(c.r),dyPrintCCTDecode(c.g),dyPrintCCTDecode(c.b));} +inline float3 dyManagedEncode(float3 c){return float3(dyPrintCCTEncode(c.r),dyPrintCCTEncode(c.g),dyPrintCCTEncode(c.b));} +kernel void dyManagedCopy(texture2d a [[texture(0)]],texture2d b [[texture(1)]],uint2 p [[thread_position_in_grid]]){if(any(p>=uint2(b.get_width(),b.get_height())))return;b.write(a.read(p),p);} +kernel void dyManagedBasis(texture2d a [[texture(0)]],texture2d b [[texture(1)]],constant BasisParams& settings [[buffer(0)]],constant float& amount [[buffer(1)]],uint2 p [[thread_position_in_grid]]){ + if(any(p>=uint2(b.get_width(),b.get_height())))return;float4 c=a.read(p);if(!(c.a>0)||amount<=0){b.write(c,p);return;} + float3 raw=c.rgb/c.a,result=basis_air(half4(half3(raw),1.h),settings).rgb; + float3 mixed=amount>=1?result:dyManagedEncode(mix(dyManagedDecode(raw),dyManagedDecode(result),amount));b.write(float4(mixed*c.a,c.a),p); +} +kernel void dyManagedPrint(texture2d a [[texture(0)]],texture3d cube [[texture(1)]],texture2d b [[texture(2)]],constant float& amount [[buffer(0)]],uint2 p [[thread_position_in_grid]]){ + if(any(p>=uint2(b.get_width(),b.get_height())))return;float4 c=a.read(p);if(!(c.a>0)||amount<=0){b.write(c,p);return;}float3 raw=c.rgb/c.a,result=dyPrintTetra(cube,raw); + b.write(float4(dyManagedEncode(mix(dyManagedDecode(raw),dyManagedDecode(result),amount))*c.a,c.a),p); +} +kernel void dyManagedBlend(texture2d before [[texture(0)]],texture2d after [[texture(1)]],texture2d output [[texture(2)]],device const DYToolMaskEntry* masks [[buffer(0)]],constant DYToolMaskHeader& h [[buffer(1)]],uint2 p [[thread_position_in_grid]]){ + if(any(p>=uint2(output.get_width(),output.get_height())))return;float4 a=before.read(p),b=after.read(p);if(!(a.a>0)){output.write(a,p);return;} + float3 ac=dyManagedDecode(a.rgb/a.a),bc=dyManagedDecode(b.rgb/b.a);float2 uv=(float2(p)+.5f)/float2(output.get_width(),output.get_height()); + float w=dyToolCoverage(uv,dyToolEncode(dyPrintFromAP1(ac)),masks,h,h.section);if(w<=0){output.write(a,p);return;}if(w>=1){output.write(b,p);return;} + output.write(float4(dyManagedEncode(mix(ac,bc,w))*a.a,a.a),p); +} +// Explicit code-value carrier for expert camera/LUT input. Host-profile mode +// never uses this reinterpretation; it converts the actual source ICC instead. +kernel void dyManagedCarrier(texture2d a [[texture(0)]],texture2d b [[texture(1)]],texture3d cube [[texture(2)]],constant uint& useLUT [[buffer(0)]],uint2 p [[thread_position_in_grid]]){ + if(any(p>=uint2(b.get_width(),b.get_height())))return;float4 c=a.read(p);if(c.a>0){float3 v=dyEncode(c.rgb/c.a);if(useLUT){constexpr sampler s(coord::normalized,address::clamp_to_edge,filter::linear);float n=cube.get_width();v=cube.sample(s,clamp(v,0.f,1.f)*((n-1)/n)+.5f/n).rgb;}c.rgb=v*c.a;}b.write(c,p); +} diff --git a/大鱼调色/Plugin/DYModel.h b/大鱼调色/Plugin/DYModel.h index ff9a37e..0aced97 100644 --- a/大鱼调色/Plugin/DYModel.h +++ b/大鱼调色/Plugin/DYModel.h @@ -14,6 +14,7 @@ FOUNDATION_EXPORT void DYReadUniforms(id manager,CMTime time,DY @property(copy) NSDictionary *paths; @property(nonatomic,copy) NSData *spiderMesh; @property BOOL spiderLinked; +@property(nonatomic,copy) NSDictionary *colorManagement; @end @interface DYInspectorToken : NSObject @property(copy) NSDictionary *folds; diff --git a/大鱼调色/Plugin/DYModel.mm b/大鱼调色/Plugin/DYModel.mm index 6a4c754..98937da 100644 --- a/大鱼调色/Plugin/DYModel.mm +++ b/大鱼调色/Plugin/DYModel.mm @@ -1,3 +1,4 @@ +#import "DYManagedColor.h" #import "DYModel.h" #import "DYToolState.h" #include @@ -206,14 +207,14 @@ BOOL DYCreateParameters(idm,NSError**error){id=2236&&pid<2400)||pid==DYAssetsParameterID)[_renderer invalidatePreview];dispatch_async(dispatch_get_main_queue(),^{[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:self.apiManager];});return YES;} - (BOOL)pluginState:(NSData**)state atTime:(CMTime)t quality:(FxQuality)q error:(NSError**)e{ - DYUniforms u;DYReadUniforms(_apiManager,t,&u);CMTime frameDuration=kCMTimeInvalid,origin=kCMTimeZero;idtiming=[_apiManager apiForProtocol:@protocol(FxTimingAPI_v4)];if([timing respondsToSelector:@selector(frameDuration:)])[timing frameDuration:&frameDuration];if([timing respondsToSelector:@selector(startTimeForEffect:)])[timing startTimeForEffect:&origin];int64_t frame=DYFilmFrameIndex(t,frameDuration,origin);u.filmFrameKey=DYFilmFrameKey(frame,u.film.grainHold,u.film.grainSeed);DYAssetState*a=DYReadAssets(_apiManager,t);DYToolDocument *tools=DYReadTools(_apiManager,t);[self adoptToolCanvasDocument:tools.document];double copyAuto=0;[[_apiManager apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)]getFloatValue:©Auto fromParameter:8800 atTime:t];NSMutableDictionary *snapshot=DYMutablePlist(DYToolRenderSnapshot(tools.document,t));for(NSMutableDictionary *node in snapshot[@"layers"]){DYUniforms layer=DYToolUniforms(node);if([node[@"type"]isEqual:@"film"])node[@"filmFrameKey"]=@(DYFilmFrameKey(frame,layer.film.grainHold,layer.film.grainSeed));}NSDictionary*s=@{@"schema":@2,@"tools":snapshot,@"copyAuto":@(copyAuto>.5),@"uniforms":[NSData dataWithBytes:&u length:sizeof(u)],@"paths":a.paths?:@{},@"spider":a.spiderMesh?:[NSData data]};*state=[NSPropertyListSerialization dataWithPropertyList:s format:NSPropertyListBinaryFormat_v1_0 options:0 error:e];return *state!=nil; + DYUniforms u;DYReadUniforms(_apiManager,t,&u);CMTime frameDuration=kCMTimeInvalid,origin=kCMTimeZero;idtiming=[_apiManager apiForProtocol:@protocol(FxTimingAPI_v4)];if([timing respondsToSelector:@selector(frameDuration:)])[timing frameDuration:&frameDuration];if([timing respondsToSelector:@selector(startTimeForEffect:)])[timing startTimeForEffect:&origin];int64_t frame=DYFilmFrameIndex(t,frameDuration,origin);u.filmFrameKey=DYFilmFrameKey(frame,u.film.grainHold,u.film.grainSeed);DYAssetState*a=DYReadAssets(_apiManager,t);DYToolDocument *tools=DYReadTools(_apiManager,t);[self adoptToolCanvasDocument:tools.document];double copyAuto=0;[[_apiManager apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)]getFloatValue:©Auto fromParameter:8800 atTime:t];NSMutableDictionary *snapshot=DYMutablePlist(DYToolRenderSnapshot(tools.document,t));for(NSMutableDictionary *node in snapshot[@"layers"]){DYUniforms layer=DYToolUniforms(node);if([node[@"type"]isEqual:@"film"])node[@"filmFrameKey"]=@(DYFilmFrameKey(frame,layer.film.grainHold,layer.film.grainSeed));}NSInteger primaries=-1;idgamut=[_apiManager apiForProtocol:@protocol(FxColorGamutAPI_v2)];if([gamut respondsToSelector:@selector(colorPrimaries)])primaries=gamut.colorPrimaries;NSDictionary*s=@{@"colorManagement":a.colorManagement?:@{},@"hostPrimaries":@(primaries),@"schema":@2,@"tools":snapshot,@"copyAuto":@(copyAuto>.5),@"uniforms":[NSData dataWithBytes:&u length:sizeof(u)],@"paths":a.paths?:@{},@"spider":a.spiderMesh?:[NSData data]};*state=[NSPropertyListSerialization dataWithPropertyList:s format:NSPropertyListBinaryFormat_v1_0 options:0 error:e];return *state!=nil; } - (BOOL)destinationImageRect:(FxRect*)rect sourceImages:(NSArray*)src destinationImage:(FxImageTile*)dst pluginState:(NSData*)s atTime:(CMTime)t error:(NSError**)e{if(!src.count)return NO;*rect=src[0].imagePixelBounds;return YES;} - (BOOL)sourceTileRect:(FxRect*)rect sourceImageIndex:(NSUInteger)i sourceImages:(NSArray*)src destinationTileRect:(FxRect)dstRect destinationImage:(FxImageTile*)dst pluginState:(NSData*)s atTime:(CMTime)t error:(NSError**)e{if(i>=src.count)return NO;*rect=src[i].imagePixelBounds;return YES;} - (BOOL)renderDestinationImage:(FxImageTile*)dst sourceImages:(NSArray*)src pluginState:(NSData*)s atTime:(CMTime)t error:(NSError**)e{ - if(!src.count||!src[0].ioSurface||!dst.ioSurface||!s.length)return NO;NSDictionary*p=[NSPropertyListSerialization propertyListWithData:s options:NSPropertyListImmutable format:NULL error:e];if(![p isKindOfClass:NSDictionary.class])return NO;NSData*b=p[@"uniforms"];if(![@[@1,@2]containsObject:p[@"schema"]]||![b isKindOfClass:NSData.class]||b.length!=sizeof(DYUniforms)||![p[@"paths"]isKindOfClass:NSDictionary.class])return NO;DYUniforms u;[b getBytes:&u length:sizeof(u)];uint64_t beta=!_betaFirstRenderStarted.exchange(true)?DYBetaSpanBegin(@"first_render",nil):0;BOOL ok=[_renderer renderSource:src[0] destination:dst uniforms:u paths:p[@"paths"] spider:p[@"spider"] tools:p[@"tools"] error:e];DYBetaSpanEnd(beta,@{@"status":ok?@"passed":@"failed"});if(!ok)DYBetaEvent(@"render_error",@{@"error_domain":(e&&*e)?(*e).domain:@"unknown",@"error_code":@((e&&*e)?(*e).code:0)});if(ok){if(_toolCaptureEnabled&&!_trackingActive.load()){dy::GrayFrame frame=[self toolGrayFrame:src[0] error:nil];if(frame.valid()){@synchronized(self){_toolSourceFrame=std::move(frame);_toolSourceTime=t;}}}BOOL analyze=NO;@synchronized(self){if(![p[@"copyAuto"]boolValue])_copyAnalyzed=NO;else if(!_copyAnalyzed){_copyAnalyzed=YES;analyze=YES;}}if(analyze){NSDictionary*values=DYAutoGrade([_renderer preview]);if(values)dispatch_async(dispatch_get_main_queue(),^{[self applyValues:values];});}}return ok; + if(!src.count||!src[0].ioSurface||!dst.ioSurface||!s.length)return NO;NSDictionary*p=[NSPropertyListSerialization propertyListWithData:s options:NSPropertyListImmutable format:NULL error:e];if(![p isKindOfClass:NSDictionary.class])return NO;NSData*b=p[@"uniforms"];if(![@[@1,@2]containsObject:p[@"schema"]]||![b isKindOfClass:NSData.class]||b.length!=sizeof(DYUniforms)||![p[@"paths"]isKindOfClass:NSDictionary.class])return NO;DYUniforms u;[b getBytes:&u length:sizeof(u)];uint64_t beta=!_betaFirstRenderStarted.exchange(true)?DYBetaSpanBegin(@"first_render",nil):0;BOOL ok=[_renderer renderSource:src[0] destination:dst uniforms:u paths:p[@"paths"] spider:p[@"spider"] tools:p[@"tools"] colorManagement:p[@"colorManagement"] hostPrimaries:p[@"hostPrimaries"]?[p[@"hostPrimaries"]integerValue]:-1 error:e];DYBetaSpanEnd(beta,@{@"status":ok?@"passed":@"failed"});if(!ok)DYBetaEvent(@"render_error",@{@"error_domain":(e&&*e)?(*e).domain:@"unknown",@"error_code":@((e&&*e)?(*e).code:0)});if(ok){if(_toolCaptureEnabled&&!_trackingActive.load()){dy::GrayFrame frame=[self toolGrayFrame:src[0] error:nil];if(frame.valid()){@synchronized(self){_toolSourceFrame=std::move(frame);_toolSourceTime=t;}}}BOOL analyze=NO;@synchronized(self){if(![p[@"copyAuto"]boolValue])_copyAnalyzed=NO;else if(!_copyAnalyzed){_copyAnalyzed=YES;analyze=YES;}}if(analyze){NSDictionary*values=DYAutoGrade([_renderer preview]);if(values)dispatch_async(dispatch_get_main_queue(),^{[self applyValues:values];});}}return ok; } - (void)alert:(NSString*)message{dispatch_async(dispatch_get_main_queue(),^{NSAlert*a=[NSAlert new];a.messageText=@"大鱼调色";a.informativeText=message?:@"操作未完成";[a runModal];[a release];});} - (void)exportRequested:(NSNotification*)n{ diff --git a/大鱼调色/Plugin/DYRenderer.h b/大鱼调色/Plugin/DYRenderer.h index 2b03423..83d011f 100644 --- a/大鱼调色/Plugin/DYRenderer.h +++ b/大鱼调色/Plugin/DYRenderer.h @@ -18,4 +18,7 @@ /// Analysis preview retains the host texture's original row order separately. - (NSData*)lookLUTPreview; - (void)invalidatePreview; +- (NSDictionary*)colorContext; +- (BOOL)renderSource:(FxImageTile*)source destination:(FxImageTile*)destination uniforms:(DYUniforms)uniforms paths:(NSDictionary*)paths spider:(NSData*)spider tools:(NSDictionary*)tools colorManagement:(NSDictionary*)state hostPrimaries:(NSInteger)primaries error:(NSError**)error; +- (BOOL)exportLUT:(NSURL*)url uniforms:(DYUniforms)uniforms paths:(NSDictionary*)paths spider:(NSData*)spider tools:(NSDictionary*)tools colorManagement:(NSDictionary*)state error:(NSError**)error; @end diff --git a/大鱼调色/Plugin/DYToolState.mm b/大鱼调色/Plugin/DYToolState.mm index ae4248e..0e5f6d9 100644 --- a/大鱼调色/Plugin/DYToolState.mm +++ b/大鱼调色/Plugin/DYToolState.mm @@ -62,7 +62,7 @@ static NSData *parameterData(DYMaskParameters p){return [NSData dataWithBytes:&p static BOOL readParameters(id data,DYMaskParameters *p){if(![data isKindOfClass:NSData.class]||[data length]!=sizeof(*p))return NO;[data getBytes:p length:sizeof(*p)];return dyValidMaskParameters(*p);} static CMTime keyTime(NSDictionary *key){return CMTimeMakeWithEpoch([key[@"value"]longLongValue],[key[@"scale"]intValue],[key[@"epoch"]longLongValue]);} NSDictionary *DYNewMask(NSInteger kind){if(kind<0||kind>5)return nil;DYMaskParameters p=dyDefaultMaskParameters();p.kind=(DYMaskKind)kind;p.width=.5;p.height=.5;p.sourceStage=DYMaskSourceOriginal;if(kind==DYMaskHSLKey)p.flags=DYMaskHueEnabled;NSData *nodes=[NSData data];if(kind==DYMaskBezier){DYBezierNode n[4]={};float x[4]={-.5,.5,.5,-.5},y[4]={-.5,-.5,.5,.5};for(int i=0;i<4;i++)n[i]={x[i],y[i],x[i],y[i],x[i],y[i]};nodes=[NSData dataWithBytes:n length:sizeof(n)];}return @{@"id":NSUUID.UUID.UUIDString,@"enabled":@YES,@"combine":@0,@"parameters":parameterData(p),@"nodes":nodes,@"keys":@[]};} -NSDictionary *DYNewTool(NSString *type){if(![DYToolTypes()containsObject:type])return nil;return @{@"id":NSUUID.UUID.UUIDString,@"type":type,@"values":[type isEqual:@"skin"]?@{@"skinStrength":@0}:[type isEqual:@"primary"]?@{@"cmtoneMapping":@1}:@{},@"paths":@{},@"spiderLinked":@YES,@"masks":@[]};} +NSDictionary *DYNewTool(NSString *type){if(![DYToolTypes()containsObject:type])return nil;return @{@"id":NSUUID.UUID.UUIDString,@"type":type,@"values":[type isEqual:@"skin"]?@{@"skinStrength":@0}:[type isEqual:@"primary"]?@{@"cmtoneMapping":@0}:@{},@"paths":@{},@"spiderLinked":@YES,@"masks":@[]};} BOOL DYValidToolMask(NSDictionary *mask){ if(![mask isKindOfClass:NSDictionary.class]||!validID(mask[@"id"])||!finiteNumber(mask[@"enabled"])||!finiteNumber(mask[@"combine"])||[mask[@"combine"]integerValue]<0||[mask[@"combine"]integerValue]>2)return NO; DYMaskParameters p;if(!readParameters(mask[@"parameters"],&p))return NO;NSData *nodes=mask[@"nodes"];if(![nodes isKindOfClass:NSData.class]||nodes.length%sizeof(DYBezierNode)||nodes.length>32*sizeof(DYBezierNode))return NO;