-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRSVideoViewController.m
More file actions
446 lines (375 loc) · 14.1 KB
/
Copy pathRSVideoViewController.m
File metadata and controls
446 lines (375 loc) · 14.1 KB
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
//
//
// RSVideoViewController
//
// Created by Sheldon Thomas on 6/24/12.
// Copyright (c) 2012 Resplendent G.P. All rights reserved.
//
#import "RSVideoViewController.h"
#import "UIImage+Extensions.h"
@interface RSVideoViewController ()
@end
@implementation RSVideoViewController
@synthesize delegate = _delegate;
@synthesize isFront;
-(CGRect)video_previewLayerFrame
{
return _previewLayer.frame;
}
- (UIImage*)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection
{
CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
/*Lock the image buffer*/
CVPixelBufferLockBaseAddress(imageBuffer,0);
/*Get information about the image*/
uint8_t *baseAddress = (uint8_t *)CVPixelBufferGetBaseAddress(imageBuffer);
size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
size_t width = CVPixelBufferGetWidth(imageBuffer);
size_t height = CVPixelBufferGetHeight(imageBuffer);
/*We unlock the image buffer*/
CVPixelBufferUnlockBaseAddress(imageBuffer,0);
/*Create a CGImageRef from the CVImageBufferRef*/
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef newContext = CGBitmapContextCreate(baseAddress, width, height, 8, bytesPerRow, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst);
CGImageRef newImage = CGBitmapContextCreateImage(newContext);
/*We release some components*/
CGContextRelease(newContext);
CGColorSpaceRelease(colorSpace);
/*We display the result on the custom layer*/
/*self.customLayer.contents = (id) newImage;*/
/*We display the result on the image view (We need to change the orientation of the image so that the video is displayed correctly)*/
UIImage *image= [UIImage imageWithCGImage:newImage scale:1.0 orientation:UIImageOrientationRight];
/*We relase the CGImageRef*/
CGImageRelease(newImage);
return image;
}
- (UIImage *) imageFromSampleBuffer:(CMSampleBufferRef) sampleBuffer
{
// Get a CMSampleBuffer's Core Video image buffer for the media data
CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
// Lock the base address of the pixel buffer
CVPixelBufferLockBaseAddress(imageBuffer, 0);
// Get the number of bytes per row for the pixel buffer
void *baseAddress = CVPixelBufferGetBaseAddress(imageBuffer);
// Get the number of bytes per row for the pixel buffer
size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
// Get the pixel buffer width and height
size_t width = CVPixelBufferGetWidth(imageBuffer);
size_t height = CVPixelBufferGetHeight(imageBuffer);
// Create a device-dependent RGB color space
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
// Create a bitmap graphics context with the sample buffer data
CGContextRef context = CGBitmapContextCreate(baseAddress, width, height, 8,
bytesPerRow, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst);
// Create a Quartz image from the pixel data in the bitmap graphics context
CGImageRef quartzImage = CGBitmapContextCreateImage(context);
// Unlock the pixel buffer
CVPixelBufferUnlockBaseAddress(imageBuffer,0);
// Free up the context and color space
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
// Create an image object from the Quartz image
UIImage *image = [UIImage imageWithCGImage:quartzImage];
// Release the Quartz image
CGImageRelease(quartzImage);
return (image);
}
-(void)doRecycle
{
_videoConnection = nil;
for (AVCaptureConnection *connection in stillOutput.connections) {
for (AVCaptureInputPort *port in [connection inputPorts]) {
if ([[port mediaType] isEqual:AVMediaTypeVideo] ) {
_videoConnection = connection;
break;
}
}
if (_videoConnection) { break; }
}
}
-(void)recycleConnection
{
if ([_videoConnection respondsToSelector:@selector(isActive)])
{
if (![_videoConnection isActive])
{
[self doRecycle];
}
}
}
-(void)captureImageWithCompletionBlock:(void(^)(BOOL completed))completion
{
[self doRecycle];
if (_videoConnection)
{
[stillOutput captureStillImageAsynchronouslyFromConnection:_videoConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error){
if (error)
[_delegate cameraCaptureDidFail:self andError:error];
else
{
NSData* imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
// UIImage* i = [self imageFromSampleBuffer:imageDataSampleBuffer];
UIImage* i = [UIImage imageWithData:imageData];
[_delegate cameraCaptureDidFinish:self withImage:i];
}
if (completion)
completion(YES);
}];
}
else
{
[_delegate cameraCaptureDidFail:self andError:[NSError errorWithDomain:NSInternalInconsistencyException code:200 userInfo:@{@"reason": @"encountered a nil video connection"}]];
if (completion)
completion(NO);
}
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:@"adjustingExposure"])
{
if ([[change objectForKey:@"new"] intValue])
{
// NSLog(@"Started Exposure");
}
else
{
// NSLog(@"Ending Exposure");
}
}
else if ([keyPath isEqualToString:@"adjustingFocus"])
{
if ([[change objectForKey:@"new"] intValue])
{
// NSLog(@"Started Focus");
}
else
{
[_backCamera lockForConfiguration:nil];
[_backCamera setFocusMode:AVCaptureFocusModeContinuousAutoFocus];
[_backCamera unlockForConfiguration];
// NSLog(@"End Focus, Locked.");
}
}
else
NSLog(@"Odd Keypath %@", keyPath);
}
-(void)switchCameras
{
if (isFront)
{ // go to the back camera
if (!_backCamera)
{
_backCamera = [self get_backCamera];
NSError* e = nil;
_backCameraInput = [AVCaptureDeviceInput deviceInputWithDevice:_backCamera error:&e];
}
if (_backCameraInput)
{
if ([[session inputs] containsObject:_frontCameraInput])
[session removeInput:_frontCameraInput];
[session addInput:_backCameraInput];
}
}
else
{ // go to the front facing camera
if (!_frontCamera)
{
_frontCamera = [self get_frontCamera];
NSError* e = nil;
_frontCameraInput = [AVCaptureDeviceInput deviceInputWithDevice:_frontCamera error:&e];
if (e)
NSLog(@"Error initalizing the Front Camera Capture Device");
}
if (_frontCameraInput)
{
if ([[session inputs] containsObject:_backCameraInput])
[session removeInput:_backCameraInput];
[session addInput:_frontCameraInput];
}
}
isFront = !isFront;
}
-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
CGSize _screenSize = [[UIScreen mainScreen]bounds].size;
if (_screenSize.height > 480)
{
_barHeight = 96.0f;
}
else
{
_barHeight = 53.0f;
}
}
return self;
}
- (void)viewDidLoad
{
[self.view setBackgroundColor:[UIColor clearColor]];
session = [AVCaptureSession new];
if ([session canSetSessionPreset:AVCaptureSessionPresetPhoto])
[session setSessionPreset:AVCaptureSessionPresetPhoto];
_backCamera = [self get_backCamera];
if ([_backCamera respondsToSelector:@selector(isLowLightBoostSupported)])
{
if ([_backCamera isLowLightBoostSupported])
{
NSError* e = nil;
[_backCamera lockForConfiguration:&e];
if (e) @throw e;
[_backCamera setAutomaticallyEnablesLowLightBoostWhenAvailable:YES];
[_backCamera unlockForConfiguration];
}
}
NSError* e;
if (_backCamera)
{
_backCameraInput = [AVCaptureDeviceInput deviceInputWithDevice:_backCamera error:&e];
if (e) @throw e;
if ([session canAddInput:_backCameraInput])
[session addInput:_backCameraInput];
}
stillOutput = [AVCaptureStillImageOutput new];
// NSDictionary *outputSettings = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithUnsignedInt:kCVPixelFormatType_32BGRA], (id)kCVPixelBufferPixelFormatTypeKey, nil];
NSDictionary* newOutput = @{[NSNumber numberWithUnsignedInt:kCVPixelFormatType_32BGRA] : (id)kCVPixelBufferPixelFormatTypeKey, AVVideoCodecJPEG : AVVideoCodecKey};
[stillOutput setOutputSettings:newOutput];
if ([session canAddOutput:stillOutput])
[session addOutput:stillOutput];
CGRect previewFrame = self.view.frame;
/*
Adjust the position of the preview frame
*/
CGRect bounds = CGRectMake(0, 0, 320, self.view.frame.size.height - _barHeight);
// CGRect bounds = self.view.bounds;
_previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:session];
[_previewLayer setFrame:previewFrame];
_previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
_previewLayer.bounds = bounds;
_previewLayer.position=CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds));
[self.view.layer addSublayer:_previewLayer];
[self doRecycle];
isFront = NO;
[super viewDidLoad];
}
-(void)viewDidAppear:(BOOL)animated
{
[self setEnableCameraCapture:YES];
[super viewDidAppear:animated];
}
-(BOOL)setCaptureFlashMode:(AVCaptureFlashMode)mode
{
if ([_backCamera isFlashModeSupported:mode])
{
NSError* e = nil;
[_backCamera lockForConfiguration:&e];
if (e)
return NO;
else
{
[_backCamera setFlashMode:mode];
return YES;
}
}
else
return NO;
}
-(AVCaptureDevice*)get_backCamera
{
NSArray* devices = [AVCaptureDevice devices];
for (AVCaptureDevice* device in devices) {
if ([device position] == AVCaptureDevicePositionBack)
{
if ([device isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeContinuousAutoWhiteBalance])
{
[device lockForConfiguration:nil];
[device setWhiteBalanceMode:AVCaptureWhiteBalanceModeContinuousAutoWhiteBalance];
if ([device isFocusModeSupported:AVCaptureFocusModeContinuousAutoFocus])
[device setFocusMode:AVCaptureFocusModeContinuousAutoFocus];
[device unlockForConfiguration];
}
// if ([device isExposureModeSupported:AVCaptureExposureModeLocked])
// NSLog(@"AVCaptureExposureModeLocked");
// if ([device isExposureModeSupported:AVCaptureExposureModeContinuousAutoExposure])
// NSLog(@"AVCaptureExposureModeContinuousAutoExposure");
// if ([device isExposureModeSupported:AVCaptureExposureModeAutoExpose])
// NSLog(@"AVCaptureExposureModeAutoExpose");
[device addObserver:self forKeyPath:@"adjustingExposure" options:NSKeyValueObservingOptionNew context:nil];
[device addObserver:self forKeyPath:@"adjustingFocus" options:NSKeyValueObservingOptionNew context:nil];
return device;
}
}
return nil;
}
-(AVCaptureDevice*)get_frontCamera
{
NSArray* devices = [AVCaptureDevice devices];
for (AVCaptureDevice* device in devices) {
if ([device position] == AVCaptureDevicePositionFront)
return device;
}
return nil;
}
-(void)cameraFocusAtPoint:(CGPoint)point
{
AVCaptureDevice* captureDevice;
if ([[session inputs] containsObject:_frontCameraInput])
captureDevice = _frontCamera;
else
captureDevice = _backCamera;
if ([captureDevice isFocusPointOfInterestSupported] && [captureDevice isFocusModeSupported:AVCaptureFocusModeAutoFocus] && [captureDevice isExposurePointOfInterestSupported])
{
NSError* e = nil;
if ([captureDevice lockForConfiguration:&e])
{
if (e)
{NSLog(@"ERROR %@", e);return;}
if ([captureDevice isExposurePointOfInterestSupported] && [captureDevice isExposureModeSupported:AVCaptureExposureModeContinuousAutoExposure])
{
[captureDevice setExposurePointOfInterest:point];
[captureDevice setExposureMode:AVCaptureExposureModeContinuousAutoExposure];
}
if ([captureDevice isFocusPointOfInterestSupported])
{
[captureDevice setFocusPointOfInterest:point];
[captureDevice setFocusMode:AVCaptureFocusModeAutoFocus];
}
[captureDevice unlockForConfiguration];
}
}
}
- (void)viewDidUnload
{
[self setEnableCameraCapture:NO];
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
#pragma mark - Setter/Getter methods
-(BOOL)enableCameraCapture
{
return session.isRunning;
}
-(void)setEnableCameraCapture:(BOOL)enableCameraCapture
{
if (self.enableCameraCapture == enableCameraCapture)
return;
if (enableCameraCapture)
{
[session startRunning];
}
else
{
[session stopRunning];
}
}
-(void)dealloc
{
[_backCamera removeObserver:self forKeyPath:@"adjustingExposure"];
[_backCamera removeObserver:self forKeyPath:@"adjustingFocus"];
}
@end