CvAbstractCamera2.mm 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. //
  2. // CvAbstractCamera2.mm
  3. //
  4. // Created by Giles Payne on 2020/04/01.
  5. //
  6. #import "CvCamera2.h"
  7. #pragma mark - Private Interface
  8. @interface CvAbstractCamera2 ()
  9. @property (nonatomic, strong) AVCaptureVideoPreviewLayer* captureVideoPreviewLayer;
  10. - (void)deviceOrientationDidChange:(NSNotification*)notification;
  11. - (void)startCaptureSession;
  12. - (void)setDesiredCameraPosition:(AVCaptureDevicePosition)desiredPosition;
  13. - (void)updateSize;
  14. @end
  15. #pragma mark - Implementation
  16. @implementation CvAbstractCamera2
  17. #pragma mark - Constructors
  18. - (id)init;
  19. {
  20. self = [super init];
  21. if (self) {
  22. // react to device orientation notifications
  23. [[NSNotificationCenter defaultCenter] addObserver:self
  24. selector:@selector(deviceOrientationDidChange:)
  25. name:UIDeviceOrientationDidChangeNotification
  26. object:nil];
  27. [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
  28. self.currentDeviceOrientation = [[UIDevice currentDevice] orientation];
  29. // check if camera available
  30. self.cameraAvailable = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
  31. NSLog(@"camera available: %@", (self.cameraAvailable ? @"YES" : @"NO") );
  32. _running = NO;
  33. // set camera default configuration
  34. self.defaultAVCaptureDevicePosition = AVCaptureDevicePositionFront;
  35. self.defaultAVCaptureVideoOrientation = AVCaptureVideoOrientationLandscapeLeft;
  36. self.defaultFPS = 15;
  37. self.defaultAVCaptureSessionPreset = AVCaptureSessionPreset352x288;
  38. self.parentView = nil;
  39. self.useAVCaptureVideoPreviewLayer = NO;
  40. }
  41. return self;
  42. }
  43. - (id)initWithParentView:(UIView*)parent;
  44. {
  45. self = [super init];
  46. if (self) {
  47. // react to device orientation notifications
  48. [[NSNotificationCenter defaultCenter] addObserver:self
  49. selector:@selector(deviceOrientationDidChange:)
  50. name:UIDeviceOrientationDidChangeNotification
  51. object:nil];
  52. [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
  53. self.currentDeviceOrientation = [[UIDevice currentDevice] orientation];
  54. // check if camera available
  55. self.cameraAvailable = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
  56. NSLog(@"camera available: %@", (self.cameraAvailable ? @"YES" : @"NO") );
  57. _running = NO;
  58. // set camera default configuration
  59. self.defaultAVCaptureDevicePosition = AVCaptureDevicePositionFront;
  60. self.defaultAVCaptureVideoOrientation = AVCaptureVideoOrientationLandscapeLeft;
  61. self.defaultFPS = 15;
  62. self.defaultAVCaptureSessionPreset = AVCaptureSessionPreset640x480;
  63. self.parentView = parent;
  64. self.useAVCaptureVideoPreviewLayer = YES;
  65. }
  66. return self;
  67. }
  68. - (void)dealloc;
  69. {
  70. [[NSNotificationCenter defaultCenter] removeObserver:self];
  71. [[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];
  72. }
  73. #pragma mark - Public interface
  74. - (void)start;
  75. {
  76. if (![NSThread isMainThread]) {
  77. NSLog(@"[Camera] Warning: Call start only from main thread");
  78. [self performSelectorOnMainThread:@selector(start) withObject:nil waitUntilDone:NO];
  79. return;
  80. }
  81. if (self.running == YES) {
  82. return;
  83. }
  84. _running = YES;
  85. // TODO: update image size data before actually starting (needed for recording)
  86. [self updateSize];
  87. if (self.cameraAvailable) {
  88. [self startCaptureSession];
  89. }
  90. }
  91. - (void)pause;
  92. {
  93. _running = NO;
  94. [self.captureSession stopRunning];
  95. }
  96. - (void)stop;
  97. {
  98. _running = NO;
  99. // Release any retained subviews of the main view.
  100. // e.g. self.myOutlet = nil;
  101. if (self.captureSession) {
  102. for (AVCaptureInput *input in self.captureSession.inputs) {
  103. [self.captureSession removeInput:input];
  104. }
  105. for (AVCaptureOutput *output in self.captureSession.outputs) {
  106. [self.captureSession removeOutput:output];
  107. }
  108. [self.captureSession stopRunning];
  109. }
  110. _captureSessionLoaded = NO;
  111. }
  112. // use front/back camera
  113. - (void)switchCameras;
  114. {
  115. BOOL was_running = self.running;
  116. if (was_running) {
  117. [self stop];
  118. }
  119. if (self.defaultAVCaptureDevicePosition == AVCaptureDevicePositionFront) {
  120. self.defaultAVCaptureDevicePosition = AVCaptureDevicePositionBack;
  121. } else {
  122. self.defaultAVCaptureDevicePosition = AVCaptureDevicePositionFront;
  123. }
  124. if (was_running) {
  125. [self start];
  126. }
  127. }
  128. #pragma mark - Device Orientation Changes
  129. - (void)deviceOrientationDidChange:(NSNotification*)notification
  130. {
  131. (void)notification;
  132. UIDeviceOrientation orientation = [UIDevice currentDevice].orientation;
  133. switch (orientation)
  134. {
  135. case UIDeviceOrientationPortrait:
  136. case UIDeviceOrientationPortraitUpsideDown:
  137. case UIDeviceOrientationLandscapeLeft:
  138. case UIDeviceOrientationLandscapeRight:
  139. self.currentDeviceOrientation = orientation;
  140. break;
  141. case UIDeviceOrientationFaceUp:
  142. case UIDeviceOrientationFaceDown:
  143. default:
  144. break;
  145. }
  146. NSLog(@"deviceOrientationDidChange: %d", (int)orientation);
  147. [self updateOrientation];
  148. }
  149. #pragma mark - Private Interface
  150. - (void)createCaptureSession;
  151. {
  152. // set a av capture session preset
  153. self.captureSession = [[AVCaptureSession alloc] init];
  154. if ([self.captureSession canSetSessionPreset:self.defaultAVCaptureSessionPreset]) {
  155. [self.captureSession setSessionPreset:self.defaultAVCaptureSessionPreset];
  156. } else if ([self.captureSession canSetSessionPreset:AVCaptureSessionPresetLow]) {
  157. [self.captureSession setSessionPreset:AVCaptureSessionPresetLow];
  158. } else {
  159. NSLog(@"[Camera] Error: could not set session preset");
  160. }
  161. }
  162. - (void)createCaptureDevice;
  163. {
  164. // setup the device
  165. AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
  166. [self setDesiredCameraPosition:self.defaultAVCaptureDevicePosition];
  167. NSLog(@"[Camera] device connected? %@", device.connected ? @"YES" : @"NO");
  168. NSLog(@"[Camera] device position %@", (device.position == AVCaptureDevicePositionBack) ? @"back" : @"front");
  169. }
  170. - (void)createVideoPreviewLayer;
  171. {
  172. self.captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.captureSession];
  173. if ([self.captureVideoPreviewLayer.connection isVideoOrientationSupported])
  174. {
  175. [self.captureVideoPreviewLayer.connection setVideoOrientation:self.defaultAVCaptureVideoOrientation];
  176. }
  177. if (self.parentView != nil) {
  178. self.captureVideoPreviewLayer.frame = self.parentView.bounds;
  179. self.captureVideoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
  180. [self.parentView.layer addSublayer:self.captureVideoPreviewLayer];
  181. }
  182. NSLog(@"[Camera] created AVCaptureVideoPreviewLayer");
  183. }
  184. - (void)setDesiredCameraPosition:(AVCaptureDevicePosition)desiredPosition;
  185. {
  186. for (AVCaptureDevice *device in [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]) {
  187. if ([device position] == desiredPosition) {
  188. [self.captureSession beginConfiguration];
  189. NSError* error = nil;
  190. AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
  191. if (!input) {
  192. NSLog(@"error creating input %@", [error description]);
  193. }
  194. // support for autofocus
  195. if ([device isFocusModeSupported:AVCaptureFocusModeContinuousAutoFocus]) {
  196. error = nil;
  197. if ([device lockForConfiguration:&error]) {
  198. device.focusMode = AVCaptureFocusModeContinuousAutoFocus;
  199. [device unlockForConfiguration];
  200. } else {
  201. NSLog(@"unable to lock device for autofocus configuration %@", [error description]);
  202. }
  203. }
  204. [self.captureSession addInput:input];
  205. for (AVCaptureInput *oldInput in self.captureSession.inputs) {
  206. [self.captureSession removeInput:oldInput];
  207. }
  208. [self.captureSession addInput:input];
  209. [self.captureSession commitConfiguration];
  210. break;
  211. }
  212. }
  213. }
  214. - (void)startCaptureSession
  215. {
  216. if (!self.cameraAvailable) {
  217. return;
  218. }
  219. if (self.captureSessionLoaded == NO) {
  220. [self createCaptureSession];
  221. [self createCaptureDevice];
  222. [self createCaptureOutput];
  223. // setup preview layer
  224. if (self.useAVCaptureVideoPreviewLayer) {
  225. [self createVideoPreviewLayer];
  226. } else {
  227. [self createCustomVideoPreview];
  228. }
  229. _captureSessionLoaded = YES;
  230. }
  231. [self.captureSession startRunning];
  232. }
  233. - (void)createCaptureOutput;
  234. {
  235. [NSException raise:NSInternalInconsistencyException
  236. format:@"You must override %s in a subclass", __FUNCTION__];
  237. }
  238. - (void)createCustomVideoPreview;
  239. {
  240. [NSException raise:NSInternalInconsistencyException
  241. format:@"You must override %s in a subclass", __FUNCTION__];
  242. }
  243. - (void)updateOrientation;
  244. {
  245. // nothing to do here
  246. }
  247. - (void)updateSize;
  248. {
  249. if ([self.defaultAVCaptureSessionPreset isEqualToString:AVCaptureSessionPresetPhoto]) {
  250. //TODO: find the correct resolution
  251. self.imageWidth = 640;
  252. self.imageHeight = 480;
  253. } else if ([self.defaultAVCaptureSessionPreset isEqualToString:AVCaptureSessionPresetHigh]) {
  254. //TODO: find the correct resolution
  255. self.imageWidth = 640;
  256. self.imageHeight = 480;
  257. } else if ([self.defaultAVCaptureSessionPreset isEqualToString:AVCaptureSessionPresetMedium]) {
  258. //TODO: find the correct resolution
  259. self.imageWidth = 640;
  260. self.imageHeight = 480;
  261. } else if ([self.defaultAVCaptureSessionPreset isEqualToString:AVCaptureSessionPresetLow]) {
  262. //TODO: find the correct resolution
  263. self.imageWidth = 640;
  264. self.imageHeight = 480;
  265. } else if ([self.defaultAVCaptureSessionPreset isEqualToString:AVCaptureSessionPreset352x288]) {
  266. self.imageWidth = 352;
  267. self.imageHeight = 288;
  268. } else if ([self.defaultAVCaptureSessionPreset isEqualToString:AVCaptureSessionPreset640x480]) {
  269. self.imageWidth = 640;
  270. self.imageHeight = 480;
  271. } else if ([self.defaultAVCaptureSessionPreset isEqualToString:AVCaptureSessionPreset1280x720]) {
  272. self.imageWidth = 1280;
  273. self.imageHeight = 720;
  274. } else {
  275. self.imageWidth = 640;
  276. self.imageHeight = 480;
  277. }
  278. }
  279. - (void)lockFocus;
  280. {
  281. AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
  282. if ([device isFocusModeSupported:AVCaptureFocusModeLocked]) {
  283. NSError *error = nil;
  284. if ([device lockForConfiguration:&error]) {
  285. device.focusMode = AVCaptureFocusModeLocked;
  286. [device unlockForConfiguration];
  287. } else {
  288. NSLog(@"unable to lock device for locked focus configuration %@", [error description]);
  289. }
  290. }
  291. }
  292. - (void) unlockFocus;
  293. {
  294. AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
  295. if ([device isFocusModeSupported:AVCaptureFocusModeContinuousAutoFocus]) {
  296. NSError *error = nil;
  297. if ([device lockForConfiguration:&error]) {
  298. device.focusMode = AVCaptureFocusModeContinuousAutoFocus;
  299. [device unlockForConfiguration];
  300. } else {
  301. NSLog(@"unable to lock device for autofocus configuration %@", [error description]);
  302. }
  303. }
  304. }
  305. - (void)lockExposure;
  306. {
  307. AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
  308. if ([device isExposureModeSupported:AVCaptureExposureModeLocked]) {
  309. NSError *error = nil;
  310. if ([device lockForConfiguration:&error]) {
  311. device.exposureMode = AVCaptureExposureModeLocked;
  312. [device unlockForConfiguration];
  313. } else {
  314. NSLog(@"unable to lock device for locked exposure configuration %@", [error description]);
  315. }
  316. }
  317. }
  318. - (void) unlockExposure;
  319. {
  320. AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
  321. if ([device isExposureModeSupported:AVCaptureExposureModeContinuousAutoExposure]) {
  322. NSError *error = nil;
  323. if ([device lockForConfiguration:&error]) {
  324. device.exposureMode = AVCaptureExposureModeContinuousAutoExposure;
  325. [device unlockForConfiguration];
  326. } else {
  327. NSLog(@"unable to lock device for autoexposure configuration %@", [error description]);
  328. }
  329. }
  330. }
  331. - (void)lockBalance;
  332. {
  333. AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
  334. if ([device isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeLocked]) {
  335. NSError *error = nil;
  336. if ([device lockForConfiguration:&error]) {
  337. device.whiteBalanceMode = AVCaptureWhiteBalanceModeLocked;
  338. [device unlockForConfiguration];
  339. } else {
  340. NSLog(@"unable to lock device for locked white balance configuration %@", [error description]);
  341. }
  342. }
  343. }
  344. - (void) unlockBalance;
  345. {
  346. AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
  347. if ([device isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeContinuousAutoWhiteBalance]) {
  348. NSError *error = nil;
  349. if ([device lockForConfiguration:&error]) {
  350. device.whiteBalanceMode = AVCaptureWhiteBalanceModeContinuousAutoWhiteBalance;
  351. [device unlockForConfiguration];
  352. } else {
  353. NSLog(@"unable to lock device for auto white balance configuration %@", [error description]);
  354. }
  355. }
  356. }
  357. @end