Metal作为苹果官方支持的图形API在苹果设备上有更好的适配性和性能表现,在进行iOS开发时,部分开发者会期望可以支持Metal处理CVSDK处理过的纹理。
V4.4.0开始,iOS sample提供支持metal渲染环境的方案。
4.4.0版本Demo中写入了支持Metal的渲染环境的示例,客户可以使用Metal渲染指令来处理经过SDK的纹理。
创建CVPixelBuffer时,支持Metal和OpenGL的兼容选项,通过将CVPixelBuffer与MTLTexture进行绑定来创建GL和Metal共同操作的缓存区域,故可将MTLTexture设置为BEPixelBufferGLTexture的一个属性来从pixelbuffer直接访问其绑定的Metal纹理。
BEMTLView负责Metal环境的创建和面片渲染指令的执行(将sdk处理后的纹理渲染到屏幕)。
由于metal渲染环境为实现层逻辑,因此本文档仅对sample中提供的示例代码进行说明。
可参考该示例与项目进行集成。
该部分对sample中的工具类代码进行说明,涉及纹理转换等工具函数。
示例代码在sample中的位置:Core/Core/Utils/BEImageUtils.h[.m]
添加CVPixelBuffer转MTLTexture的工具函数,直接对pixelbuffer的内存区域进行拷贝,创建一个新的mtltexture;如果使用BEPixelBufferGLTexture,则无需调用该接口,直接访问到pixelbuffer对应的mtltexture。
新增接口: // {zh} / @brief CVPixelBuffer 转 metal纹理 {en} /@Briefing CVPixelBuffer to metal texture /// @param pixelBuffer CVPixelBuffer - (id<MTLTexture>)transformCVPixelBufferToMTLTexture:(CVPixelBufferRef)pixelBuffer;
示例代码在sample中的位置:Core/Core/Utils/BEGLTexture.h[.m]
对BEPixelBufferGLTexture进行定义的扩展
类定义扩展:(仅写了新增部分) // {zh} / 内部完成了 CVPixelBuffer 与 gl 纹理及 mtl 纹理的绑定,当完成对纹理的处理之后, {en} /Internally completed the binding of CVPixelBuffer to gl texture and mtl texture. After the texture is processed, // {zh} / 直接调用 pixelBuffer 就可以得到处理之后的 CVPixelBuffer {en} /Call pixelBuffer directly to get the processed CVPixelBuffer @interface BEPixelBufferGLTexture : NSObject <BEGLTexture> @property (nonatomic) id<MTLTexture> mtlTexture; // {zh} / @brief 根据 CVMetalTextureCacheRef 初始化 {en} CVMetalTextureCacheRef initialization - (instancetype)initWithMTKTextureCache:(CVMetalTextureCacheRef)textureCache; // {zh} / @brief 根据宽、高、CVMetalTextureCacheRef 初始化 {en} CVMetalTextureCacheRef initialization based on width, height - (instancetype)initWithWidth:(int)width height:(int)height mtlTextureCache:(CVMetalTextureCacheRef)textureCache; // {zh} / @brief 根据 CVPixelBuffer 初始化 {en} /@Briefing initialization based on CVPixelBuffer - (instancetype)initWithCVPixelBuffer:(CVPixelBufferRef)pixelBuffer mtlTextureCache:(CVMetalTextureCacheRef)textureCache; @end
示例代码在sample中的位置:Core/Core/Utils/BEShaderTypes.h
包含的是MSL(Metal Shader Language)中数据类型和buffer索引等数据。
该部分文档为sample中绘制、上屏及UI实现代码的位置,可根据自己项目实际情况进行参考。
示例代码在sample中的位置:Common/Common/ui/view/content/BEMTLView.h[.m]
负责Metal环境的创建,Metal相关的渲染指令都在该文件中的(void) drawRect:(CGRect)rect中完成;
新增接口: // 更新屏幕宽高时调用 - (void)resetWidthAndHeight; // 将mtltexture绘制到该view上 - (void)renderWithTexture:(id<MTLTexture>)texture size:(CGSize)size applyingOrientation:(int)orientation fitType:(int)fitType;
示例代码在sample中的位置:Common/Common/ui/vc/BEBaseVC.h[.m]
在VC基类中添加BEMTLView属性对象和drawTextureOnScreen函数;
新添加接口: 以metal纹理作为输入,绘制到BaseVC的属性成员mtlView上 // {zh} / @param rotation 旋转角度 {en} /@param rotation angle - (void)drawMTLTextureOnScreen:(id<BEGLTexture>)texture rotation:(int)rotation;
示例代码在sample中的位置:Common/Common/ui/vc/BEBaseBarVC.m
完成将sdk处理结果保存到本地的逻辑;
示例在sample中的位置:app/app/metal/fundamental.metal
metal的shader文件,因直接参与编译,故需要放在非静态库目录下(在demo中,即为app工程下)。这部分的shader文件为demo示例,可根据项目环境自己设置。