blob: 0a30c6c14c4c99b1fe2e156c0ae4d990d8b17235 [file] [log] [blame]
John Reck115195e2023-02-01 20:57:44 -05001/*
2 * Copyright (C) 2023 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "GainmapRenderer.h"
18
19#include <SkGainmapShader.h>
20
21#include "Gainmap.h"
22#include "Rect.h"
23#include "utils/Trace.h"
24
25#ifdef __ANDROID__
John Reck7beba3c2023-03-07 20:18:26 -050026#include "include/core/SkColorSpace.h"
27#include "include/core/SkImage.h"
28#include "include/core/SkShader.h"
29#include "include/effects/SkRuntimeEffect.h"
30#include "include/private/SkGainmapInfo.h"
John Reck115195e2023-02-01 20:57:44 -050031#include "renderthread/CanvasContext.h"
John Reck7beba3c2023-03-07 20:18:26 -050032#include "src/core/SkColorFilterPriv.h"
33#include "src/core/SkImageInfoPriv.h"
34#include "src/core/SkRuntimeEffectPriv.h"
Nolan Scobied84b3da2024-04-18 20:49:08 +000035
36#include <cmath>
John Reck115195e2023-02-01 20:57:44 -050037#endif
38
39namespace android::uirenderer {
40
41using namespace renderthread;
42
John Reck45fd4a52023-04-20 13:40:18 -040043float getTargetHdrSdrRatio(const SkColorSpace* destColorspace) {
John Reck7beba3c2023-03-07 20:18:26 -050044 // We should always have a known destination colorspace. If we don't we must be in some
45 // legacy mode where we're lost and also definitely not going to HDR
46 if (destColorspace == nullptr) {
47 return 1.f;
48 }
49
50 constexpr float GenericSdrWhiteNits = 203.f;
51 constexpr float maxPQLux = 10000.f;
52 constexpr float maxHLGLux = 1000.f;
53 skcms_TransferFunction destTF;
54 destColorspace->transferFn(&destTF);
55 if (skcms_TransferFunction_isPQish(&destTF)) {
56 return maxPQLux / GenericSdrWhiteNits;
57 } else if (skcms_TransferFunction_isHLGish(&destTF)) {
58 return maxHLGLux / GenericSdrWhiteNits;
John Reck7beba3c2023-03-07 20:18:26 -050059#ifdef __ANDROID__
John Reckaa584a32023-08-23 17:08:37 -040060 } else if (RenderThread::isCurrent()) {
John Reck7beba3c2023-03-07 20:18:26 -050061 CanvasContext* context = CanvasContext::getActiveContext();
62 return context ? context->targetSdrHdrRatio() : 1.f;
John Reck7beba3c2023-03-07 20:18:26 -050063#endif
64 }
John Reckaa584a32023-08-23 17:08:37 -040065 return 1.f;
John Reck7beba3c2023-03-07 20:18:26 -050066}
67
John Reck115195e2023-02-01 20:57:44 -050068void DrawGainmapBitmap(SkCanvas* c, const sk_sp<const SkImage>& image, const SkRect& src,
69 const SkRect& dst, const SkSamplingOptions& sampling, const SkPaint* paint,
70 SkCanvas::SrcRectConstraint constraint,
71 const sk_sp<const SkImage>& gainmapImage, const SkGainmapInfo& gainmapInfo) {
72 ATRACE_CALL();
73#ifdef __ANDROID__
John Reck7beba3c2023-03-07 20:18:26 -050074 auto destColorspace = c->imageInfo().refColorSpace();
75 float targetSdrHdrRatio = getTargetHdrSdrRatio(destColorspace.get());
John Reck115195e2023-02-01 20:57:44 -050076 if (targetSdrHdrRatio > 1.f && gainmapImage) {
77 SkPaint gainmapPaint = *paint;
78 float sX = gainmapImage->width() / (float)image->width();
79 float sY = gainmapImage->height() / (float)image->height();
80 SkRect gainmapSrc = src;
81 // TODO: Tweak rounding?
82 gainmapSrc.fLeft *= sX;
83 gainmapSrc.fRight *= sX;
84 gainmapSrc.fTop *= sY;
85 gainmapSrc.fBottom *= sY;
John Reck7beba3c2023-03-07 20:18:26 -050086 auto shader =
87 SkGainmapShader::Make(image, src, sampling, gainmapImage, gainmapSrc, sampling,
88 gainmapInfo, dst, targetSdrHdrRatio, destColorspace);
John Reck115195e2023-02-01 20:57:44 -050089 gainmapPaint.setShader(shader);
90 c->drawRect(dst, gainmapPaint);
91 } else
92#endif
93 c->drawImageRect(image.get(), src, dst, sampling, paint, constraint);
94}
95
John Reck7beba3c2023-03-07 20:18:26 -050096#ifdef __ANDROID__
97
98static constexpr char gGainmapSKSL[] = R"SKSL(
99 uniform shader base;
100 uniform shader gainmap;
101 uniform colorFilter workingSpaceToLinearSrgb;
102 uniform half4 logRatioMin;
103 uniform half4 logRatioMax;
104 uniform half4 gainmapGamma;
105 uniform half4 epsilonSdr;
106 uniform half4 epsilonHdr;
107 uniform half W;
108 uniform int gainmapIsAlpha;
109 uniform int gainmapIsRed;
110 uniform int singleChannel;
111 uniform int noGamma;
112
113 half4 toDest(half4 working) {
114 half4 ls = workingSpaceToLinearSrgb.eval(working);
115 vec3 dest = fromLinearSrgb(ls.rgb);
116 return half4(dest.r, dest.g, dest.b, ls.a);
117 }
118
119 half4 main(float2 coord) {
120 half4 S = base.eval(coord);
121 half4 G = gainmap.eval(coord);
122 if (gainmapIsAlpha == 1) {
123 G = half4(G.a, G.a, G.a, 1.0);
124 }
125 if (gainmapIsRed == 1) {
126 G = half4(G.r, G.r, G.r, 1.0);
127 }
128 if (singleChannel == 1) {
129 half L;
130 if (noGamma == 1) {
131 L = mix(logRatioMin.r, logRatioMax.r, G.r);
132 } else {
133 L = mix(logRatioMin.r, logRatioMax.r, pow(G.r, gainmapGamma.r));
134 }
135 half3 H = (S.rgb + epsilonSdr.rgb) * exp(L * W) - epsilonHdr.rgb;
136 return toDest(half4(H.r, H.g, H.b, S.a));
137 } else {
138 half3 L;
139 if (noGamma == 1) {
140 L = mix(logRatioMin.rgb, logRatioMax.rgb, G.rgb);
141 } else {
142 L = mix(logRatioMin.rgb, logRatioMax.rgb, pow(G.rgb, gainmapGamma.rgb));
143 }
144 half3 H = (S.rgb + epsilonSdr.rgb) * exp(L * W) - epsilonHdr.rgb;
145 return toDest(half4(H.r, H.g, H.b, S.a));
146 }
147 }
148)SKSL";
149
150static sk_sp<SkRuntimeEffect> gainmap_apply_effect() {
151 static const SkRuntimeEffect* effect = []() -> SkRuntimeEffect* {
152 auto buildResult = SkRuntimeEffect::MakeForShader(SkString(gGainmapSKSL), {});
153 if (buildResult.effect) {
154 return buildResult.effect.release();
155 } else {
156 LOG_ALWAYS_FATAL("Failed to build gainmap shader: %s", buildResult.errorText.c_str());
157 }
158 }();
159 SkASSERT(effect);
160 return sk_ref_sp(effect);
161}
162
163static bool all_channels_equal(const SkColor4f& c) {
164 return c.fR == c.fG && c.fR == c.fB;
165}
166
167class DeferredGainmapShader {
168private:
169 sk_sp<SkRuntimeEffect> mShader{gainmap_apply_effect()};
170 SkRuntimeShaderBuilder mBuilder{mShader};
171 SkGainmapInfo mGainmapInfo;
172 std::mutex mUniformGuard;
173
174 void setupChildren(const sk_sp<const SkImage>& baseImage,
175 const sk_sp<const SkImage>& gainmapImage, SkTileMode tileModeX,
176 SkTileMode tileModeY, const SkSamplingOptions& samplingOptions) {
177 sk_sp<SkColorSpace> baseColorSpace =
178 baseImage->colorSpace() ? baseImage->refColorSpace() : SkColorSpace::MakeSRGB();
179
180 // Determine the color space in which the gainmap math is to be applied.
181 sk_sp<SkColorSpace> gainmapMathColorSpace = baseColorSpace->makeLinearGamma();
182
183 // Create a color filter to transform from the base image's color space to the color space
184 // in which the gainmap is to be applied.
185 auto colorXformSdrToGainmap =
186 SkColorFilterPriv::MakeColorSpaceXform(baseColorSpace, gainmapMathColorSpace);
187
188 // The base image shader will convert into the color space in which the gainmap is applied.
189 auto baseImageShader = baseImage->makeRawShader(tileModeX, tileModeY, samplingOptions)
190 ->makeWithColorFilter(colorXformSdrToGainmap);
191
192 // The gainmap image shader will ignore any color space that the gainmap has.
193 const SkMatrix gainmapRectToDstRect =
194 SkMatrix::RectToRect(SkRect::MakeWH(gainmapImage->width(), gainmapImage->height()),
195 SkRect::MakeWH(baseImage->width(), baseImage->height()));
196 auto gainmapImageShader = gainmapImage->makeRawShader(tileModeX, tileModeY, samplingOptions,
197 &gainmapRectToDstRect);
198
199 // Create a color filter to transform from the color space in which the gainmap is applied
200 // to the intermediate destination color space.
201 auto colorXformGainmapToDst = SkColorFilterPriv::MakeColorSpaceXform(
202 gainmapMathColorSpace, SkColorSpace::MakeSRGBLinear());
203
204 mBuilder.child("base") = std::move(baseImageShader);
205 mBuilder.child("gainmap") = std::move(gainmapImageShader);
206 mBuilder.child("workingSpaceToLinearSrgb") = std::move(colorXformGainmapToDst);
207 }
208
209 void setupGenericUniforms(const sk_sp<const SkImage>& gainmapImage,
210 const SkGainmapInfo& gainmapInfo) {
Nolan Scobied84b3da2024-04-18 20:49:08 +0000211 const SkColor4f logRatioMin({std::log(gainmapInfo.fGainmapRatioMin.fR),
212 std::log(gainmapInfo.fGainmapRatioMin.fG),
213 std::log(gainmapInfo.fGainmapRatioMin.fB), 1.f});
214 const SkColor4f logRatioMax({std::log(gainmapInfo.fGainmapRatioMax.fR),
215 std::log(gainmapInfo.fGainmapRatioMax.fG),
216 std::log(gainmapInfo.fGainmapRatioMax.fB), 1.f});
John Reck7beba3c2023-03-07 20:18:26 -0500217 const int noGamma = gainmapInfo.fGainmapGamma.fR == 1.f &&
218 gainmapInfo.fGainmapGamma.fG == 1.f &&
219 gainmapInfo.fGainmapGamma.fB == 1.f;
220 const uint32_t colorTypeFlags = SkColorTypeChannelFlags(gainmapImage->colorType());
221 const int gainmapIsAlpha = colorTypeFlags == kAlpha_SkColorChannelFlag;
222 const int gainmapIsRed = colorTypeFlags == kRed_SkColorChannelFlag;
223 const int singleChannel = all_channels_equal(gainmapInfo.fGainmapGamma) &&
224 all_channels_equal(gainmapInfo.fGainmapRatioMin) &&
225 all_channels_equal(gainmapInfo.fGainmapRatioMax) &&
226 (colorTypeFlags == kGray_SkColorChannelFlag ||
227 colorTypeFlags == kAlpha_SkColorChannelFlag ||
228 colorTypeFlags == kRed_SkColorChannelFlag);
229 mBuilder.uniform("logRatioMin") = logRatioMin;
230 mBuilder.uniform("logRatioMax") = logRatioMax;
231 mBuilder.uniform("gainmapGamma") = gainmapInfo.fGainmapGamma;
232 mBuilder.uniform("epsilonSdr") = gainmapInfo.fEpsilonSdr;
233 mBuilder.uniform("epsilonHdr") = gainmapInfo.fEpsilonHdr;
234 mBuilder.uniform("noGamma") = noGamma;
235 mBuilder.uniform("singleChannel") = singleChannel;
236 mBuilder.uniform("gainmapIsAlpha") = gainmapIsAlpha;
237 mBuilder.uniform("gainmapIsRed") = gainmapIsRed;
238 }
239
240 sk_sp<const SkData> build(float targetHdrSdrRatio) {
241 sk_sp<const SkData> uniforms;
242 {
243 // If we are called concurrently from multiple threads, we need to guard the call
244 // to writableUniforms() which mutates mUniform. This is otherwise safe because
245 // writeableUniforms() will make a copy if it's not unique before mutating
246 // This can happen if a BitmapShader is used on multiple canvas', such as a
247 // software + hardware canvas, which is otherwise valid as SkShader is "immutable"
248 std::lock_guard _lock(mUniformGuard);
John Reck4ef70c22023-08-09 16:07:57 -0400249 // Compute the weight parameter that will be used to blend between the images.
250 float W = 0.f;
251 if (targetHdrSdrRatio > mGainmapInfo.fDisplayRatioSdr) {
252 if (targetHdrSdrRatio < mGainmapInfo.fDisplayRatioHdr) {
Nolan Scobied84b3da2024-04-18 20:49:08 +0000253 W = (std::log(targetHdrSdrRatio) -
254 std::log(mGainmapInfo.fDisplayRatioSdr)) /
255 (std::log(mGainmapInfo.fDisplayRatioHdr) -
256 std::log(mGainmapInfo.fDisplayRatioSdr));
John Reck4ef70c22023-08-09 16:07:57 -0400257 } else {
258 W = 1.f;
259 }
260 }
John Reck7beba3c2023-03-07 20:18:26 -0500261 mBuilder.uniform("W") = W;
262 uniforms = mBuilder.uniforms();
263 }
264 return uniforms;
265 }
266
267public:
268 explicit DeferredGainmapShader(const sk_sp<const SkImage>& image,
269 const sk_sp<const SkImage>& gainmapImage,
270 const SkGainmapInfo& gainmapInfo, SkTileMode tileModeX,
271 SkTileMode tileModeY, const SkSamplingOptions& sampling) {
272 mGainmapInfo = gainmapInfo;
273 setupChildren(image, gainmapImage, tileModeX, tileModeY, sampling);
274 setupGenericUniforms(gainmapImage, gainmapInfo);
275 }
276
277 static sk_sp<SkShader> Make(const sk_sp<const SkImage>& image,
278 const sk_sp<const SkImage>& gainmapImage,
279 const SkGainmapInfo& gainmapInfo, SkTileMode tileModeX,
280 SkTileMode tileModeY, const SkSamplingOptions& sampling) {
281 auto deferredHandler = std::make_shared<DeferredGainmapShader>(
282 image, gainmapImage, gainmapInfo, tileModeX, tileModeY, sampling);
283 auto callback =
284 [deferredHandler](const SkRuntimeEffectPriv::UniformsCallbackContext& renderContext)
285 -> sk_sp<const SkData> {
286 return deferredHandler->build(getTargetHdrSdrRatio(renderContext.fDstColorSpace));
287 };
288 return SkRuntimeEffectPriv::MakeDeferredShader(deferredHandler->mShader.get(), callback,
289 deferredHandler->mBuilder.children());
290 }
291};
292
293sk_sp<SkShader> MakeGainmapShader(const sk_sp<const SkImage>& image,
294 const sk_sp<const SkImage>& gainmapImage,
295 const SkGainmapInfo& gainmapInfo, SkTileMode tileModeX,
296 SkTileMode tileModeY, const SkSamplingOptions& sampling) {
297 return DeferredGainmapShader::Make(image, gainmapImage, gainmapInfo, tileModeX, tileModeY,
298 sampling);
299}
300
301#else // __ANDROID__
302
303sk_sp<SkShader> MakeGainmapShader(const sk_sp<const SkImage>& image,
304 const sk_sp<const SkImage>& gainmapImage,
305 const SkGainmapInfo& gainmapInfo, SkTileMode tileModeX,
306 SkTileMode tileModeY, const SkSamplingOptions& sampling) {
307 return nullptr;
308}
309
310#endif // __ANDROID__
311
John Reck115195e2023-02-01 20:57:44 -0500312} // namespace android::uirenderer