unity中使用shader增强视频

使用shader对视频texture做特效处理

该功能主要在片元着色器中实现,考虑到是移动设备,因此要兼顾考虑效果和性能。
在shader中的实现,这里只展示像素增强算法,关于shader的结构请看其他

变量

_MainTex

当前渲染的texture

_MainTex_TexelSize

_MainTex_TexelSize这个变量的从字面意思是主贴图 _MainTex 的像素尺寸大小,是一个四元数,是 unity 内置的变量,它的值为 Vector4(1 / width, 1 / height, width, height)

_ColorBoost

自定义关于亮度、对比度、饱和度、色弱调整的参数

1
"_ColorBoost",(_brightness, cont, _saturate, _daltonize * 10f));

_Sharpen

自定义关于锐化的参数

1
"_Sharpen",(sharpen, _sharpenDepthThreshold, _sharpenClamp, _sharpenRelaxation)

shader

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
uniform sampler2D _MainTex;
uniform float4 _MainTex_TexelSize;
uniform float4 _ColorBoost;
uniform float4 _Sharpen;

float getLuma(float3 rgb) {
const float3 lum = float3(0.299, 0.587, 0.114);
return dot(rgb, lum);
}

void beautifyPassFast(v2f i, inout half3 rgbM) {

half2 xInc = half2(_MainTex_TexelSize.x, 0);
half2 yInc = half2(0, _MainTex_TexelSize.y);

half lumaM = getLuma(rgbM);

half3 rgbN = tex2D(_MainTex, saturate(i.uv + yInc)).rgb;
half3 rgbS = tex2D(_MainTex, saturate(i.uv - yInc)).rgb;
half3 rgbW = tex2D(_MainTex, saturate(i.uv - xInc)).rgb;
half lumaN = getLuma(rgbN);
half lumaW = getLuma(rgbW);
half lumaS = getLuma(rgbS);
half maxLuma = max(lumaN,lumaS);
maxLuma = max(maxLuma, lumaW);
half minLuma = min(lumaN,lumaS);
minLuma = min(minLuma, lumaW) - 0.000001;
half lumaPower = 2 * lumaM - minLuma - maxLuma;
half lumaAtten = saturate(_Sharpen.w / (maxLuma - minLuma));
rgbM *= 1.0 + clamp(lumaPower * lumaAtten * _Sharpen.x, -_Sharpen.z, _Sharpen.z);

// 3. Vibrance
half3 maxComponent = max(rgbM.r, max(rgbM.g, rgbM.b));
half3 minComponent = min(rgbM.r, min(rgbM.g, rgbM.b));
half sat = saturate(maxComponent - minComponent);
rgbM *= 1.0 + _ColorBoost.z * (1.0 - sat) * (rgbM - getLuma(rgbM));

// 5. Final contrast + brightness
rgbM = (rgbM - halves) * _ColorBoost.y + halves;
rgbM *= _ColorBoost.x;
}