美肤
磨皮、美白与肤色等参数。各参数范围可能不同,UI 的 0–100 应按对应接口转换。
选择平台,跑通预览,再把美肤、美型、轻美妆与滤镜融入你的产品。
Android 从 Maven Central 引入 1.3.6,iOS 固定 Swift Package 1.3.6,HarmonyOS 使用 OHPM @snapbeauty/core 1.3.2。macOS 使用 Swift Package,Windows 从 GitHub Releases 获取 .nupkg 后通过本地 NuGet 源安装。启用效果需要匹配应用身份的授权,桌面授权与移动端分开签发。
SnapBeauty 做的事情很简单:你给它一帧相机画面,它还给你一帧处理好的画面(磨皮、瘦脸、妆容、滤镜等)。你负责拿到相机画面、把结果显示出来或发给对方。下面按顺序走,每一步都接着上一步。
| 名词 | 意思 |
|---|---|
| 帧 | 视频里的一张画面。相机每秒给你约 30 张,每一张都要处理一次。 |
| 纹理(Texture) | 存放在显卡里的一张图片。Android 的相机画面和 SDK 的输入输出都用它,不用 CPU 来回拷贝,所以快。 |
| GL 线程 | Android / 鸿蒙里专门操作显卡的线程。创建引擎、处理每一帧、释放引擎都必须在同一个 GL 线程里做,否则会黑屏或崩溃。 |
| 像素缓冲区(CVPixelBuffer) | iOS 里存放一张图片的内存对象,相机每一帧都是这种格式。 |
| Surface | 相机往里“写画面”的一块区域。鸿蒙里把 SDK 给的 Surface 交给相机,SDK 就能直接拿到画面。 |
| 授权(License) | 一段与应用身份绑定的文本。没有或不匹配时,SDK 不会报错崩溃,而是直接返回原图——所以“没效果”时先查授权。 |
先安装 SDK 并声明需要的相机权限,再初始化授权与引擎。由宿主采集和显示画面,将帧交给 SDK,并在停止采集后释放引擎。
选择平台查看完整示例源码和运行说明。Android、iOS 包含相机和 RTC 场景;HarmonyOS 提供相机示例,macOS 与 Windows 提供桌面 C 接口示例。
目标:做一个相机预览页,画面经过 SnapBeauty 后显示在屏幕上。思路:Camera2 把画面写进 SurfaceTexture → 在 GL 线程转成 2D 纹理 → 交给 SnapBeauty → 把结果画到 GLSurfaceView。
在 app/build.gradle 加入 SDK。依赖来自 Maven Central,settings.gradle 的仓库里有 mavenCentral() 即可。
android {
compileSdk 36
defaultConfig {
minSdk 23 // 接入第三方 RTC SDK 时,以各家 SDK 的最低版本要求为准
targetSdk 36
}
}
dependencies {
implementation 'cn.snapbeauty:snapbeauty-android:1.3.6'
}
在 AndroidManifest.xml 里加相机权限,并声明需要 OpenGL ES 3.0(SDK 依赖它)。android:name=".App" 是下一步要写的 Application 类(SDK 只需要一个 Context,在别处初始化也行,只要早于第一次创建引擎)。
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:glEsVersion="0x00030000" android:required="true" />
<application android:name=".App" ...>
<!-- 你自己的页面或服务照常声明,SDK 不要求特定的 Activity -->
</application>
</manifest>
把申请到的授权文件放到 app/src/main/,应用启动时读出来交给 SDK。只需做一次。授权缺失或和包名不匹配时 SDK 不会崩溃,而是返回原图,并通过监听器告诉你原因。
import android.app.Application
import android.util.Log
import ai.snapbeauty.core.SnapBeauty
class App : Application() {
override fun onCreate() {
super.onCreate()
// 授权出错时打日志,方便定位“为什么没效果”
SnapBeauty.setLicenseErrorListener { status ->
Log.e("SnapBeauty", "授权异常:${status.code},已使用原图")
}
val license = runCatching {
assets.open("snapbeauty.license").bufferedReader().use { it.readText() }
}.getOrDefault("")
SnapBeauty.init(this, license)
}
}
这一步先不接相机,只是把 SDK 包成好用的形式。先放翻转工具:OpenGL 纹理的行是“从下往上”,而 SDK 要求“从上往下”,所以进出 SDK 前后各翻一次。
import android.opengl.GLES30.*
/** GL 纹理的行是“从下往上”,SDK 需要“从上往下”。这个类负责来回翻转。可直接复制使用。 */
internal class SdkTextureBridge {
private val textures = IntArray(2)
private val fbos = IntArray(3)
private var width = 0
private var height = 0
/** slot 取 0 或 1:输入翻转用 0,输出翻转回来用 1,两块输出互不覆盖。 */
fun flip(input: Int, w: Int, h: Int, slot: Int): Int {
val read = get(GL_READ_FRAMEBUFFER_BINDING)
val draw = get(GL_DRAW_FRAMEBUFFER_BINDING)
val scissor = glIsEnabled(GL_SCISSOR_TEST)
try {
if (width != w || height != h) { // 尺寸变了就重建
release(); glGenFramebuffers(3, fbos, 0)
for (i in 0..1) {
textures[i] = newTexture()
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, null)
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbos[i])
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textures[i], 0)
check(glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE)
}
width = w; height = h
}
glDisable(GL_SCISSOR_TEST)
glBindFramebuffer(GL_READ_FRAMEBUFFER, fbos[2])
glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, input, 0)
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbos[slot])
// 目标矩形上下颠倒 = 翻转行方向
glBlitFramebuffer(0, 0, w, h, 0, h, w, 0, GL_COLOR_BUFFER_BIT, GL_NEAREST)
return textures[slot]
} finally { // 还原宿主原有的 GL 状态
glBindFramebuffer(GL_READ_FRAMEBUFFER, read); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, draw)
if (scissor) glEnable(GL_SCISSOR_TEST)
}
}
fun release() {
glDeleteTextures(2, textures, 0); glDeleteFramebuffers(3, fbos, 0)
textures.fill(0); fbos.fill(0); width = 0; height = 0
}
private fun newTexture(): Int {
val id = IntArray(1); glGenTextures(1, id, 0)
glBindTexture(GL_TEXTURE_2D, id[0])
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)
return id[0]
}
private fun get(key: Int) = IntArray(1).also { glGetIntegerv(key, it, 0) }[0]
}
再放处理器。以后你要调美颜参数、换滤镜、处理一帧,都只和这个类打交道;腾讯云 / 声网 / 即构的示例(见 RTC 场景)也复用它。
import android.content.Context
import ai.snapbeauty.core.FaceParams
import ai.snapbeauty.core.SkinParams
import ai.snapbeauty.core.SnapBeautyEngine
/** 把 SDK 引擎包一层。所有方法必须在同一个 GL 线程调用。 */
class SnapBeautyProcessor(context: Context) {
private val engine = SnapBeautyEngine(context.applicationContext) // 创建引擎
private val bridge = SdkTextureBridge() // 上一步的翻转工具
/** 美肤。界面滑杆 0~1:磨皮要乘 6 换算成 SDK 的范围,其余直接传。 */
fun setSkin(smooth: Float, white: Float, rosy: Float) {
engine.skin = SkinParams(smoothing = smooth * 6f, brightening = white, rosiness = rosy)
}
/** 美型。其余参数不写就保持默认(不变形)。 */
fun setFace(slim: Float, eyes: Float) {
engine.face = FaceParams(faceSlimming = slim, eyeScale = eyes)
}
/** 妆容 / 滤镜:传 ID 与强度;ID 为 null 表示关闭。可用 ID 以随包资源为准。 */
fun setMakeup(id: String?, strength: Float) = engine.setMakeup(id, strength)
fun setFilter(id: String?, strength: Float) = engine.setFilter(id, strength)
/** 设备是否支持美颜。不支持时 process 会直接返回原纹理。 */
fun available() = SnapBeautyEngine.isSupported()
/**
* 处理一帧。texture 必须是:已旋正(人脸朝上)、未镜像、GL_TEXTURE_2D 的纹理。
* 返回处理后的纹理,只在“下一次调用 process 之前”有效,不要自己保存或删除它。
*/
fun process(texture: Int, width: Int, height: Int): Int {
if (!available()) return texture
val input = bridge.flip(texture, width, height, 0) // 行方向:GL → SDK
val output = engine.process(input, width, height)
return if (output == input) texture else bridge.flip(output, width, height, 1) // SDK → GL
}
/** 切换镜头或画面突变时调用,清掉人脸跟踪的历史。 */
fun resetTracking() = engine.resetSmoothing()
fun release() { engine.release(); bridge.release() }
}
传给 process 的必须是:① 普通 GL_TEXTURE_2D(不是相机的 OES 外部纹理);② 已经旋正,人脸朝上;③ 未镜像。前置摄像头想要“镜子效果”,只在最后显示时镜像,别在送给 SDK 前做。
用 GLSurfaceView 做显示。它的 Renderer 回调都运行在 GL 线程,正好满足“创建、处理、释放在同一线程”的要求。下面是整条链路的骨架,每一处注释都对应上面说过的步骤;标注“宿主实现”的 4 个函数是常规 OpenGL 代码(生成外部纹理、画外部纹理、画普通纹理、分配 FBO),与 SnapBeauty 无关,网上 OpenGL ES 教程均有现成写法。
import android.graphics.SurfaceTexture
import android.opengl.GLES11Ext
import android.opengl.GLES30.*
import android.opengl.GLSurfaceView
import javax.microedition.khronos.egl.EGLConfig
import javax.microedition.khronos.opengles.GL10
class BeautyRenderer(
private val view: GLSurfaceView,
private val onCameraSurface: (SurfaceTexture) -> Unit, // 拿到相机要写入的 SurfaceTexture 后回调
) : GLSurfaceView.Renderer {
private lateinit var processor: SnapBeautyProcessor
private var cameraTexture: SurfaceTexture? = null
private var oesId = 0 // 相机原始画面(外部纹理 OES)
private var rawId = 0 // 转成普通 2D 纹理后的画面,交给 SDK
private var rawFbo = 0
private var frameReady = false
private var frameW = 0 // 旋正后的画面宽高
private var frameH = 0
// ① GL 环境就绪:在这里创建一切。这个回调所在线程就是“GL 线程”。
override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) {
oesId = newOesTexture() // 宿主实现:生成 GL_TEXTURE_EXTERNAL_OES 纹理
cameraTexture = SurfaceTexture(oesId).also {
it.setOnFrameAvailableListener { synchronized(this) { frameReady = true }; view.requestRender() }
onCameraSurface(it) // 交给相机去写
}
processor = SnapBeautyProcessor(view.context)
processor.setSkin(smooth = 0.35f, white = 0.2f, rosy = 0.1f) // 默认美肤
}
override fun onSurfaceChanged(gl: GL10?, width: Int, height: Int) { glViewport(0, 0, width, height) }
// ② 每来一帧调用一次
override fun onDrawFrame(gl: GL10?) {
val camera = cameraTexture ?: return
val ready = synchronized(this) { frameReady.also { frameReady = false } }
if (!ready) return
camera.updateTexImage() // 取最新一帧到 oesId
// 画面旋转后宽高要对调。frameW / frameH / 旋转矩阵由宿主按相机方向算出。
ensureRawTexture(frameW, frameH) // 宿主实现:分配 rawId 与 rawFbo
drawOesToRaw(oesId, rawFbo, frameW, frameH) // 宿主实现:把 OES 画成普通 2D 纹理,同时转正、取消镜像
val result = processor.process(rawId, frameW, frameH) // ③ 交给 SnapBeauty
drawToScreen(result) // ④ 宿主实现:把 result 画到屏幕(居中裁切)
}
// ⑤ 页面关闭(GLSurfaceView.onPause 之前)必须在 GL 线程里释放
fun release() = view.queueEvent {
processor.release()
cameraTexture?.release(); cameraTexture = null
glDeleteTextures(2, intArrayOf(oesId, rawId), 0)
if (rawFbo != 0) glDeleteFramebuffers(1, intArrayOf(rawFbo), 0)
}
// ---- 下面几个是常规 OpenGL 代码,各 Android GL 教程均有写法,此处不展开 ----
private fun newOesTexture(): Int = TODO("glGenTextures + 绑定 GL_TEXTURE_EXTERNAL_OES + 设置过滤参数")
private fun ensureRawTexture(w: Int, h: Int) { TODO("w/h 变化时重建 rawId 与 rawFbo") }
private fun drawOesToRaw(oes: Int, fbo: Int, w: Int, h: Int) { TODO("用 samplerExternalOES 着色器画满 fbo") }
private fun drawToScreen(texture: Int) { TODO("用普通 sampler2D 着色器画到屏幕") }
}
标准 Camera2 写法。关键只有一点:输出目标是上一步 onCameraSurface 给你的那个 SurfaceTexture。相机权限由你的应用按自己的方式申请,授权通过后再调用。
import android.hardware.camera2.*
import android.graphics.SurfaceTexture
import android.os.Handler
import android.view.Surface
// 相机权限已授予后调用。texture 就是上一步 onCameraSurface 回调里拿到的那个。
fun openCamera(manager: CameraManager, texture: SurfaceTexture, handler: Handler) {
val id = manager.cameraIdList.first { // 选前置摄像头
manager.getCameraCharacteristics(it).get(CameraCharacteristics.LENS_FACING) ==
CameraCharacteristics.LENS_FACING_FRONT
}
texture.setDefaultBufferSize(1280, 720) // 采集分辨率,按设备支持的尺寸选
val surface = Surface(texture)
manager.openCamera(id, object : CameraDevice.StateCallback() {
override fun onOpened(device: CameraDevice) {
device.createCaptureSession(listOf(surface), object : CameraCaptureSession.StateCallback() {
override fun onConfigured(session: CameraCaptureSession) {
val request = device.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW)
.apply { addTarget(surface) }.build()
session.setRepeatingRequest(request, null, handler) // 开始持续出画面
}
override fun onConfigureFailed(session: CameraCaptureSession) { session.close() }
}, handler)
}
override fun onDisconnected(device: CameraDevice) { device.close() }
override fun onError(device: CameraDevice, error: Int) { device.close() }
}, handler)
}
SDK 不关心宿主是 Activity、Fragment、Compose 还是纯后台服务,只要求有一个 GL 线程。如果用 GLSurfaceView,创建后设置 setEGLContextClientVersion(3) 和 renderer,渲染模式用 RENDERMODE_WHEN_DIRTY(来一帧画一帧)。退出时顺序很重要:
renderer.release(),让它在 GL 线程里释放引擎和纹理。GLSurfaceView 则调用 onPause())。① Logcat 里搜 “SnapBeauty” 有没有授权异常;② SnapBeautyEngine.isSupported() 是否为 true;③ 画面是倒的或镜像:检查第 5 步“转正、取消镜像”;④ 黑屏:创建、处理、释放是否在同一个 GL 线程。更多见常见问题。
在 Release + R8 混淆环境再验证一次:模型、效果资源与原生库是否打进包、包名与签名是否和授权一致、切后台再回来相机能否恢复。
目标:相机画面经过 SnapBeauty 后显示在屏幕上。思路:AVCaptureSession 每帧给你一个 BGRA 的 CVPixelBuffer → 交给 SnapBeauty → 得到处理后的 CVPixelBuffer → 用 Metal 画到屏幕(或发给 RTC)。SDK 的 Objective-C 接口放在一个很薄的 Objective-C++ 封装里,Swift 通过桥接头文件调用它。
Xcode → File → Add Package Dependencies,填入下面的地址,版本选 Exact Version 1.3.6,勾选 SnapBeautySDK 产品。需要 Metal GPU 推理时,可额外勾选 SnapBeautyGPU;不添加时使用 CPU 推理。SDK 二进制、模型和 Metal 着色器都由它带上,不用另外拷资源。
https://github.com/YunJuChuang-Tech/snapbeauty-ios-sdk.git
在 Info.plist 加相机用途说明,否则一打开相机 App 就会闪退。文案写给用户看,说清楚为什么需要相机。
<key>NSCameraUsageDescription</key>
<string>用于拍摄并实时预览美颜效果</string>
授权文件(snapbeauty.license)放进 App 包的 Assets 目录。只需做一次;授权缺失或与 Bundle ID 不匹配时,SDK 返回原图,并在 setLicenseErrorHandler 里告诉你原因。
import SwiftUI
import SnapBeauty
@main
struct DemoApp: App {
init() {
// 授权出错时打日志,方便定位“为什么没效果”
SnapBeauty.setLicenseErrorHandler { status in
NSLog("SnapBeauty 授权异常:%ld,已显示原图", status.code.rawValue)
}
// 授权文件放在 App 包里:Assets/snapbeauty.license
let url = Bundle.main.bundleURL.appendingPathComponent("Assets/snapbeauty.license")
let license = (try? String(contentsOf: url, encoding: .utf8)) ?? ""
_ = SnapBeauty.initialize(license: license)
}
var body: some Scene { WindowGroup { ContentView() } }
}
新建这两个文件,再建一个桥接头文件 Demo-Bridging-Header.h,里面只写一行 #import "BeautyFrameProcessor.h",并在 Build Settings 的 “Objective-C Bridging Header” 填上它。这样 Swift 就能直接用 BeautyFrameProcessor。
#import <Foundation/Foundation.h>
#import <CoreVideo/CoreVideo.h>
NS_ASSUME_NONNULL_BEGIN
/// 对 SDK 引擎的一层封装。请在同一个串行队列里调用。
@interface BeautyFrameProcessor : NSObject
- (nullable instancetype)initWithAssets:(NSString *)assets shaders:(NSString *)shaders error:(NSError **)error;
/// 输入、输出都是 BGRA 的 CVPixelBuffer。返回的缓冲区由调用方释放(CF_RETURNS_RETAINED)。
- (nullable CVPixelBufferRef)process:(CVPixelBufferRef)input
smooth:(float)smooth white:(float)white rosy:(float)rosy
slim:(float)slim eyes:(float)eyes
error:(NSError **)error CF_RETURNS_RETAINED;
@end
NS_ASSUME_NONNULL_END
#import "BeautyFrameProcessor.h"
#import "SnapBeauty.h" // SDK 提供的头文件
#import <QuartzCore/QuartzCore.h>
@implementation BeautyFrameProcessor {
SnapBeautyEngine *_engine;
int64_t _timestamp;
}
- (instancetype)initWithAssets:(NSString *)assets shaders:(NSString *)shaders error:(NSError **)error {
if ((self = [super init])) {
_engine = [[SnapBeautyEngine alloc] initWithAssetsPath:assets shadersPath:shaders error:error];
if (!_engine) return nil; // 创建失败(资源缺失等)
}
return self;
}
- (CVPixelBufferRef)process:(CVPixelBufferRef)input
smooth:(float)smooth white:(float)white rosy:(float)rosy
slim:(float)slim eyes:(float)eyes error:(NSError **)error {
// 1) 设置效果参数(没写的字段保持默认)
SnapBeautySkinParams *skin = [SnapBeautySkinParams new];
skin.smoothing = smooth * 6; // 界面 0~1,磨皮乘 6
skin.brightening = white;
skin.rosiness = rosy;
SnapBeautyFaceParams *face = [SnapBeautyFaceParams new];
face.faceSlimming = slim;
face.eyeScale = eyes;
_engine.skin = skin;
_engine.face = face;
[_engine setMakeup:nil strength:0]; // 妆容 ID + 强度;nil 为关闭
[_engine setFilter:nil strength:0]; // 滤镜 ID + 强度
// 2) 处理一帧。时间戳必须单调递增(纳秒)。
_timestamp = MAX(_timestamp + 1, (int64_t)(CACurrentMediaTime() * 1e9));
id<MTLTexture> texture = [_engine processPixelBuffer:input frontCamera:NO
timestamp:_timestamp showOriginal:NO error:error];
if (!texture) return nil;
// 3) SDK 返回的是 Metal 纹理;复制进一块独立的 BGRA CVPixelBuffer 再交给调用方
CVPixelBufferRef output = nil;
NSDictionary *attrs = @{(id)kCVPixelBufferIOSurfacePropertiesKey: @{},
(id)kCVPixelBufferMetalCompatibilityKey: @YES};
if (CVPixelBufferCreate(kCFAllocatorDefault, texture.width, texture.height,
kCVPixelFormatType_32BGRA, (__bridge CFDictionaryRef)attrs, &output) != kCVReturnSuccess) return nil;
CVPixelBufferLockBaseAddress(output, 0);
[texture getBytes:CVPixelBufferGetBaseAddress(output) bytesPerRow:CVPixelBufferGetBytesPerRow(output)
fromRegion:MTLRegionMake2D(0, 0, texture.width, texture.height) mipmapLevel:0];
// 个别版本的纹理是 RGBA 排列,需要换成 BGRA;以纹理的实际 pixelFormat 为准
if (texture.pixelFormat == MTLPixelFormatRGBA8Unorm) {
uint8_t *bytes = CVPixelBufferGetBaseAddress(output);
size_t stride = CVPixelBufferGetBytesPerRow(output);
for (NSUInteger y = 0; y < texture.height; ++y)
for (NSUInteger x = 0; x < texture.width; ++x) {
uint8_t *p = bytes + y * stride + x * 4;
uint8_t r = p[0]; p[0] = p[2]; p[2] = r;
}
}
CVPixelBufferUnlockBaseAddress(output, 0);
return output;
}
@end
引擎、参数对象都是 Objective-C 接口,放在 .mm 里调用最直接;并且“Metal 纹理 → 独立的 CVPixelBuffer”这步统一做掉,后面显示、录制、发给 RTC 都拿到同一种格式,不会出现颜色发蓝发红。
标准 AVFoundation 写法。有两个设置不能漏:输出格式设为 BGRA、画面转正且不镜像。相机回调和美颜处理放在同一个串行队列,避免并发调用引擎。
import AVFoundation
final class CameraCapture: NSObject, AVCaptureVideoDataOutputSampleBufferDelegate {
private let session = AVCaptureSession()
private let queue = DispatchQueue(label: "demo.camera") // 相机与美颜都在这个串行队列
var onFrame: ((CVPixelBuffer) -> Void)?
func start() {
queue.async { [self] in
session.beginConfiguration()
session.sessionPreset = .vga640x480
guard let device = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .front),
let input = try? AVCaptureDeviceInput(device: device),
session.canAddInput(input) else { session.commitConfiguration(); return }
session.addInput(input)
let output = AVCaptureVideoDataOutput()
// 关键:要 BGRA 格式,SDK 的输入就是它
output.videoSettings = [kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA]
output.alwaysDiscardsLateVideoFrames = true // 处理不过来就丢帧,不要堆积
output.setSampleBufferDelegate(self, queue: queue)
session.addOutput(output)
// 关键:画面转正(竖屏)、不镜像;镜像留到显示时再做
if let c = output.connection(with: .video) {
c.videoOrientation = .portrait
if c.isVideoMirroringSupported { c.automaticallyAdjustsVideoMirroring = false; c.isVideoMirrored = false }
}
session.commitConfiguration()
session.startRunning()
}
}
func stop() { queue.async { [self] in session.stopRunning() } }
func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
guard let buffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return }
onFrame?(buffer) // 每一帧交给下面的处理
}
}
用 MTKView 加 CoreImage,把 CVPixelBuffer 居中裁切铺满画到屏幕。前置摄像头的“镜子效果”只在这里做。
import MetalKit
import CoreImage
/// 用 MTKView + CoreImage 把 CVPixelBuffer 画到屏幕,居中裁切铺满。
final class FrameView: MTKView {
private var context: CIContext!
private var queue: MTLCommandQueue!
private var frame: CVPixelBuffer?
init() {
let gpu = MTLCreateSystemDefaultDevice()
super.init(frame: .zero, device: gpu)
context = CIContext(mtlDevice: gpu!); queue = gpu!.makeCommandQueue()
framebufferOnly = false; colorPixelFormat = .bgra8Unorm
enableSetNeedsDisplay = true; isPaused = true // 来一帧画一帧
}
required init(coder: NSCoder) { fatalError() }
func present(_ buffer: CVPixelBuffer) { frame = buffer; setNeedsDisplay() }
override func draw(_ rect: CGRect) {
guard let frame, let drawable = currentDrawable, let command = queue.makeCommandBuffer() else { return }
var image = CIImage(cvPixelBuffer: frame)
// 前置摄像头想要“镜子效果”:只在显示时水平翻转,不要在送进 SDK 之前翻
image = image.transformed(by: CGAffineTransform(a: -1, b: 0, c: 0, d: 1, tx: image.extent.width, ty: 0))
let size = drawableSize
let scale = max(size.width / image.extent.width, size.height / image.extent.height)
image = image.transformed(by: CGAffineTransform(scaleX: scale, y: scale))
.transformed(by: CGAffineTransform(translationX: (size.width - image.extent.width * scale) / 2,
y: (size.height - image.extent.height * scale) / 2))
context.render(image, to: drawable.texture, commandBuffer: command,
bounds: CGRect(origin: .zero, size: size), colorSpace: CGColorSpaceCreateDeviceRGB())
command.present(drawable); command.commit()
}
}
创建处理器时传入 SDK 自带的资源与着色器路径;每来一帧就处理一次,失败时显示原图。
import SnapBeautyResources // SDK 随包的资源与着色器路径
let camera = CameraCapture()
let previewView = FrameView() // 加到你的界面里
let processor = try BeautyFrameProcessor(
assets: SnapBeautyResources.assets.path, // 模型、滤镜等资源目录
shaders: SnapBeautyResources.shaders.path) // Metal 着色器目录
camera.onFrame = { input in
// 在相机队列里处理;失败就显示原图,不要中断画面
var shown = input
if let output = try? processor.process(input, smooth: 0.35, white: 0.2, rosy: 0.1, slim: 0, eyes: 0) {
shown = output // 独立的 BGRA 缓冲区,Swift 会自动管理其生命周期
}
DispatchQueue.main.async { previewView.present(shown) } // 显示(见第 6 步)
}
camera.start()
页面消失时调用 camera.stop(),等队列里最后一帧处理完,再让 processor 随页面一起释放(置为 nil)。切换前后摄像头后,建议重新创建处理器,清掉人脸跟踪的历史。
纹理读回正确不代表屏幕显示方向正确。分别检查实际预览、保存的帧以及 RTC 远端画面的旋转、镜像和颜色,避免在多个环节重复翻转。
iOS 示例封装固定单人处理;SDK 返回的 Metal 纹理实际可能是 RGBA 排列,上面代码已按 pixelFormat 转换成 BGRA。真机实拍、发布签名与业务链路仍需用交付版本逐项验收。
目标:相机预览经过 SnapBeauty 后显示在页面上。鸿蒙的做法和 Android / iOS 不同:你不用自己处理每一帧。你把页面上的显示区域(XComponent 的 surface)交给 SDK,SDK 返回一个“相机应该写入的 surface”,相机直接写给它,SDK 处理后自己画到显示区域。
在 entry/oh-package.json5 中添加 OHPM 远程依赖,然后在 DevEco Studio 执行 Sync,或在工程根目录运行 ohpm install。SDK 的原生库和基础资源由构建工具合并;妆容贴图、唇色和面板素材需要由宿主提供。使用美颜效果仍需申请与应用身份匹配的授权。
{
"name": "entry",
"version": "1.0.0",
"dependencies": {
"@snapbeauty/core": "1.3.2"
}
}
在 entry/src/main/module.json5 的 module 里加入相机权限。$string:camera_reason 要在 resources/base/element/string.json 里写一句给用户看的说明。
"requestPermissions": [
{
"name": "ohos.permission.CAMERA",
"reason": "$string:camera_reason",
"usedScene": { "abilities": ["EntryAbility"], "when": "inuse" }
}
]
授权文件放到 entry/src/main/resources/。在 EntryAbility 里读出并初始化,只需一次。
import UIAbility from '@ohos.app.ability.UIAbility';
import window from '@ohos.window';
import { SnapBeauty } from '@snapbeauty/core';
import { util } from '@kit.ArkTS';
export default class EntryAbility extends UIAbility {
onWindowStageCreate(stage: window.WindowStage): void {
// 授权文件放在 entry/src/main/resources/rawfile/snapbeauty.license
let license: string = '';
try {
license = new util.TextDecoder('utf-8').decodeToString(
this.context.resourceManager.getRawFileContentSync('snapbeauty.license'));
} catch (_) { /* 没有授权文件:SDK 会直接返回原图 */ }
SnapBeauty.init(this.context, license); // 只需一次
stage.loadContent('pages/Index');
}
}
这是标准的 CameraKit 流程,唯一和 SnapBeauty 相关的是两处:engine.attach(...) 拿到相机要写入的 surface,以及 engine.configureFrame(...) 告诉 SDK 旋转后的画面尺寸。关闭顺序不能乱:先停相机,再 engine.release()。
import camera from '@ohos.multimedia.camera';
import common from '@ohos.app.ability.common';
import abilityAccessCtrl from '@ohos.abilityAccessCtrl';
import { SnapBeautyEngine } from '@snapbeauty/core';
export class CameraPreview {
private input: camera.CameraInput | undefined;
private output: camera.PreviewOutput | undefined;
private session: camera.PhotoSession | undefined;
private attached: boolean = false;
constructor(private context: common.UIAbilityContext, private engine: SnapBeautyEngine,
private report: (message: string) => void) {}
/** active=true 打开相机;false 关闭并释放。front=true 前置。 */
async request(active: boolean, front: boolean, surface: string, root: string): Promise<void> {
await this.close();
if (!active || !surface || !root) { return; }
try { await this.open(front, surface, root); }
catch (error) { await this.close(); this.report(`相机启动失败:${error.message}`); }
}
private async open(front: boolean, surface: string, root: string): Promise<void> {
// 1) 申请相机权限
const result = await abilityAccessCtrl.createAtManager()
.requestPermissionsFromUser(this.context, ['ohos.permission.CAMERA']);
if (result.authResults[0] !== 0) { throw new Error('请在系统设置中允许相机权限'); }
// 2) 选摄像头与预览分辨率
const manager = camera.getCameraManager(this.context);
const position = front ? camera.CameraPosition.CAMERA_POSITION_FRONT : camera.CameraPosition.CAMERA_POSITION_BACK;
const device = manager.getSupportedCameras().find((c: camera.CameraDevice) => c.cameraPosition === position);
if (!device) { throw new Error('没有找到此摄像头'); }
const profiles = manager.getSupportedOutputCapability(device, camera.SceneMode.NORMAL_PHOTO).previewProfiles;
const profile = profiles[0];
// 3) 关键:把显示用的 surface 和资源目录交给 SDK,SDK 返回“相机该写入的 surface”
const cameraSurface = this.engine.attach(surface, root, profile.size.width, profile.size.height);
this.attached = true;
// 4) 标准 CameraKit:把预览输出接到 SDK 给的 surface
this.input = manager.createCameraInput(device);
await this.input.open();
this.output = manager.createPreviewOutput(profile, cameraSurface);
this.session = manager.createSession<camera.PhotoSession>(camera.SceneMode.NORMAL_PHOTO);
this.session.beginConfig();
this.session.addInput(this.input);
this.session.addOutput(this.output);
await this.session.commitConfig();
// 5) 告诉 SDK 旋转后的画面尺寸(90/270 度要对调宽高),第三个参数是否镜像
const rotation = this.output.getPreviewRotation(0);
this.output.setPreviewRotation(rotation, true);
const rotated = rotation === camera.ImageRotation.ROTATION_90 || rotation === camera.ImageRotation.ROTATION_270;
this.engine.configureFrame(rotated ? profile.size.height : profile.size.width,
rotated ? profile.size.width : profile.size.height, false);
await this.session.start();
this.report('相机美颜 · 单人模式');
}
/** 关闭顺序不能乱:先停相机,再释放 SDK。 */
private async close(): Promise<void> {
if (this.session) {
try { await this.session.stop(); } catch (_) {}
try { await this.session.release(); } catch (_) {}
this.session = undefined;
}
if (this.output) { try { await this.output.release(); } catch (_) {} this.output = undefined; }
if (this.input) { try { await this.input.close(); } catch (_) {} this.input = undefined; }
if (this.attached) { this.engine.release(); this.attached = false; }
}
}
页面里放一个 XComponent 做显示区域;区域加载完成后打开相机,页面销毁时关闭。美肤、美型、妆容和滤镜都在引擎对象上设置,改完立即生效,不用重启相机。
import common from '@ohos.app.ability.common';
import { SnapBeautyEngine, SkinParams, FaceParams } from '@snapbeauty/core';
import { CameraPreview } from '../model/CameraPreview';
@Entry
@Component
struct Index {
private controller: XComponentController = new XComponentController();
private engine: SnapBeautyEngine = new SnapBeautyEngine(); // ① 创建引擎
private camera: CameraPreview | undefined;
private surfaceId: string = '';
private root: string = ''; // 资源目录:包含 snapbeauty/ 子目录的真实文件夹路径
aboutToAppear(): void {
const context = getContext(this) as common.UIAbilityContext;
this.camera = new CameraPreview(context, this.engine, (msg: string) => { console.info(msg); });
// 把 SDK 随包资源(rawfile 里的 snapbeauty/ 目录)复制到应用沙箱,root 指向复制后的目录。
// 这是常规的文件复制;示例工程的 installDemoAssets 还额外校验了文件摘要。
this.root = context.filesDir + '/beauty';
// ② 设置效果:美肤、美型、妆容、滤镜
const skin = new SkinParams();
skin.smoothing = 0.35 * 6; skin.brightening = 0.2; skin.rosiness = 0.1;
const face = new FaceParams();
face.faceSlimming = 0; face.eyeScale = 0;
this.engine.skin = skin;
this.engine.face = face;
this.engine.setMakeup('', 0); // 妆容 ID + 强度;空字符串为关闭
this.engine.setFilter('', 0); // 滤镜 ID + 强度
}
aboutToDisappear(): void { this.camera?.request(false, true, '', this.root); } // ⑤ 关闭相机并释放
build() {
// ③ 预览画面:SDK 把美颜后的结果直接画进这个 XComponent
XComponent({ id: 'camera-preview', type: XComponentType.SURFACE, controller: this.controller })
.width('100%').height('100%')
.onLoad(() => {
this.surfaceId = this.controller.getXComponentSurfaceId();
this.camera?.request(true, true, this.surfaceId, this.root); // ④ 打开相机
})
.onDestroy(() => { this.surfaceId = ''; this.camera?.request(false, true, '', this.root); })
}
}
SDK 的模型和滤镜资源必须在一个真实的文件夹里,不能直接从 rawfile 读取。通常做法是首次启动时把 rawfile 里的 snapbeauty/ 目录复制到应用沙箱(如 filesDir/beauty),root 就是这个目录的路径。示例工程的 installDemoAssets 就是做这件事并校验文件摘要,需要的话可向项目联系人索取。
XComponent 的 onLoad 已触发、root 路径下存在 snapbeauty/。相机示例已完成依赖解析、ArkTS 编译和 unsigned HAP 检查;签名安装与真机实拍仍待验证。当前未提供鸿蒙 RTC 示例,不能据此推断已支持完整通话链路。
宿主采集并显示画面。SnapBeauty 在 Metal 上渲染,在 CPU 上做人脸推理。可以用与 Windows 共用的 C 接口,也可以通过随包的 SnapBeauty.h、module.modulemap 使用与 iOS 相同的 SnapBeautyEngine。
方式一:Swift Package
在 Xcode 选择 File → Add Package Dependencies,填入 SnapBeauty macOS SDK 的仓库地址,精确版本选 1.3.6。需要 Metal GPU 推理时,可额外添加 SnapBeautyGPUMacOS 产品。
添加 SnapBeautyMacOSSDK 产品。SnapBeauty 模块提供 SDK 接口,SnapBeautyMacOSResources 提供模型、滤镜和 Metal 着色器。
GitHub Releases 提供二进制 XCFramework;手动使用该附件时,资源从 Swift Package 中取得。
方式二:独立 ZIP 手动集成
include/ # 加入头文件搜索路径
lib/libSnapBeauty.dylib # 链接 -lSnapBeauty,放入 App 的 Contents/Frameworks
Assets/ # 与 Shaders/ 同级,一起放入 App 资源目录
Shaders/
SnapBeauty-macOS-1.3.6.zip,将 include/ 加入头文件搜索路径,链接 lib/libSnapBeauty.dylib(-lSnapBeauty)。Contents/Frameworks,给可执行文件加 @executable_path/../Frameworks 的 rpath。Assets/ 和 Shaders/ 一起放入 App 资源目录,保持两者同级。每个进程启动时先调用 xm_desktop_init,再用 xm_desktop_engine_create 创建引擎。
SnapBeautyMacOSResources.assets 的文件路径。assets_root_utf8 可指向 Assets/ 或包含 Assets/ 和 Shaders/ 的根目录。桌面授权与移动端分开签发。查看桌面授权方式。
app_id_utf8;仅无 Bundle ID 的 C 接口命令行宿主使用显式 app_id_utf8。code 为 0 表示有效,读取当前状态用 xm_desktop_license_status。Application Support/SnapBeauty;C 接口的授权错误回调在 SDK 私有队列触发。宿主通过 AVCaptureSession 等方式采集画面,用相机时在 App 的 Info.plist 配置 NSCameraUsageDescription 并由宿主申请权限。示例输入为 BGRA8。帧规格、返回值和生命周期见 桌面 C 接口帧约定。
#include <stddef.h>
#include <stdio.h>
#include "snapbeauty/desktop.h"
/* 宿主启动时调用。授权文本和资源绝对路径由宿主传入。 */
xm_status beauty_start(const char *license_text, const char *assets_path,
xm_desktop_engine **engine) {
const xm_desktop_init_options init = {
.struct_size = sizeof(init),
.license_utf8 = license_text,
.app_id_utf8 = NULL, /* App 有 Bundle ID */
.storage_dir_utf8 = NULL,
};
const char *license_status = xm_desktop_init(&init);
/* 宿主解析 license_status 的 code,并向用户展示授权状态。 */
(void)license_status;
const xm_desktop_options options = {
.struct_size = sizeof(options),
.assets_root_utf8 = assets_path,
};
xm_status status = xm_desktop_engine_create(&options, engine);
if (status != XM_OK) {
fprintf(stderr, "%s\n", xm_desktop_last_error(NULL));
return status;
}
float values[XM_PARAM_COUNT] = {0};
values[XM_PARAM_SMOOTHING] = 4.2f;
const xm_params params = { sizeof(params), values, XM_PARAM_COUNT, NULL, NULL };
status = xm_desktop_engine_set_params(*engine, ¶ms);
if (status != XM_OK) {
xm_desktop_engine_destroy(*engine);
*engine = NULL;
}
return status;
}
/* 每张采集帧调用一次。out 由宿主分配,与 pixels 不重叠。 */
xm_status beauty_frame(xm_desktop_engine *engine, const uint8_t *pixels,
int32_t width, int32_t height, int32_t stride,
int64_t timestamp_ns, uint8_t *out, int32_t out_stride) {
const xm_desktop_frame frame = {
.struct_size = sizeof(frame),
.pixels = pixels,
.width = width,
.height = height,
.stride = stride,
.format = XM_PIXEL_BGRA8,
.timestamp_ns = timestamp_ns,
.out_pixels = out,
.out_stride = out_stride,
};
return xm_desktop_process(engine, &frame, NULL);
}
/* 等本引擎的帧回调退出后调用。 */
void beauty_stop(xm_desktop_engine *engine) {
xm_desktop_engine_destroy(engine);
}
通用 E / L 状态见 桌面错误码。没有 Metal 设备时引擎创建返回 E005 XM_NOT_CONFIGURED,xm_desktop_last_error(NULL) 含 gpu_unsupported。L006 表示 macOS 授权身份不匹配,L013 可由 Bundle ID 和 app_id_utf8 同时缺失引起,L012 应检查存储目录权限。
已在 Apple 芯片 Mac Studio(macOS 26.5)完成 C 接口 49 项检查及静态帧回放。另在一台 MacBook 上验证了相机预览、人脸检测和磨皮。首次权限弹窗、macOS 12 到 14 实机、真实生产授权接受均未验证。当前 ZIP 提供 arm64,未提供 Intel Mac 版本。
独立 ZIP 里的 SDK dylib 已通过 Developer ID 签名和公证。宿主还需满足 macOS 的库验证要求。干净机器上的首次启动、Gatekeeper 实际提示和 App Sandbox 未验证。
宿主采集并显示画面。SDK 通过 snapbeauty/desktop.h 提供纯 C 接口,使用 OpenGL 渲染,在 CPU 上做人脸推理。
方式一:NuGet 本地包源
从 GitHub Releases 下载 SnapBeauty.Windows.1.3.6.nupkg。
在 Visual Studio 的 NuGet 包源里添加存放该文件的本地目录,并选择该源。
把 SnapBeauty.Windows 1.3.6 安装到 x64 C++ 项目。构建配置会添加头文件路径和导入库。
编译后把 snapbeauty.dll 和 Assets/ 复制到 EXE 输出目录。
方式二:独立 ZIP 手动集成
include/ # 加入头文件搜索路径
lib/snapbeauty.lib # 链接
bin/snapbeauty.dll # 放到宿主 EXE 旁
Assets/ # 随应用一起带上
tools/sb-fingerprint.exe # 获取 EXE 签名证书指纹
每个进程启动时先调用 xm_desktop_init,再将 Assets/ 的路径传入 xm_desktop_engine_create。
桌面授权与移动端分开签发。查看桌面授权方式。
app_id 和 signers(1 到 4 个宿主 EXE 签名证书的 SHA-256 指纹)。tools\sb-fingerprint.exe <exe>,可用它获取指纹。xm_desktop_init 传入同一个 app_id 和授权文本,返回状态 JSON。code 为 0 表示有效。%LOCALAPPDATA%\SnapBeauty\<exe 名>,授权错误回调在 SDK 线程触发。宿主可通过 Media Foundation 采集画面。下面用 RGBA8 演示,若上游输出 BGRA8,按实际格式传 XM_PIXEL_BGRA8。帧规格和返回值见 桌面 C 接口帧约定。
如需动态卸载 DLL,先退出宿主帧回调并销毁引擎,再调用 xm_desktop_shutdown 等待续期线程退出。
#include <stddef.h>
#include <stdio.h>
#include "snapbeauty/desktop.h"
/* 宿主启动时调用。授权文本和资源绝对路径由宿主传入。 */
xm_status beauty_start(const char *license_text, const char *assets_path,
const char *app_id, xm_desktop_engine **engine) {
const xm_desktop_init_options init = {
.struct_size = sizeof(init),
.license_utf8 = license_text,
.app_id_utf8 = app_id,
.storage_dir_utf8 = NULL,
};
const char *license_status = xm_desktop_init(&init);
/* 宿主解析 license_status 的 code,并向用户展示授权状态。 */
(void)license_status;
const xm_desktop_options options = {
.struct_size = sizeof(options),
.assets_root_utf8 = assets_path,
};
xm_status status = xm_desktop_engine_create(&options, engine);
if (status != XM_OK) {
fprintf(stderr, "%s\n", xm_desktop_last_error(NULL));
return status;
}
float values[XM_PARAM_COUNT] = {0};
values[XM_PARAM_SMOOTHING] = 4.2f;
const xm_params params = { sizeof(params), values, XM_PARAM_COUNT, NULL, NULL };
status = xm_desktop_engine_set_params(*engine, ¶ms);
if (status != XM_OK) {
xm_desktop_engine_destroy(*engine);
*engine = NULL;
}
return status;
}
/* 每张采集帧调用一次。out 由宿主分配,与 pixels 不重叠。 */
xm_status beauty_frame(xm_desktop_engine *engine, const uint8_t *pixels,
int32_t width, int32_t height, int32_t stride,
int64_t timestamp_ns, uint8_t *out, int32_t out_stride) {
const xm_desktop_frame frame = {
.struct_size = sizeof(frame),
.pixels = pixels,
.width = width,
.height = height,
.stride = stride,
.format = XM_PIXEL_RGBA8,
.timestamp_ns = timestamp_ns,
.out_pixels = out,
.out_stride = out_stride,
};
return xm_desktop_process(engine, &frame, NULL);
}
/* 等本引擎的帧回调退出后调用。 */
void beauty_stop(xm_desktop_engine *engine) {
xm_desktop_engine_destroy(engine);
}
通用 E / L 状态见 桌面错误码。L003 可由缺少 signers 或指纹数量、格式错误引起;L006 应检查 app_id、签名和指纹;L013 应检查 app_id_utf8 和初始化参数结构大小。
已在 Windows 11、Intel UHD Graphics 730 上完成 C 接口 49 项检查、静态帧回放及 12 个本地 HTTPS 授权运输场景。NVIDIA RTX 2060(Windows 11)也通过了 C 接口和静态帧验证。Windows 相机实拍与真机权限弹窗、AMD / 双显卡、Windows 10 实机、普通 TDR、干净机器首次启动和真实生产授权接受均未验证。本版 SDK 包未做 Authenticode 签名,宿主 EXE 仍需按上面的授权要求签名。
需要厂商的 OpenGL 2.1+ 驱动和帧缓冲对象支持。Windows 自带的 GL 1.1、远程桌面会话和无显卡驱动的虚拟机不满足要求。SDK 无软件渲染模式,宿主可继续显示原画面。
输入 RGBA8 或 BGRA8,第 0 行在顶部,画面不镜像。宽高各为 1–4096,输入和输出步幅都以字节计且至少为宽度的 4 倍。时间戳用单调递增的采集时间(纳秒,非负)。调用方分配独立的输出缓冲区,尺寸和格式与输入一致。若传入 xm_frame_result,先设置 struct_size,桌面的 texture 字段恒为 0。
使用 XM_PARAM_COUNT 个浮点数构造 xm_params,参数从下一帧起生效。切镜头或重新开流时调用 xm_desktop_engine_reset 清除跟踪状态。先等同一引擎上的调用退出,再调用 xm_desktop_engine_destroy。
xm_desktop_refresh_license_async / xm_desktop_refresh_lease_async 请求检查,仍受刷新间隔和退避规则约束。Windows 的宿主签名校验适用于两种授权方式。network 仅记录运输诊断,例如 timeout 或 license_fetch_failed;实际效果以 SDK 本地验签后的授权状态为准。真实生产授权接受测试未验证。
引擎 E 码对应函数返回的 xm_status,授权 L000–L019 对应授权状态 JSON 中的数值 code。创建失败时用 xm_desktop_last_error(NULL) 读取文字错误,已有引擎时传入该引擎句柄。
| 状态 | 输出与处理 |
|---|---|
E000 XM_OK | 成功写出画面。授权无效或没有生效的参数时,写出原帧(无效果、无水印)。检查 xm_desktop_license_status。 |
E001 XM_INVALID_ARGUMENT | 不写输出。检查指针、结构大小、帧尺寸、步幅、格式、时间戳或缓冲区重叠。 |
E002 XM_OUT_OF_MEMORY | 输出原帧。可降低分辨率或释放其他引擎。 |
E003 XM_INTERNAL_ERROR | 输出原帧。渲染失败后 SDK 会尝试重建上下文和引擎,保留参数;反复失败时读取文字错误。 |
E005 XM_NOT_CONFIGURED | 创建失败时没有引擎;运行时 GPU 不可用则输出原帧。Windows 若持续返回 gpu_lost,在新进程中重建引擎。 |
| 状态 | 排查方式 |
|---|---|
L003 MALFORMED | Windows 检查 signers 是否含 1 到 4 个格式正确的证书指纹;缺失时需重签。 |
L004 UNKNOWN_KEY | 核对授权签发方和 SDK 包是否匹配。 |
L006 APP_MISMATCH | macOS 核对 Bundle ID;Windows 核对 app_id 和最终宿主 EXE 的 Authenticode 签名及证书指纹。 |
L008 EXPIRED | 核对有效期并联系签发方续期。 |
L012 STORAGE_ERROR | 核对默认存储目录权限,或显式提供当前用户可写的目录。 |
L013 IDENTITY_ERROR | 核对初始化结构大小及平台所需的应用身份。 |
| 项目 | Android / iOS / HarmonyOS | macOS / Windows 的 C 接口 |
|---|---|---|
| 引擎 | 使用各平台绑定,HarmonyOS 通过 Surface 接入相机。 | 以 xm_desktop_engine_create / xm_desktop_engine_destroy 管理不透明句柄;macOS 另有 Objective-C / Swift 接口。 |
| 宿主帧 | Android 用 GL 纹理,iOS 用 BGRA CVPixelBuffer,HarmonyOS 用 Surface。 | 宿主分配 RGBA8 / BGRA8 CPU 缓冲区,macOS 用 Metal 渲染,Windows 用 OpenGL 渲染。 |
| 线程 | 按平台约束管理 GL 线程或采集、渲染队列。 | SDK 持有工作线程和 GPU 上下文,同一引擎上的调用串行。 |
| 参数 | 通过各平台的参数对象设置效果。 | 同套参数含义与范围,xm_params 传 40 个浮点数及可选的妆容风格名和滤镜名。xm_desktop_engine_set_max_faces 和 xm_desktop_engine_set_frame_budget 可设置多人脸上限及帧预算,多脸性能未验证。妆容素材由宿主准备。 |
| 授权身份 | 按各移动平台单独申请。 | 与移动端分开签发。macOS 用 Bundle ID,Windows 用 app_id 及宿主签名证书指纹。 |
移动端可在试用申请页选择平台并填写应用标识,领取 15 天试用证书。每日自助签发 10 个名额;名额用完后请联系客服。同一应用重复申请不会重新计算试用期。桌面授权单独签发,所需信息见 macOS 授权和 Windows 授权。
| 信息 | 用途 |
|---|---|
| 平台与应用身份 | Android 包名;iOS 或鸿蒙 Bundle ID。移动端试用证书绑定所选平台和应用标识。macOS 使用 Bundle ID,Windows 使用 app_id 和宿主 EXE 签名证书指纹。 |
| 版本与设备 | 目标系统、设备型号、CPU 架构,以及开发和发布环境。 |
| 场景与效果 | 相机、录制或 RTC;计划使用的美肤、美型、妆容和滤镜。 |
| 网络条件 | 是否需要离线使用、是否允许访问授权服务,以及计划评估的时间范围。 |
授权可能包含应用身份、有效期、版本和功能限制。需要联网租约时,证书有效期与当前租约状态应一并核对;断网可用时间以具体授权为准。不要把所有失败都视为资源或算法问题。
先约定采集、处理、显示与发送各自负责什么,能减少画面方向、颜色和资源生命周期问题。
| 约定 | 检查内容 |
|---|---|
| 尺寸与方向 | 传入实际帧宽高;横竖屏、旋转和裁切的负责环节清晰。 |
| 前摄镜像 | 本地预览与发送画面分别定义镜像行为,避免重复翻转。 |
| 颜色与格式 | 核对纹理类型、像素格式、通道顺序,以及 RTC 转换约定。 |
| 线程与同步 | 按平台规则调用引擎;异步发送或读回前完成必要的 GPU 同步。 |
| 所有权与有效期 | 确认谁释放输入和输出;跨帧或异步使用前按需要复制。 |
| 停止与恢复 | 先停止输入,再释放处理链路;恢复时重建上下文与资源,按需重置跟踪。 |
磨皮、美白与肤色等参数。各参数范围可能不同,UI 的 0–100 应按对应接口转换。
脸型与五官局部调整。双向参数有各自的中性值,全部置零不一定等于恢复原图。
妆容 ID、贴图与配置需要配套。随包妆容和宿主自备资源应分别管理。
使用交付资源中的 LUT ID,独立控制强度。妆容与滤镜联动由宿主或示例配置决定。
区分恢复参数默认值、清除妆容 / 滤镜、重置跟踪状态和显示原图。它们的目的不同;对比时应保证采集帧、裁切和显示变换一致。
多脸跟踪数量、实际参与效果的人脸数量和帧预算是不同概念。共享核心不代表每个交付版本的接口与效果范围完全一致,也不代表每张检测到的脸都会应用全部效果。
iOS、HarmonyOS 开发代码已补充多脸、预算和统计相关接口,既有示例仍有使用较早 SDK 的情况。请核对随包 API、授权功能和真机结果,再决定界面展示的选项;不要把开发代码的进展当作已发布能力。
先用同一处理链路跑通本地预览,再按 RTC 厂商约定接入纹理回调或自定义视频源。相机采集、效果处理与发送端的帧所有权要明确。
| 场景 | Android / iOS | HarmonyOS |
|---|---|---|
| 本地相机 | 已有示例,具体设备覆盖以交付记录为准 | 已编译,待签名安装与实拍 |
| TRTC | 已有场景代码,真实双端通话待联调 | 暂无示例 |
| Agora / ZEGO | 已有场景代码,真实频道 / 房间待联调 | 暂无示例 |
以下片段基于 SnapBeauty 1.3.2、TRTC 13.5.0.20670、Agora 4.6.4 和 ZEGO 3.25.0,用于说明帧交接,并非完整应用。先按各 SDK 文档初始化、申请权限和配置服务端签发的会话凭据;相机采集、GL 纹理与像素读回辅助函数、线程同步与资源释放由宿主实现;SnapBeauty 的调用见 Android 章节的 SnapBeautyProcessor,授权在应用启动时按授权章节初始化。
处理器须与 TRTC 的 EGL 上下文共享纹理,在回调返回前同步完成处理;切换镜头或结束时按 GL 生命周期释放。processTrtcFrame 是宿主函数,内部调用 SnapBeauty 引擎,内部使用 Android 章节第 4 步的 SnapBeautyProcessor;rotateTexture 是宿主实现的 GL 辅助函数(按角度把纹理旋转后画到新纹理)。
// 在 TRTC 采集开始前注册;常量来自 TRTCCloudDef。
val result = cloud.setLocalVideoProcessListener(
TRTC_VIDEO_PIXEL_FORMAT_Texture_2D,
TRTC_VIDEO_BUFFER_TYPE_TEXTURE,
object : TRTCCloudListener.TRTCVideoFrameListener {
override fun onGLContextCreated() { /* 创建共享上下文处理器 */ }
override fun onProcessVideoFrame(
input: TRTCCloudDef.TRTCVideoFrame?,
output: TRTCCloudDef.TRTCVideoFrame
): Int {
val frame = input ?: return 0
val source = frame.texture ?: return 0
val target = output.texture ?: TRTCCloudDef.TRTCTexture().also {
output.texture = it
}
// 同步转正、处理并还原方向;失败或设备不支持时返回原纹理。
target.textureId = processTrtcFrame(
source.textureId, frame.width, frame.height, frame.rotation * 90
)
target.eglContext10 = source.eglContext10
target.eglContext14 = source.eglContext14
output.width = frame.width; output.height = frame.height
output.rotation = frame.rotation; output.timestamp = frame.timestamp
output.pixelFormat = frame.pixelFormat; output.bufferType = frame.bufferType
return 0
}
override fun onGLContextDestory() { /* 停止输入并释放处理器 */ }
}
)
check(result == 0)
// ---- 宿主函数:processor 是 Android 章节第 4 步的 SnapBeautyProcessor,在 onGLContextCreated 中创建、onGLContextDestory 中释放 ----
fun processTrtcFrame(texture: Int, width: Int, height: Int, rotation: Int): Int {
if (rotation == 0) return processor.process(texture, width, height)
// TRTC 纹理带旋转:先转正(交换宽高),处理后再转回原方向。
val upright = rotateTexture(texture, width, height, rotation)
val uw = if (rotation % 180 == 0) width else height
val uh = if (rotation % 180 == 0) height else width
return rotateTexture(processor.process(upright, uw, uh), uw, uh, -rotation)
}
示例使用自定义视频源,处理后的画面先读回为独立 RGBA 字节数组;前摄镜像只用于本地预览。注意 stride 以像素为单位。检查加入频道与推帧的返回值,退出时先停止推帧。
// 启用外部帧源;加入频道时只发布自定义轨道。
engine.setExternalVideoSource(true, false, Constants.ExternalVideoSourceType.VIDEO_FRAME)
val options = ChannelMediaOptions().apply {
publishCameraTrack = false
publishCustomVideoTrack = true
customVideoTrackId = 0
}
engine.joinChannel(token, channel, uid, options)
// 在持有 GL 上下文的采集线程:processor 即 Android 章节第 4 步的 SnapBeautyProcessor,输入同样须为已旋正、未镜像的纹理。
// reader 为宿主的 glReadPixels 封装,返回顶行优先、紧凑排列、尺寸 width × height × 4 的 RGBA。
val processed = processor.process(cameraTexture, width, height)
val rgba = reader.read(processed, width, height)
val frame = AgoraVideoFrame().apply {
format = AgoraVideoFrame.FORMAT_RGBA
stride = width // 像素数
this.height = height
rotation = 0
timeStamp = captureTimeNs / 1_000_000L
buf = rgba
}
// 在频道已加入、引擎仍有效时推送;0 为轨道 ID。
val code = engine.pushExternalVideoFrameById(frame, 0)
check(code == 0)
captureRequested 和 roomJoined 是宿主管理的状态;在采集回调和房间状态变化时更新,并与引擎销毁同步。captureUnixTimeMs 为从采集时钟映射的 Unix 毫秒时间,strides[0] 以字节为单位。
// 在开始推流前配置自定义采集,并监听主通道开始 / 停止采集。
engine.enableCustomVideoCapture(true, ZegoCustomVideoCaptureConfig().apply {
bufferType = ZegoVideoBufferType.RAW_DATA
})
engine.setCustomVideoCaptureHandler(object : IZegoCustomVideoCaptureHandler() {
override fun onStart(channel: ZegoPublishChannel) {
if (channel == ZegoPublishChannel.MAIN) captureRequested = true
}
override fun onStop(channel: ZegoPublishChannel) {
if (channel == ZegoPublishChannel.MAIN) captureRequested = false
}
})
// 同 Agora:先处理并读回,再拷入宿主复用的直接 ByteBuffer。
// directRgba 顶行优先、紧凑 RGBA,容量为 width × height × 4。
val processed = processor.process(cameraTexture, width, height)
val rgba = reader.read(processed, width, height)
directRgba.clear(); directRgba.put(rgba); directRgba.flip()
val param = ZegoVideoFrameParam().apply {
format = ZegoVideoFrameFormat.RGBA32
this.width = width; this.height = height
rotation = 0; strides[0] = width * 4 // 每行字节数
}
if (roomJoined && captureRequested) {
engine.sendCustomVideoCaptureRawData(
directRgba, directRgba.remaining(), param, captureUnixTimeMs
)
}
这些片段基于 Android 本地链路编写:TRTC 本地纹理处理已验证;Agora 和 ZEGO 的本地 RGBA 转换已验证。真实频道、房间和远端效果仍需使用有效凭据联调。iOS 及鸿蒙请分别参考随包接口说明。
本地预览成功不代表远端已收到效果帧。联调时同时检查时间戳、发送帧格式、方向、镜像、线程、远端画面与音视频同步。业务凭据按厂商要求配置。
iOS 的思路比 Android 简单:BGRA 的 CVPixelBuffer 本身就是各家自定义视频源能直接接收的格式。所以只需要在上面“第 7 步”的 camera.onFrame 里,把 shown(美颜后的缓冲区)同时交给 RTC 发送即可。下面是各家的核心片段,进房凭据(UserSig / Token)一律由你的服务端签发。HarmonyOS 暂无 RTC 示例。
// ① 进房前:关闭 TRTC 自带采集,改为自定义采集
TRTCCloud *trtc = [TRTCCloud sharedInstance];
[trtc enableCustomVideoCapture:TRTCVideoStreamTypeBig enable:YES];
// ② 进房。userSig 由你的服务端生成,不要写进 App
TRTCParams *params = [TRTCParams new];
params.sdkAppId = sdkAppId; params.roomId = roomId;
params.userId = userId; params.userSig = userSig;
[trtc enterRoom:params appScene:TRTCAppSceneVideoCall];
// ③ 进房成功后,每帧把“美颜后的 BGRA 缓冲区”发出去(buffer 就是 BeautyFrameProcessor 的输出)
TRTCVideoFrame *frame = [TRTCVideoFrame new];
frame.pixelFormat = TRTCVideoPixelFormat_32BGRA;
frame.bufferType = TRTCVideoBufferType_PixelBuffer;
frame.pixelBuffer = buffer;
frame.width = (uint32_t)CVPixelBufferGetWidth(buffer);
frame.height = (uint32_t)CVPixelBufferGetHeight(buffer);
frame.rotation = TRTCVideoRotation_0; // 画面已转正
frame.timestamp = (uint64_t)(CMTimeGetSeconds(timestamp) * 1000);
[trtc sendCustomVideoData:TRTCVideoStreamTypeBig frame:frame];
// ④ 退出:先停止发帧,再
[trtc exitRoom];
[trtc enableCustomVideoCapture:TRTCVideoStreamTypeBig enable:NO];
[TRTCCloud destroySharedInstance];// ① 创建引擎,改用自定义视频源(不发布相机轨道)
AgoraRtcEngineKit *agora = [AgoraRtcEngineKit sharedEngineWithAppId:appId delegate:self];
[agora setChannelProfile:AgoraChannelProfileCommunication];
[agora enableVideo];
[agora setExternalVideoSource:YES useTexture:YES sourceType:AgoraExternalVideoSourceTypeVideoFrame];
// ② 加入频道,只发布自定义轨道。token 由你的服务端生成
AgoraRtcChannelMediaOptions *options = [AgoraRtcChannelMediaOptions new];
options.publishCameraTrack = NO;
options.publishCustomVideoTrack = YES;
options.customVideoTrackId = 0;
int result = [agora joinChannelByToken:token channelId:channel uid:uid mediaOptions:options joinSuccess:nil];
NSAssert(result == 0, @"加入频道失败");
// ③ 加入成功后,每帧推送美颜后的 BGRA 缓冲区
AgoraVideoFrame *frame = [AgoraVideoFrame new];
frame.format = 12; // CVPixelBuffer 格式,取值以声网 SDK 头文件为准
frame.textureBuf = buffer;
frame.time = timestamp;
frame.rotation = 0;
BOOL ok = [agora pushExternalVideoFrame:frame videoTrackId:0];
// ④ 退出:先停止推帧,再
[agora leaveChannel:nil];
[AgoraRtcEngineKit destroy];// ① 创建引擎,开启自定义采集,数据类型选 CVPixelBuffer
ZegoEngineProfile *profile = [ZegoEngineProfile new];
profile.appID = appId; profile.scenario = ZegoScenarioDefault;
ZegoExpressEngine *zego = [ZegoExpressEngine createEngineWithProfile:profile eventHandler:self];
ZegoCustomVideoCaptureConfig *custom = [ZegoCustomVideoCaptureConfig new];
custom.bufferType = ZegoVideoBufferTypeCVPixelBuffer;
[zego enableCustomVideoCapture:YES config:custom];
[zego setCustomVideoCaptureHandler:self]; // self 实现 onStart / onStop
// ② 登录房间;登录成功(ZegoRoomStateConnected)后再开始推流
ZegoRoomConfig *config = [ZegoRoomConfig new]; config.token = token; // token 由你的服务端生成
[zego loginRoom:roomId user:[ZegoUser userWithUserID:userId] config:config];
// 在 onRoomStateUpdate 里:[zego startPublishingStream:streamId];
// ③ 只有“主通道已开始采集”时才发帧:onStart 置 YES,onStop 置 NO
- (void)onStart:(ZegoPublishChannel)channel { if (channel == ZegoPublishChannelMain) _captureRequested = YES; }
- (void)onStop:(ZegoPublishChannel)channel { if (channel == ZegoPublishChannelMain) _captureRequested = NO; }
if (_captureRequested) {
[zego sendCustomVideoCapturePixelBuffer:buffer timestamp:timestamp]; // 美颜后的 BGRA 缓冲区
}
// ④ 退出:先停止发帧,再
[zego stopPublishingStream]; [zego logoutRoom];
[ZegoExpressEngine destroyEngine:nil];
先绕过效果处理,确认相机和显示链路。Android 再检查输入是否为 GL_TEXTURE_2D、上下文是否有效、调用是否在约定线程,以及输出是否在有效期内被消费。其他平台核对输入格式、surface 或 Metal 资源状态。
依次检查授权状态、模型与效果资源是否完整、人脸是否被检测到、参数和资源 ID 是否匹配,以及预览或 RTC 发送端是否使用了处理后的输出。Android 失败时可能返回原输入纹理。
分别检查采集方向、处理变换、显示变换和发送约定,避免同一修正执行两次。颜色异常应核对实际 pixelFormat、RGBA / BGRA 通道与转换路径;同时检查保存帧和最终屏幕。
检查是否仍有旧相机回调或异步任务访问已释放资源。用新帧的宽高、方向和镜像重配链路,按版本接口重置跟踪 / 平滑状态;上下文丢失时需要按文档重建资源。
核对版本、授权功能、最大跟踪数、实际处理人数与预算统计。引擎耗时通常不包含完整采集、预览或 RTC 开销;用目标设备和真实场景评估整条链路,不以接口存在推断效果范围。
对比最终应用的包名、签名、资源目录、ABI、线程与采集配置。提供平台、设备、SDK 版本、授权状态码、复现步骤和不含凭据的日志,方便项目联系人定位。
SDK 在设备上处理画面。宿主应用对用户采集、保存和上传的内容负责,上架前请对照以下两份文档。
把下面的检查带到目标设备上。建议使用最终包名、签名、资源和构建配置再走一遍。
按平台章节准备 SDK 和应用身份。移动端可自助领取试用授权,桌面端单独签发。