Compare commits
51 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 350a67d63e | |||
| 0832eeb927 | |||
| 3eb3c4db2b | |||
| f2f64a6580 | |||
| e388eaa21e | |||
| 507ec687c3 | |||
| d79e2d4829 | |||
| 387c864e71 | |||
| c44194230b | |||
| 7870134192 | |||
| 3cb80cba01 | |||
| 658fb4ca07 | |||
| 94e3dddfea | |||
| d3f52c26f4 | |||
| 4dd890a885 | |||
| a320a51e90 | |||
| 1ab12173f4 | |||
| a513e4157f | |||
| 11b1d4738b | |||
| 7a63dbe34a | |||
| 05ee09b1ce | |||
| 30afffd79f | |||
| 3b6e4f60c8 | |||
| 7b5326adcb | |||
| e6d24ec1b4 | |||
| 5c419c3031 | |||
| 0653f11cfd | |||
| bc70751aff | |||
| ebb2d0a485 | |||
| 483bf4563b | |||
| 2015b4db0e | |||
| 85e846ef25 | |||
| 8420a3808f | |||
| 1fb3a03593 | |||
| cd0d7f34cf | |||
| 6a4290e17b | |||
| 3379dbaba4 | |||
| 8e7eafb797 | |||
| 62f90d09ef | |||
| f0c0c393a0 | |||
| c798581992 | |||
| aa625e8a56 | |||
| 0b09ad4483 | |||
| 15124d26cc | |||
| 525c802ca4 | |||
| 1b786d4c3d | |||
| 5d20554db4 | |||
| f79760470e | |||
| 469d1fcc70 | |||
| a7bf5a0894 | |||
| d27f999341 |
@@ -1 +0,0 @@
|
||||
echo "4.0" > .swift-version
|
||||
+4
-3
@@ -1,11 +1,11 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = "ARVideoKit"
|
||||
s.version = "1.3"
|
||||
s.version = "1.51"
|
||||
s.summary = "Capture & record ARKit videos 📹, photos 🌄, Live Photos 🎇, and GIFs 🎆."
|
||||
s.description = "Enabling developers to capture videos 📹, photos 🌄, Live Photos 🎇, and GIFs 🎆 with augmented reality components."
|
||||
s.homepage = "https://github.com/AFathi/ARVideoKit"
|
||||
s.screenshots = "http://www.ahmedbekhit.com/SK_PREV.gif", "http://www.ahmedbekhit.com/SCN_PREVIEW.gif"
|
||||
|
||||
s.swift_version = '4.2'
|
||||
|
||||
|
||||
s.license = { :type => "Apache 2.0", :file => "LICENSE" }
|
||||
@@ -16,7 +16,8 @@ Pod::Spec.new do |s|
|
||||
|
||||
s.platform = :ios, "11.0"
|
||||
|
||||
s.source = { :git => "https://github.com/AFathi/ARVideoKit.git", :tag => "1.3" }
|
||||
# ARVideoKit for Swift 4.2
|
||||
s.source = { :git => "https://github.com/AFathi/ARVideoKit.git", :tag => "1.51" }
|
||||
s.source_files = "ARVideoKit", "ARVideoKit/**/*.{h,m,swift}"
|
||||
s.resources = "ARVideoKit/Assets/*.scnassets"
|
||||
end
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
B466A8B82279E34C00BD7070 /* WeakProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = B466A8B72279E34C00BD7070 /* WeakProxy.swift */; };
|
||||
FB2E36891FAE29C00035B8D6 /* LICENSE in Resources */ = {isa = PBXBuildFile; fileRef = FB2E36881FAE29BF0035B8D6 /* LICENSE */; };
|
||||
FB404FFE20D72A190056EA1D /* JPEG.swift in Sources */ = {isa = PBXBuildFile; fileRef = FB404FFD20D72A190056EA1D /* JPEG.swift */; };
|
||||
FBD604DF1FA969DD00EC9804 /* ARVideoKit.h in Headers */ = {isa = PBXBuildFile; fileRef = FBD604DD1FA969DD00EC9804 /* ARVideoKit.h */; settings = {ATTRIBUTES = (Public, ); }; };
|
||||
@@ -33,6 +34,7 @@
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
B466A8B72279E34C00BD7070 /* WeakProxy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WeakProxy.swift; sourceTree = "<group>"; };
|
||||
FB2E36881FAE29BF0035B8D6 /* LICENSE */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = LICENSE; sourceTree = "<group>"; };
|
||||
FB404FFD20D72A190056EA1D /* JPEG.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JPEG.swift; sourceTree = "<group>"; };
|
||||
FBD604DA1FA969DD00EC9804 /* ARVideoKit.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = ARVideoKit.framework; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
@@ -71,6 +73,14 @@
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
B466A8B62279E33800BD7070 /* Utils */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
B466A8B72279E34C00BD7070 /* WeakProxy.swift */,
|
||||
);
|
||||
path = Utils;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
FBA0AA0A1FAD9D9D006C481B /* Writer */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
@@ -99,6 +109,7 @@
|
||||
FBD604DC1FA969DD00EC9804 /* ARVideoKit */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
B466A8B62279E33800BD7070 /* Utils */,
|
||||
FBD604E51FA96ACD00EC9804 /* Assets */,
|
||||
FBD604E61FA96AD400EC9804 /* Enumerations */,
|
||||
FBD604E71FA96AE500EC9804 /* Extensions */,
|
||||
@@ -171,11 +182,9 @@
|
||||
FBD605011FA96B5900EC9804 /* Live Photo */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
FBD605021FA96B6B00EC9804 /* LoveLiver_LICENSE */,
|
||||
FBDBF6BA20F3E009004E757D /* LoveLiver */,
|
||||
FBD605031FA96B6B00EC9804 /* Generate+LivePhoto.swift */,
|
||||
FBD605061FA96B6B00EC9804 /* PHLivePhotoPlus.swift */,
|
||||
FB404FFD20D72A190056EA1D /* JPEG.swift */,
|
||||
FBD605051FA96B6B00EC9804 /* QuickTimeMov.swift */,
|
||||
);
|
||||
path = "Live Photo";
|
||||
sourceTree = "<group>";
|
||||
@@ -190,6 +199,16 @@
|
||||
path = Sources;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
FBDBF6BA20F3E009004E757D /* LoveLiver */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
FBD605021FA96B6B00EC9804 /* LoveLiver_LICENSE */,
|
||||
FB404FFD20D72A190056EA1D /* JPEG.swift */,
|
||||
FBD605051FA96B6B00EC9804 /* QuickTimeMov.swift */,
|
||||
);
|
||||
path = LoveLiver;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXHeadersBuildPhase section */
|
||||
@@ -282,6 +301,7 @@
|
||||
FBD604F51FA96B3300EC9804 /* UIImage+VideoBuffer.swift in Sources */,
|
||||
FBD605111FA96BA100EC9804 /* ARView.swift in Sources */,
|
||||
FBD604F61FA96B3300EC9804 /* CGImage+Resize.swift in Sources */,
|
||||
B466A8B82279E34C00BD7070 /* WeakProxy.swift in Sources */,
|
||||
FBD604F91FA96B3300EC9804 /* UIViewController+hasType.swift in Sources */,
|
||||
FBD605141FA96BA100EC9804 /* ViewAR.swift in Sources */,
|
||||
FBD604EE1FA96B2700EC9804 /* ARVideoOptions.swift in Sources */,
|
||||
@@ -442,7 +462,7 @@
|
||||
PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)";
|
||||
SKIP_INSTALL = YES;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
SWIFT_VERSION = 4.0;
|
||||
SWIFT_VERSION = 4.2;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
};
|
||||
name = Debug;
|
||||
@@ -467,7 +487,7 @@
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.ahmedbekhit.ARVideoKit;
|
||||
PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)";
|
||||
SKIP_INSTALL = YES;
|
||||
SWIFT_VERSION = 4.0;
|
||||
SWIFT_VERSION = 4.2;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
};
|
||||
name = Release;
|
||||
|
||||
@@ -3,6 +3,6 @@
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>IDEWorkspaceSharedSettings_AutocreateContextsIfNeeded</key>
|
||||
<false/>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0940"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "FBD604D91FA969DD00EC9804"
|
||||
BuildableName = "ARVideoKit.framework"
|
||||
BlueprintName = "ARVideoKit"
|
||||
ReferencedContainer = "container:ARVideoKit.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
</Testables>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Release"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "FBD604D91FA969DD00EC9804"
|
||||
BuildableName = "ARVideoKit.framework"
|
||||
BlueprintName = "ARVideoKit"
|
||||
ReferencedContainer = "container:ARVideoKit.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "FBD604D91FA969DD00EC9804"
|
||||
BuildableName = "ARVideoKit.framework"
|
||||
BlueprintName = "ARVideoKit"
|
||||
ReferencedContainer = "container:ARVideoKit.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -13,6 +13,7 @@
|
||||
/// Recommended for iPhone X
|
||||
case aspectFill
|
||||
}
|
||||
|
||||
/// Allows specifying the video rendering frame per second `FPS` rate.
|
||||
@objc public enum ARVideoFrameRate: Int {
|
||||
/// The framework automatically sets the most appropriate `FPS` based on the device support.
|
||||
@@ -22,6 +23,7 @@
|
||||
/// Sets the `FPS` to 60 frames per second.
|
||||
case fps60 = 60
|
||||
}
|
||||
|
||||
/// Allows specifying the final video orientation.
|
||||
@objc public enum ARVideoOrientation: Int {
|
||||
/// The framework automatically sets the video orientation based on the active `ARInputViewOrientation` orientations.
|
||||
@@ -31,6 +33,7 @@
|
||||
/// Sets the video orientation to always landscape.
|
||||
case alwaysLandscape
|
||||
}
|
||||
|
||||
/// Allows specifying when to request Microphone access.
|
||||
@objc public enum RecordARMicrophonePermission: Int {
|
||||
/// The framework automatically requests Microphone access when needed.
|
||||
@@ -38,6 +41,7 @@
|
||||
/// Allows manual permission request.
|
||||
case manual
|
||||
}
|
||||
|
||||
/// An object that returns the AR recorder current status.
|
||||
@objc public enum RecordARStatus: Int {
|
||||
/// The current status of the recorder is unknown.
|
||||
@@ -49,6 +53,7 @@
|
||||
/// The current recorder is paused.
|
||||
case paused
|
||||
}
|
||||
|
||||
/// An object that returns the current Microphone status.
|
||||
@objc public enum RecordARMicrophoneStatus: Int {
|
||||
// The current status of the Microphone access is unknown.
|
||||
|
||||
@@ -8,19 +8,16 @@
|
||||
|
||||
import CoreGraphics
|
||||
|
||||
internal extension CGImage {
|
||||
internal func resize(with ratio:Float) -> CGImage? {
|
||||
let imageWidth = Float(self.width)
|
||||
let imageHeight = Float(self.height)
|
||||
|
||||
let width = imageWidth * ratio
|
||||
let height = imageHeight * ratio
|
||||
extension CGImage {
|
||||
func resize(with ratio: Float) -> CGImage? {
|
||||
let imageWidth: Int = Int(Float(self.width) * ratio)
|
||||
let imageHeight: Int = Int(Float(self.height) * ratio)
|
||||
|
||||
guard let colorSpace = self.colorSpace else { return nil }
|
||||
guard let context = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: self.bitsPerComponent, bytesPerRow: self.bytesPerRow, space: colorSpace, bitmapInfo: self.alphaInfo.rawValue) else { return nil }
|
||||
guard let context = CGContext(data: nil, width: imageWidth, height: imageHeight, bitsPerComponent: self.bitsPerComponent, bytesPerRow: self.bytesPerRow, space: colorSpace, bitmapInfo: self.alphaInfo.rawValue) else { return nil }
|
||||
|
||||
context.interpolationQuality = .low
|
||||
context.draw(self, in: CGRect(x: 0, y: 0, width: Int(width), height: Int(height)))
|
||||
context.draw(self, in: CGRect(x: 0, y: 0, width: imageWidth, height: imageHeight))
|
||||
|
||||
return context.makeImage()
|
||||
}
|
||||
|
||||
@@ -8,14 +8,15 @@
|
||||
|
||||
import AVFoundation
|
||||
import Photos
|
||||
|
||||
@available(iOS 11.0, *)
|
||||
internal extension RecordAR {
|
||||
extension RecordAR {
|
||||
|
||||
internal func adjustTime(current:CMTime, resume:CMTime, pause:CMTime) -> CMTime {
|
||||
func adjustTime(current: CMTime, resume: CMTime, pause: CMTime) -> CMTime {
|
||||
return CMTimeSubtract(current, CMTimeSubtract(resume, pause))
|
||||
}
|
||||
|
||||
internal func imageFromBuffer(buffer:CVPixelBuffer) -> UIImage {
|
||||
func imageFromBuffer(buffer: CVPixelBuffer) -> UIImage {
|
||||
let coreImg = CIImage(cvPixelBuffer: buffer)
|
||||
let context = CIContext()
|
||||
let cgImg = context.createCGImage(coreImg, from: coreImg.extent)
|
||||
@@ -29,8 +30,8 @@ internal extension RecordAR {
|
||||
return false
|
||||
}
|
||||
|
||||
var recentAngle:CGFloat = 0
|
||||
var rotationAngle:CGFloat = 0
|
||||
var recentAngle: CGFloat = 0
|
||||
var rotationAngle: CGFloat = 0
|
||||
switch UIDevice.current.orientation {
|
||||
case .landscapeLeft:
|
||||
rotationAngle = -90
|
||||
@@ -53,8 +54,7 @@ internal extension RecordAR {
|
||||
case .alwaysPortrait:
|
||||
rotationAngle = 0
|
||||
case .alwaysLandscape:
|
||||
if rotationAngle == 90 || rotationAngle == -90 {
|
||||
}else{
|
||||
if rotationAngle != 90 || rotationAngle != -90 {
|
||||
rotationAngle = -90
|
||||
}
|
||||
default:
|
||||
@@ -64,7 +64,7 @@ internal extension RecordAR {
|
||||
return UIImage(cgImage: cgImg!).rotate(by: rotationAngle, flip: false)
|
||||
}
|
||||
|
||||
@objc internal func appWillEnterBackground() {
|
||||
@objc func appWillEnterBackground() {
|
||||
delegate?.recorder(willEnterBackground: status)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,9 +8,10 @@
|
||||
|
||||
import CoreVideo
|
||||
import UIKit
|
||||
internal extension UIImage
|
||||
|
||||
extension UIImage
|
||||
{
|
||||
internal func rotate(by degrees: CGFloat, flip:Bool?=nil) -> UIImage
|
||||
func rotate(by degrees: CGFloat, flip: Bool? = nil) -> UIImage
|
||||
{
|
||||
let radians = CGFloat(degrees * (CGFloat.pi / 180.0))
|
||||
|
||||
@@ -26,10 +27,10 @@ internal extension UIImage
|
||||
if let isFlipped = flip {
|
||||
if !isFlipped {
|
||||
bitmap?.scaleBy(x: 1.0, y: -1.0)
|
||||
}else{
|
||||
} else {
|
||||
bitmap?.scaleBy(x: -1.0, y: -1.0)
|
||||
}
|
||||
}else{
|
||||
} else {
|
||||
bitmap?.scaleBy(x: -1.0, y: -1.0)
|
||||
}
|
||||
bitmap?.draw(self.cgImage!, in: CGRect(origin: CGPoint(x: -self.size.width / 2, y: -self.size.height / 2), size: self.size))
|
||||
@@ -41,7 +42,7 @@ internal extension UIImage
|
||||
|
||||
var buffer: CVPixelBuffer? {
|
||||
let attrs = [kCVPixelBufferCGImageCompatibilityKey: kCFBooleanTrue, kCVPixelBufferCGBitmapContextCompatibilityKey: kCFBooleanTrue] as CFDictionary
|
||||
var pixelBuffer : CVPixelBuffer?
|
||||
var pixelBuffer: CVPixelBuffer?
|
||||
let status = CVPixelBufferCreate(kCFAllocatorDefault, Int(self.size.width), Int(self.size.height), kCVPixelFormatType_32ARGB, attrs, &pixelBuffer)
|
||||
guard (status == kCVReturnSuccess) else {
|
||||
return nil
|
||||
|
||||
@@ -8,17 +8,18 @@
|
||||
|
||||
import UIKit
|
||||
import ARKit
|
||||
|
||||
@available(iOS 11.0, *)
|
||||
internal extension UIScreen {
|
||||
extension UIScreen {
|
||||
/**
|
||||
`isiPhone10` is a boolean that returns if the device is iPhone X or not.
|
||||
*/
|
||||
internal var isiPhone10: Bool {
|
||||
var isiPhone10: Bool {
|
||||
return self.nativeBounds.size == CGSize(width: 1125, height: 2436) || self.nativeBounds.size == CGSize(width: 2436, height: 1125)
|
||||
}
|
||||
}
|
||||
@available(iOS 11.0, *)
|
||||
internal extension UIView {
|
||||
extension UIView {
|
||||
var parent: UIViewController? {
|
||||
var responder: UIResponder? = self
|
||||
while responder != nil {
|
||||
@@ -31,20 +32,10 @@ internal extension UIView {
|
||||
}
|
||||
|
||||
var isButton: Bool {
|
||||
if let _ = self as? UIButton {
|
||||
return true
|
||||
}else{
|
||||
return false
|
||||
}
|
||||
return (self is UIButton)
|
||||
}
|
||||
|
||||
var isARView: Bool {
|
||||
if let _ = self as? ARSCNView {
|
||||
return true
|
||||
}else if let _ = self as? ARSKView {
|
||||
return true
|
||||
}else {
|
||||
return false
|
||||
}
|
||||
return (self is ARSCNView) || (self is ARSKView)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,17 +8,14 @@
|
||||
|
||||
import UIKit
|
||||
import ARKit
|
||||
|
||||
@available(iOS 11.0, *)
|
||||
internal extension UIViewController {
|
||||
internal var hasARView: Bool {
|
||||
extension UIViewController {
|
||||
var hasARView: Bool {
|
||||
let views = self.view.subviews
|
||||
for v in views {
|
||||
if let _ = v as? ARSCNView {
|
||||
if v is ARSCNView || v is ARSKView {
|
||||
return true
|
||||
}else if let _ = v as? ARSKView {
|
||||
return true
|
||||
}else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return false
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>FMWK</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.31</string>
|
||||
<string>1.32</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>$(CURRENT_PROJECT_VERSION)</string>
|
||||
<key>NSPrincipalClass</key>
|
||||
|
||||
@@ -10,6 +10,7 @@ import Foundation
|
||||
import CoreVideo
|
||||
import CoreMedia
|
||||
import ARKit
|
||||
|
||||
/**
|
||||
The recorder protocol.
|
||||
|
||||
@@ -26,13 +27,26 @@ import ARKit
|
||||
- parameter path: A `URL` object that returns the video file path.
|
||||
- parameter noError: A boolean that returns true when the recorder ends without errors. Otherwise, it returns false.
|
||||
*/
|
||||
func recorder(didEndRecording path:URL, with noError:Bool)
|
||||
func recorder(didEndRecording path: URL, with noError: Bool)
|
||||
|
||||
/**
|
||||
A protocol method that is triggered when a recorder fails recording.
|
||||
- parameter error: An `Error` object that returns the error value.
|
||||
- parameter status: A string that returns the reason of the recorder failure in a string literal format.
|
||||
*/
|
||||
func recorder(didFailRecording error:Error?, and status:String)
|
||||
func recorder(didFailRecording error: Error?, and status: String)
|
||||
|
||||
/**
|
||||
A protocol method that is triggered when a recorder is cancelled.
|
||||
- parameter status: A string that returns the reason the of recorder cancelation in a string literal format.
|
||||
*/
|
||||
@objc optional func recorder(didCancelRecording status: String)
|
||||
|
||||
/**
|
||||
A protocol method that is triggered when a recorder is modified.
|
||||
- parameter duration: A double that returns the duration of current recording
|
||||
*/
|
||||
@objc optional func recorder(didUpdateRecording duration: TimeInterval)
|
||||
|
||||
/**
|
||||
A protocol method that is triggered when the application will resign active.
|
||||
@@ -41,5 +55,5 @@ import ARKit
|
||||
|
||||
- NOTE: Check [applicationWillResignActive(_:)](https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622950-applicationwillresignactive) for more information.
|
||||
*/
|
||||
@objc func recorder(willEnterBackground status:RecordARStatus)
|
||||
@objc func recorder(willEnterBackground status: RecordARStatus)
|
||||
}
|
||||
|
||||
@@ -28,5 +28,5 @@ import ARKit
|
||||
- parameter time: A `CMTime` object that returns the time a buffer was rendered with.
|
||||
- parameter rawBuffer: A `CVPixelBuffer` object that returns the raw buffer.
|
||||
*/
|
||||
func frame(didRender buffer:CVPixelBuffer, with time:CMTime, using rawBuffer:CVPixelBuffer)
|
||||
func frame(didRender buffer: CVPixelBuffer, with time: CMTime, using rawBuffer: CVPixelBuffer)
|
||||
}
|
||||
|
||||
@@ -11,10 +11,10 @@ import AVFoundation
|
||||
import ImageIO
|
||||
import MobileCoreServices
|
||||
|
||||
internal class GIFGenerator {
|
||||
internal let gifQueue = DispatchQueue(label:"com.ahmedbekhit.GIFQueue", attributes: .concurrent)
|
||||
fileprivate var currentGIFPath:URL?
|
||||
fileprivate var newGIFPath:URL {
|
||||
class GIFGenerator {
|
||||
let gifQueue = DispatchQueue(label:"com.ahmedbekhit.GIFQueue", attributes: .concurrent)
|
||||
private var currentGIFPath: URL?
|
||||
private var newGIFPath: URL {
|
||||
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
|
||||
let documentsDirectory = paths[0]
|
||||
|
||||
@@ -29,29 +29,32 @@ internal class GIFGenerator {
|
||||
return URL(fileURLWithPath: gifPath, isDirectory: false)
|
||||
}
|
||||
|
||||
internal func generate(gif images:[UIImage], with delay:Float, loop count:Int = 0, adjust:Bool, _ finished: ((_ status: Bool, _ path: URL?) -> Void)? = nil) {
|
||||
func generate(gif images:[UIImage], with delay: Float, loop count: Int = 0, adjust: Bool, _ finished: ((_ status: Bool, _ path: URL?) -> Void)? = nil) {
|
||||
currentGIFPath = newGIFPath
|
||||
gifQueue.async {
|
||||
let gifSettings = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: count]]
|
||||
let imageSettings = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFDelayTime as String: delay]]
|
||||
|
||||
guard let path = self.currentGIFPath else{return}
|
||||
guard let destination = CGImageDestinationCreateWithURL(path as CFURL, kUTTypeGIF, images.count, nil) else{finished?(false, nil);return}
|
||||
guard let path = self.currentGIFPath else { return }
|
||||
guard let destination = CGImageDestinationCreateWithURL(path as CFURL, kUTTypeGIF, images.count, nil) else {
|
||||
finished?(false, nil)
|
||||
return
|
||||
}
|
||||
logAR.message("\(destination)")
|
||||
CGImageDestinationSetProperties(destination, gifSettings as CFDictionary)
|
||||
for image in images {
|
||||
if let imageRef = image.cgImage {
|
||||
var ratio:Float = 0.0
|
||||
if adjust{ratio=0.5}else{ratio=1.0}
|
||||
var ratio: Float = 0.0
|
||||
if adjust { ratio = 0.5 } else { ratio = 1.0 }
|
||||
CGImageDestinationAddImage(destination, imageRef.resize(with: ratio)!, imageSettings as CFDictionary)
|
||||
}
|
||||
}
|
||||
|
||||
if !CGImageDestinationFinalize(destination){
|
||||
finished?(false, nil);
|
||||
finished?(false, nil)
|
||||
return
|
||||
}else{
|
||||
finished?(true, path);
|
||||
} else {
|
||||
finished?(true, path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,32 +8,33 @@
|
||||
|
||||
import AVFoundation
|
||||
import Photos
|
||||
@available(iOS 11.0, *)
|
||||
internal class LivePhotoGenerator {
|
||||
fileprivate var keyPhotoPath:URL?
|
||||
|
||||
fileprivate var finalKeyPhotoPath:URL?
|
||||
fileprivate var finalPairedVideoPath:URL?
|
||||
@available(iOS 11.0, *)
|
||||
class LivePhotoGenerator {
|
||||
private var keyPhotoPath: URL?
|
||||
|
||||
private var finalKeyPhotoPath: URL?
|
||||
private var finalPairedVideoPath: URL?
|
||||
|
||||
internal let livePhotoQueue = DispatchQueue(label:"com.ahmedbekhit.livePhotoQueue", attributes: .concurrent)
|
||||
let livePhotoQueue = DispatchQueue(label:"com.ahmedbekhit.livePhotoQueue", attributes: .concurrent)
|
||||
|
||||
internal func generate(livePhoto video:URL?, _ finished: ((_ status: Bool, _ photo: PHLivePhotoPlus?, _ pairedVideoPath:URL?, _ keyFramePath:URL?) -> Void)? = nil) {
|
||||
func generate(livePhoto video: URL?, _ finished: ((_ status: Bool, _ photo: PHLivePhotoPlus?, _ pairedVideoPath: URL?, _ keyFramePath: URL?) -> Void)? = nil) {
|
||||
livePhotoQueue.async {
|
||||
guard let liveFrames = video else{finished?(false, nil, nil, nil); return}
|
||||
guard let liveFrames = video else { finished?(false, nil, nil, nil); return }
|
||||
let asset = AVURLAsset(url: video!)
|
||||
let generator = AVAssetImageGenerator(asset: asset)
|
||||
generator.appliesPreferredTrackTransform = true
|
||||
|
||||
//retrieves the key photo frame from the middle of the video asset
|
||||
let time = NSValue(time: CMTimeMultiplyByFloat64(asset.duration, 0.5))
|
||||
|
||||
let time = NSValue(time: CMTimeMultiplyByFloat64(asset.duration, multiplier: 0.5))
|
||||
|
||||
//generates the key photo CGImage asynchronously
|
||||
generator.generateCGImagesAsynchronously(forTimes: [time], completionHandler:{_,image,_,_,_ in
|
||||
if let cgImg = image, let imgData = UIImagePNGRepresentation(UIImage(cgImage: cgImg)) {
|
||||
generator.generateCGImagesAsynchronously(forTimes: [time], completionHandler: { _, image, _, _, _ in
|
||||
if let cgImg = image, let imgData = UIImage(cgImage: cgImg).pngData() {
|
||||
do {
|
||||
self.keyPhotoPath = self.newPath(for: true, and: false)
|
||||
try imgData.write(to: self.keyPhotoPath!, options: [.atomic])
|
||||
}catch let error {
|
||||
} catch let error {
|
||||
self.keyPhotoPath = nil
|
||||
logAR.message("An error occurred while capturing a live photo: \(error)")
|
||||
finished?(false, nil, nil, nil)
|
||||
@@ -42,9 +43,9 @@ internal class LivePhotoGenerator {
|
||||
self.finalKeyPhotoPath = self.newPath(for: true, and: true)
|
||||
self.finalPairedVideoPath = self.newPath(for: false, and: true)
|
||||
|
||||
guard let keyFrame = self.keyPhotoPath else{finished?(false, nil, nil, nil); return}
|
||||
guard let keyLiveFrame = self.finalKeyPhotoPath else{finished?(false, nil, nil, nil); return}
|
||||
guard let keyLiveFrames = self.finalPairedVideoPath else{finished?(false, nil, nil, nil); return}
|
||||
guard let keyFrame = self.keyPhotoPath else { finished?(false, nil, nil, nil); return }
|
||||
guard let keyLiveFrame = self.finalKeyPhotoPath else { finished?(false, nil, nil, nil); return }
|
||||
guard let keyLiveFrames = self.finalPairedVideoPath else { finished?(false, nil, nil, nil); return }
|
||||
|
||||
let assetIdentifier = UUID().uuidString
|
||||
|
||||
@@ -61,7 +62,7 @@ internal class LivePhotoGenerator {
|
||||
finalPhoto.pairedVideoPath = keyLiveFrames
|
||||
finished?(true, finalPhoto, finalPhoto.pairedVideoPath, finalPhoto.keyPhotoPath)
|
||||
return
|
||||
}else{
|
||||
} else {
|
||||
let finalPhoto = PHLivePhotoPlus(photo: photo!)
|
||||
finalPhoto.keyPhotoPath = keyLiveFrame
|
||||
finalPhoto.pairedVideoPath = keyLiveFrames
|
||||
@@ -74,7 +75,7 @@ internal class LivePhotoGenerator {
|
||||
}
|
||||
}
|
||||
|
||||
func newPath(for JPEG:Bool, and live:Bool) -> URL {
|
||||
func newPath(for JPEG: Bool, and live: Bool) -> URL {
|
||||
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
|
||||
let documentsDirectory = paths[0]
|
||||
|
||||
@@ -96,9 +97,9 @@ internal class LivePhotoGenerator {
|
||||
|
||||
if JPEG && live {
|
||||
return URL(fileURLWithPath: "\(livePhotosFolder)/\(formatter.string(from: date))AR.jpg", isDirectory: false)
|
||||
}else if JPEG && !live {
|
||||
} else if JPEG && !live {
|
||||
return URL(fileURLWithPath: "\(documentsDirectory)/\(formatter.string(from: date))AR.jpg", isDirectory: false)
|
||||
}else{
|
||||
} else {
|
||||
return URL(fileURLWithPath: "\(livePhotosFolder)/\(formatter.string(from: date))AR.mov", isDirectory: false)
|
||||
}
|
||||
}
|
||||
|
||||
+8
-8
@@ -10,11 +10,11 @@ import Foundation
|
||||
import MobileCoreServices
|
||||
import ImageIO
|
||||
|
||||
internal class JPEG {
|
||||
fileprivate let kFigAppleMakerNote_AssetIdentifier = "17"
|
||||
fileprivate let path : String
|
||||
class JPEG {
|
||||
private let kFigAppleMakerNote_AssetIdentifier = "17"
|
||||
private let path: String
|
||||
|
||||
init(path : String) {
|
||||
init(path: String) {
|
||||
self.path = path
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ internal class JPEG {
|
||||
return makerNote?.object(forKey: kFigAppleMakerNote_AssetIdentifier) as? String
|
||||
}
|
||||
|
||||
func write(_ dest : String, assetIdentifier : String) {
|
||||
func write(_ dest: String, assetIdentifier: String) {
|
||||
guard let dest = CGImageDestinationCreateWithURL(URL(fileURLWithPath: dest) as CFURL, kUTTypeJPEG, 1, nil)
|
||||
else { return }
|
||||
defer { CGImageDestinationFinalize(dest) }
|
||||
@@ -38,19 +38,19 @@ internal class JPEG {
|
||||
CGImageDestinationAddImageFromSource(dest, imageSource, 0, metadata)
|
||||
}
|
||||
|
||||
fileprivate func metadata() -> NSDictionary? {
|
||||
private func metadata() -> NSDictionary? {
|
||||
return self.imageSource().flatMap {
|
||||
CGImageSourceCopyPropertiesAtIndex($0, 0, nil) as NSDictionary?
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate func imageSource() -> CGImageSource? {
|
||||
private func imageSource() -> CGImageSource? {
|
||||
return self.data().flatMap {
|
||||
CGImageSourceCreateWithData($0 as CFData, nil)
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate func data() -> Data? {
|
||||
private func data() -> Data? {
|
||||
return (try? Data(contentsOf: URL(fileURLWithPath: path)))
|
||||
}
|
||||
}
|
||||
+39
-34
@@ -9,20 +9,21 @@
|
||||
|
||||
import Foundation
|
||||
import AVFoundation
|
||||
@available(iOS 11.0, *)
|
||||
internal class QuickTimeMov {
|
||||
fileprivate let kKeyContentIdentifier = "com.apple.quicktime.content.identifier"
|
||||
fileprivate let kKeyStillImageTime = "com.apple.quicktime.still-image-time"
|
||||
fileprivate let kKeySpaceQuickTimeMetadata = "mdta"
|
||||
fileprivate let path : String
|
||||
fileprivate let dummyTimeRange = CMTimeRangeMake(CMTimeMake(0, 1000), CMTimeMake(200, 3000))
|
||||
|
||||
fileprivate lazy var asset : AVURLAsset = {
|
||||
@available(iOS 11.0, *)
|
||||
class QuickTimeMov {
|
||||
private let kKeyContentIdentifier = "com.apple.quicktime.content.identifier"
|
||||
private let kKeyStillImageTime = "com.apple.quicktime.still-image-time"
|
||||
private let kKeySpaceQuickTimeMetadata = "mdta"
|
||||
private let path: String
|
||||
private let dummyTimeRange = CMTimeRange(start: CMTime(value: 0, timescale: 1000), duration: CMTime(value: 200, timescale: 3000))
|
||||
|
||||
private lazy var asset: AVURLAsset = {
|
||||
let url = URL(fileURLWithPath: self.path)
|
||||
return AVURLAsset(url: url)
|
||||
}()
|
||||
|
||||
init(path : String) {
|
||||
init(path: String) {
|
||||
self.path = path
|
||||
}
|
||||
|
||||
@@ -43,7 +44,7 @@ internal class QuickTimeMov {
|
||||
|
||||
while true {
|
||||
guard let buffer = output.copyNextSampleBuffer() else { return nil }
|
||||
if CMSampleBufferGetNumSamples(buffer) != 0 {
|
||||
if CMSampleBufferGetNumSamples(buffer) > 0 {
|
||||
let group = AVTimedMetadataGroup(sampleBuffer: buffer)
|
||||
for item in group?.items ?? [] {
|
||||
if item.key as? String == kKeyStillImageTime &&
|
||||
@@ -57,11 +58,11 @@ internal class QuickTimeMov {
|
||||
return nil
|
||||
}
|
||||
|
||||
func write(_ dest : String, assetIdentifier : String) {
|
||||
func write(_ dest: String, assetIdentifier: String) {
|
||||
|
||||
var audioReader : AVAssetReader? = nil
|
||||
var audioWriterInput : AVAssetWriterInput? = nil
|
||||
var audioReaderOutput : AVAssetReaderOutput? = nil
|
||||
var audioReader: AVAssetReader? = nil
|
||||
var audioWriterInput: AVAssetWriterInput? = nil
|
||||
var audioReaderOutput: AVAssetReaderOutput? = nil
|
||||
do {
|
||||
// --------------------------------------------------
|
||||
// reader for source video
|
||||
@@ -70,9 +71,11 @@ internal class QuickTimeMov {
|
||||
logAR.message("not found video track")
|
||||
return
|
||||
}
|
||||
let readerSettings: [String: AnyObject] = [
|
||||
kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA as AnyObject
|
||||
]
|
||||
let (reader, output) = try self.reader(track,
|
||||
settings: [kCVPixelBufferPixelFormatTypeKey as String:
|
||||
NSNumber(value: kCVPixelFormatType_32BGRA as UInt32)])
|
||||
settings: readerSettings)
|
||||
// --------------------------------------------------
|
||||
// writer for mov
|
||||
// --------------------------------------------------
|
||||
@@ -88,7 +91,7 @@ internal class QuickTimeMov {
|
||||
|
||||
|
||||
let url = URL(fileURLWithPath: self.path)
|
||||
let aAudioAsset : AVAsset = AVAsset(url: url)
|
||||
let aAudioAsset: AVAsset = AVAsset(url: url)
|
||||
|
||||
if aAudioAsset.tracks.count > 1 {
|
||||
logAR.message("Has Audio")
|
||||
@@ -100,15 +103,15 @@ internal class QuickTimeMov {
|
||||
writer.add(audioWriterInput!)
|
||||
}
|
||||
//setup audio reader
|
||||
let audioTrack:AVAssetTrack = aAudioAsset.tracks(withMediaType: AVMediaType.audio).first!
|
||||
let audioTrack: AVAssetTrack = aAudioAsset.tracks(withMediaType: AVMediaType.audio).first!
|
||||
audioReaderOutput = AVAssetReaderTrackOutput(track: audioTrack, outputSettings: nil)
|
||||
|
||||
do{
|
||||
audioReader = try AVAssetReader(asset: aAudioAsset)
|
||||
}catch{
|
||||
fatalError("Unable to read Asset: \(error) : ")
|
||||
} catch {
|
||||
fatalError("Unable to read Asset: \(error): ")
|
||||
}
|
||||
//let audioReader:AVAssetReader = AVAssetReader(asset: aAudioAsset, error: &error)
|
||||
//let audioReader: AVAssetReader = AVAssetReader(asset: aAudioAsset, error: &error)
|
||||
if (audioReader?.canAdd(audioReaderOutput!))! {
|
||||
audioReader?.add(audioReaderOutput!)
|
||||
} else {
|
||||
@@ -125,7 +128,7 @@ internal class QuickTimeMov {
|
||||
// --------------------------------------------------
|
||||
writer.startWriting()
|
||||
reader.startReading()
|
||||
writer.startSession(atSourceTime: kCMTimeZero)
|
||||
writer.startSession(atSourceTime: CMTime.zero)
|
||||
|
||||
// write metadata track
|
||||
adapter.append(AVTimedMetadataGroup(items: [metadataForStillImageTime()],
|
||||
@@ -145,7 +148,7 @@ internal class QuickTimeMov {
|
||||
input.markAsFinished()
|
||||
if reader.status == .completed && aAudioAsset.tracks.count > 1 {
|
||||
audioReader?.startReading()
|
||||
writer.startSession(atSourceTime: kCMTimeZero)
|
||||
writer.startSession(atSourceTime: CMTime.zero)
|
||||
let media_queue = DispatchQueue(label: "assetAudioWriterQueue", attributes: [])
|
||||
audioWriterInput?.requestMediaDataWhenReady(on: media_queue) {
|
||||
while (audioWriterInput?.isReadyForMoreMediaData)! {
|
||||
@@ -154,7 +157,7 @@ internal class QuickTimeMov {
|
||||
if !(audioWriterInput?.append(sampleBuffer2!))! {
|
||||
audioReader?.cancelReading()
|
||||
}
|
||||
}else {
|
||||
} else {
|
||||
audioWriterInput?.markAsFinished()
|
||||
logAR.message("Audio writer finish")
|
||||
writer.finishWriting() {
|
||||
@@ -192,36 +195,38 @@ internal class QuickTimeMov {
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate func metadata() -> [AVMetadataItem] {
|
||||
private func metadata() -> [AVMetadataItem] {
|
||||
return asset.metadata(forFormat: AVMetadataFormat.quickTimeMetadata)
|
||||
}
|
||||
|
||||
fileprivate func track(_ mediaType : AVMediaType) -> AVAssetTrack? {
|
||||
private func track(_ mediaType: AVMediaType) -> AVAssetTrack? {
|
||||
return asset.tracks(withMediaType: mediaType).first
|
||||
}
|
||||
|
||||
fileprivate func reader(_ track : AVAssetTrack, settings: [String:AnyObject]?) throws -> (AVAssetReader, AVAssetReaderOutput) {
|
||||
private func reader(_ track: AVAssetTrack, settings: [String: AnyObject]?) throws -> (AVAssetReader, AVAssetReaderOutput) {
|
||||
let output = AVAssetReaderTrackOutput(track: track, outputSettings: settings)
|
||||
let reader = try AVAssetReader(asset: asset)
|
||||
reader.add(output)
|
||||
return (reader, output)
|
||||
}
|
||||
|
||||
fileprivate func metadataAdapter() -> AVAssetWriterInputMetadataAdaptor {
|
||||
let spec : NSDictionary = [
|
||||
private func metadataAdapter() -> AVAssetWriterInputMetadataAdaptor {
|
||||
let spec: NSDictionary = [
|
||||
kCMMetadataFormatDescriptionMetadataSpecificationKey_Identifier as NSString:
|
||||
"\(kKeySpaceQuickTimeMetadata)/\(kKeyStillImageTime)",
|
||||
kCMMetadataFormatDescriptionMetadataSpecificationKey_DataType as NSString:
|
||||
"com.apple.metadata.datatype.int8" ]
|
||||
|
||||
var desc : CMFormatDescription? = nil
|
||||
CMMetadataFormatDescriptionCreateWithMetadataSpecifications(kCFAllocatorDefault, kCMMetadataFormatType_Boxed, [spec] as CFArray, &desc)
|
||||
var desc: CMFormatDescription? = nil
|
||||
CMMetadataFormatDescriptionCreateWithMetadataSpecifications(allocator: kCFAllocatorDefault, metadataType: kCMMetadataFormatType_Boxed, metadataSpecifications: [spec] as CFArray, formatDescriptionOut: &desc)
|
||||
|
||||
// CMFormatDescription.createForMetadata(allocator: kCFAllocatorDefault, metadataType: kCMMetadataFormatType_Boxed, metadataSpecifications: [spec] as CFArray, formatDescriptionOut: &desc)
|
||||
let input = AVAssetWriterInput(mediaType: AVMediaType.metadata,
|
||||
outputSettings: nil, sourceFormatHint: desc)
|
||||
return AVAssetWriterInputMetadataAdaptor(assetWriterInput: input)
|
||||
}
|
||||
|
||||
fileprivate func videoSettings(_ size : CGSize) -> [String:AnyObject] {
|
||||
private func videoSettings(_ size: CGSize) -> [String: AnyObject] {
|
||||
return [
|
||||
AVVideoCodecKey: AVVideoCodecType.h264 as AnyObject,
|
||||
AVVideoWidthKey: size.width as AnyObject,
|
||||
@@ -229,7 +234,7 @@ internal class QuickTimeMov {
|
||||
]
|
||||
}
|
||||
|
||||
fileprivate func metadataFor(_ assetIdentifier: String) -> AVMetadataItem {
|
||||
private func metadataFor(_ assetIdentifier: String) -> AVMetadataItem {
|
||||
let item = AVMutableMetadataItem()
|
||||
item.key = kKeyContentIdentifier as (NSCopying & NSObjectProtocol)?
|
||||
item.keySpace = AVMetadataKeySpace(rawValue: kKeySpaceQuickTimeMetadata)
|
||||
@@ -238,7 +243,7 @@ internal class QuickTimeMov {
|
||||
return item
|
||||
}
|
||||
|
||||
fileprivate func metadataForStillImageTime() -> AVMetadataItem {
|
||||
private func metadataForStillImageTime() -> AVMetadataItem {
|
||||
let item = AVMutableMetadataItem()
|
||||
item.key = kKeyStillImageTime as (NSCopying & NSObjectProtocol)?
|
||||
item.keySpace = AVMetadataKeySpace(rawValue: kKeySpaceQuickTimeMetadata)
|
||||
@@ -7,6 +7,7 @@
|
||||
//
|
||||
|
||||
import Photos
|
||||
|
||||
/**
|
||||
A `PHLivePhotoPlus` object is a `PHLivePhoto` sub-class that contains objects to allow manual exporting of a live photo.
|
||||
|
||||
@@ -17,18 +18,18 @@ import Photos
|
||||
* [Email](mailto:me@ahmedbekhit.com)
|
||||
*/
|
||||
@available(iOS 9.1, *)
|
||||
@objc public class PHLivePhotoPlus: PHLivePhoto {
|
||||
internal var pairedVideoPath:URL?
|
||||
internal var keyPhotoPath:URL?
|
||||
@objc public class PHLivePhotoPlus: NSObject {
|
||||
var pairedVideoPath: URL?
|
||||
var keyPhotoPath: URL?
|
||||
|
||||
/// A `PHLivePhoto` object that returns the Live Photo content from `PHLivePhotoPlus`.
|
||||
@objc public var livePhoto:PHLivePhoto?
|
||||
@objc public var livePhoto: PHLivePhoto?
|
||||
|
||||
@objc public override init() {
|
||||
super.init()
|
||||
}
|
||||
|
||||
@objc public init(photo:PHLivePhoto) {
|
||||
@objc public init(photo: PHLivePhoto) {
|
||||
super.init()
|
||||
livePhoto = photo
|
||||
}
|
||||
|
||||
@@ -1,249 +0,0 @@
|
||||
|
||||
//
|
||||
// QuickTimeMov.swift
|
||||
// LoveLiver
|
||||
//
|
||||
// Created by mzp on 10/10/15.
|
||||
// Copyright © 2015 mzp. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import AVFoundation
|
||||
@available(iOS 11.0, *)
|
||||
internal class QuickTimeMov {
|
||||
fileprivate let kKeyContentIdentifier = "com.apple.quicktime.content.identifier"
|
||||
fileprivate let kKeyStillImageTime = "com.apple.quicktime.still-image-time"
|
||||
fileprivate let kKeySpaceQuickTimeMetadata = "mdta"
|
||||
fileprivate let path : String
|
||||
fileprivate let dummyTimeRange = CMTimeRangeMake(CMTimeMake(0, 1000), CMTimeMake(200, 3000))
|
||||
|
||||
fileprivate lazy var asset : AVURLAsset = {
|
||||
let url = URL(fileURLWithPath: self.path)
|
||||
return AVURLAsset(url: url)
|
||||
}()
|
||||
|
||||
init(path : String) {
|
||||
self.path = path
|
||||
}
|
||||
|
||||
func readAssetIdentifier() -> String? {
|
||||
for item in metadata() {
|
||||
if item.key as? String == kKeyContentIdentifier &&
|
||||
item.keySpace!.rawValue == kKeySpaceQuickTimeMetadata {
|
||||
return item.value as? String
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func readStillImageTime() -> NSNumber? {
|
||||
if let track = track(AVMediaType.metadata) {
|
||||
let (reader, output) = try! self.reader(track, settings: nil)
|
||||
reader.startReading()
|
||||
|
||||
while true {
|
||||
guard let buffer = output.copyNextSampleBuffer() else { return nil }
|
||||
if CMSampleBufferGetNumSamples(buffer) != 0 {
|
||||
let group = AVTimedMetadataGroup(sampleBuffer: buffer)
|
||||
for item in group?.items ?? [] {
|
||||
if item.key as? String == kKeyStillImageTime &&
|
||||
item.keySpace!.rawValue == kKeySpaceQuickTimeMetadata {
|
||||
return item.numberValue
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func write(_ dest : String, assetIdentifier : String) {
|
||||
|
||||
var audioReader : AVAssetReader? = nil
|
||||
var audioWriterInput : AVAssetWriterInput? = nil
|
||||
var audioReaderOutput : AVAssetReaderOutput? = nil
|
||||
do {
|
||||
// --------------------------------------------------
|
||||
// reader for source video
|
||||
// --------------------------------------------------
|
||||
guard let track = self.track(AVMediaType.video) else {
|
||||
logAR.message("not found video track")
|
||||
return
|
||||
}
|
||||
let (reader, output) = try self.reader(track,
|
||||
settings: [kCVPixelBufferPixelFormatTypeKey as String:
|
||||
NSNumber(value: kCVPixelFormatType_32BGRA as UInt32)])
|
||||
// --------------------------------------------------
|
||||
// writer for mov
|
||||
// --------------------------------------------------
|
||||
let writer = try AVAssetWriter(outputURL: URL(fileURLWithPath: dest), fileType: AVFileType.mov)
|
||||
writer.metadata = [metadataFor(assetIdentifier)]
|
||||
|
||||
// video track
|
||||
let input = AVAssetWriterInput(mediaType: AVMediaType.video,
|
||||
outputSettings: videoSettings(track.naturalSize))
|
||||
input.expectsMediaDataInRealTime = true
|
||||
input.transform = track.preferredTransform
|
||||
writer.add(input)
|
||||
|
||||
|
||||
let url = URL(fileURLWithPath: self.path)
|
||||
let aAudioAsset : AVAsset = AVAsset(url: url)
|
||||
|
||||
if aAudioAsset.tracks.count > 1 {
|
||||
logAR.message("Has Audio")
|
||||
//setup audio writer
|
||||
audioWriterInput = AVAssetWriterInput(mediaType: AVMediaType.audio, outputSettings: nil)
|
||||
|
||||
audioWriterInput?.expectsMediaDataInRealTime = false
|
||||
if writer.canAdd(audioWriterInput!){
|
||||
writer.add(audioWriterInput!)
|
||||
}
|
||||
//setup audio reader
|
||||
let audioTrack:AVAssetTrack = aAudioAsset.tracks(withMediaType: AVMediaType.audio).first!
|
||||
audioReaderOutput = AVAssetReaderTrackOutput(track: audioTrack, outputSettings: nil)
|
||||
|
||||
do{
|
||||
audioReader = try AVAssetReader(asset: aAudioAsset)
|
||||
}catch{
|
||||
fatalError("Unable to read Asset: \(error) : ")
|
||||
}
|
||||
//let audioReader:AVAssetReader = AVAssetReader(asset: aAudioAsset, error: &error)
|
||||
if (audioReader?.canAdd(audioReaderOutput!))! {
|
||||
audioReader?.add(audioReaderOutput!)
|
||||
} else {
|
||||
logAR.message("cant add audio reader")
|
||||
}
|
||||
}
|
||||
|
||||
// metadata track
|
||||
let adapter = metadataAdapter()
|
||||
writer.add(adapter.assetWriterInput)
|
||||
|
||||
// --------------------------------------------------
|
||||
// creating video
|
||||
// --------------------------------------------------
|
||||
writer.startWriting()
|
||||
reader.startReading()
|
||||
writer.startSession(atSourceTime: kCMTimeZero)
|
||||
|
||||
// write metadata track
|
||||
adapter.append(AVTimedMetadataGroup(items: [metadataForStillImageTime()],
|
||||
timeRange: dummyTimeRange))
|
||||
|
||||
// write video track
|
||||
input.requestMediaDataWhenReady(on: DispatchQueue(label: "assetVideoWriterQueue", attributes: [])) {
|
||||
while(input.isReadyForMoreMediaData) {
|
||||
if reader.status == .reading {
|
||||
if let buffer = output.copyNextSampleBuffer() {
|
||||
if !input.append(buffer) {
|
||||
logAR.message("cannot write: \(String(describing: writer.error))")
|
||||
reader.cancelReading()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
input.markAsFinished()
|
||||
if reader.status == .completed && aAudioAsset.tracks.count > 1 {
|
||||
audioReader?.startReading()
|
||||
writer.startSession(atSourceTime: kCMTimeZero)
|
||||
let media_queue = DispatchQueue(label: "assetAudioWriterQueue", attributes: [])
|
||||
audioWriterInput?.requestMediaDataWhenReady(on: media_queue) {
|
||||
while (audioWriterInput?.isReadyForMoreMediaData)! {
|
||||
let sampleBuffer2:CMSampleBuffer? = audioReaderOutput?.copyNextSampleBuffer()
|
||||
if audioReader?.status == .reading && sampleBuffer2 != nil {
|
||||
if !(audioWriterInput?.append(sampleBuffer2!))! {
|
||||
audioReader?.cancelReading()
|
||||
}
|
||||
}else {
|
||||
audioWriterInput?.markAsFinished()
|
||||
logAR.message("Audio writer finish")
|
||||
writer.finishWriting() {
|
||||
if let e = writer.error {
|
||||
logAR.message("cannot write: \(e)")
|
||||
} else {
|
||||
logAR.message("finish writing.")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
logAR.message("Video Reader not completed")
|
||||
writer.finishWriting() {
|
||||
if let e = writer.error {
|
||||
logAR.message("cannot write: \(e)")
|
||||
} else {
|
||||
logAR.message("finish writing.")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
while writer.status == .writing {
|
||||
RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.5))
|
||||
}
|
||||
if let e = writer.error {
|
||||
logAR.message("cannot write: \(e)")
|
||||
}
|
||||
} catch {
|
||||
logAR.message("error")
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate func metadata() -> [AVMetadataItem] {
|
||||
return asset.metadata(forFormat: AVMetadataFormat.quickTimeMetadata)
|
||||
}
|
||||
|
||||
fileprivate func track(_ mediaType : AVMediaType) -> AVAssetTrack? {
|
||||
return asset.tracks(withMediaType: mediaType).first
|
||||
}
|
||||
|
||||
fileprivate func reader(_ track : AVAssetTrack, settings: [String:AnyObject]?) throws -> (AVAssetReader, AVAssetReaderOutput) {
|
||||
let output = AVAssetReaderTrackOutput(track: track, outputSettings: settings)
|
||||
let reader = try AVAssetReader(asset: asset)
|
||||
reader.add(output)
|
||||
return (reader, output)
|
||||
}
|
||||
|
||||
fileprivate func metadataAdapter() -> AVAssetWriterInputMetadataAdaptor {
|
||||
let spec : NSDictionary = [
|
||||
kCMMetadataFormatDescriptionMetadataSpecificationKey_Identifier as NSString:
|
||||
"\(kKeySpaceQuickTimeMetadata)/\(kKeyStillImageTime)",
|
||||
kCMMetadataFormatDescriptionMetadataSpecificationKey_DataType as NSString:
|
||||
"com.apple.metadata.datatype.int8" ]
|
||||
|
||||
var desc : CMFormatDescription? = nil
|
||||
CMMetadataFormatDescriptionCreateWithMetadataSpecifications(kCFAllocatorDefault, kCMMetadataFormatType_Boxed, [spec] as CFArray, &desc)
|
||||
let input = AVAssetWriterInput(mediaType: AVMediaType.metadata,
|
||||
outputSettings: nil, sourceFormatHint: desc)
|
||||
return AVAssetWriterInputMetadataAdaptor(assetWriterInput: input)
|
||||
}
|
||||
|
||||
fileprivate func videoSettings(_ size : CGSize) -> [String:AnyObject] {
|
||||
return [
|
||||
AVVideoCodecKey: AVVideoCodecType.h264 as AnyObject,
|
||||
AVVideoWidthKey: size.width as AnyObject,
|
||||
AVVideoHeightKey: size.height as AnyObject
|
||||
]
|
||||
}
|
||||
|
||||
fileprivate func metadataFor(_ assetIdentifier: String) -> AVMetadataItem {
|
||||
let item = AVMutableMetadataItem()
|
||||
item.key = kKeyContentIdentifier as (NSCopying & NSObjectProtocol)?
|
||||
item.keySpace = AVMetadataKeySpace(rawValue: kKeySpaceQuickTimeMetadata)
|
||||
item.value = assetIdentifier as (NSCopying & NSObjectProtocol)?
|
||||
item.dataType = "com.apple.metadata.datatype.UTF-8"
|
||||
return item
|
||||
}
|
||||
|
||||
fileprivate func metadataForStillImageTime() -> AVMetadataItem {
|
||||
let item = AVMutableMetadataItem()
|
||||
item.key = kKeyStillImageTime as (NSCopying & NSObjectProtocol)?
|
||||
item.keySpace = AVMetadataKeySpace(rawValue: kKeySpaceQuickTimeMetadata)
|
||||
item.value = 0 as (NSCopying & NSObjectProtocol)?
|
||||
item.dataType = "com.apple.metadata.datatype.int8"
|
||||
return item
|
||||
}
|
||||
}
|
||||
@@ -8,112 +8,116 @@
|
||||
|
||||
import Foundation
|
||||
import ARKit
|
||||
fileprivate var view:Any?
|
||||
fileprivate var renderEngine:SCNRenderer!
|
||||
|
||||
@available(iOS 11.0, *)
|
||||
internal struct RenderAR {
|
||||
internal var ARcontentMode:ARFrameMode!
|
||||
init(_ ARview:Any?, renderer:SCNRenderer, contentMode:ARFrameMode) {
|
||||
struct RenderAR {
|
||||
private var view: Any?
|
||||
private var renderEngine: SCNRenderer!
|
||||
var ARcontentMode: ARFrameMode!
|
||||
|
||||
init(_ ARview: Any?, renderer: SCNRenderer, contentMode: ARFrameMode) {
|
||||
view = ARview
|
||||
renderEngine = renderer
|
||||
ARcontentMode = contentMode
|
||||
}
|
||||
internal let pixelsQueue = DispatchQueue(label:"com.ahmedbekhit.PixelsQueue", attributes: .concurrent)
|
||||
internal var time:CFTimeInterval {return CACurrentMediaTime()}
|
||||
internal var rawBuffer:CVPixelBuffer? {
|
||||
|
||||
let pixelsQueue = DispatchQueue(label: "com.ahmedbekhit.PixelsQueue", attributes: .concurrent)
|
||||
var time: CFTimeInterval { return CACurrentMediaTime()}
|
||||
var rawBuffer: CVPixelBuffer? {
|
||||
if let view = view as? ARSCNView {
|
||||
guard let rawBuffer = view.session.currentFrame?.capturedImage else{return nil}
|
||||
guard let rawBuffer = view.session.currentFrame?.capturedImage else { return nil }
|
||||
return rawBuffer
|
||||
}else if let view = view as? ARSKView {
|
||||
guard let rawBuffer = view.session.currentFrame?.capturedImage else{return nil}
|
||||
} else if let view = view as? ARSKView {
|
||||
guard let rawBuffer = view.session.currentFrame?.capturedImage else { return nil }
|
||||
return rawBuffer
|
||||
}else if let _ = view as? SCNView {
|
||||
} else if view is SCNView {
|
||||
return buffer
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
internal var bufferSize:CGSize? {
|
||||
guard let raw = rawBuffer else{return nil};
|
||||
var width = CVPixelBufferGetWidth(raw);
|
||||
var height = CVPixelBufferGetHeight(raw);
|
||||
var bufferSize: CGSize? {
|
||||
guard let raw = rawBuffer else { return nil }
|
||||
var width = CVPixelBufferGetWidth(raw)
|
||||
var height = CVPixelBufferGetHeight(raw)
|
||||
|
||||
switch ARcontentMode {
|
||||
case .auto:
|
||||
if UIScreen.main.isiPhone10 {
|
||||
width = Int(UIScreen.main.nativeBounds.width)
|
||||
height = Int(UIScreen.main.nativeBounds.height)
|
||||
}
|
||||
case .aspectFit:
|
||||
width = CVPixelBufferGetWidth(raw);
|
||||
height = CVPixelBufferGetHeight(raw);
|
||||
case .aspectFill:
|
||||
width = Int(UIScreen.main.nativeBounds.width)
|
||||
height = Int(UIScreen.main.nativeBounds.height)
|
||||
default:
|
||||
if UIScreen.main.isiPhone10 {
|
||||
if let contentMode = ARcontentMode {
|
||||
switch contentMode {
|
||||
case .auto:
|
||||
if UIScreen.main.isiPhone10 {
|
||||
width = Int(UIScreen.main.nativeBounds.width)
|
||||
height = Int(UIScreen.main.nativeBounds.height)
|
||||
}
|
||||
case .aspectFit:
|
||||
width = CVPixelBufferGetWidth(raw)
|
||||
height = CVPixelBufferGetHeight(raw)
|
||||
case .aspectFill:
|
||||
width = Int(UIScreen.main.nativeBounds.width)
|
||||
height = Int(UIScreen.main.nativeBounds.height)
|
||||
default:
|
||||
if UIScreen.main.isiPhone10 {
|
||||
width = Int(UIScreen.main.nativeBounds.width)
|
||||
height = Int(UIScreen.main.nativeBounds.height)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if width > height {
|
||||
return CGSize(width: height, height: width)
|
||||
}else{
|
||||
} else {
|
||||
return CGSize(width: width, height: height)
|
||||
}
|
||||
}
|
||||
|
||||
internal var bufferSizeFill:CGSize? {
|
||||
guard let raw = rawBuffer else{return nil};
|
||||
let width = CVPixelBufferGetWidth(raw);
|
||||
let height = CVPixelBufferGetHeight(raw);
|
||||
var bufferSizeFill: CGSize? {
|
||||
guard let raw = rawBuffer else { return nil }
|
||||
let width = CVPixelBufferGetWidth(raw)
|
||||
let height = CVPixelBufferGetHeight(raw)
|
||||
if width > height {
|
||||
return CGSize(width: height, height: width)
|
||||
}else{
|
||||
} else {
|
||||
return CGSize(width: width, height: height)
|
||||
}
|
||||
}
|
||||
|
||||
internal var buffer:CVPixelBuffer? {
|
||||
if let _ = view as? ARSCNView {
|
||||
guard let size = bufferSize else{return nil};
|
||||
var buffer: CVPixelBuffer? {
|
||||
if view is ARSCNView {
|
||||
guard let size = bufferSize else { return nil }
|
||||
//UIScreen.main.bounds.size
|
||||
var renderedFrame:UIImage?
|
||||
var renderedFrame: UIImage?
|
||||
pixelsQueue.sync {
|
||||
renderedFrame = renderEngine.snapshot(atTime: self.time, with: size, antialiasingMode: .none);
|
||||
renderedFrame = renderEngine.snapshot(atTime: self.time, with: size, antialiasingMode: .none)
|
||||
}
|
||||
if let _ = renderedFrame {
|
||||
}else{
|
||||
renderedFrame = renderEngine.snapshot(atTime: time, with: size, antialiasingMode: .none);
|
||||
} else {
|
||||
renderedFrame = renderEngine.snapshot(atTime: time, with: size, antialiasingMode: .none)
|
||||
}
|
||||
guard let buffer = renderedFrame!.buffer else{return nil};
|
||||
return buffer;
|
||||
}else if let _ = view as? ARSKView {
|
||||
guard let size = bufferSize else{return nil};
|
||||
var renderedFrame:UIImage?
|
||||
guard let buffer = renderedFrame!.buffer else { return nil }
|
||||
return buffer
|
||||
} else if view is ARSKView {
|
||||
guard let size = bufferSize else { return nil }
|
||||
var renderedFrame: UIImage?
|
||||
pixelsQueue.sync {
|
||||
renderedFrame = renderEngine.snapshot(atTime: self.time, with: size, antialiasingMode: .none).rotate(by: 180);
|
||||
renderedFrame = renderEngine.snapshot(atTime: self.time, with: size, antialiasingMode: .none).rotate(by: 180)
|
||||
}
|
||||
if let _ = renderedFrame {
|
||||
}else{
|
||||
renderedFrame = renderEngine.snapshot(atTime: time, with: size, antialiasingMode: .none).rotate(by: 180);
|
||||
if renderedFrame == nil {
|
||||
renderedFrame = renderEngine.snapshot(atTime: time, with: size, antialiasingMode: .none).rotate(by: 180)
|
||||
}
|
||||
guard let buffer = renderedFrame!.buffer else{return nil};
|
||||
guard let buffer = renderedFrame!.buffer else { return nil }
|
||||
return buffer;
|
||||
}else if let _ = view as? SCNView {
|
||||
} else if view is SCNView {
|
||||
let size = UIScreen.main.bounds.size
|
||||
var renderedFrame:UIImage?
|
||||
var renderedFrame: UIImage?
|
||||
pixelsQueue.sync {
|
||||
renderedFrame = renderEngine.snapshot(atTime: self.time, with: size, antialiasingMode: .none);
|
||||
renderedFrame = renderEngine.snapshot(atTime: self.time, with: size, antialiasingMode: .none)
|
||||
}
|
||||
if let _ = renderedFrame {
|
||||
}else{
|
||||
renderedFrame = renderEngine.snapshot(atTime: time, with: size, antialiasingMode: .none);
|
||||
} else {
|
||||
renderedFrame = renderEngine.snapshot(atTime: time, with: size, antialiasingMode: .none)
|
||||
}
|
||||
guard let buffer = renderedFrame!.buffer else{return nil};
|
||||
return buffer;
|
||||
guard let buffer = renderedFrame!.buffer else { return nil }
|
||||
return buffer
|
||||
}
|
||||
return nil;
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,37 +9,38 @@
|
||||
import AVFoundation
|
||||
import CoreImage
|
||||
import UIKit
|
||||
|
||||
@available(iOS 11.0, *)
|
||||
internal class WritAR:NSObject, AVCaptureAudioDataOutputSampleBufferDelegate {
|
||||
fileprivate var assetWriter: AVAssetWriter!
|
||||
fileprivate var videoInput: AVAssetWriterInput!
|
||||
fileprivate var audioInput: AVAssetWriterInput!
|
||||
fileprivate var session: AVCaptureSession!
|
||||
class WritAR: NSObject, AVCaptureAudioDataOutputSampleBufferDelegate {
|
||||
private var assetWriter: AVAssetWriter!
|
||||
private var videoInput: AVAssetWriterInput!
|
||||
private var audioInput: AVAssetWriterInput!
|
||||
private var session: AVCaptureSession!
|
||||
|
||||
fileprivate var pixelBufferInput: AVAssetWriterInputPixelBufferAdaptor!
|
||||
fileprivate var videoOutputSettings: Dictionary<String, AnyObject>!
|
||||
fileprivate var audioSettings: [String : Any]?
|
||||
private var pixelBufferInput: AVAssetWriterInputPixelBufferAdaptor!
|
||||
private var videoOutputSettings: Dictionary<String, AnyObject>!
|
||||
private var audioSettings: [String: Any]?
|
||||
|
||||
internal let audioBufferQueue = DispatchQueue(label: "com.ahmedbekhit.AudioBufferQueue")
|
||||
let audioBufferQueue = DispatchQueue(label: "com.ahmedbekhit.AudioBufferQueue")
|
||||
|
||||
fileprivate var isRecording:Bool = false
|
||||
private var isRecording: Bool = false
|
||||
|
||||
internal var delegate:RecordARDelegate?
|
||||
internal var videoInputOrientation:ARVideoOrientation = .auto
|
||||
weak var delegate: RecordARDelegate?
|
||||
var videoInputOrientation: ARVideoOrientation = .auto
|
||||
|
||||
init(output:URL, width:Int, height:Int, adjustForSharing:Bool, audioEnabled:Bool, orientaions:[ARInputViewOrientation], queue:DispatchQueue, allowMix:Bool){
|
||||
init(output: URL, width: Int, height: Int, adjustForSharing: Bool, audioEnabled: Bool, orientaions:[ARInputViewOrientation], queue: DispatchQueue, allowMix: Bool) {
|
||||
super.init()
|
||||
do {
|
||||
assetWriter = try AVAssetWriter(outputURL: output, fileType: AVFileType.mp4)
|
||||
}catch{
|
||||
} catch {
|
||||
// FIXME: handle when failed to allocate AVAssetWriter.
|
||||
return
|
||||
}
|
||||
if audioEnabled {
|
||||
if allowMix {
|
||||
do {
|
||||
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord, with: [AVAudioSessionCategoryOptions.mixWithOthers , AVAudioSessionCategoryOptions.allowBluetooth, AVAudioSessionCategoryOptions.defaultToSpeaker, AVAudioSessionCategoryOptions.interruptSpokenAudioAndMixWithOthers])
|
||||
try AVAudioSession.sharedInstance().setActive(true)
|
||||
}catch{}
|
||||
let audioOptions: AVAudioSession.CategoryOptions = [.mixWithOthers , .allowBluetooth, .defaultToSpeaker, .interruptSpokenAudioAndMixWithOthers]
|
||||
try? AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playAndRecord, mode: AVAudioSession.Mode.spokenAudio, options: audioOptions)
|
||||
try? AVAudioSession.sharedInstance().setActive(true)
|
||||
}
|
||||
AVAudioSession.sharedInstance().requestRecordPermission({ permitted in
|
||||
if permitted {
|
||||
@@ -51,19 +52,19 @@ internal class WritAR:NSObject, AVCaptureAudioDataOutputSampleBufferDelegate {
|
||||
//HEVC file format only supports A10 Fusion Chip or higher.
|
||||
//to support HEVC, make sure to check if the device is iPhone 7 or higher
|
||||
videoOutputSettings = [
|
||||
AVVideoCodecKey : AVVideoCodecType.h264 as AnyObject,
|
||||
AVVideoWidthKey : width as AnyObject,
|
||||
AVVideoHeightKey : height as AnyObject
|
||||
AVVideoCodecKey: AVVideoCodecType.h264 as AnyObject,
|
||||
AVVideoWidthKey: width as AnyObject,
|
||||
AVVideoHeightKey: height as AnyObject
|
||||
]
|
||||
|
||||
let attributes : [String:Bool] = [
|
||||
kCVPixelBufferCGImageCompatibilityKey as String : true,
|
||||
kCVPixelBufferCGBitmapContextCompatibilityKey as String : true
|
||||
let attributes: [String: Bool] = [
|
||||
kCVPixelBufferCGImageCompatibilityKey as String: true,
|
||||
kCVPixelBufferCGBitmapContextCompatibilityKey as String: true
|
||||
]
|
||||
videoInput = AVAssetWriterInput(mediaType: .video, outputSettings: videoOutputSettings)
|
||||
|
||||
videoInput.expectsMediaDataInRealTime = true
|
||||
pixelBufferInput = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: videoInput, sourcePixelBufferAttributes: attributes)
|
||||
pixelBufferInput = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: videoInput, sourcePixelBufferAttributes: nil)
|
||||
|
||||
var angleEnabled: Bool {
|
||||
for v in orientaions {
|
||||
@@ -74,8 +75,8 @@ internal class WritAR:NSObject, AVCaptureAudioDataOutputSampleBufferDelegate {
|
||||
return false
|
||||
}
|
||||
|
||||
var recentAngle:CGFloat = 0
|
||||
var rotationAngle:CGFloat = 0
|
||||
var recentAngle: CGFloat = 0
|
||||
var rotationAngle: CGFloat = 0
|
||||
switch UIDevice.current.orientation {
|
||||
case .landscapeLeft:
|
||||
rotationAngle = -90
|
||||
@@ -98,14 +99,14 @@ internal class WritAR:NSObject, AVCaptureAudioDataOutputSampleBufferDelegate {
|
||||
|
||||
switch videoInputOrientation {
|
||||
case .auto:
|
||||
t = t.rotated(by:((rotationAngle*CGFloat.pi)/180))
|
||||
t = t.rotated(by: ((rotationAngle*CGFloat.pi) / 180))
|
||||
case .alwaysPortrait:
|
||||
t = t.rotated(by:0)
|
||||
t = t.rotated(by: 0)
|
||||
case .alwaysLandscape:
|
||||
if rotationAngle == 90 || rotationAngle == -90 {
|
||||
t = t.rotated(by:((rotationAngle*CGFloat.pi)/180))
|
||||
}else{
|
||||
t = t.rotated(by:((-90*CGFloat.pi)/180))
|
||||
t = t.rotated(by: ((rotationAngle * CGFloat.pi) / 180))
|
||||
} else {
|
||||
t = t.rotated(by: ((-90 * CGFloat.pi) / 180))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,19 +114,19 @@ internal class WritAR:NSObject, AVCaptureAudioDataOutputSampleBufferDelegate {
|
||||
|
||||
if assetWriter.canAdd(videoInput) {
|
||||
assetWriter.add(videoInput)
|
||||
}else{
|
||||
} else {
|
||||
delegate?.recorder(didFailRecording: assetWriter.error, and: "An error occurred while adding video input.")
|
||||
isWritingWithoutError = false
|
||||
}
|
||||
assetWriter.shouldOptimizeForNetworkUse = adjustForSharing
|
||||
}
|
||||
|
||||
internal func prepareAudioDevice(with queue:DispatchQueue) {
|
||||
func prepareAudioDevice(with queue: DispatchQueue) {
|
||||
let device: AVCaptureDevice = AVCaptureDevice.default(for: .audio)!
|
||||
var audioDeviceInput:AVCaptureDeviceInput?
|
||||
var audioDeviceInput: AVCaptureDeviceInput?
|
||||
do {
|
||||
audioDeviceInput = try AVCaptureDeviceInput(device: device)
|
||||
}catch{
|
||||
} catch {
|
||||
audioDeviceInput = nil
|
||||
}
|
||||
|
||||
@@ -145,7 +146,7 @@ internal class WritAR:NSObject, AVCaptureAudioDataOutputSampleBufferDelegate {
|
||||
}
|
||||
|
||||
|
||||
audioSettings = audioDataOutput.recommendedAudioSettingsForAssetWriter(writingTo: .m4v) as? [String : Any]
|
||||
audioSettings = audioDataOutput.recommendedAudioSettingsForAssetWriter(writingTo: .m4v) as? [String: Any]
|
||||
|
||||
audioInput = AVAssetWriterInput(mediaType: .audio, outputSettings: audioSettings)
|
||||
audioInput.expectsMediaDataInRealTime = true
|
||||
@@ -159,49 +160,37 @@ internal class WritAR:NSObject, AVCaptureAudioDataOutputSampleBufferDelegate {
|
||||
}
|
||||
}
|
||||
|
||||
internal var startingVideoTime:CMTime?
|
||||
internal var isWritingWithoutError: Bool?
|
||||
var startingVideoTime: CMTime?
|
||||
var isWritingWithoutError: Bool?
|
||||
var currentDuration: TimeInterval = 0 // Seconds
|
||||
|
||||
internal func insert(pixel buffer:CVPixelBuffer, with intervals:CFTimeInterval) {
|
||||
var time:CMTime {return CMTimeMakeWithSeconds(intervals, 1000000);}
|
||||
if assetWriter.status == .unknown {
|
||||
if let _ = startingVideoTime {isWritingWithoutError = false; return}else{startingVideoTime = time}
|
||||
if assetWriter.startWriting() {
|
||||
assetWriter.startSession(atSourceTime: startingVideoTime!)
|
||||
session.startRunning()
|
||||
isRecording = true
|
||||
isWritingWithoutError = true
|
||||
}else{
|
||||
delegate?.recorder(didFailRecording: assetWriter.error, and: "An error occurred while starting the video session.")
|
||||
isWritingWithoutError = false
|
||||
}
|
||||
}else if assetWriter.status == .failed {
|
||||
delegate?.recorder(didFailRecording: assetWriter.error, and: "Video session failed while recording.")
|
||||
logAR.message("An error occurred while recording the video, status: \(assetWriter.status.rawValue), error: \(assetWriter.error!.localizedDescription)")
|
||||
isWritingWithoutError = false
|
||||
return
|
||||
}
|
||||
if videoInput.isReadyForMoreMediaData {
|
||||
append(pixel: buffer, with: time)
|
||||
isWritingWithoutError = true
|
||||
}
|
||||
func insert(pixel buffer: CVPixelBuffer, with intervals: CFTimeInterval) {
|
||||
let time: CMTime = CMTime(seconds: intervals, preferredTimescale: 1000000)
|
||||
insert(pixel: buffer, with: time)
|
||||
}
|
||||
|
||||
internal func insert(pixel buffer:CVPixelBuffer, with time:CMTime) {
|
||||
func insert(pixel buffer: CVPixelBuffer, with time: CMTime) {
|
||||
if assetWriter.status == .unknown {
|
||||
if let _ = startingVideoTime {isWritingWithoutError = false; return}else{startingVideoTime = time}
|
||||
guard startingVideoTime == nil else {
|
||||
isWritingWithoutError = false
|
||||
return
|
||||
}
|
||||
startingVideoTime = time
|
||||
if assetWriter.startWriting() {
|
||||
assetWriter.startSession(atSourceTime: startingVideoTime!)
|
||||
currentDuration = 0
|
||||
isRecording = true
|
||||
isWritingWithoutError = true
|
||||
}else{
|
||||
} else {
|
||||
delegate?.recorder(didFailRecording: assetWriter.error, and: "An error occurred while starting the video session.")
|
||||
currentDuration = 0
|
||||
isRecording = false
|
||||
isWritingWithoutError = false
|
||||
}
|
||||
}else if assetWriter.status == .failed {
|
||||
} else if assetWriter.status == .failed {
|
||||
delegate?.recorder(didFailRecording: assetWriter.error, and: "Video session failed while recording.")
|
||||
logAR.message("An error occurred while recording the video, status: \(assetWriter.status.rawValue), error: \(assetWriter.error!.localizedDescription)")
|
||||
currentDuration = 0
|
||||
isRecording = false
|
||||
isWritingWithoutError = false
|
||||
return
|
||||
@@ -209,8 +198,10 @@ internal class WritAR:NSObject, AVCaptureAudioDataOutputSampleBufferDelegate {
|
||||
|
||||
if videoInput.isReadyForMoreMediaData {
|
||||
append(pixel: buffer, with: time)
|
||||
currentDuration = time.seconds - startingVideoTime!.seconds
|
||||
isRecording = true
|
||||
isWritingWithoutError = true
|
||||
delegate?.recorder?(didUpdateRecording: currentDuration)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -227,30 +218,45 @@ internal class WritAR:NSObject, AVCaptureAudioDataOutputSampleBufferDelegate {
|
||||
func pause() {
|
||||
isRecording = false
|
||||
}
|
||||
func end(writing finished: @escaping () -> Void){
|
||||
|
||||
func end(writing finished: @escaping () -> Void) {
|
||||
if let session = session {
|
||||
if session.isRunning {
|
||||
session.stopRunning()
|
||||
}
|
||||
}
|
||||
assetWriter.finishWriting(completionHandler: finished)
|
||||
|
||||
if assetWriter.status == .writing {
|
||||
assetWriter.finishWriting(completionHandler: finished)
|
||||
}
|
||||
}
|
||||
|
||||
func cancel() {
|
||||
if let session = session {
|
||||
if session.isRunning {
|
||||
session.stopRunning()
|
||||
}
|
||||
}
|
||||
assetWriter.cancelWriting()
|
||||
}
|
||||
}
|
||||
|
||||
@available(iOS 11.0, *)
|
||||
fileprivate extension WritAR {
|
||||
func append(pixel buffer:CVPixelBuffer, with time: CMTime) {
|
||||
private extension WritAR {
|
||||
func append(pixel buffer: CVPixelBuffer, with time: CMTime) {
|
||||
pixelBufferInput.append(buffer, withPresentationTime: time)
|
||||
}
|
||||
}
|
||||
|
||||
//Simple Logging to show logs only while debugging.
|
||||
internal class logAR{
|
||||
internal class func message(_ message: String) {
|
||||
class logAR {
|
||||
class func message(_ message: String) {
|
||||
#if DEBUG
|
||||
print("ARVideoKit @ \(Date().timeIntervalSince1970):- \(message)")
|
||||
#endif
|
||||
}
|
||||
internal class func remove(from path: URL?) {
|
||||
|
||||
class func remove(from path: URL?) {
|
||||
if let file = path?.path {
|
||||
let manager = FileManager.default
|
||||
if manager.fileExists(atPath: file) {
|
||||
|
||||
@@ -9,9 +9,6 @@
|
||||
import UIKit
|
||||
import ARKit
|
||||
|
||||
fileprivate var parentVC:UIViewController?
|
||||
fileprivate var recentAngle = 0
|
||||
|
||||
/**
|
||||
A class that configures the Augmented Reality View orientations.
|
||||
|
||||
@@ -23,24 +20,27 @@ fileprivate var recentAngle = 0
|
||||
*/
|
||||
@available(iOS 11.0, *)
|
||||
@objc public class ARView: NSObject {
|
||||
fileprivate var ivo:[ARInputViewOrientation] = []
|
||||
private weak var parentVC: UIViewController?
|
||||
private var recentAngle = 0
|
||||
private var inputViewOrientation:[ARInputViewOrientation] = []
|
||||
|
||||
/// An array of `ARInputViewOrientation` objects that allow customizing the accepted orientations in a `UIViewController` that contains Augmented Reality scenes.
|
||||
public var inputViewOrientations:[ARInputViewOrientation] {
|
||||
public var inputViewOrientations: [ARInputViewOrientation] {
|
||||
get{
|
||||
return ivo
|
||||
return inputViewOrientation
|
||||
}
|
||||
set{
|
||||
if newValue.count == 0 {
|
||||
ivo = [.portrait]
|
||||
}else{
|
||||
ivo = newValue
|
||||
inputViewOrientation = [.portrait]
|
||||
} else {
|
||||
inputViewOrientation = newValue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate var ivom:ARInputViewOrientationMode = .auto
|
||||
private var ivom: ARInputViewOrientationMode = .auto
|
||||
/// An object that allow customizing which subviews will rotate in a `UIViewController` that contains Augmented Reality scenes.
|
||||
public var inputViewOrientationMode:ARInputViewOrientationMode {
|
||||
public var inputViewOrientationMode: ARInputViewOrientationMode {
|
||||
get{
|
||||
return ivom
|
||||
}
|
||||
@@ -50,9 +50,9 @@ fileprivate var recentAngle = 0
|
||||
}
|
||||
|
||||
|
||||
@objc init?(ARSceneKit:ARSCNView) {
|
||||
@objc init?(ARSceneKit: ARSCNView) {
|
||||
super.init()
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(deviceDidRotate), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(deviceDidRotate), name: UIDevice.orientationDidChangeNotification, object: nil)
|
||||
|
||||
let value = UIInterfaceOrientation.portrait.rawValue
|
||||
UIDevice.current.setValue(value, forKey: "orientation")
|
||||
@@ -66,9 +66,9 @@ fileprivate var recentAngle = 0
|
||||
parentVC = vc
|
||||
}
|
||||
|
||||
@objc init?(ARSpriteKit:ARSKView) {
|
||||
@objc init?(ARSpriteKit: ARSKView) {
|
||||
super.init()
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(deviceDidRotate), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(deviceDidRotate), name: UIDevice.orientationDidChangeNotification, object: nil)
|
||||
|
||||
let value = UIInterfaceOrientation.portrait.rawValue
|
||||
UIDevice.current.setValue(value, forKey: "orientation")
|
||||
@@ -80,9 +80,9 @@ fileprivate var recentAngle = 0
|
||||
parentVC = vc
|
||||
}
|
||||
|
||||
@objc init?(SceneKit:SCNView) {
|
||||
@objc init?(SceneKit: SCNView) {
|
||||
super.init()
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(deviceDidRotate), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(deviceDidRotate), name: UIDevice.orientationDidChangeNotification, object: nil)
|
||||
|
||||
let value = UIInterfaceOrientation.portrait.rawValue
|
||||
UIDevice.current.setValue(value, forKey: "orientation")
|
||||
@@ -96,7 +96,7 @@ fileprivate var recentAngle = 0
|
||||
parentVC = vc
|
||||
}
|
||||
|
||||
@objc fileprivate func deviceDidRotate() {
|
||||
@objc private func deviceDidRotate() {
|
||||
guard var views = parentVC?.view.subviews else {
|
||||
return
|
||||
}
|
||||
@@ -105,11 +105,11 @@ fileprivate var recentAngle = 0
|
||||
|
||||
switch inputViewOrientationMode {
|
||||
case .auto:
|
||||
views = views.filter{!$0.isARView && $0.isButton}
|
||||
views = views.filter { !$0.isARView && $0.isButton }
|
||||
case .all:
|
||||
views = views.filter{!$0.isARView}
|
||||
views = views.filter { !$0.isARView }
|
||||
case .manual(let subviews):
|
||||
views = subviews.filter{!$0.isARView}
|
||||
views = subviews.filter { !$0.isARView }
|
||||
case .disabled:
|
||||
views = []
|
||||
}
|
||||
|
||||
+222
-128
@@ -12,13 +12,6 @@ import ARKit
|
||||
import Photos
|
||||
import PhotosUI
|
||||
|
||||
fileprivate var view:Any?
|
||||
fileprivate var renderEngine:SCNRenderer!
|
||||
fileprivate var gpuLoop:CADisplayLink!
|
||||
fileprivate var isResting = false
|
||||
fileprivate var ARcontentMode:ARFrameMode!
|
||||
@available(iOS 11.0, *)
|
||||
fileprivate var renderer:RenderAR!
|
||||
/**
|
||||
This class renders the `ARSCNView` or `ARSKView` content with the device's camera stream to generate a video 📹, photo 🌄, live photo 🎇 or GIF 🎆.
|
||||
|
||||
@@ -34,7 +27,7 @@ fileprivate var renderer:RenderAR!
|
||||
/**
|
||||
An object that passes the AR recorder errors and status in the protocol methods.
|
||||
*/
|
||||
@objc public var delegate:RecordARDelegate?
|
||||
@objc public var delegate: RecordARDelegate?
|
||||
/**
|
||||
An object that passes the AR rendered content in the protocol method.
|
||||
*/
|
||||
@@ -42,55 +35,74 @@ fileprivate var renderer:RenderAR!
|
||||
/**
|
||||
An object that returns the AR recorder current status.
|
||||
*/
|
||||
@objc public internal(set)var status:RecordARStatus = .unknown
|
||||
@objc public internal(set)var status: RecordARStatus = .unknown
|
||||
/**
|
||||
An object that returns the current Microphone status.
|
||||
*/
|
||||
@objc public internal(set)var micStatus:RecordARMicrophoneStatus = .unknown
|
||||
@objc public internal(set)var micStatus: RecordARMicrophoneStatus = .unknown
|
||||
/**
|
||||
An object that allow customizing when to ask for Microphone permission, if needed. Default is `.auto`.
|
||||
An object that allow customizing when to ask for Microphone permission, if needed. Default is `.manual`.
|
||||
*/
|
||||
@objc public var requestMicPermission:RecordARMicrophonePermission = .auto
|
||||
@objc public var requestMicPermission: RecordARMicrophonePermission = .manual {
|
||||
didSet {
|
||||
switch self.requestMicPermission {
|
||||
case .auto:
|
||||
if self.enableAudio {
|
||||
self.requestMicrophonePermission()
|
||||
}
|
||||
case .manual:
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
An object that allow customizing the video frame per second rate. Default is `.auto`.
|
||||
*/
|
||||
@objc public var fps:ARVideoFrameRate = .auto
|
||||
@objc public var fps: ARVideoFrameRate = .auto
|
||||
/**
|
||||
An object that allow customizing the video orientation. Default is `.auto`.
|
||||
*/
|
||||
@objc public var videoOrientation:ARVideoOrientation = .auto
|
||||
@objc public var videoOrientation: ARVideoOrientation = .auto
|
||||
/**
|
||||
An object that allow customizing the AR content mode. Default is `.auto`.
|
||||
*/
|
||||
@objc public var contentMode:ARFrameMode = .auto
|
||||
@objc public var contentMode: ARFrameMode = .auto
|
||||
/**
|
||||
A boolean that enables or disables AR content rendering before recording for image & video processing. Default is `true`.
|
||||
*/
|
||||
@objc public var onlyRenderWhileRecording:Bool = true
|
||||
@objc public var onlyRenderWhileRecording: Bool = true {
|
||||
didSet {
|
||||
self.onlyRenderWhileRec = self.onlyRenderWhileRecording
|
||||
}
|
||||
}
|
||||
/**
|
||||
A boolean that enables or disables audio recording. Default is `true`.
|
||||
*/
|
||||
@objc public var enableAudio:Bool = true
|
||||
@objc public var enableAudio: Bool = true {
|
||||
didSet {
|
||||
self.requestMicPermission = (self.requestMicPermission == .manual) ? .manual: .auto
|
||||
}
|
||||
}
|
||||
/**
|
||||
A boolean that enables or disables audio `mixWithOthers` if audio recording is enabled. This allows playing music and recording audio at the same time. Default is `true`.
|
||||
*/
|
||||
@objc public var enableMixWithOthers:Bool = true
|
||||
@objc public var enableMixWithOthers: Bool = true
|
||||
/**
|
||||
A boolean that enables or disables adjusting captured media for sharing online. Default is `true`.
|
||||
*/
|
||||
@objc public var adjustVideoForSharing:Bool = true
|
||||
@objc public var adjustVideoForSharing: Bool = true
|
||||
/**
|
||||
A boolean that enables or disables adjusting captured GIFs for sharing online. Default is `true`.
|
||||
*/
|
||||
@objc public var adjustGIFForSharing:Bool = true
|
||||
@objc public var adjustGIFForSharing: Bool = true
|
||||
/**
|
||||
A boolean that enables or disables clearing cached media after exporting to Camera Roll. Default is `true`.
|
||||
*/
|
||||
@objc public var deleteCacheWhenExported:Bool = true
|
||||
@objc public var deleteCacheWhenExported: Bool = true
|
||||
/**
|
||||
A boolean that enables or disables using envronment light rendering. Default is `false`.
|
||||
*/
|
||||
@objc public var enableAdjustEnvironmentLighting:Bool = false {
|
||||
@objc public var enableAdjustEnvironmentLighting: Bool = false {
|
||||
didSet{
|
||||
if (renderEngine != nil) {
|
||||
renderEngine.autoenablesDefaultLighting = enableAdjustEnvironmentLighting
|
||||
@@ -136,48 +148,60 @@ fileprivate var renderer:RenderAR!
|
||||
view = SceneKit
|
||||
setup()
|
||||
}
|
||||
|
||||
//MARK: - Deinit
|
||||
deinit {
|
||||
gpuLoop.invalidate()
|
||||
}
|
||||
|
||||
//MARK: - Internal threads
|
||||
internal let writerQueue = DispatchQueue(label:"com.ahmedbekhit.WriterQueue")
|
||||
internal let gifWriterQueue = DispatchQueue(label: "com.ahmedbekhit.GIFWriterQueue", attributes: .concurrent)
|
||||
internal let audioSessionQueue = DispatchQueue(label: "com.ahmedbekhit.AudioSessionQueue", attributes: .concurrent)
|
||||
//MARK: - threads
|
||||
let writerQueue = DispatchQueue(label:"com.ahmedbekhit.WriterQueue")
|
||||
let gifWriterQueue = DispatchQueue(label: "com.ahmedbekhit.GIFWriterQueue", attributes: .concurrent)
|
||||
let audioSessionQueue = DispatchQueue(label: "com.ahmedbekhit.AudioSessionQueue", attributes: .concurrent)
|
||||
|
||||
//MARK: - Internal Objects
|
||||
fileprivate var scnView:SCNView!
|
||||
fileprivate var fileCount = 0
|
||||
//MARK: - Objects
|
||||
private var view: Any?
|
||||
private var renderEngine: SCNRenderer!
|
||||
private var gpuLoop: CADisplayLink!
|
||||
private var isResting = false
|
||||
private var ARcontentMode: ARFrameMode!
|
||||
private var renderer: RenderAR!
|
||||
|
||||
private var scnView: SCNView!
|
||||
private var fileCount = 0
|
||||
|
||||
internal var parent:UIViewController? {
|
||||
var parent: UIViewController? {
|
||||
if let view = view as? ARSCNView {
|
||||
return view.parent!
|
||||
}else if let view = view as? ARSKView {
|
||||
} else if let view = view as? ARSKView {
|
||||
return view.parent!
|
||||
}else if let view = view as? SCNView {
|
||||
} else if let view = view as? SCNView {
|
||||
return view.parent!
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
//Used for gif capturing
|
||||
internal var gifImages:[UIImage] = []
|
||||
var gifImages:[UIImage] = []
|
||||
//Used for checking current recorder status
|
||||
internal var isCapturingPhoto = false
|
||||
internal var isRecordingGIF = false
|
||||
internal var isRecording = false
|
||||
internal var adjustPausedTime = false
|
||||
internal var backFromPause = false
|
||||
internal var recordingWithLimit = false
|
||||
internal var onlyRenderWhileRec = false
|
||||
var isCapturingPhoto = false
|
||||
var isRecordingGIF = false
|
||||
var isRecording = false
|
||||
var adjustPausedTime = false
|
||||
var backFromPause = false
|
||||
var recordingWithLimit = false
|
||||
var onlyRenderWhileRec = true
|
||||
//Used to modify video time when paused
|
||||
internal var pausedFrameTime:CMTime?
|
||||
internal var resumeFrameTime:CMTime?
|
||||
var pausedFrameTime: CMTime?
|
||||
var resumeFrameTime: CMTime?
|
||||
//Used to locate the path of the video recording
|
||||
internal var currentVideoPath:URL?
|
||||
var currentVideoPath: URL?
|
||||
//Used to locate the path of the audio recording
|
||||
internal var currentAudioPath:URL?
|
||||
var currentAudioPath: URL?
|
||||
//Used to initialize the video writer
|
||||
internal var writer:WritAR?
|
||||
var writer: WritAR?
|
||||
//Used to generate a new video path
|
||||
internal var newVideoPath:URL {
|
||||
var newVideoPath: URL {
|
||||
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
|
||||
let documentsDirectory = paths[0]
|
||||
|
||||
@@ -192,20 +216,27 @@ fileprivate var renderer:RenderAR!
|
||||
return URL(fileURLWithPath: vidPath, isDirectory: false)
|
||||
}
|
||||
|
||||
//MARK: - Internal Video Setup
|
||||
internal func setup() {
|
||||
//MARK: - Video Setup
|
||||
func setup() {
|
||||
if let view = view as? ARSCNView {
|
||||
guard let mtlDevice = MTLCreateSystemDefaultDevice() else {logAR.message("ERROR:- This device does not support Metal");return}
|
||||
guard let mtlDevice = MTLCreateSystemDefaultDevice() else {
|
||||
logAR.message("ERROR:- This device does not support Metal")
|
||||
return
|
||||
}
|
||||
renderEngine = SCNRenderer(device: mtlDevice, options: nil)
|
||||
renderEngine.scene = view.scene
|
||||
|
||||
gpuLoop = CADisplayLink(target: self, selector: #selector(renderFrame))
|
||||
|
||||
gpuLoop = CADisplayLink(target: WeakProxy(target: self),
|
||||
selector: #selector(renderFrame))
|
||||
gpuLoop.preferredFramesPerSecond = fps.rawValue
|
||||
gpuLoop.add(to: .main, forMode: .commonModes)
|
||||
gpuLoop.add(to: .main, forMode: .common)
|
||||
|
||||
status = .readyToRecord
|
||||
}else if let view = view as? ARSKView {
|
||||
guard let mtlDevice = MTLCreateSystemDefaultDevice() else {logAR.message("ERROR:- This device does not support Metal");return}
|
||||
} else if let view = view as? ARSKView {
|
||||
guard let mtlDevice = MTLCreateSystemDefaultDevice() else {
|
||||
logAR.message("ERROR:- This device does not support Metal")
|
||||
return
|
||||
}
|
||||
let material = SCNMaterial()
|
||||
material.diffuse.contents = view.scene
|
||||
|
||||
@@ -218,42 +249,34 @@ fileprivate var renderer:RenderAR!
|
||||
|
||||
renderEngine = SCNRenderer(device: mtlDevice, options: nil)
|
||||
renderEngine.scene = scnView.scene
|
||||
|
||||
gpuLoop = CADisplayLink(target: self, selector: #selector(renderFrame))
|
||||
|
||||
gpuLoop = CADisplayLink(target: WeakProxy(target: self),
|
||||
selector: #selector(renderFrame))
|
||||
gpuLoop.preferredFramesPerSecond = fps.rawValue
|
||||
gpuLoop.add(to: .main, forMode: .commonModes)
|
||||
gpuLoop.add(to: .main, forMode: .common)
|
||||
|
||||
status = .readyToRecord
|
||||
}else if let view = view as? SCNView {
|
||||
guard let mtlDevice = MTLCreateSystemDefaultDevice() else {logAR.message("ERROR:- This device does not support Metal");return}
|
||||
} else if let view = view as? SCNView {
|
||||
guard let mtlDevice = MTLCreateSystemDefaultDevice() else {
|
||||
logAR.message("ERROR:- This device does not support Metal")
|
||||
return
|
||||
}
|
||||
renderEngine = SCNRenderer(device: mtlDevice, options: nil)
|
||||
renderEngine.scene = view.scene
|
||||
|
||||
gpuLoop = CADisplayLink(target: self, selector: #selector(renderFrame))
|
||||
|
||||
gpuLoop = CADisplayLink(target: WeakProxy(target: self),
|
||||
selector: #selector(renderFrame))
|
||||
gpuLoop.preferredFramesPerSecond = fps.rawValue
|
||||
gpuLoop.add(to: .main, forMode: .commonModes)
|
||||
gpuLoop.add(to: .main, forMode: .common)
|
||||
|
||||
status = .readyToRecord
|
||||
}
|
||||
|
||||
switch requestMicPermission {
|
||||
case .auto:
|
||||
AVAudioSession.sharedInstance().requestRecordPermission({ permitted in
|
||||
if permitted {
|
||||
self.micStatus = .enabled
|
||||
}else{
|
||||
self.micStatus = .disabled
|
||||
}
|
||||
})
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
onlyRenderWhileRec = onlyRenderWhileRecording
|
||||
|
||||
renderer = RenderAR(view, renderer: renderEngine, contentMode: contentMode)
|
||||
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(appWillEnterBackground), name: Notification.Name.UIApplicationWillResignActive, object: nil)
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(appWillEnterBackground), name: UIApplication.willResignActiveNotification, object: nil)
|
||||
}
|
||||
|
||||
|
||||
@@ -271,7 +294,7 @@ fileprivate var renderer:RenderAR!
|
||||
/**
|
||||
A method that renders a `PHLivePhoto` 🎇 and returns `PHLivePhotoPlus` in the completion handler.
|
||||
|
||||
In order to manually export the `PHLivePhotoPlus`, use `export(live photo:PHLivePhotoPlus)` method.
|
||||
In order to manually export the `PHLivePhotoPlus`, use `export(live photo: PHLivePhotoPlus)` method.
|
||||
- parameter export: A boolean that enables or disables automatically exporting the `PHLivePhotoPlus` when ready.
|
||||
- parameter finished: A block that will be called when Live Photo rendering is complete.
|
||||
|
||||
@@ -289,9 +312,9 @@ fileprivate var renderer:RenderAR!
|
||||
`exported`
|
||||
A boolean that returns `true` when a `PHLivePhotoPlus` is successfully exported to the Photo Library. Otherwise, it returns `false`.
|
||||
*/
|
||||
@objc public func livePhoto(export:Bool, _ finished: ((_ status:Bool, _ livePhoto:PHLivePhotoPlus, _ permissionStatus:PHAuthorizationStatus, _ exported:Bool) -> Swift.Void)? = nil) {
|
||||
@objc public func livePhoto(export: Bool, _ finished: ((_ status: Bool, _ livePhoto: PHLivePhotoPlus, _ permissionStatus: PHAuthorizationStatus, _ exported: Bool) -> Swift.Void)? = nil) {
|
||||
self.record(forDuration: 3.0) { path in
|
||||
let generator:LivePhotoGenerator? = LivePhotoGenerator()
|
||||
let generator: LivePhotoGenerator? = LivePhotoGenerator()
|
||||
generator?.generate(livePhoto: path) { success, photo, frames, keyFrame in
|
||||
if success && export {
|
||||
if self.fileCount == 0 {
|
||||
@@ -300,7 +323,7 @@ fileprivate var renderer:RenderAR!
|
||||
finished?(true, photo!, status, done)
|
||||
}
|
||||
}
|
||||
}else{
|
||||
} else {
|
||||
finished?(success, photo!, PHAuthorizationStatus.notDetermined, false)
|
||||
}
|
||||
}
|
||||
@@ -309,7 +332,7 @@ fileprivate var renderer:RenderAR!
|
||||
/**
|
||||
A method that generates a GIF 🎆 image and returns its local path (`URL`) in the completion handler.
|
||||
|
||||
In order to manually export the GIF image `URL`, use `func export(image path:URL)` method.
|
||||
In order to manually export the GIF image `URL`, use `func export(image path: URL)` method.
|
||||
- parameter duration: A `TimeInterval` object that can be set to the duration specified in seconds.
|
||||
- parameter export: A boolean that enables or disables automatically exporting the GIF image `URL` when ready.
|
||||
- parameter finished: A block that will be called when GIF image rendering is complete.
|
||||
@@ -328,23 +351,24 @@ fileprivate var renderer:RenderAR!
|
||||
`exported`
|
||||
A boolean that returns `true` when a GIF image `URL` is successfully exported to the Photo Library. Otherwise, it returns `false`.
|
||||
*/
|
||||
@objc public func gif(forDuration duration:TimeInterval, export:Bool, _ finished: ((_ status:Bool, _ gifPath: URL, _ permissionStatus:PHAuthorizationStatus, _ exported:Bool) -> Swift.Void)? = nil) {
|
||||
@objc public func gif(forDuration duration: TimeInterval, export: Bool, _ finished: ((_ status: Bool, _ gifPath: URL, _ permissionStatus: PHAuthorizationStatus, _ exported: Bool) -> Swift.Void)? = nil) {
|
||||
writerQueue.sync {
|
||||
self.isRecordingGIF = true
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + duration) {
|
||||
self.isRecordingGIF = false
|
||||
let generator:GIFGenerator? = GIFGenerator()
|
||||
generator?.generate(gif: self.gifImages, with: 0.1, loop: 0, adjust: self.adjustGIFForSharing) {ready, path in
|
||||
let generator: GIFGenerator? = GIFGenerator()
|
||||
generator?.generate(gif: self.gifImages, with: 0.1, loop: 0, adjust: self.adjustGIFForSharing) { ready, path in
|
||||
// FIXME: `path` may be nil
|
||||
if ready {
|
||||
self.gifImages.removeAll()
|
||||
if export {
|
||||
self.export(image: path!) { done, status in
|
||||
finished?(ready, path!, status, done)
|
||||
}
|
||||
}else{
|
||||
} else {
|
||||
finished?(ready, path!, .notDetermined, false)
|
||||
}
|
||||
}else{
|
||||
} else {
|
||||
self.gifImages.removeAll()
|
||||
finished?(ready, path!, .notDetermined, false)
|
||||
}
|
||||
@@ -355,8 +379,15 @@ fileprivate var renderer:RenderAR!
|
||||
///A method that starts or resumes ⏯ recording a video 📹.
|
||||
@objc public func record() {
|
||||
writerQueue.sync {
|
||||
self.isRecording = true
|
||||
self.status = .recording
|
||||
if self.enableAudio && micStatus == .unknown {
|
||||
self.requestMicrophonePermission { _ in
|
||||
self.isRecording = true
|
||||
self.status = .recording
|
||||
}
|
||||
} else {
|
||||
self.isRecording = true
|
||||
self.status = .recording
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
@@ -364,7 +395,7 @@ fileprivate var renderer:RenderAR!
|
||||
|
||||
In order to stop the recording before the specified duration, simply call `stop()` or `stopAndExport()` methods.
|
||||
|
||||
- WARNING : You CAN NOT `pause()` video recording when a duration is specified.
|
||||
- WARNING: You CAN NOT `pause()` video recording when a duration is specified.
|
||||
- parameter duration: A `TimeInterval` object that can be set to the duration specified in seconds.
|
||||
- parameter finished: A block that will be called when the specified `duration` has ended.
|
||||
|
||||
@@ -373,16 +404,30 @@ fileprivate var renderer:RenderAR!
|
||||
`videoPath`
|
||||
A `URL` object that contains the local file path of the video to allow manual exporting or preview of the video.
|
||||
*/
|
||||
@objc public func record(forDuration duration:TimeInterval, _ finished: ((_ videoPath: URL) -> Swift.Void)? = nil) {
|
||||
@objc public func record(forDuration duration: TimeInterval, _ finished: ((_ videoPath: URL) -> Swift.Void)? = nil) {
|
||||
writerQueue.sync {
|
||||
self.recordingWithLimit = true
|
||||
self.isRecording = true
|
||||
self.status = .recording
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + duration) {
|
||||
self.stop { path in
|
||||
finished?(path)
|
||||
if self.enableAudio && micStatus == .unknown {
|
||||
self.requestMicrophonePermission { _ in
|
||||
self.recordingWithLimit = true
|
||||
self.isRecording = true
|
||||
self.status = .recording
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + duration) {
|
||||
self.stop { path in
|
||||
finished?(path)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
self.recordingWithLimit = true
|
||||
self.isRecording = true
|
||||
self.status = .recording
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + duration) {
|
||||
self.stop { path in
|
||||
finished?(path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
/**
|
||||
@@ -395,8 +440,8 @@ fileprivate var renderer:RenderAR!
|
||||
onlyRenderWhileRec = false
|
||||
isRecording = false
|
||||
adjustPausedTime = true
|
||||
}else{
|
||||
logAR.message("NOT PERMITTED: The [ pause() ] method CAN NOT be used while using [ record(forDuration duration:TimeInterval) ]")
|
||||
} else {
|
||||
logAR.message("NOT PERMITTED: The [ pause() ] method CAN NOT be used while using [ record(forDuration duration: TimeInterval) ]")
|
||||
}
|
||||
}
|
||||
/**
|
||||
@@ -415,7 +460,7 @@ fileprivate var renderer:RenderAR!
|
||||
`exported`
|
||||
A boolean that returns `true` when a video is successfully exported to the Photo Library. Otherwise, it returns `false`.
|
||||
*/
|
||||
@objc public func stopAndExport(_ finished: ((_ videoPath: URL, _ permissionStatus:PHAuthorizationStatus, _ exported:Bool) -> Swift.Void)? = nil) {
|
||||
@objc public func stopAndExport(_ finished: ((_ videoPath: URL, _ permissionStatus: PHAuthorizationStatus, _ exported: Bool) -> Swift.Void)? = nil) {
|
||||
writerQueue.sync {
|
||||
self.isRecording = false
|
||||
self.adjustPausedTime = false
|
||||
@@ -432,7 +477,7 @@ fileprivate var renderer:RenderAR!
|
||||
}
|
||||
self.delegate?.recorder(didEndRecording: path, with: true)
|
||||
self.status = .readyToRecord
|
||||
}else{
|
||||
} else {
|
||||
finished?(self.currentVideoPath!, .notDetermined, false)
|
||||
self.status = .readyToRecord
|
||||
self.delegate?.recorder(didFailRecording: errSecDecode as? Error, and: "An error occured while stopping your video.")
|
||||
@@ -467,7 +512,7 @@ fileprivate var renderer:RenderAR!
|
||||
finished?(path)
|
||||
self.delegate?.recorder(didEndRecording: path, with: true)
|
||||
self.status = .readyToRecord
|
||||
}else{
|
||||
} else {
|
||||
self.status = .readyToRecord
|
||||
self.delegate?.recorder(didFailRecording: errSecDecode as? Error, and: "An error occured while stopping your video.")
|
||||
}
|
||||
@@ -476,6 +521,39 @@ fileprivate var renderer:RenderAR!
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
A method that cancels ⏹ recording a video 📹.
|
||||
|
||||
- parameter finished: A block that will be called when the specified `duration` has ended.
|
||||
|
||||
*/
|
||||
@objc public func cancel() {
|
||||
writerQueue.sync {
|
||||
isRecording = false
|
||||
adjustPausedTime = false
|
||||
backFromPause = false
|
||||
recordingWithLimit = false
|
||||
|
||||
pausedFrameTime = nil
|
||||
resumeFrameTime = nil
|
||||
|
||||
DispatchQueue.main.async {
|
||||
self.writer?.cancel()
|
||||
if let path = self.currentVideoPath {
|
||||
logAR.remove(from: path)
|
||||
self.delegate?.recorder?(didCancelRecording: "Recording was cancelled manually.")
|
||||
self.status = .readyToRecord
|
||||
} else {
|
||||
self.status = .readyToRecord
|
||||
self.delegate?.recorder(didFailRecording: errSecDecode as? Error, and: "An error occured while stopping your video.")
|
||||
}
|
||||
self.writer = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
A method that exports a video 📹 file path to the Photo Library 📲💾.
|
||||
|
||||
@@ -557,7 +635,7 @@ fileprivate var renderer:RenderAR!
|
||||
/**
|
||||
A method that exports a `PHLivePhotoPlus` 🎇 object to the Photo Library 📲💾.
|
||||
|
||||
- parameter photo: A `PHLivePhotoPlus` object that can be set to the returned `PHLivePhotoPlus` object in the `livePhoto(export:Bool, _ finished:{})` method.
|
||||
- parameter photo: A `PHLivePhotoPlus` object that can be set to the returned `PHLivePhotoPlus` object in the `livePhoto(export: Bool, _ finished:{})` method.
|
||||
|
||||
- parameter finished: A block that will be called when the export process is complete.
|
||||
|
||||
@@ -570,8 +648,14 @@ fileprivate var renderer:RenderAR!
|
||||
A `PHAuthorizationStatus` object that returns the current application's status for exporting media to the Photo Library.
|
||||
*/
|
||||
@objc public func export(live photo: PHLivePhotoPlus, _ finished: ((_ exported: Bool, _ permissionStatus: PHAuthorizationStatus) -> Void)? = nil) {
|
||||
guard let keyPhotoPath = photo.keyPhotoPath else{logAR.message("An error occurred while exporting a live photo"); return}
|
||||
guard let videoPath = photo.pairedVideoPath else{logAR.message("An error occurred while exporting a live photo"); return}
|
||||
guard let keyPhotoPath = photo.keyPhotoPath else {
|
||||
logAR.message("An error occurred while exporting a live photo")
|
||||
return
|
||||
}
|
||||
guard let videoPath = photo.pairedVideoPath else {
|
||||
logAR.message("An error occurred while exporting a live photo")
|
||||
return
|
||||
}
|
||||
|
||||
let status = PHPhotoLibrary.authorizationStatus()
|
||||
if status == .notDetermined {
|
||||
@@ -616,7 +700,7 @@ fileprivate var renderer:RenderAR!
|
||||
finished?(permitted)
|
||||
if permitted {
|
||||
self.micStatus = .enabled
|
||||
}else{
|
||||
} else {
|
||||
self.micStatus = .disabled
|
||||
}
|
||||
})
|
||||
@@ -632,7 +716,7 @@ fileprivate var renderer:RenderAR!
|
||||
Recommended to use in the `UIViewController`'s method `func viewWillAppear(_ animated: Bool)`
|
||||
- parameter configuration: An object that defines motion and scene tracking behaviors for the session.
|
||||
*/
|
||||
@objc public func prepare(_ configuration:ARConfiguration?=nil) {
|
||||
@objc public func prepare(_ configuration: ARConfiguration? = nil) {
|
||||
ARcontentMode = contentMode
|
||||
onlyRenderWhileRec = onlyRenderWhileRecording
|
||||
if let view = view as? ARSCNView {
|
||||
@@ -640,14 +724,14 @@ fileprivate var renderer:RenderAR!
|
||||
ViewAR.orientation = .portrait
|
||||
|
||||
//try resetting anchors for the initial landscape orientation issue.
|
||||
guard let config = configuration else {return}
|
||||
guard let config = configuration else { return }
|
||||
view.session.run(config)
|
||||
}else if let view = view as? ARSKView {
|
||||
} else if let view = view as? ARSKView {
|
||||
UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
|
||||
ViewAR.orientation = .portrait
|
||||
guard let config = configuration else {return}
|
||||
guard let config = configuration else { return }
|
||||
view.session.run(config)
|
||||
}else if let _ = view as? SCNView {
|
||||
} else if let _ = view as? SCNView {
|
||||
UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
|
||||
ViewAR.orientation = .portrait
|
||||
}
|
||||
@@ -662,19 +746,27 @@ fileprivate var renderer:RenderAR!
|
||||
}
|
||||
}
|
||||
|
||||
//MARK: - Internal AR Video Frames Rendering
|
||||
//MARK: - AR Video Frames Rendering
|
||||
@available(iOS 11.0, *)
|
||||
internal extension RecordAR {
|
||||
@objc internal func renderFrame() {
|
||||
extension RecordAR {
|
||||
@objc func renderFrame() {
|
||||
//frame rendering
|
||||
if self.onlyRenderWhileRec && !isRecording && !isRecordingGIF {return}
|
||||
guard let buffer = renderer.buffer else{return}
|
||||
guard let rawBuffer = renderer.rawBuffer else{logAR.message("ERROR:- An error occurred while rendering the camera's main buffers.");return}
|
||||
guard let size = renderer.bufferSize else{logAR.message("ERROR:- An error occurred while rendering the camera buffer.");return}
|
||||
if self.onlyRenderWhileRec && !isRecording && !isRecordingGIF { return }
|
||||
|
||||
guard let buffer = renderer.buffer else { return }
|
||||
guard let rawBuffer = renderer.rawBuffer else {
|
||||
logAR.message("ERROR:- An error occurred while rendering the camera's main buffers.")
|
||||
return
|
||||
}
|
||||
guard let size = renderer.bufferSize else {
|
||||
logAR.message("ERROR:- An error occurred while rendering the camera buffer.")
|
||||
return
|
||||
}
|
||||
renderer.ARcontentMode = contentMode
|
||||
|
||||
self.writerQueue.sync {
|
||||
var time:CMTime {return CMTimeMakeWithSeconds(renderer.time, 1000000);}
|
||||
|
||||
var time: CMTime { return CMTime(seconds: renderer.time, preferredTimescale: 1000000) }
|
||||
|
||||
self.renderAR?.frame(didRender: buffer, with: time, using: rawBuffer)
|
||||
|
||||
@@ -688,22 +780,22 @@ internal extension RecordAR {
|
||||
//frame writing
|
||||
if self.isRecording {
|
||||
if let frameWriter = self.writer {
|
||||
var finalFrameTime:CMTime?
|
||||
var finalFrameTime: CMTime?
|
||||
if self.backFromPause {
|
||||
if self.resumeFrameTime == nil {
|
||||
self.resumeFrameTime = time
|
||||
}
|
||||
//Formula: (currentTime - (timeWhenResume - timeWhenPaused))
|
||||
guard let resumeTime = self.resumeFrameTime else {return}
|
||||
guard let pausedTime = self.pausedFrameTime else {return}
|
||||
guard let resumeTime = self.resumeFrameTime,
|
||||
let pausedTime = self.pausedFrameTime else { return }
|
||||
finalFrameTime = self.adjustTime(current: time, resume: resumeTime, pause: pausedTime)
|
||||
}else{
|
||||
} else {
|
||||
finalFrameTime = time
|
||||
}
|
||||
|
||||
frameWriter.insert(pixel: buffer, with: finalFrameTime!)
|
||||
|
||||
guard let isWriting = frameWriter.isWritingWithoutError else {return}
|
||||
guard let isWriting = frameWriter.isWritingWithoutError else { return }
|
||||
if !isWriting {
|
||||
self.isRecording = false
|
||||
|
||||
@@ -711,21 +803,23 @@ internal extension RecordAR {
|
||||
self.delegate?.recorder(didFailRecording: errSecDecode as? Error, and: "An error occured while recording your video.")
|
||||
self.delegate?.recorder(didEndRecording: self.currentVideoPath!, with: false)
|
||||
}
|
||||
}else{
|
||||
} else {
|
||||
self.currentVideoPath = self.newVideoPath
|
||||
|
||||
self.writer = WritAR(output: self.currentVideoPath!, width: Int(size.width), height: Int(size.height), adjustForSharing: self.adjustVideoForSharing, audioEnabled: self.enableAudio, orientaions: self.inputViewOrientations, queue: self.writerQueue, allowMix: self.enableMixWithOthers)
|
||||
self.writer?.videoInputOrientation = self.videoOrientation
|
||||
self.writer?.delegate = self.delegate
|
||||
}
|
||||
}else if !self.isRecording && self.adjustPausedTime {
|
||||
} else if !self.isRecording && self.adjustPausedTime {
|
||||
writer?.pause()
|
||||
|
||||
self.adjustPausedTime = false
|
||||
|
||||
if self.pausedFrameTime != nil {
|
||||
self.pausedFrameTime = self.adjustTime(current: time, resume: self.resumeFrameTime!, pause: self.pausedFrameTime!)
|
||||
}else{
|
||||
if self.pausedFrameTime != nil && self.resumeFrameTime != nil {
|
||||
self.pausedFrameTime = self.adjustTime(current: time,
|
||||
resume: self.resumeFrameTime!,
|
||||
pause: self.pausedFrameTime!)
|
||||
} else {
|
||||
self.pausedFrameTime = time
|
||||
}
|
||||
|
||||
|
||||
@@ -23,9 +23,12 @@ import ARKit
|
||||
|
||||
Recommended to return in the application delegate method `func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask`.
|
||||
*/
|
||||
@objc internal(set) public static var orientation: UIInterfaceOrientationMask {get {return mask;}set {mask = newValue}}
|
||||
@objc internal(set) public static var orientation: UIInterfaceOrientationMask {
|
||||
get { return mask }
|
||||
set { mask = newValue }
|
||||
}
|
||||
|
||||
internal static var orientations:[UIInterfaceOrientationMask] {
|
||||
static var orientations: [UIInterfaceOrientationMask] {
|
||||
var all:[UIInterfaceOrientationMask] = []
|
||||
if let info = Bundle.main.infoDictionary {
|
||||
if let supportedOrientaions = info["UISupportedInterfaceOrientations"] as? NSArray {
|
||||
@@ -33,11 +36,11 @@ import ARKit
|
||||
if let o = orientation as? String {
|
||||
if o == "UIInterfaceOrientationPortrait" {
|
||||
all.append(.portrait)
|
||||
}else if o == "UIInterfaceOrientationPortraitUpsideDown" {
|
||||
} else if o == "UIInterfaceOrientationPortraitUpsideDown" {
|
||||
all.append(.portraitUpsideDown)
|
||||
}else if o == "UIInterfaceOrientationLandscapeLeft" {
|
||||
} else if o == "UIInterfaceOrientationLandscapeLeft" {
|
||||
all.append(.landscapeLeft)
|
||||
}else if o == "UIInterfaceOrientationLandscapeRight" {
|
||||
} else if o == "UIInterfaceOrientationLandscapeRight" {
|
||||
all.append(.landscapeRight)
|
||||
}
|
||||
}
|
||||
@@ -48,9 +51,21 @@ import ARKit
|
||||
return all
|
||||
}
|
||||
//returns the application's delegate to check if the current UIViewController contains an ARView
|
||||
fileprivate static var delegate = UIApplication.shared.delegate
|
||||
private static var delegate = UIApplication.shared.delegate
|
||||
//variable for the setter in `mask`
|
||||
fileprivate static var m: UIInterfaceOrientationMask = .portrait
|
||||
private static var m: UIInterfaceOrientationMask = .portrait
|
||||
//returns the most appropriate orientation based on the content of the UIViewController.
|
||||
fileprivate static var mask: UIInterfaceOrientationMask {get {if let vc = delegate?.window??.inputViewController {if vc.hasARView {return .portrait}else{return UIInterfaceOrientationMask(orientations)}};return m;}set {m = newValue;}}
|
||||
private static var mask: UIInterfaceOrientationMask {
|
||||
get {
|
||||
if let vc = delegate?.window??.inputViewController {
|
||||
if vc.hasARView {
|
||||
return .portrait
|
||||
} else {
|
||||
return UIInterfaceOrientationMask(orientations)
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
set { m = newValue }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
//
|
||||
// SSSS.swift
|
||||
// ARVideoKit
|
||||
//
|
||||
// Created by Saul Moreno Abril on 01/05/2019.
|
||||
// Copyright © 2019 Ahmed Fathit Bekhit. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
class WeakProxy: NSObject {
|
||||
weak var target: NSObjectProtocol?
|
||||
|
||||
init(target: NSObjectProtocol) {
|
||||
self.target = target
|
||||
super.init()
|
||||
}
|
||||
|
||||
override func responds(to aSelector: Selector!) -> Bool {
|
||||
return (target?.responds(to: aSelector) ?? false) || super.responds(to: aSelector)
|
||||
}
|
||||
|
||||
override func forwardingTarget(for aSelector: Selector!) -> Any? {
|
||||
return target
|
||||
}
|
||||
}
|
||||
@@ -418,7 +418,7 @@
|
||||
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
DEVELOPMENT_TEAM = P5DZ3XQ9FJ;
|
||||
DEVELOPMENT_TEAM = LXD85S9DW4;
|
||||
FRAMEWORK_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"$(PROJECT_DIR)",
|
||||
@@ -429,7 +429,7 @@
|
||||
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
|
||||
PRODUCT_BUNDLE_IDENTIFIER = "com.ahmedbekhit.ARVideoKit-Example";
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_VERSION = 4.0;
|
||||
SWIFT_VERSION = 4.2;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
};
|
||||
name = Debug;
|
||||
@@ -440,7 +440,7 @@
|
||||
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
DEVELOPMENT_TEAM = P5DZ3XQ9FJ;
|
||||
DEVELOPMENT_TEAM = LXD85S9DW4;
|
||||
FRAMEWORK_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"$(PROJECT_DIR)",
|
||||
@@ -451,7 +451,7 @@
|
||||
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
|
||||
PRODUCT_BUNDLE_IDENTIFIER = "com.ahmedbekhit.ARVideoKit-Example";
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_VERSION = 4.0;
|
||||
SWIFT_VERSION = 4.2;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
};
|
||||
name = Release;
|
||||
|
||||
@@ -19,8 +19,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
|
||||
return ViewAR.orientation
|
||||
}
|
||||
|
||||
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
|
||||
// Override point for customization after application launch.
|
||||
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
@@ -41,6 +41,8 @@ class SCNViewController: UIViewController, ARSCNViewDelegate, RenderARDelegate,
|
||||
sceneView.autoenablesDefaultLighting = true
|
||||
|
||||
// Initialize ARVideoKit recorder
|
||||
|
||||
|
||||
recorder = RecordAR(ARSceneKit: sceneView)
|
||||
|
||||
/*----👇---- ARVideoKit Configuration ----👇----*/
|
||||
@@ -113,7 +115,7 @@ class SCNViewController: UIViewController, ARSCNViewDelegate, RenderARDelegate,
|
||||
}else if status == .denied || status == .restricted || status == .notDetermined {
|
||||
let errorView = UIAlertController(title: "😅", message: "Please allow access to the photo library in order to save this media file.", preferredStyle: .alert)
|
||||
let settingsBtn = UIAlertAction(title: "Open Settings", style: .cancel) { (_) -> Void in
|
||||
guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else {
|
||||
guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else {
|
||||
return
|
||||
}
|
||||
if UIApplication.shared.canOpenURL(settingsUrl) {
|
||||
@@ -121,11 +123,11 @@ class SCNViewController: UIViewController, ARSCNViewDelegate, RenderARDelegate,
|
||||
UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
|
||||
})
|
||||
} else {
|
||||
UIApplication.shared.openURL(URL(string:UIApplicationOpenSettingsURLString)!)
|
||||
UIApplication.shared.openURL(URL(string:UIApplication.openSettingsURLString)!)
|
||||
}
|
||||
}
|
||||
}
|
||||
errorView.addAction(UIAlertAction(title: "Later", style: UIAlertActionStyle.default, handler: {
|
||||
errorView.addAction(UIAlertAction(title: "Later", style: UIAlertAction.Style.default, handler: {
|
||||
(UIAlertAction)in
|
||||
}))
|
||||
errorView.addAction(settingsBtn)
|
||||
|
||||
@@ -106,7 +106,7 @@ class SKViewController: UIViewController, ARSKViewDelegate, RenderARDelegate, Re
|
||||
}else if status == .denied || status == .restricted || status == .notDetermined {
|
||||
let errorView = UIAlertController(title: "😅", message: "Please allow access to the photo library in order to save this media file.", preferredStyle: .alert)
|
||||
let settingsBtn = UIAlertAction(title: "Open Settings", style: .cancel) { (_) -> Void in
|
||||
guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else {
|
||||
guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else {
|
||||
return
|
||||
}
|
||||
if UIApplication.shared.canOpenURL(settingsUrl) {
|
||||
@@ -114,11 +114,11 @@ class SKViewController: UIViewController, ARSKViewDelegate, RenderARDelegate, Re
|
||||
UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
|
||||
})
|
||||
} else {
|
||||
UIApplication.shared.openURL(URL(string:UIApplicationOpenSettingsURLString)!)
|
||||
UIApplication.shared.openURL(URL(string:UIApplication.openSettingsURLString)!)
|
||||
}
|
||||
}
|
||||
}
|
||||
errorView.addAction(UIAlertAction(title: "Later", style: UIAlertActionStyle.default, handler: {
|
||||
errorView.addAction(UIAlertAction(title: "Later", style: UIAlertAction.Style.default, handler: {
|
||||
(UIAlertAction)in
|
||||
}))
|
||||
errorView.addAction(settingsBtn)
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||

|
||||
> Use [swift_5](https://github.com/AFathi/ARVideoKit/tree/swift_5) branch for projects written in Swift 5
|
||||
|
||||
> Use [master](https://github.com/AFathi/ARVideoKit/tree/master) branch for projects written in Swift 4.0
|
||||
|
||||

|
||||
|
||||
An iOS Framework that enables developers to capture videos 📹, photos 🌄, Live Photos 🎇, and GIFs 🎆 with ARKit content.
|
||||
|
||||
@@ -12,7 +16,7 @@ In other words, you **NO LONGER** have to ~screen record~/~screenshot~ to captur
|
||||
| [Key Features](#key-features) | Lists the key features `ARVideoKit` offers |
|
||||
| [Compatibility](#compatibility) | Describes the `ARVideoKit` device and iOS compatibality |
|
||||
| [Example Projects](#example-projects) | Explains how to run the example project provided in this repository |
|
||||
| [Installation](#installation) | Describes the [Cocoapods](#cocoapods) & [Manual](#manual) options to install `ARVideoKit` |
|
||||
| [Installation](#installation) | Describes the [Cocoapods](#cocoapods), [Carthage](#carthage) & [Manual](#manual) options to install `ARVideoKit` |
|
||||
| [Implementation](#implementation) | Lists the [steps needed](#implementation) for Objective-C & Swift, [notes](#note), and [reference](#youre-all-set-) for more options |
|
||||
| [Publishing to the App Store](#publishing-to-the-app-store) | Describes the steps **required** before submitting an application using `ARVideoKit` to the App Store. |
|
||||
|[](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=ahmedfbekhit@gmail.com&item_name=Support+ARVideoKit+Developer&item_number=ARVideoKit+Framework+Donations&amount=0%2e00¤cy_code=USD) | [Donations](#donate) will support me to keep maintaining `ARVideoKit` ❤️|
|
||||
@@ -50,32 +54,27 @@ To try the example project, simply clone this repository and open the `Examples`
|
||||
|
||||
## Installation
|
||||
### Cocoapods
|
||||
1. Download [CocoaPods](http://cocoapods.org) using this command in `Terminal`
|
||||
1. Add this line to your project's `Podfile` (for Swift 4.2 projects)
|
||||
```
|
||||
$ sudo gem install cocoapods
|
||||
pod 'ARVideoKit','~> 1.51'
|
||||
```
|
||||
2. Redirect to your project folder in `Terminal`
|
||||
```
|
||||
$ cd YOUR_PROJECT_FILE_PATH
|
||||
```
|
||||
3. Initialize a pod in `Terminal`
|
||||
```
|
||||
$ pod init
|
||||
```
|
||||
4. Open Podfile in a text editor and add this line
|
||||
```
|
||||
pod 'ARVideoKit'
|
||||
```
|
||||
5. Go back to the `Terminal` and install the pod
|
||||
2. Install the pod
|
||||
```
|
||||
$ pod install
|
||||
```
|
||||
|
||||
### Manual
|
||||
Drag the `ARVideoKit.framework` file as an embedded binary of your project targets. `ARVideoKit.framework` can be found in the `/Framework Build/` folder of this repository.
|
||||

|
||||
### Carthage
|
||||
1. Add this line to your project's `Cartfile`
|
||||
```
|
||||
github "AFathi/ARVideoKit" ~> 1.31
|
||||
```
|
||||
2. Update your Carthage directory
|
||||
```
|
||||
$ carthage update
|
||||
```
|
||||
|
||||
Or you may drag `ARVideoKit.xcodeproj` into your project and click the **+** button in the embedded binaries section of your project's target.
|
||||
### Manual
|
||||
Drag `ARVideoKit.xcodeproj` into your project and click the **+** button in the embedded binaries section of your project's target.
|
||||

|
||||
## Implementation
|
||||
### Swift
|
||||
@@ -154,10 +153,15 @@ Also, feel free to create an issue if you have any suggestions or need any help
|
||||
|
||||
_Feel free to add your application to this list!_
|
||||
## License
|
||||
Copyright 2017 Ahmed Fathi Bekhit, www.ahmedbekhit.com, me@ahmedbekhit.com
|
||||
### ARVideoKit Framework
|
||||
Copyright 2018 Ahmed Fathi Bekhit, www.ahmedbekhit.com, me@ahmedbekhit.com
|
||||
|
||||
`ARVideoKit` is licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
|
||||
|
||||
[http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
|
||||
|
||||
### ARVideoKit Logo & Header
|
||||
Designed by [**Gabriel Garcia**](https://github.com/ggabogarcia) and licensed under the [Creative Commons Attribution 4.0 International License](https://creativecommons.org/licenses/by/4.0/)
|
||||

|
||||
|
||||
Binary file not shown.
@@ -1,32 +0,0 @@
|
||||
//
|
||||
// ARInputViewOptions.swift
|
||||
// AR Video
|
||||
//
|
||||
// Created by Ahmed Bekhit on 10/18/17.
|
||||
// Copyright © 2017 Ahmed Fathi Bekhit. All rights reserved.
|
||||
//
|
||||
|
||||
import UIKit
|
||||
|
||||
/// Allows specifying the accepted orientaions in a `UIViewController` with AR scenes.
|
||||
@objc public enum ARInputViewOrientation: Int {
|
||||
/// Enables the portrait input views orientation.
|
||||
case portrait = 1
|
||||
/// Enables the landscape left input views orientation.
|
||||
case landscapeLeft = 3
|
||||
/// Enables the landscape right input views orientation.
|
||||
case landscapeRight = 4
|
||||
}
|
||||
|
||||
/// Allows specifying which subviews will rotate in a `UIViewController` with AR scenes.
|
||||
public enum ARInputViewOrientationMode {
|
||||
/// The framework automatically detects and rotates key objects in a `UIViewController`.
|
||||
case auto
|
||||
/// Rotates all objects in a `UIViewController`.
|
||||
case all
|
||||
/// Rotates manually specified `UIView` subviews in a `UIViewController`.
|
||||
case manual(subviews:[UIView])
|
||||
/// Disables rotating any objects in a `UIViewController`.
|
||||
case disabled
|
||||
}
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
//
|
||||
// ARVideoOptions.swift
|
||||
// AR Video
|
||||
//
|
||||
// Created by Ahmed Bekhit on 10/18/17.
|
||||
// Copyright © 2017 Ahmed Fathi Bekhit. All rights reserved.
|
||||
//
|
||||
|
||||
/// Allows specifying the final video orientation.
|
||||
@objc public enum ARFrameMode: Int {
|
||||
case auto
|
||||
case aspectFit
|
||||
/// Recommended for iPhone X
|
||||
case aspectFill
|
||||
}
|
||||
/// Allows specifying the video rendering frame per second `FPS` rate.
|
||||
@objc public enum ARVideoFrameRate: Int {
|
||||
/// The framework automatically sets the most appropriate `FPS` based on the device support.
|
||||
case auto = 0
|
||||
/// Sets the `FPS` to 30 frames per second.
|
||||
case fps30 = 30
|
||||
/// Sets the `FPS` to 60 frames per second.
|
||||
case fps60 = 60
|
||||
}
|
||||
/// Allows specifying the final video orientation.
|
||||
@objc public enum ARVideoOrientation: Int {
|
||||
/// The framework automatically sets the video orientation based on the active `ARInputViewOrientation` orientations.
|
||||
case auto
|
||||
/// Sets the video orientation to always portrait.
|
||||
case alwaysPortrait
|
||||
/// Sets the video orientation to always landscape.
|
||||
case alwaysLandscape
|
||||
}
|
||||
/// Allows specifying when to request Microphone access.
|
||||
@objc public enum RecordARMicrophonePermission: Int {
|
||||
/// The framework automatically requests Microphone access when needed.
|
||||
case auto
|
||||
/// Allows manual permission request.
|
||||
case manual
|
||||
}
|
||||
/// An object that returns the AR recorder current status.
|
||||
@objc public enum RecordARStatus: Int {
|
||||
/// The current status of the recorder is unknown.
|
||||
case unknown
|
||||
/// The current recorder is ready to record.
|
||||
case readyToRecord
|
||||
/// The current recorder is recording.
|
||||
case recording
|
||||
/// The current recorder is paused.
|
||||
case paused
|
||||
}
|
||||
/// An object that returns the current Microphone status.
|
||||
@objc public enum RecordARMicrophoneStatus: Int {
|
||||
// The current status of the Microphone access is unknown.
|
||||
case unknown
|
||||
// The current status of the Microphone access is enabled.
|
||||
case enabled
|
||||
// The current status of the Microphone access is disabled.
|
||||
case disabled
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
//
|
||||
// CGImage+Resize.swift
|
||||
// AR Video
|
||||
//
|
||||
// Created by Ahmed Bekhit on 10/27/17.
|
||||
// Copyright © 2017 Ahmed Fathi Bekhit. All rights reserved.
|
||||
//
|
||||
|
||||
import CoreGraphics
|
||||
|
||||
internal extension CGImage {
|
||||
internal func resize(with ratio:Float) -> CGImage? {
|
||||
let imageWidth = Float(self.width)
|
||||
let imageHeight = Float(self.height)
|
||||
|
||||
let width = imageWidth * ratio
|
||||
let height = imageHeight * ratio
|
||||
|
||||
guard let colorSpace = self.colorSpace else { return nil }
|
||||
guard let context = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: self.bitsPerComponent, bytesPerRow: self.bytesPerRow, space: colorSpace, bitmapInfo: self.alphaInfo.rawValue) else { return nil }
|
||||
|
||||
context.interpolationQuality = .low
|
||||
context.draw(self, in: CGRect(x: 0, y: 0, width: Int(width), height: Int(height)))
|
||||
|
||||
return context.makeImage()
|
||||
}
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
//
|
||||
// RecordAR+PhotoRender.swift
|
||||
// AR Video
|
||||
//
|
||||
// Created by Ahmed Bekhit on 10/27/17.
|
||||
// Copyright © 2017 Ahmed Fathi Bekhit. All rights reserved.
|
||||
//
|
||||
|
||||
import AVFoundation
|
||||
import Photos
|
||||
@available(iOS 11.0, *)
|
||||
internal extension RecordAR {
|
||||
|
||||
internal func adjustTime(current:CMTime, resume:CMTime, pause:CMTime) -> CMTime {
|
||||
return CMTimeSubtract(current, CMTimeSubtract(resume, pause))
|
||||
}
|
||||
|
||||
internal func imageFromBuffer(buffer:CVPixelBuffer) -> UIImage {
|
||||
let coreImg = CIImage(cvPixelBuffer: buffer)
|
||||
let context = CIContext()
|
||||
let cgImg = context.createCGImage(coreImg, from: coreImg.extent)
|
||||
|
||||
var angleEnabled: Bool {
|
||||
for v in inputViewOrientations {
|
||||
if UIDevice.current.orientation.rawValue == v.rawValue {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
var recentAngle:CGFloat = 0
|
||||
var rotationAngle:CGFloat = 0
|
||||
switch UIDevice.current.orientation {
|
||||
case .landscapeLeft:
|
||||
rotationAngle = -90
|
||||
recentAngle = -90
|
||||
case .landscapeRight:
|
||||
rotationAngle = 90
|
||||
recentAngle = 90
|
||||
case .faceUp, .faceDown, .portraitUpsideDown:
|
||||
rotationAngle = recentAngle
|
||||
default:
|
||||
rotationAngle = 0
|
||||
recentAngle = 0
|
||||
}
|
||||
|
||||
if !angleEnabled {
|
||||
rotationAngle = 0
|
||||
}
|
||||
|
||||
switch videoOrientation {
|
||||
case .alwaysPortrait:
|
||||
rotationAngle = 0
|
||||
case .alwaysLandscape:
|
||||
if rotationAngle == 90 || rotationAngle == -90 {
|
||||
}else{
|
||||
rotationAngle = -90
|
||||
}
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
return UIImage(cgImage: cgImg!).rotate(by: rotationAngle, flip: false)
|
||||
}
|
||||
|
||||
@objc internal func appWillEnterBackground() {
|
||||
delegate?.recorder(willEnterBackground: status)
|
||||
}
|
||||
}
|
||||
|
||||
extension FloatingPoint {
|
||||
var degreesToRadians: Self { return self * .pi / 180 }
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
//
|
||||
// UIImage+VideoBuffer.swift
|
||||
// AR Video
|
||||
//
|
||||
// Created by Ahmed Bekhit on 10/18/17.
|
||||
// Copyright © 2017 Ahmed Fathi Bekhit. All rights reserved.
|
||||
//
|
||||
|
||||
import CoreVideo
|
||||
import UIKit
|
||||
internal extension UIImage
|
||||
{
|
||||
internal func rotate(by degrees: CGFloat, flip:Bool?=nil) -> UIImage
|
||||
{
|
||||
let radians = CGFloat(degrees * (CGFloat.pi / 180.0))
|
||||
|
||||
let bufferView = UIView(frame: CGRect(origin: CGPoint.zero, size: self.size))
|
||||
let t: CGAffineTransform = CGAffineTransform(rotationAngle: radians)
|
||||
bufferView.transform = t
|
||||
let bufferSize = bufferView.frame.size
|
||||
|
||||
UIGraphicsBeginImageContextWithOptions(bufferSize, false, self.scale)
|
||||
let bitmap = UIGraphicsGetCurrentContext()
|
||||
bitmap?.translateBy(x: bufferSize.width / 2, y: bufferSize.height / 2)
|
||||
bitmap?.rotate(by: radians)
|
||||
if let isFlipped = flip {
|
||||
if !isFlipped {
|
||||
bitmap?.scaleBy(x: 1.0, y: -1.0)
|
||||
}else{
|
||||
bitmap?.scaleBy(x: -1.0, y: -1.0)
|
||||
}
|
||||
}else{
|
||||
bitmap?.scaleBy(x: -1.0, y: -1.0)
|
||||
}
|
||||
bitmap?.draw(self.cgImage!, in: CGRect(origin: CGPoint(x: -self.size.width / 2, y: -self.size.height / 2), size: self.size))
|
||||
|
||||
let finalBuffer = UIGraphicsGetImageFromCurrentImageContext()
|
||||
UIGraphicsEndImageContext()
|
||||
return finalBuffer!
|
||||
}
|
||||
|
||||
var buffer: CVPixelBuffer? {
|
||||
let attrs = [kCVPixelBufferCGImageCompatibilityKey: kCFBooleanTrue, kCVPixelBufferCGBitmapContextCompatibilityKey: kCFBooleanTrue] as CFDictionary
|
||||
var pixelBuffer : CVPixelBuffer?
|
||||
let status = CVPixelBufferCreate(kCFAllocatorDefault, Int(self.size.width), Int(self.size.height), kCVPixelFormatType_32ARGB, attrs, &pixelBuffer)
|
||||
guard (status == kCVReturnSuccess) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
CVPixelBufferLockBaseAddress(pixelBuffer!, CVPixelBufferLockFlags(rawValue: 0))
|
||||
let pixelData = CVPixelBufferGetBaseAddress(pixelBuffer!)
|
||||
|
||||
let rgbColorSpace = CGColorSpaceCreateDeviceRGB()
|
||||
let context = CGContext(data: pixelData, width: Int(self.size.width), height: Int(self.size.height), bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(pixelBuffer!), space: rgbColorSpace, bitmapInfo: CGImageAlphaInfo.noneSkipFirst.rawValue)
|
||||
|
||||
context?.translateBy(x: 0, y: self.size.height)
|
||||
context?.scaleBy(x: 1.0, y: -1.0)
|
||||
|
||||
UIGraphicsPushContext(context!)
|
||||
self.draw(in: CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height))
|
||||
UIGraphicsPopContext()
|
||||
CVPixelBufferUnlockBaseAddress(pixelBuffer!, CVPixelBufferLockFlags(rawValue: 0))
|
||||
|
||||
return pixelBuffer
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
//
|
||||
// UIView+isType.swift
|
||||
// AR Video
|
||||
//
|
||||
// Created by Ahmed Bekhit on 10/18/17.
|
||||
// Copyright © 2017 Ahmed Fathi Bekhit. All rights reserved.
|
||||
//
|
||||
|
||||
import UIKit
|
||||
import ARKit
|
||||
@available(iOS 11.0, *)
|
||||
internal extension UIScreen {
|
||||
/**
|
||||
`isiPhone10` is a boolean that returns if the device is iPhone X or not.
|
||||
*/
|
||||
internal var isiPhone10: Bool {
|
||||
return self.nativeBounds.size == CGSize(width: 1125, height: 2436) || self.nativeBounds.size == CGSize(width: 2436, height: 1125)
|
||||
}
|
||||
}
|
||||
@available(iOS 11.0, *)
|
||||
internal extension UIView {
|
||||
var parent: UIViewController? {
|
||||
var responder: UIResponder? = self
|
||||
while responder != nil {
|
||||
responder = responder!.next
|
||||
if let viewController = responder as? UIViewController {
|
||||
return viewController
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var isButton: Bool {
|
||||
if let _ = self as? UIButton {
|
||||
return true
|
||||
}else{
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
var isARView: Bool {
|
||||
if let _ = self as? ARSCNView {
|
||||
return true
|
||||
}else if let _ = self as? ARSKView {
|
||||
return true
|
||||
}else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
//
|
||||
// UIViewController+hasType.swift
|
||||
// AR Video
|
||||
//
|
||||
// Created by Ahmed Bekhit on 10/18/17.
|
||||
// Copyright © 2017 Ahmed Fathi Bekhit. All rights reserved.
|
||||
//
|
||||
|
||||
import UIKit
|
||||
import ARKit
|
||||
@available(iOS 11.0, *)
|
||||
internal extension UIViewController {
|
||||
internal var hasARView: Bool {
|
||||
let views = self.view.subviews
|
||||
for v in views {
|
||||
if let _ = v as? ARSCNView {
|
||||
return true
|
||||
}else if let _ = v as? ARSKView {
|
||||
return true
|
||||
}else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
//
|
||||
// RecordARDelegate.swift
|
||||
// AR Video
|
||||
//
|
||||
// Created by Ahmed Bekhit on 10/18/17.
|
||||
// Copyright © 2017 Ahmed Fathi Bekhit. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import CoreVideo
|
||||
import CoreMedia
|
||||
import ARKit
|
||||
/**
|
||||
The recorder protocol.
|
||||
|
||||
- Author: Ahmed Fathi Bekhit
|
||||
* [Github](http://github.com/AFathi)
|
||||
* [Website](http://ahmedbekhit.com)
|
||||
* [Twitter](http://twitter.com/iAFapps)
|
||||
* [Email](mailto:me@ahmedbekhit.com)
|
||||
*/
|
||||
@available(iOS 11.0, *)
|
||||
@objc public protocol RecordARDelegate {
|
||||
/**
|
||||
A protocol method that is triggered when a recorder ends recording.
|
||||
- parameter path: A `URL` object that returns the video file path.
|
||||
- parameter noError: A boolean that returns true when the recorder ends without errors. Otherwise, it returns false.
|
||||
*/
|
||||
func recorder(didEndRecording path:URL, with noError:Bool)
|
||||
/**
|
||||
A protocol method that is triggered when a recorder fails recording.
|
||||
- parameter error: An `Error` object that returns the error value.
|
||||
- parameter status: A string that returns the reason of the recorder failure in a string literal format.
|
||||
*/
|
||||
func recorder(didFailRecording error:Error?, and status:String)
|
||||
|
||||
/**
|
||||
A protocol method that is triggered when the application will resign active.
|
||||
- parameter status: A `RecordARStatus` object that returns the AR recorder current status.
|
||||
|
||||
|
||||
- NOTE: Check [applicationWillResignActive(_:)](https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622950-applicationwillresignactive) for more information.
|
||||
*/
|
||||
@objc func recorder(willEnterBackground status:RecordARStatus)
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
//
|
||||
// RenderARDelegate.swift
|
||||
// AR Video
|
||||
//
|
||||
// Created by Ahmed Bekhit on 10/21/17.
|
||||
// Copyright © 2017 Ahmed Fathi Bekhit. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import CoreVideo
|
||||
import CoreMedia
|
||||
import ARKit
|
||||
|
||||
/**
|
||||
The renderer protocol.
|
||||
|
||||
- Author: Ahmed Fathi Bekhit
|
||||
* [Github](http://github.com/AFathi)
|
||||
* [Website](http://ahmedbekhit.com)
|
||||
* [Twitter](http://twitter.com/iAFapps)
|
||||
* [Email](mailto:me@ahmedbekhit.com)
|
||||
*/
|
||||
@available(iOS 11.0, *)
|
||||
@objc public protocol RenderARDelegate {
|
||||
/**
|
||||
A protocol method that is triggered when a frame renders the `ARSCNView` or `ARSKView` content with the device's camera stream.
|
||||
- parameter buffer: A `CVPixelBuffer` object that returns the rendered buffer.
|
||||
- parameter time: A `CMTime` object that returns the time a buffer was rendered with.
|
||||
- parameter rawBuffer: A `CVPixelBuffer` object that returns the raw buffer.
|
||||
*/
|
||||
func frame(didRender buffer:CVPixelBuffer, with time:CMTime, using rawBuffer:CVPixelBuffer)
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
//
|
||||
// Generate+GIF.swift
|
||||
// AR Video
|
||||
//
|
||||
// Created by Ahmed Bekhit on 10/27/17.
|
||||
// Copyright © 2017 Ahmed Fathi Bekhit. All rights reserved.
|
||||
//
|
||||
|
||||
import UIKit
|
||||
import AVFoundation
|
||||
import ImageIO
|
||||
import MobileCoreServices
|
||||
|
||||
internal class GIFGenerator {
|
||||
internal let gifQueue = DispatchQueue(label:"com.ahmedbekhit.GIFQueue", attributes: .concurrent)
|
||||
fileprivate var currentGIFPath:URL?
|
||||
fileprivate var newGIFPath:URL {
|
||||
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
|
||||
let documentsDirectory = paths[0]
|
||||
|
||||
let formatter = DateFormatter()
|
||||
formatter.dateStyle = .full
|
||||
formatter.timeStyle = .full
|
||||
formatter.dateFormat = "yyyy-MM-dd'@'HH-mm-ssZZZZ"
|
||||
|
||||
let date = Date(timeIntervalSince1970: Date().timeIntervalSince1970)
|
||||
|
||||
let gifPath = "\(documentsDirectory)/\(formatter.string(from: date))AR.gif"
|
||||
return URL(fileURLWithPath: gifPath, isDirectory: false)
|
||||
}
|
||||
|
||||
internal func generate(gif images:[UIImage], with delay:Float, loop count:Int = 0, adjust:Bool, _ finished: ((_ status: Bool, _ path: URL?) -> Void)? = nil) {
|
||||
currentGIFPath = newGIFPath
|
||||
gifQueue.async {
|
||||
let gifSettings = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: count]]
|
||||
let imageSettings = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFDelayTime as String: delay]]
|
||||
|
||||
guard let path = self.currentGIFPath else{return}
|
||||
guard let destination = CGImageDestinationCreateWithURL(path as CFURL, kUTTypeGIF, images.count, nil) else{finished?(false, nil);return}
|
||||
logAR.message("\(destination)")
|
||||
CGImageDestinationSetProperties(destination, gifSettings as CFDictionary)
|
||||
for image in images {
|
||||
if let imageRef = image.cgImage {
|
||||
var ratio:Float = 0.0
|
||||
if adjust{ratio=0.5}else{ratio=1.0}
|
||||
CGImageDestinationAddImage(destination, imageRef.resize(with: ratio)!, imageSettings as CFDictionary)
|
||||
}
|
||||
}
|
||||
|
||||
if !CGImageDestinationFinalize(destination){
|
||||
finished?(false, nil);
|
||||
return
|
||||
}else{
|
||||
finished?(true, path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,105 +0,0 @@
|
||||
//
|
||||
// Generate+LivePhoto.swift
|
||||
// AR Video
|
||||
//
|
||||
// Created by Ahmed Bekhit on 10/28/17.
|
||||
// Copyright © 2017 Ahmed Fathi Bekhit. All rights reserved.
|
||||
//
|
||||
|
||||
import AVFoundation
|
||||
import Photos
|
||||
@available(iOS 11.0, *)
|
||||
internal class LivePhotoGenerator {
|
||||
fileprivate var keyPhotoPath:URL?
|
||||
|
||||
fileprivate var finalKeyPhotoPath:URL?
|
||||
fileprivate var finalPairedVideoPath:URL?
|
||||
|
||||
internal let livePhotoQueue = DispatchQueue(label:"com.ahmedbekhit.livePhotoQueue", attributes: .concurrent)
|
||||
|
||||
internal func generate(livePhoto video:URL?, _ finished: ((_ status: Bool, _ photo: PHLivePhotoPlus?, _ pairedVideoPath:URL?, _ keyFramePath:URL?) -> Void)? = nil) {
|
||||
livePhotoQueue.async {
|
||||
guard let liveFrames = video else{finished?(false, nil, nil, nil); return}
|
||||
let asset = AVURLAsset(url: video!)
|
||||
let generator = AVAssetImageGenerator(asset: asset)
|
||||
generator.appliesPreferredTrackTransform = true
|
||||
|
||||
//retrieves the key photo frame from the middle of the video asset
|
||||
let time = NSValue(time: CMTimeMultiplyByFloat64(asset.duration, 0.5))
|
||||
|
||||
//generates the key photo CGImage asynchronously
|
||||
generator.generateCGImagesAsynchronously(forTimes: [time], completionHandler:{_,image,_,_,_ in
|
||||
if let cgImg = image, let imgData = UIImagePNGRepresentation(UIImage(cgImage: cgImg)) {
|
||||
do {
|
||||
self.keyPhotoPath = self.newPath(for: true, and: false)
|
||||
try imgData.write(to: self.keyPhotoPath!, options: [.atomic])
|
||||
}catch let error {
|
||||
self.keyPhotoPath = nil
|
||||
logAR.message("An error occurred while capturing a live photo: \(error)")
|
||||
finished?(false, nil, nil, nil)
|
||||
return
|
||||
}
|
||||
self.finalKeyPhotoPath = self.newPath(for: true, and: true)
|
||||
self.finalPairedVideoPath = self.newPath(for: false, and: true)
|
||||
|
||||
guard let keyFrame = self.keyPhotoPath else{finished?(false, nil, nil, nil); return}
|
||||
guard let keyLiveFrame = self.finalKeyPhotoPath else{finished?(false, nil, nil, nil); return}
|
||||
guard let keyLiveFrames = self.finalPairedVideoPath else{finished?(false, nil, nil, nil); return}
|
||||
|
||||
let assetIdentifier = UUID().uuidString
|
||||
|
||||
JPEG(path: keyFrame.path).write(keyLiveFrame.path, assetIdentifier: assetIdentifier)
|
||||
QuickTimeMov(path: liveFrames.path).write(keyLiveFrames.path, assetIdentifier: assetIdentifier)
|
||||
|
||||
|
||||
PHLivePhoto.request(withResourceFileURLs: [keyLiveFrames, keyLiveFrame], placeholderImage: UIImage(cgImage: cgImg), targetSize: .zero, contentMode: .aspectFit) { photo, settings in
|
||||
logAR.remove(from: keyFrame)
|
||||
logAR.remove(from: liveFrames)
|
||||
if let livePhoto = photo {
|
||||
let finalPhoto = PHLivePhotoPlus(photo: livePhoto)
|
||||
finalPhoto.keyPhotoPath = keyLiveFrame
|
||||
finalPhoto.pairedVideoPath = keyLiveFrames
|
||||
finished?(true, finalPhoto, finalPhoto.pairedVideoPath, finalPhoto.keyPhotoPath)
|
||||
return
|
||||
}else{
|
||||
let finalPhoto = PHLivePhotoPlus(photo: photo!)
|
||||
finalPhoto.keyPhotoPath = keyLiveFrame
|
||||
finalPhoto.pairedVideoPath = keyLiveFrames
|
||||
finished?(false, finalPhoto, finalPhoto.pairedVideoPath, finalPhoto.keyPhotoPath)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func newPath(for JPEG:Bool, and live:Bool) -> URL {
|
||||
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
|
||||
let documentsDirectory = paths[0]
|
||||
|
||||
let livePhotosFolder = "\(documentsDirectory)/livePhotos"
|
||||
|
||||
let formatter = DateFormatter()
|
||||
formatter.dateStyle = .full
|
||||
formatter.timeStyle = .full
|
||||
formatter.dateFormat = "yyyy-MM-dd'@'HH-mm-ssZZZZ"
|
||||
|
||||
let date = Date(timeIntervalSince1970: Date().timeIntervalSince1970)
|
||||
|
||||
do {
|
||||
try FileManager.default.createDirectory(atPath: livePhotosFolder, withIntermediateDirectories: true, attributes: nil)
|
||||
}catch let error {
|
||||
logAR.message("An error occurred while rendering the live photo: \(error)")
|
||||
return URL(fileURLWithPath: "\(documentsDirectory)/\(formatter.string(from: date))AR.jpg", isDirectory: false)
|
||||
}
|
||||
|
||||
if JPEG && live {
|
||||
return URL(fileURLWithPath: "\(livePhotosFolder)/\(formatter.string(from: date))AR.jpg", isDirectory: false)
|
||||
}else if JPEG && !live {
|
||||
return URL(fileURLWithPath: "\(documentsDirectory)/\(formatter.string(from: date))AR.jpg", isDirectory: false)
|
||||
}else{
|
||||
return URL(fileURLWithPath: "\(livePhotosFolder)/\(formatter.string(from: date))AR.mov", isDirectory: false)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
//
|
||||
// JPEG.swift
|
||||
// LoveLiver
|
||||
//
|
||||
// Created by mzp on 10/10/15.
|
||||
// Copyright © 2015 mzp. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import MobileCoreServices
|
||||
import ImageIO
|
||||
|
||||
internal class JPEG {
|
||||
fileprivate let kFigAppleMakerNote_AssetIdentifier = "17"
|
||||
fileprivate let path : String
|
||||
|
||||
init(path : String) {
|
||||
self.path = path
|
||||
}
|
||||
|
||||
func read() -> String? {
|
||||
guard let makerNote = metadata()?.object(forKey: kCGImagePropertyMakerAppleDictionary) as! NSDictionary? else {
|
||||
return nil
|
||||
}
|
||||
return makerNote.object(forKey: kFigAppleMakerNote_AssetIdentifier) as! String?
|
||||
}
|
||||
|
||||
func write(_ dest : String, assetIdentifier : String) {
|
||||
guard let dest = CGImageDestinationCreateWithURL(URL(fileURLWithPath: dest) as CFURL, kUTTypeJPEG, 1, nil)
|
||||
else { return }
|
||||
defer { CGImageDestinationFinalize(dest) }
|
||||
guard let imageSource = self.imageSource() else { return }
|
||||
guard let metadata = self.metadata()?.mutableCopy() as? NSMutableDictionary else { return }
|
||||
|
||||
let makerNote = NSMutableDictionary()
|
||||
makerNote.setObject(assetIdentifier, forKey: kFigAppleMakerNote_AssetIdentifier as NSCopying)
|
||||
metadata.setObject(makerNote, forKey: kCGImagePropertyMakerAppleDictionary as String as String as NSCopying)
|
||||
CGImageDestinationAddImageFromSource(dest, imageSource, 0, metadata)
|
||||
}
|
||||
|
||||
fileprivate func metadata() -> NSDictionary? {
|
||||
return self.imageSource().flatMap {
|
||||
CGImageSourceCopyPropertiesAtIndex($0, 0, nil) as NSDictionary?
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate func imageSource() -> CGImageSource? {
|
||||
return self.data().flatMap {
|
||||
CGImageSourceCreateWithData($0 as CFData, nil)
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate func data() -> Data? {
|
||||
return (try? Data(contentsOf: URL(fileURLWithPath: path)))
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
The MIT License
|
||||
|
||||
Copyright (c) 2015 mzp.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
@@ -1,39 +0,0 @@
|
||||
//
|
||||
// PHLivePhotoPlus.swift
|
||||
// AR Video
|
||||
//
|
||||
// Created by Ahmed Bekhit on 10/30/17.
|
||||
// Copyright © 2017 Ahmed Fathi Bekhit. All rights reserved.
|
||||
//
|
||||
|
||||
import Photos
|
||||
/**
|
||||
A `PHLivePhotoPlus` object is a `PHLivePhoto` sub-class that contains objects to allow manual exporting of a live photo.
|
||||
|
||||
- Author: Ahmed Fathi Bekhit
|
||||
* [Github](http://github.com/AFathi)
|
||||
* [Website](http://ahmedbekhit.com)
|
||||
* [Twitter](http://twitter.com/iAFapps)
|
||||
* [Email](mailto:me@ahmedbekhit.com)
|
||||
*/
|
||||
@available(iOS 9.1, *)
|
||||
@objc public class PHLivePhotoPlus: PHLivePhoto {
|
||||
internal var pairedVideoPath:URL?
|
||||
internal var keyPhotoPath:URL?
|
||||
|
||||
/// A `PHLivePhoto` object that returns the Live Photo content from `PHLivePhotoPlus`.
|
||||
@objc public var livePhoto:PHLivePhoto?
|
||||
|
||||
@objc public override init() {
|
||||
super.init()
|
||||
}
|
||||
|
||||
@objc public init(photo:PHLivePhoto) {
|
||||
super.init()
|
||||
livePhoto = photo
|
||||
}
|
||||
|
||||
@objc required public init?(coder aDecoder: NSCoder) {
|
||||
fatalError("init(coder:) has not been implemented")
|
||||
}
|
||||
}
|
||||
@@ -1,119 +0,0 @@
|
||||
//
|
||||
// RenderAR.swift
|
||||
// ARVideoKit
|
||||
//
|
||||
// Created by Ahmed Bekhit on 1/7/18.
|
||||
// Copyright © 2018 Ahmed Fathit Bekhit. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import ARKit
|
||||
fileprivate var view:Any?
|
||||
fileprivate var renderEngine:SCNRenderer!
|
||||
@available(iOS 11.0, *)
|
||||
internal struct RenderAR {
|
||||
internal var ARcontentMode:ARFrameMode!
|
||||
init(_ ARview:Any?, renderer:SCNRenderer, contentMode:ARFrameMode) {
|
||||
view = ARview
|
||||
renderEngine = renderer
|
||||
ARcontentMode = contentMode
|
||||
}
|
||||
internal let pixelsQueue = DispatchQueue(label:"com.ahmedbekhit.PixelsQueue", attributes: .concurrent)
|
||||
internal var time:CFTimeInterval {return CACurrentMediaTime()}
|
||||
internal var rawBuffer:CVPixelBuffer? {
|
||||
if let view = view as? ARSCNView {
|
||||
guard let rawBuffer = view.session.currentFrame?.capturedImage else{return nil}
|
||||
return rawBuffer
|
||||
}else if let view = view as? ARSKView {
|
||||
guard let rawBuffer = view.session.currentFrame?.capturedImage else{return nil}
|
||||
return rawBuffer
|
||||
}else if let _ = view as? SCNView {
|
||||
return buffer
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
internal var bufferSize:CGSize? {
|
||||
guard let raw = rawBuffer else{return nil};
|
||||
var width = CVPixelBufferGetWidth(raw);
|
||||
var height = CVPixelBufferGetHeight(raw);
|
||||
|
||||
switch ARcontentMode {
|
||||
case .auto:
|
||||
if UIScreen.main.isiPhone10 {
|
||||
width = Int(UIScreen.main.nativeBounds.width)
|
||||
height = Int(UIScreen.main.nativeBounds.height)
|
||||
}
|
||||
case .aspectFit:
|
||||
width = CVPixelBufferGetWidth(raw);
|
||||
height = CVPixelBufferGetHeight(raw);
|
||||
case .aspectFill:
|
||||
width = Int(UIScreen.main.nativeBounds.width)
|
||||
height = Int(UIScreen.main.nativeBounds.height)
|
||||
default:
|
||||
if UIScreen.main.isiPhone10 {
|
||||
width = Int(UIScreen.main.nativeBounds.width)
|
||||
height = Int(UIScreen.main.nativeBounds.height)
|
||||
}
|
||||
}
|
||||
|
||||
if width > height {
|
||||
return CGSize(width: height, height: width)
|
||||
}else{
|
||||
return CGSize(width: width, height: height)
|
||||
}
|
||||
}
|
||||
|
||||
internal var bufferSizeFill:CGSize? {
|
||||
guard let raw = rawBuffer else{return nil};
|
||||
let width = CVPixelBufferGetWidth(raw);
|
||||
let height = CVPixelBufferGetHeight(raw);
|
||||
if width > height {
|
||||
return CGSize(width: height, height: width)
|
||||
}else{
|
||||
return CGSize(width: width, height: height)
|
||||
}
|
||||
}
|
||||
|
||||
internal var buffer:CVPixelBuffer? {
|
||||
if let _ = view as? ARSCNView {
|
||||
guard let size = bufferSize else{return nil};
|
||||
//UIScreen.main.bounds.size
|
||||
var renderedFrame:UIImage?
|
||||
pixelsQueue.sync {
|
||||
renderedFrame = renderEngine.snapshot(atTime: self.time, with: size, antialiasingMode: .none);
|
||||
}
|
||||
if let _ = renderedFrame {
|
||||
}else{
|
||||
renderedFrame = renderEngine.snapshot(atTime: time, with: size, antialiasingMode: .none);
|
||||
}
|
||||
guard let buffer = renderedFrame!.buffer else{return nil};
|
||||
return buffer;
|
||||
}else if let _ = view as? ARSKView {
|
||||
guard let size = bufferSize else{return nil};
|
||||
var renderedFrame:UIImage?
|
||||
pixelsQueue.sync {
|
||||
renderedFrame = renderEngine.snapshot(atTime: self.time, with: size, antialiasingMode: .none).rotate(by: 180);
|
||||
}
|
||||
if let _ = renderedFrame {
|
||||
}else{
|
||||
renderedFrame = renderEngine.snapshot(atTime: time, with: size, antialiasingMode: .none).rotate(by: 180);
|
||||
}
|
||||
guard let buffer = renderedFrame!.buffer else{return nil};
|
||||
return buffer;
|
||||
}else if let _ = view as? SCNView {
|
||||
let size = UIScreen.main.bounds.size
|
||||
var renderedFrame:UIImage?
|
||||
pixelsQueue.sync {
|
||||
renderedFrame = renderEngine.snapshot(atTime: self.time, with: size, antialiasingMode: .none);
|
||||
}
|
||||
if let _ = renderedFrame {
|
||||
}else{
|
||||
renderedFrame = renderEngine.snapshot(atTime: time, with: size, antialiasingMode: .none);
|
||||
}
|
||||
guard let buffer = renderedFrame!.buffer else{return nil};
|
||||
return buffer;
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
}
|
||||
@@ -1,266 +0,0 @@
|
||||
//
|
||||
// WritAR.swift
|
||||
// AR Video
|
||||
//
|
||||
// Created by Ahmed Bekhit on 10/19/17.
|
||||
// Copyright © 2017 Ahmed Fathi Bekhit. All rights reserved.
|
||||
//
|
||||
|
||||
import AVFoundation
|
||||
import CoreImage
|
||||
import UIKit
|
||||
@available(iOS 11.0, *)
|
||||
internal class WritAR:NSObject, AVCaptureAudioDataOutputSampleBufferDelegate {
|
||||
fileprivate var assetWriter: AVAssetWriter!
|
||||
fileprivate var videoInput: AVAssetWriterInput!
|
||||
fileprivate var audioInput: AVAssetWriterInput!
|
||||
fileprivate var session: AVCaptureSession!
|
||||
|
||||
fileprivate var pixelBufferInput: AVAssetWriterInputPixelBufferAdaptor!
|
||||
fileprivate var videoOutputSettings: Dictionary<String, AnyObject>!
|
||||
fileprivate var audioSettings: [String : Any]?
|
||||
|
||||
internal let audioBufferQueue = DispatchQueue(label: "com.ahmedbekhit.AudioBufferQueue")
|
||||
|
||||
fileprivate var isRecording:Bool = false
|
||||
|
||||
internal var delegate:RecordARDelegate?
|
||||
internal var videoInputOrientation:ARVideoOrientation = .auto
|
||||
|
||||
init(output:URL, width:Int, height:Int, adjustForSharing:Bool, audioEnabled:Bool, orientaions:[ARInputViewOrientation], queue:DispatchQueue, allowMix:Bool){
|
||||
super.init()
|
||||
do {
|
||||
assetWriter = try AVAssetWriter(outputURL: output, fileType: AVFileType.mp4)
|
||||
}catch{
|
||||
return
|
||||
}
|
||||
if audioEnabled {
|
||||
if allowMix {
|
||||
do {
|
||||
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord, with: [AVAudioSessionCategoryOptions.mixWithOthers , AVAudioSessionCategoryOptions.allowBluetooth, AVAudioSessionCategoryOptions.defaultToSpeaker, AVAudioSessionCategoryOptions.interruptSpokenAudioAndMixWithOthers])
|
||||
try AVAudioSession.sharedInstance().setActive(true)
|
||||
}catch{}
|
||||
}
|
||||
AVAudioSession.sharedInstance().requestRecordPermission({ permitted in
|
||||
if permitted {
|
||||
self.prepareAudioDevice(with: queue)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
//HEVC file format only supports A10 Fusion Chip or higher.
|
||||
//to support HEVC, make sure to check if the device is iPhone 7 or higher
|
||||
videoOutputSettings = [
|
||||
AVVideoCodecKey : AVVideoCodecType.h264 as AnyObject,
|
||||
AVVideoWidthKey : width as AnyObject,
|
||||
AVVideoHeightKey : height as AnyObject
|
||||
]
|
||||
|
||||
let attributes : [String:Bool] = [
|
||||
kCVPixelBufferCGImageCompatibilityKey as String : true,
|
||||
kCVPixelBufferCGBitmapContextCompatibilityKey as String : true
|
||||
]
|
||||
videoInput = AVAssetWriterInput(mediaType: .video, outputSettings: videoOutputSettings)
|
||||
|
||||
videoInput.expectsMediaDataInRealTime = true
|
||||
pixelBufferInput = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: videoInput, sourcePixelBufferAttributes: attributes)
|
||||
|
||||
var angleEnabled: Bool {
|
||||
for v in orientaions {
|
||||
if UIDevice.current.orientation.rawValue == v.rawValue {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
var recentAngle:CGFloat = 0
|
||||
var rotationAngle:CGFloat = 0
|
||||
switch UIDevice.current.orientation {
|
||||
case .landscapeLeft:
|
||||
rotationAngle = -90
|
||||
recentAngle = -90
|
||||
case .landscapeRight:
|
||||
rotationAngle = 90
|
||||
recentAngle = 90
|
||||
case .faceUp, .faceDown, .portraitUpsideDown:
|
||||
rotationAngle = recentAngle
|
||||
default:
|
||||
rotationAngle = 0
|
||||
recentAngle = 0
|
||||
}
|
||||
|
||||
if !angleEnabled {
|
||||
rotationAngle = 0
|
||||
}
|
||||
|
||||
var t = CGAffineTransform.identity
|
||||
|
||||
switch videoInputOrientation {
|
||||
case .auto:
|
||||
t = t.rotated(by:((rotationAngle*CGFloat.pi)/180))
|
||||
case .alwaysPortrait:
|
||||
t = t.rotated(by:0)
|
||||
case .alwaysLandscape:
|
||||
if rotationAngle == 90 || rotationAngle == -90 {
|
||||
t = t.rotated(by:((rotationAngle*CGFloat.pi)/180))
|
||||
}else{
|
||||
t = t.rotated(by:((-90*CGFloat.pi)/180))
|
||||
}
|
||||
}
|
||||
|
||||
videoInput.transform = t
|
||||
|
||||
if assetWriter.canAdd(videoInput) {
|
||||
assetWriter.add(videoInput)
|
||||
}else{
|
||||
delegate?.recorder(didFailRecording: assetWriter.error, and: "An error occurred while adding video input.")
|
||||
isWritingWithoutError = false
|
||||
}
|
||||
assetWriter.shouldOptimizeForNetworkUse = adjustForSharing
|
||||
}
|
||||
|
||||
internal func prepareAudioDevice(with queue:DispatchQueue) {
|
||||
let device: AVCaptureDevice = AVCaptureDevice.default(for: .audio)!
|
||||
var audioDeviceInput:AVCaptureDeviceInput?
|
||||
do {
|
||||
audioDeviceInput = try AVCaptureDeviceInput(device: device)
|
||||
}catch{
|
||||
audioDeviceInput = nil
|
||||
}
|
||||
|
||||
let audioDataOutput = AVCaptureAudioDataOutput()
|
||||
audioDataOutput.setSampleBufferDelegate(self, queue: queue)
|
||||
|
||||
session = AVCaptureSession()
|
||||
session.sessionPreset = .medium
|
||||
session.usesApplicationAudioSession = true
|
||||
session.automaticallyConfiguresApplicationAudioSession = false
|
||||
|
||||
if session.canAddInput(audioDeviceInput!) {
|
||||
session.addInput(audioDeviceInput!)
|
||||
}
|
||||
if session.canAddOutput(audioDataOutput) {
|
||||
session.addOutput(audioDataOutput)
|
||||
}
|
||||
|
||||
|
||||
audioSettings = audioDataOutput.recommendedAudioSettingsForAssetWriter(writingTo: .m4v) as? [String : Any]
|
||||
|
||||
audioInput = AVAssetWriterInput(mediaType: .audio, outputSettings: audioSettings)
|
||||
audioInput.expectsMediaDataInRealTime = true
|
||||
|
||||
audioBufferQueue.async {
|
||||
self.session.startRunning()
|
||||
}
|
||||
|
||||
if assetWriter.canAdd(audioInput) {
|
||||
assetWriter.add(audioInput)
|
||||
}
|
||||
}
|
||||
|
||||
internal var startingVideoTime:CMTime?
|
||||
internal var isWritingWithoutError: Bool?
|
||||
|
||||
internal func insert(pixel buffer:CVPixelBuffer, with intervals:CFTimeInterval) {
|
||||
var time:CMTime {return CMTimeMakeWithSeconds(intervals, 1000000);}
|
||||
if assetWriter.status == .unknown {
|
||||
if let _ = startingVideoTime {isWritingWithoutError = false; return}else{startingVideoTime = time}
|
||||
if assetWriter.startWriting() {
|
||||
assetWriter.startSession(atSourceTime: startingVideoTime!)
|
||||
session.startRunning()
|
||||
isRecording = true
|
||||
isWritingWithoutError = true
|
||||
}else{
|
||||
delegate?.recorder(didFailRecording: assetWriter.error, and: "An error occurred while starting the video session.")
|
||||
isWritingWithoutError = false
|
||||
}
|
||||
}else if assetWriter.status == .failed {
|
||||
delegate?.recorder(didFailRecording: assetWriter.error, and: "Video session failed while recording.")
|
||||
logAR.message("An error occurred while recording the video, status: \(assetWriter.status.rawValue), error: \(assetWriter.error!.localizedDescription)")
|
||||
isWritingWithoutError = false
|
||||
return
|
||||
}
|
||||
if videoInput.isReadyForMoreMediaData {
|
||||
append(pixel: buffer, with: time)
|
||||
isWritingWithoutError = true
|
||||
}
|
||||
}
|
||||
|
||||
internal func insert(pixel buffer:CVPixelBuffer, with time:CMTime) {
|
||||
if assetWriter.status == .unknown {
|
||||
if let _ = startingVideoTime {isWritingWithoutError = false; return}else{startingVideoTime = time}
|
||||
if assetWriter.startWriting() {
|
||||
assetWriter.startSession(atSourceTime: startingVideoTime!)
|
||||
isRecording = true
|
||||
isWritingWithoutError = true
|
||||
}else{
|
||||
delegate?.recorder(didFailRecording: assetWriter.error, and: "An error occurred while starting the video session.")
|
||||
isRecording = false
|
||||
isWritingWithoutError = false
|
||||
}
|
||||
}else if assetWriter.status == .failed {
|
||||
delegate?.recorder(didFailRecording: assetWriter.error, and: "Video session failed while recording.")
|
||||
logAR.message("An error occurred while recording the video, status: \(assetWriter.status.rawValue), error: \(assetWriter.error!.localizedDescription)")
|
||||
isRecording = false
|
||||
isWritingWithoutError = false
|
||||
return
|
||||
}
|
||||
|
||||
if videoInput.isReadyForMoreMediaData {
|
||||
append(pixel: buffer, with: time)
|
||||
isRecording = true
|
||||
isWritingWithoutError = true
|
||||
}
|
||||
}
|
||||
|
||||
func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
|
||||
if let input = audioInput {
|
||||
audioBufferQueue.async { [weak self] in
|
||||
if input.isReadyForMoreMediaData && (self?.isRecording)! {
|
||||
input.append(sampleBuffer)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func pause() {
|
||||
isRecording = false
|
||||
}
|
||||
func end(writing finished: @escaping () -> Void){
|
||||
if let session = session {
|
||||
if session.isRunning {
|
||||
session.stopRunning()
|
||||
}
|
||||
}
|
||||
assetWriter.finishWriting(completionHandler: finished)
|
||||
}
|
||||
}
|
||||
@available(iOS 11.0, *)
|
||||
fileprivate extension WritAR {
|
||||
func append(pixel buffer:CVPixelBuffer, with time: CMTime) {
|
||||
pixelBufferInput.append(buffer, withPresentationTime: time)
|
||||
}
|
||||
}
|
||||
|
||||
//Simple Logging to show logs only while debugging.
|
||||
internal class logAR{
|
||||
internal class func message(_ message: String) {
|
||||
#if DEBUG
|
||||
print("ARVideoKit @ \(Date().timeIntervalSince1970):- \(message)")
|
||||
#endif
|
||||
}
|
||||
internal class func remove(from path: URL?) {
|
||||
if let file = path?.path {
|
||||
let manager = FileManager.default
|
||||
if manager.fileExists(atPath: file) {
|
||||
do{
|
||||
try manager.removeItem(atPath: file)
|
||||
self.message("Successfuly deleted media file from cached after exporting to Camera Roll.")
|
||||
} catch let error {
|
||||
self.message("An error occurred while deleting cached media: \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,149 +0,0 @@
|
||||
//
|
||||
// ARView.swift
|
||||
// ARVideoKit
|
||||
//
|
||||
// Created by Ahmed Bekhit on 10/14/17.
|
||||
// Copyright © 2017 Ahmed Fathi Bekhit. All rights reserved.
|
||||
//
|
||||
|
||||
import UIKit
|
||||
import ARKit
|
||||
|
||||
fileprivate var parentVC:UIViewController?
|
||||
fileprivate var recentAngle = 0
|
||||
|
||||
/**
|
||||
A class that configures the Augmented Reality View orientations.
|
||||
|
||||
- Author: Ahmed Fathi Bekhit
|
||||
* [Github](http://github.com/AFathi)
|
||||
* [Website](http://ahmedbekhit.com)
|
||||
* [Twitter](http://twitter.com/iAFapps)
|
||||
* [Email](mailto:me@ahmedbekhit.com)
|
||||
*/
|
||||
@available(iOS 11.0, *)
|
||||
@objc public class ARView: NSObject {
|
||||
fileprivate var ivo:[ARInputViewOrientation] = []
|
||||
/// An array of `ARInputViewOrientation` objects that allow customizing the accepted orientations in a `UIViewController` that contains Augmented Reality scenes.
|
||||
public var inputViewOrientations:[ARInputViewOrientation] {
|
||||
get{
|
||||
return ivo
|
||||
}
|
||||
set{
|
||||
if newValue.count == 0 {
|
||||
ivo = [.portrait]
|
||||
}else{
|
||||
ivo = newValue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate var ivom:ARInputViewOrientationMode = .auto
|
||||
/// An object that allow customizing which subviews will rotate in a `UIViewController` that contains Augmented Reality scenes.
|
||||
public var inputViewOrientationMode:ARInputViewOrientationMode {
|
||||
get{
|
||||
return ivom
|
||||
}
|
||||
set{
|
||||
ivom = newValue
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@objc init?(ARSceneKit:ARSCNView) {
|
||||
super.init()
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(deviceDidRotate), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
|
||||
|
||||
let value = UIInterfaceOrientation.portrait.rawValue
|
||||
UIDevice.current.setValue(value, forKey: "orientation")
|
||||
|
||||
ViewAR.orientation = .portrait
|
||||
|
||||
guard let vc = ARSceneKit.parent else {
|
||||
return
|
||||
}
|
||||
|
||||
parentVC = vc
|
||||
}
|
||||
|
||||
@objc init?(ARSpriteKit:ARSKView) {
|
||||
super.init()
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(deviceDidRotate), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
|
||||
|
||||
let value = UIInterfaceOrientation.portrait.rawValue
|
||||
UIDevice.current.setValue(value, forKey: "orientation")
|
||||
|
||||
ViewAR.orientation = .portrait
|
||||
guard let vc = ARSpriteKit.parent else {
|
||||
return
|
||||
}
|
||||
parentVC = vc
|
||||
}
|
||||
|
||||
@objc init?(SceneKit:SCNView) {
|
||||
super.init()
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(deviceDidRotate), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
|
||||
|
||||
let value = UIInterfaceOrientation.portrait.rawValue
|
||||
UIDevice.current.setValue(value, forKey: "orientation")
|
||||
|
||||
ViewAR.orientation = .portrait
|
||||
|
||||
guard let vc = SceneKit.parent else {
|
||||
return
|
||||
}
|
||||
|
||||
parentVC = vc
|
||||
}
|
||||
|
||||
@objc fileprivate func deviceDidRotate() {
|
||||
guard var views = parentVC?.view.subviews else {
|
||||
return
|
||||
}
|
||||
|
||||
var rotationAngle = 0
|
||||
|
||||
switch inputViewOrientationMode {
|
||||
case .auto:
|
||||
views = views.filter{!$0.isARView && $0.isButton}
|
||||
case .all:
|
||||
views = views.filter{!$0.isARView}
|
||||
case .manual(let subviews):
|
||||
views = subviews.filter{!$0.isARView}
|
||||
case .disabled:
|
||||
views = []
|
||||
}
|
||||
var angleEnabled: Bool {
|
||||
for v in inputViewOrientations {
|
||||
if UIDevice.current.orientation.rawValue == v.rawValue {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
switch UIDevice.current.orientation {
|
||||
case .landscapeLeft:
|
||||
rotationAngle = 90
|
||||
recentAngle = 90
|
||||
case .landscapeRight:
|
||||
rotationAngle = -90
|
||||
recentAngle = -90
|
||||
case .faceUp, .faceDown, .portraitUpsideDown:
|
||||
rotationAngle = recentAngle
|
||||
default:
|
||||
rotationAngle = 0
|
||||
recentAngle = 0
|
||||
}
|
||||
|
||||
if !angleEnabled {
|
||||
rotationAngle = 0
|
||||
}
|
||||
|
||||
for view in views {
|
||||
UIView.animate(withDuration: 0.2, animations: {
|
||||
view.transform = CGAffineTransform(rotationAngle: CGFloat(rotationAngle).degreesToRadians)
|
||||
})
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,786 +0,0 @@
|
||||
//
|
||||
// RecordAR.swift
|
||||
// ARVideoKit
|
||||
//
|
||||
// Created by Ahmed Bekhit on 10/18/17.
|
||||
// Copyright © 2017 Ahmed Fathi Bekhit. All rights reserved.
|
||||
//
|
||||
|
||||
import UIKit
|
||||
import Metal
|
||||
import ARKit
|
||||
import Photos
|
||||
import PhotosUI
|
||||
|
||||
fileprivate var view:Any?
|
||||
fileprivate var renderEngine:SCNRenderer!
|
||||
fileprivate var gpuLoop:CADisplayLink!
|
||||
fileprivate var isResting = false
|
||||
fileprivate var ARcontentMode:ARFrameMode!
|
||||
@available(iOS 11.0, *)
|
||||
fileprivate var renderer:RenderAR!
|
||||
/**
|
||||
This class renders the `ARSCNView` or `ARSKView` content with the device's camera stream to generate a video 📹, photo 🌄, live photo 🎇 or GIF 🎆.
|
||||
|
||||
- Author: 🤓 Ahmed Fathi Bekhit © 2017
|
||||
* [Github](http://github.com/AFathi)
|
||||
* [Website](http://ahmedbekhit.com)
|
||||
* [Twitter](http://twitter.com/iAFapps)
|
||||
* [Email](mailto:me@ahmedbekhit.com)
|
||||
*/
|
||||
@available(iOS 11.0, *)
|
||||
@objc public class RecordAR: ARView {
|
||||
//MARK: - Public objects to configure RecordAR
|
||||
/**
|
||||
An object that passes the AR recorder errors and status in the protocol methods.
|
||||
*/
|
||||
@objc public var delegate:RecordARDelegate?
|
||||
/**
|
||||
An object that passes the AR rendered content in the protocol method.
|
||||
*/
|
||||
@objc public var renderAR: RenderARDelegate?
|
||||
/**
|
||||
An object that returns the AR recorder current status.
|
||||
*/
|
||||
@objc public internal(set)var status:RecordARStatus = .unknown
|
||||
/**
|
||||
An object that returns the current Microphone status.
|
||||
*/
|
||||
@objc public internal(set)var micStatus:RecordARMicrophoneStatus = .unknown
|
||||
/**
|
||||
An object that allow customizing when to ask for Microphone permission, if needed. Default is `.auto`.
|
||||
*/
|
||||
@objc public var requestMicPermission:RecordARMicrophonePermission = .auto
|
||||
/**
|
||||
An object that allow customizing the video frame per second rate. Default is `.auto`.
|
||||
*/
|
||||
@objc public var fps:ARVideoFrameRate = .auto
|
||||
/**
|
||||
An object that allow customizing the video orientation. Default is `.auto`.
|
||||
*/
|
||||
@objc public var videoOrientation:ARVideoOrientation = .auto
|
||||
/**
|
||||
An object that allow customizing the AR content mode. Default is `.auto`.
|
||||
*/
|
||||
@objc public var contentMode:ARFrameMode = .auto
|
||||
/**
|
||||
A boolean that enables or disables AR content rendering before recording for image & video processing. Default is `true`.
|
||||
*/
|
||||
@objc public var onlyRenderWhileRecording:Bool = true
|
||||
/**
|
||||
A boolean that enables or disables audio recording. Default is `true`.
|
||||
*/
|
||||
@objc public var enableAudio:Bool = true
|
||||
/**
|
||||
A boolean that enables or disables audio `mixWithOthers` if audio recording is enabled. This allows playing music and recording audio at the same time. Default is `true`.
|
||||
*/
|
||||
@objc public var enableMixWithOthers:Bool = true
|
||||
/**
|
||||
A boolean that enables or disables adjusting captured media for sharing online. Default is `true`.
|
||||
*/
|
||||
@objc public var adjustVideoForSharing:Bool = true
|
||||
/**
|
||||
A boolean that enables or disables adjusting captured GIFs for sharing online. Default is `true`.
|
||||
*/
|
||||
@objc public var adjustGIFForSharing:Bool = true
|
||||
/**
|
||||
A boolean that enables or disables clearing cached media after exporting to Camera Roll. Default is `true`.
|
||||
*/
|
||||
@objc public var deleteCacheWhenExported:Bool = true
|
||||
/**
|
||||
A boolean that enables or disables using envronment light rendering. Default is `false`.
|
||||
*/
|
||||
@objc public var enableAdjsutEnvironmentLighting:Bool = false {
|
||||
|
||||
didSet{
|
||||
if (renderEngine != nil) {
|
||||
renderEngine.autoenablesDefaultLighting = enableAdjsutEnvironmentLighting
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//MARK: - Public initialization methods
|
||||
/**
|
||||
Initialize 🌞🍳 `RecordAR` with an `ARSCNView` 🚀.
|
||||
*/
|
||||
@objc override public init?(ARSceneKit: ARSCNView) {
|
||||
super.init(ARSceneKit: ARSceneKit)
|
||||
view = ARSceneKit
|
||||
setup()
|
||||
}
|
||||
|
||||
/**
|
||||
Initialize 🌞🍳 `RecordAR` with an `ARSKView` 👾.
|
||||
*/
|
||||
@objc override public init?(ARSpriteKit: ARSKView) {
|
||||
super.init(ARSpriteKit: ARSpriteKit)
|
||||
view = ARSpriteKit
|
||||
scnView = SCNView(frame: UIScreen.main.bounds)
|
||||
|
||||
let bundle = Bundle(for: RecordAR.self)
|
||||
let url = bundle.url(forResource: "video.scnassets/vid", withExtension: "scn")
|
||||
|
||||
do {
|
||||
let scene = try SCNScene(url: url!, options: nil)
|
||||
scnView.scene = scene
|
||||
setup()
|
||||
}catch let error {
|
||||
logAR.message("Error occurred while loading SK Video Assets : \(error). Please download \"video.scnassets\" from\nwww.ahmedbekhit.com/ARVideoKitAssets")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Initialize 🌞🍳 `RecordAR` with an `SCNView` 🚀.
|
||||
*/
|
||||
@objc override public init?(SceneKit: SCNView) {
|
||||
super.init(SceneKit: SceneKit)
|
||||
view = SceneKit
|
||||
setup()
|
||||
}
|
||||
|
||||
//MARK: - Internal threads
|
||||
internal let writerQueue = DispatchQueue(label:"com.ahmedbekhit.WriterQueue")
|
||||
internal let gifWriterQueue = DispatchQueue(label: "com.ahmedbekhit.GIFWriterQueue", attributes: .concurrent)
|
||||
internal let audioSessionQueue = DispatchQueue(label: "com.ahmedbekhit.AudioSessionQueue", attributes: .concurrent)
|
||||
|
||||
//MARK: - Internal Objects
|
||||
fileprivate var scnView:SCNView!
|
||||
fileprivate var fileCount = 0
|
||||
|
||||
internal var parent:UIViewController? {
|
||||
if let view = view as? ARSCNView {
|
||||
return view.parent!
|
||||
}else if let view = view as? ARSKView {
|
||||
return view.parent!
|
||||
}else if let view = view as? SCNView {
|
||||
return view.parent!
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
//Used for gif capturing
|
||||
internal var gifImages:[UIImage] = []
|
||||
//Used for checking current recorder status
|
||||
internal var isCapturingPhoto = false
|
||||
internal var isRecordingGIF = false
|
||||
internal var isRecording = false
|
||||
internal var adjustPausedTime = false
|
||||
internal var backFromPause = false
|
||||
internal var recordingWithLimit = false
|
||||
internal var onlyRenderWhileRec = false
|
||||
//Used to modify video time when paused
|
||||
internal var pausedFrameTime:CMTime?
|
||||
internal var resumeFrameTime:CMTime?
|
||||
//Used to locate the path of the video recording
|
||||
internal var currentVideoPath:URL?
|
||||
//Used to locate the path of the audio recording
|
||||
internal var currentAudioPath:URL?
|
||||
//Used to initialize the video writer
|
||||
internal var writer:WritAR?
|
||||
//Used to generate a new video path
|
||||
internal var newVideoPath:URL {
|
||||
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
|
||||
let documentsDirectory = paths[0]
|
||||
|
||||
let formatter = DateFormatter()
|
||||
formatter.dateStyle = .full
|
||||
formatter.timeStyle = .full
|
||||
formatter.dateFormat = "yyyy-MM-dd'@'HH-mm-ssZZZZ"
|
||||
|
||||
let date = Date(timeIntervalSince1970: Date().timeIntervalSince1970)
|
||||
|
||||
let vidPath = "\(documentsDirectory)/\(formatter.string(from: date))ARVideo.mp4"
|
||||
return URL(fileURLWithPath: vidPath, isDirectory: false)
|
||||
}
|
||||
|
||||
//MARK: - Internal Video Setup
|
||||
internal func setup() {
|
||||
if let view = view as? ARSCNView {
|
||||
guard let mtlDevice = MTLCreateSystemDefaultDevice() else {logAR.message("ERROR:- This device does not support Metal");return}
|
||||
renderEngine = SCNRenderer(device: mtlDevice, options: nil)
|
||||
renderEngine.scene = view.scene
|
||||
|
||||
gpuLoop = CADisplayLink(target: self, selector: #selector(renderFrame))
|
||||
gpuLoop.preferredFramesPerSecond = fps.rawValue
|
||||
gpuLoop.add(to: .main, forMode: .commonModes)
|
||||
|
||||
status = .readyToRecord
|
||||
}else if let view = view as? ARSKView {
|
||||
guard let mtlDevice = MTLCreateSystemDefaultDevice() else {logAR.message("ERROR:- This device does not support Metal");return}
|
||||
let material = SCNMaterial()
|
||||
material.diffuse.contents = view.scene
|
||||
|
||||
let plane = SCNPlane(width: view.bounds.width, height: view.bounds.height)
|
||||
let node = SCNNode(geometry: plane)
|
||||
node.geometry?.firstMaterial = material
|
||||
node.position = SCNVector3Make(0, 0, 0)
|
||||
|
||||
scnView.scene?.rootNode.addChildNode(node)
|
||||
|
||||
renderEngine = SCNRenderer(device: mtlDevice, options: nil)
|
||||
renderEngine.scene = scnView.scene
|
||||
|
||||
gpuLoop = CADisplayLink(target: self, selector: #selector(renderFrame))
|
||||
gpuLoop.preferredFramesPerSecond = fps.rawValue
|
||||
gpuLoop.add(to: .main, forMode: .commonModes)
|
||||
|
||||
status = .readyToRecord
|
||||
}else if let view = view as? SCNView {
|
||||
guard let mtlDevice = MTLCreateSystemDefaultDevice() else {logAR.message("ERROR:- This device does not support Metal");return}
|
||||
renderEngine = SCNRenderer(device: mtlDevice, options: nil)
|
||||
renderEngine.scene = view.scene
|
||||
|
||||
gpuLoop = CADisplayLink(target: self, selector: #selector(renderFrame))
|
||||
gpuLoop.preferredFramesPerSecond = fps.rawValue
|
||||
gpuLoop.add(to: .main, forMode: .commonModes)
|
||||
|
||||
status = .readyToRecord
|
||||
}
|
||||
|
||||
switch requestMicPermission {
|
||||
case .auto:
|
||||
AVAudioSession.sharedInstance().requestRecordPermission({ permitted in
|
||||
if permitted {
|
||||
self.micStatus = .enabled
|
||||
}else{
|
||||
self.micStatus = .disabled
|
||||
}
|
||||
})
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
onlyRenderWhileRec = onlyRenderWhileRecording
|
||||
|
||||
renderer = RenderAR(view, renderer: renderEngine, contentMode: contentMode)
|
||||
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(appWillEnterBackground), name: Notification.Name.UIApplicationWillResignActive, object: nil)
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
//MARK: - Public methods for capturing videos, photos, Live Photos, and GIFs
|
||||
|
||||
/// A method that renders a photo 🌄 and returns it as `UIImage`.
|
||||
@objc public func photo() -> UIImage {
|
||||
if let buffer = renderer.buffer {
|
||||
return imageFromBuffer(buffer: buffer)
|
||||
}
|
||||
return UIImage()
|
||||
}
|
||||
/**
|
||||
A method that renders a `PHLivePhoto` 🎇 and returns `PHLivePhotoPlus` in the completion handler.
|
||||
|
||||
In order to manually export the `PHLivePhotoPlus`, use `export(live photo:PHLivePhotoPlus)` method.
|
||||
- parameter export: A boolean that enables or disables automatically exporting the `PHLivePhotoPlus` when ready.
|
||||
- parameter finished: A block that will be called when Live Photo rendering is complete.
|
||||
|
||||
The block returns the following parameters:
|
||||
|
||||
`status`
|
||||
A boolean that returns `true` when a `PHLivePhotoPlus` is successfully rendered. Otherwise, it returns `false`.
|
||||
|
||||
`livePhoto`
|
||||
A `PHLivePhotoPlus` object that contains a `PHLivePhoto` and other objects to allow manual exporting of a live photo.
|
||||
|
||||
`permissionStatus`
|
||||
A `PHAuthorizationStatus` object that returns the current application's status for exporting media to the Photo Library. It returns `nil` if the `export` parameter is `false`.
|
||||
|
||||
`exported`
|
||||
A boolean that returns `true` when a `PHLivePhotoPlus` is successfully exported to the Photo Library. Otherwise, it returns `false`.
|
||||
*/
|
||||
@objc public func livePhoto(export:Bool, _ finished: ((_ status:Bool, _ livePhoto:PHLivePhotoPlus, _ permissionStatus:PHAuthorizationStatus, _ exported:Bool) -> Swift.Void)? = nil) {
|
||||
self.record(forDuration: 3.0) { path in
|
||||
let generator:LivePhotoGenerator? = LivePhotoGenerator()
|
||||
generator?.generate(livePhoto: path) { success, photo, frames, keyFrame in
|
||||
if success && export {
|
||||
if self.fileCount == 0 {
|
||||
self.fileCount += 1
|
||||
self.export(live: photo!) { done, status in
|
||||
finished?(true, photo!, status, done)
|
||||
}
|
||||
}
|
||||
}else{
|
||||
finished?(success, photo!, PHAuthorizationStatus.notDetermined, false)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
A method that generates a GIF 🎆 image and returns its local path (`URL`) in the completion handler.
|
||||
|
||||
In order to manually export the GIF image `URL`, use `func export(image path:URL)` method.
|
||||
- parameter duration: A `TimeInterval` object that can be set to the duration specified in seconds.
|
||||
- parameter export: A boolean that enables or disables automatically exporting the GIF image `URL` when ready.
|
||||
- parameter finished: A block that will be called when GIF image rendering is complete.
|
||||
|
||||
The block returns the following parameters:
|
||||
|
||||
`status`
|
||||
A boolean that returns `true` when a GIF image `URL` is successfully rendered. Otherwise, it returns `false`.
|
||||
|
||||
`gifPath`
|
||||
A `URL` object that contains the local file path of the GIF image to allow manual exporting of a GIF.
|
||||
|
||||
`permissionStatus`
|
||||
A `PHAuthorizationStatus` object that returns the current application's status for exporting media to the Photo Library. It returns `nil` if the `export` parameter is `false`.
|
||||
|
||||
`exported`
|
||||
A boolean that returns `true` when a GIF image `URL` is successfully exported to the Photo Library. Otherwise, it returns `false`.
|
||||
*/
|
||||
@objc public func gif(forDuration duration:TimeInterval, export:Bool, _ finished: ((_ status:Bool, _ gifPath: URL, _ permissionStatus:PHAuthorizationStatus, _ exported:Bool) -> Swift.Void)? = nil) {
|
||||
writerQueue.sync {
|
||||
self.isRecordingGIF = true
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + duration) {
|
||||
self.isRecordingGIF = false
|
||||
let generator:GIFGenerator? = GIFGenerator()
|
||||
generator?.generate(gif: self.gifImages, with: 0.1, loop: 0, adjust: self.adjustGIFForSharing) {ready, path in
|
||||
if ready {
|
||||
self.gifImages.removeAll()
|
||||
if export {
|
||||
self.export(image: path!) { done, status in
|
||||
finished?(ready, path!, status, done)
|
||||
}
|
||||
}else{
|
||||
finished?(ready, path!, .notDetermined, false)
|
||||
}
|
||||
}else{
|
||||
self.gifImages.removeAll()
|
||||
finished?(ready, path!, .notDetermined, false)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
///A method that starts or resumes ⏯ recording a video 📹.
|
||||
@objc public func record() {
|
||||
writerQueue.sync {
|
||||
self.isRecording = true
|
||||
self.status = .recording
|
||||
}
|
||||
}
|
||||
/**
|
||||
A method that starts recording a video 📹 with a specified duration ⏳ in seconds.
|
||||
|
||||
In order to stop the recording before the specified duration, simply call `stop()` or `stopAndExport()` methods.
|
||||
|
||||
- WARNING : You CAN NOT `pause()` video recording when a duration is specified.
|
||||
- parameter duration: A `TimeInterval` object that can be set to the duration specified in seconds.
|
||||
- parameter finished: A block that will be called when the specified `duration` has ended.
|
||||
|
||||
The block returns the following parameter:
|
||||
|
||||
`videoPath`
|
||||
A `URL` object that contains the local file path of the video to allow manual exporting or preview of the video.
|
||||
*/
|
||||
@objc public func record(forDuration duration:TimeInterval, _ finished: ((_ videoPath: URL) -> Swift.Void)? = nil) {
|
||||
writerQueue.sync {
|
||||
self.recordingWithLimit = true
|
||||
self.isRecording = true
|
||||
self.status = .recording
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + duration) {
|
||||
self.stop { path in
|
||||
finished?(path)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
A method that pauses recording a video ⏸📹.
|
||||
|
||||
In order to resume recording, simply call the `record()` method.
|
||||
*/
|
||||
@objc public func pause() {
|
||||
if !recordingWithLimit {
|
||||
onlyRenderWhileRec = false
|
||||
isRecording = false
|
||||
adjustPausedTime = true
|
||||
}else{
|
||||
logAR.message("NOT PERMITTED: The [ pause() ] method CAN NOT be used while using [ record(forDuration duration:TimeInterval) ]")
|
||||
}
|
||||
}
|
||||
/**
|
||||
A method that stops ⏹ recording a video 📹 and exports it to the Photo Library 📲💾.
|
||||
|
||||
- parameter finished: A block that will be called when the export process is complete.
|
||||
|
||||
The block returns the following parameters:
|
||||
|
||||
`videoPath`
|
||||
A `URL` object that contains the local file path of the video to allow manual exporting or preview of the video.
|
||||
|
||||
`permissionStatus`
|
||||
A `PHAuthorizationStatus` object that returns the current application's status for exporting media to the Photo Library.
|
||||
|
||||
`exported`
|
||||
A boolean that returns `true` when a video is successfully exported to the Photo Library. Otherwise, it returns `false`.
|
||||
*/
|
||||
@objc public func stopAndExport(_ finished: ((_ videoPath: URL, _ permissionStatus:PHAuthorizationStatus, _ exported:Bool) -> Swift.Void)? = nil) {
|
||||
writerQueue.sync {
|
||||
self.isRecording = false
|
||||
self.adjustPausedTime = false
|
||||
self.backFromPause = false
|
||||
self.recordingWithLimit = false
|
||||
|
||||
self.pausedFrameTime = nil
|
||||
self.resumeFrameTime = nil
|
||||
|
||||
self.writer?.end {
|
||||
if let path = self.currentVideoPath {
|
||||
self.export(video: path) { exported, status in
|
||||
finished?(path, status, exported)
|
||||
}
|
||||
self.delegate?.recorder(didEndRecording: path, with: true)
|
||||
self.status = .readyToRecord
|
||||
}else{
|
||||
finished?(self.currentVideoPath!, .notDetermined, false)
|
||||
self.status = .readyToRecord
|
||||
self.delegate?.recorder(didFailRecording: errSecDecode as? Error, and: "An error occured while stopping your video.")
|
||||
}
|
||||
self.writer = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
A method that stops ⏹ recording a video 📹 and returns the video path in the completion handler.
|
||||
|
||||
- parameter finished: A block that will be called when the specified `duration` has ended.
|
||||
|
||||
The block returns the following parameter:
|
||||
|
||||
`videoPath`
|
||||
A `URL` object that contains the local file path of the video to allow manual exporting or preview of the video.
|
||||
*/
|
||||
@objc public func stop(_ finished:((_ videoPath: URL) -> Swift.Void)? = nil) {
|
||||
writerQueue.sync {
|
||||
isRecording = false
|
||||
adjustPausedTime = false
|
||||
backFromPause = false
|
||||
recordingWithLimit = false
|
||||
|
||||
pausedFrameTime = nil
|
||||
resumeFrameTime = nil
|
||||
|
||||
DispatchQueue.main.async {
|
||||
self.writer?.end {
|
||||
if let path = self.currentVideoPath {
|
||||
finished?(path)
|
||||
self.delegate?.recorder(didEndRecording: path, with: true)
|
||||
self.status = .readyToRecord
|
||||
}else{
|
||||
self.status = .readyToRecord
|
||||
self.delegate?.recorder(didFailRecording: errSecDecode as? Error, and: "An error occured while stopping your video.")
|
||||
}
|
||||
self.writer = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
A method that exports a video 📹 file path to the Photo Library 📲💾.
|
||||
|
||||
- parameter path: A `URL` object that can be set to a local video file path to export to the Photo Library.
|
||||
|
||||
- parameter finished: A block that will be called when the export process is complete.
|
||||
|
||||
The block returns the following parameters:
|
||||
|
||||
`exported`
|
||||
A boolean that returns `true` when a video is successfully exported to the Photo Library. Otherwise, it returns `false`.
|
||||
|
||||
`permissionStatus`
|
||||
A `PHAuthorizationStatus` object that returns the current application's status for exporting media to the Photo Library.
|
||||
*/
|
||||
@objc public func export(video path:URL, _ finished: ((_ exported:Bool, _ permissionStatus:PHAuthorizationStatus) -> Swift.Void)? = nil) {
|
||||
audioSessionQueue.async {
|
||||
let photos = PHPhotoLibrary.authorizationStatus()
|
||||
if photos == .notDetermined {
|
||||
PHPhotoLibrary.requestAuthorization({ status in
|
||||
if status == .authorized {
|
||||
PHPhotoLibrary.shared().performChanges({
|
||||
PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: path)
|
||||
}) { saved, _ in
|
||||
if saved && self.deleteCacheWhenExported {
|
||||
logAR.remove(from: path)
|
||||
}
|
||||
finished?(saved, status)
|
||||
}
|
||||
}else{
|
||||
finished?(false, status)
|
||||
}
|
||||
})
|
||||
}else if photos == .authorized {
|
||||
PHPhotoLibrary.shared().performChanges({
|
||||
PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: path)
|
||||
}) { saved, error in
|
||||
if saved && self.deleteCacheWhenExported {
|
||||
logAR.remove(from: path)
|
||||
}
|
||||
finished?(saved, photos)
|
||||
}
|
||||
}else if photos == .denied || photos == .restricted {
|
||||
finished?(false, photos)
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
A method that exports any image 🌄/🎆 (including gif, jpeg, and png) to the Photo Library 📲💾.
|
||||
|
||||
- parameter path: A `URL` object that can be set to a local image file path to export to the Photo Library.
|
||||
- parameter UIImage: A `UIImage` object.
|
||||
- parameter finished: A block that will be called when the export process is complete.
|
||||
|
||||
The block returns the following parameters:
|
||||
|
||||
`exported`
|
||||
A boolean that returns `true` when an image is successfully exported to the Photo Library. Otherwise, it returns `false`.
|
||||
|
||||
`permissionStatus`
|
||||
A `PHAuthorizationStatus` object that returns the current application's status for exporting media to the Photo Library.
|
||||
*/
|
||||
@objc public func export(image path:URL?=nil, UIImage:UIImage?=nil, _ finished: ((_ exported:Bool, _ permissionStatus:PHAuthorizationStatus) -> Swift.Void)? = nil) {
|
||||
let photos = PHPhotoLibrary.authorizationStatus()
|
||||
if photos == .notDetermined {
|
||||
PHPhotoLibrary.requestAuthorization({ status in
|
||||
if status == .authorized {
|
||||
PHPhotoLibrary.shared().performChanges({
|
||||
if let path = path {
|
||||
PHAssetChangeRequest.creationRequestForAssetFromImage(atFileURL: path)
|
||||
}else if let image = UIImage {
|
||||
PHAssetChangeRequest.creationRequestForAsset(from: image)
|
||||
}
|
||||
}) { saved, error in
|
||||
if saved && self.deleteCacheWhenExported {
|
||||
if let path = path {
|
||||
logAR.remove(from: path)
|
||||
}
|
||||
}
|
||||
finished?(saved, status)
|
||||
}
|
||||
}else{
|
||||
finished?(false, status)
|
||||
}
|
||||
})
|
||||
}else if photos == .authorized {
|
||||
PHPhotoLibrary.shared().performChanges({
|
||||
if let path = path {
|
||||
PHAssetChangeRequest.creationRequestForAssetFromImage(atFileURL: path)
|
||||
}else if let image = UIImage {
|
||||
PHAssetChangeRequest.creationRequestForAsset(from: image)
|
||||
}
|
||||
}) { saved, error in
|
||||
if saved && self.deleteCacheWhenExported {
|
||||
if let path = path {
|
||||
logAR.remove(from: path)
|
||||
}
|
||||
}
|
||||
finished?(saved, photos)
|
||||
}
|
||||
}else if photos == .denied || photos == .restricted {
|
||||
finished?(false, photos)
|
||||
}
|
||||
}
|
||||
/**
|
||||
A method that exports a `PHLivePhotoPlus` 🎇 object to the Photo Library 📲💾.
|
||||
|
||||
- parameter photo: A `PHLivePhotoPlus` object that can be set to the returned `PHLivePhotoPlus` object in the `livePhoto(export:Bool, _ finished:{})` method.
|
||||
|
||||
- parameter finished: A block that will be called when the export process is complete.
|
||||
|
||||
The block returns the following parameters:
|
||||
|
||||
`exported`
|
||||
A boolean that returns `true` when the Live Photo is successfully exported to the Photo Library. Otherwise, it returns `false`.
|
||||
|
||||
`permissionStatus`
|
||||
A `PHAuthorizationStatus` object that returns the current application's status for exporting media to the Photo Library.
|
||||
*/
|
||||
@objc public func export(live photo:PHLivePhotoPlus, _ finished: ((_ exported:Bool, _ permissionStatus:PHAuthorizationStatus) -> Swift.Void)? = nil) {
|
||||
guard let keyPhotoPath = photo.keyPhotoPath else{logAR.message("An error occurred while exporting a live photo"); return}
|
||||
guard let videoPath = photo.pairedVideoPath else{logAR.message("An error occurred while exporting a live photo"); return}
|
||||
|
||||
let photos = PHPhotoLibrary.authorizationStatus()
|
||||
if photos == .notDetermined {
|
||||
PHPhotoLibrary.requestAuthorization({ status in
|
||||
if status == .authorized {
|
||||
PHPhotoLibrary.shared().performChanges({
|
||||
let request = PHAssetCreationRequest.forAsset()
|
||||
let options = PHAssetResourceCreationOptions()
|
||||
request.addResource(with: .photo, fileURL: keyPhotoPath, options: options)
|
||||
request.addResource(with: .pairedVideo, fileURL: videoPath, options: options)
|
||||
}, completionHandler: { saved, error in
|
||||
if saved {
|
||||
if self.deleteCacheWhenExported {
|
||||
logAR.remove(from: keyPhotoPath)
|
||||
logAR.remove(from: videoPath)
|
||||
}
|
||||
self.fileCount = 0
|
||||
}else{
|
||||
logAR.message("An error occurred while exporting a live photo: \(error!)")
|
||||
}
|
||||
finished?(saved, status)
|
||||
})
|
||||
}else{
|
||||
finished?(false, status)
|
||||
}
|
||||
})
|
||||
}else if photos == .authorized {
|
||||
PHPhotoLibrary.shared().performChanges({
|
||||
let request = PHAssetCreationRequest.forAsset()
|
||||
let options = PHAssetResourceCreationOptions()
|
||||
request.addResource(with: .photo, fileURL: keyPhotoPath, options: options)
|
||||
request.addResource(with: .pairedVideo, fileURL: videoPath, options: options)
|
||||
}, completionHandler: { saved, error in
|
||||
if saved {
|
||||
if self.deleteCacheWhenExported {
|
||||
logAR.remove(from: keyPhotoPath)
|
||||
logAR.remove(from: videoPath)
|
||||
}
|
||||
self.fileCount = 0
|
||||
}else{
|
||||
logAR.message("An error occurred while exporting a live photo: \(error!)")
|
||||
}
|
||||
finished?(saved, photos)
|
||||
})
|
||||
}else if photos == .denied || photos == .restricted {
|
||||
finished?(false, photos)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
A method that requsts microphone 🎙 permission manually, if micPermission is set to `manual`.
|
||||
- parameter finished: A block that will be called when the audio permission is requested.
|
||||
|
||||
The block returns the following parameter:
|
||||
|
||||
`status`
|
||||
A boolean that returns `true` when a the Microphone access is permitted. Otherwise, it returns `false`.
|
||||
*/
|
||||
@objc public func requestMicrophonePermission(_ finished: ((_ status: Bool) -> Swift.Void)? = nil) {
|
||||
AVAudioSession.sharedInstance().requestRecordPermission({ permitted in
|
||||
finished?(permitted)
|
||||
if permitted {
|
||||
self.micStatus = .enabled
|
||||
}else{
|
||||
self.micStatus = .disabled
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
//MARK: - Public methods for setting up UIViewController orientations
|
||||
@available(iOS 11.0, *)
|
||||
@objc public extension RecordAR {
|
||||
/**
|
||||
A method that prepares the video recorder with `ARConfiguration` 📝.
|
||||
|
||||
Recommended to use in the `UIViewController`'s method `func viewWillAppear(_ animated: Bool)`
|
||||
- parameter configuration: An object that defines motion and scene tracking behaviors for the session.
|
||||
*/
|
||||
@objc public func prepare(_ configuration:ARConfiguration?=nil) {
|
||||
ARcontentMode = contentMode
|
||||
onlyRenderWhileRec = onlyRenderWhileRecording
|
||||
if let view = view as? ARSCNView {
|
||||
UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
|
||||
ViewAR.orientation = .portrait
|
||||
|
||||
//try resetting anchors for the initial landscape orientation issue.
|
||||
guard let config = configuration else {return}
|
||||
view.session.run(config)
|
||||
}else if let view = view as? ARSKView {
|
||||
UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
|
||||
ViewAR.orientation = .portrait
|
||||
guard let config = configuration else {return}
|
||||
view.session.run(config)
|
||||
}else if let _ = view as? SCNView {
|
||||
UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
|
||||
ViewAR.orientation = .portrait
|
||||
}
|
||||
}
|
||||
/**
|
||||
A method that switches off the orientation lock used in a `UIViewController` with AR scenes 📐😴.
|
||||
|
||||
Recommended to use in the `UIViewController`'s method `func viewWillDisappear(_ animated: Bool)`.
|
||||
*/
|
||||
@objc public func rest() {
|
||||
ViewAR.orientation = UIInterfaceOrientationMask(ViewAR.orientations)
|
||||
}
|
||||
}
|
||||
|
||||
//MARK: - Internal AR Video Frames Rendering
|
||||
@available(iOS 11.0, *)
|
||||
internal extension RecordAR {
|
||||
@objc internal func renderFrame() {
|
||||
//frame rendering
|
||||
if self.onlyRenderWhileRec && !isRecording && !isRecordingGIF {return}
|
||||
guard let buffer = renderer.buffer else{return}
|
||||
guard let rawBuffer = renderer.rawBuffer else{logAR.message("ERROR:- An error occurred while rendering the camera's main buffers.");return}
|
||||
guard let size = renderer.bufferSize else{logAR.message("ERROR:- An error occurred while rendering the camera buffer.");return}
|
||||
renderer.ARcontentMode = contentMode
|
||||
|
||||
self.writerQueue.sync {
|
||||
var time:CMTime {return CMTimeMakeWithSeconds(renderer.time, 1000000);}
|
||||
|
||||
self.renderAR?.frame(didRender: buffer, with: time, using: rawBuffer)
|
||||
|
||||
//gif images writing
|
||||
if self.isRecordingGIF {
|
||||
self.gifWriterQueue.sync {
|
||||
self.gifImages.append(self.imageFromBuffer(buffer: buffer))
|
||||
}
|
||||
}
|
||||
|
||||
//frame writing
|
||||
if self.isRecording {
|
||||
if let frameWriter = self.writer {
|
||||
var finalFrameTime:CMTime?
|
||||
if self.backFromPause {
|
||||
if self.resumeFrameTime == nil {
|
||||
self.resumeFrameTime = time
|
||||
}
|
||||
//Formula: (currentTime - (timeWhenResume - timeWhenPaused))
|
||||
guard let resumeTime = self.resumeFrameTime else {return}
|
||||
guard let pausedTime = self.pausedFrameTime else {return}
|
||||
finalFrameTime = self.adjustTime(current: time, resume: resumeTime, pause: pausedTime)
|
||||
}else{
|
||||
finalFrameTime = time
|
||||
}
|
||||
|
||||
frameWriter.insert(pixel: buffer, with: finalFrameTime!)
|
||||
|
||||
guard let isWriting = frameWriter.isWritingWithoutError else {return}
|
||||
if !isWriting {
|
||||
self.isRecording = false
|
||||
|
||||
self.status = .readyToRecord
|
||||
self.delegate?.recorder(didFailRecording: errSecDecode as? Error, and: "An error occured while recording your video.")
|
||||
self.delegate?.recorder(didEndRecording: self.currentVideoPath!, with: false)
|
||||
}
|
||||
}else{
|
||||
self.currentVideoPath = self.newVideoPath
|
||||
|
||||
self.writer = WritAR(output: self.currentVideoPath!, width: Int(size.width), height: Int(size.height), adjustForSharing: self.adjustVideoForSharing, audioEnabled: self.enableAudio, orientaions: self.inputViewOrientations, queue: self.writerQueue, allowMix: self.enableMixWithOthers)
|
||||
self.writer?.videoInputOrientation = self.videoOrientation
|
||||
self.writer?.delegate = self.delegate
|
||||
}
|
||||
}else if !self.isRecording && self.adjustPausedTime {
|
||||
writer?.pause()
|
||||
|
||||
self.adjustPausedTime = false
|
||||
|
||||
if self.pausedFrameTime != nil {
|
||||
self.pausedFrameTime = self.adjustTime(current: time, resume: self.resumeFrameTime!, pause: self.pausedFrameTime!)
|
||||
}else{
|
||||
self.pausedFrameTime = time
|
||||
}
|
||||
|
||||
self.backFromPause = true
|
||||
self.resumeFrameTime = nil
|
||||
|
||||
self.status = .paused
|
||||
self.onlyRenderWhileRec = onlyRenderWhileRecording
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
//
|
||||
// prepare.swift
|
||||
// AR Video
|
||||
//
|
||||
// Created by Ahmed Bekhit on 10/16/17.
|
||||
// Copyright © 2017 Ahmed Fathi Bekhit. All rights reserved.
|
||||
//
|
||||
|
||||
import ARKit
|
||||
/**
|
||||
A struct that identifies the application `UIViewController`s and their orientations.
|
||||
|
||||
- Author: Ahmed Fathi Bekhit
|
||||
* [Github](http://github.com/AFathi)
|
||||
* [Website](http://ahmedbekhit.com)
|
||||
* [Twitter](http://twitter.com/iAFapps)
|
||||
* [Email](mailto:me@ahmedbekhit.com)
|
||||
*/
|
||||
@available(iOS 11.0, *)
|
||||
@objc public class ViewAR: NSObject {
|
||||
/**
|
||||
A `UIInterfaceOrientationMask` object that returns the recommended orientations for a `UIViewController` with AR scenes.
|
||||
|
||||
Recommended to return in the application delegate method `func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask`.
|
||||
*/
|
||||
@objc internal(set) public static var orientation: UIInterfaceOrientationMask {get {return mask;}set {mask = newValue}}
|
||||
|
||||
internal static var orientations:[UIInterfaceOrientationMask] {
|
||||
var all:[UIInterfaceOrientationMask] = []
|
||||
if let info = Bundle.main.infoDictionary {
|
||||
if let supportedOrientaions = info["UISupportedInterfaceOrientations"] as? NSArray {
|
||||
for orientation in supportedOrientaions {
|
||||
if let o = orientation as? String {
|
||||
if o == "UIInterfaceOrientationPortrait" {
|
||||
all.append(.portrait)
|
||||
}else if o == "UIInterfaceOrientationPortraitUpsideDown" {
|
||||
all.append(.portraitUpsideDown)
|
||||
}else if o == "UIInterfaceOrientationLandscapeLeft" {
|
||||
all.append(.landscapeLeft)
|
||||
}else if o == "UIInterfaceOrientationLandscapeRight" {
|
||||
all.append(.landscapeRight)
|
||||
}
|
||||
}
|
||||
}
|
||||
return all
|
||||
}
|
||||
}
|
||||
return all
|
||||
}
|
||||
//returns the application's delegate to check if the current UIViewController contains an ARView
|
||||
fileprivate static var delegate = UIApplication.shared.delegate
|
||||
//variable for the setter in `mask`
|
||||
fileprivate static var m: UIInterfaceOrientationMask = .portrait
|
||||
//returns the most appropriate orientation based on the content of the UIViewController.
|
||||
fileprivate static var mask: UIInterfaceOrientationMask {get {if let vc = delegate?.window??.inputViewController {if vc.hasARView {return .portrait}else{return UIInterfaceOrientationMask(orientations)}};return m;}set {m = newValue;}}
|
||||
}
|
||||
Reference in New Issue
Block a user