Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixes and additions #10

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 18 additions & 3 deletions ASScreenRecorder/ASScreenRecorder.h
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,31 @@ typedef void (^VideoCompletionBlock)(void);
@interface ASScreenRecorder : NSObject
@property (nonatomic, readonly) BOOL isRecording;

// delegate is only required when implementing ASScreenRecorderDelegate - see below
/*
*delegate is only required when implementing ASScreenRecorderDelegate - see below
*/
@property (nonatomic, weak) id <ASScreenRecorderDelegate> delegate;

// if saveURL is nil, video will be saved into camera roll
// this property can not be changed whilst recording is in progress
/**
* if saveURL is nil, video will be saved into camera roll
* this property can not be changed whilst recording is in progress
*/
@property (strong, nonatomic) NSURL *videoURL;

@property (nonatomic, getter = isPaused) BOOL paused;

/**
* Default value is 60.
* Set this property before calling -startRecording;
*/
@property (nonatomic) NSInteger fps;

+ (instancetype)sharedInstance;
- (BOOL)startRecording;
- (void)pauseRecording;
- (void)resumeRecording;
- (void)stopRecordingWithCompletion:(VideoCompletionBlock)completionBlock;

@end


Expand Down
70 changes: 69 additions & 1 deletion ASScreenRecorder/ASScreenRecorder.m
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@
#import <QuartzCore/QuartzCore.h>
#import <AssetsLibrary/AssetsLibrary.h>

#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)

@interface ASScreenRecorder()
@property (strong, nonatomic) AVAssetWriter *videoWriter;
@property (strong, nonatomic) AVAssetWriterInput *videoWriterInput;
Expand All @@ -19,6 +22,9 @@ @interface ASScreenRecorder()
@property (strong, nonatomic) NSDictionary *outputBufferPoolAuxAttributes;
@property (nonatomic) CFTimeInterval firstTimeStamp;
@property (nonatomic) BOOL isRecording;

@property (strong, nonatomic) NSMutableArray *pauseResumeTimeRanges;

@end

@implementation ASScreenRecorder
Expand Down Expand Up @@ -63,6 +69,7 @@ - (instancetype)init
dispatch_set_target_queue(_render_queue, dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_HIGH, 0));
_frameRenderingSemaphore = dispatch_semaphore_create(1);
_pixelAppendSemaphore = dispatch_semaphore_create(1);
_fps = 60;
}
return self;
}
Expand All @@ -81,20 +88,54 @@ - (BOOL)startRecording
[self setUpWriter];
_isRecording = (_videoWriter.status == AVAssetWriterStatusWriting);
_displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(writeVideoFrame)];
_displayLink.frameInterval = 60 / self.fps;
[_displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
}
return _isRecording;
}

- (void)pauseRecording
{
if (_displayLink.paused) {
return;
}

if (!self.pauseResumeTimeRanges) {
self.pauseResumeTimeRanges = [NSMutableArray new];
}

[self.pauseResumeTimeRanges addObject:@(_displayLink.timestamp + 0.001)]; //adding a small delay

_displayLink.paused = YES;
}

- (void)resumeRecording
{
if (_displayLink && _displayLink.isPaused) {
_displayLink.paused = NO;
}
}

- (void)stopRecordingWithCompletion:(VideoCompletionBlock)completionBlock;
{
if (_isRecording) {
_isRecording = NO;
[_displayLink removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
[self completeRecordingSession:completionBlock];
self.pauseResumeTimeRanges = nil;
}
}

- (BOOL)isPaused
{
return _displayLink.paused;
}

- (void)setPaused:(BOOL)paused
{
[self pauseRecording];
}

#pragma mark - private

-(void)setUpWriter
Expand Down Expand Up @@ -231,10 +272,21 @@ - (void)writeVideoFrame
dispatch_async(_render_queue, ^{
if (![_videoWriterInput isReadyForMoreMediaData]) return;

if (self.pauseResumeTimeRanges.count % 2 != 0) {
[self.pauseResumeTimeRanges addObject:@(_displayLink.timestamp)];
}

if (!self.firstTimeStamp) {
self.firstTimeStamp = _displayLink.timestamp;
}
CFTimeInterval elapsed = (_displayLink.timestamp - self.firstTimeStamp);
if (self.pauseResumeTimeRanges.count) {
for (int i = 0; i < self.pauseResumeTimeRanges.count; i += 2) {
double pausedTime = [self.pauseResumeTimeRanges[i] doubleValue];
double resumeTime = [self.pauseResumeTimeRanges[i+1] doubleValue];
elapsed -= resumeTime - pausedTime;
}
}
CMTime time = CMTimeMakeWithSeconds(elapsed, 1000);

CVPixelBufferRef pixelBuffer = NULL;
Expand All @@ -243,12 +295,20 @@ - (void)writeVideoFrame
if (self.delegate) {
[self.delegate writeBackgroundFrameInContext:&bitmapContext];
}

CGFloat width = _viewSize.width;
CGFloat height = _viewSize.height;
if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8") && UIInterfaceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation)) {
width = MAX(_viewSize.width, _viewSize.height);
height = MIN(_viewSize.width, _viewSize.height);
}

// draw each window into the context (other windows include UIKeyboard, UIAlert)
// FIX: UIKeyboard is currently only rendered correctly in portrait orientation
dispatch_sync(dispatch_get_main_queue(), ^{
UIGraphicsPushContext(bitmapContext); {
for (UIWindow *window in [[UIApplication sharedApplication] windows]) {
[window drawViewHierarchyInRect:CGRectMake(0, 0, _viewSize.width, _viewSize.height) afterScreenUpdates:NO];
[window drawViewHierarchyInRect:CGRectMake(0, 0, width, height) afterScreenUpdates:NO];
}
} UIGraphicsPopContext();
});
Expand Down Expand Up @@ -295,6 +355,14 @@ - (CGContextRef)createPixelBufferAndBitmapContext:(CVPixelBufferRef *)pixelBuffe
CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, _viewSize.height);
CGContextConcatCTM(bitmapContext, flipVertical);

if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8") && UIInterfaceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation)) {
CGContextRotateCTM(bitmapContext, M_PI_2);
CGContextTranslateCTM(bitmapContext, 0, -_viewSize.width);
}
if(SYSTEM_VERSION_LESS_THAN(@"8") && [UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationLandscapeLeft) {
CGContextRotateCTM(bitmapContext, M_PI);
}

return bitmapContext;
}

Expand Down
31 changes: 23 additions & 8 deletions ExampleRecorder/ExampleRecorder/Base.lproj/Main.storyboard
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="5056" systemVersion="13C64" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" initialViewController="rS3-R9-Ivy">
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="7702" systemVersion="14D136" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" initialViewController="rS3-R9-Ivy">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="3733"/>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="7701"/>
</dependencies>
<scenes>
<!--Navigation Controller-->
Expand All @@ -19,20 +20,34 @@
</objects>
<point key="canvasLocation" x="-1" y="64"/>
</scene>
<!--Master View Controller - Master-->
<!--Master-->
<scene sceneID="VgW-fR-Quf">
<objects>
<tableViewController title="Master" id="pGg-6v-bdr" customClass="MasterViewController" sceneMemberID="viewController">
<tableView key="view" opaque="NO" clipsSubviews="YES" clearsContextBeforeDrawing="NO" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="none" showsSelectionImmediatelyOnTouchBegin="NO" rowHeight="44" sectionHeaderHeight="22" sectionFooterHeight="22" id="mLL-gJ-YKr">
<rect key="frame" x="0.0" y="0.0" width="320" height="568"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
<textView key="tableHeaderView" clipsSubviews="YES" userInteractionEnabled="NO" contentMode="scaleToFill" bounces="NO" scrollEnabled="NO" showsHorizontalScrollIndicator="NO" showsVerticalScrollIndicator="NO" editable="NO" text="Double tap anywhere on screen to start/stop screen recording" textAlignment="center" selectable="NO" id="qoy-MK-6zP">
<rect key="frame" x="0.0" y="64" width="320" height="64"/>
<textView key="tableHeaderView" clipsSubviews="YES" userInteractionEnabled="NO" contentMode="scaleToFill" bounces="NO" scrollEnabled="NO" showsHorizontalScrollIndicator="NO" showsVerticalScrollIndicator="NO" editable="NO" usesAttributedText="YES" selectable="NO" id="qoy-MK-6zP">
<rect key="frame" x="0.0" y="64" width="320" height="141"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<color key="backgroundColor" red="0.2356791198" green="0.39178222419999997" blue="0.49372842909999998" alpha="1" colorSpace="calibratedRGB"/>
<color key="textColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
<fontDescription key="fontDescription" type="boldSystem" pointSize="19"/>
<attributedString key="attributedText">
<fragment content="Double tap anywhere on screen to start/stop screen recording

">
<attributes>
<color key="NSColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
<font key="NSFont" size="19" name="HelveticaNeue"/>
<paragraphStyle key="NSParagraphStyle" alignment="center" lineBreakMode="wordWrapping" baseWritingDirection="natural"/>
</attributes>
</fragment>
<fragment content="Long press anywhere on screen to pause/resume screen recording">
<attributes>
<color key="NSColor" red="0.17020456414473681" green="1" blue="1" alpha="1" colorSpace="calibratedRGB"/>
<font key="NSFont" size="19" name="HelveticaNeue"/>
<paragraphStyle key="NSParagraphStyle" alignment="center" lineBreakMode="wordWrapping" baseWritingDirection="natural"/>
</attributes>
</fragment>
</attributedString>
<textInputTraits key="textInputTraits" autocapitalizationType="sentences"/>
</textView>
<prototypes>
Expand Down Expand Up @@ -67,7 +82,7 @@
</objects>
<point key="canvasLocation" x="459" y="64"/>
</scene>
<!--Detail View Controller - Detail-->
<!--Detail-->
<scene sceneID="Cn3-H9-jdl">
<objects>
<viewController title="Detail" id="Ah7-4n-0Wa" customClass="DetailViewController" sceneMemberID="viewController">
Expand Down
27 changes: 27 additions & 0 deletions ExampleRecorder/ExampleRecorder/UIViewController+ScreenRecorder.m
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ - (void)prepareScreenRecorder;
tapGesture.numberOfTapsRequired = 2;
tapGesture.delaysTouchesBegan = YES;
[self.view addGestureRecognizer:tapGesture];

UILongPressGestureRecognizer *longGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
[self.view addGestureRecognizer:longGesture];
}

- (void)recorderGesture:(UIGestureRecognizer *)recognizer
Expand All @@ -36,6 +39,30 @@ - (void)recorderGesture:(UIGestureRecognizer *)recognizer
}
}

- (void)handleLongPress:(UILongPressGestureRecognizer *)recognizer
{
ASScreenRecorder *recorder = [ASScreenRecorder sharedInstance];

if (!recorder.isRecording) {
return;
}

if (recognizer.state != UIGestureRecognizerStateBegan) {
return;
}


if (recorder.isPaused) {
[recorder resumeRecording];
NSLog(@"Resume recording");
[self playStartSound];
} else {
[recorder pauseRecording];
NSLog(@"Pause recording");
[self playStartSound];
}
}

- (void)playStartSound
{
NSURL *url = [NSURL URLWithString:@"/System/Library/Audio/UISounds/begin_record.caf"];
Expand Down