WIP: add pinned public CMS runtime and versioned color state; renderer integration pending
这个提交包含在:
1 父节点
5b8ef04f7e
当前提交
70a50ab445
42 个文件已更改
+1317
-9
没有与搜索条件相匹配的文件
@@ -0,0 +1,104 @@
|
||||
#pragma once
|
||||
#include "DYPremultiplied.h"
|
||||
#include <memory>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
// 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<const SpaceInfo> spaces();
|
||||
std::span<const OutputInfo> 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<float> values;
|
||||
};
|
||||
struct MetalProgram {std::string source;std::vector<ShaderTexture> 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<DYCompositeRGBA> 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<const Impl> impl;
|
||||
explicit Transform(std::shared_ptr<const Impl>);
|
||||
};
|
||||
|
||||
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<DYCompositeRGBA>, 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<DYCompositeRGBA>, 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<const PhysicalTransform> physicalBoundary(FrameStage) const {return {};}
|
||||
};
|
||||
std::shared_ptr<const FramePipeline> compileFramePipeline(const Settings &);
|
||||
} // namespace dycm
|
||||
@@ -0,0 +1,6 @@
|
||||
#pragma once
|
||||
#include <cmath>
|
||||
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});}
|
||||
@@ -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"
|
||||
]
|
||||
}
|
||||
@@ -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
|
||||
@@ -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;
|
||||
@@ -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
|
||||
@@ -0,0 +1,11 @@
|
||||
# 固定版本的公开色彩管理依赖
|
||||
|
||||
这里保留 OpenColorIO 2.5.2 及其六个静态依赖、ARM SIMD 头文件的原始源码压缩包,供离线恢复与构建。不是已安装的依赖目录或编译产物。每个来源 URL、版本、字节数、SHA-256 和许可证见 `dependencies.lock.json`;原压缩包包含完整版权声明。
|
||||
|
||||
`python3 Tools/build_ocio.py` 在产品固定缓存的 `cms-runtime` 中编译 Release arm64/macOS 14.6,使用私有命名空间 `DayuOCIO_2_5_2`,不链接 Homebrew 动态库,不在构建时下载源码。需要 Xcode 和 CMake 3.24 以上(本机为 4.4.4)。缓存修改有两处:下载入口改为已校验的本地源码包;禁用 `OCIO_OPTIMIZATION_FLAGS` 环境覆盖,防止宿主环境悄悄改变工程精度。上游转换算法保持原样。构建有进程锁,所有实际静态库均校验后才复用。
|
||||
|
||||
固定 Studio 配置 `studio-config-v2.2.0_aces-v1.3_ocio-v2.4`,不使用随升级漂移的 `studio-config-latest`。OCIO 软件版本、配置版本和 ACES 系统版本是三个独立标识。完整输出使用 DisplayViewTransform;显示编码转换不能替代 ACES 输出渲染。
|
||||
|
||||
大鱼的 ACEScc 边界使用 [Academy 公开公式](https://docs.acescentral.com/encodings/acescc/) 与 AP1 线性衔接,避免此配置 ACEScc 的 4096 点查表近似。ACEScct 和相机/显示转换仍用固定 OCIO 配置。CPU/GPU选择 `OPTIMIZATION_LOSSLESS`,输出域和透明度政策由独立模块验证。
|
||||
|
||||
当前为独立模块准备,尚未接入产品渲染、工程归档或界面。正式33及旧工程不受影响。后续集成时须将这些许可证装入发行 APP,并验证 CPU/Metal、透明度、旧工程旁路以及宿主输入/输出边界。
|
||||
@@ -0,0 +1,96 @@
|
||||
{
|
||||
"version": 1,
|
||||
"namespace": "DayuOCIO_2_5_2",
|
||||
"builtin_config": "studio-config-v2.2.0_aces-v1.3_ocio-v2.4",
|
||||
"sources": [
|
||||
{
|
||||
"name": "OpenColorIO",
|
||||
"version": "2.5.2",
|
||||
"url": "https://codeload.github.com/AcademySoftwareFoundation/OpenColorIO/tar.gz/refs/tags/v2.5.2",
|
||||
"archive": "OpenColorIO-2.5.2.tar.gz",
|
||||
"bytes": 14182890,
|
||||
"sha256": "722601e01b78b7a12da4829cb450674935f404b0e508f3f20046fa77570e3272",
|
||||
"licenses": [
|
||||
"licenses/OpenColorIO.txt"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "expat",
|
||||
"version": "2.7.2",
|
||||
"url": "https://codeload.github.com/libexpat/libexpat/tar.gz/R_2_7_2",
|
||||
"archive": "expat-2.7.2.tar.gz",
|
||||
"bytes": 8439887,
|
||||
"sha256": "d09e2dd23398805cec1bac2860304714c96dc2fde629a7a1a77d0880ab7cd242",
|
||||
"licenses": [
|
||||
"licenses/expat.txt",
|
||||
"licenses/expat-1.txt"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "yaml-cpp",
|
||||
"version": "0.8.0",
|
||||
"url": "https://codeload.github.com/jbeder/yaml-cpp/tar.gz/0.8.0",
|
||||
"archive": "yaml-cpp-0.8.0.tar.gz",
|
||||
"bytes": 1017151,
|
||||
"sha256": "fbe74bbdcee21d656715688706da3c8becfd946d92cd44705cc6098bb23b3a16",
|
||||
"licenses": [
|
||||
"licenses/yaml-cpp.txt"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Imath",
|
||||
"version": "3.2.1",
|
||||
"url": "https://codeload.github.com/AcademySoftwareFoundation/Imath/tar.gz/v3.2.1",
|
||||
"archive": "Imath-3.2.1.tar.gz",
|
||||
"bytes": 689041,
|
||||
"sha256": "b2c8a44c3e4695b74e9644c76f5f5480767355c6f98cde58ba0e82b4ad8c63ce",
|
||||
"licenses": [
|
||||
"licenses/Imath.txt"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "pystring",
|
||||
"version": "1.1.4",
|
||||
"url": "https://codeload.github.com/imageworks/pystring/tar.gz/v1.1.4",
|
||||
"archive": "pystring-1.1.4.tar.gz",
|
||||
"bytes": 19184,
|
||||
"sha256": "49da0fe2a049340d3c45cce530df63a2278af936003642330287b68cefd788fb",
|
||||
"licenses": [
|
||||
"licenses/pystring.txt"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "minizip-ng",
|
||||
"version": "4.0.10",
|
||||
"url": "https://codeload.github.com/zlib-ng/minizip-ng/tar.gz/4.0.10",
|
||||
"archive": "minizip-ng-4.0.10.tar.gz",
|
||||
"bytes": 773269,
|
||||
"sha256": "c362e35ee973fa7be58cc5e38a4a6c23cc8f7e652555daf4f115a9eb2d3a6be7",
|
||||
"licenses": [
|
||||
"licenses/minizip-ng.txt"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "zlib",
|
||||
"version": "1.3.1",
|
||||
"url": "https://codeload.github.com/madler/zlib/tar.gz/v1.3.1",
|
||||
"archive": "zlib-1.3.1.tar.gz",
|
||||
"bytes": 1572744,
|
||||
"sha256": "17e88863f3600672ab49182f217281b6fc4d3c762bde361935e436a95214d05c",
|
||||
"licenses": [
|
||||
"licenses/zlib.txt"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "sse2neon",
|
||||
"version": "227cc413fb2d50b2a10073087be96b59d5364aea",
|
||||
"url": "https://codeload.github.com/DLTcollab/sse2neon/tar.gz/227cc413fb2d50b2a10073087be96b59d5364aea",
|
||||
"archive": "sse2neon-227cc413fb2d50b2a10073087be96b59d5364aea.tar.gz",
|
||||
"bytes": 136342,
|
||||
"sha256": "3427a495743bb6fd1b5f9f806b80f57d67b1ac7ccf39a5f44aedd487fd7e6da1",
|
||||
"licenses": [
|
||||
"licenses/sse2neon.txt"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
Copyright 2013 Colour Developers
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
||||
|
||||
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE
|
||||
@@ -0,0 +1,11 @@
|
||||
Copyright Contributors to the OpenEXR Project. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
||||
|
||||
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
@@ -0,0 +1,26 @@
|
||||
Copyright Contributors to the OpenColorIO Project.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
* Neither the name of the copyright holder nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
@@ -0,0 +1,21 @@
|
||||
Copyright (c) 1998-2000 Thai Open Source Software Center Ltd and Clark Cooper
|
||||
Copyright (c) 2001-2025 Expat maintainers
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included
|
||||
in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
||||
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
||||
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
@@ -0,0 +1,21 @@
|
||||
Copyright (c) 1998-2000 Thai Open Source Software Center Ltd and Clark Cooper
|
||||
Copyright (c) 2001-2025 Expat maintainers
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included
|
||||
in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
||||
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
||||
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
@@ -0,0 +1,17 @@
|
||||
Condition of use and distribution are the same as zlib:
|
||||
|
||||
This software is provided 'as-is', without any express or implied
|
||||
warranty. In no event will the authors be held liable for any damages
|
||||
arising from the use of this software.
|
||||
|
||||
Permission is granted to anyone to use this software for any purpose,
|
||||
including commercial applications, and to alter it and redistribute it
|
||||
freely, subject to the following restrictions:
|
||||
|
||||
1. The origin of this software must not be misrepresented; you must not
|
||||
claim that you wrote the original software. If you use this software
|
||||
in a product, an acknowledgement in the product documentation would be
|
||||
appreciated but is not required.
|
||||
2. Altered source versions must be plainly marked as such, and must not be
|
||||
misrepresented as being the original software.
|
||||
3. This notice may not be removed or altered from any source distribution.
|
||||
@@ -0,0 +1,27 @@
|
||||
Copyright (c) 2008-present Contributors to the Pystring project.
|
||||
All Rights Reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
3. Neither the name of the copyright holder nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2015-2024 SSE2NEON Contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,19 @@
|
||||
Copyright (c) 2008-2015 Jesse Beder.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
@@ -0,0 +1,22 @@
|
||||
Copyright notice:
|
||||
|
||||
(C) 1995-2022 Jean-loup Gailly and Mark Adler
|
||||
|
||||
This software is provided 'as-is', without any express or implied
|
||||
warranty. In no event will the authors be held liable for any damages
|
||||
arising from the use of this software.
|
||||
|
||||
Permission is granted to anyone to use this software for any purpose,
|
||||
including commercial applications, and to alter it and redistribute it
|
||||
freely, subject to the following restrictions:
|
||||
|
||||
1. The origin of this software must not be misrepresented; you must not
|
||||
claim that you wrote the original software. If you use this software
|
||||
in a product, an acknowledgment in the product documentation would be
|
||||
appreciated but is not required.
|
||||
2. Altered source versions must be plainly marked as such, and must not be
|
||||
misrepresented as being the original software.
|
||||
3. This notice may not be removed or altered from any source distribution.
|
||||
|
||||
Jean-loup Gailly Mark Adler
|
||||
jloup@gzip.org madler@alumni.caltech.edu
|
||||
二进制文件未显示。
二进制文件未显示。
二进制文件未显示。
二进制文件未显示。
二进制文件未显示。
二进制
二进制文件未显示。
二进制文件未显示。
二进制文件未显示。
@@ -0,0 +1,98 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build the pinned color runtime offline; no Homebrew libraries or implicit downloads."""
|
||||
from pathlib import Path
|
||||
import fcntl, hashlib, json, os, re, shutil, subprocess, tarfile
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
VENDOR = ROOT / 'ThirdParty/ColorManagement'
|
||||
CACHE = Path('/Users/mac/Library/Caches/CodexBuilds/com.dayu.color/cms-runtime')
|
||||
|
||||
def digest(path):
|
||||
return hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
|
||||
def extract(archive, destination):
|
||||
with tarfile.open(archive) as tf:
|
||||
for member in tf.getmembers():
|
||||
path = (destination / member.name).resolve()
|
||||
if destination not in path.parents or member.isdev():
|
||||
raise ValueError('Unsafe source archive member')
|
||||
if member.issym() or member.islnk():
|
||||
target = ((path.parent if member.issym() else destination) / member.linkname).resolve()
|
||||
if target != destination and destination not in target.parents:
|
||||
raise ValueError('Unsafe source archive link')
|
||||
# Python 3.9 on the supported build machine has no extraction filter API.
|
||||
tf.extractall(destination)
|
||||
|
||||
def _build():
|
||||
lock = json.loads((VENDOR / 'dependencies.lock.json').read_text())
|
||||
archives = {}
|
||||
for item in lock['sources']:
|
||||
archive = VENDOR / 'sources' / item['archive']
|
||||
if archive.stat().st_size != item['bytes'] or digest(archive) != item['sha256']:
|
||||
raise ValueError('Source checksum mismatch: ' + item['name'])
|
||||
archives[item['name']] = (archive, item['sha256'])
|
||||
cmake = shutil.which('cmake') or '/opt/homebrew/bin/cmake'
|
||||
compiler = subprocess.check_output(['xcrun', 'clang++', '--version'], text=True)
|
||||
sdk = subprocess.check_output(['xcrun', '--show-sdk-version'], text=True).strip()
|
||||
identity = hashlib.sha256((json.dumps(lock, sort_keys=True) + Path(__file__).read_text() + compiler + sdk).encode()).hexdigest()
|
||||
CACHE.mkdir(parents=True, exist_ok=True)
|
||||
stamp = CACHE / 'build.json'
|
||||
if stamp.exists():
|
||||
previous = json.loads(stamp.read_text())
|
||||
if previous.get('identity') == identity and all(Path(p).is_file() and digest(Path(p)) == sha for p, sha in previous['libraries'].items()):
|
||||
return previous
|
||||
source_dir, build_dir, install = CACHE / 'source', CACHE / 'build', CACHE / 'install'
|
||||
# These are dedicated generated directories; no product APP or user source lives here.
|
||||
for path in (source_dir, build_dir, install):
|
||||
if path.exists(): shutil.rmtree(path)
|
||||
path.mkdir()
|
||||
extract(archives['OpenColorIO'][0], source_dir)
|
||||
source = source_dir / 'OpenColorIO-2.5.2'
|
||||
modules = source / 'share/cmake/modules/install'
|
||||
# Keep upstream's dependency options and target wiring, replacing only network retrieval.
|
||||
for name, (archive, sha) in archives.items():
|
||||
if name == 'OpenColorIO': continue
|
||||
filename = modules / ('Install' + ('ZLIB' if name == 'zlib' else name) + '.cmake')
|
||||
text = filename.read_text()
|
||||
text, count = re.subn(r'(?m)^\s*GIT_REPOSITORY[^\n]*\n\s*GIT_TAG[^\n]*',
|
||||
'\n URL "' + str(archive) + '"\n URL_HASH SHA256=' + sha + '\n DOWNLOAD_EXTRACT_TIMESTAMP TRUE', text)
|
||||
if count != 1: raise ValueError('Upstream install recipe changed: ' + name)
|
||||
text = re.sub(r'(?m)^\s*GIT_(CONFIG|SHALLOW)[^\n]*\n', '', text)
|
||||
filename.write_text(text)
|
||||
# This is a private, versioned runtime. A host's OCIO_OPTIMIZATION_FLAGS
|
||||
# must not silently override the precision explicitly chosen by the product.
|
||||
processor = source / 'src/OpenColorIO/Processor.cpp'
|
||||
text = processor.read_text()
|
||||
text, count = re.subn(r'OptimizationFlags EnvironmentOverride\(OptimizationFlags oFlags\)\n\{.*?\n\}',
|
||||
'OptimizationFlags EnvironmentOverride(OptimizationFlags oFlags)\n{\n return oFlags; // Dayu: fixed per-processor precision; ignore process environment.\n}', text, flags=re.S)
|
||||
if count != 1: raise ValueError('Upstream optimization override changed')
|
||||
processor.write_text(text)
|
||||
flags = ['-DCMAKE_BUILD_TYPE=Release', '-DCMAKE_OSX_ARCHITECTURES=arm64',
|
||||
'-DCMAKE_OSX_DEPLOYMENT_TARGET=14.6', '-DBUILD_SHARED_LIBS=OFF',
|
||||
'-DCMAKE_INSTALL_PREFIX=' + str(install), '-DCMAKE_INSTALL_LIBDIR=lib',
|
||||
'-DOCIO_NAMESPACE=' + lock['namespace'], '-DOCIO_INSTALL_EXT_PACKAGES=ALL',
|
||||
'-DOCIO_BUILD_APPS=OFF', '-DOCIO_BUILD_PYTHON=OFF', '-DOCIO_BUILD_TESTS=OFF',
|
||||
'-DOCIO_BUILD_GPU_TESTS=OFF', '-DOCIO_BUILD_DOCS=OFF', '-DOCIO_BUILD_JAVA=OFF',
|
||||
'-DOCIO_BUILD_NUKE=OFF', '-DOCIO_BUILD_OPENFX=OFF']
|
||||
environment = dict(os.environ, CMAKE_BUILD_PARALLEL_LEVEL='6')
|
||||
for args in ([cmake, '-S', source, '-B', build_dir] + flags,
|
||||
[cmake, '--build', build_dir, '--parallel', '6'],
|
||||
[cmake, '--install', build_dir]):
|
||||
subprocess.run([str(x) for x in args], check=True, env=environment)
|
||||
libraries = [install / 'lib/libOpenColorIO.a'] + sorted((build_dir / 'ext/dist/lib').glob('*.a'))
|
||||
if len(libraries) != 7 or not all(p.is_file() for p in libraries):
|
||||
raise ValueError('Expected OCIO and six pinned static dependencies')
|
||||
result = dict(identity=identity, compiler=compiler, sdk=sdk, namespace=lock['namespace'],
|
||||
include=str(install / 'include'), libraries={str(p): digest(p) for p in libraries},
|
||||
builtin_config=lock['builtin_config'])
|
||||
stamp.write_text(json.dumps(result, indent=2) + '\n')
|
||||
return result
|
||||
|
||||
def build():
|
||||
CACHE.mkdir(parents=True, exist_ok=True)
|
||||
with (CACHE / 'build.lock').open('a') as guard:
|
||||
fcntl.flock(guard, fcntl.LOCK_EX)
|
||||
return _build()
|
||||
|
||||
if __name__ == '__main__':
|
||||
print(json.dumps(build(), indent=2))
|
||||
@@ -0,0 +1,30 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build the pinned, ARC-isolated CMS bridge and a deterministic Xcode link file."""
|
||||
from pathlib import Path
|
||||
import hashlib, json, os, subprocess, sys, fcntl
|
||||
ROOT=Path(__file__).resolve().parent
|
||||
sys.path.insert(0,str(ROOT/'Tools'))
|
||||
from build_ocio import build
|
||||
CACHE=Path('/Users/mac/Library/Caches/CodexBuilds/com.dayu.color/cms-runtime')
|
||||
def prepare():
|
||||
runtime=build();work=CACHE/'bridge';work.mkdir(parents=True,exist_ok=True)
|
||||
with (work/'build.lock').open('a') as guard:
|
||||
fcntl.flock(guard,fcntl.LOCK_EX)
|
||||
sources=[p for p in sorted((ROOT/'Sources').glob('*.cpp'))+sorted((ROOT/'Sources').glob('*.mm')) if not p.name.startswith('._')]
|
||||
inputs=sources+[p for p in sorted((ROOT/'Sources').glob('*.h'))+sorted((ROOT/'Core').glob('*.h*')) if not p.name.startswith('._')]+[Path(__file__)]
|
||||
key=hashlib.sha256((json.dumps(runtime,sort_keys=True)+''.join(hashlib.sha256(p.read_bytes()).hexdigest() for p in inputs)).encode()).hexdigest()
|
||||
stamp=work/'build.json';library=work/'libDayuColorManagement.a'
|
||||
if not stamp.exists() or json.loads(stamp.read_text()).get('key')!=key or not library.exists():
|
||||
objects=[]
|
||||
for src in sources:
|
||||
obj=work/(src.stem+'.o');args=['xcrun','clang++','-std=c++20','-O2','-arch','arm64','-mmacosx-version-min=14.6','-I',runtime['include'],'-c',str(src),'-o',str(obj)]
|
||||
if src.suffix=='.mm':args.insert(2,'-fobjc-arc')
|
||||
subprocess.run(args,check=True);objects.append(str(obj))
|
||||
subprocess.run(['xcrun','libtool','-static','-o',str(library),*objects],check=True)
|
||||
stamp.write_text(json.dumps(dict(key=key,librarySHA256=hashlib.sha256(library.read_bytes()).hexdigest()),indent=2)+'\n')
|
||||
frameworks=['CoreGraphics','CoreImage','ColorSync','IOKit']
|
||||
args=['-ObjC',str(library),*runtime['libraries']]
|
||||
for name in frameworks:args+=['-framework',name]
|
||||
response=CACHE/'bridge-link.rsp';response.write_text('\n'.join('"'+s.replace('"','\\"')+'"' for s in args)+'\n')
|
||||
return str(response)
|
||||
if __name__=='__main__':print(prepare())
|
||||
在新工单中引用
屏蔽一个用户