# After Effects plugin Source: https://docs.facebetter.net/ae/overview Facebetter Beauty for After Effects — coming soon. Coming soon. # API Reference Source: https://docs.facebetter.net/android/api-reference Android API reference for Beauty Effect SDK 2.0 > [!NOTE] > > This page matches SDK **2.0.0**. Package: `net.pixpark.facebetter`. Makeup, reshape, whitening, and smoothing presets: [Parameter enums](/intro/makeup). Auth: [Auth & License](/intro/license). All setter methods return `int`. `0` (`ErrorCode.SUCCESS`) means success; a negative value is an [error code](#errorcode). ## Logging Call `BeautyEffectEngine.setLogConfig` **before** constructing the engine so initialization logs are captured. ### LogLevel ```java theme={null} public enum LogLevel { TRACE(0, "TRACE"), DEBUG(1, "DEBUG"), INFO(2, "INFO"), WARN(3, "WARN"), ERROR(4, "ERROR"), CRITICAL(5, "CRITICAL"); } ``` | Method | Description | | - | - | | `int getLevel()` | Numeric level (`0`–`5`) | | `String getName()` | Name string | | `boolean isEnabledFor(LogLevel other)` | `true` if this level is at least as severe as `other` | | `static LogLevel fromLevel(int level)` | Lookup by numeric value, or `null` | | `static LogLevel fromName(String name)` | Case-insensitive lookup, or `null` | ### LogConfig Nested class: `BeautyEffectEngine.LogConfig`. | Field | Type | Default | Description | | - | - | - | - | | `consoleEnabled` | `boolean` | `false` | Write to logcat / stdout | | `fileEnabled` | `boolean` | `false` | Write to a file | | `level` | `LogLevel` | `INFO` | Minimum level to emit | | `fileName` | `String` | `""` | Log file path; used only when `fileEnabled` is `true` | ```java theme={null} public static class LogConfig { public boolean consoleEnabled = false; public boolean fileEnabled = false; public LogLevel level = LogLevel.INFO; public String fileName = ""; public LogConfig(); public LogConfig(boolean consoleEnabled, boolean fileEnabled, LogLevel level, String fileName); } ``` ```java theme={null} public static void setLogConfig(LogConfig config); ``` Throws `IllegalArgumentException` if `config` or `config.level` is `null`. ## Engine ### EngineConfig Nested class: `BeautyEffectEngine.EngineConfig`. | Field | Type | Default | Description | | - | - | - | - | | `appId` | `String` | — | Dashboard App ID | | `appKey` | `String` | — | Dashboard App Key | | `licenseToken` | `String` | — | License token string, `{token}` JSON, or offline `.lic` contents | **Auth priority:** if `licenseToken` is non-empty, the SDK validates that token locally. Otherwise `appId` + `appKey` are required and the SDK calls `/facebetter/v2/auth`. Details: [Auth & License](/intro/license). ```java theme={null} public static class EngineConfig { public String appId; public String appKey; public String licenseToken; public EngineConfig(); public EngineConfig(String appId, String appKey); public boolean isValid(); } ``` `isValid()` returns `true` when `licenseToken` is non-empty, or when both `appId` and `appKey` are non-empty. ### BeautyEffectEngine Main engine. Construct once, call `release()` when the Activity / Fragment is destroyed. ```java theme={null} public BeautyEffectEngine(Context context, EngineConfig config); public void release(); ``` The constructor throws `IllegalArgumentException` if `context` or `config` is `null`, or if `config.isValid()` is `false`. The SDK reads `context.getPackageName()` for license binding. ### FrameType Set on `ImageFrame.type` **before** `processImage`. There is no separate process-mode argument. | Value | Description | | - | - | | `IMAGE` | Single photo / still. Higher quality. | | `VIDEO` | Camera / live stream. Lower latency. Default. | ```java theme={null} public enum FrameType { IMAGE(0), VIDEO(1); } ``` ```java theme={null} public ImageFrame processImage(ImageFrame inputFrame); ``` Reads `inputFrame.type`. Returns the processed frame (same pixel format as input), or `null` if the engine was already released. Throws `IllegalArgumentException` if `inputFrame` or `inputFrame.type` is `null`. ## Beauty Intensity range `[0.0, 1.0]` unless noted. `0` turns the effect off. ```java theme={null} public int setSmoothing(float value); public int setSmoothingStyle(SmoothingStyle style); public int setWhitening(float value); public int setWhiteningStyle(WhiteningStyle style); public int setRosiness(float value); public int setBrightness(float value); public int setContrast(float value); public int setSaturation(float value); public int setColorTemperature(float value); public int setColorTint(float value); public int setClarity(float value); public int setBeautySkinOnly(boolean enabled); ``` | Method | Description | | - | - | | `setSmoothing` | Skin smoothing intensity | | `setSmoothingStyle` | Smoothing look (`NATURAL`, `TEXTURE`, `SMOOTH`) | | `setWhitening` | Whitening intensity | | `setWhiteningStyle` | Whitening LUT (`COLD_WHITE`, `PINK_WHITE`, `WARM_WHITE`, `WHEAT`, `TAN`) | | `setRosiness` | Rosy-tone intensity | | `setBrightness` | Full-frame brightness, `[-1, 1]`, `0` neutral | | `setContrast` | Full-frame contrast, `[-1, 1]`, `0` neutral | | `setSaturation` | Full-frame saturation, `[-1, 1]`, `0` neutral | | `setColorTemperature` | Full-frame temperature, `[-1, 1]`, `0` neutral | | `setColorTint` | Full-frame tint, `[-1, 1]`, `0` neutral | | `setClarity` | Full-frame clarity, `[0, 1]`, `0` off | | `setBeautySkinOnly` | `true` = apply skin beauty only on detected skin; `false` = whole frame | Style enums: [Parameter enums](/intro/makeup). ## Reshape ```java theme={null} public int setReshape(Reshape param, float value); ``` Intensity range **`[-1.0, 1.0]`**. `0` is off. Positive and negative are opposite directions. ```java theme={null} public enum Reshape { FACE_THIN(0), FACE_V_SHAPE(1), FACE_NARROW(2), FACE_SHORT(3), CHEEKBONE(4), JAWBONE(5), CHIN(6), NOSE_SLIM(7), EYE_SIZE(8), EYE_DISTANCE(9), FACE_SMALL(10), FOREHEAD(11), NOSE_LONG(12), PHILTRUM(13), MOUTH_SIZE(14), MOUTH_POSITION(15), MOUTH_SMILE(16), LIP_THICKNESS(17), EYE_ROUND(18), EYE_POSITION(19), EYE_ANGLE(20), EYE_CORNER_OPEN(21), LOWER_EYELID(22), BROW_POSITION(23), BROW_DISTANCE(24), BROW_THICKNESS(25); } ``` Positive / negative meaning for each value: [Parameter enums](/intro/makeup). ## Body reshape ```java theme={null} public int setBodyReshape(BodyReshape param, float value); ``` Intensity range **`[0.0, 1.0]`**. `0` is off. Requires `resource_body.fbd` via `addResourcePack` first. See [Parameter enums](/intro/makeup) and [Optional resource packs](/intro/resource-packs). ```java theme={null} public enum BodyReshape { BODY_SLIM(0), WAIST_SLIM(1), LEG_SLIM(2), SHOULDER_SLIM(3), ARM_SLIM(4), LEG_LONG(5), BUST_ENHANCE(6), LEG_STRETCH(7), TORSO_LONG(8); } ``` ## Makeup Intensity `[0.0, 1.0]`. Set intensity, then style (mask) and/or color (tint). Pupil and contour do not take a separate tint the same way; see [Parameter enums](/intro/makeup). ```java theme={null} public int setLipstick(float value); public int setLipstickColor(LipstickColor color); public int setBlush(float value); public int setBlushStyle(BlushStyle style); public int setBlushColor(BlushColor color); public int setContour(float value); public int setContourStyle(ContourStyle style); public int setEyeShadow(float value); public int setEyeShadowStyle(EyeShadowStyle style); public int setEyeShadowColor(EyeShadowColor color); public int setEyeLiner(float value); public int setEyeLinerStyle(EyeLinerStyle style); public int setEyeLinerColor(EyeLinerColor color); public int setEyebrow(float value); public int setEyebrowStyle(EyebrowStyle style); public int setEyebrowColor(EyebrowColor color); public int setEyelash(float value); public int setEyelashStyle(EyelashStyle style); public int setEyelashColor(EyelashColor color); public int setPupil(float value); public int setPupilColor(PupilColor color); public int setTeethWhiten(float value); ``` Preset names live in `BeautyParams.*`. Full tables: [Parameter enums](/intro/makeup). ## Virtual background and chroma key Portrait segmentation is the default mask. Chroma key replaces the mask source; fill is still blur or a still image. ```java theme={null} public int setChromaKey(ChromaKeyColor color); public int clearChromaKey(); public int setChromaKeySimilarity(float value); public int setChromaKeySmoothness(float value); public int setChromaKeyDesaturation(float value); public int setVirtualBackgroundBlur(float level); public int setVirtualBackground(String imagePath); public int setVirtualBackground(byte[] imageData); public int clearVirtualBackground(); ``` | Method | Description | | - | - | | `setChromaKey` | Use chroma keying as the mask (`GREEN`, `BLUE`, `RED`) | | `clearChromaKey` | Restore portrait-segmentation mask; does **not** clear the current fill | | `setChromaKeySimilarity` | How close a pixel must be to the key colour. `[0.0, 1.0]` | | `setChromaKeySmoothness` | Edge feather. `[0.0, 1.0]` | | `setChromaKeyDesaturation` | Spill suppression on semi-transparent edges. `[0.0, 1.0]` | | `setVirtualBackgroundBlur` | Background blur. `[0.0, 1.0]`. **`0` clears** the virtual background | | `setVirtualBackground(String)` | Replace background with a PNG/JPG file. Path must be non-empty | | `setVirtualBackground(byte[])` | Same, from encoded PNG/JPG bytes | | `clearVirtualBackground` | Clear blur or image fill | ```java theme={null} public enum ChromaKeyColor { GREEN(0), BLUE(1), RED(2); } ``` Empty path / empty `byte[]` returns `ErrorCode.INVALID_ARGUMENT`. ## Filters and stickers Pass a `.fbd` file path or the file bytes (for example from `assets`). The resource takes effect on the next processed frame. There is no register / unregister API. ```java theme={null} public int setFilter(String fbdFilePath); public int setFilter(byte[] fbdData); public int clearFilter(); public int setFilterIntensity(float intensity); public int setSticker(String fbdFilePath); public int setSticker(byte[] fbdData); public int clearSticker(); public int addResourcePack(String fbdFilePath); public int addResourcePack(byte[] fbdData); public int set3DSticker(String resource); public int set3DSticker(byte[] fbdData); public int clear3DSticker(); ``` | Method | Description | | - | - | | `setFilter` | Apply a LUT filter from a `.fbd` path or in-memory bytes | | `clearFilter` | Remove the current LUT | | `setFilterIntensity` | Mix `[0.0, 1.0]` | | `setSticker` | Apply a 2D sticker from a `.fbd` path or bytes | | `clearSticker` | Remove the current sticker | | `addResourcePack` | Register an extra capability pack (`resource_3d.fbd` before `set3DSticker`, or `resource_body.fbd` before `setBodyReshape`) | | `set3DSticker` | Apply a 3D sticker from a `.fbd` path or bytes | | `clear3DSticker` | Remove the 3D sticker | Empty path / empty `byte[]` returns `ErrorCode.INVALID_ARGUMENT`. ## Stats and callbacks ```java theme={null} public EngineStats getStats(); public int setCallbacks(EngineCallbacks callbacks); ``` `getStats()` returns a snapshot. Fields are `0` if the engine is not initialized. `setCallbacks` returns `ErrorCode.INVALID_ARGUMENT` if `callbacks` is `null`. ### EngineStats ```java theme={null} public class EngineStats { public double fps; public double avgProcessTimeMs; public double sessionTimeS; public int gpuLiveTextures; public int gpuLiveMeshes; public EngineStats(); public EngineStats(double fps, double avgProcessTimeMs, double sessionTimeS, int gpuLiveTextures, int gpuLiveMeshes); } ``` | Field | Description | | - | - | | `fps` | Recent processing FPS | | `avgProcessTimeMs` | Average `processImage` time in milliseconds | | `sessionTimeS` | Seconds since the engine was created | ### EngineCallbacks ```java theme={null} public class EngineCallbacks { public OnEngineEventCallback onEngineEvent; public interface OnEngineEventCallback { void onEngineEvent(int code, String message); } } ``` Leave a field `null` to skip that callback. ### EngineEventCode ```java theme={null} public final class EngineEventCode { public static final int LICENSE_VALIDATION_SUCCESS = 0; public static final int LICENSE_VALIDATION_FAILED = 1; public static final int INITIALIZATION_COMPLETE = 100; public static final int INITIALIZATION_FAILED = 101; } ``` | Code | Meaning | | - | - | | `0` | License accepted | | `1` | License rejected; `message` has detail | | `100` | Engine ready to process frames | | `101` | Engine init failed; `message` has detail | ## ErrorCode Numeric values are the same on all platforms. ```java theme={null} public final class ErrorCode { public static final int SUCCESS = 0; public static final int INVALID_ARGUMENT = -1; public static final int NOT_INITIALIZED = -2; public static final int LICENSE = -3; public static final int UNSUPPORTED = -4; public static final int IO = -5; public static final int PROCESS = -6; public static final int OUT_OF_MEMORY = -7; } ``` | Value | Constant | Meaning | | - | - | - | | `0` | `SUCCESS` | OK | | `-1` | `INVALID_ARGUMENT` | Null, empty, or out-of-range argument | | `-2` | `NOT_INITIALIZED` | Engine not initialized, or already released | | `-3` | `LICENSE` | License / auth failure | | `-4` | `UNSUPPORTED` | Feature or format not supported | | `-5` | `IO` | File or resource I/O failure | | `-6` | `PROCESS` | Frame processing failed | | `-7` | `OUT_OF_MEMORY` | Allocation failed | > [!NOTE] > > **`-1` is invalid argument. `-2` is not initialized.** ## ImageFrame Wraps native pixel buffers. Always call `release()` when finished. ### Create ```java theme={null} public static ImageFrame createWithFile(String filePath); public static ImageFrame createWithRGBA(ByteBuffer data, int width, int height, int stride); public static ImageFrame createWithBGRA(ByteBuffer data, int width, int height, int stride); public static ImageFrame createWithRGB(ByteBuffer data, int width, int height, int stride); public static ImageFrame createWithBGR(ByteBuffer data, int width, int height, int stride); public static ImageFrame createWithI420(int width, int height, ByteBuffer yBuffer, int strideY, ByteBuffer uBuffer, int strideU, ByteBuffer vBuffer, int strideV); public static ImageFrame createWithNV12(int width, int height, ByteBuffer yBuffer, int strideY, ByteBuffer uvBuffer, int strideUV); public static ImageFrame createWithNV21(int width, int height, ByteBuffer yBuffer, int strideY, ByteBuffer vuBuffer, int strideVU); public static ImageFrame createWithAndroid420(int width, int height, ByteBuffer yBuffer, int strideY, ByteBuffer uBuffer, int strideU, ByteBuffer vBuffer, int strideV, int pixelStrideUV); public static ImageFrame createWithTexture(int texture, int width, int height, int stride); public static ImageFrame createWithTexture(int texture, int width, int height, int stride, boolean externalOes); public static ImageFrame createWithTexture(int texture, int width, int height, int stride, boolean externalOes, float[] texMatrix); public void setGlRenderTarget(int texture); public static ImageFrame createWithBitmap(Bitmap bitmap); ``` | Factory | Notes | | - | - | | `createWithFile` | PNG / JPG path | | `createWithAndroid420` | Camera2 `YUV_420_888` | | `createWithTexture` | `GL_TEXTURE_2D` in the **current** GL context; `stride` is usually `width * 4` | | `setGlRenderTarget` | Optional `GL_TEXTURE_2D` render target on the current context. Borrowed, not owned | | `createWithBitmap` | Copies `ARGB_8888` pixels into an RGBA frame | Returns `null` on failure (invalid bitmap, native alloc failed, …). Prefer `ByteBuffer.allocateDirect` for packed / planar factories. ### Fields and operations ```java theme={null} public FrameType type = FrameType.VIDEO; public int rotate(Rotation rotation); public int mirror(MirrorMode mode); public void setMirror(MirrorMode mode); public ImageFrame convert(Format format); public int toFile(String path, int quality); public int toFile(String path); public Bitmap toBitmap(); public boolean isValid(); public void release(); ``` | Method | Description | | - | - | | `rotate` | Rotate in place. Returns `0` on success | | `mirror` | Immediate mirror. `MirrorMode.HORIZONTAL` / `VERTICAL` / `BOTH`. `NONE` leaves pixels unchanged | | `setMirror` | Flag applied **inside** `processImage` (avoids an extra convert). `MirrorMode.NONE` clears | | `convert` | Returns a **new** frame in `format`; caller must `release()` it | | `toFile` | Write PNG/JPG. Quality `1`–`100`; overload defaults to `90` | | `toBitmap` | `ARGB_8888` `Bitmap` (converts to RGBA first if needed) | `rotate`, `mirror`, and `setMirror` change CPU pixel frames only (RGBA, RGB, YUV, and image files). They do not transform an OpenGL texture. Supply a texture that is already upright. ### Accessors ```java theme={null} public int getWidth(); public int getHeight(); public int getStride(); public int getSize(); public ByteBuffer getData(); public Format getFormat(); public int getTexture(); public ByteBuffer getDataY(); public ByteBuffer getDataU(); public ByteBuffer getDataV(); public ByteBuffer getDataUV(); public int getStrideY(); public int getStrideU(); public int getStrideV(); public int getStrideUV(); ``` `getTexture()` returns `0` if the frame is not bound to a GPU texture. ### Format ```java theme={null} public enum Format { I420(0), // YUV 4:2:0 planar Y, U, V NV12(1), // YUV 4:2:0 Y + UV NV21(2), // YUV 4:2:0 Y + VU (Android camera default) BGRA(3), RGBA(4), BGR(5), RGB(6), Texture(7); } ``` ### Rotation Clockwise. ```java theme={null} public enum Rotation { ROTATION_0(0), ROTATION_90(1), ROTATION_180(2), ROTATION_270(3); } ``` # Best Practices Source: https://docs.facebetter.net/android/best-practices Performance and architecture for Beauty Effect SDK 2.0 on Android ## Choose FrameType Set `ImageFrame.type` before `processImage`. There is no extra mode argument. **`FrameType.VIDEO`** (default) * Camera preview, video calls, live streaming * Lower latency **`FrameType.IMAGE`** * Gallery photos, export, capture stills * Higher quality, more cost per frame ```java theme={null} input.type = ImageFrame.FrameType.VIDEO; ImageFrame output = engine.processImage(input); ``` ## Large stills (preview vs export) Do not feed full-resolution pixels into `processImage` on every slider change, and do not throw the original away after scaling. When the photo opens, keep the full `Bitmap` and build **one** preview frame (long edge about 1280–1440). Slider changes call `processImage` on the preview (`FrameType.IMAGE`). Export calls `processImage` on a full-resolution frame with the same setters. Output size matches the input frame — do not upscale the preview. Camera preview stays capture resolution + `FrameType.VIDEO`. ```java theme={null} preview.type = ImageFrame.FrameType.IMAGE; ImageFrame previewOut = engine.processImage(preview); full.type = ImageFrame.FrameType.IMAGE; ImageFrame exportOut = engine.processImage(full); ``` ## Parameter ranges Start low; raise after you confirm face detection and FPS. | API | Range | Notes | | - | - | - | | Smoothing / whitening / rosiness / makeup intensity / filter intensity / VB blur / chroma knobs | `[0, 1]` | `0` off | | Brightness / contrast / saturation / temperature / tint | **`[-1, 1]`** | `0` neutral; full frame | | Clarity | `[0, 1]` | `0` off; full frame | | `setReshape` | **`[-1, 1]`** | `0` off; sign is direction | Live preview (example): ```java theme={null} engine.setSmoothing(0.25f); engine.setWhitening(0.12f); engine.setRosiness(0.08f); engine.setReshape(Reshape.FACE_THIN, 0.15f); engine.setReshape(Reshape.EYE_SIZE, 0.12f); ``` Enable `setBeautySkinOnly(true)` when you do not want smoothing on hair / clothes / background. Preset names: [Parameter enums](/intro/makeup). ## Memory Use **direct** `ByteBuffer`s when creating frames from pixel data: ```java theme={null} ByteBuffer data = ByteBuffer.allocateDirect(width * height * 4); ``` Release native frames: ```java theme={null} ImageFrame input = ImageFrame.createWithRGBA(data, width, height, stride); try { input.type = ImageFrame.FrameType.VIDEO; ImageFrame output = engine.processImage(input); try { // draw / encode output } finally { if (output != null) { output.release(); } } } finally { if (input != null) { input.release(); } } ``` * One engine per process / GL context; do not create per frame * Interactive stills: scale a **copy** for preview; keep the original `Bitmap` for export. See [Large stills](#large-stills) * `convert()` allocates a **new** frame — release it ## OpenGL ES When you pass a GL texture: * Construct the engine on the GL thread with a current context * Keep input texture, `processImage`, and output texture on that same context * Recreate the engine after context loss * Read the result with `output.getTexture()`, not a CPU download, when you stay on GPU See [Implement Beauty](/android/implement-beauty#external-texture-opengl-es). ## One engine, application context Hold a single `BeautyEffectEngine`. Use `getApplicationContext()` so the engine outlives an Activity, and still `release()` when the session ends. ```java theme={null} public final class BeautyEngineHolder { private static BeautyEngineHolder sInstance; private BeautyEffectEngine mEngine; public static synchronized BeautyEngineHolder get(Context context) { if (sInstance == null) { sInstance = new BeautyEngineHolder(context.getApplicationContext()); } return sInstance; } private BeautyEngineHolder(Context app) { BeautyEffectEngine.EngineConfig config = new BeautyEffectEngine.EngineConfig(); config.appId = "your_app_id"; config.appKey = "your_app_key"; mEngine = new BeautyEffectEngine(app, config); } public BeautyEffectEngine engine() { return mEngine; } public synchronized void release() { if (mEngine != null) { mEngine.release(); mEngine = null; } sInstance = null; } } ``` > [!WARNING] > > Always `release()` the engine when the session is done. ImageFrame objects also need `release()`. ## Off the UI thread Run `processImage` on a camera / GL / dedicated thread. Post results to the main looper only for UI. ```java theme={null} executor.execute(() -> { input.type = ImageFrame.FrameType.VIDEO; ImageFrame output = engine.processImage(input); mainHandler.post(() -> callback.onFrame(output)); }); ``` Do not share one `ImageFrame` across threads without your own lock. The demo camera path processes the latest frame on the render thread. ## Filters and stickers from assets Keep `.fbd` files in `assets/` and pass `byte[]` (or copy to `filesDir` and pass a path). Call `setFilter` / `setSticker` once when the user picks an effect, not every frame. Adjust mix with `setFilterIntensity`. GPU upload happens on the next `processImage`. ## Monitor with getStats ```java theme={null} EngineStats stats = engine.getStats(); Log.d(TAG, "fps=" + stats.fps + " avgMs=" + stats.avgProcessTimeMs + " sessionS=" + stats.sessionTimeS); ``` If `avgProcessTimeMs` stays above \~33 ms on a live 30 FPS preview, drop resolution, use `FrameType.VIDEO`, or reduce simultaneous reshape / makeup / VB. ## Persist user sliders Store intensities yourself (`SharedPreferences`). Re-apply with `setSmoothing`, `setReshape`, `setLipstick`, … after the engine is created — the SDK does not persist UI state. ## Lifecycle * `onResume` / `onPause`: start and stop the camera; keep the engine if you will resume soon * `onDestroy` / `onDetach`: `engine.release()` if this owner created it * Create the engine and call process on the thread whose GL context is current. Input and output textures must belong to that context. There is no context flag on the config. ## Tests ```java theme={null} @Test public void processRgbaFrame() { BeautyEffectEngine.EngineConfig config = new BeautyEffectEngine.EngineConfig(); config.appId = "test_app_id"; config.appKey = "test_app_key"; BeautyEffectEngine engine = new BeautyEffectEngine(context, config); ByteBuffer data = ByteBuffer.allocateDirect(640 * 480 * 4); ImageFrame input = ImageFrame.createWithRGBA(data, 640, 480, 640 * 4); input.type = ImageFrame.FrameType.IMAGE; ImageFrame output = engine.processImage(input); assertNotNull(output); assertTrue(output.isValid()); input.release(); output.release(); engine.release(); } ``` Instrument tests need a valid license (`licenseToken` or reachable `/facebetter/v2/auth` plus a bound package name). # Error Handling Source: https://docs.facebetter.net/android/error-handling Handle Beauty Effect SDK 2.0 errors on Android Beauty setters return `int`. Compare against `ErrorCode`. Construction and `processImage` can also throw or return `null`. ## ErrorCode ```java theme={null} public final class ErrorCode { public static final int SUCCESS = 0; public static final int INVALID_ARGUMENT = -1; public static final int NOT_INITIALIZED = -2; public static final int LICENSE = -3; public static final int UNSUPPORTED = -4; public static final int IO = -5; public static final int PROCESS = -6; public static final int OUT_OF_MEMORY = -7; } ``` | Value | Constant | Typical cause | | - | - | - | | `0` | `SUCCESS` | Call succeeded | | `-1` | `INVALID_ARGUMENT` | `null` / empty path, empty `byte[]`, `null` callbacks | | `-2` | `NOT_INITIALIZED` | Engine not initialized, or already released | | `-3` | `LICENSE` | Token / online auth rejected | | `-4` | `UNSUPPORTED` | Format or feature not available | | `-5` | `IO` | Missing `.fbd`, unreadable image, log file path | | `-6` | `PROCESS` | Frame processing failed | | `-7` | `OUT_OF_MEMORY` | Out of memory | > [!NOTE] > > **`-1` is invalid argument. `-2` is not initialized.** ```java theme={null} int ret = engine.setSmoothing(0.5f); if (ret != ErrorCode.SUCCESS) { Log.e(TAG, "setSmoothing failed: " + ret); } ``` ## Construction `new BeautyEffectEngine(context, config)` throws `IllegalArgumentException` when: * `context` or `config` is `null` * `config.isValid()` is `false` (no `licenseToken` and missing `appId` / `appKey`) It does **not** return `null`. ```java theme={null} BeautyEffectEngine.EngineConfig config = new BeautyEffectEngine.EngineConfig(); config.appId = "your_app_id"; config.appKey = "your_app_key"; // config.licenseToken = "..."; BeautyEffectEngine engine; try { engine = new BeautyEffectEngine(this, config); } catch (IllegalArgumentException e) { Log.e(TAG, "EngineConfig invalid", e); return; } ``` License and resource init can still fail asynchronously. Subscribe to engine events: ```java theme={null} EngineCallbacks callbacks = new EngineCallbacks(); callbacks.onEngineEvent = (code, message) -> { if (code == EngineEventCode.LICENSE_VALIDATION_FAILED || code == EngineEventCode.INITIALIZATION_FAILED) { Log.e(TAG, "engine event " + code + ": " + message); } }; engine.setCallbacks(callbacks); ``` | `EngineEventCode` | Value | | - | - | | `LICENSE_VALIDATION_SUCCESS` | `0` | | `LICENSE_VALIDATION_FAILED` | `1` | | `INITIALIZATION_COMPLETE` | `100` | | `INITIALIZATION_FAILED` | `101` | Auth troubleshooting: [Auth & License](/intro/license). Enable logging **before** construct — see [Implement Beauty](/android/implement-beauty). ## processImage ```java theme={null} if (input == null || !input.isValid()) { Log.e(TAG, "Invalid input frame"); return null; } if (input.type == null) { input.type = ImageFrame.FrameType.VIDEO; } ImageFrame output; try { output = engine.processImage(input); } catch (IllegalArgumentException e) { Log.e(TAG, "processImage rejected the frame", e); return null; } if (output == null) { Log.e(TAG, "processImage returned null (engine released or native failure)"); return null; } ``` * `null` input or `null` `type` → `IllegalArgumentException` * Engine already `release()`d → `null` (no exception) * Always `release()` both input and output in a `finally` block ```java theme={null} ImageFrame output = null; try { input.type = ImageFrame.FrameType.VIDEO; output = engine.processImage(input); return output; } finally { if (input != null) { input.release(); } } ``` If you convert the output (`convert`, `toBitmap`), release the extra frame too. ## Filters, stickers, virtual background Empty path or empty `byte[]` returns `ErrorCode.INVALID_ARGUMENT`. Missing files typically return `ErrorCode.IO`. ```java theme={null} int ret = engine.setFilter(fbdPath); if (ret == ErrorCode.INVALID_ARGUMENT) { Log.e(TAG, "Filter path empty"); } else if (ret == ErrorCode.IO) { Log.e(TAG, "Cannot read .fbd: " + fbdPath); } else if (ret != ErrorCode.SUCCESS) { Log.e(TAG, "setFilter: " + ret); } ``` Filter / sticker changes take effect on the **next** processed frame. A successful setter does not prove the texture uploaded; watch later `processImage` results and SDK logs. ## Logging setup `setLogConfig` throws if `config` or `level` is `null`. Create parent directories before enabling file logs. ```java theme={null} File logFile = new File(getFilesDir(), "facebetter.log"); File parent = logFile.getParentFile(); if (parent != null && !parent.exists() && !parent.mkdirs()) { Log.e(TAG, "Cannot create log dir"); return; } BeautyEffectEngine.LogConfig logConfig = new BeautyEffectEngine.LogConfig(); logConfig.consoleEnabled = true; logConfig.fileEnabled = true; logConfig.level = BeautyEffectEngine.LogLevel.DEBUG; logConfig.fileName = logFile.getAbsolutePath(); BeautyEffectEngine.setLogConfig(logConfig); ``` ## Out of memory `ErrorCode.OUT_OF_MEMORY` or `OutOfMemoryError` usually means frames are not released, resolution is too high, or heap/direct buffers accumulated. * Use `ByteBuffer.allocateDirect` for camera / packed pixels * Release every `ImageFrame` (including `convert` results) * Prefer `FrameType.VIDEO` for live camera * Do not construct a new engine every frame ## Stats for slow frames ```java theme={null} EngineStats stats = engine.getStats(); if (stats.avgProcessTimeMs > 33) { Log.w(TAG, "Slow pipeline: " + stats.avgProcessTimeMs + " ms, fps=" + stats.fps); } ``` # FAQ Source: https://docs.facebetter.net/android/faq Android Beauty Effect SDK 2.0 common questions ## Integration ### Engine construction throws or never becomes ready * `IllegalArgumentException`: `EngineConfig` needs a non-empty `licenseToken`, **or** both `appId` and `appKey` * Bind the **application package name** in the Dashboard to this app * For online auth, confirm network access to `/facebetter/v2/auth` * Listen for `EngineEventCode.LICENSE_VALIDATION_FAILED` / `INITIALIZATION_FAILED` * Call `setLogConfig` **before** `new BeautyEffectEngine(...)` Auth: [Auth & License](/intro/license). ### Compile: cannot resolve `net.pixpark.facebetter` * Maven: `implementation 'net.pixpark:facebetter:2.0.0'` * Local AAR: `implementation files('libs/facebetter.aar')` and Sync * Clean / Rebuild ### `UnsatisfiedLinkError` * Device ABI must be `arm64-v8a` or `armeabi-v7a` * Keep `libfacebetter.so` if you shrink/obfuscate; keep Facebetter native methods in ProGuard / R8 * Confirm the AAR / Maven artifact is complete ## Effects ### Beauty looks weak * Raise intensities in `[0, 1]` (`setSmoothing`, `setWhitening`, makeup, …) * Reshape uses **`[-1, 1]`** — a value near `0` is almost off * Confirm `INITIALIZATION_COMPLETE` and that `processImage` returns a non-null frame ### Face looks warped * Lower `setReshape` magnitudes; opposite sign reverses the direction * Avoid stacking many reshape knobs at high absolute values * Use `FrameType.IMAGE` for still export if live `VIDEO` looks softer, not stronger ### Virtual background does nothing * Call `setVirtualBackgroundBlur(level)` with `level > 0`, **or** `setVirtualBackground(path|bytes)` * `setVirtualBackgroundBlur(0)` **clears** the effect * Image path must be a readable PNG/JPG; empty path returns `ErrorCode.INVALID_ARGUMENT` * Green screen: `setChromaKey(ChromaKeyColor.GREEN)` plus a fill (blur or image) * `clearChromaKey()` only restores the portrait mask; it does not remove the fill ### Filter or sticker does not appear * Pass a `.fbd` **path or bytes** to `setFilter` / `setSticker` (no register API) * Upload happens on the **next** `processImage` on the GL thread * `setFilterIntensity(0)` makes a LUT invisible ## Performance and memory ### Preview is slow * `input.type = ImageFrame.FrameType.VIDEO` * Lower capture resolution * Fewer simultaneous reshape / makeup / VB effects * `processImage` off the main thread (camera or GL thread) * Watch `engine.getStats().avgProcessTimeMs` * Large gallery stills: build a smaller preview frame when the photo opens; export the original once. See [Best practices](/android/best-practices#large-stills) ### Memory climbs or native crash * `release()` every `ImageFrame`, including `convert()` results and `processImage` output * Use `ByteBuffer.allocateDirect` * One engine instance; call `engine.release()` in `onDestroy` ### ANR * Do not run `processImage` on the UI thread for HD video * Do not load large `.fbd` / JPEG files on the main thread ## Image and camera ### How do I change pixel format? Use `ImageFrame.convert(Format)` (returns a new frame): ```java theme={null} ImageFrame rgba = frame.convert(ImageFrame.Format.RGBA); ImageFrame nv21 = frame.convert(ImageFrame.Format.NV21); ImageFrame i420 = frame.convert(ImageFrame.Format.I420); ``` Packed pixels: `getData()`. Planar YUV: `getDataY()` / `getDataU()` / `getDataV()` or `getDataUV()`. ### Camera2 preview 1. `Image` from `YUV_420_888` 2. `ImageFrame.createWithAndroid420(...)` 3. `rotate` / `mirror` for sensor + front camera 4. `input.type = FrameType.VIDEO` 5. `processImage(input)` 6. Convert or `getTexture()` for display ### Rotation `rotate(ImageFrame.Rotation.ROTATION_90)` (0 / 90 / 180 / 270, clockwise) mutates the frame. ## Permissions Online auth: ```xml theme={null} ``` Camera preview: `CAMERA` (runtime request on API 23+). File logs outside app storage may need storage permissions on older APIs. ## Debugging Enable logs before creating the engine: ```java theme={null} BeautyEffectEngine.LogConfig logConfig = new BeautyEffectEngine.LogConfig(); logConfig.consoleEnabled = true; logConfig.fileEnabled = true; logConfig.level = BeautyEffectEngine.LogLevel.DEBUG; logConfig.fileName = getFilesDir() + "/facebetter.log"; BeautyEffectEngine.setLogConfig(logConfig); ``` Setters return `0` on success. **`-1` = invalid argument, `-2` = not initialized.** Full list: [Error Handling](/android/error-handling). ## Compatibility * Android 7.0 (API 24)+ * ABIs: `arm64-v8a`, `armeabi-v7a` * Maven: `net.pixpark:facebetter:2.0.0` To upgrade: bump the Maven / AAR version, Clean, rebuild, and retest license + camera + stills. # Implement Beauty Source: https://docs.facebetter.net/android/implement-beauty Integrate Beauty Effect SDK 2.0 on Android ## Add the SDK ### Method A: Maven (recommended) In the project `build.gradle` / `settings.gradle` repositories: ```groovy theme={null} repositories { mavenCentral() } ``` Module `build.gradle`: ```groovy theme={null} dependencies { implementation 'net.pixpark:facebetter:2.0.0' } ``` **Version Catalog** (`gradle/libs.versions.toml`): ```toml theme={null} [versions] facebetter = "2.0.0" [libraries] facebetter = { group = "net.pixpark", name = "facebetter", version.ref = "facebetter" } ``` ```groovy theme={null} dependencies { implementation libs.facebetter } ``` ### Method B: Local AAR Download the SDK from [Download](https://facebetter.net/download), copy `facebetter.aar` into `libs/`, then: ```groovy theme={null} dependencies { implementation files('libs/facebetter.aar') implementation libs.appcompat implementation libs.material } ``` ### Permissions `AndroidManifest.xml`: ```xml theme={null} ``` | Permission | When | | - | - | | Network | Required for online `appId` + `appKey`. Offline `licenseToken` does not need the network for validation | | Storage | Only if `LogConfig.fileEnabled` writes outside the app directory | | Camera | Only if you capture live frames | Request `CAMERA` at runtime on API 23+. ## Imports ```java theme={null} import net.pixpark.facebetter.BeautyEffectEngine; import net.pixpark.facebetter.BeautyParams.*; import net.pixpark.facebetter.EngineCallbacks; import net.pixpark.facebetter.EngineEventCode; import net.pixpark.facebetter.EngineStats; import net.pixpark.facebetter.ErrorCode; import net.pixpark.facebetter.ImageFrame; ``` ## Logging Logging is off by default. Enable it **before** `new BeautyEffectEngine(...)`. > [!WARNING] > > Call `setLogConfig` before constructing the engine, or you will miss initialization logs. ```java theme={null} BeautyEffectEngine.LogConfig logConfig = new BeautyEffectEngine.LogConfig(); logConfig.consoleEnabled = true; logConfig.fileEnabled = true; logConfig.level = BeautyEffectEngine.LogLevel.INFO; logConfig.fileName = getFilesDir() + "/facebetter.log"; BeautyEffectEngine.setLogConfig(logConfig); ``` ## Create the engine Credentials: [Subscription](/intro/enable-service#get-appid-and-appkey). Auth details: [Auth & License](/intro/license). If `licenseToken` is non-empty, it is used (license token / `{token}` JSON / offline `.lic`). Otherwise `appId` + `appKey` call `/facebetter/v2/auth`. ```java theme={null} BeautyEffectEngine.EngineConfig config = new BeautyEffectEngine.EngineConfig(); config.appId = "your appId"; config.appKey = "your appKey"; // config.licenseToken = "/* license token, {token} JSON, or .lic contents */"; BeautyEffectEngine engine; try { engine = new BeautyEffectEngine(this, config); } catch (IllegalArgumentException e) { Log.e(TAG, "Invalid EngineConfig", e); return; } ``` The constructor does not return `null`; it throws if `config` is invalid. Watch `EngineEventCode.INITIALIZATION_COMPLETE` / `INITIALIZATION_FAILED` on callbacks for async init. ## Beauty Intensity `[0.0, 1.0]`. `0` disables the effect. Check `ErrorCode.SUCCESS` (`0`). ```java theme={null} engine.setSmoothing(0.5f); engine.setSmoothingStyle(SmoothingStyle.NATURAL); engine.setWhitening(0.3f); engine.setWhiteningStyle(WhiteningStyle.COLD_WHITE); engine.setRosiness(0.15f); engine.setBrightness(0.1f); engine.setClarity(0.2f); engine.setBeautySkinOnly(true); ``` > [!TIP] > > With `setBeautySkinOnly(true)`, smoothing / whitening / rosiness apply only on detected skin. Clothing and background stay unchanged. Styles: [Parameter enums](/intro/makeup). ## Reshape Range **`[-1.0, 1.0]`**. `0` is off. ```java theme={null} engine.setReshape(Reshape.FACE_THIN, 0.4f); engine.setReshape(Reshape.EYE_SIZE, 0.3f); engine.setReshape(Reshape.CHIN, -0.2f); ``` All 26 parameters (`FACE_THIN` … `BROW_THICKNESS`) and positive / negative directions: [Parameter enums](/intro/makeup). ## Body reshape Range **`[0.0, 1.0]`**. `0` is off. Register `resource_body.fbd` with `addResourcePack` first (not in the AAR). See [Parameter enums](/intro/makeup) and [Optional resource packs](/intro/resource-packs). ```java theme={null} engine.addResourcePack(loadAssetBytes("resource_body.fbd")); engine.setBodyReshape(BodyReshape.WAIST_SLIM, 0.4f); engine.setBodyReshape(BodyReshape.LEG_STRETCH, 0.3f); engine.setBodyReshape(BodyReshape.TORSO_LONG, 0.3f); ``` ## Makeup Set intensity, then style and/or color. ```java theme={null} engine.setLipstick(0.6f); engine.setLipstickColor(LipstickColor.ROUGE); engine.setBlush(0.4f); engine.setBlushStyle(BlushStyle.SUN_KISSED); engine.setBlushColor(BlushColor.CORAL_PINK); engine.setContour(0.35f); engine.setContourStyle(ContourStyle.NATURAL); engine.setEyeShadow(0.45f); engine.setEyeShadowStyle(EyeShadowStyle.SOFT); engine.setEyeShadowColor(EyeShadowColor.PLUM); engine.setEyeLiner(0.4f); engine.setEyeLinerStyle(EyeLinerStyle.CLASSIC); engine.setEyebrow(0.35f); engine.setEyebrowStyle(EyebrowStyle.NATURAL); engine.setEyelash(0.4f); engine.setEyelashStyle(EyelashStyle.CLASSIC); engine.setPupil(0.3f); engine.setPupilColor(PupilColor.HAZEL); ``` Full preset lists: [Parameter enums](/intro/makeup). ## Virtual background and chroma key Blur (`0` clears), still image, or chroma-key mask + fill. ```java theme={null} engine.setVirtualBackgroundBlur(0.6f); int ret = engine.setVirtualBackground("/sdcard/bg.jpg"); if (ret != ErrorCode.SUCCESS) { Log.e(TAG, "setVirtualBackground failed: " + ret); } byte[] png = loadAssetBytes("backgrounds/office.png"); engine.setVirtualBackground(png); engine.setChromaKey(ChromaKeyColor.GREEN); engine.setChromaKeySimilarity(0.4f); engine.setChromaKeySmoothness(0.3f); engine.setChromaKeyDesaturation(0.2f); engine.clearChromaKey(); engine.clearVirtualBackground(); ``` `clearChromaKey()` restores portrait segmentation and does **not** remove the current blur/image fill. ## Filters and stickers Load a `.fbd` from a file path or `assets`. No register step. ```java theme={null} engine.setFilter(getFilesDir() + "/filters/vivid.fbd"); engine.setFilterIntensity(0.8f); byte[] lut = loadAssetBytes("filters/vivid.fbd"); engine.setFilter(lut); engine.clearFilter(); engine.setSticker(getFilesDir() + "/stickers/cherry.fbd"); byte[] sticker = loadAssetBytes("stickers/cherry.fbd"); engine.setSticker(sticker); engine.clearSticker(); ``` 3D stickers need the optional `resource_3d.fbd` pack (not in the AAR). See [Optional resource packs](/intro/resource-packs). Register it from your app assets, then apply a 3D sticker `.fbd`: ```java theme={null} engine.addResourcePack(loadAssetBytes("resource_3d.fbd")); engine.set3DSticker(loadAssetBytes("stickers/3d/oculos.fbd")); engine.clear3DSticker(); ``` Filter / sticker changes take effect on the next `processImage`. ```java theme={null} private byte[] loadAssetBytes(String path) throws IOException { try (InputStream in = getAssets().open(path); ByteArrayOutputStream out = new ByteArrayOutputStream()) { byte[] buf = new byte[4096]; int n; while ((n = in.read(buf)) >= 0) { out.write(buf, 0, n); } return out.toByteArray(); } } ``` ## Callbacks and stats ```java theme={null} EngineCallbacks callbacks = new EngineCallbacks(); callbacks.onEngineEvent = (code, message) -> { switch (code) { case EngineEventCode.LICENSE_VALIDATION_SUCCESS: Log.d(TAG, "License OK"); break; case EngineEventCode.LICENSE_VALIDATION_FAILED: Log.e(TAG, "License failed: " + message); break; case EngineEventCode.INITIALIZATION_COMPLETE: Log.d(TAG, "Engine ready"); break; case EngineEventCode.INITIALIZATION_FAILED: Log.e(TAG, "Init failed: " + message); break; default: break; } }; engine.setCallbacks(callbacks); EngineStats stats = engine.getStats(); Log.d(TAG, "fps=" + stats.fps + " avgMs=" + stats.avgProcessTimeMs + " sessionS=" + stats.sessionTimeS); ``` ## Process frames > [!WARNING] > > Call `ImageFrame.release()` on every frame you create (and on `processImage` output). Skipping this leaks native memory. Set `ImageFrame.type` to `FrameType.IMAGE` (still) or `FrameType.VIDEO` (camera / live). `processImage` takes **only** the frame — no extra mode argument. ```java theme={null} ByteBuffer data = ByteBuffer.allocateDirect(width * height * 4); ImageFrame input = ImageFrame.createWithRGBA(data, width, height, width * 4); input.type = ImageFrame.FrameType.VIDEO; ImageFrame output = engine.processImage(input); ``` From a file or `Bitmap`: ```java theme={null} ImageFrame input = ImageFrame.createWithFile("/sdcard/photo.jpg"); input.type = ImageFrame.FrameType.IMAGE; ImageFrame output = engine.processImage(input); Bitmap preview = output.toBitmap(); ``` Rotate / mirror before processing if the camera sensor is rotated. These calls change CPU pixels only, not an OpenGL texture: ```java theme={null} input.rotate(ImageFrame.Rotation.ROTATION_90); input.mirror(ImageFrame.MirrorMode.HORIZONTAL); ``` > [!TIP] > > The engine keeps input and output pixel formats aligned (NV21 in → NV21 out, RGBA in → RGBA out). Read pixels with `getData()` / planar accessors, or convert: ```java theme={null} ImageFrame rgba = output.convert(ImageFrame.Format.RGBA); ByteBuffer pixels = rgba.getData(); int w = rgba.getWidth(); int h = rgba.getHeight(); int stride = rgba.getStride(); rgba.release(); ImageFrame i420 = output.convert(ImageFrame.Format.I420); ByteBuffer y = i420.getDataY(); ByteBuffer u = i420.getDataU(); ByteBuffer v = i420.getDataV(); i420.release(); ``` ## Camera pipeline Typical Camera2 `YUV_420_888` → engine → display: ```java theme={null} Image.Plane[] planes = image.getPlanes(); ImageFrame input = ImageFrame.createWithAndroid420( image.getWidth(), image.getHeight(), planes[0].getBuffer(), planes[0].getRowStride(), planes[1].getBuffer(), planes[1].getRowStride(), planes[2].getBuffer(), planes[2].getRowStride(), planes[1].getPixelStride()); if (input == null) { image.close(); return; } if (isFrontCamera) { input.rotate(ImageFrame.Rotation.ROTATION_270); input.mirror(ImageFrame.MirrorMode.HORIZONTAL); } else { input.rotate(ImageFrame.Rotation.ROTATION_90); } input.type = ImageFrame.FrameType.VIDEO; ImageFrame output = engine.processImage(input); image.close(); ``` ## External texture (OpenGL ES) > [!WARNING] > > Create the engine and call process on the thread whose GL context is current. Input and output textures must belong to that context. CPU frames do not need a caller GL context. There is no context flag on the config. Use this when you already render with OpenGL ES and want to avoid CPU round-trips. ```java theme={null} BeautyEffectEngine.EngineConfig config = new BeautyEffectEngine.EngineConfig(); config.appId = "your appId"; config.appKey = "your appKey"; BeautyEffectEngine engine = new BeautyEffectEngine(context, config); engine.setSmoothing(0.5f); ``` ```java theme={null} int stride = srcWidth * 4; ImageFrame input = ImageFrame.createWithTexture(srcTextureId, srcWidth, srcHeight, stride); if (input == null) { return; } input.type = ImageFrame.FrameType.VIDEO; ImageFrame output = engine.processImage(input); if (output == null) { input.release(); return; } int dstTextureId = output.getTexture(); int dstWidth = output.getWidth(); int dstHeight = output.getHeight(); output.release(); input.release(); ``` Recommended sampler state for input `GL_TEXTURE_2D`: ```java theme={null} GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE); ``` Notes: * Input texture: `GL_TEXTURE_2D`, typically RGBA; `stride` is usually `width * 4` * Lazy-create the engine in the first GL callback so the context is current * Output texture is owned by the SDK; do not `glDeleteTextures` it. Release the `ImageFrame` * If the GL context is lost, `release()` the engine and create it again on the new context * Use `FrameType.VIDEO` for live GL pipelines * For TRTC / Agora / LiveKit and similar SDKs: [Third-party Integration](/android/third-party-integration) ## Lifecycle > [!WARNING] > > Call `engine.release()` in `onDestroy` / `onDetach`. Unreleased engines leak GPU and native memory. ```java theme={null} @Override protected void onDestroy() { super.onDestroy(); if (mBeautyEngine != null) { mBeautyEngine.release(); mBeautyEngine = null; } } ``` ```java theme={null} if (input != null) { input.release(); } if (output != null) { output.release(); } ``` ## Related * [Third-party Integration](/android/third-party-integration) * [Best Practices](/android/best-practices) * [Error Handling](/android/error-handling) * [FAQ](/android/faq) * [API Reference](/android/api-reference) # Quick Start Source: https://docs.facebetter.net/android/quick-start Run the Android sample application ## Requirements * **Android**: 7.0 (API 24) and above * **Language**: Java * **ABIs**: `armeabi-v7a`, `arm64-v8a` * **SDK**: Facebetter **2.0.0** (`net.pixpark:facebetter:2.0.0`) ## Get the sample Clone the [GitHub repository](https://github.com/pixpark/facebetter-sdk) and open `demo/android` in Android Studio. ```bash theme={null} git clone https://github.com/pixpark/facebetter-sdk.git ``` ## Bind the package name and credentials ### Bind the application package name Follow [Subscription](/intro/enable-service#bind-application-information) and bind your Android **application package name** in the Dashboard, for example `com.example.app`. ### Create the engine Follow [Subscription](/intro/enable-service#get-appid-and-appkey) to copy `appId` / `appKey`, or use a `licenseToken`. Open the demo camera Activity and set `EngineConfig` before `new BeautyEffectEngine(...)`. **Online** (`appId` + `appKey` → `/facebetter/v2/auth`): ```java theme={null} BeautyEffectEngine.EngineConfig config = new BeautyEffectEngine.EngineConfig(); config.appId = "your appId"; config.appKey = "your appKey"; mBeautyEngine = new BeautyEffectEngine(this, config); ``` **Token** (license token string, `{token}` JSON, or offline `.lic` contents). If `licenseToken` is non-empty, it wins and the SDK does not call the network with `appId` / `appKey`: ```java theme={null} BeautyEffectEngine.EngineConfig config = new BeautyEffectEngine.EngineConfig(); config.licenseToken = "/* license token, {token} JSON, or .lic contents */"; mBeautyEngine = new BeautyEffectEngine(this, config); ``` > [!TIP] > > Auth modes and offline `.lic` files: [Auth & License](/intro/license). ## Run Sync Gradle in Android Studio, pick a device or emulator, and run. ![Android Project](https://mintcdn.com/facebetter/DM5KtVsHX1q4Zlkm/images/android-1.png?fit=max\&auto=format\&n=DM5KtVsHX1q4Zlkm\&q=85\&s=a438660e665544658ee265245f033df2) # Third-party Integration Source: https://docs.facebetter.net/android/third-party-integration Wire Facebetter beauty into TRTC, Agora, LiveKit, and other Android video pipelines SDK **2.0.0**. Hook Facebetter into a third-party SDK’s **custom video preprocess** callback: on that SDK’s **OpenGL ES thread**, run `processImage` on an external texture, then return the output texture. Full texture rules: [Implement Beauty · External texture](/android/implement-beauty#external-texture-opengl-es). Room join, publish, and permissions belong in the vendor’s docs — this page only covers the Facebetter hookup. ``` Third-party SDK (GL thread) input textureId ↓ ImageFrame.createWithTexture → processImage ↓ output textureId → write back to vendor frame / callback ``` ## Shared contract | Item | Requirement | | - | - | | Input | `GL_TEXTURE_2D` (RGBA); `stride` is usually `width * 4` | | Frame type | `ImageFrame.FrameType.VIDEO` | | Output | SDK owns the output texture — do not `glDeleteTextures`. Always `ImageFrame.release()` | | Lifecycle | When the vendor destroys the GL context, `engine.release()`, then recreate on the new context | `createWithTexture` accepts `GL_TEXTURE_2D`, or `GL_TEXTURE_EXTERNAL_OES` when `externalOes` is true. For OES, pass the 16-float matrix from `SurfaceTexture.getTransformMatrix`. Blitting to `GL_TEXTURE_2D` is still fine. ### Shared helper Reuse this on every vendor GL callback (must run on the GL thread): ```java theme={null} import net.pixpark.facebetter.BeautyEffectEngine; import net.pixpark.facebetter.ImageFrame; /** @return beauty output GL_TEXTURE_2D; on failure returns srcTextureId (or 0, your choice) */ static int processTexture(BeautyEffectEngine engine, int srcTextureId, int width, int height) { if (engine == null || srcTextureId == 0 || width <= 0 || height <= 0) { return srcTextureId; } int stride = width * 4; ImageFrame input = ImageFrame.createWithTexture(srcTextureId, width, height, stride); if (input == null) { return srcTextureId; } input.type = ImageFrame.FrameType.VIDEO; ImageFrame output = engine.processImage(input); if (output == null) { input.release(); return srcTextureId; } int dst = output.getTexture(); output.release(); input.release(); return dst != 0 ? dst : srcTextureId; } ``` Create the engine (also on the GL thread): ```java theme={null} BeautyEffectEngine.EngineConfig config = new BeautyEffectEngine.EngineConfig(); config.appId = "your appId"; config.appKey = "your appKey"; // or config.licenseToken = "..."; BeautyEffectEngine engine = new BeautyEffectEngine(context, config); engine.setSmoothing(0.5f); ``` Credentials: [Subscription](/intro/enable-service), [Auth & License](/intro/license). *** ## TRTC (Tencent) Hook: `TRTCCloud.setLocalVideoProcessListener`. Use pixel format **Texture\_2D** and buffer type **TEXTURE**. Create Facebetter in `onGLContextCreated`, process in `onProcessVideoFrame` and set `dstFrame.texture.textureId`, `release()` in `onGLContextDestory`. ```java theme={null} import com.tencent.trtc.TRTCCloud; import com.tencent.trtc.TRTCCloudDef; import com.tencent.trtc.TRTCCloudListener; trtcCloud.setLocalVideoProcessListener( TRTCCloudDef.TRTC_VIDEO_PIXEL_FORMAT_Texture_2D, TRTCCloudDef.TRTC_VIDEO_BUFFER_TYPE_TEXTURE, new TRTCCloudListener.TRTCVideoFrameListener() { @Override public void onGLContextCreated() { // TRTC has bound the GL context — lazy-create BeautyEffectEngine here ensureEngine(); } @Override public int onProcessVideoFrame( TRTCCloudDef.TRTCVideoFrame srcFrame, TRTCCloudDef.TRTCVideoFrame dstFrame) { int out = processTexture( beautyEngine, srcFrame.texture.textureId, srcFrame.width, srcFrame.height); dstFrame.texture.textureId = out; return 0; } @Override public void onGLContextDestory() { if (beautyEngine != null) { beautyEngine.release(); beautyEngine = null; } } }); ``` Release the engine after removing the listener or leaving the room. See Tencent’s third-party beauty guide for the latest TRTC details. *** ## Agora Hook: `RtcEngine.registerVideoFrameObserver` (Video SDK **4.x**). You need to: 1. Return `PROCESS_MODE_READ_WRITE` from `getVideoFrameProcessMode()` 2. Prefer a **TextureBuffer** with type **RGB (`GL_TEXTURE_2D`)** 3. Run Facebetter in `onCaptureVideoFrame` (or your chosen observe position), then **write** the processed texture back into the `VideoFrame` ```java theme={null} import io.agora.rtc2.RtcEngine; import io.agora.rtc2.video.IVideoFrameObserver; import io.agora.base.VideoFrame; engine.registerVideoFrameObserver(new IVideoFrameObserver() { @Override public boolean onCaptureVideoFrame(int sourceType, VideoFrame videoFrame) { VideoFrame.Buffer buffer = videoFrame.getBuffer(); if (!(buffer instanceof VideoFrame.TextureBuffer)) { return true; // non-texture: pass through or convert, per your app } VideoFrame.TextureBuffer tex = (VideoFrame.TextureBuffer) buffer; if (tex.getType() != VideoFrame.TextureBuffer.Type.RGB) { return true; // OES: convert to GL_TEXTURE_2D, or adjust format preference } ensureEngine(); // must use the current GL / EGL context int outId = processTexture( beautyEngine, tex.getTextureId(), tex.getWidth(), tex.getHeight()); // Wrap outId as a TextureBuffer and write it back into videoFrame. // Exact APIs (TextureBufferHelper / replaceBuffer, etc.) vary by Agora version — // follow Agora’s raw video-frame docs, then return true. return true; } @Override public int getVideoFrameProcessMode() { return IVideoFrameObserver.PROCESS_MODE_READ_WRITE; } @Override public int getVideoFormatPreference() { // Prefer a processable texture; use the constant from your Agora version return IVideoFrameObserver.VIDEO_PIXEL_DEFAULT; } // Implement other callbacks as needed; POSITION_POST_CAPTURER is common }); ``` > [!WARNING] > > How you inject a new `textureId` back into Agora’s `VideoFrame` depends on their TextureBuffer helpers and differs across major versions. Facebetter only produces a new `GL_TEXTURE_2D`; the write-back step must follow [Agora’s video frame observer](https://docs.agora.io/en/video-calling/develop/product-workflow) / API Reference. Unregister the observer and `beautyEngine.release()` before destroying `RtcEngine`. *** ## LiveKit Hook: pass an `org.webrtc.VideoProcessor` (or equivalent track processor) when creating the local video track. Process textures in `onFrameCaptured`, then deliver via `sink.onFrame(...)`. ```kotlin theme={null} import io.livekit.android.room.track.LocalVideoTrackOptions import org.webrtc.VideoFrame import org.webrtc.VideoProcessor import org.webrtc.VideoSink class FacebetterVideoProcessor( private val appContext: android.content.Context, ) : VideoProcessor { private var sink: VideoSink? = null private var beautyEngine: BeautyEffectEngine? = null override fun setSink(videoSink: VideoSink?) { sink = videoSink } override fun onCapturerStarted(success: Boolean) {} override fun onCapturerStopped() { beautyEngine?.release() beautyEngine = null } override fun onFrameCaptured(frame: VideoFrame) { val buffer = frame.buffer if (buffer !is VideoFrame.TextureBuffer || buffer.type != VideoFrame.TextureBuffer.Type.RGB ) { sink?.onFrame(frame) return } ensureEngine() // LiveKit / WebRTC current EGL context val outId = processTexture( beautyEngine, buffer.textureId, buffer.width, buffer.height, ) // Build a new TextureBuffer / VideoFrame from outId, then: // sink?.onFrame(processedFrame) // processedFrame.release() // // TextureBuffer construction needs WebRTC Handler / YuvConverter, etc. — // follow LiveKit Android SDK and WebRTC samples for the wrap. sink?.onFrame(frame) } } // Attach the processor when creating the track (API per your livekit-android version) val videoTrack = room.localParticipant.createVideoTrack( options = LocalVideoTrackOptions(), videoProcessor = FacebetterVideoProcessor(context), ) videoTrack.startCapture() room.localParticipant.publishVideoTrack(videoTrack) ``` You can also implement a custom `VideoCapturer`, run `processTexture` after capture, then call `capturerObserver.onFrameCaptured`. Official processors (for example virtual background) live in LiveKit’s `livekit-android-track-processors` module. *** ## Troubleshooting | Symptom | Check | | - | - | | Black / no video | Engine created and `processImage` on the vendor **GL thread**; failed frames not dropped by mistake | | Intermittent crash | `release()` on GL destroy / capturer stop; never `glDeleteTextures` on the output | | Distortion | Width / height / rotation / mirror match the vendor frame; OES not converted to 2D | ## Related * [Implement Beauty](/android/implement-beauty) * [Best Practices](/android/best-practices) * [Error Handling](/android/error-handling) * [API Reference](/android/api-reference) # Face Makeup Source: https://docs.facebetter.net/effect-creator/face-makeup Create face makeup effects with Facebetter Effect Creator Coming soon. # Face Sticker Source: https://docs.facebetter.net/effect-creator/face-sticker Instructions for using the Face Sticker creation plugin ## Workflow Initialization Before designing with the plugin, you need to initialize the workspace: 1. Under the **Workflow Initialization** section, click the **Initialize Workspace** button. 2. The plugin will automatically create a 2048x2048 canvas named `Facebetter_Workspace`. 3. The canvas contains 106 standard face **design** reference points (the Figma template). 4. **Option**: Check "Show Landmark Numbers" to easily identify the numbers of different parts. ## Sticker Layer and Attribute Binding This is the core step of sticker creation, used to define how the sticker follows face movements. 1. **Select Layer**: Select the sticker layer you designed in the Figma canvas (it must be located within the workspace). 2. **Configure Attributes**: * **Blend Mode**: Set the fusion effect between the sticker and the face (e.g., Normal, Overlay, Screen, etc.). * **Position Type**: * **Landmarks**: Follow specific face landmarks (most common). * **Face Rect**: Position based on the entire face area. * **Screen Space**: Fixed at a screen position. * **Trigger Type**: Set the conditions for the sticker to appear (Always show, Face detected, Mouth open, etc.). * **Trigger Delay**: Delay time after triggering. * **Alpha Factor**: Adjust the overall transparency of the sticker. * **FPS**: Set the animation frame rate (if the layer contains multiple frames). ## Preview and Export 1. **3D Preview**: * Click **3D Preview**. * In the popup window, you can see the real-time effect of the sticker on a 3D face model. * Supports left-click to rotate, right-click to pan, and scroll wheel to zoom. 2. **Export Package**: * After confirming the preview, click **Export**. * The plugin writes a **`.fbd`** package. Load it with `setSticker` (path or bytes). There is no separate preload step. # Introduction Source: https://docs.facebetter.net/effect-creator/introduction Introduction to Facebetter Effect Creator Figma Plugin The Facebetter Effect Creator Figma plugin is a convenient tool specifically designed for creating stickers and makeup effects for the Beauty Effect SDK. It aims to simplify the creation process for stickers and makeup effects. With this plugin, you can directly complete sticker design, face landmark binding, attribute configuration, and 3D preview export within Figma. ## Login and Language Settings The plugin must be logged in before it can be used. You can log in using a Facebetter account or email, or use social accounts such as Google or GitHub. 1. **Launch Plugin**: Run the Facebetter Effect Creator plugin in Figma. 2. **Login**: Supports Google, GitHub, or email login. 3. **Language Switching**: Click the dropdown menu icon at the top of the interface to switch between **Simplified Chinese** and **English**. ![Facebetter Effect Creator Plugin Login](https://mintcdn.com/facebetter/DM5KtVsHX1q4Zlkm/images/fb-figma-login.jpg?fit=max\&auto=format\&n=DM5KtVsHX1q4Zlkm\&q=85\&s=8a3a2c724f733c4bb8a0233bde1c60e8) ## Install Plugin Click this link: [Plugin](https://www.figma.com/community/plugin/1591037386605818409/facebetter-effect-creator), or search for "Facebetter Effect Creator" in Figma, click "Open In" to open the plugin in an existing document or a newly created design document. A new blank document is recommended. ![Facebetter Effect Creator Plugin Installation](https://mintcdn.com/facebetter/DM5KtVsHX1q4Zlkm/images/fb-figma-install.jpg?fit=max\&auto=format\&n=DM5KtVsHX1q4Zlkm\&q=85\&s=1f52833b8ac3affbd5ea805917700f25) ### Attribute Editing ![Facebetter Effect Creator Plugin Editor](https://mintcdn.com/facebetter/DM5KtVsHX1q4Zlkm/images/fb-effect-creator-editor.png?fit=max\&auto=format\&n=DM5KtVsHX1q4Zlkm\&q=85\&s=eebece51b81a0b0f891275a4f35b181f) ### 3D Preview ![Facebetter Effect Creator 3D Preview](https://mintcdn.com/facebetter/DM5KtVsHX1q4Zlkm/images/fb-effect-creator-3d-preview.png?fit=max\&auto=format\&n=DM5KtVsHX1q4Zlkm\&q=85\&s=06b2e515ba1502307703eeea38763433) # Screen Sticker Source: https://docs.facebetter.net/effect-creator/screen-sticker Create screen stickers with Facebetter Effect Creator Coming soon. # Final Cut Pro FAQ Source: https://docs.facebetter.net/fcp/faq macOS blocks the app, or Facebetter Beauty does not show up in Final Cut Pro. ## macOS says the app is damaged or cannot be opened The installer is not signed or notarized yet, so Gatekeeper may block it. Try in this order: 1. Right-click **Facebetter FCP Beauty.app** → **Open** → **Open**. 2. **System Settings** → **Privacy & Security** → **Open Anyway**. 3. In Terminal: ```bash theme={null} xattr -cr "/Applications/Facebetter FCP Beauty.app" ``` Then open the app and click **Set up for Final Cut**. Install steps: [Install](/fcp/install). ## I cannot find Facebetter Beauty in Final Cut Pro 1. Open **Facebetter FCP Beauty.app** and finish **Set up for Final Cut**. 2. Fully quit Final Cut Pro (not only close the project window), then reopen it. 3. In the Effects browser, search for **Facebetter Beauty**. Still stuck? Email [hello@facebetter.net](mailto:hello@facebetter.net). ## Does this work on Intel Macs? No. The Final Cut / Motion plugin currently supports **Apple silicon** only. # Install Final Cut Pro plugin Source: https://docs.facebetter.net/fcp/install Install Facebetter Beauty for Final Cut Pro and Motion on macOS Apple silicon. Facebetter Beauty is a realtime beauty effect for **Final Cut Pro** and **Motion** on macOS Apple silicon. Skin, reshape, makeup, color filters, stickers, body, and virtual background run on this Mac. Download: [facebetter.net/edit](https://facebetter.net/edit). Before you start: * macOS on **Apple silicon** (M1 / M2 / M3 / M4). * Final Cut Pro (or Motion) installed. ## Install 1. Download the macOS zip and unzip it. 2. Move **Facebetter FCP Beauty.app** into **Applications** (or `~/Applications`). 3. Open the app and click **Set up for Final Cut** (registers the plugin and installs the Motion template). 4. Fully quit Final Cut Pro, reopen it, then find **Facebetter Beauty** under Effects and drag it onto a clip. No admin password is required for the usual install path. > [!TIP] > > The same setup also installs the Motion template so you can use the effect in Motion. ## If macOS says the app is damaged Builds are not signed or notarized yet. Gatekeeper may show “damaged”, “cannot be opened”, or “cannot be verified”. 1. Prefer: right-click the app → **Open** → **Open**. 2. Or: **System Settings** → **Privacy & Security** → **Open Anyway**. 3. Or in Terminal (adjust the path if needed): ```bash theme={null} xattr -cr "/Applications/Facebetter FCP Beauty.app" ``` Then open the app again and finish **Set up for Final Cut**. More troubleshooting: [FAQ](/fcp/faq). # SDK Documentation Source: https://docs.facebetter.net/index Realtime AI beauty SDK for Android, iOS, macOS, Windows, Linux, and Web. **Beauty Effect SDK 2.0** is a real-time beauty effects engine for images and live video. Pick your platform below, or start with subscription and licensing. > [!TIP] > > Integrating with Cursor, Claude, or ChatGPT? See [Use with AI](/intro/use-with-ai) for MCP and `llms.txt`. > **[Subscribe](/intro/enable-service)** > > Create a project and get AppID / AppKey. > **[Android](/android/quick-start)** > > Run the sample, then add beauty to your app. > **[iOS](/ios/quick-start)** > > CocoaPods or Framework integration. > **[Web](/web/quick-start)** > > JavaScript SDK. > **[Linux](/linux/quick-start)** > > C++ SDK for Linux. > **[Effect Creator](/effect-creator/introduction)** > > Build face and screen stickers in Figma. > **[OBS Plugin](/obs/install)** > > Install the beauty filter and adjust it in OBS. > **[Edit Plugins](/fcp/install)** > > Final Cut Pro / Motion beauty plugin; After Effects coming soon. Use the [dashboard](https://facebetter.net/dashboard) for credentials, and the [download page](https://facebetter.net/download) for binaries. # Subscription Source: https://docs.facebetter.net/intro/enable-service Enable Beauty Effect SDK subscription service and obtain AppID & AppKey to start using beauty features ## Register / Login Open the [Facebetter website](https://facebetter.net), then [Sign in](https://facebetter.net/sign-in) or [Create an account](https://facebetter.net/sign-up). Email/password and social sign-in (Google, GitHub) are supported. After sign-in you land in the [Console](https://facebetter.net/dashboard). Create a project; each project has its own plan, credentials, and platform bindings. New projects start on the **Free** plan (most effects available, output always watermarked). Plan details: [Plans & Features](./pricing). ## Bind Application Information Open **Credentials** for the project. The SDK checks that the running app matches the identifiers bound in the Console—fill in each platform you ship and save: * **iOS / macOS**: Bundle ID (e.g. `com.example.app`) * **Android**: Application package name (e.g. `com.example.app`) * **Windows**: executable file name, including `.exe` (e.g. `CustomerApp.exe`) * **Linux** (officially Ubuntu 22.04+): executable file name (e.g. `customerapp`) * **Web**: page origin (e.g. `https://app.example.com`). Electron does not check this origin. Auth fails if bindings are missing or do not match. For CLI tools without a Bundle ID, bind the process name as shown in the Console. ## Subscribe to a Plan Upgrade from the project **Overview** or **Billing** page: 1. Open **Adjust plan** (or an upgrade action on Overview). 2. Choose **Monthly** or **Yearly** (yearly is about 20% off). 3. Pick **Basic / Pro / Pro+** (or another paid tier). See [Plans & Features](./pricing). 4. Complete checkout. Card and other common methods are supported. The Chinese console also offers Alipay as one-time prepaid (monthly or yearly, no auto-renew). On **Billing** you can review renewals or expiry, invoices, and cancel auto-renew for card subscriptions. Alipay prepaid must be purchased again before it expires. ## Get AppID and AppKey On the project **Credentials** page, copy **App ID** and **App Key**. Native apps can authenticate with `appId` + `appKey`, or with a `licenseToken` (license token string, `{token}` JSON, or offline `.lic` file contents). Web must not embed `appKey` in frontend JavaScript. Details: [Auth & License](./license). To rotate the App Key, use **Reset key** on the same page. The previous key stops working immediately—update your apps first. # Auth & License Source: https://docs.facebetter.net/intro/license Beauty Effect SDK 2.0 online auth and offline license SDK **2.0** authenticates with a **license token**. Native platforms can also use `appId` + `appKey` for online auth. Web must never embed `appKey` in frontend JavaScript. > [!TIP] > > Complete [Subscription](./enable-service) first: bind your app identifiers in the Dashboard (Bundle ID / package name / domain) and enable a plan. ## Native (Android / iOS / macOS / Windows) Pass one of the following when creating the engine: | Mode | Config fields | When to use | | - | - | - | | Online | `appId` + `appKey` | Device can reach `/facebetter/v2/auth` | | Token | `licenseToken` | License token string, `{token}` JSON, or offline `.lic` | **Priority**: if `licenseToken` is non-empty, the SDK validates that token locally and does **not** call the network with `appId` / `appKey`. > [!TIP] > > Recommended (same idea as Web): keep `appId` / `appKey` on **your server**, mint a short-lived `licenseToken`, and deliver it to the app. Set `platform` in the signed request to match the client (`ios` / `android` / `macos` / `windows`). See [Web → Server proxy](#server-proxy) below. Direct `appId` + `appKey` and offline `.lic` remain supported. **iOS / macOS** ```objc theme={null} FBEngineConfig *config = [[FBEngineConfig alloc] init]; config.licenseToken = @"/* license token, {token} JSON, or .lic contents */"; self.beautyEffectEngine = [FBBeautyEffectEngine createEngineWithConfig:config]; ``` **Android** ```java theme={null} BeautyEffectEngine.EngineConfig config = new BeautyEffectEngine.EngineConfig(); config.licenseToken = "/* license token, {token} JSON, or .lic contents */"; mBeautyEngine = new BeautyEffectEngine(this, config); ``` **C++ (Windows)** ```cpp theme={null} facebetter::EngineConfig config; config.license_token = "/* license token, {token} JSON, or .lic contents */"; config.resource_path = "/path/to/resource.fbd"; auto engine = facebetter::BeautyEffectEngine::Create(config); ``` Online alternative on native platforms: ```java theme={null} config.appId = "your appId"; config.appKey = "your appKey"; ``` Prefer shipping the offline `.lic` as an app asset and loading it at runtime instead of hard-coding it in source. How to obtain one: [Offline license](#offline-license) below. ## Web The browser SDK has **no** `appId` / `appKey` fields. The engine only accepts `licenseToken` and verifies it locally. Fetch the token from **your server** **before** `init()`. ### Recommended flow 1. Create an app in the Dashboard, bind your Web **domain**, and copy `appId` / `appKey` (see [Subscription](./enable-service)) 2. Keep the keys on **your backend**; expose an endpoint (for example `POST /api/facebetter/auth`) 3. Your backend signs a request to `https://facebetter.pixpark.net/facebetter/v2/auth` and returns the **raw response body** to the page 4. Pass that string to `EngineConfig.licenseToken`, then call `init()` The official demo (`demo/web/react`) uses the same pattern: frontend in `src/fetchLicenseToken.js`, server proxy in `api/facebetter/auth.js`. > [!WARNING] > > Do not put `appKey` in a frontend bundle. An offline `.lic` on the web must match the page origin, for example `https://app.example.com`. Electron does not check origin. Online tokens expire in minutes — fetch a new one before creating the engine again. ### Frontend ```javascript theme={null} import { BeautyEffectEngine, EngineConfig } from 'facebetter'; // Body may be a bare token, or the upstream JSON text (with a token field) const licenseToken = await fetch('/api/facebetter/auth', { method: 'POST', }).then((r) => { if (!r.ok) throw new Error(`auth failed: ${r.status}`); return r.text(); }); const engine = new BeautyEffectEngine(new EngineConfig({ licenseToken })); await engine.init(); ``` ### Server proxy (Node example) Store `FB_APP_ID` / `FB_APP_KEY` in environment variables. Drop this into Express / Fastify / a serverless function: ```javascript theme={null} import { createHmac, randomBytes } from 'node:crypto'; const AUTH_URL = 'https://facebetter.pixpark.net/facebetter/v2/auth'; app.post('/api/facebetter/auth', async (req, res) => { const appId = process.env.FB_APP_ID; const appKey = process.env.FB_APP_KEY; if (!appId || !appKey) { res.status(500).json({ error: 'FB_APP_ID / FB_APP_KEY not configured' }); return; } const nonce = randomBytes(16).toString('hex'); const timestamp = Math.floor(Date.now() / 1000); const platform = 'web'; // Sign string: v2|{app_id}|{timestamp}|{nonce}|{platform} const payload = `v2|${appId}|${timestamp}|${nonce}|${platform}`; const hmac = createHmac('sha256', appKey).update(payload).digest('hex'); const upstream = await fetch(AUTH_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ app_id: appId, hmac_signature: hmac, timestamp, nonce, platform, user_agent: req.headers['user-agent'] || '', }), }); // Forward as-is for EngineConfig.licenseToken res.status(upstream.status).send(await upstream.text()); }); ``` In other languages, implement the same steps: build the sign string → HMAC-SHA256 (hex) → POST upstream → hand the body to the frontend. Runnable reference: [GitHub Demo `api/facebetter/auth.js`](https://github.com/pixpark/facebetter-sdk/blob/main/demo/web/react/api/facebetter/auth.js). ### Upstream request fields | Field | Description | | - | - | | `app_id` | Dashboard AppID | | `hmac_signature` | HMAC-SHA256 of `v2\|{app_id}\|{timestamp}\|{nonce}\|web`, hex-encoded | | `timestamp` | Unix seconds | | `nonce` | Random string (recommend ≥16 bytes hex) | | `platform` | Always `web` | | `user_agent` | Optional; pass the browser UA when available | On success the upstream returns JSON (including a `token` field). You may forward the response text as-is, or extract only the `token` string — the SDK accepts either. ## Offline license Download an offline `.lic` from the Dashboard credentials page and pass the **entire contents** as `licenseToken` / `license_token`. Paid plans lock each saved identifier. An empty platform can be filled once. To change a locked identifier, contact [support](https://facebetter.net/contact). Free plans can edit identifiers and download anytime. The file expires 15 days after the subscription ends. Downloading again does not move that date. After renewal, download a new file. ### Notes * Online tokens and offline licenses both check the Dashboard app identifier: iOS and macOS use the Bundle ID, Android uses the package name, Windows and Linux use the executable file name, and a browser uses the page origin. Electron does not check origin. A mismatch fails validation. * Not expired: features follow your subscription plan. * Expired: the engine can still initialize, but capabilities fall back to the **Free** plan (watermarked trial). After renewal, download a new file from the Dashboard. * Web offline licenses are bound to the page origin. Pass the entire `.lic` as `licenseToken`. ## Engine events Listen for license and init results via `onEngineEvent`: | Code | Name | Meaning | | - | - | - | | 0 | `LICENSE_VALIDATION_SUCCESS` | Token / online auth succeeded | | 1 | `LICENSE_VALIDATION_FAILED` | Auth failed (see message) | | 100 | `INITIALIZATION_COMPLETE` | Engine ready | | 101 | `INITIALIZATION_FAILED` | Engine init failed | # Parameter enums Source: https://docs.facebetter.net/intro/makeup Face reshape, body reshape, makeup, whitening, and smoothing enums for Beauty Effect SDK 2.0 > [!NOTE] > > This page matches SDK **2.0**. Numeric values are identical on C++, Objective-C, Java, JavaScript, and Dart. Makeup is three knobs: 1. **Intensity** — `SetLipstick` / `SetBlush` / `SetContour` / `SetEyeShadow` / `SetEyeLiner` / `SetEyebrow` / `SetEyelash` / `SetPupil`, range `[0.0, 1.0]`. `0` turns the effect off. 2. **Shape** — swap the mask texture (`SetBlushStyle`, `SetContourStyle`, `SetEyeShadowStyle`, …). 3. **Color** — tint the current shape (`SetLipstickColor`, `SetBlushColor`, `SetEyeShadowColor`, …). **Pupil** and **Contour** do not tint; changing them swaps the texture. | C++ / JS | Java | Objective-C | Dart | | - | - | - | - | | `LipstickColor::Rouge` | `LipstickColor.ROUGE` | `FBLipstickColor_Rouge` | `FBLipstickColor.rouge` | ## Whitening (`WhiteningStyle`) Used with `SetWhiteningStyle`. Intensity is still `SetWhitening`. Default: `ColdWhite`. | Value | Name | Meaning | | - | - | - | | 0 | `ColdWhite` | Cool white | | 1 | `PinkWhite` | Pink white | | 2 | `WarmWhite` | Warm white | | 3 | `Wheat` | Wheat | | 4 | `Tan` | Tan | ## Smoothing (`SmoothingStyle`) Used with `SetSmoothingStyle`. Intensity is still `SetSmoothing`. Default: `Natural`. | Value | Name | Meaning | | - | - | - | | 0 | `Natural` | Keep pores | | 1 | `Texture` | Cleaner, still textured | | 2 | `Smooth` | Creamy skin | ## Face reshape (`Reshape`) Used with `SetReshape(param, intensity)`. Range is **`[-1.0, 1.0]`**. `0` is off. Positive and negative are opposite directions (for example FaceThin: slim / fuller cheeks). > [!NOTE] > > Face reshape is available from **Pro**. Free can try it with a watermark. See [Plans & Features](./pricing). | Value | Name | Positive / negative | | - | - | - | | 0 | `FaceThin` | Slim face / fuller cheeks | | 1 | `FaceVShape` | V-shape / squarer jaw | | 2 | `FaceNarrow` | Narrow / wider face | | 3 | `FaceShort` | Shorter / longer face | | 4 | `Cheekbone` | Slim / expand cheekbones | | 5 | `Jawbone` | Slim / expand jaw | | 6 | `Chin` | Longer / shorter chin | | 7 | `NoseSlim` | Slimmer / wider nose | | 8 | `EyeSize` | Larger / smaller eyes | | 9 | `EyeDistance` | Wider / closer eye distance | | 10 | `FaceSmall` | Smaller / larger face | | 11 | `Forehead` | Fuller / lower forehead | | 12 | `NoseLong` | Longer / shorter nose | | 13 | `Philtrum` | Shorter / longer philtrum | | 14 | `MouthSize` | Larger / smaller mouth | | 15 | `MouthPosition` | Lower / higher mouth | | 16 | `MouthSmile` | Smile / downturned | | 17 | `LipThickness` | Thicker / thinner lips | | 18 | `EyeRound` | Rounder / narrower eyes | | 19 | `EyePosition` | Lower / higher eyes | | 20 | `EyeAngle` | Outer corner up / down | | 21 | `EyeCornerOpen` | Open / close eye corners | | 22 | `LowerEyelid` | Lower / lift eyelid | | 23 | `BrowPosition` | Higher / lower brows | | 24 | `BrowDistance` | Wider / closer brows | | 25 | `BrowThickness` | Thicker / thinner brows | Java names are `SNAKE_CASE` (`FACE_THIN`, `FACE_V_SHAPE`, …). Objective-C uses `FBReshape_FaceThin`. Dart uses `FBReshape.faceThin`. ## Body reshape (`BodyReshape`) Used with `SetBodyReshape(param, intensity)`. Range is **`[0.0, 1.0]`**. `0` is off. Unlike face reshape, these values are not bipolar. > [!NOTE] > > Body reshape requires **Pro+**. Free can try it with a watermark. See [Plans & Features](./pricing). Requires the optional pack `resource_body.fbd` except `LegStretch` and `TorsoLong`. Register it with `AddResourcePack` / `addResourcePack` **before** pose-based `SetBodyReshape` / `setBodyReshape`. See [Optional resource packs](./resource-packs). | Value | Name | Meaning | | - | - | - | | 0 | `BodySlim` | Slim the whole body | | 1 | `WaistSlim` | Slim the waist | | 2 | `LegSlim` | Slim the legs | | 3 | `ShoulderSlim` | Slim the shoulders | | 4 | `ArmSlim` | Slim the arms | | 5 | `LegLong` | Lengthen the legs along the skeleton | | 6 | `BustEnhance` | Enhance the bust | | 7 | `LegStretch` | Stretch below the waist (face only; no `resource_body.fbd`) | | 8 | `TorsoLong` | Lengthen the torso chin-to-waist (face only; no `resource_body.fbd`) | Java names are `SNAKE_CASE` (`BODY_SLIM`, `WAIST_SLIM`, …). Objective-C uses `FBBodyReshape_BodySlim`. Dart uses `FBBodyReshape.bodySlim`. ## Lipstick (`LipstickColor`) Single lip mask + tint. Default: `Rouge`. | Value | Name | Meaning | | - | - | - | | 0 | `Rouge` | Rose | | 1 | `RetroRed` | Retro red | | 2 | `Peach` | Peach | | 3 | `CoralOrange` | Coral orange | | 4 | `GentlePink` | Soft pink | | 5 | `VitalityOrange` | Bright orange | ## Blush Shape via `BlushStyle` (swap texture). Color via `BlushColor` (tint). Default shape `SunKissed`, default color `CoralPink`. | Value | `BlushStyle` | Meaning | | - | - | - | | 0 | `SunKissed` | Across cheekbones and nose | | 1 | `Igari` | Drunk-blush band on the nose | | 2 | `Soft` | Soft both cheeks | | 3 | `Apple` | Round apple cheeks | | 4 | `Classic` | Two classic spots | | 5 | `Doll` | Cheeks + nose tip | | 6 | `Rose` | Rose both cheeks | | Value | `BlushColor` | Meaning | | - | - | - | | 0 | `CoralPink` | Coral pink | | 1 | `DustyRose` | Dusty rose | | 2 | `VividRed` | True red | | 3 | `Berry` | Berry | | 4 | `SunsetOrange` | Sunset orange | ## Contour (`ContourStyle`) Mid-gray Overlay map: lighter than 128 highlights, darker contours. Swap texture, no tint. Default: `Natural`. | Value | Name | Meaning | | - | - | - | | 0 | `Natural` | Everyday light contour | | 1 | `Sculpt` | Stronger sculpt | | 2 | `Glow` | Highlight-first | | 3 | `Slim` | Slim cheekbones | | 4 | `Nose` | Nose definition | | 5 | `Glam` | Highlight spots | ## Eyeshadow Shape `EyeShadowStyle`, color `EyeShadowColor`. Default shape `Soft`, default color `Plum`. | Value | Style | Meaning | | - | - | - | | 0 | `Soft` | Soft wash | | 1 | `Crease` | Crease deepen | | 2 | `Smoky` | Smoky ring | | 3 | `Halo` | Halo around the eye | | 4 | `Glow` | Outer-corner lift | | 5 | `Drama` | Full coverage | | 6 | `Warm` | Warm wash | | Value | Color | Meaning | | - | - | - | | 0 | `Plum` | Plum / mauve | | 1 | `Brown` | Warm brown | | 2 | `Gold` | Soft gold | | 3 | `Pink` | Dusty pink | ## Eyeliner | Value | `EyeLinerStyle` | Meaning | | - | - | - | | 0 | `Classic` | Full liner + wing | | 1 | `Flick` | Long outer flick | | 2 | `CatEye` | Short cat-eye | | 3 | `Natural` | Thin natural line | | 4 | `Bold` | Bold coverage | | 5 | `Soft` | Soft faded wing | | Value | `EyeLinerColor` | Meaning | | - | - | - | | 0 | `Burgundy` | Burgundy brown | | 1 | `Plum` | Deep plum | | 2 | `Chocolate` | Chocolate | | 3 | `Coffee` | Near-black coffee | | 4 | `Mauve` | Dusty mauve | ## Eyebrow | Value | `EyebrowStyle` | Meaning | | - | - | - | | 0 | `Natural` | Natural arch + hair | | 1 | `Soft` | Soft powder brow | | 2 | `Feathered` | Feathered strokes | | 3 | `Mist` | Light mist | | 4 | `Arched` | Classic lift | | 5 | `Powder` | Dense powder | | 6 | `Wild` | Flyaways on the top edge | | 7 | `Full` | Full even brow | | 8 | `Straight` | Straight low arch | | Value | `EyebrowColor` | Meaning | | - | - | - | | 0 | `DarkBrown` | Dark brown | | 1 | `Black` | Black | | 2 | `SoftBrown` | Soft brown | ## Eyelash | Value | `EyelashStyle` | Meaning | | - | - | - | | 0 | `Classic` | Even clusters + lower lash | | 1 | `Manga` | Spiky manga | | 2 | `Winged` | Outer-corner length | | 3 | `Wispy` | Wispy flare | | 4 | `Clustered` | Distinct clusters | | 5 | `Doll` | Short doll lashes | | Value | `EyelashColor` | Meaning | | - | - | - | | 0 | `Black` | Near-black | | 1 | `Brown` | Soft brown | | 2 | `SoftBlack` | Soft black | ## Pupil (`PupilColor`) One iris disc per color. No tint. Default: `Hazel`. | Value | Name | Meaning | | - | - | - | | 0 | `Hazel` | Amber / honey brown | | 1 | `Ice` | Icy blue | | 2 | `Mocha` | Dark brown sparkle | | 3 | `Olive` | Forest green | | 4 | `Gloss` | Glossy dark brown | | 5 | `Moss` | Muted olive | | 6 | `Sand` | Sandy brown | | 7 | `Glow` | Lower-iris crescent highlight (not a full color lens) | | 8 | `Slate` | Blue-grey | ## Chroma key (`ChromaKeyColor`) Used with `SetChromaKey` as the virtual-background mask source. | Value | Name | | - | - | | 0 | `Green` | | 1 | `Blue` | | 2 | `Red` | # Overview Source: https://docs.facebetter.net/intro/overview Facebetter Beauty Effects SDK Engine Product Overview Facebetter is a real-time beauty effects engine designed for developers. It delivers high-quality AI-powered beauty processing for both images and live video streams. It is GPU-accelerated for low latency and high frame rates, and integrates into Android, iOS, macOS, Windows, Linux, and Web. ## Core Features ### Skin Beauty Skin controls are smoothing, whitening, and rosy tone, each in `[0.0, 1.0]` (`0` is off). Smoothing and whitening also have style presets. Full-frame color grade is separate: brightness, contrast, saturation, temperature, and tint are `[-1.0, 1.0]` (`0` is neutral); clarity is `[0.0, 1.0]`. ### Face Reshaping Comprehensive adjustments spanning facial contour and feature proportions: * **Face shape**: slim, V-shape, narrow, short, small face, forehead * **Contour**: cheekbone, jaw, chin * **Features**: nose slim/length, philtrum, mouth size/position/smile, lip thickness * **Eyes & brows**: eye size/distance/round/position/angle/corner, lower eyelid, brow position/distance/thickness Intensity range is `[-1.0, 1.0]`. See [Parameter enums](./makeup). > A single frame supports up to **5 faces** for reshape and makeup at once. ### Body reshape Body slimming and proportion controls: whole-body slim, waist, legs, shoulders, arms, longer legs, and bust enhance. Intensity is `[0.0, 1.0]` (`0` is off). Requires the optional `resource_body.fbd` pack — see [Optional resource packs](./resource-packs) and [Parameter enums](./makeup). Requires **Pro+** (Free: watermarked trial). See [Plans & Features](./pricing). ### Makeup Layered makeup: lipstick, blush, eyeshadow, eyeliner, eyebrow, eyelash, colored contacts, and contour. Intensity, shape, and color are set separately. Multiple items can be applied at once. See [Parameter enums](./makeup). ### Filters & Styles 20+ real-time style filters covering portrait, food, landscape, modern, and other themes. Intensity is adjustable. Custom filters are `.fbd` files loaded with `setFilter`. ### Virtual Background Powered by real-time portrait segmentation: * **Background blur**: keeps the foreground subject sharp while applying Gaussian blur to the background * **Background replacement**: swaps the background with a JPEG / PNG image ### Sticker Effects 2D and 3D sticker effects: * **Screen stickers**: overlaid at a fixed position on the frame * **Face-tracking stickers**: anchored to face keypoints and follow head movement * **3D stickers**: mesh props (glasses, hats, masks). Requires the optional `resource_3d.fbd` pack — see [Optional resource packs](./resource-packs). Requires **Pro+** (Free: watermarked trial). See [Plans & Features](./pricing) Sticker (and filter) resources are **`.fbd` files**. Apply one 2D sticker at a time with `setSticker` and one 3D sticker with `set3DSticker` (path or bytes). Remove with `clearSticker` / `clear3DSticker`. The new resource takes effect on the next processed frame. ### Advanced Features * **Chroma key**: key out green, blue, or red screen as the virtual-background mask Feature availability depends on the subscription plan. Free can try most effects with a watermark. See [Plans & Features](./pricing). *** ## Input / Output Formats ### Image Formats | Type | Supported Formats | | - | - | | Static images | `JPEG`, `PNG` | | Video frames | `YUV I420`, `NV12`, `NV21`, `RGB`, `RGBA`, `BGR`, `BGRA` | | GPU texture | OpenGL / OpenGL ES `Texture` | ### Resolution Limits | Scenario | Maximum | | - | - | | Real-time video stream | `720P @ 60fps` / `1080P @ 30fps` | | Static image processing | Up to `4K` | `ImageFrame` converts among these formats. *** ## Performance | Metric | Value | | - | - | | Render latency | \~`10ms` average at `1080P` (GPU parallel) | | CPU usage | \< `5%` during real-time rendering | | Memory footprint | Primarily GPU memory; system RAM usage is low | *** ## Supported Platforms | Platform | OS / Version | | - | - | | Mobile | `iOS 12.0+`, `Android 7.0+` (API 24) | | Web | Chrome, Firefox, Safari, Edge | *** ## Integration Languages & Interfaces | Interface | Use Case | | - | - | | Java / Kotlin | Android applications | | Objective-C / Swift | iOS and macOS applications | | JavaScript | Web (browser and Node.js) | *** ## Quick Start Select your target platform and follow the integration guide: * [Android Quick Start](../android/quick-start) * [iOS Quick Start](../ios/quick-start) * [macOS Quick Start](../macos/quick-start) * [Windows Quick Start](../windows/quick-start) * [Linux Quick Start](../linux/quick-start) * [Web Quick Start](../web/quick-start) # Plans & Features Source: https://docs.facebetter.net/intro/pricing Facebetter plan features and pricing details This page describes **feature support** and **pricing** for each Facebetter subscription plan. To purchase or renew, use the [Pricing](https://facebetter.net/pricing) page or the dashboard. ## Pricing One subscription covers all platforms (iOS, Android, macOS, Windows, Linux, Web). Monthly and yearly billing are available; yearly billing is about **20% off**. | Plan | Monthly (USD/month) | Yearly (USD/year) | Notes | | - | -: | -: | - | | Free | \$0 | \$0 | Try most effects with a **permanent watermark**. Unlimited time. | | Basic | \$99 | \$950 | No watermark. Skin beauty only. Standard support. | | Pro | \$229 | \$2,190 | Face reshape (26), makeup, LUT filters, priority support | | Pro+ | \$399 | \$3,830 | Body reshape, virtual background, stickers (incl. 3D), chroma key, subject outline | Exact amounts are shown on the [Pricing](https://facebetter.net/pricing) page or in the dashboard. ## Feature Support ✓ = included. W = available on Free **with watermark**. — = not included. ### Runtime and watermark | Feature | Free | Basic | Pro | Pro+ | | - | - | - | - | - | | Time limit | Unlimited | Unlimited | Unlimited | Unlimited | | Watermark | Always on | No | No | No | ### Beauty and Reshape | Feature | Free | Basic | Pro | Pro+ | | - | - | - | - | - | | Basic beauty (smoothing, whitening, rosy, color grade, skin-only) | W | ✓ | ✓ | ✓ | | Reshape (26 face / feature controls) | W | — | ✓ | ✓ | | Body reshape (7 controls) | W | — | — | ✓ | | Makeup (lipstick, blush, eye makeup, contacts, contour, etc.) | W | — | ✓ | ✓ | ### Filters and Effects | Feature | Free | Basic | Pro | Pro+ | | - | - | - | - | - | | Style (LUT) filters | W | — | ✓ | ✓ | | Stickers (2D / 3D) | W | — | — | ✓ | | Virtual background (blur / image replace) | W | — | — | ✓ | | Chroma key (green / blue / red) | W | — | — | ✓ | | Subject outline | W | — | — | ✓ | ### Support | Feature | Free | Basic | Pro | Pro+ | | - | - | - | - | - | | Community support | ✓ | ✓ | ✓ | ✓ | | Email and instant messaging | — | ✓ | ✓ | ✓ | | Priority technical support | — | — | ✓ | ✓ | ## Use Cases | Plan | Use case | | - | - | | Free | Integration tests and effect preview. Output always has a watermark. | | Basic | Shipping skin beauty only, with no watermark and unlimited runtime | | Pro | Livestream / short video that needs reshape, makeup, and LUT filters | | Pro+ | Production apps that need body reshape, virtual background, stickers (incl. 3D), chroma key, or subject outline | To subscribe or change your plan, log in to the [Dashboard](https://facebetter.net/dashboard) and use the subscription section, or go to the [Pricing](https://facebetter.net/pricing) page. # Changelog Source: https://docs.facebetter.net/intro/release-note Beauty Effect SDK Release Note This site documents **SDK 2.x**. Latest: **v2.1.0**. ## v2.1.0 2026-09-21 1. Body reshape: slim, waist, legs, shoulders, arms, longer legs, bust, and more. See [Parameter enums](./makeup) 2. 3D stickers (glasses, hats, and other mesh props) 3. Optional resource packs for body reshape and 3D stickers. See [Optional resource packs](./resource-packs) ## v2.0.1 2026-09-15 1. Faster processing on Web and Android ## v2.0.0 2026-09-09 1. New auth: native `licenseToken` or `appId` + `appKey`; Web uses `licenseToken` only (from your server) 2. Skin beauty: smoothing, whitening, sharpening, rosiness, skin-only, plus style presets 3. Face reshape (26 controls) 4. Makeup: intensity, shape, and color. See [Parameter enums](./makeup) 5. LUT filters and 2D stickers (`.fbd`) 6. Virtual background: blur, image replace, chroma key 7. Processing stats (`getStats()`) ## v1.5.1 2026-08-03 1. Fixed a crash with skin-only beauty on images of different sizes 2. Faster processing ## v1.5.0 2026-07-30 1. Offline license from the Dashboard (no network required) 2. Auth guide: [Auth & License](./license) ## v1.4.7 2026-07-29 1. Lipstick and blush style selection 2. Plan renewals and upgrades take effect on the next auth 3. Fixed Web skin-only beauty crash 4. Fixed occasional crashes and black frames ## v1.4.6 2026-06-22 1. More stable tracking when the face moves quickly ## v1.4.5 2026-06-09 3. Fixed sticker black screen in live video ## v1.4.4 2026-06-02 1. Fixed filters and stickers in live video 2. Fixed iOS texture color output ## v1.4.3 2026-05-04 1. Lipstick and blush makeup 2. More built-in stickers 3. Fixed removing stickers in some cases ## v1.4.2 2026-04-23 1. More reliable Web license checks ## v1.4.1 2026-04-12 1. Windows SDK includes 32-bit and 64-bit ## v1.4.0 2026-03-24 1. Apply beauty on skin areas only ## v1.3.2 2026-03-10 1. Free plan shows a watermark after 10 minutes 2. Windows and Linux SDK ## v1.3.1 2026-03-03 1. Web npm 1.3.0 2. Mirror docs ## v1.3.0 2026-02-20 1. Faster processing 2. Android Maven 3. iOS / macOS Demo via CocoaPods 4. Style filters and stickers ## v1.2.5 2026-01-15 1. More reliable authentication ## v1.2.2 2026-01-08 1. Updated subscription plans ## v1.2.1 2025-12-20 1. Watermark 2. Auth runs in the background 3. Updated pricing tiers ## v1.2.0 2025-12-01 1. All platforms: Android, iOS, macOS, Windows, Linux, Web 2. Virtual background 3. Style filters 4. Stickers 5. Online auth upgrade 6. More stable face tracking ## v1.1.3 2025-11-10 1. Updated subscription plans ## v1.1.2 2025-10-28 1. More stable face tracking 2. Fixed face jitter ## v1.1.1 2025-10-15 1. LUT filters 2. Face keypoint callback 3. Green-screen matting 4. Bind app ID 5. Online auth 6. Multiple projects ## v1.1.0 2025-09-20 1. Live video texture processing 2. Easier APIs ## v1.0.6 2025-09-05 1. Better Android, iOS, and macOS demos 2. Fixed Android layout 3. Android camera permission check ## v1.0.5 2025-08-18 1. Better beauty controls ## v1.0.4 2025-08-01 1. More accurate face detection 2. Smaller resource files ## v1.0.3 2025-07-15 1. Makeup works on multiple faces ## v1.0.2 2025-07-01 1. Virtual background 2. Web docs (English and Chinese) 3. npm install # Optional resource packs Source: https://docs.facebetter.net/intro/resource-packs Download extra capability packs such as resource_3d.fbd and resource_body.fbd, then register them with AddResourcePack The SDK ships a core runtime pack `resource.fbd` (\~7 MB) for 2D beauty, makeup, filters, and 2D stickers. Some capabilities need an **optional** pack. These files are **not** inside the iOS / Android / Web SDK. Download them at integrate time and register each one with `AddResourcePack` / `addResourcePack` **before** the matching setter. | Pack | Size | Required before | | - | - | - | | `resource_3d.fbd` | \~9 MB | `Set3DSticker` / `set3DSticker` | | `resource_body.fbd` | \~8.5 MB | Pose-based `SetBodyReshape` (not `LegStretch` / `TorsoLong`) | > [!NOTE] > > 3D stickers and body reshape require **Pro+**. Free can try them with a watermark. See [Plans & Features](./pricing). Download them from the [GitHub Release](https://github.com/pixpark/facebetter-sdk/releases) (also mirrored on the [download page](https://facebetter.net/download)). ## How lookup works The engine searches the core pack plus every extra pack you add. Files are keyed by their **inner relative path**. Keep inner paths unique across packs — give each capability its own prefix (`tddfa/…`, `body/…`). If two packs contain the same path, the **last** `AddResourcePack` wins. Register each `.fbd` with a separate call. Do **not** concatenate pack files. ## Desktop (Windows / macOS / C++) Place `resource_3d.fbd` and/or `resource_body.fbd` next to `resource.fbd`. The engine loads those siblings automatically. You can still call `AddResourcePack` explicitly. ```cpp theme={null} engine->AddResourcePack("resource/resource_3d.fbd"); engine->Set3DSticker("assets/stickers/3d/oculos.fbd"); engine->Clear3DSticker(); engine->AddResourcePack("resource/resource_body.fbd"); engine->SetBodyReshape(BodyReshape::WaistSlim, 0.4f); ``` ## iOS / macOS / Android / Web The mobile and Web SDKs do **not** embed these optional packs. Copy or fetch each file in **your** app, then call `addResourcePack` (path or bytes). ```javascript theme={null} const pack3d = new Uint8Array( await (await fetch('/resource_3d.fbd')).arrayBuffer() ); engine.addResourcePack(pack3d); engine.set3DSticker('/stickers/3d/oculos.fbd'); const packBody = new Uint8Array( await (await fetch('/resource_body.fbd')).arrayBuffer() ); engine.addResourcePack(packBody); engine.setBodyReshape(BodyReshape.WaistSlim, 0.4); ``` 2D stickers still use `setSticker` only. `addResourcePack` is for capability models, not sticker assets. > [!TIP] > > Call `addResourcePack` once per extra pack after the engine is created (Web: after `init()`). Later 3D stickers or body-reshape calls reuse the same pack. # Use with AI Source: https://docs.facebetter.net/intro/use-with-ai Connect Facebetter docs to Cursor, Claude, ChatGPT, and other AI tools via MCP, llms.txt, and Markdown pages These docs are published for both humans and AI tools. You can connect an IDE agent to the whole site, or paste a single page as Markdown. ## MCP (recommended) Point Cursor, Claude, VS Code, or any MCP client at: ```text theme={null} https://docs.facebetter.net/mcp ``` After connecting, ask the agent to use the Facebetter docs MCP when integrating the SDK. It can search the site and read pages as Markdown. ### One-click from any page On any docs page, open the menu in the top-right corner: * **Connect to Cursor** / **Connect to VS Code** — install the MCP server * **Copy MCP server URL** — copy `https://docs.facebetter.net/mcp` * **Copy page** / **View as Markdown** — use the current page as chat context ## llms.txt and per-page Markdown | Resource | URL | Use when | | - | - | - | | Docs index | [https://docs.facebetter.net/llms.txt](https://docs.facebetter.net/llms.txt) | Tool can fetch a catalog of pages | | Full text | [https://docs.facebetter.net/llms-full.txt](https://docs.facebetter.net/llms-full.txt) | You want one file with most content | | Single page | Add `.md` to any URL | ChatGPT or tools without MCP | Example single page: ```text theme={null} https://docs.facebetter.net/android/quick-start.md ``` Chinese pages live under `/zh/`, for example: ```text theme={null} https://docs.facebetter.net/zh/android/quick-start.md ``` ## Prompt examples **With MCP connected** ```text theme={null} Use the Facebetter docs MCP. Help me integrate Beauty Effect SDK 2.0 into my Android app. Follow Quick Start, then Implement Beauty. Use only 2.0 APIs (setSmoothing, licenseToken, FrameType). Prefer current docs over prior knowledge. ``` **Without MCP** ```text theme={null} Read https://docs.facebetter.net/llms.txt first, then open the Android Quick Start and Implement Beauty pages (use the .md links). Help me integrate Facebetter into my Android project. Prefer those pages over prior knowledge. ``` Replace Android with iOS, Web, or another platform as needed. # API Reference Source: https://docs.facebetter.net/ios/api-reference iOS Objective-C API for Beauty Effect SDK 2.0 > [!NOTE] > > This page matches SDK **2.0.0**. Preset meanings: [Parameter enums](/intro/makeup). Auth: [Auth & License](/intro/license). iOS and macOS share this Objective-C API. iOS-only: `+[FBImageFrame createWithUIImage:]`. Minimum OS: **iOS 12.0**, architecture **arm64**. ## Logging ### `FBLogLevel` ```objc theme={null} typedef NS_ENUM(NSInteger, FBLogLevel) { FBLogLevel_Trace = 0, FBLogLevel_Debug, FBLogLevel_Info, FBLogLevel_Warn, FBLogLevel_Error, FBLogLevel_Critical, }; ``` ### `FBLogConfig` | Property | Type | Description | | - | - | - | | `consoleEnabled` | `BOOL` | Console output | | `fileEnabled` | `BOOL` | File output | | `level` | `FBLogLevel` | Minimum level | | `fileName` | `NSString *` | Log path (used when `fileEnabled` is `YES`) | ```objc theme={null} FB_OBJC_API @interface FBLogConfig : NSObject @property(nonatomic, assign) BOOL consoleEnabled; @property(nonatomic, assign) BOOL fileEnabled; @property(nonatomic, assign) FBLogLevel level; @property(nonatomic, copy, nullable) NSString *fileName; - (instancetype)init; @end ``` Call `+[FBBeautyEffectEngine setLogConfig:]` **before** `createEngineWithConfig:`. Returns `FBErrorCode` (`0` success, `-1` if `config` is nil). ## Engine configuration ### `FBEngineConfig` | Property | Type | Description | | - | - | - | | `appId` | `NSString *` | Dashboard App ID (online auth) | | `appKey` | `NSString *` | Dashboard App Key (online auth) | | `licenseToken` | `NSString *` | License token string, `{token}` JSON, or native `.lic` contents | **Auth priority:** if `licenseToken` is non-empty, validate that token locally and skip `/facebetter/v2/auth`. Otherwise use `appId` + `appKey` for online auth. Bind the app **Bundle ID** in the Dashboard. ```objc theme={null} FB_OBJC_API @interface FBEngineConfig : NSObject @property(nonatomic, copy) NSString *appId; @property(nonatomic, copy) NSString *appKey; @property(nonatomic, copy, nullable) NSString *licenseToken; - (instancetype)init; @end ``` ### `FBFrameType` Set on `FBImageFrame.type` before `processImage:`. Not a method argument. ```objc theme={null} typedef NS_ENUM(NSInteger, FBFrameType) { FBFrameTypeImage = 0, // stills FBFrameTypeVideo = 1 // live / camera }; ``` ## `FBBeautyEffectEngine` ```objc theme={null} FB_OBJC_API @interface FBBeautyEffectEngine : NSObject + (int)setLogConfig:(FBLogConfig *)config; + (instancetype)createEngineWithConfig:(FBEngineConfig *)config; - (int)setSmoothing:(float)intensity; - (int)setSmoothingStyle:(FBSmoothingStyle)style; - (int)setWhitening:(float)intensity; - (int)setWhiteningStyle:(FBWhiteningStyle)style; - (int)setRosiness:(float)intensity; - (int)setBrightness:(float)intensity; - (int)setContrast:(float)intensity; - (int)setSaturation:(float)intensity; - (int)setColorTemperature:(float)intensity; - (int)setColorTint:(float)intensity; - (int)setClarity:(float)intensity; - (int)setReshape:(FBReshape)param intensity:(float)value; - (int)setBodyReshape:(FBBodyReshape)param intensity:(float)value; - (int)setBeautySkinOnly:(BOOL)enabled; - (int)setLipstick:(float)intensity; - (int)setLipstickColor:(FBLipstickColor)color; - (int)setBlush:(float)intensity; - (int)setBlushStyle:(FBBlushStyle)style; - (int)setBlushColor:(FBBlushColor)color; - (int)setContour:(float)intensity; - (int)setContourStyle:(FBContourStyle)style; - (int)setEyeShadow:(float)intensity; - (int)setEyeShadowStyle:(FBEyeShadowStyle)style; - (int)setEyeShadowColor:(FBEyeShadowColor)color; - (int)setEyeLiner:(float)intensity; - (int)setEyeLinerStyle:(FBEyeLinerStyle)style; - (int)setEyeLinerColor:(FBEyeLinerColor)color; - (int)setEyebrow:(float)intensity; - (int)setEyebrowStyle:(FBEyebrowStyle)style; - (int)setEyebrowColor:(FBEyebrowColor)color; - (int)setEyelash:(float)intensity; - (int)setEyelashStyle:(FBEyelashStyle)style; - (int)setEyelashColor:(FBEyelashColor)color; - (int)setPupil:(float)intensity; - (int)setPupilColor:(FBPupilColor)color; - (int)setTeethWhiten:(float)intensity; - (int)setChromaKey:(FBChromaKeyColor)color; - (int)clearChromaKey; - (int)setChromaKeySimilarity:(float)value; - (int)setChromaKeySmoothness:(float)value; - (int)setChromaKeyDesaturation:(float)value; - (int)setVirtualBackgroundBlur:(float)level; - (int)setVirtualBackground:(NSString *)imagePath; - (int)setVirtualBackgroundWithData:(NSData *)imageData; - (int)clearVirtualBackground; - (int)setFilter:(NSString *)fbdFilePath; - (int)setFilterWithData:(NSData *)fbdData; - (int)clearFilter; - (int)setFilterIntensity:(float)intensity; - (int)setSticker:(NSString *)fbdFilePath; - (int)setStickerWithData:(NSData *)fbdData; - (int)clearSticker; - (int)addResourcePack:(NSString *)fbdFilePath; - (int)addResourcePackWithData:(NSData *)fbdData; - (int)set3DSticker:(NSString *)resource; - (int)set3DStickerWithData:(NSData *)fbdData; - (int)clear3DSticker; - (FBEngineStats *)getStats; - (int)setCallbacks:(FBEngineCallbacks *)callbacks; - (FBImageFrame * _Nullable)processImage:(FBImageFrame *)imageFrame; @end ``` `createEngineWithConfig:` returns `nil` on failure. Integer methods return `FBErrorCode` (`0` = success). ### Skin | Method | Range / notes | | - | - | | `setSmoothing:` | `[0, 1]` intensity | | `setSmoothingStyle:` | Style; intensity still from `setSmoothing:` | | `setWhitening:` | `[0, 1]` | | `setWhiteningStyle:` | Swaps the whitening LUT | | `setRosiness:` | `[0, 1]` | | `setBrightness:` | `[-1, 1]`, `0` neutral | | `setContrast:` | `[-1, 1]`, `0` neutral | | `setSaturation:` | `[-1, 1]`, `0` neutral | | `setColorTemperature:` | `[-1, 1]`, `0` neutral | | `setColorTint:` | `[-1, 1]`, `0` neutral | | `setClarity:` | `[0, 1]` | | `setBeautySkinOnly:` | `YES` = skin regions only | ### Reshape `setReshape:intensity:` — intensity **`[-1.0, 1.0]`**, `0` off. `FBReshape` values `0`–`25`: `FBReshape_FaceThin` … `FBReshape_BrowThickness`. Directions: [Parameter enums](/intro/makeup). ```objc theme={null} typedef NS_ENUM(NSInteger, FBReshape) { FBReshape_FaceThin = 0, FBReshape_FaceVShape = 1, FBReshape_FaceNarrow = 2, FBReshape_FaceShort = 3, FBReshape_Cheekbone = 4, FBReshape_Jawbone = 5, FBReshape_Chin = 6, FBReshape_NoseSlim = 7, FBReshape_EyeSize = 8, FBReshape_EyeDistance = 9, FBReshape_FaceSmall = 10, FBReshape_Forehead = 11, FBReshape_NoseLong = 12, FBReshape_Philtrum = 13, FBReshape_MouthSize = 14, FBReshape_MouthPosition = 15, FBReshape_MouthSmile = 16, FBReshape_LipThickness = 17, FBReshape_EyeRound = 18, FBReshape_EyePosition = 19, FBReshape_EyeAngle = 20, FBReshape_EyeCornerOpen = 21, FBReshape_LowerEyelid = 22, FBReshape_BrowPosition = 23, FBReshape_BrowDistance = 24, FBReshape_BrowThickness = 25, }; ``` ### Body reshape `setBodyReshape:intensity:` — intensity **`[0.0, 1.0]`**, `0` off. Requires `resource_body.fbd` via `addResourcePack:` first. `FBBodyReshape` values `0`–`8`. See [Parameter enums](/intro/makeup) and [Optional resource packs](/intro/resource-packs). ```objc theme={null} typedef NS_ENUM(NSInteger, FBBodyReshape) { FBBodyReshape_BodySlim = 0, FBBodyReshape_WaistSlim = 1, FBBodyReshape_LegSlim = 2, FBBodyReshape_ShoulderSlim = 3, FBBodyReshape_ArmSlim = 4, FBBodyReshape_LegLong = 5, FBBodyReshape_BustEnhance = 6, FBBodyReshape_LegStretch = 7, FBBodyReshape_TorsoLong = 8, }; ``` `FBSmoothingStyle`: `Natural`, `Texture`, `Smooth`. `FBWhiteningStyle`: `ColdWhite`, `PinkWhite`, `WarmWhite`, `Wheat`, `Tan`. ### Makeup Intensity methods take `[0, 1]`. Shape / color types: [Parameter enums](/intro/makeup). | Intensity | Style | Color | | - | - | - | | `setLipstick:` | — | `setLipstickColor:` | | `setBlush:` | `setBlushStyle:` | `setBlushColor:` | | `setContour:` | `setContourStyle:` | — | | `setEyeShadow:` | `setEyeShadowStyle:` | `setEyeShadowColor:` | | `setEyeLiner:` | `setEyeLinerStyle:` | `setEyeLinerColor:` | | `setEyebrow:` | `setEyebrowStyle:` | `setEyebrowColor:` | | `setEyelash:` | `setEyelashStyle:` | `setEyelashColor:` | | `setPupil:` | — | `setPupilColor:` | | `setTeethWhiten:` | — | — | ### Virtual background and chroma key | Method | Description | | - | - | | `setChromaKey:` | Mask from green / blue / red. Fill is still blur or image. | | `clearChromaKey` | Restore portrait-segmentation mask; does **not** clear fill | | `setChromaKeySimilarity:` | Key tightness `[0, 1]` | | `setChromaKeySmoothness:` | Edge feather `[0, 1]` | | `setChromaKeyDesaturation:` | Spill suppression `[0, 1]` | | `setVirtualBackgroundBlur:` | Blur fill `[0, 1]`; `0` clears virtual background | | `setVirtualBackground:` | png/jpg file path (must be non-empty) | | `setVirtualBackgroundWithData:` | Encoded png/jpg `NSData` | | `clearVirtualBackground` | Clear blur and image fill | ```objc theme={null} typedef NS_ENUM(NSInteger, FBChromaKeyColor) { FBChromaKeyColor_Green = 0, FBChromaKeyColor_Blue, FBChromaKeyColor_Red, }; ``` ### Filters and stickers No register-by-id. Path or bytes; GPU resources are created on the next `processImage:` (GL thread / external context). | Method | Description | | - | - | | `setFilter:` | LUT from `.fbd` path | | `setFilterWithData:` | LUT from `.fbd` bytes | | `clearFilter` | Remove LUT | | `setFilterIntensity:` | `[0, 1]` | | `setSticker:` | 2D sticker `.fbd` path | | `setStickerWithData:` | Sticker bytes | | `addResourcePack:` | Extra capability pack path (`resource_3d.fbd` before `set3DSticker:`, or `resource_body.fbd` before `setBodyReshape:`) | | `addResourcePackWithData:` | Extra pack bytes | | `set3DSticker:` | 3D sticker `.fbd` path | | `set3DStickerWithData:` | 3D sticker bytes | | `clear3DSticker` | Remove the 3D sticker | | `clearSticker` | Remove sticker | Empty path / nil or empty `NSData` → `FBErrorCode_InvalidArgument`. ### Process ```objc theme={null} - (FBImageFrame * _Nullable)processImage:(FBImageFrame *)imageFrame; ``` Reads `imageFrame.type` (`FBFrameTypeImage` or `FBFrameTypeVideo`). Output format matches input. Returns `nil` on failure. ## Error codes ```objc theme={null} typedef NS_ENUM(NSInteger, FBErrorCode) { FBErrorCode_Success = 0, FBErrorCode_InvalidArgument = -1, FBErrorCode_NotInitialized = -2, FBErrorCode_License = -3, FBErrorCode_Unsupported = -4, FBErrorCode_IO = -5, FBErrorCode_Process = -6, FBErrorCode_OutOfMemory = -7, }; ``` `-1` is invalid argument. `-2` is not initialized. ## Stats and callbacks ### `FBEngineStats` | Property | Type | Description | | - | - | - | | `fps` | `double` | Frames per second | | `avgProcessTimeMs` | `double` | Average `processImage:` time (ms) | | `sessionTimeS` | `double` | Session duration (seconds) | | `gpuLiveTextures` | `NSUInteger` | Live GPU textures (leak debugging) | | `gpuLiveMeshes` | `NSUInteger` | Live GPU meshes (leak debugging) | ```objc theme={null} - (FBEngineStats *)getStats; ``` ### `FBEngineEventCode` | Value | Symbol | | - | - | | `0` | `FBEngineEventCodeLicenseValidationSuccess` | | `1` | `FBEngineEventCodeLicenseValidationFailed` | | `100` | `FBEngineEventCodeInitializationComplete` | | `101` | `FBEngineEventCodeInitializationFailed` | ### `FBEngineCallbacks` ```objc theme={null} FB_OBJC_API @interface FBEngineCallbacks : NSObject @property(nonatomic, copy, nullable) void (^onEngineEvent) (FBEngineEventCode code, NSString * _Nullable message); @end ``` ## `FBImageFrame` ### Create | Method | Notes | | - | - | | `createWithData:width:height:format:` | Raw buffer + `FBImageFormat` | | `createWithRGBA:width:height:stride:` | | | `createWithBGRA:width:height:stride:` | | | `createWithRGB:width:height:stride:` | | | `createWithBGR:width:height:stride:` | | | `createWithI420:...` | Y / U / V planes | | `createWithNV12:...` | Y + UV | | `createWithNV21:...` | Y + VU | | `createWithFile:` | png / jpg path | | `createWithTexture:width:height:stride:` | `GL_TEXTURE_2D` in the current context; `stride` usually `width * 4` | | `setGlRenderTarget:` | Optional `GL_TEXTURE_2D` render target on the current context. Borrowed | | `setMetalRenderTarget:` | Optional `MTLTexture` output on the same device. Borrowed | | `createWithUIImage:` | **iOS only** | ### Operations | Method | Description | | - | - | | `rotate:` | `FBImageRotation`; returns `FBErrorCode` | | `mirror:` | `FBMirrorModeHorizontal` / `Vertical` / `Both`; mutates pixels. `None` is a no-op | | `setMirror:` | Flag for `processImage:` (avoids extra conversions). `FBMirrorModeNone` clears | | `convert:` | Returns a new frame in the target `FBImageFormat` | | `toFile:quality:` | quality `0`–`100` | | `toFile:` | quality `90` | `rotate:`, `mirror:`, and `setMirror:` change CPU pixel frames only (RGBA, RGB, YUV, and image files). They do not transform an OpenGL texture, a CVPixelBuffer, or a Metal texture. Supply those already upright. ### Properties and accessors `width`, `height`, `stride`, `size`, `type`. Methods: `data`, `format`, `texture` (`0` if not a texture). YUV: `dataY` / `dataU` / `dataV` / `dataUV`, `strideY` / `strideU` / `strideV` / `strideUV` (`NULL` / `0` if not YUV). ```objc theme={null} typedef NS_ENUM(NSInteger, FBImageFormat) { FBImageFormatI420, FBImageFormatNV12, FBImageFormatNV21, FBImageFormatBGRA, FBImageFormatRGBA, FBImageFormatBGR, FBImageFormatRGB, FBImageFormatTexture, }; typedef NS_ENUM(NSInteger, FBImageRotation) { FBImageRotation0, FBImageRotation90, // clockwise FBImageRotation180, FBImageRotation270, }; ``` ```objc theme={null} FBImageFrame *frame = [FBImageFrame createWithUIImage:image]; frame.type = FBFrameTypeImage; FBImageFrame *out = [engine processImage:frame]; ``` ## Makeup / style enums Objective-C symbols live in `FBBeautyParams.h`. Do not duplicate meaning tables here — see [Parameter enums](/intro/makeup). * `FBSmoothingStyle`, `FBWhiteningStyle` * `FBLipstickColor` * `FBBlushStyle`, `FBBlushColor` * `FBContourStyle` * `FBEyeShadowStyle`, `FBEyeShadowColor` * `FBEyeLinerStyle`, `FBEyeLinerColor` * `FBEyebrowStyle`, `FBEyebrowColor` * `FBEyelashStyle`, `FBEyelashColor` * `FBPupilColor` # Best Practices Source: https://docs.facebetter.net/ios/best-practices iOS Beauty Effect SDK 2.0 performance and architecture > [!NOTE] > > This page matches SDK **2.0.0**. Makeup / reshape enums: [Parameter enums](/intro/makeup). ## Choose the right frame type Set `FBImageFrame.type` **before** `processImage:`. There is no process-mode argument on the engine. * **`FBFrameTypeVideo` (`1`)**: camera preview, live, calls — lower latency. * **`FBFrameTypeImage` (`0`)**: still photos — higher quality. ```objc theme={null} input.type = FBFrameTypeVideo; FBImageFrame *output = [engine processImage:input]; ``` ## Large stills (preview vs export) Do not feed full-resolution pixels into `processImage:` on every slider change, and do not throw the original away after scaling. When the photo opens, keep the full `UIImage` and build **one** preview frame (long edge about 1280–1440, `createWithUIImage:`). Slider changes process the preview (`FBFrameTypeImage`). Export processes a full-resolution frame with the same setters. Output size matches the input. Camera preview stays capture resolution + `FBFrameTypeVideo`. ```objc theme={null} preview.type = FBFrameTypeImage; FBImageFrame *previewOut = [engine processImage:preview]; full.type = FBFrameTypeImage; FBImageFrame *exportOut = [engine processImage:full]; ``` ## Parameter ranges * Skin / makeup / filter intensity: `[0.0, 1.0]`. `0` turns that effect off. * Reshape (`setReshape:intensity:`): **`[-1.0, 1.0]`**. `0` is off. Positive and negative are opposite directions. Start low on live video. Full enum meanings: [Parameter enums](/intro/makeup). ```objc theme={null} [engine setSmoothing:0.25f]; [engine setSmoothingStyle:FBSmoothingStyle_Natural]; [engine setWhitening:0.15f]; [engine setReshape:FBReshape_FaceThin intensity:0.12f]; [engine setBeautySkinOnly:YES]; ``` ## One engine, one serial queue ```objc theme={null} @interface BeautyEngineManager : NSObject @property (nonatomic, strong, readonly) FBBeautyEffectEngine *engine; @property (nonatomic, strong, readonly) dispatch_queue_t queue; + (instancetype)sharedManager; @end @implementation BeautyEngineManager + (instancetype)sharedManager { static BeautyEngineManager *instance; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ instance = [[BeautyEngineManager alloc] init]; }); return instance; } - (instancetype)init { self = [super init]; if (self) { _queue = dispatch_queue_create("com.facebetter.process", DISPATCH_QUEUE_SERIAL); FBEngineConfig *config = [[FBEngineConfig alloc] init]; config.appId = @"your_app_id"; config.appKey = @"your_app_key"; _engine = [FBBeautyEffectEngine createEngineWithConfig:config]; } return self; } - (void)process:(FBImageFrame *)input completion:(void (^)(FBImageFrame * _Nullable))completion { dispatch_async(self.queue, ^{ input.type = FBFrameTypeVideo; FBImageFrame *output = [self.engine processImage:input]; dispatch_async(dispatch_get_main_queue(), ^{ completion(output); }); }); } @end ``` Do not process frames on the main thread except for tiny stills. Do not share one engine across concurrent queues. ## Memory * Prefer ARC. Drop `FBImageFrame` references when a frame is done. * Reuse pixel buffers from the camera; avoid allocating a new RGBA buffer every frame if the capture format is already NV12 / BGRA. * Filters and stickers load on the next `processImage:` (GL thread). Do not reload the same `.fbd` every frame — call `setFilter:` / `setSticker:` once, then `setFilterIntensity:` as needed. * Use `clearFilter`, `clearSticker`, `clearVirtualBackground`, and `clearChromaKey` instead of creating a second engine. ## External OpenGL ES When the app already owns a GL context: 2. Create the engine **on that GL thread**. 3. Wrap the texture with `createWithTexture:width:height:stride:`. 4. Read the output with `[output texture]`. Input texture, engine, and output texture must stay in the same context. ## Monitor with `getStats` Prefer `FBEngineStats` over a homemade timer: ```objc theme={null} FBEngineStats *stats = [engine getStats]; NSLog(@"fps=%.1f avg=%.2fms session=%.1fs", stats.fps, stats.avgProcessTimeMs, stats.sessionTimeS); ``` Aim for `avgProcessTimeMs` under \~33 ms at 30 fps. If it climbs, drop resolution, switch to `FBFrameTypeVideo`, or turn off unused makeup / stickers. ## Lifecycle Hold the engine as a strong property on the view controller (or a session object). Nil it in `dealloc` when the session ends. Pause capture in `viewWillDisappear` / `applicationDidEnterBackground` so you stop calling `processImage:` — you do not need a special “pause” API. ```objc theme={null} - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; [self.captureSession stopRunning]; } - (void)dealloc { self.beautyEffectEngine = nil; } ``` Use `__weak` in `FBEngineCallbacks` blocks to avoid retain cycles. ## iOS capture * Camera preview is usually `kCVPixelFormatType_420YpCbCr8BiPlanarFullRange` (NV12) or BGRA. Create `FBImageFrame` with `createWithNV12:...` or `createWithBGRA:...` instead of converting to RGBA on the CPU. * Front camera: `setMirror:FBMirrorModeHorizontal` on the frame (or `mirror:` if you need the pixels flipped before the engine). * Camera permission: `NSCameraUsageDescription` in `Info.plist`. Photo library: `NSPhotoLibraryUsageDescription` if you pick stills. ## Testing * Bind the test app’s Bundle ID and use a real `appId` / `appKey` or `licenseToken`. Dummy strings fail with license events `1` / `101`. * Cover still (`FBFrameTypeImage` + `createWithUIImage:`) and live (`FBFrameTypeVideo`) paths. * Assert setter return codes are `FBErrorCode_Success`. # Error Handling Source: https://docs.facebetter.net/ios/error-handling iOS Beauty Effect SDK 2.0 error handling > [!NOTE] > > This page matches SDK **2.0.0**. Auth: [Auth & License](/intro/license). ## Error codes (`FBErrorCode`) Setter APIs return `int`. `0` is success. `createEngineWithConfig:` and `processImage:` return objects (`nil` on failure). | Value | Symbol | Meaning | | - | - | - | | `0` | `FBErrorCode_Success` | Success | | `-1` | `FBErrorCode_InvalidArgument` | Invalid argument (nil config, empty path, out-of-range value, …) | | `-2` | `FBErrorCode_NotInitialized` | Engine is not initialized | | `-3` | `FBErrorCode_License` | License / auth failure | | `-4` | `FBErrorCode_Unsupported` | Unsupported format, platform, or feature | | `-5` | `FBErrorCode_IO` | File / resource I/O error | | `-6` | `FBErrorCode_Process` | Frame processing failed | | `-7` | `FBErrorCode_OutOfMemory` | Out of memory | ```objc theme={null} typedef NS_ENUM(NSInteger, FBErrorCode) { FBErrorCode_Success = 0, FBErrorCode_InvalidArgument = -1, FBErrorCode_NotInitialized = -2, FBErrorCode_License = -3, FBErrorCode_Unsupported = -4, FBErrorCode_IO = -5, FBErrorCode_Process = -6, FBErrorCode_OutOfMemory = -7, }; ``` ## Check return values ```objc theme={null} FBLogConfig *logConfig = [[FBLogConfig alloc] init]; logConfig.consoleEnabled = YES; logConfig.level = FBLogLevel_Info; int logRet = [FBBeautyEffectEngine setLogConfig:logConfig]; if (logRet != FBErrorCode_Success) { NSLog(@"setLogConfig failed: %d", logRet); } FBEngineConfig *config = [[FBEngineConfig alloc] init]; config.appId = @"your_app_id"; config.appKey = @"your_app_key"; self.engine = [FBBeautyEffectEngine createEngineWithConfig:config]; if (self.engine == nil) { NSLog(@"Failed to create engine (check license, Bundle ID, and logs)"); return; } int ret = [self.engine setSmoothing:0.5f]; if (ret != FBErrorCode_Success) { NSLog(@"setSmoothing failed: %d", ret); } ``` Map codes in one place: ```objc theme={null} NSString *FBErrorMessage(int code) { switch (code) { case FBErrorCode_Success: return @"success"; case FBErrorCode_InvalidArgument: return @"invalid argument"; case FBErrorCode_NotInitialized: return @"engine not initialized"; case FBErrorCode_License: return @"license / auth failure"; case FBErrorCode_Unsupported: return @"unsupported"; case FBErrorCode_IO: return @"I/O error"; case FBErrorCode_Process: return @"process failed"; case FBErrorCode_OutOfMemory: return @"out of memory"; default: return [NSString stringWithFormat:@"unknown (%d)", code]; } } ``` ## Engine events `FBEngineCallbacks.onEngineEvent` reports license and init asynchronously. Set callbacks immediately after creating the engine. | Code | Symbol | Meaning | | - | - | - | | `0` | `FBEngineEventCodeLicenseValidationSuccess` | License OK | | `1` | `FBEngineEventCodeLicenseValidationFailed` | License fail | | `100` | `FBEngineEventCodeInitializationComplete` | Init complete | | `101` | `FBEngineEventCodeInitializationFailed` | Init fail | ```objc theme={null} FBEngineCallbacks *callbacks = [[FBEngineCallbacks alloc] init]; callbacks.onEngineEvent = ^(FBEngineEventCode code, NSString * _Nullable message) { switch (code) { case FBEngineEventCodeLicenseValidationFailed: NSLog(@"License failed: %@", message); break; case FBEngineEventCodeInitializationFailed: NSLog(@"Init failed: %@", message); break; default: break; } }; [self.engine setCallbacks:callbacks]; ``` > [!TIP] > > `createEngineWithConfig:` returning a non-nil instance does not replace listening for event `1` / `101`. Online auth can still fail after construction. ## Image processing Validate the frame, set `type`, and treat a `nil` return as `FBErrorCode_Process`. ```objc theme={null} - (FBImageFrame *)processSafely:(FBImageFrame *)input { if (input == nil || input.width <= 0 || input.height <= 0) { NSLog(@"Invalid FBImageFrame"); return nil; } input.type = FBFrameTypeVideo; FBImageFrame *output = [self.engine processImage:input]; if (output == nil) { NSLog(@"processImage returned nil"); } return output; } ``` Save with `toFile:` (returns `FBErrorCode`): ```objc theme={null} int saved = [output toFile:path quality:90]; if (saved != FBErrorCode_Success) { NSLog(@"toFile failed: %d", saved); } ``` ## Logging Enable logs **before** creating the engine. Create the log directory if you write a file. ```objc theme={null} NSString *logPath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"facebetter.log"]; NSString *logDir = [logPath stringByDeletingLastPathComponent]; [[NSFileManager defaultManager] createDirectoryAtPath:logDir withIntermediateDirectories:YES attributes:nil error:nil]; FBLogConfig *logConfig = [[FBLogConfig alloc] init]; logConfig.consoleEnabled = YES; logConfig.fileEnabled = YES; logConfig.level = FBLogLevel_Debug; logConfig.fileName = logPath; [FBBeautyEffectEngine setLogConfig:logConfig]; ``` ## Practical checks * **`-1` Invalid argument**: empty `.fbd` path, nil `NSData`, intensity outside the documented range, or a nil config. * **`-2` Not initialized**: calling setters after a failed `createEngineWithConfig:` (the instance is `nil` — do not send messages to it). * **`-3` License**: wrong `appId` / `appKey`, unbound Bundle ID, expired token, or no network for online auth. See [Auth & License](/intro/license). * **`-5` I/O**: missing filter / sticker / background file, or unreadable sandbox path. # FAQ Source: https://docs.facebetter.net/ios/faq iOS Beauty Effect SDK 2.0 common questions > [!NOTE] > > This page matches SDK **2.0.0**. Auth: [Auth & License](/intro/license). Enums: [Parameter enums](/intro/makeup). ## Integration ### Engine creation returns `nil` * Confirm `licenseToken` **or** `appId` + `appKey` is set. Token wins if both are present. * Bind the app **Bundle ID** in the dashboard. * Online auth needs network to `/facebetter/v2/auth`. * Enable logs **before** `createEngineWithConfig:` and watch events `1` (license fail) and `101` (init fail). * CocoaPods: `pod 'Facebetter', '2.0.0'`. Open the `.xcworkspace`, not the `.xcodeproj`. ### Missing headers or classes * Import `#import `. * For a manual `.framework`, set **Embed & Sign**. * Clean Build Folder and rebuild. * If CocoaPods scripts fail on Xcode 15+, set `ENABLE_USER_SCRIPT_SANDBOXING` to **No**. ### Runtime link / dyld errors * Architecture must be **arm64**. * Deployment target **iOS 12.0+**. * Confirm `Facebetter.framework` is in Embed Frameworks. ## Auth ### `licenseToken` vs `appId` / `appKey` If `licenseToken` is non-empty, the SDK verifies that token / `{token}` JSON / `.lic` locally and does **not** send `appId` / `appKey`. Otherwise it uses online auth. Details: [Auth & License](/intro/license). ### Event `1` or `101` License or init failed. Check Bundle ID, plan, token expiry, and logs. Creation returning a non-nil object is not enough — listen to `onEngineEvent`. ## Beauty ### Effect is too weak or too strong * Skin / makeup / filter: `[0.0, 1.0]`. * Face reshape: **`[-1.0, 1.0]`** via `setReshape:intensity:` (`0` is off). * Body reshape: **`[0.0, 1.0]`** via `setBodyReshape:intensity:`. Register `resource_body.fbd` first. * Intensity `0` disables that effect. * Skin-only: `setBeautySkinOnly:`. ### Makeup / reshape enum values Do not copy tables into app code comments — use [Parameter enums](/intro/makeup). Objective-C names look like `FBReshape_FaceThin`, `FBLipstickColor_Rouge`. ## Filters, stickers, virtual background ### Filter or sticker does nothing Pass the `.fbd` path or bytes: ```objc theme={null} [engine setFilter:fbdPath]; [engine setFilterIntensity:0.8f]; [engine clearFilter]; [engine setSticker:fbdPath]; [engine clearSticker]; ``` Textures are created on the next `processImage:` (GL thread). Empty path / nil data returns `FBErrorCode_InvalidArgument`. Missing file returns `FBErrorCode_IO`. ### Virtual background ```objc theme={null} [engine setVirtualBackgroundBlur:0.6f]; // 0 clears blur [engine setVirtualBackground:imagePath]; // png/jpg [engine setVirtualBackgroundWithData:imageData]; [engine clearVirtualBackground]; ``` Chroma key is the **mask**; fill is still blur or image: ```objc theme={null} [engine setChromaKey:FBChromaKeyColor_Green]; [engine setChromaKeySimilarity:0.4f]; [engine clearChromaKey]; // back to portrait segmentation; fill stays ``` ## Processing ### `processImage:` returns `nil` * Engine is `nil` or init failed (`-2` / event `101`). * Invalid frame (zero size, unsupported format). * Treat as process failure (`FBErrorCode_Process`). ### Frame type Set `imageFrame.type` to `FBFrameTypeImage` (`0`) or `FBFrameTypeVideo` (`1`). Do not pass a process-mode argument. ### Format conversion Use `convert:` and the frame accessors: ```objc theme={null} FBImageFrame *rgba = [frame convert:FBImageFormatRGBA]; const uint8_t *data = [rgba data]; ``` YUV: `dataY` / `dataU` / `dataV` / `dataUV` and the matching `stride*`. ### UIImage ```objc theme={null} FBImageFrame *frame = [FBImageFrame createWithUIImage:image]; frame.type = FBFrameTypeImage; FBImageFrame *out = [engine processImage:frame]; ``` ### Camera preview 1. Read `CVPixelBuffer` from `AVCaptureVideoDataOutput`. 2. Build `FBImageFrame` with `createWithNV12:...` or `createWithBGRA:...`. 3. Set `type = FBFrameTypeVideo`, optional `setMirror:FBMirrorModeHorizontal`. 4. `processImage:` then display `[output data]` or `[output texture]`. ## Performance and memory * Use `FBFrameTypeVideo` for live; lower resolution if `getStats.avgProcessTimeMs` is high. * One engine, serial queue; do not process on the main thread. * Release frames with ARC (`frame = nil`). Reuse capture buffers. * Avoid `setFilter:` / `setSticker:` every frame. ## Logging ```objc theme={null} FBLogConfig *logConfig = [[FBLogConfig alloc] init]; logConfig.consoleEnabled = YES; logConfig.fileEnabled = YES; logConfig.level = FBLogLevel_Debug; logConfig.fileName = logPath; [FBBeautyEffectEngine setLogConfig:logConfig]; // before createEngineWithConfig: ``` Return codes: `0` success, `-1` invalid argument, `-2` not initialized. Full list: [Error Handling](/ios/error-handling). ## Version * **iOS 12.0+**, **arm64**. * CocoaPods: `pod 'Facebetter', '2.0.0'`. * After upgrade: `pod install`, Clean Build Folder, re-test auth and `processImage:`. ## Threading * Default engine: serial queue for all `processImage:` and setters that touch GL resources. * Update UI on the main queue only. # Implement Beauty Source: https://docs.facebetter.net/ios/implement-beauty Implement iOS beauty with Beauty Effect SDK 2.0 > [!NOTE] > > This page matches SDK **2.0.0**. Auth: [Auth & License](/intro/license). Makeup / reshape enums: [Parameter enums](/intro/makeup). ## Add SDK dependency ### Method A: CocoaPods (recommended) ```ruby theme={null} target 'YourTargetName' do pod 'Facebetter', '2.0.0' end ``` ```bash theme={null} pod install ``` > [!WARNING] > > **Xcode 15+ compilation error** > > If you are using **Xcode 15** or later, you might encounter a `Sandbox: rsync.samba deny(1)` error. This is caused by **User Script Sandboxing**. > > **Solution:** > > 1. Select your **Project** in Xcode. > 2. Open **Build Settings**. > 3. Search for `ENABLE_USER_SCRIPT_SANDBOXING`. > 4. Change the value from `Yes` to **`No`**. ### Method B: Manual framework Download the SDK from [Download](https://facebetter.net/download), copy `Facebetter.framework` into the project, and [embed the dynamic library](https://help.apple.com/xcode/mac/current/#/dev51a648b07) with **Embed & Sign**. ![Xcode Link Library](https://mintcdn.com/facebetter/DM5KtVsHX1q4Zlkm/images/ios-3.png?fit=max\&auto=format\&n=DM5KtVsHX1q4Zlkm\&q=85\&s=d27068487388c927268f25c4aecb957e) ### Permissions Add camera permission in `Info.plist` only if the app captures from the camera: ```xml theme={null} NSCameraUsageDescription Camera permission required for beauty photography ``` ## Import ```objc theme={null} #import ``` ## Log configuration Logging is off by default. Call `setLogConfig:` **before** creating the engine. ```objc theme={null} FBLogConfig *logConfig = [[FBLogConfig alloc] init]; logConfig.level = FBLogLevel_Info; logConfig.consoleEnabled = YES; logConfig.fileEnabled = YES; logConfig.fileName = @"/path/to/facebetter.log"; [FBBeautyEffectEngine setLogConfig:logConfig]; ``` ## Create the engine Bind the iOS Bundle ID, then pass either `licenseToken` or `appId` + `appKey`. See [Get AppID and AppKey](/intro/enable-service#get-appid-and-appkey) and [Auth & License](/intro/license). **Priority:** if `licenseToken` is non-empty (license token string, `{token}` JSON, or `.lic` contents), the SDK validates it locally. Otherwise it uses `appId` + `appKey` against `/facebetter/v2/auth`. ```objc theme={null} FBEngineConfig *engineConfig = [[FBEngineConfig alloc] init]; engineConfig.appId = @"your appId"; engineConfig.appKey = @"your appKey"; // engineConfig.licenseToken = @"your license token"; self.beautyEffectEngine = [FBBeautyEffectEngine createEngineWithConfig:engineConfig]; if (self.beautyEffectEngine == nil) { NSLog(@"Failed to create beauty engine"); return; } ``` `createEngineWithConfig:` returns an **instance**, not a singleton. ## Skin beauty Intensity is typically `[0.0, 1.0]`. Style enums: [Parameter enums](/intro/makeup). ```objc theme={null} [self.beautyEffectEngine setSmoothing:0.5f]; [self.beautyEffectEngine setSmoothingStyle:FBSmoothingStyle_Natural]; [self.beautyEffectEngine setWhitening:0.3f]; [self.beautyEffectEngine setWhiteningStyle:FBWhiteningStyle_ColdWhite]; [self.beautyEffectEngine setRosiness:0.15f]; [self.beautyEffectEngine setBrightness:0.1f]; [self.beautyEffectEngine setClarity:0.2f]; ``` ### Skin-only When enabled, smoothing / whitening / rosiness apply only to detected skin. ```objc theme={null} [self.beautyEffectEngine setBeautySkinOnly:YES]; ``` ## Face reshape `setReshape:intensity:` range is **`[-1.0, 1.0]`**. `0` is off. Parameters: `FBReshape_FaceThin` … `FBReshape_BrowThickness` (`0`–`25`). Meanings: [Parameter enums](/intro/makeup). ```objc theme={null} [self.beautyEffectEngine setReshape:FBReshape_FaceThin intensity:0.4f]; [self.beautyEffectEngine setReshape:FBReshape_EyeSize intensity:0.2f]; ``` ## Body reshape `setBodyReshape:intensity:` range is **`[0.0, 1.0]`**. `0` is off. Register `resource_body.fbd` with `addResourcePack:` first. Parameters: `FBBodyReshape_BodySlim` … `FBBodyReshape_TorsoLong` (`0`–`8`). See [Parameter enums](/intro/makeup) and [Optional resource packs](/intro/resource-packs). ```objc theme={null} NSString *bodyPack = [[NSBundle mainBundle] pathForResource:@"resource_body" ofType:@"fbd"]; [self.beautyEffectEngine addResourcePack:bodyPack]; [self.beautyEffectEngine setBodyReshape:FBBodyReshape_WaistSlim intensity:0.4f]; [self.beautyEffectEngine setBodyReshape:FBBodyReshape_LegStretch intensity:0.3f]; [self.beautyEffectEngine setBodyReshape:FBBodyReshape_TorsoLong intensity:0.3f]; ``` ## Makeup Intensity, shape, and color are separate calls. Full presets: [Parameter enums](/intro/makeup). ```objc theme={null} [self.beautyEffectEngine setLipstick:0.5f]; [self.beautyEffectEngine setLipstickColor:FBLipstickColor_Rouge]; [self.beautyEffectEngine setBlush:0.4f]; [self.beautyEffectEngine setBlushStyle:FBBlushStyle_SunKissed]; [self.beautyEffectEngine setBlushColor:FBBlushColor_CoralPink]; [self.beautyEffectEngine setContour:0.35f]; [self.beautyEffectEngine setContourStyle:FBContourStyle_Natural]; [self.beautyEffectEngine setEyeShadow:0.4f]; [self.beautyEffectEngine setEyeShadowStyle:FBEyeShadowStyle_Soft]; [self.beautyEffectEngine setEyeShadowColor:FBEyeShadowColor_Plum]; [self.beautyEffectEngine setEyeLiner:0.4f]; [self.beautyEffectEngine setEyeLinerStyle:FBEyeLinerStyle_Classic]; [self.beautyEffectEngine setEyeLinerColor:FBEyeLinerColor_Coffee]; [self.beautyEffectEngine setEyebrow:0.4f]; [self.beautyEffectEngine setEyebrowStyle:FBEyebrowStyle_Natural]; [self.beautyEffectEngine setEyebrowColor:FBEyebrowColor_DarkBrown]; [self.beautyEffectEngine setEyelash:0.4f]; [self.beautyEffectEngine setEyelashStyle:FBEyelashStyle_Classic]; [self.beautyEffectEngine setEyelashColor:FBEyelashColor_Black]; [self.beautyEffectEngine setPupil:0.4f]; [self.beautyEffectEngine setPupilColor:FBPupilColor_Hazel]; ``` ## Virtual background Portrait segmentation is the default mask. Blur level is `[0.0, 1.0]`; `0` clears blur. Image path must be a non-empty png/jpg. ```objc theme={null} [self.beautyEffectEngine setVirtualBackgroundBlur:0.6f]; [self.beautyEffectEngine setVirtualBackground:imagePath]; [self.beautyEffectEngine setVirtualBackgroundWithData:pngOrJpegData]; [self.beautyEffectEngine clearVirtualBackground]; ``` ### Chroma key Chroma key replaces the mask only. Fill is still blur or the replacement image. ```objc theme={null} [self.beautyEffectEngine setChromaKey:FBChromaKeyColor_Green]; [self.beautyEffectEngine setChromaKeySimilarity:0.4f]; [self.beautyEffectEngine setChromaKeySmoothness:0.3f]; [self.beautyEffectEngine setChromaKeyDesaturation:0.2f]; [self.beautyEffectEngine clearChromaKey]; // back to portrait segmentation ``` ## Filters and stickers Pass a `.fbd` file path or in-memory bytes. Changes take effect on the next `processImage:`. ```objc theme={null} NSString *filterPath = [[NSBundle mainBundle] pathForResource:@"chuxin" ofType:@"fbd"]; [self.beautyEffectEngine setFilter:filterPath]; [self.beautyEffectEngine setFilterIntensity:0.8f]; [self.beautyEffectEngine clearFilter]; NSData *filterData = [NSData dataWithContentsOfFile:filterPath]; [self.beautyEffectEngine setFilterWithData:filterData]; NSString *stickerPath = [[NSBundle mainBundle] pathForResource:@"cherry" ofType:@"fbd"]; [self.beautyEffectEngine setSticker:stickerPath]; [self.beautyEffectEngine clearSticker]; [self.beautyEffectEngine setStickerWithData:stickerData]; ``` 3D stickers need the optional `resource_3d.fbd` pack (not in the framework). See [Optional resource packs](/intro/resource-packs): ```objc theme={null} NSString *packPath = [[NSBundle mainBundle] pathForResource:@"resource_3d" ofType:@"fbd"]; [self.beautyEffectEngine addResourcePack:packPath]; NSString *sticker3dPath = [[NSBundle mainBundle] pathForResource:@"oculos" ofType:@"fbd"]; [self.beautyEffectEngine set3DSticker:sticker3dPath]; [self.beautyEffectEngine clear3DSticker]; ``` ## Callbacks and stats ```objc theme={null} FBEngineCallbacks *callbacks = [[FBEngineCallbacks alloc] init]; callbacks.onEngineEvent = ^(FBEngineEventCode code, NSString * _Nullable message) { // 0 license OK, 1 license fail, 100 init complete, 101 init fail NSLog(@"engine event %ld %@", (long)code, message); }; [self.beautyEffectEngine setCallbacks:callbacks]; FBEngineStats *stats = [self.beautyEffectEngine getStats]; NSLog(@"fps=%.1f avg=%.2fms session=%.1fs", stats.fps, stats.avgProcessTimeMs, stats.sessionTimeS); ``` ## Process images `FBImageFrame` supports I420, NV12, NV21, RGB, RGBA, BGR, BGRA, file, texture, and `UIImage`. ```objc theme={null} FBImageFrame *fromFile = [FBImageFrame createWithFile:@"/path/photo.png"]; FBImageFrame *fromRGBA = [FBImageFrame createWithRGBA:data width:width height:height stride:stride]; FBImageFrame *fromUIImage = [FBImageFrame createWithUIImage:uiImage]; ``` Set `type` then call `processImage:` (no extra mode argument). Output keeps the input format. ```objc theme={null} input.type = FBFrameTypeVideo; // or FBFrameTypeImage FBImageFrame *output = [self.beautyEffectEngine processImage:input]; ``` > [!TIP] > > `FBFrameTypeVideo` is for live streams; `FBFrameTypeImage` is for stills. Rotate / mirror / convert / save. `rotate:` and `setMirror:` change CPU pixels only. They do not transform an OpenGL texture, a CVPixelBuffer, or a Metal texture: ```objc theme={null} [input rotate:FBImageRotation90]; [input setMirror:FBMirrorModeHorizontal]; // applied during processImage: FBImageFrame *rgba = [output convert:FBImageFormatRGBA]; const uint8_t *bytes = [rgba data]; [output toFile:@"/path/out.jpg" quality:90]; ``` YUV planes: `dataY`, `dataU`, `dataV`, `dataUV` and `strideY` / `strideU` / `strideV` / `strideUV`. ## External texture > [!WARNING] > > Create the engine and call process on the thread whose GL context is current. Input and output textures must belong to that context. CPU frames do not need a caller GL context. There is no context flag on the config. ```objc theme={null} FBEngineConfig *config = [[FBEngineConfig alloc] init]; config.appId = @"your appId"; config.appKey = @"your appKey"; self.engine = [FBBeautyEffectEngine createEngineWithConfig:config]; FBImageFrame *inputFrame = [FBImageFrame createWithTexture:textureId width:width height:height stride:width * 4]; inputFrame.type = FBFrameTypeVideo; FBImageFrame *outputFrame = [self.engine processImage:inputFrame]; GLuint outputTexture = [outputFrame texture]; ``` Recommended texture params: `GL_LINEAR`, `GL_CLAMP_TO_EDGE`. The engine does not delete your input texture. Output textures are owned by the SDK. For TRTC / Agora / LiveKit: [Third-party Integration](/ios/third-party-integration). ## Lifecycle Keep a strong reference for the session. Nil the engine when the view controller is gone. Pause the capture session when leaving the screen so you stop calling `processImage:`. ```objc theme={null} - (void)dealloc { self.beautyEffectEngine = nil; } ``` ## Related * [Third-party Integration](/ios/third-party-integration) * [Best Practices](/ios/best-practices) * [Error Handling](/ios/error-handling) * [FAQ](/ios/faq) * [API Reference](/ios/api-reference) # Quick Start Source: https://docs.facebetter.net/ios/quick-start Run the iOS sample app with Beauty Effect SDK 2.0 > [!NOTE] > > This page matches SDK **2.0.0**. Auth: [Auth & License](/intro/license). Makeup / reshape enums: [Parameter enums](/intro/makeup). ## Environment Requirements * **iOS Version**: `iOS 12.0` and above * **Development Language**: `Objective-C` * **Architecture Support**: `arm64` ## Get Sample Source Code Clone the [GitHub repository](https://github.com/pixpark/facebetter-sdk) locally, and navigate to the `demo/ios` directory. ```bash theme={null} # clone git clone https://github.com/pixpark/facebetter-sdk.git # Enter iOS Demo directory cd facebetter-sdk/demo/ios # Install dependencies pod install ``` > [!WARNING] > > **Xcode 15+ compilation error** > > If you are using **Xcode 15** or later, you might encounter a `Sandbox: rsync.samba deny(1)` error during compilation. This is caused by Xcode's default **User Script Sandboxing**. > > **Solution:** > > 1. Select your **Project** in Xcode. > 2. Navigate to the **Build Settings** tab. > 3. Search for `ENABLE_USER_SCRIPT_SANDBOXING`. > 4. Change its value from `Yes` to **`No`**. ## Configure Application Information and Keys ### Bind Application Bundle ID Follow [Bind Application Information](/intro/enable-service#bind-application-information) to bind your iOS application Bundle ID in the console, for example: `com.example.app`. ### Get credentials Follow [Get AppID and AppKey](/intro/enable-service#get-appid-and-appkey) to obtain `appId` and `appKey`. Open `demo/ios/FBExampleObjc/CameraViewController.m` and set credentials on `FBEngineConfig`. ```objc theme={null} FBEngineConfig *engineConfig = [[FBEngineConfig alloc] init]; engineConfig.appId = @"your appId"; engineConfig.appKey = @"your appKey"; // Preferred: licenseToken (license token, {token} JSON, or .lic contents) // engineConfig.licenseToken = @"your license token"; self.beautyEffectEngine = [FBBeautyEffectEngine createEngineWithConfig:engineConfig]; ``` > [!TIP] > > If `licenseToken` is non-empty, the SDK validates that token locally and does **not** call `/facebetter/v2/auth` with `appId` / `appKey`. See [Auth & License](/intro/license). ## Run the Project Open `demo/ios/FBExampleObjc.xcworkspace`. 1. Ensure Xcode project signing is correct. ![Xcode Signing](https://mintcdn.com/facebetter/DM5KtVsHX1q4Zlkm/images/ios-1.png?fit=max\&auto=format\&n=DM5KtVsHX1q4Zlkm\&q=85\&s=beb0bc3b315d6007c761b7617df679cf) 2. Build and run. Select a physical device and click the build and run button. # Third-party Integration Source: https://docs.facebetter.net/ios/third-party-integration Wire Facebetter beauty into TRTC, Agora, LiveKit, and other iOS video pipelines SDK **2.0.0**. Hook Facebetter into a third-party SDK’s **custom video preprocess** callback: process frames on that SDK’s **OpenGL ES thread** (or pixel-buffer callback), then return the result. Full texture rules: [Implement Beauty · External texture](/ios/implement-beauty#external-texture). Room join, publish, and permissions belong in the vendor’s docs — this page only covers the Facebetter hookup. ``` Third-party SDK textureId or CVPixelBuffer ↓ FBBeautyEffectEngine createWithTexture / createWithNV12|BGRA → processImage: ↓ output texture or pixels → write back to vendor frame ``` ## Shared contract | Item | Requirement | | - | - | | Input texture | `GL_TEXTURE_2D` (RGBA); `stride` usually `width * 4` | | Frame type | `FBFrameTypeVideo` | | Output | SDK owns output textures — do not `glDeleteTextures`. Keep a strong engine ref; set to `nil` when the session ends | | Lifecycle | When the vendor destroys the GL context, nil the engine, then recreate on the new context | On Apple platforms, TRTC custom preprocess commonly uses **OpenGL textures**; Agora / LiveKit more often deliver **`CVPixelBuffer`**. Both work — do not mix both modes on one engine instance. ### Shared: process texture ```objc theme={null} #import static GLuint FBProcessTexture(FBBeautyEffectEngine *engine, GLuint srcTextureId, int width, int height) { if (!engine || srcTextureId == 0 || width <= 0 || height <= 0) { return srcTextureId; } FBImageFrame *input = [FBImageFrame createWithTexture:srcTextureId width:width height:height stride:width * 4]; if (!input) { return srcTextureId; } input.type = FBFrameTypeVideo; FBImageFrame *output = [engine processImage:input]; if (!output) { return srcTextureId; } GLuint dst = [output texture]; return dst != 0 ? dst : srcTextureId; } ``` Create the engine (GL thread): ```objc theme={null} FBEngineConfig *config = [[FBEngineConfig alloc] init]; config.appId = @"your appId"; config.appKey = @"your appKey"; // or config.licenseToken = @"..."; self.beautyEngine = [FBBeautyEffectEngine createEngineWithConfig:config]; [self.beautyEngine setSmoothing:0.5f]; ``` ### Shared: process CVPixelBuffer (NV12 sketch) Agora / LiveKit callbacks often use NV12. Take plane pointers and strides from the `CVPixelBuffer`; how you write back into the vendor frame varies by SDK version. ```objc theme={null} static FBImageFrame *FBFrameFromNV12PixelBuffer(CVPixelBufferRef pb) { OSType fmt = pb ? CVPixelBufferGetPixelFormatType(pb) : 0; if (!pb || (fmt != kCVPixelFormatType_420YpCbCr8BiPlanarFullRange && fmt != kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange)) { return nil; } CVPixelBufferLockBaseAddress(pb, kCVPixelBufferLock_ReadOnly); int width = (int)CVPixelBufferGetWidth(pb); int height = (int)CVPixelBufferGetHeight(pb); uint8_t *y = (uint8_t *)CVPixelBufferGetBaseAddressOfPlane(pb, 0); uint8_t *uv = (uint8_t *)CVPixelBufferGetBaseAddressOfPlane(pb, 1); int strideY = (int)CVPixelBufferGetBytesPerRowOfPlane(pb, 0); int strideUV = (int)CVPixelBufferGetBytesPerRowOfPlane(pb, 1); FBImageFrame *frame = [FBImageFrame createWithNV12:width height:height dataY:y strideY:strideY dataUV:uv strideUV:strideUV]; CVPixelBufferUnlockBaseAddress(pb, kCVPixelBufferLock_ReadOnly); return frame; } ``` *** ## TRTC (Tencent) Hook: `setLocalVideoProcessDelegete:pixelFormat:bufferType:` (official spelling **Delegete**). Use **`TRTCVideoPixelFormat_Texture_2D`** and **`TRTCVideoBufferType_Texture`**. Implement `TRTCVideoFrameDelegate`: create the engine in `onGLContextCreated`; set `dstFrame.textureId` in `onProcessVideoFrame:dstFrame:`; nil the engine in `onGLContextDestory`. ```objc theme={null} #import #import @interface BeautyProcessDelegate : NSObject @property (nonatomic, strong) FBBeautyEffectEngine *beautyEngine; @end @implementation BeautyProcessDelegate - (void)onGLContextCreated { FBEngineConfig *config = [[FBEngineConfig alloc] init]; config.appId = @"your appId"; config.appKey = @"your appKey"; self.beautyEngine = [FBBeautyEffectEngine createEngineWithConfig:config]; [self.beautyEngine setSmoothing:0.5f]; } - (uint32_t)onProcessVideoFrame:(TRTCVideoFrame *)srcFrame dstFrame:(TRTCVideoFrame *)dstFrame { GLuint out = FBProcessTexture(self.beautyEngine, srcFrame.textureId, srcFrame.width, srcFrame.height); dstFrame.textureId = out; return 0; } - (void)onGLContextDestory { self.beautyEngine = nil; } @end // Register BeautyProcessDelegate *delegate = [[BeautyProcessDelegate alloc] init]; [[TRTCCloud sharedInstance] setLocalVideoProcessDelegete:delegate pixelFormat:TRTCVideoPixelFormat_Texture_2D bufferType:TRTCVideoBufferType_Texture]; ``` Nil the engine after clearing the delegate or leaving the room. See Tencent’s TRTC third-party beauty guide for the latest details. *** ## Agora Hook: `AgoraRtcEngineKit.setVideoFrameDelegate:` (Video SDK **4.x**). On iOS, captured frames are usually **`CVPixelBuffer`** (`textureBuf` / format `12`), not an Android-style `GL_TEXTURE_2D` id. You need to: 1. Return **ReadWrite** from `getVideoFrameProcessMode` 2. Take the `CVPixelBuffer` in `onCapture:sourceType:` (or older `onCaptureVideoFrame`) 3. Feed it via `createWithNV12:` / `createWithBGRA:`, then **write** the result back into `AgoraOutputVideoFrame` ```objc theme={null} #import @interface BeautyFrameDelegate : NSObject @property (nonatomic, strong) FBBeautyEffectEngine *beautyEngine; @end @implementation BeautyFrameDelegate - (AgoraVideoFrameProcessMode)getVideoFrameProcessMode { return AgoraVideoFrameProcessModeReadWrite; } - (BOOL)onCapture:(AgoraOutputVideoFrame *)videoFrame sourceType:(AgoraVideoSourceType)sourceType { CVPixelBufferRef pb = videoFrame.pixelBuffer; // some versions use textureBuf — check your headers if (!pb) { return YES; } if (!self.beautyEngine) { FBEngineConfig *config = [[FBEngineConfig alloc] init]; config.appId = @"your appId"; config.appKey = @"your appKey"; self.beautyEngine = [FBBeautyEffectEngine createEngineWithConfig:config]; } FBImageFrame *input = FBFrameFromNV12PixelBuffer(pb); if (!input) { return YES; // not NV12: use BGRA factory methods or convert first } input.type = FBFrameTypeVideo; FBImageFrame *output = [self.beautyEngine processImage:input]; if (!output) { return YES; } // Copy output NV12/BGRA planes back into videoFrame’s CVPixelBuffer, // or replace pixelBuffer / textureBuf per Agora docs. Details vary by version. return YES; } @end [agoraKit setVideoFrameDelegate:delegate]; ``` > [!WARNING] > > How you write a processed `CVPixelBuffer` back into Agora’s frame differs across major versions. Facebetter keeps `processImage:` output in the same format as the input; injecting that into `AgoraOutputVideoFrame` must follow [Agora raw video processing](https://docs.agora.io/en/video-calling/develop/product-workflow). Call `setVideoFrameDelegate:nil` and nil `beautyEngine` before tearing down the engine. *** ## LiveKit Hook: implement Swift `VideoProcessor`, transform in `process(frame:)`, return the new frame (or `nil` to drop). Pass `processor:` when creating the camera track, or set `track.processor` later. ```swift theme={null} import LiveKit import Facebetter // module name as packaged final class FacebetterVideoProcessor: VideoProcessor { private var beautyEngine: FBBeautyEffectEngine? func process(frame: VideoFrame) -> VideoFrame? { // Pull CVPixelBuffer from the LiveKit VideoFrame (property may be // buffer / pixelBuffer / rtcFrame — check your LiveKit Swift headers) guard let pb = frame.buffer as CVPixelBuffer? else { return frame } if beautyEngine == nil { let config = FBEngineConfig() config.appId = "your appId" config.appKey = "your appKey" beautyEngine = FBBeautyEffectEngine.createEngine(with: config) beautyEngine?.setSmoothing(0.5) } // ObjC helper: FBFrameFromNV12PixelBuffer → processImage: // then wrap the output as a LiveKit VideoFrame and return it. // See LiveKit “Video Processors” for frame wrapping. return frame } } let processor = FacebetterVideoProcessor() let track = LocalVideoTrack.createCameraTrack(processor: processor) // or: track.processor = processor try await room.localParticipant.publish(track: track) ``` Official sample processors (for example background blur) ship as `BackgroundBlurVideoProcessor`. Custom capturers can run Facebetter before frames enter the encoder. *** ## Troubleshooting | Symptom | Check | | - | - | | Black / no video | Texture path: engine on vendor **GL thread**. Pixel path: lock/unlock `CVPixelBuffer` | | Intermittent crash | Nil engine in `onGLContextDestory`; never delete output textures | | Distortion | Width / height / rotation / mirror match the vendor frame; strides use `BytesPerRow` | ## Related * [Implement Beauty](/ios/implement-beauty) * [Best Practices](/ios/best-practices) * [Error Handling](/ios/error-handling) * [API Reference](/ios/api-reference) * [macOS · Third-party Integration](/macos/third-party-integration) # API Reference Source: https://docs.facebetter.net/linux/api-reference Beauty Effect SDK 2.0 C++ API for Linux > [!NOTE] > > SDK **2.0.0**. Namespace `facebetter`. Same public C++ API as [Windows](/windows/api-reference). Headers: `facebetter/*.h`. Enums: [Parameter enums](/intro/makeup). Auth: [Auth & License](/intro/license). ## Linux notes * Ship `libfacebetter.so`. Set `LD_LIBRARY_PATH`, rpath, or `ldconfig`. * Build the SDK with `./scripts/build_linux.sh` (output `build/linux/release`) or CMake. * `resource_path` must be the **`resource.fbd` file**. * Create the engine and call process on the thread whose GL context is current. Input and output textures must belong to that context. CPU frames do not need a caller GL context. There is no context flag on the config. ```cmake theme={null} target_include_directories(app PRIVATE /path/to/sdk/include) target_link_libraries(app PRIVATE /path/to/sdk/lib/libfacebetter.so GL) ``` *** ## Logging ```cpp theme={null} enum class LogLevel { Trace = 0, Debug, Info, Warn, Error, Critical }; struct LogConfig { bool console_enabled = false; bool file_enabled = false; LogLevel level = LogLevel::Info; std::string file_name = ""; }; static int BeautyEffectEngine::SetLogConfig(const LogConfig& config); ``` Call `SetLogConfig` **before** `Create`. *** ## Engine ### `EngineConfig` | Field | Description | | - | - | | `app_id` / `app_key` | Native online v2 auth | | `resource_path` | Path to `resource.fbd` (file, not directory) | | `license_token` | token / `{token}` JSON / `.lic` — non-empty takes priority | ```cpp theme={null} struct EngineConfig { std::string app_id; std::string app_key; std::string resource_path; std::string license_token; }; static std::shared_ptr BeautyEffectEngine::Create( const EngineConfig& config); ``` *** ### Skin ```cpp theme={null} int SetSmoothing(float intensity); // [0, 1] int SetSmoothingStyle(SmoothingStyle style); int SetWhitening(float intensity); int SetWhiteningStyle(WhiteningStyle style); int SetRosiness(float intensity); int SetBrightness(float intensity); // [-1, 1], 0 neutral int SetContrast(float intensity); int SetSaturation(float intensity); int SetColorTemperature(float intensity); int SetColorTint(float intensity); int SetClarity(float intensity); // [0, 1] int SetBeautySkinOnly(bool enabled); ``` ### Reshape ```cpp theme={null} int SetReshape(Reshape param, float intensity); // [-1, 1] ``` Full `Reshape` list: [Parameter enums](/intro/makeup). ### Body reshape ```cpp theme={null} int SetBodyReshape(BodyReshape param, float intensity); // [0, 1] ``` ```cpp theme={null} ``` Full `BodyReshape` list: [Parameter enums](/intro/makeup). Requires `resource_body.fbd`. See [Optional resource packs](/intro/resource-packs). ### Makeup ```cpp theme={null} int SetLipstick(float); int SetLipstickColor(LipstickColor); int SetBlush(float); int SetBlushStyle(BlushStyle); int SetBlushColor(BlushColor); int SetContour(float); int SetContourStyle(ContourStyle); int SetEyeShadow(float); int SetEyeShadowStyle(...); int SetEyeShadowColor(...); int SetEyeLiner(float); int SetEyeLinerStyle(...); int SetEyeLinerColor(...); int SetEyebrow(float); int SetEyebrowStyle(...); int SetEyebrowColor(...); int SetEyelash(float); int SetEyelashStyle(...); int SetEyelashColor(...); int SetPupil(float); int SetPupilColor(PupilColor); ``` Lipstick is Color only; pupil is Color only; contour is Style only. Values: [Parameter enums](/intro/makeup). ### Chroma key and virtual background ```cpp theme={null} int SetChromaKey(ChromaKeyColor color); // Green, Blue, Red int ClearChromaKey(); int SetChromaKeySimilarity(float); int SetChromaKeySmoothness(float); int SetChromaKeyDesaturation(float); int SetVirtualBackgroundBlur(float level); // [0, 1]; 0 clears fill int SetVirtualBackground(const std::string& image_path); int SetVirtualBackground(const std::vector& image_data); int ClearVirtualBackground(); ``` ### Filter and sticker Path or encoded `.fbd` bytes. No register / ID API. Takes effect on the next `ProcessImage`. ```cpp theme={null} int SetFilter(const std::string& fbd_file_path); int SetFilter(const std::vector& fbd_data); int ClearFilter(); int SetFilterIntensity(float intensity); int SetSticker(const std::string& fbd_file_path); int SetSticker(const std::vector& fbd_data); int ClearSticker(); int AddResourcePack(const std::string& fbd_file_path); int AddResourcePack(const std::vector& fbd_data); int Set3DSticker(const std::string& resource); int Set3DSticker(const std::vector& fbd_data); int Clear3DSticker(); ``` Load optional packs first (`resource_3d.fbd` before 3D stickers, `resource_body.fbd` before body reshape). See [Optional resource packs](/intro/resource-packs). ### Stats, callbacks, process ```cpp theme={null} EngineStats GetStats() const; int SetCallbacks(const EngineCallbacks& callbacks); const std::shared_ptr ProcessImage( const std::shared_ptr image_frame); ``` Set `frame->type` to `FrameType::Image` or `FrameType::Video`. ```cpp theme={null} struct EngineStats { double fps = 0.0; double avg_process_time_ms = 0.0; double session_time_s = 0.0; size_t gpu_live_textures = 0; size_t gpu_live_meshes = 0; }; ``` *** ## Events | Code | Meaning | | - | - | | `0` | License success | | `1` | License failed | | `100` | Init complete | | `101` | Init failed | ```cpp theme={null} struct EngineCallbacks { std::function on_engine_event; }; ``` *** ## Image ```cpp theme={null} enum class Format { I420, NV12, NV21, BGRA, RGBA, BGR, RGB, Texture }; enum class Rotation { Rotation_0, Rotation_90, Rotation_180, Rotation_270 }; enum class FrameType { Image = 0, Video = 1 }; ``` **Factories:** `CreateWithFile`, `Create`, `CreateWithRGBA/BGRA/RGB/BGR`, `CreateWithI420/NV12/NV21`, `CreateWithTexture`. **Ops:** `Rotate`, `Mirror(MirrorMode::Horizontal|Vertical|Both)`, `SetMirror`, `Convert`, `ToFile`. `Rotate`, `Mirror`, and `SetMirror` change CPU pixel frames only (RGBA, RGB, YUV, and image files). They do not transform an OpenGL texture. Supply a texture that is already upright. **Accessors:** `Width/Height/Stride/Size/GetFormat/Data`, YUV planes, `Texture()`. Field: `FrameType type`. *** ## Error codes | Code | Meaning | | - | - | | `0` | OK | | `-1` | Invalid argument | | `-2` | Not initialized | | `-3` | License | | `-4` | Unsupported | | `-5` | I/O | | `-6` | Process | | `-7` | Out of memory | Serialize `ProcessImage` on one thread. Pixel `Data()` pointers are read-only. # Best Practices Source: https://docs.facebetter.net/linux/best-practices Performance and integration guidance for Facebetter 2.0 on Linux > [!NOTE] > > SDK **2.0.0**. C++ API is shared with Windows. Enums: [Parameter enums](/intro/makeup). ## Point `resource_path` at `resource.fbd` Pass the **file**, not a directory: ```cpp theme={null} cfg.resource_path = "/opt/facebetter/resource.fbd"; ``` Resolve an absolute path at startup so cwd changes do not break `fopen`. ## One engine, serial `ProcessImage` `Create` returns one engine for the session, not a process-wide singleton. `ImageFrame` and the engine are not thread-safe. Serialize `ProcessImage` and mutating setters on one thread. * Create the engine and call process on the thread whose GL context is current. Input and output textures must belong to that context. CPU frames do not need a caller GL context. There is no context flag on the config. ## `FrameType` on the frame | Value | Use | | - | - | | `FrameType::Video` (default) | Camera / live | | `FrameType::Image` | Still export | ## Large stills (preview vs export) Do not feed full-resolution pixels into `ProcessImage` on every slider change, and do not throw the original away after scaling. When the photo opens, keep the full buffer and build **one** preview frame (long edge about 1280–1440). Slider changes process the preview (`FrameType::Image`). Export processes a full-resolution frame with the same setters. Output size matches the input. Camera preview stays capture resolution + `FrameType::Video`. ```cpp theme={null} preview->type = FrameType::Image; auto preview_out = engine->ProcessImage(preview); full->type = FrameType::Image; auto export_out = engine->ProcessImage(full); ``` ## Intensities and skin-only Realtime: start around `0.15–0.3`. Reshape is `[-1.0, 1.0]`. Use `SetBeautySkinOnly(true)` so smoothing stays on skin. ## Filters and stickers `.fbd` path or bytes. Takes effect on the next `ProcessImage`. Do not swap assets every frame. ## `GetStats` ```cpp theme={null} EngineStats s = engine->GetStats(); if (s.avg_process_time_ms > 33.0) { // lower resolution or drop stickers / virtual background } ``` ## Shared library * Development: `LD_LIBRARY_PATH` * Shipping: `RPATH` / `RUNPATH`, or install to `/usr/local/lib` + `ldconfig` * Keep `libfacebetter.so` and headers from the **same** SDK build (`./scripts/build_linux.sh` or the download zip) ## OpenGL * Create the engine and call process on the thread whose GL context is current. Input and output textures must belong to that context. CPU frames do not need a caller GL context. There is no context flag on the config. ## Pause when idle Skip `ProcessImage` when the window is unmapped. `engine.reset()` when the session ends. ## Auth `license_token` for offline hosts; otherwise `app_id` + `app_key` online v2. Load secrets from env/config, not source. See [Auth & License](/intro/license). # Error Handling Source: https://docs.facebetter.net/linux/error-handling Beauty Effect SDK 2.0 error codes and Linux troubleshooting > [!NOTE] > > SDK **2.0.0**. Auth: [Auth & License](/intro/license). ## Return values | Code | Meaning | | - | - | | `0` | Success | | `-1` | Invalid argument | | `-2` | Not initialized | | `-3` | License | | `-4` | Unsupported | | `-5` | I/O | | `-6` | Process failed | | `-7` | Out of memory | `Create()` returns `nullptr` on failure. `ProcessImage` may return `nullptr`. ```cpp theme={null} int ret = engine->SetSmoothing(0.5f); if (ret != 0) { std::cerr << "SetSmoothing failed: " << ret << std::endl; } ``` ## Engine events | Code | Meaning | | - | - | | `0` | License success | | `1` | License failed | | `100` | Init complete | | `101` | Init failed | ```cpp theme={null} EngineCallbacks cbs; cbs.on_engine_event = [](int code, const std::string& message) { if (code == 1 || code == 101) { std::cerr << "engine event " << code << ": " << message << std::endl; } }; engine->SetCallbacks(cbs); ``` *** ## Common failures ### 1. `Create` returns `nullptr` * `resource_path` is not the **`resource.fbd` file** * Invalid `license_token` or `app_id` + `app_key` * Online auth cannot reach `/facebetter/v2/auth` * `libfacebetter.so` version mismatch ```cpp theme={null} LogConfig log_cfg; log_cfg.console_enabled = true; log_cfg.level = LogLevel::Debug; BeautyEffectEngine::SetLogConfig(log_cfg); cfg.resource_path = (std::filesystem::current_path() / "resource" / "resource.fbd").string(); auto engine = BeautyEffectEngine::Create(cfg); ``` *** ### 2. `libfacebetter.so` not found ``` error while loading shared libraries: libfacebetter.so: cannot open shared object file ``` ```bash theme={null} LD_LIBRARY_PATH=/path/to/sdk/lib ./your_app cp /path/to/sdk/lib/libfacebetter.so ./ echo "/path/to/sdk/lib" | sudo tee /etc/ld.so.conf.d/facebetter.conf sudo ldconfig ``` You can also set `RPATH` at link time (`-Wl,-rpath,/path/to/sdk/lib`). *** ### 3. `ProcessImage` returns `nullptr` ```cpp theme={null} auto input = ImageFrame::CreateWithFile("input.jpg"); if (!input || !input->Data()) return; input->type = FrameType::Image; auto output = engine->ProcessImage(input); if (!output || !output->Data()) { std::cerr << "ProcessImage failed." << std::endl; } ``` *** ### 4. Effects look unchanged No `SetBeautyTypeEnabled` in 2.0. Set intensities `> 0`. Reshape / makeup need a face. ```cpp theme={null} engine->SetSmoothing(0.5f); engine->SetReshape(Reshape::FaceThin, 0.3f); input->type = FrameType::Video; ``` *** ### 5. GLFW cannot open the display ``` GLFW: X11: Display variable not set ``` ```bash theme={null} echo $DISPLAY export DISPLAY=:0 export WAYLAND_DISPLAY=wayland-0 ``` SSH needs X11 forwarding (`ssh -X`) or a local compositor. *** ### 6. OpenGL init fails ```bash theme={null} # Ubuntu / Debian sudo apt install libgl1-mesa-dev libglu1-mesa-dev mesa-utils glxinfo | grep "OpenGL version" ``` * Create the engine and call process on the thread whose GL context is current. Input and output textures must belong to that context. CPU frames do not need a caller GL context. There is no context flag on the config. *** ## Debug logs ```cpp theme={null} LogConfig log_cfg; log_cfg.console_enabled = true; log_cfg.file_enabled = true; log_cfg.level = LogLevel::Debug; log_cfg.file_name = "facebetter.log"; BeautyEffectEngine::SetLogConfig(log_cfg); ``` # FAQ Source: https://docs.facebetter.net/linux/faq Linux Beauty Effect SDK 2.0 integration FAQ > [!NOTE] > > SDK **2.0.0**. Shared C++ API with Windows. [Parameter enums](/intro/makeup) · [Auth & License](/intro/license). ## Integration ### Engine `Create` returns `nullptr` * `resource_path` must be the **`resource.fbd` file** * Set `license_token` **or** valid `app_id` + `app_key` * Call `SetLogConfig` before `Create` * Confirm `libfacebetter.so` is loadable (`ldd your_app`) ### How do I build the SDK? ```bash theme={null} ./scripts/build_linux.sh ``` Installs to `build/linux/release`. Or CMake + Ninja from a `build/` directory. The desktop demo lives in `demo/cpp`. ### Header / link errors Add SDK `include/` to the include path. Link `libfacebetter.so`. Set `LD_LIBRARY_PATH` or rpath at runtime. ### `SetRenderView` is missing The SDK has no `SetRenderView`. Draw the `ProcessImage` output in your own view. ## Effects ### Beauty looks weak or off No `SetBeautyTypeEnabled`. Intensities default to `0`. Reshape / makeup need a face. Use `FrameType::Video` for camera. ### Reshape looks inverted Range is `[-1.0, 1.0]`. See [Parameter enums](/intro/makeup). ### Filter / sticker does nothing Pass a `.fbd` path or bytes to `SetFilter` / `SetSticker`. ### Virtual background / chroma key `SetVirtualBackgroundBlur` / `SetVirtualBackground(path|bytes)` / `ClearVirtualBackground`. Chroma: `SetChromaKey` + similarity / smoothness / desaturation; `ClearChromaKey()` restores segmentation. ## Runtime ### `libfacebetter.so: cannot open shared object file` `LD_LIBRARY_PATH`, copy next to the binary, rpath, or `ldconfig`. ### No display / GLFW X11 error Graphical session, `DISPLAY=:0`, or Wayland. SSH needs `ssh -X`. ### CMake cannot find OpenGL Install `libgl1-mesa-dev` / `mesa-libGL-devel` and reconfigure. ### Headless server * Create the engine and call process on the thread whose GL context is current. Input and output textures must belong to that context. CPU frames do not need a caller GL context. There is no context flag on the config. ## Auth If `license_token` is non-empty it wins (token / `{token}` JSON / `.lic`). Else online v2 with `app_id` + `app_key`. Events: `0` / `1` / `100` / `101`. See [Auth & License](/intro/license). ## Version Document and ship **2.0.0**. GCC 7+ / Clang 5+, C++17, OpenGL 3.0+. # Implement Beauty Source: https://docs.facebetter.net/linux/implement-beauty Integrate Beauty Effect SDK 2.0 on Linux with the C++ API > [!NOTE] > > SDK **2.0.0**. Same C++ API as Windows (`facebetter` namespace). Enums: [Parameter enums](/intro/makeup). Auth: [Auth & License](/intro/license). On Linux, Facebetter is `libfacebetter.so` plus `facebetter/*.h`. This guide follows the [C++ desktop demo](https://github.com/pixpark/facebetter-sdk) (`demo/cpp`). To compile the SDK itself, use `./scripts/build_linux.sh` or CMake in `build/linux`. ## Include headers ```cpp theme={null} #include #include #include #include using namespace facebetter; using namespace facebetter::beauty_params; ``` ## CMake linkage ```cmake theme={null} target_include_directories(your_target PRIVATE /path/to/sdk/include) target_link_libraries(your_target PRIVATE /path/to/sdk/lib/libfacebetter.so GL ) ``` At runtime, set `LD_LIBRARY_PATH`, copy `libfacebetter.so` next to the binary, or install with `ldconfig`. ## Integration flow ``` SetLogConfig → Create(EngineConfig) → set effects → ProcessImage → render ``` There is no type-enable step. Intensity `0` turns an effect off. *** ## 1. Configure logging (optional) Call **before** `Create`. ```cpp theme={null} LogConfig log_cfg; log_cfg.console_enabled = true; log_cfg.file_enabled = false; log_cfg.level = LogLevel::Info; BeautyEffectEngine::SetLogConfig(log_cfg); ``` *** ## 2. Create the engine Desktop **must** set `resource_path` to the `resource.fbd` **file**. **Auth priority:** non-empty `license_token` (token / `{token}` JSON / `.lic`) wins; otherwise `app_id` + `app_key` online v2. ```cpp theme={null} EngineConfig cfg; cfg.app_id = "your_app_id"; cfg.app_key = "your_app_key"; cfg.resource_path = "resource/resource.fbd"; // path to the .fbd file // cfg.license_token = "/* license token, {token} JSON, or .lic contents */"; auto engine = BeautyEffectEngine::Create(cfg); if (!engine) { return -1; } ``` > [!WARNING] > > `resource_path` must be the `resource.fbd` file, not a folder. Prefer an absolute path in production. *** ## 3. Set beauty parameters Skin / makeup / body reshape `[0.0, 1.0]`. Face reshape **`[-1.0, 1.0]`**. Body reshape needs `resource_body.fbd`. Full enums: [Parameter enums](/intro/makeup). Packs: [Optional resource packs](/intro/resource-packs). ```cpp theme={null} engine->SetSmoothing(0.5f); engine->SetSmoothingStyle(SmoothingStyle::Natural); engine->SetWhitening(0.3f); engine->SetWhiteningStyle(WhiteningStyle::ColdWhite); engine->SetRosiness(0.2f); engine->SetBeautySkinOnly(true); engine->SetReshape(Reshape::FaceThin, 0.4f); engine->SetReshape(Reshape::EyeSize, 0.3f); engine->AddResourcePack("resource/resource_body.fbd"); // or place resource_body.fbd next to resource.fbd engine->SetBodyReshape(BodyReshape::WaistSlim, 0.4f); engine->SetBodyReshape(BodyReshape::LegStretch, 0.3f); engine->SetBodyReshape(BodyReshape::TorsoLong, 0.3f); engine->SetLipstick(0.6f); engine->SetLipstickColor(LipstickColor::Rouge); engine->SetBlush(0.4f); engine->SetBlushStyle(BlushStyle::SunKissed); engine->SetBlushColor(BlushColor::CoralPink); engine->SetContour(0.5f); engine->SetContourStyle(ContourStyle::Natural); ``` Same pattern for eyeshadow, eyeliner, eyebrow, eyelash, and pupil. *** ## 4. Filters, stickers, and virtual background Pass a **path** or **bytes**. ```cpp theme={null} engine->SetFilter("assets/filters/natural.fbd"); engine->SetFilterIntensity(0.8f); engine->ClearFilter(); engine->SetSticker("assets/stickers/face/black_glass.fbd"); engine->ClearSticker(); engine->AddResourcePack("resource/resource_3d.fbd"); // or place it next to resource.fbd engine->Set3DSticker("assets/stickers/3d/oculos.fbd"); engine->Clear3DSticker(); engine->SetVirtualBackgroundBlur(0.6f); engine->SetVirtualBackground("assets/background.jpg"); engine->ClearVirtualBackground(); engine->SetChromaKey(ChromaKeyColor::Green); engine->SetChromaKeySimilarity(0.4f); engine->ClearChromaKey(); ``` *** ## 5. Callbacks and stats ```cpp theme={null} EngineCallbacks cbs; cbs.on_engine_event = [](int code, const std::string& message) { // 0 license OK, 1 failed, 100 init complete, 101 init failed printf("[event] %d %s\n", code, message.c_str()); }; engine->SetCallbacks(cbs); EngineStats stats = engine->GetStats(); ``` *** ## 6. Process frames Set `ImageFrame::type`. ```cpp theme={null} auto input = ImageFrame::CreateWithRGBA(rgba_data, width, height, stride); input->type = FrameType::Video; auto output = engine->ProcessImage(input); ``` Photo: ```cpp theme={null} auto input = ImageFrame::CreateWithFile("input.jpg"); input->type = FrameType::Image; auto output = engine->ProcessImage(input); output->ToFile("output.jpg", 95); ``` > [!TIP] > > Output format tracks input when possible. Convert with `output->Convert(Format::BGRA)`. ### OpenGL preview ```cpp theme={null} glBindTexture(GL_TEXTURE_2D, tex); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, output->Width(), output->Height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, output->Data()); ``` * Create the engine and call process on the thread whose GL context is current. Input and output textures must belong to that context. CPU frames do not need a caller GL context. There is no context flag on the config. *** ## 7. Minimal loop ```cpp theme={null} LogConfig log_cfg; log_cfg.console_enabled = true; log_cfg.level = LogLevel::Info; BeautyEffectEngine::SetLogConfig(log_cfg); EngineConfig cfg; cfg.app_id = "your_app_id"; cfg.app_key = "your_app_key"; cfg.resource_path = "resource/resource.fbd"; auto engine = BeautyEffectEngine::Create(cfg); if (!engine) return -1; engine->SetSmoothing(0.5f); engine->SetReshape(Reshape::FaceThin, 0.3f); engine->SetLipstick(0.5f); auto input = ImageFrame::CreateWithRGBA(rgba, width, height, stride); input->type = FrameType::Video; auto output = engine->ProcessImage(input); ``` Release with `engine.reset()`. The engine is **not** a singleton. For TRTC / Agora / LiveKit: [Third-party Integration](/linux/third-party-integration). ## Related > **[Third-party Integration](/linux/third-party-integration)** > > TRTC / Agora / LiveKit > **[API reference](/linux/api-reference)** > > C++ methods and Linux notes > **[Error handling](/linux/error-handling)** > > Return codes and .so / DISPLAY issues > **[Best practices](/linux/best-practices)** > > Performance and rpath # Quick Start Source: https://docs.facebetter.net/linux/quick-start Build and run the Facebetter C++ desktop demo on Linux (GLFW + ImGui) > [!NOTE] > > This page matches SDK **2.0.0**. Linux and Windows share the same C++ API in the `facebetter` namespace (`facebetter/*.h`). This guide builds the Facebetter C++ desktop demo on Linux. The demo uses **GLFW + Dear ImGui + OpenGL 3**: live preview on the left, beauty controls on the right. ## Requirements | Tool | Version | | - | - | | OS (prebuilt SDK zip) | Officially **Ubuntu 22.04+** (**glibc ≥ 2.35**; CI builds on Ubuntu 22.04). Other distros are not guaranteed. | | GCC or Clang | C++17 (GCC 7+ / Clang 5+) | | CMake | 3.16+ | | Ninja | `apt install ninja-build` / `dnf install ninja-build` | | OpenGL | `libgl1-mesa-dev` (Ubuntu/Debian) or `mesa-libGL-devel` (Fedora/RHEL) | | X11 / Wayland | GLFW dependencies (see below) | ### Ubuntu / Debian ```bash theme={null} sudo apt update sudo apt install -y build-essential cmake ninja-build \ libgl1-mesa-dev libglu1-mesa-dev \ libx11-dev libxrandr-dev libxinerama-dev \ libxcursor-dev libxi-dev ``` ### Fedora / RHEL ```bash theme={null} sudo dnf install -y gcc-c++ cmake ninja-build \ mesa-libGL-devel mesa-libGLU-devel \ libX11-devel libXrandr-devel libXinerama-devel \ libXcursor-devel libXi-devel ``` ## Step 1: Clone the repository ```bash theme={null} git clone https://github.com/pixpark/facebetter-sdk.git cd facebetter-sdk ``` ## Step 2: Place the SDK files Put the Linux SDK under `demo/cpp/sdk/`: ``` demo/cpp/sdk/ ├── include/ │ └── facebetter/ │ ├── beauty_effect_engine.h │ ├── beauty_params.h │ ├── image_frame.h │ └── type_defines.h ├── lib/ │ └── libfacebetter.so ← shared library └── resource/ ├── resource.fbd ← models and assets (required) ├── resource_3d.fbd ← optional; 3D stickers. Place next to `resource.fbd` or call `AddResourcePack` └── resource_body.fbd ← optional; body reshape. Place next to `resource.fbd` or call `AddResourcePack` ``` > [!WARNING] > > On desktop, `EngineConfig::resource_path` must point to the **`resource.fbd` file**, not a directory. Example: `demo/cpp/sdk/resource/resource.fbd`. > [!TIP] > > SDK packages are on the [Download](https://facebetter.net/download) page and in the [Dashboard](https://facebetter.net/dashboard). To **build the SDK from source** instead of a prebuilt package: ```bash theme={null} ./scripts/build_linux.sh ``` Output installs under `build/linux/release`. You can copy `include/`, `lib/libfacebetter.so`, and `resource.fbd` into `demo/cpp/sdk/` as above. ## Step 3: Configure license Set `app_id` / `app_key` (online v2 auth) or `license_token` before you run. If `license_token` is non-empty, it takes priority (license token string, `{token}` JSON, or offline `.lic` contents). Details: [Auth & License](/intro/license). ## Step 4: Build the demo ```bash theme={null} cd demo/cpp cmake -B build -G "Ninja" -DCMAKE_BUILD_TYPE=Release cmake --build build ``` CMake typically copies `resource/resource.fbd` (and `demo.png` if present) into `build/resource/`. ## Step 5: Prepare a preview image (optional) ``` demo/cpp/demo.png ``` ## Step 6: Run ```bash theme={null} cd demo/cpp/build # Option A: runtime library path LD_LIBRARY_PATH=../sdk/lib ./facebetter_demo # Option B: copy the .so next to the binary cp ../sdk/lib/libfacebetter.so . ./facebetter_demo ``` The window shows a live preview and a control panel (skin, 26 face-reshape params, 7 body-reshape params, makeup, filter, sticker, virtual background). Click **Reset All** to zero intensities. ## Troubleshooting **Q: `libfacebetter.so: cannot open shared object file`**\ A: Use `LD_LIBRARY_PATH=../sdk/lib ./facebetter_demo`, copy the `.so` next to the binary, or add the path with `ldconfig`. **Q: Engine create returns `nullptr` / license failed**\ A: Point `resource_path` at `resource.fbd`, and set `license_token` or valid `app_id` + `app_key`. See [Auth & License](/intro/license). **Q: CMake cannot find OpenGL**\ A: Install `libgl1-mesa-dev` (Ubuntu) or `mesa-libGL-devel` (Fedora), then re-run CMake. **Q: `GLFW: X11: Display variable not set`**\ A: Run inside a graphical session, or set `DISPLAY` (X11) / `WAYLAND_DISPLAY` (Wayland). ## Next steps > **[Implement beauty](/linux/implement-beauty)** > > Create the engine, set effects, and process frames. > **[API reference](/linux/api-reference)** > > Full C++ API (same as Windows) plus Linux notes. # Third-party Integration Source: https://docs.facebetter.net/linux/third-party-integration Wire Facebetter beauty into TRTC, Agora, LiveKit, and other Linux video pipelines SDK **2.0.0**. Same C++ API and integration model as [Windows · Third-party Integration](/windows/third-party-integration): desktop vendors usually deliver **I420 / YUV buffers**, not mobile-style OpenGL texture callbacks. This page covers Linux-only differences. Shared helpers and TRTC / Agora / LiveKit wiring live on the Windows page — swap headers and library paths for the Linux package. ``` Third-party SDK (preprocess callback) I420 planes ↓ BeautyEffectEngine CreateWithI420 → ProcessImage → write back ``` ## Linux differences | Item | Notes | | - | - | | Library | `libfacebetter.so` + `facebetter/*.h` | | Link | See [Implement Beauty](/linux/implement-beauty); watch `LD_LIBRARY_PATH` / rpath at runtime | | GL | Create the engine and call process on the thread whose GL context is current. Input and output textures must belong to that context. CPU frames do not need a caller GL context. There is no context flag on the config. | | `resource_path` | Must point at the `resource.fbd` **file** | | Dashboard binding | Package / executable / process name — [Subscription](/intro/enable-service) | Create the engine: ```cpp theme={null} EngineConfig cfg; cfg.app_id = "your_app_id"; cfg.app_key = "your_app_key"; cfg.resource_path = "/opt/yourapp/resource/resource.fbd"; auto engine = BeautyEffectEngine::Create(cfg); ``` Shared I420 helper and vendor hooks: **full copy on [Windows · Third-party Integration](/windows/third-party-integration)** (`ProcessI420InPlace`, TRTC Buffer, Agora `IVideoFrameObserver`, LiveKit custom video source). ## Vendor snapshot | Vendor | Linux notes | | - | - | | **TRTC** | PC is **Buffer / I420** only — do not use the Android Texture path | | **Agora** | C++ `registerVideoFrameObserver`, ReadWrite + in-place I420 | | **LiveKit** | Custom video source; confirm capture + GL/software path for headless hosts | ## Troubleshooting | Symptom | Check | | - | - | | Missing `.so` | `LD_LIBRARY_PATH`, rpath, matching architecture | | `Create` fails | `.fbd` path, auth, headless GL / OSMesa | | Everything else | Same as [Windows troubleshooting](/windows/third-party-integration#troubleshooting) | ## Related * [Windows · Third-party Integration](/windows/third-party-integration) (primary) * [Implement Beauty](/linux/implement-beauty) * [Best Practices](/linux/best-practices) * [API Reference](/linux/api-reference) # API Reference Source: https://docs.facebetter.net/macos/api-reference macOS Objective-C API for Beauty Effect SDK 2.0 > [!NOTE] > > This page matches SDK **2.0.0**. Preset meanings: [Parameter enums](/intro/makeup). Auth: [Auth & License](/intro/license). iOS and macOS share this Objective-C API. macOS-only: `+[FBImageFrame createWithNSImage:]`. Minimum OS: **macOS 10.15**, architectures **x86\_64** and **arm64**. Use AppKit (`NSImage`) for stills. ## Logging ### `FBLogLevel` ```objc theme={null} typedef NS_ENUM(NSInteger, FBLogLevel) { FBLogLevel_Trace = 0, FBLogLevel_Debug, FBLogLevel_Info, FBLogLevel_Warn, FBLogLevel_Error, FBLogLevel_Critical, }; ``` ### `FBLogConfig` | Property | Type | Description | | - | - | - | | `consoleEnabled` | `BOOL` | Console output | | `fileEnabled` | `BOOL` | File output | | `level` | `FBLogLevel` | Minimum level | | `fileName` | `NSString *` | Log path (used when `fileEnabled` is `YES`) | ```objc theme={null} FB_OBJC_API @interface FBLogConfig : NSObject @property(nonatomic, assign) BOOL consoleEnabled; @property(nonatomic, assign) BOOL fileEnabled; @property(nonatomic, assign) FBLogLevel level; @property(nonatomic, copy, nullable) NSString *fileName; - (instancetype)init; @end ``` Call `+[FBBeautyEffectEngine setLogConfig:]` **before** `createEngineWithConfig:`. Returns `FBErrorCode` (`0` success, `-1` if `config` is nil). ## Engine configuration ### `FBEngineConfig` | Property | Type | Description | | - | - | - | | `appId` | `NSString *` | Dashboard App ID (online auth) | | `appKey` | `NSString *` | Dashboard App Key (online auth) | | `licenseToken` | `NSString *` | License token string, `{token}` JSON, or native `.lic` contents | **Auth priority:** if `licenseToken` is non-empty, validate that token locally and skip `/facebetter/v2/auth`. Otherwise use `appId` + `appKey` for online auth. Bind the app **Bundle ID** in the Dashboard. Command-line tools without a bundle should bind the process name. ```objc theme={null} FB_OBJC_API @interface FBEngineConfig : NSObject @property(nonatomic, copy) NSString *appId; @property(nonatomic, copy) NSString *appKey; @property(nonatomic, copy, nullable) NSString *licenseToken; - (instancetype)init; @end ``` ### `FBFrameType` Set on `FBImageFrame.type` before `processImage:`. Not a method argument. ```objc theme={null} typedef NS_ENUM(NSInteger, FBFrameType) { FBFrameTypeImage = 0, // stills / NSImage FBFrameTypeVideo = 1 // live / camera }; ``` ## `FBBeautyEffectEngine` ```objc theme={null} FB_OBJC_API @interface FBBeautyEffectEngine : NSObject + (int)setLogConfig:(FBLogConfig *)config; + (instancetype)createEngineWithConfig:(FBEngineConfig *)config; - (int)setSmoothing:(float)intensity; - (int)setSmoothingStyle:(FBSmoothingStyle)style; - (int)setWhitening:(float)intensity; - (int)setWhiteningStyle:(FBWhiteningStyle)style; - (int)setRosiness:(float)intensity; - (int)setBrightness:(float)intensity; - (int)setContrast:(float)intensity; - (int)setSaturation:(float)intensity; - (int)setColorTemperature:(float)intensity; - (int)setColorTint:(float)intensity; - (int)setClarity:(float)intensity; - (int)setReshape:(FBReshape)param intensity:(float)value; - (int)setBodyReshape:(FBBodyReshape)param intensity:(float)value; - (int)setBeautySkinOnly:(BOOL)enabled; - (int)setLipstick:(float)intensity; - (int)setLipstickColor:(FBLipstickColor)color; - (int)setBlush:(float)intensity; - (int)setBlushStyle:(FBBlushStyle)style; - (int)setBlushColor:(FBBlushColor)color; - (int)setContour:(float)intensity; - (int)setContourStyle:(FBContourStyle)style; - (int)setEyeShadow:(float)intensity; - (int)setEyeShadowStyle:(FBEyeShadowStyle)style; - (int)setEyeShadowColor:(FBEyeShadowColor)color; - (int)setEyeLiner:(float)intensity; - (int)setEyeLinerStyle:(FBEyeLinerStyle)style; - (int)setEyeLinerColor:(FBEyeLinerColor)color; - (int)setEyebrow:(float)intensity; - (int)setEyebrowStyle:(FBEyebrowStyle)style; - (int)setEyebrowColor:(FBEyebrowColor)color; - (int)setEyelash:(float)intensity; - (int)setEyelashStyle:(FBEyelashStyle)style; - (int)setEyelashColor:(FBEyelashColor)color; - (int)setPupil:(float)intensity; - (int)setPupilColor:(FBPupilColor)color; - (int)setTeethWhiten:(float)intensity; - (int)setChromaKey:(FBChromaKeyColor)color; - (int)clearChromaKey; - (int)setChromaKeySimilarity:(float)value; - (int)setChromaKeySmoothness:(float)value; - (int)setChromaKeyDesaturation:(float)value; - (int)setVirtualBackgroundBlur:(float)level; - (int)setVirtualBackground:(NSString *)imagePath; - (int)setVirtualBackgroundWithData:(NSData *)imageData; - (int)clearVirtualBackground; - (int)setFilter:(NSString *)fbdFilePath; - (int)setFilterWithData:(NSData *)fbdData; - (int)clearFilter; - (int)setFilterIntensity:(float)intensity; - (int)setSticker:(NSString *)fbdFilePath; - (int)setStickerWithData:(NSData *)fbdData; - (int)clearSticker; - (int)addResourcePack:(NSString *)fbdFilePath; - (int)addResourcePackWithData:(NSData *)fbdData; - (int)set3DSticker:(NSString *)resource; - (int)set3DStickerWithData:(NSData *)fbdData; - (int)clear3DSticker; - (FBEngineStats *)getStats; - (int)setCallbacks:(FBEngineCallbacks *)callbacks; - (FBImageFrame * _Nullable)processImage:(FBImageFrame *)imageFrame; @end ``` `createEngineWithConfig:` returns `nil` on failure. Integer methods return `FBErrorCode` (`0` = success). ### Skin | Method | Range / notes | | - | - | | `setSmoothing:` | `[0, 1]` intensity | | `setSmoothingStyle:` | Style; intensity still from `setSmoothing:` | | `setWhitening:` | `[0, 1]` | | `setWhiteningStyle:` | Swaps the whitening LUT | | `setRosiness:` | `[0, 1]` | | `setBrightness:` | `[-1, 1]`, `0` neutral | | `setContrast:` | `[-1, 1]`, `0` neutral | | `setSaturation:` | `[-1, 1]`, `0` neutral | | `setColorTemperature:` | `[-1, 1]`, `0` neutral | | `setColorTint:` | `[-1, 1]`, `0` neutral | | `setClarity:` | `[0, 1]` | | `setBeautySkinOnly:` | `YES` = skin regions only | ### Reshape `setReshape:intensity:` — intensity **`[-1.0, 1.0]`**, `0` off. `FBReshape` values `0`–`25`: `FBReshape_FaceThin` … `FBReshape_BrowThickness`. Directions: [Parameter enums](/intro/makeup). ```objc theme={null} typedef NS_ENUM(NSInteger, FBReshape) { FBReshape_FaceThin = 0, FBReshape_FaceVShape = 1, FBReshape_FaceNarrow = 2, FBReshape_FaceShort = 3, FBReshape_Cheekbone = 4, FBReshape_Jawbone = 5, FBReshape_Chin = 6, FBReshape_NoseSlim = 7, FBReshape_EyeSize = 8, FBReshape_EyeDistance = 9, FBReshape_FaceSmall = 10, FBReshape_Forehead = 11, FBReshape_NoseLong = 12, FBReshape_Philtrum = 13, FBReshape_MouthSize = 14, FBReshape_MouthPosition = 15, FBReshape_MouthSmile = 16, FBReshape_LipThickness = 17, FBReshape_EyeRound = 18, FBReshape_EyePosition = 19, FBReshape_EyeAngle = 20, FBReshape_EyeCornerOpen = 21, FBReshape_LowerEyelid = 22, FBReshape_BrowPosition = 23, FBReshape_BrowDistance = 24, FBReshape_BrowThickness = 25, }; ``` ### Body reshape `setBodyReshape:intensity:` — intensity **`[0.0, 1.0]`**, `0` off. Requires `resource_body.fbd` via `addResourcePack:` first. `FBBodyReshape` values `0`–`8`. See [Parameter enums](/intro/makeup) and [Optional resource packs](/intro/resource-packs). ```objc theme={null} typedef NS_ENUM(NSInteger, FBBodyReshape) { FBBodyReshape_BodySlim = 0, FBBodyReshape_WaistSlim = 1, FBBodyReshape_LegSlim = 2, FBBodyReshape_ShoulderSlim = 3, FBBodyReshape_ArmSlim = 4, FBBodyReshape_LegLong = 5, FBBodyReshape_BustEnhance = 6, FBBodyReshape_LegStretch = 7, FBBodyReshape_TorsoLong = 8, }; ``` `FBSmoothingStyle`: `Natural`, `Texture`, `Smooth`. `FBWhiteningStyle`: `ColdWhite`, `PinkWhite`, `WarmWhite`, `Wheat`, `Tan`. ### Makeup Intensity methods take `[0, 1]`. Shape / color types: [Parameter enums](/intro/makeup). | Intensity | Style | Color | | - | - | - | | `setLipstick:` | — | `setLipstickColor:` | | `setBlush:` | `setBlushStyle:` | `setBlushColor:` | | `setContour:` | `setContourStyle:` | — | | `setEyeShadow:` | `setEyeShadowStyle:` | `setEyeShadowColor:` | | `setEyeLiner:` | `setEyeLinerStyle:` | `setEyeLinerColor:` | | `setEyebrow:` | `setEyebrowStyle:` | `setEyebrowColor:` | | `setEyelash:` | `setEyelashStyle:` | `setEyelashColor:` | | `setPupil:` | — | `setPupilColor:` | | `setTeethWhiten:` | — | — | ### Virtual background and chroma key | Method | Description | | - | - | | `setChromaKey:` | Mask from green / blue / red. Fill is still blur or image. | | `clearChromaKey` | Restore portrait-segmentation mask; does **not** clear fill | | `setChromaKeySimilarity:` | Key tightness `[0, 1]` | | `setChromaKeySmoothness:` | Edge feather `[0, 1]` | | `setChromaKeyDesaturation:` | Spill suppression `[0, 1]` | | `setVirtualBackgroundBlur:` | Blur fill `[0, 1]`; `0` clears virtual background | | `setVirtualBackground:` | png/jpg file path (must be non-empty) | | `setVirtualBackgroundWithData:` | Encoded png/jpg `NSData` | | `clearVirtualBackground` | Clear blur and image fill | ```objc theme={null} typedef NS_ENUM(NSInteger, FBChromaKeyColor) { FBChromaKeyColor_Green = 0, FBChromaKeyColor_Blue, FBChromaKeyColor_Red, }; ``` ### Filters and stickers No register-by-id. Path or bytes; GPU resources are created on the next `processImage:`. | Method | Description | | - | - | | `setFilter:` | LUT from `.fbd` path | | `setFilterWithData:` | LUT from `.fbd` bytes | | `clearFilter` | Remove LUT | | `setFilterIntensity:` | `[0, 1]` | | `setSticker:` | 2D sticker `.fbd` path | | `setStickerWithData:` | Sticker bytes | | `addResourcePack:` | Extra capability pack path (`resource_3d.fbd` before `set3DSticker:`, or `resource_body.fbd` before `setBodyReshape:`) | | `addResourcePackWithData:` | Extra pack bytes | | `set3DSticker:` | 3D sticker `.fbd` path | | `set3DStickerWithData:` | 3D sticker bytes | | `clear3DSticker` | Remove the 3D sticker | | `clearSticker` | Remove sticker | Empty path / nil or empty `NSData` → `FBErrorCode_InvalidArgument`. ### Process ```objc theme={null} - (FBImageFrame * _Nullable)processImage:(FBImageFrame *)imageFrame; ``` Reads `imageFrame.type`. Output format matches input. Returns `nil` on failure. ## Error codes ```objc theme={null} typedef NS_ENUM(NSInteger, FBErrorCode) { FBErrorCode_Success = 0, FBErrorCode_InvalidArgument = -1, FBErrorCode_NotInitialized = -2, FBErrorCode_License = -3, FBErrorCode_Unsupported = -4, FBErrorCode_IO = -5, FBErrorCode_Process = -6, FBErrorCode_OutOfMemory = -7, }; ``` `-1` is invalid argument. `-2` is not initialized. ## Stats and callbacks ### `FBEngineStats` | Property | Type | Description | | - | - | - | | `fps` | `double` | Frames per second | | `avgProcessTimeMs` | `double` | Average `processImage:` time (ms) | | `sessionTimeS` | `double` | Session duration (seconds) | | `gpuLiveTextures` | `NSUInteger` | Live GPU textures (leak debugging) | | `gpuLiveMeshes` | `NSUInteger` | Live GPU meshes (leak debugging) | ```objc theme={null} - (FBEngineStats *)getStats; ``` ### `FBEngineEventCode` | Value | Symbol | | - | - | | `0` | `FBEngineEventCodeLicenseValidationSuccess` | | `1` | `FBEngineEventCodeLicenseValidationFailed` | | `100` | `FBEngineEventCodeInitializationComplete` | | `101` | `FBEngineEventCodeInitializationFailed` | ### `FBEngineCallbacks` ```objc theme={null} FB_OBJC_API @interface FBEngineCallbacks : NSObject @property(nonatomic, copy, nullable) void (^onEngineEvent) (FBEngineEventCode code, NSString * _Nullable message); @end ``` ## `FBImageFrame` ### Create | Method | Notes | | - | - | | `createWithData:width:height:format:` | Raw buffer + `FBImageFormat` | | `createWithRGBA:width:height:stride:` | | | `createWithBGRA:width:height:stride:` | Common for AppKit bitmaps | | `createWithRGB:width:height:stride:` | | | `createWithBGR:width:height:stride:` | | | `createWithI420:...` | Y / U / V planes | | `createWithNV12:...` | Y + UV | | `createWithNV21:...` | Y + VU | | `createWithFile:` | png / jpg path | | `createWithTexture:width:height:stride:` | `GL_TEXTURE_2D` in the current context | | `setGlRenderTarget:` | Optional `GL_TEXTURE_2D` render target on the current context. Borrowed | | `setMetalRenderTarget:` | Optional `MTLTexture` output on the same device. Borrowed | | `createWithNSImage:` | **macOS only** | ### Operations | Method | Description | | - | - | | `rotate:` | `FBImageRotation`; returns `FBErrorCode` | | `mirror:` | `FBMirrorModeHorizontal` / `Vertical` / `Both`; mutates pixels. `None` is a no-op | | `setMirror:` | Flag for `processImage:`. `FBMirrorModeNone` clears | | `convert:` | Returns a new frame in the target `FBImageFormat` | | `toFile:quality:` | quality `0`–`100` | | `toFile:` | quality `90` | `rotate:`, `mirror:`, and `setMirror:` change CPU pixel frames only (RGBA, RGB, YUV, and image files). They do not transform an OpenGL texture, a CVPixelBuffer, or a Metal texture. Supply those already upright. Accessors: `width`, `height`, `stride`, `size`, `type`, `data`, `format`, `texture`. YUV: `dataY` / `dataU` / `dataV` / `dataUV` and matching strides. ```objc theme={null} typedef NS_ENUM(NSInteger, FBImageFormat) { FBImageFormatI420, FBImageFormatNV12, FBImageFormatNV21, FBImageFormatBGRA, FBImageFormatRGBA, FBImageFormatBGR, FBImageFormatRGB, FBImageFormatTexture, }; typedef NS_ENUM(NSInteger, FBImageRotation) { FBImageRotation0, FBImageRotation90, FBImageRotation180, FBImageRotation270, }; ``` ```objc theme={null} FBImageFrame *frame = [FBImageFrame createWithNSImage:image]; frame.type = FBFrameTypeImage; FBImageFrame *out = [engine processImage:frame]; ``` ## Makeup / style enums Objective-C symbols live in `FBBeautyParams.h`. Do not duplicate meaning tables here — see [Parameter enums](/intro/makeup). * `FBSmoothingStyle`, `FBWhiteningStyle` * `FBLipstickColor` * `FBBlushStyle`, `FBBlushColor` * `FBContourStyle` * `FBEyeShadowStyle`, `FBEyeShadowColor` * `FBEyeLinerStyle`, `FBEyeLinerColor` * `FBEyebrowStyle`, `FBEyebrowColor` * `FBEyelashStyle`, `FBEyelashColor` * `FBPupilColor` # Best Practices Source: https://docs.facebetter.net/macos/best-practices macOS Beauty Effect SDK 2.0 performance and architecture > [!NOTE] > > This page matches SDK **2.0.0**. Makeup / reshape enums: [Parameter enums](/intro/makeup). ## Choose the right frame type Set `FBImageFrame.type` **before** `processImage:`. There is no process-mode argument on the engine. * **`FBFrameTypeVideo` (`1`)**: camera preview, live, calls — lower latency. * **`FBFrameTypeImage` (`0`)**: still photos / `NSImage` — higher quality. ```objc theme={null} input.type = FBFrameTypeVideo; FBImageFrame *output = [engine processImage:input]; ``` ## Large stills (preview vs export) Do not feed full-resolution pixels into `processImage:` on every slider change, and do not throw the original away after scaling. When the photo opens, keep the full `NSImage` and build **one** preview frame (long edge about 1280–1440, `createWithNSImage:`). Slider changes process the preview (`FBFrameTypeImage`). Export processes a full-resolution frame with the same setters. Output size matches the input. Camera preview stays capture resolution + `FBFrameTypeVideo`. ```objc theme={null} preview.type = FBFrameTypeImage; FBImageFrame *previewOut = [engine processImage:preview]; full.type = FBFrameTypeImage; FBImageFrame *exportOut = [engine processImage:full]; ``` ## Parameter ranges * Skin / makeup / filter intensity: `[0.0, 1.0]`. `0` turns that effect off. * Reshape (`setReshape:intensity:`): **`[-1.0, 1.0]`**. `0` is off. Positive and negative are opposite directions. Start low on live video. Full enum meanings: [Parameter enums](/intro/makeup). ```objc theme={null} [engine setSmoothing:0.25f]; [engine setSmoothingStyle:FBSmoothingStyle_Natural]; [engine setWhitening:0.15f]; [engine setReshape:FBReshape_FaceThin intensity:0.12f]; [engine setBeautySkinOnly:YES]; ``` ## One engine, one serial queue ```objc theme={null} @interface BeautyEngineManager : NSObject @property (nonatomic, strong, readonly) FBBeautyEffectEngine *engine; @property (nonatomic, strong, readonly) dispatch_queue_t queue; + (instancetype)sharedManager; @end @implementation BeautyEngineManager + (instancetype)sharedManager { static BeautyEngineManager *instance; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ instance = [[BeautyEngineManager alloc] init]; }); return instance; } - (instancetype)init { self = [super init]; if (self) { _queue = dispatch_queue_create("com.facebetter.process", DISPATCH_QUEUE_SERIAL); FBEngineConfig *config = [[FBEngineConfig alloc] init]; config.appId = @"your_app_id"; config.appKey = @"your_app_key"; _engine = [FBBeautyEffectEngine createEngineWithConfig:config]; } return self; } - (void)process:(FBImageFrame *)input completion:(void (^)(FBImageFrame * _Nullable))completion { dispatch_async(self.queue, ^{ input.type = FBFrameTypeVideo; FBImageFrame *output = [self.engine processImage:input]; dispatch_async(dispatch_get_main_queue(), ^{ completion(output); }); }); } @end ``` Do not process frames on the main thread except for tiny stills. Do not share one engine across concurrent queues. ## Memory * Prefer ARC. Drop `FBImageFrame` references when a frame is done. * Reuse camera pixel buffers (NV12 / BGRA) instead of converting every frame to RGBA. * Call `setFilter:` / `setSticker:` once; textures load on the next `processImage:`. * Use `clearFilter`, `clearSticker`, `clearVirtualBackground`, and `clearChromaKey` instead of creating a second engine. ## External OpenGL When the AppKit view already owns a **desktop OpenGL 3.2 Core** context (`NSOpenGLContext` / CGL): 2. Create the engine **on that GL thread** (reuse the caller’s current context; do not create a second one). 3. Wrap a `GL_TEXTURE_2D` with `createWithTexture:width:height:stride:`. 4. Read the output with `[output texture]`. macOS uses desktop OpenGL, not OpenGL ES. Do not mix external textures and `CVPixelBuffer` on the same engine. ## Monitor with `getStats` ```objc theme={null} FBEngineStats *stats = [engine getStats]; NSLog(@"fps=%.1f avg=%.2fms session=%.1fs", stats.fps, stats.avgProcessTimeMs, stats.sessionTimeS); ``` Aim for `avgProcessTimeMs` under \~33 ms at 30 fps. Desktop GPUs can run higher resolutions; still drop effects if the UI hitchs. ## Lifecycle (AppKit) Hold the engine on the `NSViewController` (or a session object). Stop capture in `viewWillDisappear`. Pause when the window miniaturizes. Nil the engine in `dealloc` / `applicationWillTerminate`. ```objc theme={null} - (void)viewWillDisappear { [super viewWillDisappear]; [self.captureSession stopRunning]; } - (void)dealloc { self.beautyEffectEngine = nil; } ``` Use `__weak` in `FBEngineCallbacks` blocks. ## macOS capture and display * Build frames with `createWithNV12:...`, `createWithBGRA:...`, or `createWithNSImage:`. * Front camera / user-facing preview: `setMirror:FBMirrorModeHorizontal`. * Retina: process in pixel size (`backingScaleFactor`), not point size. * Camera: `NSCameraUsageDescription`. Sandboxed apps need **Outgoing Connections** for online auth. * User-picked `.fbd` / background images: security-scoped URLs. ## Testing * Bind the Mac app Bundle ID (or process name for CLI tools). * Use a real `appId` / `appKey` or `licenseToken`. * Cover `FBFrameTypeImage` + `createWithNSImage:` and `FBFrameTypeVideo`. * Assert setter codes are `FBErrorCode_Success`. Universal Binary: test Intel and Apple Silicon. # Error Handling Source: https://docs.facebetter.net/macos/error-handling macOS Beauty Effect SDK 2.0 error handling > [!NOTE] > > This page matches SDK **2.0.0**. Auth: [Auth & License](/intro/license). ## Error codes (`FBErrorCode`) Setter APIs return `int`. `0` is success. `createEngineWithConfig:` and `processImage:` return objects (`nil` on failure). | Value | Symbol | Meaning | | - | - | - | | `0` | `FBErrorCode_Success` | Success | | `-1` | `FBErrorCode_InvalidArgument` | Invalid argument (nil config, empty path, out-of-range value, …) | | `-2` | `FBErrorCode_NotInitialized` | Engine is not initialized | | `-3` | `FBErrorCode_License` | License / auth failure | | `-4` | `FBErrorCode_Unsupported` | Unsupported format, platform, or feature | | `-5` | `FBErrorCode_IO` | File / resource I/O error | | `-6` | `FBErrorCode_Process` | Frame processing failed | | `-7` | `FBErrorCode_OutOfMemory` | Out of memory | ```objc theme={null} typedef NS_ENUM(NSInteger, FBErrorCode) { FBErrorCode_Success = 0, FBErrorCode_InvalidArgument = -1, FBErrorCode_NotInitialized = -2, FBErrorCode_License = -3, FBErrorCode_Unsupported = -4, FBErrorCode_IO = -5, FBErrorCode_Process = -6, FBErrorCode_OutOfMemory = -7, }; ``` ## Check return values ```objc theme={null} FBLogConfig *logConfig = [[FBLogConfig alloc] init]; logConfig.consoleEnabled = YES; logConfig.level = FBLogLevel_Info; int logRet = [FBBeautyEffectEngine setLogConfig:logConfig]; if (logRet != FBErrorCode_Success) { NSLog(@"setLogConfig failed: %d", logRet); } FBEngineConfig *config = [[FBEngineConfig alloc] init]; config.appId = @"your_app_id"; config.appKey = @"your_app_key"; self.engine = [FBBeautyEffectEngine createEngineWithConfig:config]; if (self.engine == nil) { NSLog(@"Failed to create engine (check license, Bundle ID, network, and logs)"); return; } int ret = [self.engine setSmoothing:0.5f]; if (ret != FBErrorCode_Success) { NSLog(@"setSmoothing failed: %d", ret); } ``` Map codes in one place: ```objc theme={null} NSString *FBErrorMessage(int code) { switch (code) { case FBErrorCode_Success: return @"success"; case FBErrorCode_InvalidArgument: return @"invalid argument"; case FBErrorCode_NotInitialized: return @"engine not initialized"; case FBErrorCode_License: return @"license / auth failure"; case FBErrorCode_Unsupported: return @"unsupported"; case FBErrorCode_IO: return @"I/O error"; case FBErrorCode_Process: return @"process failed"; case FBErrorCode_OutOfMemory: return @"out of memory"; default: return [NSString stringWithFormat:@"unknown (%d)", code]; } } ``` ## Engine events `FBEngineCallbacks.onEngineEvent` reports license and init asynchronously. Set callbacks immediately after creating the engine. | Code | Symbol | Meaning | | - | - | - | | `0` | `FBEngineEventCodeLicenseValidationSuccess` | License OK | | `1` | `FBEngineEventCodeLicenseValidationFailed` | License fail | | `100` | `FBEngineEventCodeInitializationComplete` | Init complete | | `101` | `FBEngineEventCodeInitializationFailed` | Init fail | ```objc theme={null} FBEngineCallbacks *callbacks = [[FBEngineCallbacks alloc] init]; callbacks.onEngineEvent = ^(FBEngineEventCode code, NSString * _Nullable message) { switch (code) { case FBEngineEventCodeLicenseValidationFailed: NSLog(@"License failed: %@", message); break; case FBEngineEventCodeInitializationFailed: NSLog(@"Init failed: %@", message); break; default: break; } }; [self.engine setCallbacks:callbacks]; ``` > [!TIP] > > `createEngineWithConfig:` returning a non-nil instance does not replace listening for event `1` / `101`. Online auth can still fail after construction. ## Image processing Validate the frame, set `type`, and treat a `nil` return as `FBErrorCode_Process`. macOS can handle larger stills; still reject zero-size buffers. ```objc theme={null} - (FBImageFrame *)processSafely:(FBImageFrame *)input { if (input == nil || input.width <= 0 || input.height <= 0) { NSLog(@"Invalid FBImageFrame"); return nil; } input.type = FBFrameTypeVideo; FBImageFrame *output = [self.engine processImage:input]; if (output == nil) { NSLog(@"processImage returned nil"); } return output; } ``` Save with `toFile:` (returns `FBErrorCode`): ```objc theme={null} int saved = [output toFile:path quality:90]; if (saved != FBErrorCode_Success) { NSLog(@"toFile failed: %d", saved); } ``` `createWithNSImage:` returns `nil` if the `NSImage` has no bitmap representation. ## Logging Enable logs **before** creating the engine. Create the log directory if you write a file. In a sandboxed Mac app, write under the container (for example Application Support), not an arbitrary path. ```objc theme={null} NSString *logPath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"facebetter.log"]; NSString *logDir = [logPath stringByDeletingLastPathComponent]; [[NSFileManager defaultManager] createDirectoryAtPath:logDir withIntermediateDirectories:YES attributes:nil error:nil]; FBLogConfig *logConfig = [[FBLogConfig alloc] init]; logConfig.consoleEnabled = YES; logConfig.fileEnabled = YES; logConfig.level = FBLogLevel_Debug; logConfig.fileName = logPath; [FBBeautyEffectEngine setLogConfig:logConfig]; ``` ## macOS-specific failures * **App Sandbox**: enable outgoing network for online `appId` / `appKey`. User-selected files need security-scoped bookmarks (`startAccessingSecurityScopedResource`). * **`-5` I/O**: the `.fbd` / background image is outside the sandbox or the bookmark is not started. * **CLI tools**: if there is no Bundle ID, bind the process name in the Dashboard. ## Practical checks * **`-1` Invalid argument**: empty `.fbd` path, nil `NSData`, intensity outside the documented range, or a nil config. * **`-2` Not initialized**: calling setters after a failed `createEngineWithConfig:` (the instance is `nil`). * **`-3` License**: wrong credentials, unbound Bundle ID, expired token, or sandbox blocking the auth request. See [Auth & License](/intro/license). # FAQ Source: https://docs.facebetter.net/macos/faq macOS Beauty Effect SDK 2.0 common questions > [!NOTE] > > This page matches SDK **2.0.0**. Auth: [Auth & License](/intro/license). Enums: [Parameter enums](/intro/makeup). ## Integration ### Engine creation returns `nil` * Confirm `licenseToken` **or** `appId` + `appKey` is set. Token wins if both are present. * Bind the Mac **Bundle ID** (CLI tools: process name). * Online auth needs **Outgoing Connections** in the App Sandbox and a path to `/facebetter/v2/auth`. * Enable logs **before** `createEngineWithConfig:` and watch events `1` / `101`. * CocoaPods: `pod 'Facebetter', '2.0.0'`. Open the `.xcworkspace`. ### Missing headers or classes * Import `#import `. * Manual `.framework`: **Embed & Sign**. * Xcode 15+ CocoaPods sandbox: set `ENABLE_USER_SCRIPT_SANDBOXING` to **No**. ### Runtime link / dyld errors * Architectures: **x86\_64** and **arm64**. * Deployment target **macOS 10.15+**. ## Auth ### `licenseToken` vs `appId` / `appKey` If `licenseToken` is non-empty, the SDK verifies that token / `{token}` JSON / `.lic` locally. Otherwise it uses online auth. Details: [Auth & License](/intro/license). ### Event `1` or `101` License or init failed. Check Bundle ID, sandbox network, token expiry, and logs. ## Beauty ### Effect is too weak or too strong * Skin / makeup / filter: `[0.0, 1.0]`. * Reshape: **`[-1.0, 1.0]`** via `setReshape:intensity:`. * Body reshape: **`[0.0, 1.0]`** via `setBodyReshape:intensity:`. Register `resource_body.fbd` first. * Intensity `0` disables that effect. * Skin-only: `setBeautySkinOnly:`. Preset names: [Parameter enums](/intro/makeup). ## Filters, stickers, virtual background Pass the `.fbd` path or bytes. Sandboxed apps must be able to read that path. ```objc theme={null} [engine setFilter:fbdPath]; [engine setFilterIntensity:0.8f]; [engine clearFilter]; [engine setSticker:fbdPath]; [engine clearSticker]; ``` Virtual background: ```objc theme={null} [engine setVirtualBackgroundBlur:0.6f]; [engine setVirtualBackground:imagePath]; [engine setVirtualBackgroundWithData:imageData]; [engine clearVirtualBackground]; [engine setChromaKey:FBChromaKeyColor_Green]; [engine clearChromaKey]; ``` ## Processing ### `processImage:` returns `nil` ### Frame type Set `imageFrame.type` to `FBFrameTypeImage` (`0`) or `FBFrameTypeVideo` (`1`). No process-mode argument. ### Format conversion Use `convert:`: ```objc theme={null} FBImageFrame *rgba = [frame convert:FBImageFormatRGBA]; const uint8_t *data = [rgba data]; ``` ### NSImage ```objc theme={null} FBImageFrame *frame = [FBImageFrame createWithNSImage:nsImage]; frame.type = FBFrameTypeImage; FBImageFrame *out = [engine processImage:frame]; ``` ### Camera 1. `AVCaptureVideoDataOutput` → `CVPixelBuffer`. 2. `createWithNV12:...` or `createWithBGRA:...`. 3. `type = FBFrameTypeVideo`, optional `setMirror:FBMirrorModeHorizontal`. 4. Display `[output data]` or `[output texture]` in an AppKit / OpenGL view. ## Performance * `FBFrameTypeVideo` for live; watch `getStats`. * One engine, serial queue. * Pause capture when the window is miniaturized. ## Logging ```objc theme={null} [FBBeautyEffectEngine setLogConfig:logConfig]; // before createEngineWithConfig: ``` Write logs inside the sandbox container. Return codes: [Error Handling](/macos/error-handling). ## Version * **macOS 10.15+**, **x86\_64** + **arm64**. * CocoaPods: `pod 'Facebetter', '2.0.0'`. * Universal Binary: confirm the xcframework contains both slices (`lipo -info`). ## Sandbox and App Store * Outgoing network for online auth. * `NSCameraUsageDescription` for camera. * Security-scoped bookmarks for user-selected files. * Do not use private APIs; keep the engine off the main thread for live video. # Implement Beauty Source: https://docs.facebetter.net/macos/implement-beauty Implement macOS beauty with Beauty Effect SDK 2.0 > [!NOTE] > > This page matches SDK **2.0.0**. Auth: [Auth & License](/intro/license). Makeup / reshape enums: [Parameter enums](/intro/makeup). ## Add SDK dependency ### Method A: CocoaPods (recommended) ```ruby theme={null} target 'YourTargetName' do pod 'Facebetter', '2.0.0' end ``` ```bash theme={null} pod install ``` > [!WARNING] > > **Xcode 15+ compilation error** > > If you are using **Xcode 15** or later, you might encounter a `Sandbox: rsync.samba deny(1)` error. This is caused by **User Script Sandboxing**. > > **Solution:** > > 1. Select your **Project** in Xcode. > 2. Open **Build Settings**. > 3. Search for `ENABLE_USER_SCRIPT_SANDBOXING`. > 4. Change the value from `Yes` to **`No`**. ### Method B: Manual framework Download the SDK from [Download](https://facebetter.net/download), copy `Facebetter.framework` into the project, and [embed the dynamic library](https://help.apple.com/xcode/mac/current/#/dev51a648b07) with **Embed & Sign**. ![Xcode Link Library](https://mintcdn.com/facebetter/DM5KtVsHX1q4Zlkm/images/ios-3.png?fit=max\&auto=format\&n=DM5KtVsHX1q4Zlkm\&q=85\&s=d27068487388c927268f25c4aecb957e) ### Permissions Sandboxed Mac apps that use online `appId` / `appKey` must allow outgoing network: ![macOS network permission](https://mintcdn.com/facebetter/DM5KtVsHX1q4Zlkm/images/macos-4.png?fit=max\&auto=format\&n=DM5KtVsHX1q4Zlkm\&q=85\&s=76666b702fee791a6fd9ae55c4957377) Camera (optional): `NSCameraUsageDescription` in `Info.plist`. ## Import ```objc theme={null} #import ``` AppKit types (`NSImage`) require `#import ` (usually via the prefix header or the engine header on macOS). ## Log configuration Logging is off by default. Call `setLogConfig:` **before** creating the engine. ```objc theme={null} FBLogConfig *logConfig = [[FBLogConfig alloc] init]; logConfig.level = FBLogLevel_Info; logConfig.consoleEnabled = YES; logConfig.fileEnabled = YES; logConfig.fileName = @"/path/in/container/facebetter.log"; [FBBeautyEffectEngine setLogConfig:logConfig]; ``` ## Create the engine Bind the macOS Bundle ID, then pass either `licenseToken` or `appId` + `appKey`. See [Get AppID and AppKey](/intro/enable-service#get-appid-and-appkey) and [Auth & License](/intro/license). **Priority:** if `licenseToken` is non-empty (license token string, `{token}` JSON, or `.lic` contents), the SDK validates it locally. Otherwise it uses `appId` + `appKey` against `/facebetter/v2/auth`. ```objc theme={null} FBEngineConfig *engineConfig = [[FBEngineConfig alloc] init]; engineConfig.appId = @"your appId"; engineConfig.appKey = @"your appKey"; // engineConfig.licenseToken = @"your license token"; self.beautyEffectEngine = [FBBeautyEffectEngine createEngineWithConfig:engineConfig]; if (self.beautyEffectEngine == nil) { NSLog(@"Failed to create beauty engine"); return; } ``` `createEngineWithConfig:` returns an **instance**, not a singleton. For command-line tools without a Bundle ID, bind the process name in the Dashboard. ## Skin beauty Intensity is typically `[0.0, 1.0]`. Style enums: [Parameter enums](/intro/makeup). ```objc theme={null} [self.beautyEffectEngine setSmoothing:0.5f]; [self.beautyEffectEngine setSmoothingStyle:FBSmoothingStyle_Natural]; [self.beautyEffectEngine setWhitening:0.3f]; [self.beautyEffectEngine setWhiteningStyle:FBWhiteningStyle_ColdWhite]; [self.beautyEffectEngine setRosiness:0.15f]; [self.beautyEffectEngine setBrightness:0.1f]; [self.beautyEffectEngine setClarity:0.2f]; [self.beautyEffectEngine setBeautySkinOnly:YES]; ``` ## Face reshape `setReshape:intensity:` range is **`[-1.0, 1.0]`**. `0` is off. Parameters: `FBReshape_FaceThin` … `FBReshape_BrowThickness` (`0`–`25`). Meanings: [Parameter enums](/intro/makeup). ```objc theme={null} [self.beautyEffectEngine setReshape:FBReshape_FaceThin intensity:0.4f]; [self.beautyEffectEngine setReshape:FBReshape_EyeSize intensity:0.2f]; ``` ## Body reshape `setBodyReshape:intensity:` range is **`[0.0, 1.0]`**. `0` is off. Register `resource_body.fbd` with `addResourcePack:` first. Parameters: `FBBodyReshape_BodySlim` … `FBBodyReshape_TorsoLong` (`0`–`8`). See [Parameter enums](/intro/makeup) and [Optional resource packs](/intro/resource-packs). ```objc theme={null} NSString *bodyPack = [[NSBundle mainBundle] pathForResource:@"resource_body" ofType:@"fbd"]; [self.beautyEffectEngine addResourcePack:bodyPack]; [self.beautyEffectEngine setBodyReshape:FBBodyReshape_WaistSlim intensity:0.4f]; [self.beautyEffectEngine setBodyReshape:FBBodyReshape_LegStretch intensity:0.3f]; [self.beautyEffectEngine setBodyReshape:FBBodyReshape_TorsoLong intensity:0.3f]; ``` ## Makeup Intensity, shape, and color are separate calls. Full presets: [Parameter enums](/intro/makeup). ```objc theme={null} [self.beautyEffectEngine setLipstick:0.5f]; [self.beautyEffectEngine setLipstickColor:FBLipstickColor_Rouge]; [self.beautyEffectEngine setBlush:0.4f]; [self.beautyEffectEngine setBlushStyle:FBBlushStyle_SunKissed]; [self.beautyEffectEngine setBlushColor:FBBlushColor_CoralPink]; [self.beautyEffectEngine setContour:0.35f]; [self.beautyEffectEngine setContourStyle:FBContourStyle_Natural]; [self.beautyEffectEngine setEyeShadow:0.4f]; [self.beautyEffectEngine setEyeShadowStyle:FBEyeShadowStyle_Soft]; [self.beautyEffectEngine setEyeShadowColor:FBEyeShadowColor_Plum]; [self.beautyEffectEngine setEyeLiner:0.4f]; [self.beautyEffectEngine setEyeLinerStyle:FBEyeLinerStyle_Classic]; [self.beautyEffectEngine setEyeLinerColor:FBEyeLinerColor_Coffee]; [self.beautyEffectEngine setEyebrow:0.4f]; [self.beautyEffectEngine setEyebrowStyle:FBEyebrowStyle_Natural]; [self.beautyEffectEngine setEyebrowColor:FBEyebrowColor_DarkBrown]; [self.beautyEffectEngine setEyelash:0.4f]; [self.beautyEffectEngine setEyelashStyle:FBEyelashStyle_Classic]; [self.beautyEffectEngine setEyelashColor:FBEyelashColor_Black]; [self.beautyEffectEngine setPupil:0.4f]; [self.beautyEffectEngine setPupilColor:FBPupilColor_Hazel]; ``` ## Virtual background ```objc theme={null} [self.beautyEffectEngine setVirtualBackgroundBlur:0.6f]; [self.beautyEffectEngine setVirtualBackground:imagePath]; [self.beautyEffectEngine setVirtualBackgroundWithData:pngOrJpegData]; [self.beautyEffectEngine clearVirtualBackground]; ``` Chroma key replaces the mask only. Fill is still blur or the replacement image. ```objc theme={null} [self.beautyEffectEngine setChromaKey:FBChromaKeyColor_Green]; [self.beautyEffectEngine setChromaKeySimilarity:0.4f]; [self.beautyEffectEngine setChromaKeySmoothness:0.3f]; [self.beautyEffectEngine setChromaKeyDesaturation:0.2f]; [self.beautyEffectEngine clearChromaKey]; ``` ## Filters and stickers Pass a `.fbd` file path or in-memory bytes. ```objc theme={null} NSString *filterPath = [[NSBundle mainBundle] pathForResource:@"chuxin" ofType:@"fbd"]; [self.beautyEffectEngine setFilter:filterPath]; [self.beautyEffectEngine setFilterIntensity:0.8f]; [self.beautyEffectEngine clearFilter]; [self.beautyEffectEngine setFilterWithData:filterData]; NSString *stickerPath = [[NSBundle mainBundle] pathForResource:@"cherry" ofType:@"fbd"]; [self.beautyEffectEngine setSticker:stickerPath]; [self.beautyEffectEngine clearSticker]; [self.beautyEffectEngine setStickerWithData:stickerData]; ``` 3D stickers need the optional `resource_3d.fbd` pack (not in the framework). See [Optional resource packs](/intro/resource-packs): ```objc theme={null} NSString *packPath = [[NSBundle mainBundle] pathForResource:@"resource_3d" ofType:@"fbd"]; [self.beautyEffectEngine addResourcePack:packPath]; NSString *sticker3dPath = [[NSBundle mainBundle] pathForResource:@"oculos" ofType:@"fbd"]; [self.beautyEffectEngine set3DSticker:sticker3dPath]; [self.beautyEffectEngine clear3DSticker]; ``` ## Callbacks and stats ```objc theme={null} FBEngineCallbacks *callbacks = [[FBEngineCallbacks alloc] init]; callbacks.onEngineEvent = ^(FBEngineEventCode code, NSString * _Nullable message) { // 0 license OK, 1 license fail, 100 init complete, 101 init fail NSLog(@"engine event %ld %@", (long)code, message); }; [self.beautyEffectEngine setCallbacks:callbacks]; FBEngineStats *stats = [self.beautyEffectEngine getStats]; NSLog(@"fps=%.1f avg=%.2fms session=%.1fs", stats.fps, stats.avgProcessTimeMs, stats.sessionTimeS); ``` ## Process images `FBImageFrame` supports I420, NV12, NV21, RGB, RGBA, BGR, BGRA, file, texture, and **`NSImage`**. ```objc theme={null} FBImageFrame *fromFile = [FBImageFrame createWithFile:@"/path/photo.png"]; FBImageFrame *fromRGBA = [FBImageFrame createWithRGBA:data width:width height:height stride:stride]; FBImageFrame *fromNSImage = [FBImageFrame createWithNSImage:nsImage]; ``` Set `type` then call `processImage:` (no extra mode argument). Output keeps the input format. ```objc theme={null} input.type = FBFrameTypeVideo; // or FBFrameTypeImage FBImageFrame *output = [self.beautyEffectEngine processImage:input]; ``` > [!TIP] > > `FBFrameTypeVideo` is for live streams; `FBFrameTypeImage` is for stills and `NSImage`. Rotate and mirror change CPU pixels only. They do not transform an OpenGL texture, a CVPixelBuffer, or a Metal texture. ```objc theme={null} [input rotate:FBImageRotation90]; [input setMirror:FBMirrorModeHorizontal]; FBImageFrame *rgba = [output convert:FBImageFormatRGBA]; const uint8_t *bytes = [rgba data]; [output toFile:@"/path/out.jpg" quality:90]; ``` YUV planes: `dataY`, `dataU`, `dataV`, `dataUV` and matching strides. ## External texture > [!WARNING] > > Create the engine and call process on the thread whose GL context is current. Input and output textures must belong to that context. CPU frames do not need a caller GL context. There is no context flag on the config. ```objc theme={null} FBEngineConfig *config = [[FBEngineConfig alloc] init]; config.appId = @"your appId"; config.appKey = @"your appKey"; self.engine = [FBBeautyEffectEngine createEngineWithConfig:config]; FBImageFrame *inputFrame = [FBImageFrame createWithTexture:textureId width:width height:height stride:width * 4]; inputFrame.type = FBFrameTypeVideo; FBImageFrame *outputFrame = [self.engine processImage:inputFrame]; GLuint outputTexture = [outputFrame texture]; ``` For TRTC / Agora / LiveKit: [Third-party Integration](/macos/third-party-integration). ## Lifecycle Keep a strong reference on the `NSViewController`. Stop the capture session when the view disappears or the window miniaturizes. Nil the engine when the session ends. ```objc theme={null} - (void)dealloc { self.beautyEffectEngine = nil; } ``` ## Related * [Third-party Integration](/macos/third-party-integration) * [Best Practices](/macos/best-practices) * [Error Handling](/macos/error-handling) * [FAQ](/macos/faq) * [API Reference](/macos/api-reference) # Quick Start Source: https://docs.facebetter.net/macos/quick-start Run the macOS sample app with Beauty Effect SDK 2.0 > [!NOTE] > > This page matches SDK **2.0.0**. Auth: [Auth & License](/intro/license). Makeup / reshape enums: [Parameter enums](/intro/makeup). ## Environment Requirements * **macOS Version**: `macOS 10.15` and above * **Development Language**: `Objective-C` (AppKit / `NSImage`) * **Architecture Support**: `x86_64`, `arm64` (Apple Silicon) ## Get Sample Source Code Clone the [GitHub repository](https://github.com/pixpark/facebetter-sdk) locally, and navigate to the `demo/macos` directory. ```bash theme={null} # clone git clone https://github.com/pixpark/facebetter-sdk.git # Enter macOS Demo directory cd facebetter-sdk/demo/macos # Install dependencies pod install ``` > [!WARNING] > > **Xcode 15+ compilation error** > > If you are using **Xcode 15** or later, you might encounter a `Sandbox: rsync.samba deny(1)` error during compilation. This is caused by Xcode's default **User Script Sandboxing**. > > **Solution:** > > 1. Select your **Project** in Xcode. > 2. Navigate to the **Build Settings** tab. > 3. Search for `ENABLE_USER_SCRIPT_SANDBOXING`. > 4. Change its value from `Yes` to **`No`**. ## Configure Application Information and Keys ### Bind Application Bundle ID Follow [Bind Application Information](/intro/enable-service#bind-application-information) to bind your macOS application Bundle ID in the console, for example: `com.example.app`. ### Get credentials Follow [Get AppID and AppKey](/intro/enable-service#get-appid-and-appkey) to obtain `appId` and `appKey`. Open `demo/macos/FBExampleObjc/BeautyCameraViewController.m` and set credentials on `FBEngineConfig`. ```objc theme={null} FBEngineConfig *engineConfig = [[FBEngineConfig alloc] init]; engineConfig.appId = @"your appId"; engineConfig.appKey = @"your appKey"; // Preferred: licenseToken (license token, {token} JSON, or .lic contents) // engineConfig.licenseToken = @"your license token"; self.beautyEffectEngine = [FBBeautyEffectEngine createEngineWithConfig:engineConfig]; ``` > [!TIP] > > If `licenseToken` is non-empty, the SDK validates that token locally and does **not** call `/facebetter/v2/auth` with `appId` / `appKey`. See [Auth & License](/intro/license). ## Run the Project Open `demo/macos/FBExampleObjc.xcworkspace`. 1. Ensure Xcode project signing is correct. ![Xcode Signing](https://mintcdn.com/facebetter/DM5KtVsHX1q4Zlkm/images/ios-1.png?fit=max\&auto=format\&n=DM5KtVsHX1q4Zlkm\&q=85\&s=beb0bc3b315d6007c761b7617df679cf) 2. Allow outgoing network access if you use online `appId` / `appKey` auth (App Sandbox). ![macOS network permission](https://mintcdn.com/facebetter/DM5KtVsHX1q4Zlkm/images/macos-4.png?fit=max\&auto=format\&n=DM5KtVsHX1q4Zlkm\&q=85\&s=76666b702fee791a6fd9ae55c4957377) 3. Build and run. Select a Mac (or Simulator) and click the build and run button. # Third-party Integration Source: https://docs.facebetter.net/macos/third-party-integration Wire Facebetter beauty into TRTC, Agora, LiveKit, and other macOS video pipelines SDK **2.0.0**. Hook Facebetter into a third-party SDK’s **custom video preprocess** callback: process frames on that SDK’s **OpenGL thread** (or pixel-buffer callback), then return the result. Shares the same Objective-C API as [iOS · Third-party Integration](/ios/third-party-integration); differences are mostly runtime (OpenGL, App Sandbox, process-name binding). Full texture rules: [Implement Beauty · External texture](/macos/implement-beauty#external-texture). ``` Third-party SDK textureId or CVPixelBuffer ↓ FBBeautyEffectEngine createWithTexture / createWithNV12|BGRA → processImage: ↓ output texture or pixels → write back to vendor frame ``` ## Shared contract | Item | Requirement | | - | - | | Input texture | `GL_TEXTURE_2D` (RGBA); `stride` usually `width * 4` | | Frame type | `FBFrameTypeVideo` | | Output | Do not `glDeleteTextures` the output; keep a strong engine ref and nil it when the session ends | | Sandbox | Online auth needs **Outgoing Connections**; use `licenseToken` / `.lic` for offline | TRTC custom preprocess commonly uses **OpenGL textures**; Agora / LiveKit more often deliver **`CVPixelBuffer`**. Do not mix both modes on one engine. ### Shared: process texture ```objc theme={null} #import static GLuint FBProcessTexture(FBBeautyEffectEngine *engine, GLuint srcTextureId, int width, int height) { if (!engine || srcTextureId == 0 || width <= 0 || height <= 0) { return srcTextureId; } FBImageFrame *input = [FBImageFrame createWithTexture:srcTextureId width:width height:height stride:width * 4]; if (!input) { return srcTextureId; } input.type = FBFrameTypeVideo; FBImageFrame *output = [engine processImage:input]; if (!output) { return srcTextureId; } GLuint dst = [output texture]; return dst != 0 ? dst : srcTextureId; } ``` ```objc theme={null} FBEngineConfig *config = [[FBEngineConfig alloc] init]; config.appId = @"your appId"; config.appKey = @"your appKey"; self.beautyEngine = [FBBeautyEffectEngine createEngineWithConfig:config]; [self.beautyEngine setSmoothing:0.5f]; ``` ### Shared: process CVPixelBuffer (NV12 sketch) ```objc theme={null} static FBImageFrame *FBFrameFromNV12PixelBuffer(CVPixelBufferRef pb) { OSType fmt = pb ? CVPixelBufferGetPixelFormatType(pb) : 0; if (!pb || (fmt != kCVPixelFormatType_420YpCbCr8BiPlanarFullRange && fmt != kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange)) { return nil; } CVPixelBufferLockBaseAddress(pb, kCVPixelBufferLock_ReadOnly); int width = (int)CVPixelBufferGetWidth(pb); int height = (int)CVPixelBufferGetHeight(pb); uint8_t *y = (uint8_t *)CVPixelBufferGetBaseAddressOfPlane(pb, 0); uint8_t *uv = (uint8_t *)CVPixelBufferGetBaseAddressOfPlane(pb, 1); int strideY = (int)CVPixelBufferGetBytesPerRowOfPlane(pb, 0); int strideUV = (int)CVPixelBufferGetBytesPerRowOfPlane(pb, 1); FBImageFrame *frame = [FBImageFrame createWithNV12:width height:height dataY:y strideY:strideY dataUV:uv strideUV:strideUV]; CVPixelBufferUnlockBaseAddress(pb, kCVPixelBufferLock_ReadOnly); return frame; } ``` *** ## TRTC (Tencent) Hook: `setLocalVideoProcessDelegete:pixelFormat:bufferType:` (official spelling **Delegete**). **`TRTCVideoPixelFormat_Texture_2D`** + **`TRTCVideoBufferType_Texture`**. ```objc theme={null} #import #import @interface BeautyProcessDelegate : NSObject @property (nonatomic, strong) FBBeautyEffectEngine *beautyEngine; @end @implementation BeautyProcessDelegate - (void)onGLContextCreated { FBEngineConfig *config = [[FBEngineConfig alloc] init]; config.appId = @"your appId"; config.appKey = @"your appKey"; self.beautyEngine = [FBBeautyEffectEngine createEngineWithConfig:config]; [self.beautyEngine setSmoothing:0.5f]; } - (uint32_t)onProcessVideoFrame:(TRTCVideoFrame *)srcFrame dstFrame:(TRTCVideoFrame *)dstFrame { GLuint out = FBProcessTexture(self.beautyEngine, srcFrame.textureId, srcFrame.width, srcFrame.height); dstFrame.textureId = out; return 0; } - (void)onGLContextDestory { self.beautyEngine = nil; } @end BeautyProcessDelegate *delegate = [[BeautyProcessDelegate alloc] init]; [[TRTCCloud sharedInstance] setLocalVideoProcessDelegete:delegate pixelFormat:TRTCVideoPixelFormat_Texture_2D bufferType:TRTCVideoBufferType_Texture]; ``` Nil the engine after clearing the delegate or leaving the room. See Tencent’s TRTC third-party beauty docs for the latest details. *** ## Agora Hook: `AgoraRtcEngineKit.setVideoFrameDelegate:` (Video SDK **4.x**). Captured frames on macOS are also typically **`CVPixelBuffer`**. ```objc theme={null} #import @interface BeautyFrameDelegate : NSObject @property (nonatomic, strong) FBBeautyEffectEngine *beautyEngine; @end @implementation BeautyFrameDelegate - (AgoraVideoFrameProcessMode)getVideoFrameProcessMode { return AgoraVideoFrameProcessModeReadWrite; } - (BOOL)onCapture:(AgoraOutputVideoFrame *)videoFrame sourceType:(AgoraVideoSourceType)sourceType { CVPixelBufferRef pb = videoFrame.pixelBuffer; // or textureBuf — check your headers if (!pb) { return YES; } if (!self.beautyEngine) { FBEngineConfig *config = [[FBEngineConfig alloc] init]; config.appId = @"your appId"; config.appKey = @"your appKey"; self.beautyEngine = [FBBeautyEffectEngine createEngineWithConfig:config]; } FBImageFrame *input = FBFrameFromNV12PixelBuffer(pb); if (!input) { return YES; } input.type = FBFrameTypeVideo; FBImageFrame *output = [self.beautyEngine processImage:input]; if (!output) { return YES; } // Write output back into videoFrame’s CVPixelBuffer (details vary by Agora version) return YES; } @end [agoraKit setVideoFrameDelegate:delegate]; ``` > [!WARNING] > > How you write a processed `CVPixelBuffer` back into Agora’s frame differs across major versions. Facebetter keeps output in the same format as the input; follow Agora’s docs for injecting into `AgoraOutputVideoFrame`. Call `setVideoFrameDelegate:nil` and nil `beautyEngine` before teardown. *** ## LiveKit Implement Swift `VideoProcessor`, process `CVPixelBuffer` in `process(frame:)`, and pass `processor:` when creating the camera track (supported on macOS as well). ```swift theme={null} import LiveKit import Facebetter final class FacebetterVideoProcessor: VideoProcessor { private var beautyEngine: FBBeautyEffectEngine? func process(frame: VideoFrame) -> VideoFrame? { guard let pb = frame.buffer as CVPixelBuffer? else { return frame } if beautyEngine == nil { let config = FBEngineConfig() config.appId = "your appId" config.appKey = "your appKey" beautyEngine = FBBeautyEffectEngine.createEngine(with: config) beautyEngine?.setSmoothing(0.5) } // FBFrameFromNV12PixelBuffer → processImage: → wrap as LiveKit VideoFrame return frame } } let processor = FacebetterVideoProcessor() let track = LocalVideoTrack.createCameraTrack(processor: processor) try await room.localParticipant.publish(track: track) ``` See `BackgroundBlurVideoProcessor` (macOS 12+) for an official sample. Screen-share tracks can use the same processor pattern (API per your LiveKit Swift version). *** ## Troubleshooting | Symptom | Check | | - | - | | Black / no video | Engine on vendor **GL thread**; sandbox not blocking online auth | | Intermittent crash | Nil engine in `onGLContextDestory` | | Distortion | Width / height / rotation / `BytesPerRow` strides | ## Related * [Implement Beauty](/macos/implement-beauty) * [Best Practices](/macos/best-practices) * [Error Handling](/macos/error-handling) * [API Reference](/macos/api-reference) * [iOS · Third-party Integration](/ios/third-party-integration) # Adjust effects Source: https://docs.facebetter.net/obs/effects Adjust skin, face shape, makeup, stickers, and background in the Facebetter panel. After the filter is on a source, adjust it in the panel on the right. The OBS preview follows the sliders. Streaming and recording send the processed picture. If you have not added the filter yet, start with [Sign in and add the filter](/obs/login). ![Adjust skin in the Facebetter panel](https://mintcdn.com/facebetter/8-QG_hBISFqsZt9s/images/obs/panel.png?fit=max\&auto=format\&n=8-QG_hBISFqsZt9s\&q=85\&s=00cd543a464faf5353bbfd14f9655f77) Across the top of the panel, from left to right: * **Switch**: compare on and off. Off shows the original preview. Turn it back on before you go live. * **Source menu**: one source that already has the filter, or **All sources**. All sources writes the change onto every Facebetter filter. * **Reset**: return the current page to its defaults. * **Gear**: settings. Choose whether the panel opens when OBS starts, and open the account and subscription page. Under that are seven pages: | Page | What it does | | - | - | | Skin | Smooth, whiten, and rosy glow. **Skin only** limits the effect to skin, so clothes, the background, and a product in frame stay as they are. Smooth styles are Texture, Natural, and Smooth. Whiten tones are Cool, Pink, Warm, Wheat, and Tan. | | Shape | Face, forehead and brows, eyes, nose, and mouth. Each control moves both ways. 0 means unchanged. | | Makeup | Lipstick, blush, contour, eyeshadow, eyeliner, brows, lashes, and lenses. Style, shade, and intensity are separate. | | Filter | Film color. Pick a LUT, then set the amount. None turns color grading off. | | Sticker | 2D face tracking, 2D screen stickers, and 3D stickers. None removes the sticker. | | Body | Slim the body, waist, legs, shoulders, and arms, lengthen the legs, and adjust the bust. This suits a half-body or full-body shot. | | BG | Keep the original background, blur it, or replace it with a preset. Cutout can use portrait segmentation, or a green, blue, or red screen. | The panel language follows OBS. Simplified Chinese, Traditional Chinese, English, Japanese, Korean, Portuguese, Spanish, and German have their own interface. Other OBS languages show English. ## Remove the watermark The free plan includes every effect above, and the output has a watermark. Pro removes the watermark and can be used on 2 devices. * Monthly: \$8.99 * Yearly: \$69 Click **Remove watermark** at the top of the panel, or open the gear → Account and subscribe on the page. Dismissing the banner lasts only until you quit OBS. Subscribe and manage devices at [facebetter.net/dashboard/obs](https://facebetter.net/dashboard/obs). # FAQ Source: https://docs.facebetter.net/obs/faq What to do on a Mac when the Facebetter OBS plugin is missing, sliders will not move, or the preview does not change. ## Facebetter is missing from the panel and from the filter list Quit OBS completely and open it again. Then check that the plugin is here: ```text theme={null} ~/Library/Application Support/obs-studio/plugins/facebetter.plugin ``` An Intel Mac needs the Intel build of OBS. Apple silicon needs the Apple silicon build. OBS will not load the plugin if those do not match. See [Install on Mac](/obs/install). ## macOS says the plugin is damaged Open Terminal, paste this line, press Return, and open OBS again: ```bash theme={null} xattr -dr com.apple.quarantine ~/Library/Application\ Support/obs-studio/plugins/facebetter.plugin ``` ## Sliders are gray and will not move The filter is not on a source yet. The panel says you need to add a filter before the controls can be used. Right-click the source → Filters → + → Facebetter Beauty. You can still click the page titles to see what is there. The sliders unlock after the filter is added. See [Sign in and add the filter](/obs/login). ## The filter is added, but the preview does not change Check that the switch at the top of the panel is on, and that the source menu is the source you are looking at. If every slider is at 0, the picture looks like the original. Body effects need more of the person in frame. A face-only shot barely changes. What each page does is in [Adjust effects](/obs/effects). # FAQ Source: https://docs.facebetter.net/obs/faq-windows What to do on Windows when the Facebetter OBS plugin is missing, sliders will not move, or the preview does not change. ## Facebetter is missing from the panel and from the filter list Use 64-bit OBS Studio 28 or later. After you copy the folder, quit OBS completely and open it again. The plugin does not belong in `%APPDATA%\obs-studio\`. Confirm both files exist, with these names: ```text theme={null} C:\ProgramData\obs-studio\plugins\obs-facebetter\bin\64bit\obs-facebetter.dll C:\ProgramData\obs-studio\plugins\obs-facebetter\bin\64bit\facebetter.dll ``` Keep the `data` folder next to `bin`. See [Install on Windows](/obs/install-windows). ## Sliders are gray and will not move The filter is not on a source yet. The panel says you need to add a filter before the controls can be used. Right-click the source → Filters → + → Facebetter Beauty. You can still click the page titles to see what is there. The sliders unlock after the filter is added. See [Sign in and add the filter](/obs/login). ## The filter is added, but the preview does not change Check that the switch at the top of the panel is on, and that the source menu is the source you are looking at. If every slider is at 0, the picture looks like the original. Body effects need more of the person in frame. A face-only shot barely changes. What each page does is in [Adjust effects](/obs/effects). # Install on Mac Source: https://docs.facebetter.net/obs/install Install the Facebetter OBS plugin on a Mac. Facebetter is a realtime beauty filter for OBS Studio. Skin, face shape, makeup, color filters, stickers, body, and background are processed on this computer. It does not affect the whole OBS window by itself. Add **Facebetter Beauty** to the source you want, and the sliders in the side panel start working. A camera, image, or video source all work. The OBS screenshots on these pages use the English interface. The installer screenshots use Chinese macOS. The English names of those buttons are in the steps below. Before you start: * macOS 13 or later. Use the Intel build of OBS on an Intel Mac, and the Apple silicon build on Apple silicon. * OBS Studio 28 or later, 64-bit. Download: [facebetter.net/obs](https://facebetter.net/obs). For Windows, see [Install on Windows](/obs/install-windows). ## Download and unzip Download the macOS zip and double-click it. Inside are the installer `Facebetter-OBS-*-macos-universal.pkg` and two short guides, `README.zh.txt` and `README.en.txt`. ![Unzipped installer and readme files](https://mintcdn.com/facebetter/8-QG_hBISFqsZt9s/images/obs/pkg.png?fit=max\&auto=format\&n=8-QG_hBISFqsZt9s\&q=85\&s=68d6100a34993f54c2565446c870cb99) Quit OBS completely first, including the OBS icon in the menu bar. If OBS is running during install, that session will not load the new plugin. ## If macOS says the package cannot be opened The package is not notarized yet. The first double-click is often blocked. The dialog title is “未打开” (the package was not opened) and one button is “移到废纸篓” (Move to Trash). ![macOS cannot verify the package. Do not move it to the Trash.](https://mintcdn.com/facebetter/8-QG_hBISFqsZt9s/images/obs/gatekeeper.png?fit=max\&auto=format\&n=8-QG_hBISFqsZt9s\&q=85\&s=6fd5b0f39a16452fe0c97a88cd4d6d4e) > [!WARNING] > > Click Done (完成). Do not click Move to Trash (移到废纸篓). Then: 1. Open System Settings → Privacy & Security (系统设置 → 隐私与安全性). 2. Scroll to the Security section and find the row that says Facebetter was blocked to protect the Mac. 3. Click Open Anyway (仍要打开). ![Open Anyway in Privacy and Security](https://mintcdn.com/facebetter/8-QG_hBISFqsZt9s/images/obs/privacy.png?fit=max\&auto=format\&n=8-QG_hBISFqsZt9s\&q=85\&s=a176a1f4037583dbec919413e7e3012b) After you confirm, the installer continues. You can also Control-click the pkg, choose Open, and click Open again in the confirmation dialog. ## Finish the installer The first installer page is the introduction. Click Continue (继续). ![Installer introduction](https://mintcdn.com/facebetter/8-QG_hBISFqsZt9s/images/obs/install-intro.png?fit=max\&auto=format\&n=8-QG_hBISFqsZt9s\&q=85\&s=b1c41a48b0246358efdb877266a803e4) On the disk confirmation page, click Continue again. On Installation Type (安装类型), keep the default and click Install (安装). Do not click Change Install Location (更改安装位置). The plugin is installed for the current user only. Other accounts on this Mac are left alone. ![Installation type page. Click Install.](https://mintcdn.com/facebetter/8-QG_hBISFqsZt9s/images/obs/install-type.png?fit=max\&auto=format\&n=8-QG_hBISFqsZt9s\&q=85\&s=10564b986103e00a370d028baf0777e4) macOS may ask for your password or Touch ID. When it finishes, the plugin is here: ```text theme={null} ~/Library/Application Support/obs-studio/plugins/facebetter.plugin ``` Open OBS, then [sign in and add the filter](/obs/login). # Install on Windows Source: https://docs.facebetter.net/obs/install-windows Install the Facebetter OBS plugin on Windows. Facebetter is a realtime beauty filter for OBS Studio. Skin, face shape, makeup, color filters, stickers, body, and background are processed on this computer. It does not affect the whole OBS window by itself. Add **Facebetter Beauty** to the source you want, and the sliders in the side panel start working. A camera, image, or video source all work. Mac install steps are in [Install on Mac](/obs/install). After install, sign-in and adjustments are the same on both systems: [Sign in and add the filter](/obs/login). Before you start: * Windows 10 or Windows 11, 64-bit. * OBS Studio 28 or later, 64-bit. Download: [facebetter.net/obs](https://facebetter.net/obs) ## Quit OBS and unzip Quit OBS completely first. If OBS is running while you copy the plugin, that session will not load it. Download the Windows zip and unzip it. Inside is the whole `obs-facebetter` folder, plus short guides in Chinese and English. Copy that folder. Do not pull out a single DLL on its own. ## Copy it into the OBS plugin folder Copy the entire `obs-facebetter` folder to: ```text theme={null} C:\ProgramData\obs-studio\plugins\ ``` When the copy finishes, the plugin folder is: ```text theme={null} C:\ProgramData\obs-studio\plugins\obs-facebetter\ ``` `ProgramData` is hidden by default. In File Explorer, open View → Show → Hidden items. If Windows asks for permission while copying, allow it. This is the shared plugin folder on this PC. OBS loads plugins from here. Do not put the folder in `%APPDATA%\obs-studio\`. That location holds scenes and logs, not plugins. Both of these files must be present, with these names: ```text theme={null} C:\ProgramData\obs-studio\plugins\obs-facebetter\bin\64bit\obs-facebetter.dll C:\ProgramData\obs-studio\plugins\obs-facebetter\bin\64bit\facebetter.dll ``` Keep the `data` folder next to `bin`. It holds locales and resources. Open OBS, then [sign in and add the filter](/obs/login). # Sign in and add the filter Source: https://docs.facebetter.net/obs/login Sign in to Facebetter and add the beauty filter to an OBS source. [Install on macOS](/obs/install) or [install on Windows](/obs/install-windows) first, then sign in and attach the filter to a source. Sign-in, adding the filter, and adjusting effects work the same on macOS and Windows. The screenshots below are English OBS on a Mac. ## Sign in After OBS opens, the Facebetter panel sits on the right. If you do not see it, use **Tools → Facebetter**. The panel can stay docked next to the audio mixer. Before you sign in, the middle of the panel is the sign-in page. ![Facebetter panel on the right of OBS, before sign-in](https://mintcdn.com/facebetter/8-QG_hBISFqsZt9s/images/obs/login.png?fit=max\&auto=format\&n=8-QG_hBISFqsZt9s\&q=85\&s=b21350e52c05006a6fe5fe62aa0db6a4) 1. Click **Sign in**. If you do not have an account, click **Sign up** underneath. 2. The system browser opens the Facebetter authorization page. If you are already signed in on the website, the page shows that account and does not ask for the password again. 3. Click **Authorize OBS**. To use another account, click **Use a different account**. ![Authorize the current account for the OBS plugin](https://mintcdn.com/facebetter/8-QG_hBISFqsZt9s/images/obs/login-auth.png?fit=max\&auto=format\&n=8-QG_hBISFqsZt9s\&q=85\&s=f7db5b3231d2b9dc1b2737f4f1d3faf4) When authorization finishes, return to OBS. The free plan includes every effect. Output carries a `facebetter.net` watermark. ## Add the filter to a source Signing in does not beautify the picture. If the top of the panel says **No filter yet**, the sliders stay locked. Add the filter to a source first. The source does not have to be a camera. An image, a video, or a media source works the same way. ### Open Filters for that source In the Sources list, right-click the item you want to process and choose **Filters**. ![Right-click a source and choose Filters](https://mintcdn.com/facebetter/8-QG_hBISFqsZt9s/images/obs/add-filter.png?fit=max\&auto=format\&n=8-QG_hBISFqsZt9s\&q=85\&s=70888b0d5512803be59257f3b8a42be3) There is also a **Filters** button under the Sources list. Select the source, then click that button. ### Add Facebetter Beauty At the bottom left of the Filters window, click **+**, choose **Facebetter Beauty**, confirm the name, and close the window. ![Choose Facebetter Beauty in the filter list](https://mintcdn.com/facebetter/8-QG_hBISFqsZt9s/images/obs/add-beauty.png?fit=max\&auto=format\&n=8-QG_hBISFqsZt9s\&q=85\&s=bfb3c0e27390ab339926b8a3cec9e93e) Two things happen: * The Facebetter panel comes forward. To open it later, use **Tools → Facebetter**. * The source menu at the top of the panel changes from “No filter yet” to that source, or to **All sources**. The sliders can be dragged. The Filters window is not where you adjust the look. It has one sentence and an **Open Facebetter panel** button. Smoothing, whitening, and face shape are adjusted in the Facebetter panel on the right. If a scene has several pictures, add the filter once on each source you want to process. Next, drag the sliders in [Adjust effects](/obs/effects). If a slider is gray, see the [macOS FAQ](/obs/faq) or the [Windows FAQ](/obs/faq-windows). # API Reference Source: https://docs.facebetter.net/web/api-reference Facebetter Web SDK 2.0 API > [!NOTE] > > This page matches SDK **2.0.0**. Makeup / reshape / style enums: [Parameter enums](/intro/makeup). Auth: [Auth & License](/intro/license). Package: **`facebetter`**. Typical import: ```javascript theme={null} import { BeautyEffectEngine, EngineConfig, FrameType, MirrorMode, Reshape, } from 'facebetter'; ``` ## EngineConfig ```javascript theme={null} new EngineConfig({ licenseToken, // string — required. License token string, or `{token}` JSON }) ``` Web **does not** accept `appId` / `appKey` on this object. An offline `.lic` must match the page origin. Electron does not check origin. `isValid()` is true when `licenseToken` is a non-empty string. Fetch the token from **your server** **before** `init()`. See [Auth & License](/intro/license). ## BeautyEffectEngine ```javascript theme={null} const engine = new BeautyEffectEngine(config); await engine.init({ onProgress: ({ percent }) => { // 0–100 while runtime files download }, }); ``` ### Lifecycle | Method | Description | | - | - | | `init(options?)` | Initialize the engine (auth and resources). `options.timeout` (default `120000`) is the init timeout in ms. `options.onProgress({ loaded, total, percent })` reports **download** progress of the runtime files. | | `setLogConfig({ consoleEnabled, fileEnabled, level, fileName })` | Global log config. Call before `init()`. `level`: `0` TRACE … `5` CRITICAL. File logging is not supported in the browser. Returns `Promise`. | | `destroy()` | Release the engine and its resources. | `engine.initialized` is `true` after a successful `init()`. ### Skin | Method | Range | | - | - | | `setSmoothing(value)` | `[0, 1]` | | `setSmoothingStyle(style)` | `SmoothingStyle` | | `setWhitening(value)` | `[0, 1]` | | `setWhiteningStyle(style)` | `WhiteningStyle` | | `setRosiness(value)` | `[0, 1]` | | `setBrightness(value)` | `[-1, 1]` | | `setContrast(value)` | `[-1, 1]` | | `setSaturation(value)` | `[-1, 1]` | | `setColorTemperature(value)` | `[-1, 1]` | | `setColorTint(value)` | `[-1, 1]` | | `setClarity(value)` | `[0, 1]` | | `setBeautySkinOnly(enabled)` | `boolean` | ### Reshape `setReshape(param, value)` — `param` is `Reshape.*`, `value` in **`[-1.0, 1.0]`**. See [Parameter enums](/intro/makeup). ### Body reshape `setBodyReshape(param, value)` — `param` is `BodyReshape.*`, `value` in **`[0.0, 1.0]`**. Requires `resource_body.fbd` via `addResourcePack` first. See [Parameter enums](/intro/makeup) and [Optional resource packs](/intro/resource-packs). ### Makeup Intensity `[0, 1]`. Style / color enums: [Parameter enums](/intro/makeup). | Intensity | Style / color | | - | - | | `setLipstick` | `setLipstickColor` | | `setBlush` | `setBlushStyle`, `setBlushColor` | | `setContour` | `setContourStyle` | | `setEyeShadow` | `setEyeShadowStyle`, `setEyeShadowColor` | | `setEyeLiner` | `setEyeLinerStyle`, `setEyeLinerColor` | | `setEyebrow` | `setEyebrowStyle`, `setEyebrowColor` | | `setEyelash` | `setEyelashStyle`, `setEyelashColor` | | `setPupil` | `setPupilColor` | | `setTeethWhiten` | — | ### Filter / sticker | Method | Description | | - | - | | `setFilter(path \| Uint8Array)` | Apply a LUT `.fbd` from URL or bytes | | `clearFilter()` | Remove the current filter | | `setFilterIntensity(intensity)` | `[0, 1]` | | `setSticker(path \| Uint8Array)` | Apply a 2D sticker `.fbd` | | `clearSticker()` | Remove the sticker | | `addResourcePack(path \| Uint8Array)` | Register an extra capability pack (`resource_3d.fbd` before `set3DSticker`, or `resource_body.fbd` before `setBodyReshape`) | | `set3DSticker(path \| Uint8Array)` | Apply a 3D sticker `.fbd` | | `clear3DSticker()` | Remove the 3D sticker | ### Virtual background / chroma key | Method | Description | | - | - | | `setVirtualBackgroundBlur(level)` | Continuous blur `[0, 1]`. `0` clears it | | `setVirtualBackground(path \| Uint8Array)` | png/jpg path or encoded bytes | | `clearVirtualBackground()` | Turn off blur / image | | `setChromaKey(color)` | `ChromaKeyColor.Green` / `Blue` / `Red` | | `clearChromaKey()` | Back to portrait-segmentation mask | | `setChromaKeySimilarity(value)` | `[0, 1]` | | `setChromaKeySmoothness(value)` | `[0, 1]` | | `setChromaKeyDesaturation(value)` | `[0, 1]` | ### Callbacks ```javascript theme={null} engine.setCallbacks({ onEngineEvent, // (code, message) => void }); ``` ### Processing ```javascript theme={null} processImage(input, width, height, frameType = FrameType.Video, mirrorMode = MirrorMode.None) → ImageData ``` * `input`: `ImageData` | `HTMLImageElement` | `HTMLCanvasElement` | `HTMLVideoElement` | `Uint8ClampedArray` * `width` / `height` required only for `Uint8ClampedArray` * `mirrorMode` mirrors this CPU image before processing. Web has no rotate API. `processTexture` does not mirror or rotate. ```javascript theme={null} processTexture(textureHandle, width, height, stride, frameType, mirrorMode) → number ``` Returns an output `GL_TEXTURE_2D` handle. **This path does not mirror or rotate.** Prefer `processImage`. ### Stats ```javascript theme={null} engine.getStats() → { fps, avgProcessTimeMs, sessionTimeS, gpuLiveTextures, gpuLiveMeshes } ``` ## Enums (JS) Values match native. Full makeup / reshape tables: [Parameter enums](/intro/makeup). ```javascript theme={null} FrameType = { Image: 0, Video: 1 } MirrorMode = { None: 0, Horizontal: 1, Vertical: 2, Both: 3 } EngineEventCode = { LicenseValidationSuccess: 0, LicenseValidationFailed: 1, InitializationComplete: 100, InitializationFailed: 101, } ChromaKeyColor = { Green: 0, Blue: 1, Red: 2 } Reshape = { FaceThin: 0, FaceVShape: 1, /* … BrowThickness: 25 */ } ``` Also exported: `SmoothingStyle`, `WhiteningStyle`, `LipstickColor`, `BlushStyle`, `BlushColor`, `ContourStyle`, `EyeShadowStyle`, `EyeShadowColor`, `EyeLinerStyle`, `EyeLinerColor`, `EyebrowStyle`, `EyebrowColor`, `EyelashStyle`, `EyelashColor`, `PupilColor`. ## FacebetterError ```javascript theme={null} class FacebetterError extends Error { constructor(message, code = -1) // name === 'FacebetterError' // code: number or string } ``` Numeric codes: `0`, `-1` … `-7`. See [Error handling](/web/error-handling). # Best Practices Source: https://docs.facebetter.net/web/best-practices Facebetter Web SDK 2.0 performance and security > [!NOTE] > > SDK **2.0.0**. Auth: [Auth & License](/intro/license). ## Auth in production Keep `app_id` / `app_key` on the server. Fetch a short-lived `licenseToken` from **your** backend, then pass it to the engine. ```javascript theme={null} const licenseToken = await fetch('/api/facebetter/auth', { method: 'POST' }).then((r) => r.text()); const engine = new BeautyEffectEngine(new EngineConfig({ licenseToken })); ``` > [!WARNING] > > Never put `appKey` in a frontend bundle. Bind the exact page origin in the Dashboard, for example `https://app.example.com`. Electron does not check origin. ## One engine per page Create **one** `BeautyEffectEngine`, call `init()` once, reuse it for the session. Do not construct a new engine every frame. ```javascript theme={null} useEffect(() => { let engine; (async () => { engine = new BeautyEffectEngine(new EngineConfig({ licenseToken })); await engine.init(); engineRef.current = engine; })(); return () => { engineRef.current?.destroy(); engineRef.current = null; }; }, []); ``` ## Frame loop * Drive video with `requestAnimationFrame`, not an unbounded `while`. * Use `FrameType.Video` for camera; `FrameType.Image` for stills. * Match canvas size to the processed `ImageData` to avoid extra scaling. * Skip frames until `video.readyState >= 2` and `videoWidth > 0`. * Prefer `processImage` for camera and canvas. `processTexture` does not apply mirror. ```javascript theme={null} const result = engine.processImage( video, video.videoWidth, video.videoHeight, FrameType.Video, MirrorMode.Horizontal, ); ctx.putImageData(result, 0, 0); ``` ## Large stills (preview vs export) For gallery photos and retouching apps, do not send full-resolution pixels into `processImage` on every slider change. When the file opens, keep two buffers: 1. **Preview frame** — a downscaled `ImageData` (long edge about 1280–1440, or the display canvas CSS size × `devicePixelRatio`, whichever is smaller). Use this while the user adjusts effects. 2. **Original** — the `HTMLImageElement` (or an unscaled bitmap). Run `processImage` on it **once**, when the user exports. Use `FrameType.Image` for both. Same engine, same setters. Output size matches input size: preview output is small; export output is full resolution. Do not upscale the preview result to fake an export. Do not pass an unscaled `` into the preview loop — `processImage` reads `naturalWidth` / `naturalHeight`. ```javascript theme={null} function rasterize(source, maxEdge) { const sw = source.naturalWidth || source.width; const sh = source.naturalHeight || source.height; const scale = Math.min(1, maxEdge / Math.max(sw, sh)); const w = Math.max(1, Math.round(sw * scale)); const h = Math.max(1, Math.round(sh * scale)); const canvas = document.createElement('canvas'); canvas.width = w; canvas.height = h; const ctx = canvas.getContext('2d'); ctx.drawImage(source, 0, 0, w, h); return ctx.getImageData(0, 0, w, h); } const preview = rasterize(image, 1440); // once, when the file opens // Keep `image` for export const previewOut = engine.processImage( preview, preview.width, preview.height, FrameType.Image, ); previewCtx.putImageData(previewOut, 0, 0); // Export — full resolution, once const exportOut = engine.processImage( image, image.naturalWidth, image.naturalHeight, FrameType.Image, ); ``` Camera preview is a different path: capture resolution + `FrameType.Video`. Debounce slider-driven `processImage`. Show a busy state before export; full-resolution processing is synchronous and can hitch the page. ## Parameters Start low in real-time preview (`smoothing` \~ `0.2`–`0.5`). Reshape is `[-1, 1]`; small values look more natural on camera. `setBeautySkinOnly(true)` avoids smearing backgrounds when smoothing is high. ## Resources * Host filter / sticker `.fbd` and background jpg/png as static files; pass the URL into `setFilter` / `setSticker` / `setVirtualBackground`. * Runtime resources are loaded by the SDK during `init()`. Do not put a site-root `resource.fbd` for the engine. * Switch filter / sticker on user input, not every frame. ## Memory * Call `destroy()` on unmount / `beforeunload`. * Reuse the display canvas; do not allocate a new canvas per frame. ## HTTPS and CORS Camera access needs HTTPS or localhost. If filter / sticker assets are on another origin, send CORS headers. ## Related * [Error handling](/web/error-handling) * [FAQ](/web/faq) * [API reference](/web/api-reference) # Error Handling Source: https://docs.facebetter.net/web/error-handling Facebetter Web SDK 2.0 errors > [!NOTE] > > SDK **2.0.0**. Auth failures: [Auth & License](/intro/license). Failed calls throw `FacebetterError`. Numeric `code` values are listed below. Some load / auth failures use a **string** `code` instead. ```javascript theme={null} import { BeautyEffectEngine, EngineConfig, FacebetterError } from 'facebetter'; try { const licenseToken = await fetch('/api/facebetter/auth', { method: 'POST' }).then((r) => r.text()); const engine = new BeautyEffectEngine(new EngineConfig({ licenseToken })); await engine.init(); engine.setSmoothing(0.5); } catch (error) { if (error instanceof FacebetterError) { console.error(error.code, error.message); } else { console.error(error); } } ``` ## Numeric codes | Code | Meaning | | - | - | | `0` | Success (`checkResult` does not throw) | | `-1` | Invalid argument (null, empty path, out-of-range intensity, …) | | `-2` | Engine not initialized or already destroyed | | `-3` | License invalid | | `-4` | Unsupported platform / format | | `-5` | I/O (resource / filter / sticker / background file) | | `-6` | Processing failed | | `-7` | Out of memory | ## JavaScript-layer codes (string) These are thrown during `init()` / load / auth: | `error.code` | When | | - | - | | `'TIMEOUT'` | `init()` timed out | | `'NETWORK_ERROR'` | Fetch / network failure | | `'WASM_LOAD_ERROR'` | SDK failed to load (network, CDN, or ad blocker) | | `'LICENSE_ERROR'` | Missing `licenseToken`, or the token was rejected | | `'ENGINE_CREATE_FAILED'` | Engine failed to create | | `'UNKNOWN_ERROR'` | Unclassified JS exception wrapped as `FacebetterError` | ```javascript theme={null} try { await engine.init({ timeout: 30000 }); } catch (error) { if (!(error instanceof FacebetterError)) throw error; if (error.code === 'LICENSE_ERROR' || error.code === -3) { // token missing, expired, or domain not bound — see /intro/license } else if (error.code === 'WASM_LOAD_ERROR' || error.code === 'TIMEOUT') { // network, CDN, or ad blocker } } ``` ## Init checklist 1. Config is valid: non-empty `licenseToken`. 2. The SDK can download its runtime files (`facebetter-core` package, or files next to the UMD script). 3. Page is a [secure context](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts). 4. Dashboard domain matches the page origin (production). 5. Production does **not** embed `appKey` in frontend JS. ## Parameter and process errors Beauty intensities must be `[0.0, 1.0]`. Reshape must be `[-1.0, 1.0]`. Out of range throws `FacebetterError` before the native call. `processImage` throws if the engine is not initialized, buffers cannot be allocated, or the native process returns a non-zero status. Validate video `readyState` and non-zero `videoWidth` / `videoHeight` before calling. Empty filter / sticker / background **paths** are rejected; use `clearFilter()`, `clearSticker()`, or `clearVirtualBackground()`. ## Engine events vs exceptions Auth / init can also arrive on `onEngineEvent` (`EngineEventCode` `0` / `1` / `100` / `101`) after `init()` has already resolved. Listen for `LicenseValidationFailed` and `InitializationFailed` even if `init()` did not throw. ## Related * [Implement beauty](/web/implement-beauty) * [FAQ](/web/faq) * [API reference](/web/api-reference) # FAQ Source: https://docs.facebetter.net/web/faq Facebetter Web SDK 2.0 FAQ > [!NOTE] > > SDK **2.0.0**. Auth: [Auth & License](/intro/license). Enums: [Parameter enums](/intro/makeup). ## Integration ### Engine create / `init()` failed * `EngineConfig` must set a non-empty `licenseToken`. There are no `appId` / `appKey` fields on Web config. * Production: your server must return the auth API body (`{success, token}` or error JSON). See [Auth & License](/intro/license). * Confirm the page can download the SDK runtime files (bundler / CDN). See [Error handling](/web/error-handling). * Confirm the page is HTTPS or localhost. * Check `FacebetterError.code` ([Error handling](/web/error-handling)). ### How do I pass AppID / AppKey? You don't — not on `EngineConfig`. Hold them on the server, fetch a token, and pass `licenseToken`. ### Can I use an offline `.lic` in the browser? Yes, if the license origin matches the page, for example `https://app.example.com`. Electron does not check origin. ### How do I update the package? ```bash theme={null} npm install facebetter@2.0.0 ``` ## Effects ### Beauty looks weak or too strong Intensities are `[0.0, 1.0]`. Reshape is `[-1.0, 1.0]` (`0` = off). Try `FrameType.Image` for stills. Style enums: [Parameter enums](/intro/makeup). ### Filter / sticker does nothing Pass the `.fbd` **path or bytes** directly to `setFilter` / `setSticker`. Empty string throws — call `clearFilter()` / `clearSticker()`. ### Virtual background is blank Call `setVirtualBackgroundBlur(level)` or `setVirtualBackground(path|Uint8Array)`, not a options object. `0` blur clears the effect. For green screen, `setChromaKey` only sets the mask; still set blur or an image. ### Output is black Video may not have a frame yet (`videoWidth === 0`). Canvas context missing. Call `processImage` only after `engine.initialized`. ## Performance ### Preview is slow Camera: use `FrameType.Video`, cap capture resolution (for example 720p), and run the loop in `requestAnimationFrame`. Watch `engine.getStats().avgProcessTimeMs`. For large gallery stills, do not send the original into `processImage` on every slider tick. Build a smaller preview frame when the file opens; export the original once. See [Best practices](/web/best-practices#large-stills). ### Memory grows in an SPA Call `engine.destroy()` when leaving the page. Do not leak engines across route changes. ## Compatibility Supported: Chrome 57+, Firefox 52+, Safari 11+, Edge 16+. On mobile, lower capture resolution and effect intensities. ## React example ```jsx theme={null} import { useEffect, useRef } from 'react'; import { BeautyEffectEngine, EngineConfig } from 'facebetter'; function BeautyPreview() { const engineRef = useRef(null); useEffect(() => { let engine; (async () => { const licenseToken = await fetch('/api/facebetter/auth', { method: 'POST' }).then((r) => r.text()); engine = new BeautyEffectEngine(new EngineConfig({ licenseToken })); engineRef.current = engine; await engine.init(); })().catch(console.error); return () => { engine?.destroy(); engineRef.current = null; }; }, []); return ; } ``` Full sample: `demo/web/react` in the SDK repo. ## Related * [Quick start](/web/quick-start) * [Implement beauty](/web/implement-beauty) * [Error handling](/web/error-handling) * [Best practices](/web/best-practices) * [API reference](/web/api-reference) # Implement Beauty Source: https://docs.facebetter.net/web/implement-beauty Integrate Facebetter Web SDK 2.0 > [!NOTE] > > SDK **2.0.0**. Auth: [Auth & License](/intro/license). Enum values: [Parameter enums](/intro/makeup). ## Install ```bash theme={null} npm install facebetter ``` ```javascript theme={null} import { BeautyEffectEngine, EngineConfig, FrameType, MirrorMode, Reshape, SmoothingStyle, WhiteningStyle, LipstickColor, ChromaKeyColor, EngineEventCode, FacebetterError, } from 'facebetter'; ``` ## Create the engine `EngineConfig` on Web has **only** these fields. There is no `appId` / `appKey` on the config object. | Field | Purpose | | - | - | | `licenseToken` | License token string, or `{token}` JSON. **Required.** Fetch it before `init()`. | The SDK loads runtime files during `init()`. You do not host a site-root `resource.fbd` for the engine. Optional download progress: `init({ onProgress })`. The engine does not fetch tokens. An offline `.lic` must match the page origin. Electron does not check origin. ```javascript theme={null} const licenseToken = await fetch('/api/facebetter/auth', { method: 'POST' }).then((r) => r.text()); const engine = new BeautyEffectEngine(new EngineConfig({ licenseToken })); await engine.setLogConfig({ consoleEnabled: true, fileEnabled: false, level: 2, // TRACE=0 … CRITICAL=5 }); await engine.init(); ``` > [!WARNING] > > Call `setLogConfig` before `init()` if you want to see load / auth logs. File logging is not supported in the browser (`fileEnabled` is ignored). ```javascript theme={null} try { await engine.init(); } catch (error) { if (error instanceof FacebetterError) { console.error(error.code, error.message); } throw error; } ``` ## Skin beauty Intensity range **`[0.0, 1.0]`**. `0` turns the effect off. ```javascript theme={null} engine.setSmoothing(0.8); engine.setSmoothingStyle(SmoothingStyle.Natural); engine.setWhitening(0.5); engine.setWhiteningStyle(WhiteningStyle.ColdWhite); engine.setRosiness(0.2); engine.setBeautySkinOnly(true); ``` > [!TIP] > > `setBeautySkinOnly(true)` limits smoothing / whitening / rosiness to detected skin. Clothing and background stay unchanged. Style enums: [Parameter enums](/intro/makeup). ## Face reshape ```javascript theme={null} engine.setReshape(Reshape.FaceThin, 0.3); engine.setReshape(Reshape.EyeSize, 0.2); ``` Range is **`[-1.0, 1.0]`**. `0` is off. Positive and negative are opposite directions (for example `FaceThin`: slim / fuller cheeks). Full list: [Parameter enums](/intro/makeup). ## Body reshape ```javascript theme={null} const bodyPack = new Uint8Array( await (await fetch('/resource_body.fbd')).arrayBuffer() ); engine.addResourcePack(bodyPack); engine.setBodyReshape(BodyReshape.WaistSlim, 0.4); engine.setBodyReshape(BodyReshape.LegStretch, 0.3); engine.setBodyReshape(BodyReshape.TorsoLong, 0.3); ``` Range is **`[0.0, 1.0]`**. `0` is off. Fetch `resource_body.fbd` and call `addResourcePack` after `init()` first. Full list: [Parameter enums](/intro/makeup). Packs: [Optional resource packs](/intro/resource-packs). ## Makeup Intensity, shape, and color are separate setters. Intensity is `[0.0, 1.0]`. Presets: [Parameter enums](/intro/makeup). ```javascript theme={null} engine.setLipstick(0.4); engine.setLipstickColor(LipstickColor.Rouge); engine.setBlush(0.3); engine.setBlushStyle(/* BlushStyle.SunKissed */); engine.setBlushColor(/* BlushColor.CoralPink */); engine.setContour(0.4); engine.setContourStyle(/* ContourStyle.Natural */); engine.setEyeShadow(0.35); engine.setEyeShadowStyle(/* EyeShadowStyle.Soft */); engine.setEyeShadowColor(/* EyeShadowColor.Plum */); engine.setEyeLiner(0.3); engine.setEyeLinerStyle(/* ... */); engine.setEyeLinerColor(/* ... */); engine.setEyebrow(0.3); engine.setEyebrowStyle(/* ... */); engine.setEyebrowColor(/* ... */); engine.setEyelash(0.3); engine.setEyelashStyle(/* ... */); engine.setEyelashColor(/* ... */); engine.setPupil(0.4); engine.setPupilColor(/* PupilColor.Hazel */); ``` ## Filters and stickers Pass a `.fbd` URL or in-memory `Uint8Array` directly to the setter. ```javascript theme={null} engine.setFilter('/assets/filters/portrait/natural/natural.fbd'); engine.setFilterIntensity(0.8); engine.clearFilter(); engine.setSticker('/stickers/face/fox.fbd'); engine.clearSticker(); ``` 3D stickers need the optional `resource_3d.fbd` pack (not in the Web SDK). See [Optional resource packs](/intro/resource-packs). Fetch bytes and register them after `init()`: ```javascript theme={null} const pack = new Uint8Array( await (await fetch('/resource_3d.fbd')).arrayBuffer() ); engine.addResourcePack(pack); engine.set3DSticker('/stickers/3d/oculos.fbd'); engine.clear3DSticker(); ``` ```javascript theme={null} const bytes = new Uint8Array(await (await fetch('/filters/chuxin.fbd')).arrayBuffer()); engine.setFilter(bytes); ``` ## Virtual background and chroma key ```javascript theme={null} engine.setVirtualBackgroundBlur(0.6); // [0, 1]; 0 clears blur engine.setVirtualBackground('/background.jpg'); // path or Uint8Array (png/jpg) engine.clearVirtualBackground(); engine.setChromaKey(ChromaKeyColor.Green); engine.setChromaKeySimilarity(0.4); engine.setChromaKeySmoothness(0.2); engine.setChromaKeyDesaturation(0.3); engine.clearChromaKey(); ``` > [!TIP] > > Chroma key only replaces the **mask**. Fill is still `setVirtualBackgroundBlur` or `setVirtualBackground`. Blur and image replacement are mutually exclusive. ## Callbacks ```javascript theme={null} engine.setCallbacks({ onEngineEvent: (code, message) => { if (code === EngineEventCode.LicenseValidationSuccess) { console.log('license ok'); } else if (code === EngineEventCode.LicenseValidationFailed) { console.error('license failed', message); } else if (code === EngineEventCode.InitializationComplete) { console.log('engine ready'); } else if (code === EngineEventCode.InitializationFailed) { console.error('init failed', message); } }, }); ``` | Code | Name | | - | - | | `0` | `EngineEventCode.LicenseValidationSuccess` | | `1` | `EngineEventCode.LicenseValidationFailed` | | `100` | `EngineEventCode.InitializationComplete` | | `101` | `EngineEventCode.InitializationFailed` | ## Process frames Prefer `processImage`. It returns `ImageData` synchronously. ```javascript theme={null} const canvas = document.querySelector('canvas'); const ctx = canvas.getContext('2d'); const video = document.querySelector('video'); function loop() { if (engine.initialized && video.readyState >= 2) { const result = engine.processImage( video, video.videoWidth, video.videoHeight, FrameType.Video, MirrorMode.Horizontal, // front camera ); if (result) { if (canvas.width !== result.width) canvas.width = result.width; if (canvas.height !== result.height) canvas.height = result.height; ctx.putImageData(result, 0, 0); } } requestAnimationFrame(loop); } loop(); ``` `input` may be `ImageData`, `HTMLImageElement`, `HTMLCanvasElement`, `HTMLVideoElement`, or `Uint8ClampedArray` (then `width` / `height` are required). * `FrameType.Video` — live camera / streaming (temporal smoothing) * `FrameType.Image` — still photos `processTexture(textureHandle, width, height, stride, frameType, mirrorMode)` is for custom GPU texture input. **This path does not mirror or rotate.** Typical web apps should use `processImage`. ## Stats ```javascript theme={null} const { fps, avgProcessTimeMs, sessionTimeS } = engine.getStats(); ``` ## Destroy ```javascript theme={null} engine.destroy(); ``` Call this on page unload or when a React/Vue component unmounts. For TRTC / Agora / LiveKit: [Third-party Integration](/web/third-party-integration). ## Related * [Third-party Integration](/web/third-party-integration) * [Error handling](/web/error-handling) * [Best practices](/web/best-practices) * [API reference](/web/api-reference) * [FAQ](/web/faq) # Quick Start Source: https://docs.facebetter.net/web/quick-start Run the Facebetter Web SDK 2.0 example > [!NOTE] > > This page matches SDK **2.0.0**. Auth: [Auth & License](/intro/license). Makeup / reshape enums: [Parameter enums](/intro/makeup). ## Requirements * **Browser**: Chrome 57+, Firefox 52+, Safari 11+, Edge 16+ * **Language**: JavaScript (ES6+) or TypeScript * **Context**: HTTPS or `localhost` (required for camera) ## Install SDK ```bash theme={null} npm install facebetter ``` ```javascript theme={null} import { BeautyEffectEngine, EngineConfig, FrameType, MirrorMode, Reshape, } from 'facebetter'; ``` ## Get the example Clone the [GitHub repository](https://github.com/pixpark/facebetter-sdk) and open `demo/web/react`: ```bash theme={null} git clone https://github.com/pixpark/facebetter-sdk.git cd demo/web/react ``` The demo is a Vite + React app. It depends on the in-repo SDK via `file:` during development. ## Bind domain and get credentials 1. In the Dashboard, bind your Web **domain** (for example `example.com`). See [Subscription](/intro/enable-service). 2. Copy `appId` / `appKey` from the Dashboard. **Do not put them on `EngineConfig`.** On Web they belong on your **server**. Web has **no** offline `.lic`. Details: [Auth & License](/intro/license). ## Configure the demo The demo **does not put keys in the page**. The page calls your proxy at `/api/facebetter/auth` (`src/fetchLicenseToken.js`) and passes the response into the engine. The production proxy lives in `api/facebetter/auth.js`; during local `vite` that path is forwarded to the deployed demo proxy. ```javascript theme={null} const licenseToken = await fetch('/api/facebetter/auth', { method: 'POST' }).then((r) => r.text()); const engine = new BeautyEffectEngine(new EngineConfig({ licenseToken })); await engine.init(); ``` In production, implement the same proxy on **your** server. Full steps and a Node example: [Auth & License](/intro/license). The SDK loads runtime files during `init()`. You do **not** need to copy `resource.fbd` into `public/`. Optional: `init({ onProgress })` reports download percent. 3D stickers need `resource_3d.fbd`; body reshape needs `resource_body.fbd` — see [Optional resource packs](/intro/resource-packs). ## Run ```bash theme={null} npm install npm run dev ``` Open the URL Vite prints (usually `http://localhost:5175`). ## Verify 1. Open DevTools (F12) and watch the console. 2. Allow camera if prompted. 3. Drag beauty sliders — you should see skin smoothing / reshape on the preview. ## Minimal production init ```javascript theme={null} import { BeautyEffectEngine, EngineConfig } from 'facebetter'; const licenseToken = await fetch('/api/facebetter/auth', { method: 'POST' }).then((r) => r.text()); const engine = new BeautyEffectEngine(new EngineConfig({ licenseToken })); await engine.init(); ``` Your server holds `app_id` / `app_key` and returns a token. Example server code is on [Auth & License](/intro/license). # Third-party Integration Source: https://docs.facebetter.net/web/third-party-integration Wire Facebetter beauty into TRTC, Agora, LiveKit, and other browser realtime pipelines SDK **2.0.0**. The Web SDK has **no** native-style unified “GL texture preprocess callback”. Use this pipeline instead: **Capture → `processImage` → draw to canvas → `captureStream` / take a `MediaStreamTrack` → hand it to the third-party SDK (`replaceTrack` or a custom video track).** Auth uses `licenseToken` only. Fetch it from your server before `init()`. **Never** embed `appKey` in frontend JS. See [Auth & License](/intro/license) and [Implement Beauty](/web/implement-beauty). ``` getUserMedia / vendor preview track ↓ HTMLVideoElement ↓ BeautyEffectEngine.processImage(...) ↓ canvas + putImageData ↓ canvas.captureStream() → MediaStreamTrack ↓ TRTC / Agora / LiveKit publish or replaceTrack ``` ## Recommended pipeline (vendor-agnostic) ```javascript theme={null} import { BeautyEffectEngine, EngineConfig, FrameType, MirrorMode, } from 'facebetter'; const engine = new BeautyEffectEngine(new EngineConfig({ licenseToken: await fetch('/api/facebetter/auth', { method: 'POST' }).then((r) => r.text()), })); await engine.setLogConfig({ consoleEnabled: true, level: 2 }); await engine.init(); const video = document.createElement('video'); video.playsInline = true; video.muted = true; video.srcObject = await navigator.mediaDevices.getUserMedia({ video: { width: 1280, height: 720 }, audio: false, }); await video.play(); const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); function loop() { if (engine.initialized && video.readyState >= 2 && video.videoWidth > 0) { const result = engine.processImage( video, video.videoWidth, video.videoHeight, FrameType.Video, MirrorMode.Horizontal, // front camera as needed ); if (result) { if (canvas.width !== result.width) canvas.width = result.width; if (canvas.height !== result.height) canvas.height = result.height; ctx.putImageData(result, 0, 0); } } requestAnimationFrame(loop); } loop(); // Beauty video track — pass to any RTC / meeting SDK const beautyStream = canvas.captureStream(30); const beautyTrack = beautyStream.getVideoTracks()[0]; ``` > [!TIP] > > Prefer `processImage`. `processTexture` is for existing GPU texture handles and **does not apply mirror**. For live preview / publish, use the canvas pipeline above. On page unload: `beautyTrack.stop()`, cancel `requestAnimationFrame`, and `engine.destroy()`. *** ## Hook into third-party SDKs Vendor Web APIs change across versions. Below is only how to **feed `beautyTrack` in**; join, tokens, and device picking stay in their docs. ### TRTC (Tencent Web) Two common patterns (check your `trtc-js-sdk` / TUI version): 1. **Create the local stream from the beauty track** (custom video source / pass a `MediaStreamTrack`) 2. **Create a camera stream first, then `replaceTrack(beautyTrack)`** ```javascript theme={null} // Sketch: replace the video track on a local stream // const localStream = TRTC.createStream({ ... }); // await localStream.initialize(); // await localStream.replaceTrack(beautyTrack); // await client.publish(localStream); ``` Do not assume a native-style `onProcessVideoFrame(textureId)` exists on Web. ### Agora Web Use a **custom video track** or `replaceTrack` on an existing track: ```javascript theme={null} import AgoraRTC from 'agora-rtc-sdk-ng'; // A: custom video track from MediaStreamTrack (API name per agora-rtc-sdk-ng) const customVideoTrack = AgoraRTC.createCustomVideoTrack({ mediaStreamTrack: beautyTrack, }); await client.publish([customVideoTrack /*, microphoneTrack */]); // B: already have a camera track // await cameraTrack.replaceTrack(beautyTrack); ``` ### LiveKit Web Pass the processed track into LiveKit’s local video track factory, or replace on a published track: ```javascript theme={null} import { Room, LocalVideoTrack, createLocalVideoTrack } from 'livekit-client'; // Sketch: create from MediaStreamTrack and publish (factory name per livekit-client) const track = LocalVideoTrack.createFromMediaStreamTrack(beautyTrack); await room.localParticipant.publishTrack(track); // Or on an existing LocalVideoTrack: // await localVideoTrack.replaceTrack(beautyTrack); ``` *** ## Notes | Item | Detail | | - | - | | Auth | Fetch `licenseToken` from your server | | Perf | Reuse one canvas; cap `captureStream` FPS; do not allocate a new canvas every frame | | Audio | Example is video-only; take the mic from a separate `getUserMedia({ audio: true })` and publish it | | Mirror | Preview can use `MirrorMode` in `processImage`; decide whether encode should match | | Vendor churn | `replaceTrack` / `createCustomVideoTrack` signatures change — follow the current Web SDK | ## Troubleshooting | Symptom | Check | | - | - | | Black frame | `video.videoWidth === 0`, forgot `await engine.init()`, canvas size not updated | | Remote has no beauty | You published **beautyTrack**, not the raw camera track | | Auth failure | Proxy returns the auth body verbatim; domain bound in the Dashboard | | Stutter | Lower resolution / FPS; ensure a single `processImage` loop | ## Related * [Implement Beauty](/web/implement-beauty) * [Best Practices](/web/best-practices) * [Error Handling](/web/error-handling) * [Auth & License](/intro/license) * [API Reference](/web/api-reference) # API Reference Source: https://docs.facebetter.net/windows/api-reference Beauty Effect SDK 2.0 C++ API for Windows > [!NOTE] > > SDK **2.0.0**. Namespace `facebetter`. Headers: `facebetter/beauty_effect_engine.h`, `beauty_params.h`, `image_frame.h`, `type_defines.h`. Style / color / reshape enums: [Parameter enums](/intro/makeup). Auth: [Auth & License](/intro/license). ## Logging ### `LogLevel` ```cpp theme={null} enum class LogLevel { Trace = 0, Debug, Info, Warn, Error, Critical }; ``` ### `LogConfig` | Field | Default | Description | | - | - | - | | `console_enabled` | `false` | stdout | | `file_enabled` | `false` | write a file | | `level` | `Info` | minimum level | | `file_name` | `""` | path when `file_enabled` is true | ```cpp theme={null} struct LogConfig { bool console_enabled = false; bool file_enabled = false; LogLevel level = LogLevel::Info; std::string file_name = ""; }; ``` *** ## Engine ### `EngineConfig` | Field | Description | | - | - | | `app_id` | Dashboard app ID (online v2 auth with `app_key`) | | `app_key` | Dashboard app key | | `resource_path` | **Path to the `resource.fbd` file** (required on desktop) | | `license_token` | License token string, `{token}` JSON, or offline `.lic` contents | **Auth priority:** if `license_token` is non-empty, validate that token locally and skip `app_id` + `app_key` network auth. Otherwise use `app_id` + `app_key` against `/facebetter/v2/auth`. ```cpp theme={null} struct EngineConfig { std::string app_id; std::string app_key; std::string resource_path; std::string license_token; }; ``` ### `BeautyEffectEngine` Non-copyable. Create with `Create`; destroy by releasing the `shared_ptr`. #### `SetLogConfig` (static) ```cpp theme={null} static int SetLogConfig(const LogConfig& config); ``` Call **before** `Create`. Returns `0` on success. #### `Create` (static) ```cpp theme={null} static std::shared_ptr Create(const EngineConfig& config); ``` Returns `nullptr` on failure. ```cpp theme={null} EngineConfig cfg; cfg.app_id = "your_app_id"; cfg.app_key = "your_app_key"; cfg.resource_path = "resource/resource.fbd"; auto engine = BeautyEffectEngine::Create(cfg); ``` *** ### Skin Intensities `[0.0, 1.0]` unless noted. `0` is off. Returns `0` on success. ```cpp theme={null} virtual int SetSmoothing(float intensity) = 0; virtual int SetSmoothingStyle(beauty_params::SmoothingStyle style) = 0; virtual int SetWhitening(float intensity) = 0; virtual int SetWhiteningStyle(beauty_params::WhiteningStyle style) = 0; virtual int SetRosiness(float intensity) = 0; virtual int SetBrightness(float intensity) = 0; virtual int SetContrast(float intensity) = 0; virtual int SetSaturation(float intensity) = 0; virtual int SetColorTemperature(float intensity) = 0; virtual int SetColorTint(float intensity) = 0; virtual int SetClarity(float intensity) = 0; virtual int SetBeautySkinOnly(bool enabled) = 0; ``` `SetBeautySkinOnly(true)` applies smoothing / whitening / etc. only on detected skin. Style enums: [Parameter enums](/intro/makeup). ### Reshape ```cpp theme={null} virtual int SetReshape(beauty_params::Reshape param, float intensity) = 0; ``` `intensity` is **`[-1.0, 1.0]`**. `0` is off. Positive / negative are opposite directions. Full list: [Parameter enums](/intro/makeup). ```cpp theme={null} engine->SetReshape(Reshape::FaceThin, 0.4f); ``` ### Body reshape ```cpp theme={null} virtual int SetBodyReshape(beauty_params::BodyReshape param, float intensity) = 0; ``` `intensity` is **`[0.0, 1.0]`**. `0` is off. Requires `resource_body.fbd` (sibling of `resource.fbd`, or `AddResourcePack`). Full list: [Parameter enums](/intro/makeup). Packs: [Optional resource packs](/intro/resource-packs). ```cpp theme={null} engine->SetBodyReshape(BodyReshape::WaistSlim, 0.4f); ``` ### Makeup Each effect has intensity plus Style (mask) and/or Color (tint). Lipstick: Color only. Pupil: Color only. Contour: Style only. ```cpp theme={null} virtual int SetLipstick(float intensity) = 0; virtual int SetLipstickColor(beauty_params::LipstickColor color) = 0; virtual int SetBlush(float intensity) = 0; virtual int SetBlushStyle(beauty_params::BlushStyle style) = 0; virtual int SetBlushColor(beauty_params::BlushColor color) = 0; virtual int SetContour(float intensity) = 0; virtual int SetContourStyle(beauty_params::ContourStyle style) = 0; virtual int SetEyeShadow(float intensity) = 0; virtual int SetEyeShadowStyle(beauty_params::EyeShadowStyle style) = 0; virtual int SetEyeShadowColor(beauty_params::EyeShadowColor color) = 0; virtual int SetEyeLiner(float intensity) = 0; virtual int SetEyeLinerStyle(beauty_params::EyeLinerStyle style) = 0; virtual int SetEyeLinerColor(beauty_params::EyeLinerColor color) = 0; virtual int SetEyebrow(float intensity) = 0; virtual int SetEyebrowStyle(beauty_params::EyebrowStyle style) = 0; virtual int SetEyebrowColor(beauty_params::EyebrowColor color) = 0; virtual int SetEyelash(float intensity) = 0; virtual int SetEyelashStyle(beauty_params::EyelashStyle style) = 0; virtual int SetEyelashColor(beauty_params::EyelashColor color) = 0; virtual int SetPupil(float intensity) = 0; virtual int SetPupilColor(beauty_params::PupilColor color) = 0; ``` Values: [Parameter enums](/intro/makeup). ### Chroma key Mask for virtual background. Fill is still `SetVirtualBackgroundBlur` / `SetVirtualBackground`. With no fill, the keyed region is transparent. `ClearChromaKey()` restores portrait segmentation. ```cpp theme={null} virtual int SetChromaKey(beauty_params::ChromaKeyColor color) = 0; virtual int ClearChromaKey() = 0; virtual int SetChromaKeySimilarity(float value) = 0; // [0, 1] virtual int SetChromaKeySmoothness(float value) = 0; // [0, 1] virtual int SetChromaKeyDesaturation(float value) = 0; // [0, 1] ``` `ChromaKeyColor`: `Green = 0`, `Blue`, `Red`. ### Virtual background ```cpp theme={null} virtual int SetVirtualBackgroundBlur(float level) = 0; // [0, 1]; 0 clears fill virtual int SetVirtualBackground(const std::string& image_path) = 0; virtual int SetVirtualBackground(const std::vector& image_data) = 0; virtual int ClearVirtualBackground() = 0; ``` PNG / JPEG. Path must be non-empty. Bytes overload is encoded image data. ### Filter (LUT `.fbd`) GPU LUT is created on the next `ProcessImage`. No register / ID API. ```cpp theme={null} virtual int SetFilter(const std::string& fbd_file_path) = 0; virtual int SetFilter(const std::vector& fbd_data) = 0; virtual int ClearFilter() = 0; virtual int SetFilterIntensity(float intensity) = 0; // [0, 1] ``` ### Sticker (`.fbd`) ```cpp theme={null} virtual int SetSticker(const std::string& fbd_file_path) = 0; virtual int SetSticker(const std::vector& fbd_data) = 0; virtual int ClearSticker() = 0; virtual int AddResourcePack(const std::string& fbd_file_path) = 0; virtual int AddResourcePack(const std::vector& fbd_data) = 0; virtual int Set3DSticker(const std::string& resource) = 0; virtual int Set3DSticker(const std::vector& fbd_data) = 0; virtual int Clear3DSticker() = 0; ``` Load optional packs first (`resource_3d.fbd` before 3D stickers, `resource_body.fbd` before body reshape). See [Optional resource packs](/intro/resource-packs). ### Stats, callbacks, process ```cpp theme={null} virtual EngineStats GetStats() const = 0; virtual int SetCallbacks(const EngineCallbacks& callbacks) = 0; virtual const std::shared_ptr ProcessImage( const std::shared_ptr image_frame) = 0; ``` Set `image_frame->type` to `FrameType::Image` or `FrameType::Video` (default). Output format tracks input when possible. Returns `nullptr` on failure. ```cpp theme={null} input->type = FrameType::Video; auto output = engine->ProcessImage(input); ``` *** ## `EngineStats` ```cpp theme={null} struct EngineStats { double fps = 0.0; double avg_process_time_ms = 0.0; double session_time_s = 0.0; size_t gpu_live_textures = 0; size_t gpu_live_meshes = 0; }; ``` ## Callbacks and events ```cpp theme={null} enum class EngineEventCode { LicenseValidationSuccess = 0, LicenseValidationFailed = 1, EngineInitializationComplete = 100, EngineInitializationFailed = 101, }; ``` | Code | Meaning | | - | - | | `0` | License success | | `1` | License failed | | `100` | Init complete | | `101` | Init failed | ```cpp theme={null} struct EngineCallbacks { std::function on_engine_event = nullptr; }; ``` *** ## Image ### `Format` ```cpp theme={null} enum class Format { I420, NV12, NV21, BGRA, RGBA, BGR, RGB, Texture }; ``` ### `Rotation` ```cpp theme={null} enum class Rotation { Rotation_0, Rotation_90, Rotation_180, Rotation_270 // clockwise }; ``` ### `FrameType` ```cpp theme={null} enum class FrameType { Image = 0, // still / photo Video = 1 // stream (default) }; ``` Set on `ImageFrame::type`. ### `ImageFrame` Not copyable. Not thread-safe. **Factories** ```cpp theme={null} static std::shared_ptr CreateWithFile(const std::string& file_path); static std::shared_ptr Create( const uint8_t* data, int width, int height, Format format); static std::shared_ptr CreateWithRGBA( const uint8_t* data, int width, int height, int stride); static std::shared_ptr CreateWithBGRA( const uint8_t* data, int width, int height, int stride, bool copy_data = false); static std::shared_ptr CreateWithRGB( const uint8_t* data, int width, int height, int stride); static std::shared_ptr CreateWithBGR( const uint8_t* data, int width, int height, int stride); static std::shared_ptr CreateWithI420( int width, int height, const uint8_t* dataY, int strideY, const uint8_t* dataU, int strideU, const uint8_t* dataV, int strideV); static std::shared_ptr CreateWithNV12( int width, int height, const uint8_t* dataY, int strideY, const uint8_t* dataUV, int strideUV); static std::shared_ptr CreateWithNV21( int width, int height, const uint8_t* dataY, int strideY, const uint8_t* dataUV, int strideUV); static std::shared_ptr CreateWithTexture( uint32_t texture, int width, int height, int stride, bool external_oes = false, const float* tex_matrix_4x4 = nullptr); void SetGlRenderTarget(uint32_t texture); ``` Prefer dedicated YUV factories over `Create` for multi-plane formats. **Operations** ```cpp theme={null} int Rotate(Rotation rotation); int Mirror(MirrorMode mode); // Horizontal | Vertical | Both void SetMirror(MirrorMode mode); // inside ProcessImage; None clears std::shared_ptr Convert(Format format) const; int ToFile(const std::string& path, int quality = 90) const; ``` `Rotate`, `Mirror`, and `SetMirror` change CPU pixel frames only (RGBA, RGB, YUV, and image files). They do not transform an OpenGL texture or a D3D11 texture. Supply those already upright. **Accessors:** `Width()`, `Height()`, `Stride()`, `Size()`, `GetFormat()`, `Data()`, `DataY/U/V()`, `StrideY/U/V()`, `DataUV()`, `StrideUV()`, `Texture()`. Public field: `FrameType type = FrameType::Video`. *** ## Error codes Typical `int` returns: | Code | Meaning | | - | - | | `0` | OK | | `-1` | Invalid argument | | `-2` | Not initialized | | `-3` | License | | `-4` | Unsupported | | `-5` | I/O | | `-6` | Process | | `-7` | Out of memory | *** ## Notes * Create the engine and call process on the thread whose GL context is current. Input and output textures must belong to that context. CPU frames do not need a caller GL context. There is no context flag on the config. * **Lifetime:** factory methods return `std::shared_ptr`. * **Pixel pointers** from `Data()` are `const` — do not write through them. * The SDK has no `SetRenderView`. Draw the `ProcessImage` output in your own view. # Best Practices Source: https://docs.facebetter.net/windows/best-practices Performance and integration guidance for Facebetter 2.0 on Windows > [!NOTE] > > SDK **2.0.0**. Enums: [Parameter enums](/intro/makeup). ## Point `resource_path` at `resource.fbd` Desktop engines open the pack with `fopen`. Pass the **file**, not a folder: ```cpp theme={null} cfg.resource_path = "C:/app/assets/resource.fbd"; ``` Ship `resource.fbd` next to the app (or under an assets dir) and resolve an absolute path at startup. ## One engine, serial `ProcessImage` `Create` returns one engine for the session, not a process-wide singleton. `ImageFrame` and the engine are not thread-safe. Serialize `ProcessImage` and mutating setters on one thread. * Create the engine and call process on the thread whose GL context is current. Input and output textures must belong to that context. CPU frames do not need a caller GL context. There is no context flag on the config. ```cpp theme={null} // good: one engine, one processing thread std::shared_ptr engine = BeautyEffectEngine::Create(cfg); ``` Drop the `shared_ptr` when the camera session ends. Recreating the engine every frame is expensive (license + init). ## `FrameType` on the frame Set `frame->type` before `ProcessImage`. | Value | Use | | - | - | | `FrameType::Video` (default) | Camera, capture, live preview | | `FrameType::Image` | Single photo / export | ## Large stills (preview vs export) Do not feed full-resolution pixels into `ProcessImage` on every slider change, and do not throw the original away after scaling. When the photo opens, keep the full buffer and build **one** preview frame (long edge about 1280–1440). Slider changes process the preview (`FrameType::Image`). Export processes a full-resolution frame with the same setters. Output size matches the input. Camera preview stays capture resolution + `FrameType::Video`. ```cpp theme={null} preview->type = FrameType::Image; auto preview_out = engine->ProcessImage(preview); full->type = FrameType::Image; auto export_out = engine->ProcessImage(full); ``` ## Intensities Start low for realtime. Reshape is **`[-1.0, 1.0]`**; other intensities are `[0.0, 1.0]`. ```cpp theme={null} engine->SetSmoothing(0.25f); engine->SetWhitening(0.15f); engine->SetReshape(Reshape::FaceThin, 0.15f); engine->SetBeautySkinOnly(true); ``` Enable `SetBeautySkinOnly(true)` so smoothing / whitening stay on skin. ## Filters and stickers Pass `.fbd` paths or bytes. Changes take effect on the next `ProcessImage`. Avoid swapping filter/sticker every frame. ```cpp theme={null} engine->SetFilter(filter_path); engine->SetFilterIntensity(0.7f); ``` ## Monitor with `GetStats` ```cpp theme={null} EngineStats s = engine->GetStats(); if (s.avg_process_time_ms > 33.0) { // drop resolution, lower intensities, or skip stickers } ``` Aim for `avg_process_time_ms` under your frame budget (about 33 ms at 30 fps). Prefer 720p for preview; use `FrameType::Image` for still export. ## OpenGL context * Create the engine and call process on the thread whose GL context is current. Input and output textures must belong to that context. CPU frames do not need a caller GL context. There is no context flag on the config. Place `facebetter.dll` beside the `.exe` (or on `PATH`). Link `facebetter.lib` at build time. ## Pause when idle When the window is minimized or the camera stops, skip `ProcessImage` and optionally `engine.reset()` if the session is over. Do not process on the UI thread if it blocks input. ## Auth Prefer `license_token` for offline / locked-down networks. Otherwise `app_id` + `app_key` online v2. Do not hard-code production keys in public repos — load from config. See [Auth & License](/intro/license). # Error Handling Source: https://docs.facebetter.net/windows/error-handling Beauty Effect SDK 2.0 error codes and Windows troubleshooting > [!NOTE] > > SDK **2.0.0**. Auth details: [Auth & License](/intro/license). ## Return values Most setters return `int`: | Code | Meaning | | - | - | | `0` | Success | | `-1` | Invalid argument | | `-2` | Not initialized | | `-3` | License | | `-4` | Unsupported | | `-5` | I/O | | `-6` | Process failed | | `-7` | Out of memory | `BeautyEffectEngine::Create()` returns `std::shared_ptr`; failure is `nullptr`. `ProcessImage` may return `nullptr` on failure. ```cpp theme={null} int ret = engine->SetSmoothing(0.5f); if (ret != 0) { std::cerr << "SetSmoothing failed: " << ret << std::endl; } ``` ## Engine events Register `on_engine_event` after `Create`. Codes: | Code | Meaning | | - | - | | `0` | License success | | `1` | License failed | | `100` | Init complete | | `101` | Init failed | The `message` string has extra detail on failures. ```cpp theme={null} EngineCallbacks cbs; cbs.on_engine_event = [](int code, const std::string& message) { if (code == 1 || code == 101) { std::cerr << "engine event " << code << ": " << message << std::endl; } }; engine->SetCallbacks(cbs); ``` *** ## Common failures ### 1. `Create` returns `nullptr` Typical causes: * `resource_path` is a directory, missing, or not the `resource.fbd` **file** * Invalid / inactive `app_id` + `app_key`, or bad `license_token` * `facebetter.dll` missing or mismatched with `facebetter.lib` * Online auth cannot reach `/facebetter/v2/auth` Enable logs **before** `Create`: ```cpp theme={null} LogConfig log_cfg; log_cfg.console_enabled = true; log_cfg.level = LogLevel::Debug; BeautyEffectEngine::SetLogConfig(log_cfg); EngineConfig cfg; cfg.app_id = "your_app_id"; cfg.app_key = "your_app_key"; cfg.resource_path = (std::filesystem::current_path() / "resource" / "resource.fbd").string(); auto engine = BeautyEffectEngine::Create(cfg); if (!engine) { std::cerr << "Create failed — check logs, resource.fbd, and license." << std::endl; return -1; } ``` *** ### 2. `facebetter.dll` not found Windows shows a dialog if the DLL is not on the loader path. ```bat theme={null} dir build\facebetter.dll copy sdk\lib\facebetter.dll build\ ``` Or rebuild so CMake copies it next to the executable. *** ### 3. `ProcessImage` returns `nullptr` Check the input frame, engine pointer, and logs (`-6` process / `-7` OOM on setters). ```cpp theme={null} auto input = ImageFrame::CreateWithFile("input.jpg"); if (!input || !input->Data()) { std::cerr << "Failed to load input." << std::endl; return; } input->type = FrameType::Image; auto output = engine->ProcessImage(input); if (!output || !output->Data()) { std::cerr << "ProcessImage failed." << std::endl; } ``` *** ### 4. Effects look unchanged 2.0 does **not** use `SetBeautyTypeEnabled`. Effects are off at intensity `0`. Reshape / makeup also need a detected face. ```cpp theme={null} engine->SetSmoothing(0.5f); engine->SetReshape(Reshape::FaceThin, 0.3f); engine->SetLipstick(0.5f); input->type = FrameType::Video; ``` *** ### 5. OpenGL / display GLFW or `gladLoadGLLoader` can fail on outdated drivers, VMs, or Remote Desktop without GPU. ```cpp theme={null} if (!glfwInit()) { std::cerr << "GLFW init failed." << std::endl; return 1; } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); ``` * Create the engine and call process on the thread whose GL context is current. Input and output textures must belong to that context. CPU frames do not need a caller GL context. There is no context flag on the config. *** ## Debug logs ```cpp theme={null} LogConfig log_cfg; log_cfg.console_enabled = true; log_cfg.file_enabled = true; log_cfg.level = LogLevel::Debug; log_cfg.file_name = "facebetter.log"; BeautyEffectEngine::SetLogConfig(log_cfg); ``` The file is written relative to the current working directory unless you pass an absolute `file_name`. # FAQ Source: https://docs.facebetter.net/windows/faq Windows Beauty Effect SDK 2.0 integration FAQ > [!NOTE] > > SDK **2.0.0**. [Parameter enums](/intro/makeup) · [Auth & License](/intro/license). ## Integration ### Engine `Create` returns `nullptr` * `resource_path` must be the **`resource.fbd` file** (not a directory) * Set `license_token` **or** valid `app_id` + `app_key` * Enable `SetLogConfig` before `Create` * Confirm `facebetter.dll` matches the import library ### Header not found / link errors Include `facebetter/` from the SDK `include` directory. Link `facebetter.lib` and ship `facebetter.dll` next to the executable. ### `SetRenderView` is missing The SDK has no `SetRenderView`. Draw the `ProcessImage` output in your own view. ## Effects ### Beauty looks weak or off Intensities default to `0` (off). There is no `SetBeautyTypeEnabled`. Reshape / makeup need a face. Try `FrameType::Video` for camera frames. ### Reshape looks inverted Range is `[-1.0, 1.0]`. Positive and negative are opposite directions (see [Parameter enums](/intro/makeup)). ### Filter / sticker does nothing Pass a `.fbd` **path** or bytes to `SetFilter` / `SetSticker`. They take effect on the next `ProcessImage`. ### Virtual background / chroma key Use `SetVirtualBackgroundBlur`, `SetVirtualBackground(path|bytes)`, `ClearVirtualBackground`. Chroma key: `SetChromaKey(ChromaKeyColor::Green)` then similarity / smoothness / desaturation. `ClearChromaKey()` restores portrait segmentation. ## Performance ### Preview is slow Lower resolution, use `FrameType::Video`, reduce stickers / virtual background, and check `GetStats().avg_process_time_ms`. Avoid recreating `ImageFrame` from files every frame — feed camera buffers. For large gallery stills, build a smaller preview frame when the photo opens and export the original once. See [Best practices](/windows/best-practices#large-stills). ### High memory Reuse pixel buffers. Drop `shared_ptr` when unused. Do not create a new engine per frame. ### Remote Desktop / VM has no beauty preview Hardware OpenGL may be unavailable. Test on a machine with a real GPU driver. ## Auth ### `license_token` vs `app_id` + `app_key` If `license_token` is non-empty, it wins (token / `{token}` JSON / `.lic`). Otherwise native online v2 uses `app_id` + `app_key`. See [Auth & License](/intro/license). ### Event `1` or `101` License failed or init failed. Read the callback `message` and Debug logs. ## Version ### What version should I document / ship? **2.0.0**. ### Which Windows versions / compilers? Windows 10+, MSVC 2019+ (C++17), x64. Ninja + CMake 3.16+ is the documented demo path. # Implement Beauty Source: https://docs.facebetter.net/windows/implement-beauty Integrate Beauty Effect SDK 2.0 on Windows with the C++ API > [!NOTE] > > SDK **2.0.0**. Headers live in `facebetter/*.h`. Makeup / reshape / style enums: [Parameter enums](/intro/makeup). Auth: [Auth & License](/intro/license). On Windows, Facebetter is a C++ library (`facebetter.lib` + `facebetter.dll`). This guide follows the [C++ desktop demo](https://github.com/pixpark/facebetter-sdk) (`demo/cpp`). ## Include headers ```cpp theme={null} #include #include #include #include using namespace facebetter; using namespace facebetter::beauty_params; ``` ## Integration flow ``` SetLogConfig → Create(EngineConfig) → set effects → ProcessImage → render ``` There is no type-enable step. Setting an intensity above `0` turns that effect on. *** ## 1. Configure logging (optional) Call this **before** `Create` so initialization logs are captured. ```cpp theme={null} LogConfig log_cfg; log_cfg.console_enabled = true; log_cfg.file_enabled = false; log_cfg.level = LogLevel::Info; BeautyEffectEngine::SetLogConfig(log_cfg); ``` Levels (low → high): `Trace` / `Debug` / `Info` / `Warn` / `Error` / `Critical`. *** ## 2. Create the engine Desktop **must** set `resource_path` to the `resource.fbd` **file**. **Auth priority:** if `license_token` is non-empty, the SDK validates that token (license token string, `{token}` JSON, or offline `.lic`) and does not call the network with `app_id` / `app_key`. Otherwise it uses `app_id` + `app_key` against `/facebetter/v2/auth`. ```cpp theme={null} EngineConfig cfg; cfg.app_id = "your_app_id"; cfg.app_key = "your_app_key"; cfg.resource_path = "resource/resource.fbd"; // path to the .fbd file // Optional: token takes priority when non-empty // cfg.license_token = "/* license token, {token} JSON, or .lic contents */"; std::shared_ptr engine = BeautyEffectEngine::Create(cfg); if (!engine) { // Check resource_path, license_token / app_id+app_key, and logs return -1; } ``` > [!WARNING] > > `resource_path` must be the `resource.fbd` file, not a folder. Relative paths are resolved from the process working directory. Prefer an absolute path in production. *** ## 3. Set beauty parameters Skin / makeup / body-reshape intensities are `[0.0, 1.0]`. `0` is off. Face reshape is **`[-1.0, 1.0]`**. Full enum lists: [Parameter enums](/intro/makeup). ### Skin ```cpp theme={null} engine->SetSmoothing(0.5f); engine->SetSmoothingStyle(SmoothingStyle::Natural); engine->SetWhitening(0.3f); engine->SetWhiteningStyle(WhiteningStyle::ColdWhite); engine->SetRosiness(0.2f); engine->SetBeautySkinOnly(true); // beauty only on detected skin ``` ### Face reshape ```cpp theme={null} engine->SetReshape(Reshape::FaceThin, 0.4f); engine->SetReshape(Reshape::EyeSize, 0.3f); engine->SetReshape(Reshape::Chin, -0.2f); // negative = opposite direction ``` ### Body reshape Range **`[0.0, 1.0]`**. `0` is off. Place `resource_body.fbd` next to `resource.fbd` or call `AddResourcePack`. See [Parameter enums](/intro/makeup) and [Optional resource packs](/intro/resource-packs). ```cpp theme={null} engine->AddResourcePack("resource/resource_body.fbd"); // or place it next to resource.fbd engine->SetBodyReshape(BodyReshape::WaistSlim, 0.4f); engine->SetBodyReshape(BodyReshape::LegStretch, 0.3f); engine->SetBodyReshape(BodyReshape::TorsoLong, 0.3f); ``` ### Makeup Intensity, shape, and color are separate setters. Lipstick is color-only; pupil is color-only; contour is style-only. ```cpp theme={null} engine->SetLipstick(0.6f); engine->SetLipstickColor(LipstickColor::Rouge); engine->SetBlush(0.4f); engine->SetBlushStyle(BlushStyle::SunKissed); engine->SetBlushColor(BlushColor::CoralPink); engine->SetContour(0.5f); engine->SetContourStyle(ContourStyle::Natural); engine->SetEyeShadow(0.4f); engine->SetEyeShadowStyle(EyeShadowStyle::Soft); engine->SetEyeShadowColor(EyeShadowColor::Plum); ``` Same pattern for eyeliner, eyebrow, eyelash, and pupil (`SetEyeLiner` / `SetEyebrow` / `SetEyelash` / `SetPupil` plus Style / Color where applicable). *** ## 4. Filters, stickers, and virtual background Pass a **file path** or **encoded bytes**. ```cpp theme={null} engine->SetFilter("assets/filters/natural.fbd"); engine->SetFilterIntensity(0.8f); engine->ClearFilter(); engine->SetSticker("assets/stickers/face/black_glass.fbd"); engine->ClearSticker(); engine->AddResourcePack("resource/resource_3d.fbd"); // or place it next to resource.fbd engine->Set3DSticker("assets/stickers/3d/oculos.fbd"); engine->Clear3DSticker(); engine->SetVirtualBackgroundBlur(0.6f); // [0, 1]; 0 clears fill engine->SetVirtualBackground("assets/background.jpg"); engine->ClearVirtualBackground(); engine->SetChromaKey(ChromaKeyColor::Green); engine->SetChromaKeySimilarity(0.4f); engine->SetChromaKeySmoothness(0.1f); engine->SetChromaKeyDesaturation(0.2f); engine->ClearChromaKey(); // back to portrait segmentation ``` LUT / sticker textures are created on the next `ProcessImage` call (the active GL thread). For 3D stickers see [Optional resource packs](/intro/resource-packs). *** ## 5. Callbacks and stats ```cpp theme={null} EngineCallbacks cbs; cbs.on_engine_event = [](int code, const std::string& message) { // 0 license OK, 1 license failed, 100 init complete, 101 init failed printf("[event] %d %s\n", code, message.c_str()); }; engine->SetCallbacks(cbs); EngineStats stats = engine->GetStats(); printf("fps=%.1f avg=%.2fms session=%.1fs\n", stats.fps, stats.avg_process_time_ms, stats.session_time_s); ``` *** ## 6. Process frames Set `ImageFrame::type` to `FrameType::Video` (realtime, default) or `FrameType::Image` (single photo). ```cpp theme={null} auto input = ImageFrame::CreateWithRGBA(rgba_data, width, height, stride); input->type = FrameType::Video; auto output = engine->ProcessImage(input); if (output && output->Data()) { const uint8_t* p = output->Data(); int w = output->Width(); int h = output->Height(); } ``` **File (photo mode):** ```cpp theme={null} auto input = ImageFrame::CreateWithFile("input.jpg"); input->type = FrameType::Image; auto output = engine->ProcessImage(input); output->ToFile("output.jpg", 95); ``` > [!TIP] > > The engine keeps output format aligned with input when possible (RGBA in → RGBA out, I420 in → I420 out). Use `Convert(Format::BGRA)` if you need another layout. ### Upload to OpenGL (preview) ```cpp theme={null} GLuint tex = 0; glGenTextures(1, &tex); glBindTexture(GL_TEXTURE_2D, tex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, output->Width(), output->Height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, output->Data()); ``` Keep `facebetter.dll` next to the executable (the demo CMake copies it after build). *** ## 7. Minimal loop ```cpp theme={null} LogConfig log_cfg; log_cfg.console_enabled = true; log_cfg.level = LogLevel::Info; BeautyEffectEngine::SetLogConfig(log_cfg); EngineConfig cfg; cfg.app_id = "your_app_id"; cfg.app_key = "your_app_key"; cfg.resource_path = "resource/resource.fbd"; auto engine = BeautyEffectEngine::Create(cfg); if (!engine) return -1; engine->SetSmoothing(0.5f); engine->SetReshape(Reshape::FaceThin, 0.3f); engine->SetLipstick(0.5f); engine->SetLipstickColor(LipstickColor::Rouge); auto input = ImageFrame::CreateWithRGBA(rgba, width, height, stride); input->type = FrameType::Video; auto output = engine->ProcessImage(input); ``` When you are done, drop the `shared_ptr` (`engine.reset()`). `BeautyEffectEngine` is **not** a singleton. For TRTC / Agora / LiveKit: [Third-party Integration](/windows/third-party-integration). ## Related > **[Third-party Integration](/windows/third-party-integration)** > > TRTC / Agora / LiveKit > **[API reference](/windows/api-reference)** > > All C++ methods and types > **[Error handling](/windows/error-handling)** > > Return codes and Windows DLL issues > **[Best practices](/windows/best-practices)** > > Performance and threading # Quick Start Source: https://docs.facebetter.net/windows/quick-start Build and run the Facebetter C++ desktop demo on Windows (GLFW + ImGui) > [!NOTE] > > This page matches SDK **2.0.0**. Windows uses the C++ API in the `facebetter` namespace (`facebetter/*.h`). This guide builds the Facebetter C++ desktop demo on Windows. The demo uses **GLFW + Dear ImGui + OpenGL 3**: live preview on the left, beauty controls on the right. ## Requirements | Tool | Version | | - | - | | Visual Studio / MSVC | 2019 or later (C++17) | | CMake | 3.16+ | | Ninja | Any recent version (`winget install Ninja-build.Ninja`) | | Windows SDK | 10.0+ | > [!TIP] > > MinGW-w64 also works, but MSVC is recommended. ## Step 1: Clone the repository ```bash theme={null} git clone https://github.com/pixpark/facebetter-sdk.git cd facebetter-sdk ``` ## Step 2: Place the SDK files Unzip the Windows SDK package and place files under `demo/cpp/sdk/`: ``` demo/cpp/sdk/ ├── include/ │ └── facebetter/ │ ├── beauty_effect_engine.h │ ├── beauty_params.h │ ├── image_frame.h │ └── type_defines.h ├── lib/ │ ├── facebetter.lib ← import library │ └── facebetter.dll ← runtime DLL └── resource/ ├── resource.fbd ← models and assets (required) ├── resource_3d.fbd ← optional; 3D stickers. Place next to `resource.fbd` or call `AddResourcePack` └── resource_body.fbd ← optional; body reshape. Place next to `resource.fbd` or call `AddResourcePack` ``` > [!WARNING] > > On desktop, `EngineConfig::resource_path` must point to the **`resource.fbd` file**, not a directory. Example: `demo/cpp/sdk/resource/resource.fbd`. > [!TIP] > > SDK packages are on the [Download](https://facebetter.net/download) page and in the [Dashboard](https://facebetter.net/dashboard). ## Step 3: Configure license Set `app_id` / `app_key` (online v2 auth) or `license_token` in the demo before you run it. If `license_token` is non-empty, it takes priority (license token string, `{token}` JSON, or offline `.lic` contents). Details: [Auth & License](/intro/license). ## Step 4: Build Open a **Developer Command Prompt for VS** (or PowerShell with the MSVC environment loaded): ```bat theme={null} cd demo\cpp cmake -B build -G "Ninja" -DCMAKE_BUILD_TYPE=Release cmake --build build ``` After the build, CMake typically: * Copies `facebetter.dll` next to the executable in `build/` * Copies `resource/resource.fbd` to `build/resource/resource.fbd` * Copies `demo.png` (if present) to `build/resource/demo.png` ## Step 5: Prepare a preview image (optional) Place a face photo named `demo.png` in `demo/cpp/`: ``` demo/cpp/demo.png ``` ## Step 6: Run ```bat theme={null} cd demo\cpp\build .\facebetter_demo.exe ``` The window shows: * **Left panel** — live beauty-processed preview * **Right panel** — Beauty Control Panel: * **Basic beauty**: smoothing / whitening / rosiness, plus full-frame color grade * **Face reshape**: 26 reshape params (range `[-1.0, 1.0]`) * **Body reshape**: 7 params (range `[0.0, 1.0]`; needs `resource_body.fbd`) * **Makeup**: lipstick / blush / eyeshadow / eyeliner / eyebrow / eyelash / pupil / contour * **Filter / sticker / virtual background** Click **Reset All** to zero intensities. ## Troubleshooting **Q: "facebetter.dll was not found" at startup**\ A: Confirm `demo/cpp/sdk/lib/facebetter.dll` exists, then re-run `cmake --build build` so CMake copies the DLL next to the executable. **Q: Engine create returns `nullptr` / license failed**\ A: Point `resource_path` at `resource.fbd`, and set `license_token` or valid `app_id` + `app_key`. See [Auth & License](/intro/license). **Q: CMake cannot find Ninja**\ A: Run `winget install Ninja-build.Ninja`, or use `-G "Visual Studio 17 2022"` and `--config Release`. ## Next steps > **[Implement beauty](/windows/implement-beauty)** > > Create the engine, set effects, and process frames. > **[API reference](/windows/api-reference)** > > Full C++ API for Windows. # Third-party Integration Source: https://docs.facebetter.net/windows/third-party-integration Wire Facebetter beauty into TRTC, Agora, LiveKit, and other Windows video pipelines SDK **2.0.0**. Desktop differs from mobile: TRTC / Agora on **Windows usually deliver CPU buffers (I420 / YUV)**, not OpenGL `textureId`. Hook Facebetter in the vendor’s custom preprocess callback, run `ImageFrame::CreateWithI420` (or NV12) → `ProcessImage`, then write planes back. Shares the same C++ API as the C++ API. Basics: [Implement Beauty](/windows/implement-beauty). Room join / publish belong in the vendor’s docs. ``` Third-party SDK (preprocess callback) I420 / YUV planes ↓ BeautyEffectEngine CreateWithI420 → ProcessImage ↓ write back to vendor dst / in-place buffers ``` ## Shared contract | Item | Requirement | | - | - | | Engine | `BeautyEffectEngine::Create`; desktop must set `resource_path` to the `resource.fbd` **file** | | Context | Create the engine and call process on the thread whose GL context is current. Input and output textures must belong to that context. CPU frames do not need a caller GL context. There is no context flag on the config. | | Format | Prefer **I420** on PC (matches TRTC Buffer / Agora YUV420) | | Frame type | `FrameType::Video` | | Lifecycle | After removing callbacks, `engine.reset()`. Not a singleton | ### Shared: process I420 and write planes back ```cpp theme={null} #include #include #include using namespace facebetter; static void CopyPlane(uint8_t* dst, int dst_stride, const uint8_t* src, int src_stride, int width, int height) { for (int y = 0; y < height; ++y) { std::memcpy(dst + y * dst_stride, src + y * src_stride, width); } } /** Returns true on success; leave vendor buffers untouched on failure */ static bool ProcessI420InPlace(BeautyEffectEngine* engine, uint8_t* y, int stride_y, uint8_t* u, int stride_u, uint8_t* v, int stride_v, int width, int height) { if (!engine || !y || !u || !v || width <= 0 || height <= 0) { return false; } auto input = ImageFrame::CreateWithI420( width, height, y, stride_y, u, stride_u, v, stride_v); if (!input) { return false; } input->type = FrameType::Video; auto output = engine->ProcessImage(input); if (!output || !output->DataY()) { return false; } CopyPlane(y, stride_y, output->DataY(), output->StrideY(), width, height); CopyPlane(u, stride_u, output->DataU(), output->StrideU(), width / 2, height / 2); CopyPlane(v, stride_v, output->DataV(), output->StrideV(), width / 2, height / 2); return true; } ``` Create the engine: ```cpp theme={null} EngineConfig cfg; cfg.app_id = "your_app_id"; cfg.app_key = "your_app_key"; cfg.resource_path = "resource/resource.fbd"; auto engine = BeautyEffectEngine::Create(cfg); if (!engine) { return; } engine->SetSmoothing(0.5f); ``` Credentials: [Subscription](/intro/enable-service), [Auth & License](/intro/license). *** ## TRTC (Tencent) Windows / desktop C++: **custom preprocess uses Buffer, not Texture**. Newer SDKs use `enableLocalVideoCustomProcess` + `setLocalVideoCustomProcessCallback` (older `setLocalVideoProcessCallback` is deprecated — check your version). Use pixel format **I420** and buffer type **Buffer**. In `onProcessVideoFrame`, process `srcFrame` and fill `dstFrame`. ```cpp theme={null} #include "ITRTCCloud.h" #include "TRTCTypeDef.h" class BeautyFrameCallback : public liteav::ITRTCVideoFrameCallback { public: explicit BeautyFrameCallback(std::shared_ptr engine) : engine_(std::move(engine)) {} int onProcessVideoFrame(liteav::TRTCVideoFrame* src, liteav::TRTCVideoFrame* dst) override { if (!src || !dst || !engine_) { return 0; } // Field names (data / split YUV planes) vary slightly by LiteAV headers ProcessI420InPlace(engine_.get(), /* y,u,v,strides,width,height from src */); // Copy processed planes into dst, or set dst->data / length per TRTC docs return 0; } private: std::shared_ptr engine_; }; // Registration sketch (names per your TRTC C++ version): // trtc->enableLocalVideoCustomProcess(true); // trtc->setLocalVideoCustomProcessCallback(callback); ``` > [!NOTE] > > Tencent docs: mobile can use Texture; **PC supports Buffer only**. Do not follow the Android `Texture_2D` path on Windows. *** ## Agora Hook: `IRtcEngine::registerVideoFrameObserver` (C++ Video SDK **4.x**). Windows typically yields **YUV420 / I420**. 1. Return `PROCESS_MODE_READ_WRITE` from `getVideoFrameProcessMode` 2. In `onCaptureVideoFrame`, run `ProcessI420InPlace` on `yBuffer` / `uBuffer` / `vBuffer` 3. Return `true` so the SDK keeps the frame ```cpp theme={null} #include "IAgoraMediaEngine.h" #include "IAgoraRtcEngine.h" class BeautyObserver : public agora::media::IVideoFrameObserver { public: explicit BeautyObserver(std::shared_ptr engine) : engine_(std::move(engine)) {} bool onCaptureVideoFrame(agora::rtc::VIDEO_SOURCE_TYPE /*type*/, VideoFrame& frame) override { if (!engine_ || !frame.yBuffer || !frame.uBuffer || !frame.vBuffer) { return true; } ProcessI420InPlace(engine_.get(), frame.yBuffer, frame.yStride, frame.uBuffer, frame.uStride, frame.vBuffer, frame.vStride, frame.width, frame.height); return true; } VIDEO_FRAME_PROCESS_MODE getVideoFrameProcessMode() override { return PROCESS_MODE_READ_WRITE; } // Implement getVideoFormatPreference / getObservedFramePosition per Agora docs private: std::shared_ptr engine_; }; // mediaEngine->registerVideoFrameObserver(observer); ``` Unregister before destroying `IRtcEngine`, then `engine.reset()`. *** ## LiveKit On desktop, the usual pattern is a **custom video source**: capture / process yourself, then push frames into LiveKit (C++ client or your bridge) — not the mobile `VideoProcessor` texture callback. Recommended pipeline: 1. Capture frames (camera / DXGI / etc.) 2. `CreateWithI420` / `CreateWithRGBA` → `ProcessImage` 3. Wrap the output as a LiveKit / WebRTC frame and push into `VideoSource` / `RTCVideoSource` Exact type names vary by LiveKit client version — see [LiveKit docs](https://docs.livekit.io/) for custom tracks. Facebetter only covers step 2. *** ## Troubleshooting | Symptom | Check | | - | - | | `Create` fails | `resource_path` points at the `.fbd` **file**; auth is valid | | No beauty | Processing inside ReadWrite / custom preprocess; planes written back | | Distortion | Row-by-row copy with correct `stride`; even width/height for I420 | | Stutter | Avoid large per-frame allocations; serialize `ProcessImage` on one thread | ## Related * [Implement Beauty](/windows/implement-beauty) * [Best Practices](/windows/best-practices) * [API Reference](/windows/api-reference)