| | |
| | | import SwiftUI |
| | | import MetalKit |
| | | |
| | | struct MetalVideoRenderView: UIViewRepresentable { |
| | | // 统一接口,接收各种视频源的帧数据 |
| | | var frameData: VideoFrameData? |
| | | |
| | | struct VideoRendererView: UIViewRepresentable { |
| | | @Binding var pixelBuffer: CVPixelBuffer? |
| | | |
| | | //用 Coordinator 缓存实例 |
| | | func makeCoordinator() -> Coordinator { |
| | | Coordinator(self) |
| | | return Coordinator() |
| | | } |
| | | |
| | | |
| | | func makeUIView(context: Context) -> MTKView { |
| | | let mtkView = MTKView() |
| | | mtkView.device = context.coordinator.device |
| | | mtkView.delegate = context.coordinator |
| | | mtkView.framebufferOnly = false |
| | | mtkView.colorPixelFormat = .bgra8Unorm |
| | | mtkView.autoResizeDrawable = true |
| | | return mtkView |
| | | return context.coordinator.mtkView |
| | | } |
| | | |
| | | |
| | | func updateUIView(_ uiView: MTKView, context: Context) { |
| | | // 更新帧数据 |
| | | context.coordinator.updateFrame(frameData) |
| | | if let buffer = pixelBuffer { |
| | | //print("updateUIView") |
| | | context.coordinator.renderer.display(pixelBuffer: buffer) |
| | | } |
| | | } |
| | | |
| | | class Coordinator: NSObject, MTKViewDelegate { |
| | | var parent: MetalVideoRenderView |
| | | var device: MTLDevice |
| | | var commandQueue: MTLCommandQueue |
| | | var pipelineState: MTLRenderPipelineState |
| | | var textureCache: CVMetalTextureCache? |
| | | |
| | | // YUV转RGB的着色器 |
| | | var yuvConversionPipeline: MTLComputePipelineState? |
| | | |
| | | init(_ parent: MetalVideoRenderView) { |
| | | self.parent = parent |
| | | self.device = MTLCreateSystemDefaultDevice()! |
| | | self.commandQueue = device.makeCommandQueue()! |
| | | |
| | | // 初始化Metal资源 |
| | | // (这里需要设置渲染管线和纹理缓存) |
| | | } |
| | | |
| | | func updateFrame(_ frameData: VideoFrameData?) { |
| | | // 根据不同的帧数据格式(YUV/RGBA)进行处理 |
| | | // 将数据转换为Metal纹理 |
| | | } |
| | | |
| | | func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {} |
| | | |
| | | func draw(in view: MTKView) { |
| | | // 执行Metal绘制命令 |
| | | |
| | | class Coordinator { |
| | | let mtkView: MTKView |
| | | let renderer: MetalRenderer |
| | | |
| | | init() { |
| | | print("📦 MetalRendererWrapper 初始化了") |
| | | mtkView = MTKView() |
| | | renderer = MetalRenderer(mtkView: mtkView) |
| | | } |
| | | } |
| | | } |
| | | |