Skip to content

Commit

Permalink
seems to be working
Browse files Browse the repository at this point in the history
  • Loading branch information
gertig committed Feb 8, 2014
1 parent bc1c151 commit 2cba7bb
Show file tree
Hide file tree
Showing 7 changed files with 151 additions and 58 deletions.
2 changes: 2 additions & 0 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,5 @@ source 'https://rubygems.org'

gem 'rake'
# Add your dependencies here:

gem 'awesome_print_motion' # aliased to ap
12 changes: 12 additions & 0 deletions Gemfile.lock
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
GEM
remote: https://rubygems.org/
specs:
awesome_print_motion (0.1.0)
rake (10.1.1)

PLATFORMS
ruby

DEPENDENCIES
awesome_print_motion
rake
20 changes: 19 additions & 1 deletion Rakefile
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,23 @@ end

Motion::Project::App.setup do |app|
# Use `rake config' to see complete project settings.
app.name = 'motion-avcam'
app.name = 'AVCam'
app.frameworks += [
'AssetsLibrary',
'AudioToolbox',
'AVFoundation',
'CoreGraphics',
'CoreImage',
'CoreMedia',
'CoreVideo',
'Foundation',
'ImageIO',
'MediaPlayer',
'MessageUI',
'MobileCoreServices',
'OpenGLES',
'QuartzCore',
'SystemConfiguration',
'UIKit'
]
end
2 changes: 1 addition & 1 deletion app/AVCamPreviewView.rb
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ class AVCamPreviewView < UIView
attr_accessor :session

def self.layerClass
"AVCaptureVideoPreviewLayer" #.class
AVCaptureVideoPreviewLayer #.class
end

def session
Expand Down
151 changes: 96 additions & 55 deletions app/AVCamViewController.rb
Original file line number Diff line number Diff line change
Expand Up @@ -50,52 +50,50 @@
#import <AssetsLibrary/AssetsLibrary.h>
#import "AVCamPreviewView.h"

static void * CapturingStillImageContext = &CapturingStillImageContext;
static void * RecordingContext = &RecordingContext;
static void * SessionRunningAndDeviceAuthorizedContext = &SessionRunningAndDeviceAuthorizedContext;
class AVCamViewController < UIViewController

@interface AVCamViewController () <AVCaptureFileOutputRecordingDelegate>
attr_accessor :sessionQueue, :session, :videoDeviceInput, :movieFileOutput, :stillImageOutput
# Utilities
attr_accessor :backgroundRecordingID, :deviceAuthorized, :sessionRunningAndDeviceAuthorized, :lockInterfaceRotation, :runtimeErrorHandlingObserver

# For use in the storyboards.
@property (nonatomic, weak) IBOutlet AVCamPreviewView *previewView;
@property (nonatomic, weak) IBOutlet UIButton *recordButton;
@property (nonatomic, weak) IBOutlet UIButton *cameraButton;
@property (nonatomic, weak) IBOutlet UIButton *stillButton;
# Views and Buttons
attr_accessor :previewView, :recordButton, :cameraButton, :stillButton

- (IBAction)toggleMovieRecording:(id)sender;
- (IBAction)changeCamera:(id)sender;
- (IBAction)snapStillImage:(id)sender;
- (IBAction)focusAndExposeTap:(UIGestureRecognizer *)gestureRecognizer;
# ContextPointer = Pointer.new(:object, 3)
# ContextPointer[0]="Capturing"
# ContextPointer[1]="Recording"
# ContextPointer[2]="SessionRunning"

# Session management.
# Communicate with the session and other session objects on this queue

# @property (nonatomic) dispatch_queue_t sessionQueue;
# @property (nonatomic) AVCaptureSession *session;
# @property (nonatomic) AVCaptureDeviceInput *videoDeviceInput;
# @property (nonatomic) AVCaptureMovieFileOutput *movieFileOutput;
# @property (nonatomic) AVCaptureStillImageOutput *stillImageOutput;
CapturePointer = Pointer.new(:object, 1)
CapturePointer[0] = "Capturing"

# Utilities.
# @property (nonatomic) UIBackgroundTaskIdentifier backgroundRecordingID;
# @property (nonatomic, getter = isDeviceAuthorized) BOOL deviceAuthorized;
# @property (nonatomic, readonly, getter = isSessionRunningAndDeviceAuthorized) BOOL sessionRunningAndDeviceAuthorized;
# @property (nonatomic) BOOL lockInterfaceRotation;
# @property (nonatomic) id runtimeErrorHandlingObserver;
RecordingPointer = Pointer.new(:object, 1)
RecordingPointer[0] = "Recording"

# @end
SessionRunningPointer = Pointer.new(:object, 1)
SessionRunningPointer[0] = "SessionRunning"

class AVCamViewController < UIViewController

attr_accessor :sessionQueue, :session, :videoDeviceInput, :movieFileOutput, :stillImageOutput
# Utilities
attr_accessor :backgroundRecordingID, :deviceAuthorized, :sessionRunningAndDeviceAuthorized, :lockInterfaceRotation, :runtimeErrorHandlingObserver
CapturingStillImageContext = CapturePointer
RecordingContext = RecordingPointer
SessionRunningAndDeviceAuthorizedContext = SessionRunningPointer

def sessionRunningAndDeviceAuthorized
NSLog("[method] sessionRunningAndDeviceAuthorized")
self.session.isRunning && self.deviceAuthorized
end

def isSessionRunningAndDeviceAuthorized
self.session.isRunning && self.isDeviceAuthorized
def sessionRunningAndDeviceAuthorized=(sessionRunningAndDeviceAuthorized)
@sessionRunningAndDeviceAuthorized = sessionRunningAndDeviceAuthorized
end

# def deviceAuthorized

# end

def self.keyPathsForValuesAffectingSessionRunningAndDeviceAuthorized
NSLog("[method] self.NSObject.keyPathsForValuesAffectingAuthorized")
NSSet.setWithObjects("session.running", "deviceAuthorized", nil)
end

Expand All @@ -107,6 +105,28 @@ def viewDidLoad
self.setSession(session)

# Setup the preview view
@previewView = AVCamPreviewView.alloc.initWithFrame(self.view.bounds)

@recordButton = UIButton.buttonWithType(UIButtonTypeCustom)
@recordButton.setTitle("Record", forState:UIControlStateNormal)
@recordButton.addTarget(self, action:"toggleMovieRecording:", forControlEvents:UIControlEventTouchUpInside)
@recordButton.frame = [[32,516], [72, 30]]

@cameraButton = UIButton.buttonWithType(UIButtonTypeCustom)
@cameraButton.setTitle("Swap", forState:UIControlStateNormal)
@cameraButton.addTarget(self, action:"changeCamera:", forControlEvents:UIControlEventTouchUpInside)
@cameraButton.frame = [[216,516], [72, 30]]

@stillButton = UIButton.buttonWithType(UIButtonTypeCustom)
@stillButton.setTitle("Still", forState:UIControlStateNormal)
@stillButton.addTarget(self, action:"snapStillImage:", forControlEvents:UIControlEventTouchUpInside)
@stillButton.frame = [[124,516], [72, 30]]

self.view.addSubview(@previewView)
self.view.addSubview(@recordButton)
self.view.addSubview(@cameraButton)
self.view.addSubview(@stillButton)

self.previewView.setSession(session)

# Check for device authorization
Expand Down Expand Up @@ -155,6 +175,7 @@ def viewDidLoad
# video orientation changes on the AVCaptureVideoPreviewLayer’s connection with
# other session manipulation.

NSLog("Set Video Orientation")
self.previewView.layer.connection.setVideoOrientation(self.interfaceOrientation)
}
end
Expand Down Expand Up @@ -185,8 +206,8 @@ def viewDidLoad
stillImageOutput = AVCaptureStillImageOutput.alloc.init

if session.canAddOutput(stillImageOutput)
settings = { AVVideoCodecKey: AVVideoCodecJPEG }
NSLog("Settings Object: %@", settings)
settings = { :AVVideoCodecKey => AVVideoCodecJPEG }
NSLog("Settings Object: %@", settings.to_s)
stillImageOutput.setOutputSettings(settings)
session.addOutput(stillImageOutput)
self.setStillImageOutput(stillImageOutput)
Expand All @@ -198,13 +219,16 @@ def viewWillAppear(animated)

# dispatch_async([self sessionQueue], ^{
@sessionQueue.async {

NSLog("Setup a bunch of observers")

self.addObserver(self, forKeyPath:"sessionRunningAndDeviceAuthorized", options:(NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew), context:SessionRunningAndDeviceAuthorizedContext)

self.addObserver(self, forKeyPath:"stillImageOutput.capturingStillImage", options:(NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew), context:CapturingStillImageContext)

self.addObserver(self, forKeyPath:"movieFileOutput.recording", options:(NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew), context:RecordingContext)

NSNotificationCenter.defaultCenter.addObserver(self, selector:@selector(subjectAreaDidChange:), name:AVCaptureDeviceSubjectAreaDidChangeNotification, object:self.videoDeviceInput.device)
NSNotificationCenter.defaultCenter.addObserver(self, selector:"subjectAreaDidChange:", name:AVCaptureDeviceSubjectAreaDidChangeNotification, object:self.videoDeviceInput.device)

# __weak AVCamViewController *weakSelf = self;
self.setRuntimeErrorHandlingObserver(NSNotificationCenter.defaultCenter.addObserverForName(AVCaptureSessionRuntimeErrorNotification, object:self.session, queue:nil, usingBlock: -> note {
Expand All @@ -213,7 +237,7 @@ def viewWillAppear(animated)
@sessionQueue.async {
# Manually restarting the session since it must have been stopped due to an error.
self.session.startRunning
self.recordButton.setTitle("Record",forState(UIControlStateNormal))
self.recordButton.setTitle("Record", forState:UIControlStateNormal)
}
}.weak!))

Expand Down Expand Up @@ -257,30 +281,48 @@ def willRotateToInterfaceOrientation(toInterfaceOrientation, duration:duration)

def observeValueForKeyPath(keyPath, ofObject:object, change:change, context:context)

if context == CapturingStillImageContext
isCapturingStillImage = change[NSKeyValueChangeNewKey].boolValue
NSLog("Observed Value For Key Path: %@", keyPath)
# NSLog("context = %@", context[0])
NSLog("change = %@", change.to_s)

# if context == CapturingStillImageContext
if keyPath == "stillImageOutput.capturingStillImage"
isCapturingStillImage = Utils.boolValue(change[NSKeyValueChangeNewKey])
NSLog("CapturingStillImageContext, change New: %@", isCapturingStillImage.to_s)

# isCapturingStillImage = change["new"].nil?

if isCapturingStillImage
self.runStillImageCaptureAnimation
end
elsif context == RecordingContext
isRecording = change[NSKeyValueChangeNewKey].boolValue
# elsif context == RecordingContext
elsif keyPath == "movieFileOutput.recording"
isRecording = Utils.boolValue(change[NSKeyValueChangeNewKey])
NSLog("RecordingContext, change New: %@", isRecording.to_s)

# isRecording = change["new"].nil?

# dispatch_async(dispatch_get_main_queue(), ->{
Dispatch::Queue.main.async {
if isRecording
self.cameraButton.setEnabled(false)
self.recordButton.setTitle(NSLocalizedString("Stop", "Recording button stop title"), forState:UIControlStateNormal)
self.recordButton.setTitle("Stop", forState:UIControlStateNormal)
self.recordButton.setEnabled(true)
else
self.cameraButton.setEnabled(true)
self.recordButton.setTitle(NSLocalizedString("Record", "Recording button record title"), forState:UIControlStateNormal)
self.recordButton.setTitle("Record", forState:UIControlStateNormal)
self.recordButton.setEnabled(true)
end
} # main.async
elsif context == SessionRunningAndDeviceAuthorizedContext
isRunning = change[NSKeyValueChangeNewKey].boolValue
# elsif context == SessionRunningAndDeviceAuthorizedContext
elsif keyPath == "sessionRunningAndDeviceAuthorized"
isRunning = Utils.boolValue(change[NSKeyValueChangeNewKey])
NSLog("SessionRunningAndDeviceAuthorizedContext, change New: %@", isRunning.to_s)
# isRunning = change["new"].nil?


# isRunning = true

# dispatch_async(dispatch_get_main_queue(), ->{
Dispatch::Queue.main.async {
if isRunning
Expand All @@ -294,7 +336,8 @@ def observeValueForKeyPath(keyPath, ofObject:object, change:change, context:cont
end
} # main.async
else
super #.observeValueForKeyPath(keyPath, ofObject:object, change:change, context:context)
NSLog("Uh oh, not going to handle this properly")
# super #.observeValueForKeyPath(keyPath, ofObject:object, change:change, context:context)
end
end

Expand Down Expand Up @@ -400,12 +443,12 @@ def snapStillImage(sender)
# Capture a still image.
NSLog("Is this Block Correct?")

self.stillImageOutput.captureStillImageAsynchronouslyFromConnection(self.stillImageOutput.connectionWithMediaType(AVMediaTypeVideo), completionHandler: -> |imageDataSampleBuffer, error| {
self.stillImageOutput.captureStillImageAsynchronouslyFromConnection(self.stillImageOutput.connectionWithMediaType(AVMediaTypeVideo), completionHandler: -> imageDataSampleBuffer, error {

if imageDataSampleBuffer
imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer)
image = UIImage.alloc.initWithData(imageData)
ALAssetsLibrary.alloc.init.writeImageToSavedPhotosAlbum(image.CGImage,orientation(image.imageOrientation, completionBlock:nil))
ALAssetsLibrary.alloc.init.writeImageToSavedPhotosAlbum(image.CGImage, orientation:image.imageOrientation, completionBlock:nil)
end
})
} # end @sessionQueue.async
Expand All @@ -419,7 +462,7 @@ def focusAndExposeTap(gestureRecognizer)
end

def subjectAreaDidChange(notification)
devicePoint = CGPointMake(.5, .5)
devicePoint = CGPointMake(0.5, 0.5)
self.focusWithMode(AVCaptureFocusModeContinuousAutoFocus, exposeWithMode:AVCaptureExposureModeContinuousAutoExposure, atDevicePoint:devicePoint, monitorSubjectAreaChange:false)
end

Expand All @@ -439,15 +482,13 @@ def captureOutput(captureOutput, didFinishRecordingToOutputFileAtURL:outputFileU

self.setBackgroundRecordingID(UIBackgroundTaskInvalid)

ALAssetsLibrary.alloc.init.writeVideoAtPathToSavedPhotosAlbum(outputFileURL, completionBlock:-> |assetURL, error| {
ALAssetsLibrary.alloc.init.writeVideoAtPathToSavedPhotosAlbum(outputFileURL, completionBlock: -> assetURL, error {

if error
NSLog("%@", error)
NSLog("Error 84 - %@", error)
end

NSLog("Is this error correct?")
# NSFileManager.defaultManager.removeItemAtURL(outputFileURL, error.call(nil))
NSFileManager.defaultManager.removeItemAtURL(outputFileURL, error(nil))
NSFileManager.defaultManager.removeItemAtURL(outputFileURL, error:nil)

if backgroundRecordingID != UIBackgroundTaskInvalid
UIApplication.sharedApplication.endBackgroundTask(backgroundRecordingID)
Expand Down Expand Up @@ -525,7 +566,7 @@ def runStillImageCaptureAnimation
# dispatch_async(dispatch_get_main_queue(), ^{
Dispatch::Queue.main.async {
self.previewView.layer.setOpacity(0.0)
UIView.animateWithDuration(.25, animations: -> {
UIView.animateWithDuration(0.25, animations: -> {
self.previewView.layer.setOpacity(1.0)
})
}
Expand Down
20 changes: 20 additions & 0 deletions app/Utils.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
class Utils

def self.boolValue(val)
case val
when 0
return false
when 1
return true
when nil
return false
when true
return true
when false
return false
else
return false
end
end

end
2 changes: 1 addition & 1 deletion app/app_delegate.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
class AppDelegate
def application(application, didFinishLaunchingWithOptions:launchOptions)
welcomeViewController = WelcomeViewController.alloc.initWithNibName('WelcomeViewController', bundle:nil)
welcomeViewController = AVCamViewController.alloc.init #WithNibName('WelcomeViewController', bundle:nil)
navController = UINavigationController.alloc.initWithRootViewController(welcomeViewController)
@window = UIWindow.alloc.initWithFrame(UIScreen.mainScreen.bounds)
@window.rootViewController = navController
Expand Down

0 comments on commit 2cba7bb

Please sign in to comment.