Camera engine for iOS, written in Swift, above AVFoundation. :monkey:

Overview

cameraenginelogo

🌟 The most advanced Camera framework in Swift 🌟

License MIT  Carthage compatible  CocoaPods  Build Status CocoaPods  Support  codebeat badge  Donate

CameraEngine is an iOS camera engine library that allows easy integration of special capture features and camera customization in your iOS app.

πŸ”₯ Features

CameraEngine
☺️ Support iOS8 - iOS9
πŸ“ Support orientation device
🏁 Fast capture
πŸ“· Photo capture
πŸŽ₯ Video capture
πŸ“ˆ quality settings presset video / photo capture
πŸ™‹ switch device (front, back)
πŸ’‘ flash mode management
πŸ”¦ torch mode management
πŸ”Ž focus mode management
:bowtie: detection face, barecode, and qrcode
πŸš€ GIF encoder

πŸ”¨ Installation

CocoaPods

  • Add pod "CameraEngine" to your Podfile.
  • Run pod install or pod update.
  • import CameraEngine

Carthage

  • Add github "remirobert/CameraEngine" to your Cartfile.
  • Run carthage update and add the framework to your project.
  • import CameraEngine

Manually

  • Download all the files in the CameraEngine subdirectory.
  • Add the source files to your Xcode project.
  • import CameraEngine

To add the Framework, you can also create a workspace for your project, then add the CameraEngine.xcodeproj, and the CameraEngine, then you should be able to compile the framework, and import it in your app project.

CameraEngine supports swift3, see the development branch for a swift 3 integration.

πŸš€ Quick start

First let's init and start the camera session. You can call that in viewDidLoad, or in appDelegate.

override func viewDidLoad() {
  super.viewDidLoad()
  self.cameraEngine.startSession()
}

Next time to display the preview layer

override func viewDidLayoutSubviews() {
  let layer = self.cameraEngine.previewLayer
        
  layer.frame = self.view.bounds
  self.view.layer.insertSublayer(layer, atIndex: 0)
  self.view.layer.masksToBounds = true
}

Capture a photo

self.cameraEngine.capturePhoto { (image: UIImage?, error: NSError?) -> (Void) in
  //get the picture tooked in the πŸ‘‰ image
}

Capture a video

(Void) in }) } private func stopRecording() { self.cameraEngine.stopRecordingVideo() } ">
private func startRecording() {
  guard let url = CameraEngineFileManager.documentPath("video.mp4") else {
    return
  }
            
  self.cameraEngine.startRecordingVideo(url, blockCompletion: { (url, error) -> (Void) in
  })
}

private func stopRecording() {
  self.cameraEngine.stopRecordingVideo()
}

Generate animated image GIF

(Void) in //Do some crazy stuff here }) ">
guard let url = CameraEngineFileManager.documentPath("animated.gif") else {
  return
}
self.cameraEngine.createGif(url, frames: self.frames, delayTime: 0.1, completionGif: { (success, url) -> (Void) in
  //Do some crazy stuff here
})

πŸ”§ configurations

CameraEngine, allows you to set some parameters, such as management of flash, torch and focus. But also on the quality of the media, which also has an impact on the size of the output file.

Flash

self.cameraEngine.flashMode = .On
self.cameraEngine.flashMode = .Off
self.cameraEngine.flashMode = .Auto

Torch

self.cameraEngine.torchMode = .On
self.cameraEngine.torchMode = .Off
self.cameraEngine.torchMode = .Auto

Focus

          |  CameraEngine focus

--------------------------|------------------------------------------------------------ .Locked | means the lens is at a fixed position .AutoFocus | means setting this will cause the camera to focus once automatically, and then return back to Locked .ContinuousAutoFocus | means the camera will automatically refocus on the center of the frame when the scene changes

self.cameraEngine.cameraFocus = .Locked
self.cameraEngine.cameraFocus = .AutoFocus
self.cameraEngine.cameraFocus = .ContinuousAutoFocus

Camera presset Photo

self.cameraEngine.sessionPresset = .Low
self.cameraEngine.sessionPresset = .Medium
self.cameraEngine.sessionPresset = .High
...

Camera presset Video

self.cameraEngine.videoEncoderPresset = .Preset640x480
self.cameraEngine.videoEncoderPresset = .Preset960x540
self.cameraEngine.videoEncoderPresset = .Preset1280x720
self.cameraEngine.videoEncoderPresset = .Preset1920x1080
self.cameraEngine.videoEncoderPresset = .Preset3840x2160

πŸ‘€ Object detection

CameraEngine can detect faces, QRcodes, or barcode. It will return all metadata on each frame, when it detects something. To exploit you whenever you want later.

Set the detection mode

self.cameraEngine.metadataDetection = .Face
self.cameraEngine.metadataDetection = .QRCode
self.cameraEngine.metadataDetection = .BareCode
self.cameraEngine.metadataDetection = .None //disable the detection

exploiting face detection

self.cameraEngine.blockCompletionFaceDetection = { faceObject in
  let frameFace = (faceObject as AVMetadataObject).bounds
  self.displayLayerDetection(frame: frameFace)
}

exploiting code detection (barecode and QRCode)

self.cameraEngine.blockCompletionCodeDetection = { codeObject in
  let valueCode = codeObject.stringValue
  let frameCode = (codeObject as AVMetadataObject).bounds
  self.displayLayerDetection(frame: frameCode)
}

πŸš— πŸ’¨ Example

You will find a sample project, which implements all the features of CameraEngine, with an interface that allows you to test and play with the settings. To run the example projet, run pod install, because it uses the current prod version of CameraEngine.

Contributors 🍻

License

This project is licensed under the terms of the MIT license. See the LICENSE file.

This project is in no way affiliated with Apple Inc. This project is open source under the MIT license, which means you have full access to the source code and can modify it to fit your own needs.

If you want to support the development of this library, feel free to Donate. Thanks to all contributors so far!

bannabot

Comments
  • Minimum deployment requirement

    Minimum deployment requirement

    Hey Remy. I was trying to get the new version into my project, which is developed on minimum iOS 8.0, CameraEngine requires minimum 9.2 to do pod install. Is there a way to fix this?

    opened by Jackson0111 13
  • Focus?

    Focus?

    CameraEngine is an awesome library, I'm loving it and thanks a lot for making my life easier. It would be fantastic if you could add tap to focus function though, any chance this could be done?

    opened by Jackson0111 9
  • Start assetWriter with video buffer

    Start assetWriter with video buffer

    Bug: The video frequently begins with a black screen.

    Only start the assetWriter with a video sample. Otherwise, the output video may be missing video frames at the start of the movie. Current fix ensures that no video frames are missing.

    opened by jnoh 7
  • Put start() in ViewDidLoad() causes crash

    Put start() in ViewDidLoad() causes crash

    I have following code in ViewDidLoad() and it causes app crash with error 'Can't add a nil AVCaptureInput' :

    override func viewDidLoad() {
    
        CameraEngine.startup()
    
        let preview: AVCaptureVideoPreviewLayer = CameraEngine.getPreviewLayer()
    
        preview.frame = self.view.bounds
    
        self.view.layer.addSublayer(preview)
    
        self.view.addSubview(takePhotoButton)
    
        cameraFlash.setImage(noFlash, forState: .Normal)
    
        CameraEngine.shareInstance().flash = false
    
        self.view.addSubview(cameraFlash) // flash light button
    
        photoLibrary.setImage(album, forState: .Normal)
    
        self.view.addSubview(photoLibrary) // open photo album button
    }
    
    opened by Jackson0111 7
  • Black preview

    Black preview

    Sometimes, the preview will be black once I call engine.startSession() so I have to restart my app and then the preview will load. I would say 1/10 times this happens.

    opened by danielchristopher1 6
  • Blank Screen?

    Blank Screen?

    Hi I am trying to follow the Quick Start on the README.md and have a blank screen when I run the app.

    import UIKit
    import CameraEngine
    
    
    class ViewController: UIViewController {
    
        let cameraEngine =  CameraEngine()
    
        override func viewDidLoad() {
            super.viewDidLoad()
            self.cameraEngine.startSession()
    
    }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
    
        override func viewDidLayoutSubviews() {
            let layer = self.cameraEngine.previewLayer
    
            layer.frame = self.view.bounds
            self.view.layer.insertSublayer(layer, atIndex: 0)
            self.view.layer.masksToBounds = true
    
    
        }
    
    
    
    
    }
    
    

    Please refer to the code here, any help appreciated

    opened by z3t0 5
  • Manually adding to XCode

    Manually adding to XCode

    Hi!

    I am new to iOS development and am trying to add this project to Xcode manually. Whenever I add it as a library I cannot import the module CameraEngine, as it is not found?

    Please explain how I can do this, Thanks!

    opened by z3t0 5
  • video short delay at beginning

    video short delay at beginning

    the video captured with CameraEngine has a short delay with black screen but with audio, just for about a second.

    is it ok there? maybe u can reproduce this issue.

    thanks a lot.

    opened by zinwalin 5
  • Added ability to access the underlying AVCaptureDevice and added isAdjustingX properties.

    Added ability to access the underlying AVCaptureDevice and added isAdjustingX properties.

    Not sure if this is what you meant, but I added access to the capture device and added the "adjustingFocus"/"adjustingExposure"/"adjustingWhiteBalance" properties.

    opened by eyaldar 4
  • No ability to access isAdjustingX properties of AVCaptureDevice

    No ability to access isAdjustingX properties of AVCaptureDevice

    Hi I would like to add a focusing animation but unfortunately I can't get access to the "IsAdjustingFocus"/"isAdjustingExposure"/"isAdjustingWhiteBalance" properties of AVCaptureDevice.

    Also due to lack of protected accessor in Swift I can't add access to those properties via extension. I would really appreciate access to those indicators, but in case you really oppose to adding it to your API - can you think of any solution that doesn't include managing my own fork?

    Thanks!

    opened by eyaldar 4
  • Crash on session.addOutput(self.captureVideoOutput)

    Crash on session.addOutput(self.captureVideoOutput)

    Ever since updating to XCode8 and Swift3, I've been getting a crash in CameraEngineOutput.swift in the func configureCaptureOutput

    session.addOutput(self.captureVideoOutput)
    

    I've updated my podfile to point to the 1.0 branch and the app builds fine, but it crashes on the splash screen giving the error: Thread 4: EXC_BAD_ACCESS (code=1, address=0x50) (Note: Thread 4 is the capturesession thread)

    Has anyone else been getting this? I'm at a loss as to what to do. Currently it's taking down my whole app... not just the camera tab. Everything was working great before the switch to Swift3.

    Thanks.

    opened by natewitty 3
  • [WIP] Swift 4 and some new api is available here

    [WIP] Swift 4 and some new api is available here

    If anyone needs Swift 4.1 version of Camera Engine it is available here

    This branch also contains some code refactoring per specific project requirements, which you might find helpful for your projects as well. It allows you specify requested device outputs, such as camera and microphone and provides callback which gives you detailed information about current device access request state and an ability to send back an action to be handled.

    Device access request states:

    public enum DeviceAccessState {
            public enum UnableToAdd {
                case camera, microphone
            }    
            case authorized // can proceed safely
            case denied // settings changes required
            case restricted // probably restricted at parental control
            case notDetermined // choice by the user wasn't made yet
            case unableToAdd(UnableToAdd)
            case other(String)
        }
    

    A list of actions can be applied after retrieving device access state:

    public enum DeviceAccessAction {
            case settingsChangeRequired // access was denied  or restricted at parental control
            case canPerformFirstTimeDeviceAccess // access not determined, can present in-app device access description (optional) before requesting on system level
            case canProceedAccessGranted // access granted, can proceed safely
            case unexpectedError(String)
        }
    

    Usage example:

    cameraEngine.startSession(devicePermissionRequests: [.camera, .microphone],
                                      deviceAccessPermissionHandler: { result, onFinishHandlingDeviceAccessState in
                switch result {
                case .camera(.denied),
                     .camera(.restricted),
                     .camera(.unableToAdd(.camera)),
                     .camera(.unableToAdd(.microphone)),
                     .microphone(.denied),
                     .microphone(.restricted),
                     .microphone(.unableToAdd(.microphone)),
                     .microphone(.unableToAdd(.camera)):
                    // print("sad :(")
                    // present in-app alert that OS settings change required
                    onFinishHandlingDeviceAccessState?(.settingsChangeRequired)
                case .camera(.notDetermined), .microphone(.notDetermined):
                    //
                    //print("ok, preparing ui for the showing permission request first time")
                    //
                    onFinishHandlingDeviceAccessState?(.canPerformFirstTimeDeviceAccess)
                case .camera(.authorized), .microphone(.authorized):
                    onFinishHandlingDeviceAccessState?(.canProceedAccessGranted)
                case let .camera(.other(errorMessage)):
                    onFinishHandlingDeviceAccessState?(.unexpectedError(errorMessage))
                case let .microphone(.other(errorMessage)):
                    onFinishHandlingDeviceAccessState?(.unexpectedError(errorMessage))
                case .camera(.runningOnSimulator),
                     .microphone(.runningOnSimulator):
                    print("can't use camera device when running on simulator")
                }
            })
    

    CameraEngineSessionPreset was updated to match with the native Apple's naming: before:

    public enum CameraEngineSessionPreset {
        case photo
        case high
        case medium
        case low
        case res352x288
        case res640x480
        case res1280x720
        case res1920x1080
        case res3840x2160
        case frame960x540
        case frame1280x720
        case inputPriority
    

    After

    public enum CameraEngineSessionPreset {
        case photo
        case high
        case medium
        case low
        case cif352x288
        case vga640x480
        case hd1280x720
        case hd1920x1080
        case hd4k3840x2160
        case iFrame960x540
        case iFrame1280x720
        case inputPriority
    

    Though some things are still needs to be finished. Such as getting rid of redundancy like:

    .microphone(.unableToAdd(.microphone)),
    .microphone(.unableToAdd(.camera)):
    

    I'm a bit busy at the moment with main work at another project, will try to finish this and make PR asap, when I get a chance. Feel free to message me here I you found something wrong or you want to add or change. And many thanks to @remirobert for writing and sharing this library.

    opened by freemansion 6
  • is it possible to store video buffer for 5 seconds and after tap of button, it save the last 5 seconds?

    is it possible to store video buffer for 5 seconds and after tap of button, it save the last 5 seconds?

    is it possible to store video buffer for 5 seconds and after tap of button, it save the last 5 seconds? there can be multiple tap during camera preview. every tap, it will save the last 5 seconds.

    opened by steve21124 0
  • Cant get barcode detection to wok

    Cant get barcode detection to wok

    Using the example provided, ive added the following lines to viewDidLoad()

            self.cameraEngine.metadataDetection = .barcode
            
            self.cameraEngine.blockCompletionCodeDetection = { codeObject in
                print(codeObject.stringValue)
                let valueCode = codeObject.stringValue
                let frameCode = (codeObject as AVMetadataObject).bounds
                print(frameCode)
    //            self.displayLayerDetection(frame: frameCode)
            }
    

    and am unable to detect ean13 codes. is there something else i need to do?

    opened by multinerd 1
A fully customisable and modern camera implementation for iOS made with AVFoundation.

Features Extremely simple and easy to use Controls autofocus & exposure Customizable interface Code-made UI assets that do not lose resolution quality

Gabriel Alvarado 1.3k Nov 30, 2022
A camera app we will dive deep into AVFoundation library

Camera App In this project you are going to discover few concepts in Swift that I've been working on for few weeks, Core Animations with CAShape Layer

Dheeraj Kumar Sharma 12 Nov 13, 2022
iOS camera engine with Vine-like tap to record, animatable filters, slow motion, segments editing

SCRecorder A Vine/Instagram like audio/video recorder and filter framework in Objective-C. In short, here is a short list of the cool things you can d

Simon Corsin 3.1k Dec 25, 2022
Library for iOS Camera API. CameraKit helps you add reliable camera to your app quickly.

CameraKit helps you add reliable camera to your app quickly. Our open source camera platform provides consistent capture results, service that scales, and endless camera possibilities.

CameraKit 628 Dec 27, 2022
A Snapchat Inspired iOS Camera Framework written in Swift

Overview SwiftyCam is a a simple, Snapchat-style iOS Camera framework for easy photo and video capture. SwiftyCam allows users to capture both photos

Andrew Walz 2k Dec 21, 2022
NextLevel is a Swift camera system designed for easy integration, customized media capture, and image streaming in iOS

NextLevel is a Swift camera system designed for easy integration, customized media capture, and image streaming in iOS. Integration can optionally leverage AVFoundation or ARKit.

NextLevel 2k Jan 2, 2023
A light weight & simple & easy camera for iOS by Swift.

DKCamera Description A light weight & simple & easy camera for iOS by Swift. It uses CoreMotion framework to detect device orientation, so the screen-

Bannings 86 Aug 18, 2022
A simple, customizable camera control - video recorder for iOS.

LLSimpleCamera: A simple customizable camera - video recorder control LLSimpleCamera is a library for creating a customized camera - video recorder sc

Γ–mer Faruk GΓΌl 1.2k Dec 12, 2022
Fasttt and easy camera framework for iOS with customizable filters

FastttCamera is a wrapper around AVFoundation that allows you to build your own powerful custom camera app without all the headaches of using AVFounda

IFTTT 1.8k Dec 10, 2022
An iOS framework that uses the front camera, detects your face and takes a selfie.

TakeASelfie An iOS framework that uses the front camera, detects your face and takes a selfie. This api opens the front camera and draws an green oval

Abdullah Selek 37 Jan 3, 2023
Video and photo camera for iOS

Features: Description Records video ?? takes photos ?? Flash on/off ⚑ Front / Back camera ↕️ Hold to record video ✊ Tap to take photo ?? Tap to focus

AndrΓ© J 192 Dec 17, 2022
Instagram-like photo browser and a camera feature with a few line of code in Swift.

Fusuma is a Swift library that provides an Instagram-like photo browser with a camera feature using only a few lines of code.

Yuta Akizuki 2.4k Dec 31, 2022
Simple Swift class to provide all the configurations you need to create custom camera view in your app

Camera Manager This is a simple Swift class to provide all the configurations you need to create custom camera view in your app. It follows orientatio

Imaginary Cloud 1.3k Dec 29, 2022
A camera designed in Swift for easily integrating CoreML models - as well as image streaming, QR/Barcode detection, and many other features

Would you like to use a fully-functional camera in an iOS application in seconds? Would you like to do CoreML image recognition in just a few more sec

David Okun 868 Dec 29, 2022
ALCameraViewController - A camera view controller with custom image picker and image cropping.

ALCameraViewController A camera view controller with custom image picker and image cropping. Features Front facing and rear facing camera Simple and c

Alex Littlejohn 2k Dec 6, 2022
UIView+CameraBackground - Show camera layer as a background to any UIView.

UIView+CameraBackground Show camera layer as a background to any UIView. Features Both front and back camera supported. Flash modes: auto, on, off. Co

Yonat Sharon 63 Nov 15, 2022
This plugin defines a global navigator.camera object, which provides an API for taking pictures and for choosing images from the system's image library.

title description Camera Take pictures with the device camera. AppVeyor Travis CI cordova-plugin-camera This plugin defines a global navigator.camera

null 0 Nov 2, 2021
BarcodeScanner is a simple and beautiful wrapper around the camera with barcode capturing functionality and a great user experience.

Description BarcodeScanner is a simple and beautiful wrapper around the camera with barcode capturing functionality and a great user experience. Barco

HyperRedink 1.6k Jan 7, 2023
Mock UIImagePickerController for testing camera based UI in simulator

Mock UIImagePickerController to simulate the camera in iOS simulator.

Yonat Sharon 18 Aug 18, 2022