Script.it .Nam Myoho Renghe Kyo.

Script.it
[Objective-C] Camera Class

Lately i’ve been working more and more on mobile IOS projects.
Within these projects i tend to use mobile camera’s alot. There are alot of
different camera frameworks / modules out there, but for the sake of knowing WTF is going on inside
those pieces of code, i am writing my own camera class.

This class uses AVFoundation.framework to setup all its camera assets.
capturedetail_2x














Here’s version 1, it supports:
- preview the camera feed
- take / save pictures
- record / save videos
- set focus modes
- set exposure modes
- set white balance modes
- set torch modes
- set flash modes
- set front facing camera
- set back facing camera

Below is implementation example:

?View Code OBJECTIVE-C
1
2
3
4
5
    Camera* camera = [[Camera alloc] init];                 //creates a camera instance
    [camera setQuality: CAMERA_QUALITY_HIGH];       //sets the camera's quality
    [camera setFrontCamera];                                     //sets the front facing camera
    [camera addOnView:self.view];                             //adds the camera preview to the view
    [camera start];                                                     //starts the camera feed



And here’s Camera the code:
Camera.h

?View Code OBJECTIVE-C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
//==========================================
//  Camera.h
//
//  Created by Rackdoll on 8/9/13.
//  Copyright (c) 2013 Script.it. All rights reserved.
//==========================================
 
#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
 
 
@interface Camera : NSObject <AVCaptureFileOutputRecordingDelegate>
 
extern NSString *const CAMERA_QUALITY_LOW;
extern NSString *const CAMERA_QUALITY_MEDIUM;
extern NSString *const CAMERA_QUALITY_HIGH;
extern NSString *const CAMERA_QUALITY_640x480;
extern NSString *const CAMERA_QUALITY_1280x720;
extern NSString *const CAMERA_QUALITY_FULL_PHOTO;
 
 
//blocks.
@property (copy) void (^assetsLibCompletionBlock)(NSURL*, NSError*);
 
 
//variables.
@property ( retain, nonatomic ) AVCaptureSession*           session;
@property ( retain, nonatomic ) AVCaptureDevice*            frontCamera;
@property ( retain, nonatomic ) AVCaptureDevice*            backCamera;
@property ( retain, nonatomic ) AVCaptureDevice*            captureDevice;
@property ( retain, nonatomic ) AVCaptureDeviceInput*       deviceInput;
@property ( retain, nonatomic ) AVCaptureDeviceInput*       frontDeviceInput;
@property ( retain, nonatomic ) AVCaptureDeviceInput*       backDeviceInput;
@property ( retain, nonatomic ) AVCaptureVideoPreviewLayer* previewLayer;
@property ( retain, nonatomic ) NSString *quality;
 
 
//capture outputs.
@property ( retain, nonatomic ) AVCaptureMovieFileOutput*  movieFileOutput;
@property ( retain, nonatomic ) AVCaptureStillImageOutput* imageFileOutput;
 
 
//methods.
-(id) init;
-(void) setup;
-(void) setFrontCamera;
-(void) setBackCamera;
-(void) addOnView:(UIView*)view;
-(void) start;
-(void) stop;
 
 
//----------------------------
// SETTINGS
//----------------------------
-(void) setQuality:(NSString *) sessionPreset;
-(void) setFocusMode:(int) mode;
-(void) setFocusMode:(int) mode andFocusPoint:(CGPoint) point;
-(void) setExposureMode:(int) mode;
-(void) setExposureMode:(int) mode andExposurePoint:(CGPoint) point;
-(void) setWhiteBalanceMode:(int) mode;
-(void) setFlashMode:(int) mode;
-(void) setTorchMode:(int) mode;
 
 
 
//----------------------------
// VIDEO
//----------------------------
//video capture setup methods.
-(void) setupVideoCaptureWithDuration:(Float64)totalSeconds;
-(void) setupVideoCaptureWithDuration:(Float64)totalSeconds andFPS:(int32_t) fps;
-(void) setupVideoCaptureWithDuration:(Float64)totalSeconds andFPS:(int32_t) fps andMinimumDiskspaceLimit:(int64_t) limit;
 
//video capture methods.
-(void) captureVideo:(NSString* )fileName;
 
 
//----------------------------
// PHOTO
//----------------------------
//photo capture setup methods.
-(void) setupStillImageCapture;
 
//photo capture methods.
-(void) captureStillImage:(NSString *)fileName;
-(void) captureStillImage:(NSString *)fileName andAttachToView:(UIView*)view;
 
@end



Camera.m

?View Code OBJECTIVE-C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
//=============================================================================
//=============================================================================
//  Camera.m
//
//  Created by Rackdoll on 8/9/13.
//  Copyright (c) 2013 Script.it. All rights reserved.
//
//  Description:
//  Camera controller which sets up all the camera components needed.
//
//
//  Dependancy:
//  AVFoundation.framework
//  CoreMedia.framework
//  AssetsLibrary.framework
//  CoreGraphics.framework
//  ImageIO.framework
//
//=============================================================================
//=============================================================================
#import "Camera.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <ImageIO/ImageIO.h>
 
#define CAPTURE_FRAMES_PER_SECOND		20
#define capturedSuccessfully            @"capturedSuccessfully"
 
NSString *const CAMERA_QUALITY_LOW        = @"AVCaptureSessionPresetLow";
NSString *const CAMERA_QUALITY_MEDIUM     = @"AVCaptureSessionPresetMedium";
NSString *const CAMERA_QUALITY_HIGH       = @"AVCaptureSessionPresetHigh";
NSString *const CAMERA_QUALITY_640x480    = @"AVCaptureSessionPreset640x480";
NSString *const CAMERA_QUALITY_1280x720   = @"AVCaptureSessionPreset1280x720";
NSString *const CAMERA_QUALITY_FULL_PHOTO = @"AVCaptureSessionPresetPhoto";
 
@implementation Camera
 
 
@synthesize session;
@synthesize captureDevice;
@synthesize deviceInput;
@synthesize frontDeviceInput;
@synthesize backDeviceInput;
@synthesize previewLayer;
@synthesize movieFileOutput;
@synthesize imageFileOutput;
@synthesize frontCamera;
@synthesize backCamera;
 
/**
 *
 *  Init
 *  Initializes all needed components
 *
 */
-(id) init {
    [self setup];
    return self;
}
 
/**
 *
 *  Start
 *  Starts the camera
 *
 */
-(void) start {
    [session startRunning];
}
 
/**
 *
 *  Stop
 *  Stop the camera
 *
 */
-(void) stop {
    [session stopRunning];
}
 
/**
 *
 *  Setup
 *  Initializes all needed components
 *
 */
-( void ) setup {
    // [0] -> first set handler blocks.
    [self configureBlocks];
 
    // [1] -> setup session;
    session = [[AVCaptureSession alloc] init];
   [self setQuality:AVCaptureSessionPresetLow];
 
    // [2] -> setup capture device;
    NSArray* devices = [AVCaptureDevice devices];
    for( AVCaptureDevice *device in devices){
        if([device hasMediaType:AVMediaTypeVideo]){
            if([device position] == AVCaptureDevicePositionFront) frontCamera = device;
            if([device position] == AVCaptureDevicePositionBack )  backCamera = device;
        }
    }
 
    // [3] -> setup camera;
    [self setFrontCamera];
 
    // [4] -> setup preview;
    previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
    [previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
}
 
/**
 *  Set Front Camera
 *  Sets the camera to front-facing camera.
 *
 */
-(void) setFrontCamera {
    frontDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:frontCamera error:nil];
    captureDevice    = frontCamera;
    for(AVCaptureDeviceInput *i in [session inputs] ) [session removeInput:i];
    if( [session canAddInput:frontDeviceInput])
        [session addInput:frontDeviceInput];
}
 
/**
 *  Set Back Camera
 *  Sets the camera to back-facing camera.
 *
 */
-(void) setBackCamera {
    backDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:backCamera error:nil];
    captureDevice = backCamera;
    for(AVCaptureDeviceInput *i in [session inputs] ) [session removeInput:i];
    if( [session canAddInput:backDeviceInput])
        [session addInput:backDeviceInput];
}
 
/**
 *  Configure Blocks 
 *  Initializes all needed handler blocks.
 *
 */
-(void) configureBlocks{
    //assets lib block:
    _assetsLibCompletionBlock = ^(NSURL* assetURL, NSError* error){
        if(error){
            NSLog(@"didFinishRecordingToOutputFileAtURL - error");
        }else{
            NSLog(@"didFinishRecordingToOutputFileAtURL - succes");
            [[NSNotificationCenter defaultCenter] postNotificationName:capturedSuccessfully object:nil];
        }
    };
}
 
/**
 *
 *  Add On View
 *  Adds the preview layer on a view.
 *
 *  @params: UIView - the view on which the preview layer will be added.
 *
 *
 */
-( void ) addOnView:(UIView*)view {
    CALayer *layer = [view layer];
    [layer setMasksToBounds:YES];
    [previewLayer setFrame:CGRectMake( view.bounds.origin.x, view.bounds.origin.y,
                                       view.bounds.size.width, view.bounds.size.height)];
    [layer insertSublayer:previewLayer atIndex:0];
}
 
//********************************************************************************************************************
//
//                     CAMERA SETTINGS SECTION
//
//--------------------------------------------------------------------------------------------------------------------
 
/**
*
*  Set Quality
*  Sets the session preset quality
*
*/
-(void) setQuality: (NSString *) sessionPreset {
    [session setSessionPreset:sessionPreset];
}
 
/**
 *
 *  Set Focus Mode
 *  Sets the focus mode.
 *
 *  0 -> AVCaptureFocusModeLocked
 *  1 -> AVCaptureFocusModeAutoFocus
 *  2 -> AVCaptureFocusModeContinuousAutoFocus
 *
 */
-(void) setFocusMode:(int) mode {
    [self setFocusMode:mode andFocusPoint:CGPointMake(0.5f, 0.5f)];
}
-(void) setFocusMode:(int) mode andFocusPoint:(CGPoint)focusPoint{
    if (![captureDevice isFocusModeSupported:mode]){
        NSLog(@"[ CAMERA ] ** FOCUS MODE NOT AVAILABLE! **");
        return;
    }
 
    NSError* error = nil;
    [captureDevice lockForConfiguration:&error];
    [captureDevice setFocusPointOfInterest:focusPoint];
    [captureDevice setFocusMode:mode];
    [captureDevice unlockForConfiguration];
}
 
 
/**
 *
 *  Set Exposure Mode
 *  Sets the exposure mode.
 *
 *  0 -> AVCaptureExposureModeLocked
 *  1 -> AVCaptureExposureModeAutoExpose
 *  2 -> AVCaptureExposureModeContinuousAutoExposure
 *
 */
-(void)setExposureMode:(int) mode {
    [self setExposureMode:mode andExposurePoint:CGPointMake(0.5f, 0.5f)];
}
-(void)setExposureMode:(int) mode andExposurePoint:(CGPoint)exposurePoint {
    if(![captureDevice isExposureModeSupported:mode]) {
        NSLog(@"[ CAMERA ] ** EXPOSURE MODE NOT AVAILABLE! **");
        return;
    }
 
    NSError* error = nil;
    [captureDevice lockForConfiguration:&error];
    [captureDevice setExposurePointOfInterest:exposurePoint];
    [captureDevice setExposureMode:mode];
    [captureDevice unlockForConfiguration];
}
 
/**
 *
 *  Set White Balance Mode
 *  Sets the white balance mode.
 *
 *  0 -> AVCaptureWhiteBalanceModeLocked
 *  1 -> AVCaptureWhiteBalanceModeContinuousAutoWhiteBalance
 *
 */
-(void)setWhiteBalanceMode:(int) mode {
    if(![captureDevice isWhiteBalanceModeSupported:mode]) {
        NSLog(@"[ CAMERA ] ** WHITE BALANCE MODE NOT AVAILABLE! **");
        return;
    }
 
    NSError* error = nil;
    [captureDevice lockForConfiguration:&error];
    [captureDevice setWhiteBalanceMode:mode];
    [captureDevice unlockForConfiguration];
}
 
/**
 *
 *  Set Flash Mode
 *  Sets the flash mode.
 *
 *  0 -> AVCaptureFlashModeOff
 *  1 -> AVCaptureFlashModeOn
 *  2 -> AVCaptureFlashModeAuto
 *
 */
-(void)setFlashMode:(int) mode {
    if(![captureDevice isFlashModeSupported:mode] || ![captureDevice isFlashAvailable] || ![captureDevice hasFlash]){
        NSLog(@"[ CAMERA ] ** FLASH MODE NOT AVAILABLE! **");
        return;
    }
 
    NSError* error = nil;
    [captureDevice lockForConfiguration:&error];
    [captureDevice setFlashMode:mode];
    [captureDevice unlockForConfiguration];
}
 
/**
 *
 *  Set Torch Mode
 *  Sets the torch mode.
 *
 *  0 -> AVCaptureTorchModeOff
 *  1 -> AVCaptureTorchModeOn
 *  2 -> AVCaptureTorchModeAuto
 *
 */
-(void)setTorchMode:(int) mode {
    if(![captureDevice isTorchAvailable] || ![captureDevice isTorchModeSupported:mode] || ![captureDevice hasTorch]) {
        NSLog(@"[ CAMERA ] ** TORCH MODE NOT AVAILABLE! **");
        return;
    }
    NSError* error = nil;
    [captureDevice lockForConfiguration:&error];
    [captureDevice setTorchMode:mode];
    [captureDevice unlockForConfiguration];
}
 
//********************************************************************************************************************
//
//                      PHOTO CAPTURE SECTION
//
//--------------------------------------------------------------------------------------------------------------------
 
/**
 *
 *  Setup Still Image Capture
 *  Sets up a still image capture
 *
 *  @params: None.
 *
 */
 
-(void) setupStillImageCapture {
    if(imageFileOutput == nil ) imageFileOutput = [[AVCaptureStillImageOutput alloc] init];
    NSDictionary* outputSettings = @{AVVideoCodecKey: AVVideoCodecJPEG};
    [imageFileOutput setOutputSettings:outputSettings];
 
    //add output to the session.
    if( [session canAddOutput:imageFileOutput])
        [session addOutput: imageFileOutput];
}
 
/**
 *
 *  Capture Still Image
 *  Captures a still image
 *
 *  @params: NSString - fileName: designated filename.
 *
 */
-(void) captureStillImage:(NSString *)fileName{
    [self captureStillImage:fileName andAttachToView:nil];
}
-(void) captureStillImage:(NSString *)fileName andAttachToView:(UIView*)view{
    AVCaptureConnection* captureConnection;
    for( AVCaptureConnection* connection in [[self imageFileOutput] connections] ){
        for( AVCaptureInputPort* port in [connection inputPorts]){
            if( [[port mediaType] isEqual:AVMediaTypeVideo]){
                captureConnection = connection;
                break;
            }
        }
    }
    __weak typeof(self) weakSelf = self;
    [imageFileOutput captureStillImageAsynchronouslyFromConnection:captureConnection
                                                 completionHandler:^( CMSampleBufferRef imageDataSampleBuffer, NSError* error) {
                                                     NSData* imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
                                                     UIImage* image    = [[UIImage alloc] initWithData: imageData];
 
                                                     if(view != nil){
                                                         UIImageView* iv = [[UIImageView alloc] initWithImage:image];
                                                         iv.frame        = view.bounds;
                                                         [view addSubview:iv];
                                                     }
 
                                                     ALAssetsLibrary* library = [[ALAssetsLibrary alloc] init];
                                                     [library writeImageToSavedPhotosAlbum:[image CGImage]
                                                                               orientation:(ALAssetOrientation)[image imageOrientation]
                                                                           completionBlock: weakSelf.assetsLibCompletionBlock];
                                                 }
     ];
}
 
//********************************************************************************************************************
//
//                      VIDEO CAPTURE SECTION
//
//--------------------------------------------------------------------------------------------------------------------
 
/**
 *
 *  Setup Video Capture
 *  Sets up a video capture
 *
 *  @params: Float64 - totalSeconds: duration of the capture
 *           int32_t - fps         : Frames per second             ( Optional, default = 30          )
 *           int64_t - limit       : minimum diskspace requirement ( Optional, default = 1024 * 1024 )
 *
 */
-(void) setupVideoCaptureWithDuration:(Float64)totalSeconds{
    [self setupVideoCaptureWithDuration:totalSeconds andFPS:30 andMinimumDiskspaceLimit:1024*1024];
}
-(void) setupVideoCaptureWithDuration:(Float64)totalSeconds andFPS:(int32_t) fps {
    [self setupVideoCaptureWithDuration:totalSeconds andFPS:fps andMinimumDiskspaceLimit:1024*1024];
}
-(void) setupVideoCaptureWithDuration:(Float64)totalSeconds andFPS:(int32_t) fps andMinimumDiskspaceLimit:(int64_t) limit  {
    //make capture output.
    if( movieFileOutput == nil ) movieFileOutput = [[AVCaptureMovieFileOutput alloc] init];
    CMTime maxDuration = CMTimeMakeWithSeconds(totalSeconds, fps);
    movieFileOutput.maxRecordedDuration   = maxDuration;
    movieFileOutput.minFreeDiskSpaceLimit = limit;
 
     //add output to the session.
    if( [session canAddOutput:movieFileOutput])
        [session addOutput: movieFileOutput];
 
 
    //set camera output properties - > framerate.
    AVCaptureConnection* captureConnection = [movieFileOutput connectionWithMediaType:AVMediaTypeVideo];
    CMTimeShow( captureConnection.videoMinFrameDuration );  
    CMTimeShow( captureConnection.videoMaxFrameDuration );  
    if( captureConnection.supportsVideoMinFrameDuration)
        captureConnection.videoMinFrameDuration = CMTimeMake( 1, CAPTURE_FRAMES_PER_SECOND );
    if( captureConnection.supportsVideoMaxFrameDuration)
        captureConnection.videoMaxFrameDuration = CMTimeMake( 1, CAPTURE_FRAMES_PER_SECOND );
 
    CMTimeShow( captureConnection.videoMinFrameDuration);
    CMTimeShow( captureConnection.videoMaxFrameDuration);
}
 
/**
 *
 *  Capture Video
 *  Captures a video
 *
 *  @params: NSString - fileName: name of the video file to be saved.
 *
 */
-(void) captureVideo:(NSString * ) fileName {
    NSString* outputPATH = [[NSString alloc] initWithFormat:@"%@%@", NSTemporaryDirectory(), fileName];
    NSURL*    outputURL  = [[NSURL alloc] initFileURLWithPath:outputPATH];
    NSFileManager* fileManager = [NSFileManager defaultManager];
    if( [fileManager fileExistsAtPath:outputPATH] ){
        NSError* error;
        if([fileManager removeItemAtPath:outputPATH error:&error] == NO){
            //HANDLE ERROR - if required
        }
    }
    //start recording:
    [movieFileOutput startRecordingToOutputFileURL:outputURL recordingDelegate:self];
    outputURL  = nil;
    outputPATH = nil;
}
 
//recording handlers.
-(void) captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error {
    BOOL succes = YES;
    if([error code] != noErr){
        id value = [[error userInfo] objectForKey:AVErrorRecordingSuccessfullyFinishedKey];
        if(value) succes = [value boolValue];
    }
    if(succes){
        NSLog(@"didFinishRecordingToOutputFileAtURL - succes");
        ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
        if([library videoAtPathIsCompatibleWithSavedPhotosAlbum:outputFileURL]){
            [library writeVideoAtPathToSavedPhotosAlbum:outputFileURL
                                        completionBlock:_assetsLibCompletionBlock];
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:capturedSuccessfully object:nil];
    }else{
        //error!
         NSLog(@"didFinishRecordingToOutputFileAtURL - error");
    }
}
@end



Happy Coding!
\o
Rackdoll

Creative Commons License
[Objective-C] Camera Class by Script.it, unless otherwise expressly stated, is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 Netherlands License.

Comments are closed.

Categories
Archives
Live Supporters