I'm quite new to OpenGL
/Metal
and I'm trying to understand some fundamental concepts.
Within our app, we are using CIFilter
to filter videos. I saw a WWDC
video from 2017 explaining that you can wrap CIFilter
with Metal
and use it as a regular filter.
I'm trying to understand how to convert this OpenGL
video effect to Metal
so I can use it as a reference point for future effects.
void mainImage(out vec4 fragColor, in vec2 fragCoord) {
float amount = sin(iTime) * 0.1;
// uv coords
vec2 uv = fragCoord / iResolution.xy;
amount *= 0.3;
float split = 1. - fract(iTime / 2.);
float scanOffset = 0.01;
vec2 uv1 = vec2(uv.x + amount, uv.y);
vec2 uv2 = vec2(uv.x, uv.y + amount);
if (uv.y > split) {
uv.x += scanOffset;
uv1.x += scanOffset;
uv2.x += scanOffset;
}
float r = texture(iChannel0, uv1).r;
float g = texture(iChannel0, uv).g;
float b = texture(iChannel0, uv2).b;
fragColor = vec4(r, g, b, 1.);
}
Which produces:
After converting the OpenGL
code to Metal
I'm using the CIFilter
wrapper to use it with AVPlayerItem
:
class MetalFilter: CIFilter {
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private let kernel: CIKernel
var inputImage: CIImage?
override init() {
let url = Bundle.main.url(forResource: "default", withExtension: "metallib")!
let data = try! Data(contentsOf: url)
kernel = try! CIKernel(functionName: "vhs", fromMetalLibraryData: data)
super.init()
}
func outputImage() -> CIImage? {
guard let inputImage = inputImage else {return nil}
let sourceSize = inputImage.extent.size
let outputImage = kernel.apply(extent: CGRect(x: 0, y: 0, width: sourceSize.width, height: sourceSize.height), roiCallback: { index, destRect in
return destRect
}, arguments: [inputImage, NSNumber(value: Float(1.0 / sourceSize.width)), NSNumber(value: Float(1.0 / sourceSize.height)), NSNumber(value: 60.0)])
return outputImage
}
}
Any help will be highly appreciated!
MetalFilter
implementation seems ok so far. What are you struggling with? – Fitz