Camera SDK

Professional camera integration with advanced filters, real-time effects, and cross-platform compatibility

Advanced Camera Technology

Cutting-edge camera SDK with professional-grade controls, real-time processing, and optimized performance for mobile applications.

Rich Filter Library

Access hundreds of professionally crafted filters and effects with weekly updates through our dynamic asset store.

Cross-Platform Support

Seamless integration across iOS, Android, Flutter, and React Native with consistent APIs and platform-specific optimizations.

Easy Integration

Developer-friendly APIs with comprehensive documentation, sample code, and quick setup to get you started in minutes.

500+
Filters & Effects
4
Platforms Supported
Weekly
Asset Updates
99.9%
Uptime

Comprehensive Feature Set

Extensive Filters & Effects Library

Choose from hundreds of beautifully crafted filters and effects, updated weekly through our dynamic asset store. Includes vibrant color filters, cinematic effects, glitch styles, vintage looks, and more — perfect for every style and mood.

Real-Time Overlays & Morphing

Apply interactive overlays and real-time face morphing effects that adapt dynamically to user expressions and movements. Create unforgettable experiences with custom masks, animated objects, and morphing that reshapes facial features naturally.

Advanced Beauty Effects

Enhance selfies and videos with a comprehensive suite of beauty filters including skin smoothing, tone correction, eye brightening, and subtle contouring. All effects run smoothly with high performance optimized for mobile devices.

Cross-Platform Compatibility & Integration

Fully supports Android, iOS, Flutter, and React Native, with web support coming soon. Designed with developers in mind — integration is simple and well-documented, helping you get started in minutes.

Weekly Asset Store Updates

Access our asset store packed with fresh filters, overlays, and effects delivered weekly to keep your app content fresh and engaging. Easily add or remove assets as needed without requiring app updates.

Huge Product Roadmap Ahead

Upcoming releases include Shopping AR Experiences, Background Segmentation for virtual backgrounds, and Selfie and Hair Segmentation for detailed personalizations and virtual try-ons.

Platform Integrations

SDK Overview

The Nosmai iOS SDK is a professional real-time video processing framework that provides live camera preview, real-time filter application, face detection, beauty filters, video recording with effects, cloud-based filter management, and high-performance GPU-based processing.

System Requirements

  • iOS Version: iOS 11.0 or later
  • Xcode: 12.0 or later
  • Swift: 5.0+ (Objective-C compatible)
  • Architecture: arm64
  • Valid Nosmai License Key: Contact Nosmai team for licensing
  • Device: iPhone or iPad with camera support

Permissions Required

  • Camera access: NSCameraUsageDescription
  • Microphone access: NSMicrophoneUsageDescription (for video recording)

Installation

Multiple installation methods available for the Nosmai framework.

Method 1: CocoaPods

Add this to your Podfile:

platform :ios, '11.0'
use_frameworks! :linkage => :static

target 'YourApp' do
  use_frameworks!
  use_modular_headers!
  
  pod 'Nosmai', '~> 1.0.6'
end

Then run:

cd ios && pod install

Method 2: Manual Installation

  1. Download the nosmai.framework
  2. Drag it into your Xcode project
  3. Ensure "Copy items if needed" is checked
  4. Add to "Frameworks, Libraries, and Embedded Content" with "Embed & Sign"
  5. Add required permissions to Info.plist

Quick Start Guide

1. Import the Framework

#import <nosmai/Nosmai.h>

2. Initialize with License

// Using API key
[[NosmaiCore shared] initializeWithAPIKey:@"YOUR_API_KEY" 
                               completion:^(BOOL success, NSError *error) {
    if (success) {
        NSLog(@"SDK initialized successfully");
        // Configure camera and start preview
    } else {
        NSLog(@"SDK initialization failed: %@", error.localizedDescription);
    }
}];

// Or using custom configuration
NosmaiConfig *config = [[NosmaiConfig alloc] init];
config.apiKey = @"YOUR_API_KEY";
config.enableDebugLogging = YES;
config.enableFaceDetection = YES;

[[NosmaiCore shared] initializeWithConfig:config 
                               completion:^(BOOL success, NSError *error) {
    // Handle initialization
}];

3. Setup Camera and Preview

// Configure camera
NosmaiCameraConfig *cameraConfig = [[NosmaiCameraConfig alloc] init];
cameraConfig.position = NosmaiCameraPositionFront;
cameraConfig.sessionPreset = AVCaptureSessionPresetHigh;
cameraConfig.targetFrameRate = 30;

[[NosmaiCore shared].camera updateConfiguration:cameraConfig];

// Attach preview to a UIView
UIView *previewView = [[UIView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:previewView];
[[NosmaiCore shared].camera attachToView:previewView];

// Start camera capture
[[NosmaiCore shared].camera startCapture];

Required Permissions (Info.plist)

<key>NSCameraUsageDescription</key>
<string>This app needs camera access to apply filters and effects</string>
<key>NSMicrophoneUsageDescription</key>
<string>This app needs microphone access for video recording with audio</string>
<key>NSPhotoLibraryAddUsageDescription</key>
<string>This app needs photo library access to save photos and videos</string>

Local Filters (.nosmai Files)

Apply local filters and download cloud-based effects:

Apply Local Filter

// Apply a local .nosmai filter file
NSString *filterPath = [[NSBundle mainBundle] pathForResource:@"vintage" 
                                                        ofType:@"nosmai"];
[[NosmaiCore shared].effects applyEffect:filterPath 
                              completion:^(BOOL success, NSError *error) {
    if (success) {
        NSLog(@"Filter applied successfully");
    }
}];

// Or use the simplified SDK interface
[[NosmaiSDK sharedInstance] applyEffect:@"vintage.nosmai" 
                              completion:^(BOOL success, NSError *error) {
    // Handle result
}];

Cloud Filters

// Get available cloud filters
[[NosmaiCore shared].effects getCloudFilters:^(NSArray *filters, NSError *error) {
    if (error) {
        NSLog(@"Failed to load cloud filters: %@", error);
        return;
    }
    
    // Display filters in UI
    for (NSDictionary *filter in filters) {
        NSString *filterID = filter[@"id"];
        NSString *name = filter[@"name"];
        NSString *thumbnailURL = filter[@"thumbnailUrl"];
        
        // Add to UI...
    }
}];

// Download and apply cloud filter
[[NosmaiCore shared].effects downloadCloudFilter:filterID 
                                        progress:^(float progress) {
    // Update download progress UI
    NSLog(@"Download progress: %.0f%%", progress * 100);
} completion:^(NSString *localPath, NSError *error) {
    if (!error) {
        // Apply downloaded filter
        [[NosmaiCore shared].effects applyEffect:localPath completion:nil];
    }
}];

Remove Filters

// Remove all effects
[[NosmaiCore shared].effects removeAllEffects];

Beauty Effects & Face Enhancement

Apply comprehensive beauty effects and face enhancements:

Complete Beauty Filter Suite

NosmaiEffectsEngine *effects = [NosmaiCore shared].effects;

// Check if beauty features are licensed
if (![effects isBeautyEffectEnabled]) {
    NSLog(@"Beauty features not available");
    return;
}

// Apply multiple beauty effects
[effects applySkinSmoothing:0.7];      // 70% smoothing
[effects applySkinWhitening:0.3];      // 30% whitening
[effects applyFaceSlimming:0.2];       // 20% face slimming
[effects applyEyeEnlargement:0.15];    // 15% eye enlargement
[effects applyNoseSize:0.1];           // 10% nose refinement

Makeup Effects

// Makeup effects
[effects applyLipstickWithBlendLevel:0.6];  // 60% lipstick
[effects applyBlusherWithBlendLevel:0.4];   // 40% blusher

Color & Tone Adjustments

// Color adjustments
[effects applyRGBFilterWithRed:1.2 green:1.0 blue:0.8];
[effects applyBrightnessFilter:0.2];     // -1.0 to 1.0
[effects applyContrastFilter:1.5];       // 0.0 to 4.0
[effects applyHueFilter:180.0];          // 0-360 degrees
[effects applyHSBFilterWithHue:15.0 saturation:1.2 brightness:1.1];
[effects applyWhiteBalanceWithTemperature:5500.0 tint:-5.0];

// Other effects
[effects applySharpeningFilter:0.8];
[effects applyGrayscaleFilter];

Remove Beauty Effects

// Remove specific built-in filter
[effects removeBuiltInFilterByName:@"skinSmoothing"];

// Remove all built-in effects
[effects removeAllEffects];

Camera Control & Video Recording

Control camera functionality and record videos with effects:

Camera Controls

NosmaiCamera *camera = [NosmaiCore shared].camera;

// Switch camera
[camera switchCamera];
[camera switchToPosition:NosmaiCameraPositionBack];

// Focus and exposure control
[camera setFocusPointOfInterest:CGPointMake(0.5, 0.5)];
[camera setExposurePointOfInterest:CGPointMake(0.5, 0.5)];

// Zoom control
[camera setZoomFactor:2.0];
[camera rampToZoomFactor:3.0 withDuration:1.0];

// Flash control
[camera setFlashMode:AVCaptureFlashModeAuto];
[camera setTorchLevel:0.5];

Video Recording with Effects

// Configure recording
NosmaiRecordingConfig *config = [[NosmaiRecordingConfig alloc] init];
config.quality = NosmaiVideoQualityHigh;
config.includeAudio = YES;

// Generate output path
NSString *documentsPath = NSSearchPathForDirectoriesInDomains(
    NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
NSString *fileName = [NSString stringWithFormat:@"video_%@.mp4", 
    [[NSUUID UUID] UUIDString]];
NSURL *outputURL = [NSURL fileURLWithPath:
    [documentsPath stringByAppendingPathComponent:fileName]];

// Start recording
[[NosmaiCore shared] startRecording];
[[NosmaiCore shared].recorder startRecordingToURL:outputURL 
                                       completion:^(BOOL success, NSError *error) {
    if (success) {
        NSLog(@"Recording started");
    }
}];

Stop Recording

[[NosmaiCore shared] stopRecording];
[[NosmaiCore shared].recorder stopRecordingWithCompletion:^(BOOL success, NSError *error) {
    if (success) {
        NSLog(@"Recording saved successfully");
    }
}];

Custom Frame Processing

[[NosmaiSDK sharedInstance] setCVPixelBufferCallback:^(CVPixelBufferRef pixelBuffer) {
    // Process each frame
    // Note: This is called on a background thread
    
    // Example: Save frame as image
    CIImage *ciImage = [CIImage imageWithCVPixelBuffer:pixelBuffer];
    // Process or analyze frame...
}];

Memory Management & Performance

Proper memory management and performance optimization:

Memory Management

// Handle memory warnings
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    [[NosmaiSDK sharedInstance] didReceiveMemoryWarning:nil];
    [[NosmaiSDK sharedInstance] forceMemoryCleanup];
}

// Cleanup when done
- (void)cleanup {
    [[NosmaiCore shared] pause];
    [[NosmaiCore shared] cleanup];
}

Performance Optimization

// Preload frequently used filters
- (void)preloadCommonFilters {
    NSArray *commonFilters = @[@"beauty.nosmai", @"vintage.nosmai", @"natural.nosmai"];
    
    for (NSString *filter in commonFilters) {
        [[NosmaiCore shared].effects applyEffect:filter completion:nil];
    }
    
    // Remove all filters after preloading
    [[NosmaiCore shared].effects removeAllEffects];
}

// Use appropriate video quality
NosmaiCameraConfig *config = [[NosmaiCameraConfig alloc] init];
config.sessionPreset = AVCaptureSessionPresetMedium; // For older devices
config.targetFrameRate = 24; // Reduce frame rate if needed

State Management

// Monitor SDK state changes
@interface ViewController () 
@end

- (void)setupSDK {
    [NosmaiCore shared].delegate = self;
}

#pragma mark - NosmaiDelegate

- (void)nosmaiDidChangeState:(NosmaiState)newState {
    switch (newState) {
        case NosmaiStateReady:
            // SDK ready to use
            break;
        case NosmaiStateError:
            // Handle error state
            break;
        default:
            break;
    }
}

Error Handling & Troubleshooting

Comprehensive error handling and troubleshooting guide:

Error Handling

[[NosmaiCore shared].effects applyEffect:filterPath 
                              completion:^(BOOL success, NSError *error) {
    if (!success) {
        if (error.code == NosmaiErrorCodeInvalidLicense) {
            // Handle license error
        } else if (error.code == NosmaiErrorCodeFileNotFound) {
            // Handle missing filter
        }
        // Log error for debugging
        NSLog(@"Filter error: %@", error.localizedDescription);
    }
}];

Best Practices

  • Memory Management: Call cleanup when done, implement memory warning handling
  • Performance Optimization: Use appropriate video quality, limit concurrent effects, preload filters
  • Error Handling: Always implement completion blocks with proper error handling
  • State Management: Monitor SDK state changes using delegates
  • License Management: Store license keys securely using Keychain Services

Common Issues & Solutions

  • SDK Initialization Fails: Verify API key and check internet connection
  • Black Screen: Ensure camera permissions and proper preview setup
  • Filters Not Applying: Check SDK state and verify filter file paths
  • Memory Warnings: Implement memory cleanup and reduce video quality
  • Recording Issues: Ensure microphone permissions and adequate storage

Debug Mode

// Enable debug logging
NosmaiConfig *config = [[NosmaiConfig alloc] init];
config.enableDebugLogging = YES;
[[NosmaiCore shared] initializeWithConfig:config completion:nil];

// Export debug information
NSString *debugInfo = [[NosmaiCore shared] exportDebugInfo];
NSLog(@"Debug Info: %@", debugInfo);

License Requirements & Support

Different features require specific license tiers and support resources:

License Tiers

Basic License
  • Camera preview and capture
  • Local .nosmai filters
  • Basic color adjustments
  • Video recording
Professional License
  • Beauty filters (skin smoothing, face reshape)
  • Face detection features
  • Advanced effects
  • Priority support
Enterprise License
  • Cloud filter access
  • Custom filter development
  • Priority support
  • SLA guarantee

Support Resources

  • Documentation: https://docs.nosmai.com
  • Sample Projects: Complete implementation examples
  • Support Email: support@nosmai.com
  • GitHub Issues: Community support and bug reports

Android SDK Installation

Add the Camera SDK to your Android project using Gradle.

Gradle (Module-level)

dependencies {
    implementation 'com.nosmai:camera-sdk:1.0.0'
    implementation 'androidx.camera:camera-core:1.3.0'
    implementation 'androidx.camera:camera-camera2:1.3.0'
    implementation 'androidx.camera:camera-lifecycle:1.3.0'
    implementation 'androidx.camera:camera-view:1.3.0'
}

Gradle (Project-level)

allprojects {
    repositories {
        google()
        mavenCentral()
        maven { url 'https://maven.nosmai.com' }
    }
}

Configuration

Initialize the SDK in your Application class:

import com.nosmai.camerasdk.CameraSDK

class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        CameraSDK.initialize(this, "YOUR_API_KEY")
    }
}

Basic Usage

Implement camera functionality in your Activity or Fragment:

import com.nosmai.camerasdk.CameraManager
import com.nosmai.camerasdk.CameraConfiguration
import com.nosmai.camerasdk.CameraCallback

class CameraActivity : AppCompatActivity() {
    private lateinit var cameraManager: CameraManager
    private lateinit var previewView: PreviewView
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_camera)
        
        previewView = findViewById(R.id.previewView)
        setupCamera()
    }
    
    private fun setupCamera() {
        cameraManager = CameraManager(this)
        
        val config = CameraConfiguration.Builder()
            .setResolution(CameraConfiguration.RESOLUTION_1080P)
            .setFrameRate(30)
            .setFlashMode(CameraConfiguration.FLASH_AUTO)
            .build()
        
        cameraManager.configure(config)
        cameraManager.startPreview(previewView)
    }
    
    private fun capturePhoto() {
        cameraManager.capturePhoto(object : CameraCallback<String> {
            override fun onSuccess(result: String) {
                // Handle captured photo path
                Log.d("Camera", "Photo saved to: $result")
            }
            
            override fun onError(error: Exception) {
                Log.e("Camera", "Capture failed", error)
            }
        })
    }
    
    override fun onDestroy() {
        super.onDestroy()
        cameraManager.release()
    }
}

Permissions

Add the following permissions to your AndroidManifest.xml:

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.camera" android:required="true" />
<uses-feature android:name="android.hardware.camera.autofocus" />

SDK Overview

The Nosmai Flutter SDK enables you to build stunning camera experiences with real-time beauty effects, professional filters, and GPU-accelerated processing for Flutter applications with full cross-platform support for iOS and Android.

System Requirements

iOS
  • iOS Version: iOS 11.0 or later
  • Xcode: 12.0 or later
  • Flutter: 3.0 or later
  • Architecture: arm64
Android
  • Android API Level: 21 (Android 5.0) or later
  • Flutter: 3.0 or later
  • NDK: Required for native processing
  • Architecture: arm64-v8a, armeabi-v7a

Installation & Setup

Add the Nosmai Flutter plugin to your project with proper platform configuration.

1. Add Dependencies

dependencies:
  nosmai_flutter: ^1.0.0
  permission_handler: ^11.0.0  # For camera permissions

2. Install Dependencies

flutter pub get

3. iOS Configuration (ios/Podfile)

platform :ios, '11.0'
use_frameworks! :linkage => :static

target 'Runner' do
  use_frameworks!
  use_modular_headers!
  
  flutter_install_all_macos_pods File.dirname(File.realpath(__FILE__))
end

4. Android Configuration (android/app/build.gradle)

android {
    compileSdkVersion 34
    
    defaultConfig {
        minSdkVersion 21
        targetSdkVersion 34
    }
    
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

Quick Start Guide

Initialize the SDK with proper permission handling and camera setup:

1. SDK Initialization

import 'package:nosmai_flutter/nosmai_flutter.dart';
import 'package:permission_handler/permission_handler.dart';

class CameraScreen extends StatefulWidget {
  @override
  _CameraScreenState createState() => _CameraScreenState();
}

class _CameraScreenState extends State<CameraScreen> {
  final NosmaiFlutter _nosmai = NosmaiFlutter.instance;
  bool _isInitialized = false;
  bool _isReady = false;

  @override
  void initState() {
    super.initState();
    _initializeSDK();
  }

  Future<void> _initializeSDK() async {
    // Request camera permission
    final status = await Permission.camera.request();
    if (status != PermissionStatus.granted) {
      print('Camera permission denied');
      return;
    }

    try {
      // Initialize with your license key
      final success = await _nosmai.initWithLicense(
        'YOUR_NOSMAI_LICENSE_KEY_HERE',
      );

      setState(() {
        _isInitialized = success;
      });

      if (success) {
        await _setupCamera();
      } else {
        print('Failed to initialize Nosmai SDK - check license key');
      }
    } catch (e) {
      print('SDK initialization error: $e');
    }
  }

  Future<void> _setupCamera() async {
    try {
      await _nosmai.configureCamera(
        position: NosmaiCameraPosition.front,
        sessionPreset: NosmaiSessionPreset.high,
        targetFrameRate: 30,
      );

      setState(() {
        _isReady = true;
      });
    } catch (e) {
      print('Camera setup error: $e');
    }
  }
}

Required Permissions

iOS (ios/Runner/Info.plist):

<key>NSCameraUsageDescription</key>
<string>This app needs camera access to apply filters and effects</string>
<key>NSMicrophoneUsageDescription</key>
<string>This app needs microphone access for video recording</string>
<key>NSPhotoLibraryAddUsageDescription</key>
<string>This app needs photo library access to save photos and videos</string>

Android (android/app/src/main/AndroidManifest.xml):

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.camera" android:required="true" />
<uses-feature android:name="android.hardware.camera.autofocus" />

Camera Preview & UI

Add the camera preview widget to your UI with controls:

@override
Widget build(BuildContext context) {
  return Scaffold(
    backgroundColor: Colors.black,
    body: _isReady
        ? Stack(
            children: [
              // Camera preview
              const Positioned.fill(
                child: NosmaiCameraPreview(
                  width: double.infinity,
                  height: double.infinity,
                ),
              ),
              
              // Controls overlay
              _buildControlsOverlay(),
            ],
          )
        : _buildLoadingScreen(),
  );
}

Widget _buildLoadingScreen() {
  return const Center(
    child: Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        CircularProgressIndicator(),
        SizedBox(height: 20),
        Text(
          'Initializing camera...',
          style: TextStyle(color: Colors.white),
        ),
      ],
    ),
  );
}

Widget _buildControlsOverlay() {
  return Positioned(
    bottom: 0,
    left: 0,
    right: 0,
    child: Container(
      padding: EdgeInsets.all(20),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.bottomCenter,
          end: Alignment.topCenter,
          colors: [Colors.black, Colors.transparent],
        ),
      ),
      child: Column(
        children: [
          _buildFilterSelector(),
          SizedBox(height: 20),
          _buildCaptureControls(),
        ],
      ),
    ),
  );
}

Local Filters (.nosmai Files)

Work with local filters stored in your app's assets:

Adding Local Filters to Project

  1. Create assets folder structure:
    assets/
      filters/
        vintage.nosmai
        cinematic.nosmai
        beauty.nosmai
  2. Add to pubspec.yaml:
    flutter:
      assets:
        - assets/filters/

Working with Local Filters

// Get all available local filters
List<NosmaiLocalFilter> localFilters = await _nosmai.getLocalFilters();

for (NosmaiLocalFilter filter in localFilters) {
  print('Local Filter: ${filter.displayName} -> ${filter.path}');
}

// Apply specific local filter
String filterPath = 'assets/filters/vintage.nosmai';
try {
  await _nosmai.applyEffect(filterPath);
  print('✅ Local filter applied successfully!');
} catch (e) {
  print('❌ Failed to apply filter: $e');
}

// Remove current filter
await _nosmai.removeAllFilters();
print('✅ All filters removed');

Cloud Filters

Download and apply cloud-based filters:

Fetching Available Cloud Filters

try {
  List<NosmaiCloudFilter> cloudFilters = await _nosmai.getCloudFilters();
  
  print('Found ${cloudFilters.length} cloud filters');
  
  for (NosmaiCloudFilter filter in cloudFilters) {
    print('Cloud Filter: ${filter.displayName}');
    print('  ID: ${filter.id}');
    print('  Downloaded: ${filter.isDownloaded}');
    print('  Thumbnail: ${filter.thumbnailUrl}');
  }
} catch (e) {
  print('❌ Failed to fetch cloud filters: $e');
}

Downloading and Applying Cloud Filters

// Download a specific cloud filter
String filterId = 'some_cloud_filter_id';

try {
  // Download with progress tracking
  await _nosmai.downloadCloudFilter(
    filterId,
    onProgress: (int percentage) {
      print('Download progress: $percentage%');
      // Update UI progress bar
    },
  );
  
  print('✅ Cloud filter downloaded successfully');
  
  // Apply the downloaded filter
  await _nosmai.applyCloudFilter(filterId);
  print('✅ Cloud filter applied!');
  
} catch (e) {
  print('❌ Failed to download/apply cloud filter: $e');
}

// Download and apply in one step
try {
  await _nosmai.downloadAndApplyCloudFilter(
    filterId,
    onProgress: (int percentage) {
      print('Downloading: $percentage%');
    },
  );
  print('✅ Cloud filter downloaded and applied!');
} catch (e) {
  print('❌ Failed: $e');
}

Beauty Enhancement Filters

Apply comprehensive beauty effects and face enhancements:

Complete Beauty Filter Suite

// FACE ENHANCEMENT
await _nosmai.applySkinSmoothing(0.7);     // 0.0 to 1.0 - Smooth skin texture
await _nosmai.applySkinWhitening(0.5);     // 0.0 to 1.0 - Natural skin brightening
await _nosmai.applyFaceSlimming(0.3);      // 0.0 to 1.0 - Subtle face contouring
await _nosmai.applyEyeEnlargement(0.4);    // 0.0 to 1.0 - Eye enhancement
await _nosmai.applyNoseSize(0.2);          // 0.0 to 1.0 - Nose refinement

// MAKEUP EFFECTS
await _nosmai.applyLipstick(0.6);          // 0.0 to 1.0 - Lipstick effect
await _nosmai.applyBlusher(0.4);           // 0.0 to 1.0 - Blusher effect

// COLOR & TONE ADJUSTMENTS
await _nosmai.applyBrightness(0.5);        // -1.0 to 1.0
await _nosmai.applyContrast(2.0);          // 0.0 to 4.0 (1.0 = normal)
await _nosmai.applyHue(180.0);             // 0-360 degrees
await _nosmai.applyExposure(1.5);          // -5.0 to 5.0
await _nosmai.applySaturation(1.5);        // 0.0 to 2.0 (1.0 = normal)
await _nosmai.applySharpen(0.8);           // 0.0 to 1.0
await _nosmai.applyWhiteBalance(5500.0, 10.0); // temp: 2000-8000K, tint: -100 to +100

// Enable/disable grayscale
await _nosmai.setGrayscaleEnabled(true);   // true/false

Apply Beauty Package

Future<void> _applyBeautyPackage() async {
  try {
    // Natural beauty enhancement package
    await _nosmai.applySkinSmoothing(0.6);     // Smooth skin
    await _nosmai.applySkinWhitening(0.3);     // Slight whitening
    await _nosmai.applyFaceSlimming(0.2);      // Subtle face slimming
    await _nosmai.applyEyeEnlargement(0.3);    // Bigger eyes
    await _nosmai.applyBrightness(0.1);        // Slightly brighter
    await _nosmai.applyContrast(1.2);          // Better contrast
    
    print('✅ Beauty package applied');
    // Show success message to user
  } catch (e) {
    print('❌ Beauty package failed: $e');
  }
}

// Remove all beauty effects
Future<void> _removeAllBeautyFilters() async {
  await _nosmai.removeAllBeautyFilters();
  print('✅ All beauty filters removed');
}

Video Recording & Photo Capture

Record videos and capture photos with applied filters:

Photo Capture

bool _isCapturing = false;

Future<void> _capturePhoto() async {
  if (_isCapturing) return;
  
  setState(() {
    _isCapturing = true;
  });
    
  try {
    final result = await _nosmai.capturePhoto();
    
    if (result.success) {
      print('✅ Photo captured successfully!');
      print('Photo dimensions: ${result.width}x${result.height}');
      print('Photo size: ${result.imageData.length} bytes');
      
      // Save to gallery
      await _savePhotoToGallery(result.imageData);
      
      // Show success message
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('📸 Photo saved to gallery!'),
          backgroundColor: Colors.green,
        ),
      );
    } else {
      print('❌ Photo capture failed: ${result.error}');
    }
  } catch (e) {
    print('❌ Photo capture error: $e');
  } finally {
    setState(() {
      _isCapturing = false;
    });
  }
}

Video Recording

bool _isRecording = false;
String? _currentVideoPath;

Future<void> _toggleRecording() async {
  try {
    if (_isRecording) {
      // Stop recording
      final result = await _nosmai.stopRecording();
      
      setState(() {
        _isRecording = false;
      });
      
      if (result.success && result.videoPath != null) {
        print('✅ Video saved: ${result.videoPath}');
        print('Duration: ${result.duration} seconds');
        print('File size: ${result.fileSize} bytes');
        
        _currentVideoPath = result.videoPath;
        
        // Add to gallery
        await _saveVideoToGallery(result.videoPath!);
        
        // Show success message
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('🎬 Video saved to gallery!'),
            backgroundColor: Colors.green,
            duration: Duration(seconds: 3),
          ),
        );
      } else {
        print('❌ Recording failed: ${result.error}');
      }
    } else {
      // Start recording
      final success = await _nosmai.startRecording();
      
      if (success) {
        setState(() {
          _isRecording = true;
        });
        print('🎬 Recording started!');
      } else {
        print('❌ Failed to start recording');
      }
    }
  } catch (e) {
    print('❌ Recording error: $e');
    setState(() {
      _isRecording = false;
    });
  }
}

Camera Management & Controls

Control camera operations and settings:

Camera Switching

bool _isFrontCamera = true;

Future<void> _switchCamera() async {
  if (_nosmai == null) {
    print('❌ Camera not ready');
    return;
  }
  
  try {
    print('🔄 Switching camera...');
    
    // Switch camera
    await _nosmai.switchCamera();
    
    // Update camera state
    setState(() {
      _isFrontCamera = !_isFrontCamera;
    });
    
    String cameraType = _isFrontCamera ? 'Front' : 'Back';
    print('✅ Switched to $cameraType camera');
    
  } catch (e) {
    print('❌ Camera switch failed: $e');
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('❌ Camera switch failed'),
        backgroundColor: Colors.red,
      ),
    );
  }
}

Camera Controls

// Focus control
Future<void> _setFocusPoint(Offset point) async {
  try {
    await _nosmai.setFocusPoint(point);
    print('📱 Focus set to: $point');
  } catch (e) {
    print('❌ Focus failed: $e');
  }
}

// Exposure control
Future<void> _setExposurePoint(Offset point) async {
  try {
    await _nosmai.setExposurePoint(point);
    print('🌞 Exposure set to: $point');
  } catch (e) {
    print('❌ Exposure failed: $e');
  }
}

// Zoom control
Future<void> _setZoomLevel(double zoomLevel) async {
  try {
    // Zoom level typically ranges from 1.0 to maxZoom
    await _nosmai.setZoomLevel(zoomLevel);
    print('🔍 Zoom set to: ${zoomLevel}x');
  } catch (e) {
    print('❌ Zoom failed: $e');
  }
}

// Flash control
Future<void> _toggleFlash() async {
  try {
    await _nosmai.toggleFlash();
    print('⚡ Flash toggled');
  } catch (e) {
    print('❌ Flash toggle failed: $e');
  }
}

Performance & Memory Management

Optimize performance and manage memory properly:

Performance Optimization

// Pre-load frequently used filters
Future<void> _preloadCommonFilters() async {
  final commonFilters = [
    'assets/filters/beauty.nosmai',
    'assets/filters/vintage.nosmai',
    'assets/filters/natural.nosmai',
  ];
  
  try {
    print('🔄 Preloading common filters...');
    
    for (final filter in commonFilters) {
      // Preload by applying and then removing
      await _nosmai.applyEffect(filter);
      await Future.delayed(Duration(milliseconds: 100));
    }
    
    // Remove all filters after preloading
    await _nosmai.removeAllFilters();
    
    print('✅ Common filters preloaded successfully');
  } catch (e) {
    print('❌ Preloading failed: $e');
  }
}

// Efficient filter switching
String? _currentFilterPath;

Future<void> _switchFilter(String newFilterPath) async {
  try {
    // Skip if same filter
    if (_currentFilterPath == newFilterPath) {
      return;
    }
    
    // Remove previous filter first
    if (_currentFilterPath != null) {
      await _nosmai.removeAllFilters();
    }
    
    // Apply new filter
    if (newFilterPath.isNotEmpty && newFilterPath != 'none') {
      await _nosmai.applyEffect(newFilterPath);
      _currentFilterPath = newFilterPath;
      print('✅ Switched to filter: $newFilterPath');
    } else {
      _currentFilterPath = null;
      print('✅ All filters removed');
    }
    
  } catch (e) {
    print('❌ Filter switch failed: $e');
  }
}

Lifecycle Management

class _CameraScreenState extends State<CameraScreen> with WidgetsBindingObserver {
  
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _initializeSDK();
  }
  
  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _cleanup();
    super.dispose();
  }
  
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.paused:
        if (_isRecording) {
          _toggleRecording(); // Stop recording
        }
        _nosmai.pauseProcessing();
        break;
      case AppLifecycleState.resumed:
        _nosmai.resumeProcessing();
        break;
      default:
        break;
    }
  }
  
  Future<void> _cleanup() async {
    try {
      print('🧹 Performing final cleanup...');
      
      // Stop recording if active
      if (_isRecording) {
        await _nosmai.stopRecording();
      }
      
      // Remove all filters
      await _nosmai.removeAllFilters();
      await _nosmai.removeAllBeautyFilters();
      
      // Stop processing and cleanup
      await _nosmai.stopProcessing();
      await _nosmai.cleanup();
      
      print('✅ Cleanup completed');
    } catch (e) {
      print('❌ Cleanup failed: $e');
    }
  }
}

Error Handling & Troubleshooting

Comprehensive error handling and common issue solutions:

Error Handling

class NosmaiErrorHandler {
  static void handleError(dynamic error, String context) {
    print('Nosmai Error in $context: $error');
    
    // Categorize and handle different error types
    if (error.toString().contains('license')) {
      _handleLicenseError(error);
    } else if (error.toString().contains('permission')) {
      _handlePermissionError(error);
    } else if (error.toString().contains('network')) {
      _handleNetworkError(error);
    } else if (error.toString().contains('memory')) {
      _handleMemoryError(error);
    } else {
      _handleGenericError(error, context);
    }
  }
  
  static void _handleLicenseError(dynamic error) {
    print('License Error: Please check your license key');
  }
  
  static void _handlePermissionError(dynamic error) {
    print('Permission Error: Please grant camera permissions');
  }
  
  static void _handleNetworkError(dynamic error) {
    print('Network Error: Please check your internet connection');
  }
  
  static void _handleMemoryError(dynamic error) {
    print('Memory Error: Performing cleanup');
    // Trigger memory cleanup
  }
  
  static void _handleGenericError(dynamic error, String context) {
    print('Unexpected Error in $context: $error');
  }
}

Common Issues & Solutions

  • SDK Initialization Fails: Verify license key and internet connection
  • Camera Preview Black Screen: Check camera permissions and configuration
  • Filters Not Applying: Ensure SDK is initialized and filter paths are correct
  • Recording Issues: Check microphone permissions and storage space
  • Memory Issues: Implement proper cleanup and memory management

Best Practices

  • Initialization: Always check license validation success
  • Memory Management: Call cleanup when done, handle memory warnings
  • Filter Management: Preload common filters, remove before applying new
  • Camera Operations: Check permissions, handle camera switching
  • Performance: Use appropriate session presets, limit concurrent effects
  • Error Handling: Implement comprehensive try-catch blocks

Support & Resources

Sample Projects

Download complete sample projects for iOS, Android, and Flutter implementations.

Get Samples →

Support

Get technical support from our team for integration and implementation questions.

Contact Support →