camera_osx.mm 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. /**************************************************************************/
  2. /* camera_osx.mm */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. ///@TODO this is a near duplicate of CameraIOS, we should find a way to combine those to minimize code duplication!!!!
  31. // If you fix something here, make sure you fix it there as well!
  32. #include "camera_osx.h"
  33. #include "servers/camera/camera_feed.h"
  34. #import <AVFoundation/AVFoundation.h>
  35. //////////////////////////////////////////////////////////////////////////
  36. // MyCaptureSession - This is a little helper class so we can capture our frames
  37. @interface MyCaptureSession : AVCaptureSession <AVCaptureVideoDataOutputSampleBufferDelegate> {
  38. Ref<CameraFeed> feed;
  39. size_t width[2];
  40. size_t height[2];
  41. PoolVector<uint8_t> img_data[2];
  42. AVCaptureDeviceInput *input;
  43. AVCaptureVideoDataOutput *output;
  44. }
  45. @end
  46. @implementation MyCaptureSession
  47. - (id)initForFeed:(Ref<CameraFeed>)p_feed andDevice:(AVCaptureDevice *)p_device {
  48. if (self = [super init]) {
  49. NSError *error;
  50. feed = p_feed;
  51. width[0] = 0;
  52. height[0] = 0;
  53. width[1] = 0;
  54. height[1] = 0;
  55. [self beginConfiguration];
  56. input = [AVCaptureDeviceInput deviceInputWithDevice:p_device error:&error];
  57. if (!input) {
  58. print_line("Couldn't get input device for camera");
  59. } else {
  60. [self addInput:input];
  61. }
  62. output = [AVCaptureVideoDataOutput new];
  63. if (!output) {
  64. print_line("Couldn't get output device for camera");
  65. } else {
  66. NSDictionary *settings = @{ (NSString *)kCVPixelBufferPixelFormatTypeKey : @(kCVPixelFormatType_420YpCbCr8BiPlanarFullRange) };
  67. output.videoSettings = settings;
  68. // discard if the data output queue is blocked (as we process the still image)
  69. [output setAlwaysDiscardsLateVideoFrames:YES];
  70. // now set ourselves as the delegate to receive new frames.
  71. [output setSampleBufferDelegate:self queue:dispatch_get_main_queue()];
  72. // this takes ownership
  73. [self addOutput:output];
  74. }
  75. [self commitConfiguration];
  76. // kick off our session..
  77. [self startRunning];
  78. };
  79. return self;
  80. }
  81. - (void)cleanup {
  82. // stop running
  83. [self stopRunning];
  84. // cleanup
  85. [self beginConfiguration];
  86. // remove input
  87. if (input) {
  88. [self removeInput:input];
  89. // don't release this
  90. input = NULL;
  91. }
  92. // free up our output
  93. if (output) {
  94. [self removeOutput:output];
  95. [output setSampleBufferDelegate:nil queue:NULL];
  96. [output release];
  97. output = NULL;
  98. }
  99. [self commitConfiguration];
  100. }
  101. - (void)dealloc {
  102. // bye bye
  103. [super dealloc];
  104. }
  105. - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {
  106. // This gets called every time our camera has a new image for us to process.
  107. // May need to investigate in a way to throttle this if we get more images then we're rendering frames..
  108. // For now, version 1, we're just doing the bare minimum to make this work...
  109. CVImageBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
  110. // int _width = CVPixelBufferGetWidth(pixelBuffer);
  111. // int _height = CVPixelBufferGetHeight(pixelBuffer);
  112. // It says that we need to lock this on the documentation pages but it's not in the samples
  113. // need to lock our base address so we can access our pixel buffers, better safe then sorry?
  114. CVPixelBufferLockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly);
  115. // get our buffers
  116. unsigned char *dataY = (unsigned char *)CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, 0);
  117. unsigned char *dataCbCr = (unsigned char *)CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, 1);
  118. if (dataY == NULL) {
  119. print_line("Couldn't access Y pixel buffer data");
  120. } else if (dataCbCr == NULL) {
  121. print_line("Couldn't access CbCr pixel buffer data");
  122. } else {
  123. Ref<Image> img[2];
  124. {
  125. // do Y
  126. size_t new_width = CVPixelBufferGetWidthOfPlane(pixelBuffer, 0);
  127. size_t new_height = CVPixelBufferGetHeightOfPlane(pixelBuffer, 0);
  128. if ((width[0] != new_width) || (height[0] != new_height)) {
  129. width[0] = new_width;
  130. height[0] = new_height;
  131. img_data[0].resize(new_width * new_height);
  132. }
  133. PoolVector<uint8_t>::Write w = img_data[0].write();
  134. memcpy(w.ptr(), dataY, new_width * new_height);
  135. img[0].instance();
  136. img[0]->create(new_width, new_height, 0, Image::FORMAT_R8, img_data[0]);
  137. }
  138. {
  139. // do CbCr
  140. size_t new_width = CVPixelBufferGetWidthOfPlane(pixelBuffer, 1);
  141. size_t new_height = CVPixelBufferGetHeightOfPlane(pixelBuffer, 1);
  142. if ((width[1] != new_width) || (height[1] != new_height)) {
  143. width[1] = new_width;
  144. height[1] = new_height;
  145. img_data[1].resize(2 * new_width * new_height);
  146. }
  147. PoolVector<uint8_t>::Write w = img_data[1].write();
  148. memcpy(w.ptr(), dataCbCr, 2 * new_width * new_height);
  149. ///TODO GLES2 doesn't support FORMAT_RG8, need to do some form of conversion
  150. img[1].instance();
  151. img[1]->create(new_width, new_height, 0, Image::FORMAT_RG8, img_data[1]);
  152. }
  153. // set our texture...
  154. feed->set_YCbCr_imgs(img[0], img[1]);
  155. }
  156. // and unlock
  157. CVPixelBufferUnlockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly);
  158. }
  159. @end
  160. //////////////////////////////////////////////////////////////////////////
  161. // CameraFeedOSX - Subclass for camera feeds in OSX
  162. class CameraFeedOSX : public CameraFeed {
  163. private:
  164. AVCaptureDevice *device;
  165. MyCaptureSession *capture_session;
  166. public:
  167. AVCaptureDevice *get_device() const;
  168. CameraFeedOSX();
  169. ~CameraFeedOSX();
  170. void set_device(AVCaptureDevice *p_device);
  171. bool activate_feed();
  172. void deactivate_feed();
  173. };
  174. AVCaptureDevice *CameraFeedOSX::get_device() const {
  175. return device;
  176. };
  177. CameraFeedOSX::CameraFeedOSX() {
  178. device = NULL;
  179. capture_session = NULL;
  180. };
  181. void CameraFeedOSX::set_device(AVCaptureDevice *p_device) {
  182. device = p_device;
  183. [device retain];
  184. // get some info
  185. NSString *device_name = p_device.localizedName;
  186. name = String::utf8(device_name.UTF8String);
  187. position = CameraFeed::FEED_UNSPECIFIED;
  188. if ([p_device position] == AVCaptureDevicePositionBack) {
  189. position = CameraFeed::FEED_BACK;
  190. } else if ([p_device position] == AVCaptureDevicePositionFront) {
  191. position = CameraFeed::FEED_FRONT;
  192. };
  193. };
  194. CameraFeedOSX::~CameraFeedOSX() {
  195. if (capture_session != NULL) {
  196. [capture_session release];
  197. capture_session = NULL;
  198. };
  199. if (device != NULL) {
  200. [device release];
  201. device = NULL;
  202. };
  203. };
  204. bool CameraFeedOSX::activate_feed() {
  205. if (capture_session) {
  206. // Already recording!
  207. } else {
  208. // Start camera capture, check permission.
  209. if (@available(macOS 10.14, *)) {
  210. AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
  211. if (status == AVAuthorizationStatusAuthorized) {
  212. capture_session = [[MyCaptureSession alloc] initForFeed:this andDevice:device];
  213. } else if (status == AVAuthorizationStatusNotDetermined) {
  214. // Request permission.
  215. [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo
  216. completionHandler:^(BOOL granted) {
  217. if (granted) {
  218. capture_session = [[MyCaptureSession alloc] initForFeed:this andDevice:device];
  219. }
  220. }];
  221. }
  222. } else {
  223. capture_session = [[MyCaptureSession alloc] initForFeed:this andDevice:device];
  224. }
  225. };
  226. return true;
  227. };
  228. void CameraFeedOSX::deactivate_feed() {
  229. // end camera capture if we have one
  230. if (capture_session) {
  231. [capture_session cleanup];
  232. [capture_session release];
  233. capture_session = NULL;
  234. };
  235. };
  236. //////////////////////////////////////////////////////////////////////////
  237. // MyDeviceNotifications - This is a little helper class gets notifications
  238. // when devices are connected/disconnected
  239. @interface MyDeviceNotifications : NSObject {
  240. CameraOSX *camera_server;
  241. }
  242. @end
  243. @implementation MyDeviceNotifications
  244. - (void)devices_changed:(NSNotification *)notification {
  245. camera_server->update_feeds();
  246. }
  247. - (id)initForServer:(CameraOSX *)p_server {
  248. if (self = [super init]) {
  249. camera_server = p_server;
  250. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(devices_changed:) name:AVCaptureDeviceWasConnectedNotification object:nil];
  251. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(devices_changed:) name:AVCaptureDeviceWasDisconnectedNotification object:nil];
  252. };
  253. return self;
  254. }
  255. - (void)dealloc {
  256. // remove notifications
  257. [[NSNotificationCenter defaultCenter] removeObserver:self name:AVCaptureDeviceWasConnectedNotification object:nil];
  258. [[NSNotificationCenter defaultCenter] removeObserver:self name:AVCaptureDeviceWasDisconnectedNotification object:nil];
  259. [super dealloc];
  260. }
  261. @end
  262. MyDeviceNotifications *device_notifications = nil;
  263. //////////////////////////////////////////////////////////////////////////
  264. // CameraOSX - Subclass for our camera server on OSX
  265. void CameraOSX::update_feeds() {
  266. #if MAC_OS_X_VERSION_MIN_REQUIRED >= 101500
  267. AVCaptureDeviceDiscoverySession *session = [AVCaptureDeviceDiscoverySession discoverySessionWithDeviceTypes:[NSArray arrayWithObjects:AVCaptureDeviceTypeExternalUnknown, AVCaptureDeviceTypeBuiltInWideAngleCamera, nil] mediaType:AVMediaTypeVideo position:AVCaptureDevicePositionUnspecified];
  268. NSArray *devices = session.devices;
  269. #else
  270. NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
  271. #endif
  272. // remove devices that are gone..
  273. for (int i = feeds.size() - 1; i >= 0; i--) {
  274. Ref<CameraFeedOSX> feed = (Ref<CameraFeedOSX>)feeds[i];
  275. if (![devices containsObject:feed->get_device()]) {
  276. // remove it from our array, this will also destroy it ;)
  277. remove_feed(feed);
  278. };
  279. };
  280. // add new devices..
  281. for (AVCaptureDevice *device in devices) {
  282. bool found = false;
  283. for (int i = 0; i < feeds.size() && !found; i++) {
  284. Ref<CameraFeedOSX> feed = (Ref<CameraFeedOSX>)feeds[i];
  285. if (feed->get_device() == device) {
  286. found = true;
  287. };
  288. };
  289. if (!found) {
  290. Ref<CameraFeedOSX> newfeed;
  291. newfeed.instance();
  292. newfeed->set_device(device);
  293. // assume display camera so inverse
  294. Transform2D transform = Transform2D(-1.0, 0.0, 0.0, -1.0, 1.0, 1.0);
  295. newfeed->set_transform(transform);
  296. add_feed(newfeed);
  297. };
  298. };
  299. };
  300. CameraOSX::CameraOSX() {
  301. // Find available cameras we have at this time
  302. update_feeds();
  303. // should only have one of these....
  304. device_notifications = [[MyDeviceNotifications alloc] initForServer:this];
  305. };
  306. CameraOSX::~CameraOSX() {
  307. [device_notifications release];
  308. };