Skip to content

Instantly share code, notes, and snippets.

@agyild
Last active November 18, 2026 02:44
Show Gist options
  • Select an option

  • Save agyild/bbb4e58298b2f86aa24da3032a0d2ee6 to your computer and use it in GitHub Desktop.

Select an option

Save agyild/bbb4e58298b2f86aa24da3032a0d2ee6 to your computer and use it in GitHub Desktop.
AMD FidelityFX Contrast Adaptive Sharpening v1.2 for mpv
// LICENSE
// =======
// Copyright (c) 2017-2019 Advanced Micro Devices, Inc. All rights reserved.
// -------
// 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.
// FidelityFX Contrast Adaptive Sharpening 1.2 by AMD
// ported to mpv by agyild
// Changelog
// 2022
// - Optimized texture lookups for OpenGL 4.0+, DirectX 10+, and OpenGL ES 3.1+
// - Changed rcp + mul operations to div for better clarity when CAS_GO_SLOWER is set to 1, since the compiler should automatically
// optimize those instructions anyway.
// - Made it directly operate on LUMA plane, since the original shader was operating on LUMA by deriving it from RGB. This should
// cause a major increase in performance, especially on OpenGL 4.0+ renderers (4 texture lookups vs. 16)
// - Removed transparency preservation mechanism since the alpha channel is a separate source plan than LUMA
// - Removed final blending between the original and the sharpened pixels since it was redundant
//
// 2026-11-17
// - Replaced the hardcoded TRC functions with libplacebo's builtin linearize/delinearize functions
// - Added tunable parameter support
// - SHARPENING is renamed as Sharpness to follow the same convention as the other shaders (i.e., NIS, FSR, SGSR)
// - CAS_GO_SLOWER parameter is renamed as UsePreciseMath as per FidelityFX SDK v1.1.4
// - Replaced per-pixel peak divisions with a precomputed reciprocal multiply and collapsed the 12-tap filter weighting and normalization into dot() products
// - Deduplicated shared center-texel min/max bounds across overlapping neighborhoods and balanced reduction trees for ILP
// - Vectorized the four sub-quadrant calculations (including APrxLoSqrtF4 and APrxLoRcpF4) into vec4 SIMD operations
// - Added //!COMPONENTS 1 to enforce single-channel intermediate FBOs, simplified //!WHEN RPN expressions, and eliminated dead channel writes
// - Simplified bilinear interpolation weights and factored out shared texture coordinate offsets in HOOKED_gather
// - Changed UsePreciseMath default from 0 to 1 for better precision and SFU utilization on modern GPUs
// Notes
// - Per AMD's guidelines only upscales content up to 4x (e.g., 1080p -> 2160p, 720p -> 1440p etc.) and everything else in between,
// that means CAS will scale up to 4x at maximum, and any further scaling will be processed by mpv's scalers
// User variables
//!PARAM Sharpness
//!DESC Adjusts the range the shader adapts to high contrast (0 is not all the way off). Higher values = more high contrast sharpening.
//!TYPE CONSTANT float
//!MINIMUM 0.0
//!MAXIMUM 1.0
0.0
//!PARAM BetterDiagonals
//!DESC If set to 0, drops certain math and texture lookup operations for better performance. This is only useful on pre-OpenGL 4.0 renderers and there is no need to disable it otherwise.
//!TYPE DEFINE
//!MINIMUM 0
//!MAXIMUM 1
1
//!PARAM UsePreciseMath
//!DESC If set to 1, disables the use of optimized approximate transcendental functions which might slightly increase accuracy in exchange of performance.
//!TYPE DEFINE
//!MINIMUM 0
//!MAXIMUM 1
1
//!HOOK LUMA
//!BIND HOOKED
//!DESC FidelityFX Contrast Adaptive Upsampling and Sharpening (CAS) v1.2 (Linearization pass)
//!WHEN OUTPUT.w OUTPUT.h * LUMA.w LUMA.h * >
//!COMPONENTS 1
vec4 hook() {
return vec4(linearize(HOOKED_tex(HOOKED_pos)).r, 0.0, 0.0, 1.0);
}
//!HOOK LUMA
//!BIND HOOKED
//!DESC FidelityFX Contrast Adaptive Upsampling and Sharpening (CAS) v1.2 (Upsampling and sharpening pass)
//!WHEN OUTPUT.w OUTPUT.h * LUMA.w LUMA.h * >
//!WIDTH OUTPUT.w OUTPUT.w LUMA.w 2 * < * LUMA.w 2 * OUTPUT.w LUMA.w 2 * > * + OUTPUT.w OUTPUT.w LUMA.w 2 * = * +
//!HEIGHT OUTPUT.h OUTPUT.h LUMA.h 2 * < * LUMA.h 2 * OUTPUT.h LUMA.h 2 * > * + OUTPUT.h OUTPUT.h LUMA.h 2 * = * +
//!COMPONENTS 1
// Shader code
#if (UsePreciseMath == 0)
vec4 APrxLoSqrtF4(vec4 a) {
return uintBitsToFloat((floatBitsToUint(a) >> 1u) + 0x1fbc4639u);
}
vec4 APrxLoRcpF4(vec4 a) {
return uintBitsToFloat(0x7ef07ebbu - floatBitsToUint(a));
}
float APrxMedRcpF1(float a) {
float b = uintBitsToFloat(0x7ef19fffu - floatBitsToUint(a));
return b * (-b * a + 2.0);
}
#endif
vec4 hook()
{
// Scaling algorithm adaptively interpolates between nearest 4 results of the non-scaling algorithm.
// a b c d
// e f g h
// i j k l
// m n o p
// Working these 4 results.
// +-----+-----+
// | | |
// | f..|..g |
// | . | . |
// +-----+-----+
// | . | . |
// | j..|..k |
// | | |
// +-----+-----+
vec2 pp = HOOKED_pos * HOOKED_size - 0.5;
vec2 fp = floor(pp);
pp -= fp;
#if (defined(HOOKED_gather) && (__VERSION__ >= 400 || (GL_ES && __VERSION__ >= 310)))
vec2 base = (fp - 0.5) * HOOKED_pt;
vec2 step2 = 2.0 * HOOKED_pt;
vec4 abef = HOOKED_gather(base, 0);
float b = abef.z;
float e = abef.x;
float f = abef.y;
vec4 cdgh = HOOKED_gather(base + vec2(step2.x, 0.0), 0);
float c = cdgh.w;
float g = cdgh.x;
float h = cdgh.y;
vec4 ijmn = HOOKED_gather(base + vec2(0.0, step2.y), 0);
float i = ijmn.w;
float j = ijmn.z;
float n = ijmn.y;
vec4 klop = HOOKED_gather(base + step2, 0);
float k = klop.w;
float l = klop.z;
float o = klop.x;
#if (BetterDiagonals == 1)
float a = abef.w;
float d = cdgh.z;
float m = ijmn.x;
float p = klop.y;
#endif
#else
ivec2 sp = ivec2(fp);
#if (BetterDiagonals == 1)
float a = texelFetch(HOOKED_raw, sp + ivec2(-1, -1), 0).r * HOOKED_mul;
float d = texelFetch(HOOKED_raw, sp + ivec2( 2, -1), 0).r * HOOKED_mul;
float m = texelFetch(HOOKED_raw, sp + ivec2(-1, 2), 0).r * HOOKED_mul;
float p = texelFetch(HOOKED_raw, sp + ivec2( 2, 2), 0).r * HOOKED_mul;
#endif
float b = texelFetch(HOOKED_raw, sp + ivec2( 0, -1), 0).r * HOOKED_mul;
float e = texelFetch(HOOKED_raw, sp + ivec2(-1, 0), 0).r * HOOKED_mul;
float f = texelFetch(HOOKED_raw, sp , 0).r * HOOKED_mul;
float c = texelFetch(HOOKED_raw, sp + ivec2( 1, -1), 0).r * HOOKED_mul;
float g = texelFetch(HOOKED_raw, sp + ivec2( 1, 0), 0).r * HOOKED_mul;
float h = texelFetch(HOOKED_raw, sp + ivec2( 2, 0), 0).r * HOOKED_mul;
float i = texelFetch(HOOKED_raw, sp + ivec2(-1, 1), 0).r * HOOKED_mul;
float j = texelFetch(HOOKED_raw, sp + ivec2( 0, 1), 0).r * HOOKED_mul;
float n = texelFetch(HOOKED_raw, sp + ivec2( 0, 2), 0).r * HOOKED_mul;
float k = texelFetch(HOOKED_raw, sp + ivec2( 1, 1), 0).r * HOOKED_mul;
float l = texelFetch(HOOKED_raw, sp + ivec2( 2, 1), 0).r * HOOKED_mul;
float o = texelFetch(HOOKED_raw, sp + ivec2( 1, 2), 0).r * HOOKED_mul;
#endif
// Soft min and max across [F, G, J, K] (2.0x bigger when BetterDiagonals == 1).
// Deduplicate shared horizontal center pairs (f, g) and (j, k) across adjacent neighborhoods.
vec2 mn_fg_jk = min(vec2(f, j), vec2(g, k));
vec2 mx_fg_jk = max(vec2(f, j), vec2(g, k));
vec4 mn = min(min(mn_fg_jk.xxyy, vec4(b, c, f, g)), min(vec4(e, h, i, l), vec4(j, k, n, o)));
vec4 mx = max(max(mx_fg_jk.xxyy, vec4(b, c, f, g)), max(vec4(e, h, i, l), vec4(j, k, n, o)));
#if (BetterDiagonals == 1)
mn += min(mn, min(min(vec4(a, b, e, f), vec4(c, d, g, h)), min(vec4(i, j, m, n), vec4(k, l, o, p))));
mx += max(mx, max(max(vec4(a, b, e, f), vec4(c, d, g, h)), max(vec4(i, j, m, n), vec4(k, l, o, p))));
#endif
// Smooth minimum distance to signal limit divided by smooth max, shaped with sqrt.
const float bdval = bool(BetterDiagonals) ? 2.0 : 1.0;
const float thinB = 0.03125; // 1.0 / 32.0
// Bilinear weights: one multiply + three subtracts instead of four multiplies.
float v = pp.x * pp.y;
float t = pp.x - v;
float u = pp.y - v;
float s = 1.0 - pp.x - u;
vec4 stuv = vec4(s, t, u, v);
#if (UsePreciseMath == 1)
vec4 amp = sqrt(clamp(min(mn, bdval - mx) / mx, 0.0, 1.0));
stuv /= thinB + mx - mn;
#else
vec4 amp = APrxLoSqrtF4(clamp(min(mn, bdval - mx) * APrxLoRcpF4(mx), 0.0, 1.0));
stuv *= APrxLoRcpF4(thinB + mx - mn);
#endif
// Filter shape.
// 0 w 0
// w 1 w
// 0 w 0
const float invPeak = -1.0 / mix(8.0, 5.0, clamp(Sharpness, 0.0, 1.0));
vec4 w = amp * invPeak;
// Final weighting.
// b c
// e f g h
// i j k l
// n o
// _____ _____ _____ _____
// fs gt
//
// _____ _____ _____ _____
// fs s gt fs t gt
// ju kv
// _____ _____ _____ _____
// fs gt
// ju u kv ju v kv
// _____ _____ _____ _____
//
// ju kv
vec4 q = w * stuv;
vec2 gj_fk = vec2(g + j, f + k);
vec4 outer = vec4(b + e, c + h, i + n, l + o) + gj_fk.xyyx;
// Filter.
float W = dot(4.0 * q + stuv, vec4(1.0));
float res = dot(outer, q) + dot(vec4(f, g, j, k), stuv);
#if (UsePreciseMath == 1)
res /= W;
#else
res *= APrxMedRcpF1(W);
#endif
return vec4(delinearize(vec4(res, 0.0, 0.0, 1.0)).r, 0.0, 0.0, 1.0);
}
// LICENSE
// =======
// Copyright (c) 2017-2019 Advanced Micro Devices, Inc. All rights reserved.
// -------
// 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.
// FidelityFX Contrast Adaptive Sharpening 1.2 by AMD
// ported to mpv by agyild
// Changelog
// 2022
// - Optimized texture lookups for OpenGL 4.0+, DirectX 10+, and OpenGL ES 3.1+
// - Changed rcp + mul operations to div for better clarity when CAS_GO_SLOWER is set to 1, since the compiler should automatically
// optimize those instructions anyway.
// - Made it directly operate on LUMA plane, since the original shader was operating on LUMA by deriving it from RGB. This should
// cause a major increase in performance, especially on OpenGL 4.0+ renderers (4 texture lookups vs. 16)
// - Removed transparency preservation mechanism since the alpha channel is a separate source plan than LUMA
// - Removed final blending between the original and the sharpened pixels since it was redundant
//
// 2026-11-17
// - Replaced the hardcoded TRC functions with libplacebo's builtin linearize/delinearize functions
// - Added tunable parameter support
// - SHARPENING is renamed as Sharpness to follow the same convention as the other shaders (i.e., NIS, FSR, SGSR)
// - CAS_GO_SLOWER parameter is renamed as UsePreciseMath as per FidelityFX SDK v1.1.4
// - Removed the !WHEN constraint which should always apply the sharpen effect, not just for non-scaled playback
// - Replaced per-pixel peak division with a precomputed reciprocal multiply (invPeak)
// - Replaced HOOKED_texOff calls with integer texelFetch lookups on HOOKED_raw and factored out shared HOOKED_gather offsets
// - Added //!COMPONENTS 1 to both passes and eliminated dead channel writes in the linearization pass
// - Changed UsePreciseMath default from 0 to 1 for better precision and SFU utilization on modern GPUs
// User variables
//!PARAM Sharpness
//!DESC Adjusts the range the shader adapts to high contrast (0 is not all the way off). Higher values = more high contrast sharpening.
//!TYPE CONSTANT float
//!MINIMUM 0.0
//!MAXIMUM 1.0
0.0
//!PARAM BetterDiagonals
//!DESC If set to 0, drops certain math and texture lookup operations for better performance. This is only useful on pre-OpenGL 4.0 renderers and there is no need to disable it otherwise.
//!TYPE DEFINE
//!MINIMUM 0
//!MAXIMUM 1
1
//!PARAM UsePreciseMath
//!DESC If set to 1, disables the use of optimized approximate transcendental functions which might slightly increase accuracy in exchange of performance.
//!TYPE DEFINE
//!MINIMUM 0
//!MAXIMUM 1
1
//!HOOK LUMA
//!BIND HOOKED
//!DESC FidelityFX Contrast Adaptive Sharpening (CAS) v1.2 (Linearization pass)
//!COMPONENTS 1
// libplacebo's linearize() builtin converts the video's tagged transfer characteristics to linear light.
vec4 hook() {
return vec4(linearize(HOOKED_tex(HOOKED_pos)).r, 0.0, 0.0, 1.0);
}
//!HOOK LUMA
//!BIND HOOKED
//!DESC FidelityFX Contrast Adaptive Sharpening (CAS) v1.2 (Sharpening pass)
//!COMPONENTS 1
// Shader code
#if (UsePreciseMath == 0)
float APrxLoSqrtF1(float a) {
return uintBitsToFloat((floatBitsToUint(a) >> uint(1)) + uint(0x1fbc4639));
}
float APrxLoRcpF1(float a) {
return uintBitsToFloat(uint(0x7ef07ebb) - floatBitsToUint(a));
}
float APrxMedRcpF1(float a) {
float b = uintBitsToFloat(uint(0x7ef19fff) - floatBitsToUint(a));
return b * (-b * a + float(2.0));
}
#endif
vec4 hook()
{
// fetch a 3x3 neighborhood around the pixel 'e',
// a b c
// d(e)f
// g h i
#if (defined(HOOKED_gather) && (__VERSION__ >= 400 || (GL_ES && __VERSION__ >= 310)))
vec2 half_pt = 0.5 * HOOKED_pt;
vec4 efhi = HOOKED_gather(HOOKED_pos + half_pt, 0);
float e = efhi.w;
float f = efhi.z;
float h = efhi.x;
vec3 abd = HOOKED_gather(HOOKED_pos - half_pt, 0).wzx;
float b = abd.y;
float d = abd.z;
#if (BetterDiagonals == 1)
float a = abd.x;
float i = efhi.y;
ivec2 sp = ivec2(HOOKED_pos * HOOKED_size);
float c = texelFetch(HOOKED_raw, sp + ivec2( 1, -1), 0).r * HOOKED_mul;
float g = texelFetch(HOOKED_raw, sp + ivec2(-1, 1), 0).r * HOOKED_mul;
#endif
#else
ivec2 sp = ivec2(HOOKED_pos * HOOKED_size);
float e = texelFetch(HOOKED_raw, sp , 0).r * HOOKED_mul;
float f = texelFetch(HOOKED_raw, sp + ivec2( 1, 0), 0).r * HOOKED_mul;
float h = texelFetch(HOOKED_raw, sp + ivec2( 0, 1), 0).r * HOOKED_mul;
float b = texelFetch(HOOKED_raw, sp + ivec2( 0, -1), 0).r * HOOKED_mul;
float d = texelFetch(HOOKED_raw, sp + ivec2(-1, 0), 0).r * HOOKED_mul;
#if (BetterDiagonals == 1)
float a = texelFetch(HOOKED_raw, sp + ivec2(-1, -1), 0).r * HOOKED_mul;
float c = texelFetch(HOOKED_raw, sp + ivec2( 1, -1), 0).r * HOOKED_mul;
float g = texelFetch(HOOKED_raw, sp + ivec2(-1, 1), 0).r * HOOKED_mul;
float i = texelFetch(HOOKED_raw, sp + ivec2( 1, 1), 0).r * HOOKED_mul;
#endif
#endif
// Soft min and max.
// a b c b
// d e f * 0.5 + d e f * 0.5
// g h i h
// These are 2.0x bigger (factored out the extra multiply).
float mnL = min(min(min(d, e), min(f, b)), h);
float mxL = max(max(max(d, e), max(f, b)), h);
#if (BetterDiagonals == 1)
float mnL2 = min(mnL, min(min(a, c), min(g, i)));
mnL += mnL2;
float mxL2 = max(mxL, max(max(a, c), max(g, i)));
mxL += mxL2;
#endif
// Smooth minimum distance to signal limit divided by smooth max.
const float bdval = bool(BetterDiagonals) ? 2.0 : 1.0;
#if (UsePreciseMath == 1)
float ampL = clamp(min(mnL, bdval - mxL) / mxL, 0.0, 1.0);
#else
float ampL = clamp(min(mnL, bdval - mxL) * APrxLoRcpF1(mxL), 0.0, 1.0);
#endif
// Shaping amount of sharpening.
#if (UsePreciseMath == 1)
ampL = sqrt(ampL);
#else
ampL = APrxLoSqrtF1(ampL);
#endif
// Filter shape.
// 0 w 0
// w 1 w
// 0 w 0
const float invPeak = -1.0 / mix(8.0, 5.0, clamp(Sharpness, 0.0, 1.0));
float wL = ampL * invPeak;
// Filter.
// Using green coef only
float Weight = 1.0 + 4.0 * wL;
vec4 pix = vec4(0.0, 0.0, 0.0, 1.0);
pix.r = ((b + d + f + h) * wL) + e;
#if (UsePreciseMath == 1)
pix.r /= Weight;
#else
pix.r *= APrxMedRcpF1(Weight);
#endif
pix.r = delinearize(pix).r;
return pix;
}
@haasn

haasn commented Jan 15, 2022

Copy link
Copy Markdown
// Changed saturate(x) to lerp(x, 0.0, 1.0)

You mean clamp(x, 0.0, 1.0)

@agyild

agyild commented Jan 15, 2022

Copy link
Copy Markdown
Author

You mean clamp(x, 0.0, 1.0)

@haasn That's right, it was a typo error in comments. Fixed.

@CrHasher

Copy link
Copy Markdown

"You might want to create seperate versions of the file with different colorspace values, and apply them via autoprofiles." - How does one do that?
TARGET_TRC - what about gamma2.2?

@agyild

agyild commented Feb 18, 2022 •

Copy link
Copy Markdown
Author

"You might want to create seperate versions of the file with different colorspace values, and apply them via autoprofiles." - How does one do that?
TARGET_TRC - what about gamma2.2?

Change SOURCE_TRC and TARGET_TRC to gamma curves of your own choosing, and then duplicate the file with a new name, and apply the newly created shader with autoprofile and/or scripting mechanism.

You won't find many gamma 2.2 content in the wild, the most popular gamma curves will be either BT.1886 (2.4) or PQ. If you want to add support for gamma 2.2 you can modify the shader and add it for yourself; just duplicate BT.1886 (4th) TRC sections in the code and change the value 2.4 inside the code block to 2.2.

Edit: With the most recent update, now it is possible to use a custom power gamma curve for CAS-scaled.glsl by changing SOURCE_TRC and TARGET_TRC to 6, and modifying CUSTOM_GAMMA to a value of your own choosing.

@CrHasher

CrHasher commented Feb 19, 2022 •

Copy link
Copy Markdown

Think I will just skip conversion altogether setting SOURCE_TRC and TARGET_TRC to 0.
I'm reluctant to use such baked in options and assume a source trc and do double conversion for target trc. Until the video frame reaches CAS shader doesn't mpv already convert the frame to some trc based on source and than when presenting convert to a target trc? In this case what is the point of the internal conversion in the shader?

@agyild

agyild commented Feb 19, 2022

Copy link
Copy Markdown
Author

Think I will just skip conversion altogether setting SOURCE_TRC and TARGET_TRC to 0.
I'm reluctant to use such baked in options and assume a source trc and do double conversion for target trc. Until the video frame reaches CAS shader doesn't mpv already convert the frame to some trc based on source and than when presenting convert to a target trc? In this case what is the point of the internal conversion in the shader?

See Issue #9818.

@CrHasher

Copy link
Copy Markdown

@agyild Can you please add same SOURCE_TRC and TARGET_TRC 6 option to CAS.glsl

@agyild

agyild commented Feb 20, 2022 •

Copy link
Copy Markdown
Author

@agyild Can you please add same SOURCE_TRC and TARGET_TRC 6 option to CAS.glsl

Done.

In addition, CAS.glsl also hooks LUMA, and only runs if the content is non-scaled. However, this behavior can be disabled by following the instructions in the comments to make it also work as a pre-upscale sharpener.

@CrHasher

CrHasher commented Feb 20, 2022 •

Copy link
Copy Markdown

Did some testing and here are my findings:

After the change to make CAS.glsl use LUMA it does not work anymore:
1CAS-luma-inf-Screenshot 2022-02-20 122239

And sharpening without scaling is IMO not recommended because all the sharpening artifacts get scaled at a later stage, why make CAS a pre-scale filter?:
2CAS-luma-prescale-inf-Screenshot 2022-02-20 122239
Scaling should always happen before sharpening most of the time. With sharpening you want to restore some missing information in the signal, but you don't want any mistakes made by your sharpening algorithm to be made more visible by scaling. This is why IMO most sharpeners use RGB.

The RGB version for CAS.glsl was ok:
0CAS-rgb-inf-Screenshot 2022-02-20 122804

@agyild

agyild commented Feb 20, 2022 •

Copy link
Copy Markdown
Author

The "RGB" version of CAS was actually worse because it was directly making sharpening calculations on the green channel by default. The shaders don't do anything at all with RGB data, it's all done on LUMA. They are designed to derive LUMA from RGB, because video game renderers do not have separate CHROMA and LUMA channels like in video content. The most recent version of CAS.glsl doesn't do pre-upscale sharpening, unless you modify the WHEN directive to do so. CAS.glsl should be used for 1:1 scaling, for upscaling you should use CAS-scaled.glsl.

Also in your screenshot, you have only modified the first WHEN directive in the relinearization pass. You have to modify both WHEN directives for it to properly work as a pre-upscale sharpener.

@CrHasher

CrHasher commented Feb 20, 2022 •

Copy link
Copy Markdown

I did miss the second when condition, but if I did not modify any WHEN condition the CAS was not applied at all. Even so I see CAS as something applied after scaling not as a pre-scaling sharpening shader. FSR does scaling first RCAS after and not without a reason, you want to sharpen after scaling for better results. Can you make CAS be applied after other LUMA scalers? One such example FSRCNN or any other LUMA scalers?

@agyild

agyild commented Feb 22, 2022 •

Copy link
Copy Markdown
Author

I did miss the second when condition, but if I did not modify any WHEN condition the CAS was not applied at all. Even so I see CAS as something applied after scaling not as a pre-scaling sharpening shader. FSR does scaling first RCAS after and not without a reason, you want to sharpen after scaling for better results. Can you make CAS be applied after other LUMA scalers? One such example FSRCNN or any other LUMA scalers?

It is already possible to do it in cases where the video resolution is 50% of the output resolution at maximum (considering the luma upscaler does 4x area scaling). Make sure that CAS.glsl is applied after the other luma scaler. For example:

glsl-shader=~~/shaders/FSRCNNX_x2_16-0-4-1.glsl
glsl-shader=~~/shaders/CAS.glsl

So in this case by the time CAS.glsl runs the luma texture will be 1:1 to OUTPUT which will trigger CAS. In other cases where you have a smaller video, you have to apply the RGB version of CAS since scale works on RGB texture, and LUMA remains unscaled, in which case if sharpened would result in pre-scale sharpening. Or if you don't care about that just modify the WHEN directive as shown in the comments, and in that case CAS will always sharpen the pre-scaled LUMA.

@CrHasher

CrHasher commented Mar 23, 2022 •

Copy link
Copy Markdown

Can you elaborate a bit more on why CAS can't be used as a post scaling sharpener, removing the WHEN condition completely from CAS.glsl and adding it after FSRCNNX I see CAS is being applied at the last stage of LUMA processing:
image

Why does CAS care if the LUMA is upscaled or not? All it should work on is a LUMA you give it scaled or not scaled.

But interesting enough pre-scale sharpening is way more pronounced than post-scale sharpening with CAS:
CAS+FSRCNNX
CAS+FSRCNNX
FSRCNNX+CAS
FSRCNNX+CAS

FSRCNNX (for reference)
FSRCNNX

Does CAS use some info on how much sharpening it should do based on image size vs. display size?

@agyild

agyild commented Mar 23, 2022

Copy link
Copy Markdown
Author

Because this is a reference implementation of CAS algorithm and it is originally not designed to be used as pre-scaling sharpener. In video game implementations it either sharpens the native rendered output or it upscales and sharpens the lower resolution output. By default I am trying to emulate this behavior.

The directives are there so the users get this intended effect. It does not stop one from modifying the code to remove this limit or create their own fork. If you know what you are doing you can use it in any way that you would like. Note that due to how mpv works, it is only possible to use CAS as a post-scaling sharpener when the LUMA channel is resized to the exact size of the output beforehand (e.g., FSRCNNX(720p) -> 1440p on 1440p output).

@CrHasher

CrHasher commented Mar 23, 2022 •

Copy link
Copy Markdown

Makes more sense now. FSRCNNX is a double-er the LUMA at the stage CAS has access to it is a LUMA bigger than even the display size for most content like 1080p on 1440p display (because I forced CAS to be used after FSRCNNX and before downscaling with lanczos). For the post-scale sharpening CAS-rgb would be needed to be able to process the upscaled+downscaled final frame.

I did propose that FSR.glsl should be changed to work on LUMA because it made sense there, but I'm still not convinced that the change to LUMA in CAS.glsl makes sense. The unchanged CAS.glsl that is a 1:1 sharpener has a very limited use-case and as soon as you insert another shader it is most likely not used anymore. The changed CAS.glsl (by modifying the WHEN condition) used as a pre-scale sharpener makes the result have a lot of sharpening artifacts even more than FSR.

IMO and correct me if I'm wrong, but to make CAS.glsl more useful it would make more sense to have a step in the shader that saves LUMA information after scale/dscale (not sure if its possible because internal scalers are rgb) and use that info in CAS-rgb instead of GREEN channel. This would make CAS a post-scale sharpener useful with any combination of other shaders.

This is what I would find useful for this CAS.glsl:
any-scaler + CAS-rgb sharpener

Aren't any of these shaders doing it like this?

Or maybe recreate LUMA from RGB if all else fails (instead of using GREEN channel), something similar to adaptive-sharpen.glsl

// RGB to luma
    float luma[25] = float[](CtL(c[0]), CtL(c[1]), CtL(c[2]), CtL(c[3]), CtL(c[4]), CtL(c[5]), CtL(c[6]),
                             CtL(c[7]),  CtL(c[8]),  CtL(c[9]),  CtL(c[10]), CtL(c[11]), CtL(c[12]),
                             CtL(c[13]), CtL(c[14]), CtL(c[15]), CtL(c[16]), CtL(c[17]), CtL(c[18]),
                             CtL(c[19]), CtL(c[20]), CtL(c[21]), CtL(c[22]), CtL(c[23]), CtL(c[24]));

ghost commented Apr 26, 2024 •

Copy link
Copy Markdown

Hello, I liked this shader so much since it is not that aggressive (not scaled one). How can I make this work on all resolutions. Probably I have to change this but dunno change to what.

//!WHEN OUTPUT.w OUTPUT.h * LUMA.w LUMA.h * / 1.0 > ! OUTPUT.w OUTPUT.h * LUMA.w LUMA.h * / 1.0 < ! *

@christoph-heinrich

Copy link
Copy Markdown

@fideliochan You can remove all !WHEN lines to make it resolution independent.

ghost commented Apr 26, 2024

Copy link
Copy Markdown

@christoph-heinrich it worked, thank you so much!

@agyild

agyild commented Nov 18, 2026

Copy link
Copy Markdown
Author

Minor update, full details are in the changelog of each shader. But here is the important stuff:

  • Tunable parameter support (now requires vo=gpu-next):
    # Example parameter configuration. Parameters can be applied to both shaders.
    glsl-shader-opts=CAS-scaled/Sharpness=0.5
    glsl-shader-opts=CAS-scaled/BetterDiagonals=1
    glsl-shader-opts=CAS/UsePreciseMath=1
  • CAS.glsl now applies in every condition, not just for 1:1 non-scaled content. Meaning it can be used freely for post and pre-sharpening. If you want to restrict it to only non-scaled content, you can do so using conditional auto profiles.
  • SOURCE_TRC and TARGET_TRC parameters have been removed and are no longer needed thanks to libplacebo's built-in linearize/delinearize functions. This step should now be automated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment