camera_macos.mm 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. /**************************************************************************/
  2. /* camera_macos.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_macos.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. Vector<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 = nullptr;
  91. }
  92. // free up our output
  93. if (output) {
  94. [self removeOutput:output];
  95. [output setSampleBufferDelegate:nil queue:nullptr];
  96. output = nullptr;
  97. }
  98. [self commitConfiguration];
  99. }
  100. - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {
  101. // This gets called every time our camera has a new image for us to process.
  102. // May need to investigate in a way to throttle this if we get more images then we're rendering frames..
  103. // For now, version 1, we're just doing the bare minimum to make this work...
  104. CVImageBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
  105. // int _width = CVPixelBufferGetWidth(pixelBuffer);
  106. // int _height = CVPixelBufferGetHeight(pixelBuffer);
  107. // It says that we need to lock this on the documentation pages but it's not in the samples
  108. // need to lock our base address so we can access our pixel buffers, better safe then sorry?
  109. CVPixelBufferLockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly);
  110. // get our buffers
  111. unsigned char *dataY = (unsigned char *)CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, 0);
  112. unsigned char *dataCbCr = (unsigned char *)CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, 1);
  113. if (dataY == nullptr) {
  114. print_line("Couldn't access Y pixel buffer data");
  115. } else if (dataCbCr == nullptr) {
  116. print_line("Couldn't access CbCr pixel buffer data");
  117. } else {
  118. Ref<Image> img[2];
  119. {
  120. // do Y
  121. size_t new_width = CVPixelBufferGetWidthOfPlane(pixelBuffer, 0);
  122. size_t new_height = CVPixelBufferGetHeightOfPlane(pixelBuffer, 0);
  123. if ((width[0] != new_width) || (height[0] != new_height)) {
  124. width[0] = new_width;
  125. height[0] = new_height;
  126. img_data[0].resize(new_width * new_height);
  127. }
  128. uint8_t *w = img_data[0].ptrw();
  129. memcpy(w, dataY, new_width * new_height);
  130. img[0].instantiate();
  131. img[0]->set_data(new_width, new_height, 0, Image::FORMAT_R8, img_data[0]);
  132. }
  133. {
  134. // do CbCr
  135. size_t new_width = CVPixelBufferGetWidthOfPlane(pixelBuffer, 1);
  136. size_t new_height = CVPixelBufferGetHeightOfPlane(pixelBuffer, 1);
  137. if ((width[1] != new_width) || (height[1] != new_height)) {
  138. width[1] = new_width;
  139. height[1] = new_height;
  140. img_data[1].resize(2 * new_width * new_height);
  141. }
  142. uint8_t *w = img_data[1].ptrw();
  143. memcpy(w, dataCbCr, 2 * new_width * new_height);
  144. ///TODO OpenGL doesn't support FORMAT_RG8, need to do some form of conversion
  145. img[1].instantiate();
  146. img[1]->set_data(new_width, new_height, 0, Image::FORMAT_RG8, img_data[1]);
  147. }
  148. // set our texture...
  149. feed->set_ycbcr_images(img[0], img[1]);
  150. }
  151. // and unlock
  152. CVPixelBufferUnlockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly);
  153. }
  154. @end
  155. //////////////////////////////////////////////////////////////////////////
  156. // CameraFeedMacOS - Subclass for camera feeds in macOS
  157. class CameraFeedMacOS : public CameraFeed {
  158. private:
  159. AVCaptureDevice *device;
  160. MyCaptureSession *capture_session;
  161. public:
  162. AVCaptureDevice *get_device() const;
  163. CameraFeedMacOS();
  164. void set_device(AVCaptureDevice *p_device);
  165. bool activate_feed();
  166. void deactivate_feed();
  167. };
  168. AVCaptureDevice *CameraFeedMacOS::get_device() const {
  169. return device;
  170. }
  171. CameraFeedMacOS::CameraFeedMacOS() {
  172. device = nullptr;
  173. capture_session = nullptr;
  174. }
  175. void CameraFeedMacOS::set_device(AVCaptureDevice *p_device) {
  176. device = p_device;
  177. // get some info
  178. NSString *device_name = p_device.localizedName;
  179. name = String::utf8(device_name.UTF8String);
  180. position = CameraFeed::FEED_UNSPECIFIED;
  181. if ([p_device position] == AVCaptureDevicePositionBack) {
  182. position = CameraFeed::FEED_BACK;
  183. } else if ([p_device position] == AVCaptureDevicePositionFront) {
  184. position = CameraFeed::FEED_FRONT;
  185. };
  186. }
  187. bool CameraFeedMacOS::activate_feed() {
  188. if (capture_session) {
  189. // Already recording!
  190. } else {
  191. // Start camera capture, check permission.
  192. if (@available(macOS 10.14, *)) {
  193. AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
  194. if (status == AVAuthorizationStatusAuthorized) {
  195. capture_session = [[MyCaptureSession alloc] initForFeed:this andDevice:device];
  196. } else if (status == AVAuthorizationStatusNotDetermined) {
  197. // Request permission.
  198. [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo
  199. completionHandler:^(BOOL granted) {
  200. if (granted) {
  201. capture_session = [[MyCaptureSession alloc] initForFeed:this andDevice:device];
  202. }
  203. }];
  204. }
  205. } else {
  206. capture_session = [[MyCaptureSession alloc] initForFeed:this andDevice:device];
  207. }
  208. };
  209. return true;
  210. }
  211. void CameraFeedMacOS::deactivate_feed() {
  212. // end camera capture if we have one
  213. if (capture_session) {
  214. [capture_session cleanup];
  215. capture_session = nullptr;
  216. };
  217. }
  218. //////////////////////////////////////////////////////////////////////////
  219. // MyDeviceNotifications - This is a little helper class gets notifications
  220. // when devices are connected/disconnected
  221. @interface MyDeviceNotifications : NSObject {
  222. CameraMacOS *camera_server;
  223. }
  224. @end
  225. @implementation MyDeviceNotifications
  226. - (void)devices_changed:(NSNotification *)notification {
  227. camera_server->update_feeds();
  228. }
  229. - (id)initForServer:(CameraMacOS *)p_server {
  230. if (self = [super init]) {
  231. camera_server = p_server;
  232. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(devices_changed:) name:AVCaptureDeviceWasConnectedNotification object:nil];
  233. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(devices_changed:) name:AVCaptureDeviceWasDisconnectedNotification object:nil];
  234. };
  235. return self;
  236. }
  237. - (void)dealloc {
  238. // remove notifications
  239. [[NSNotificationCenter defaultCenter] removeObserver:self name:AVCaptureDeviceWasConnectedNotification object:nil];
  240. [[NSNotificationCenter defaultCenter] removeObserver:self name:AVCaptureDeviceWasDisconnectedNotification object:nil];
  241. }
  242. @end
  243. MyDeviceNotifications *device_notifications = nil;
  244. //////////////////////////////////////////////////////////////////////////
  245. // CameraMacOS - Subclass for our camera server on macOS
  246. void CameraMacOS::update_feeds() {
  247. #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101500
  248. AVCaptureDeviceDiscoverySession *session;
  249. #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 140000
  250. // Avoid deprecated warning if the minimum SDK is 14.0.
  251. session = [AVCaptureDeviceDiscoverySession discoverySessionWithDeviceTypes:[NSArray arrayWithObjects:AVCaptureDeviceTypeExternal, AVCaptureDeviceTypeBuiltInWideAngleCamera, nil] mediaType:AVMediaTypeVideo position:AVCaptureDevicePositionUnspecified];
  252. #else
  253. session = [AVCaptureDeviceDiscoverySession discoverySessionWithDeviceTypes:[NSArray arrayWithObjects:AVCaptureDeviceTypeExternalUnknown, AVCaptureDeviceTypeBuiltInWideAngleCamera, nil] mediaType:AVMediaTypeVideo position:AVCaptureDevicePositionUnspecified];
  254. #endif
  255. NSArray<AVCaptureDevice *> *devices = session.devices;
  256. #else
  257. NSArray<AVCaptureDevice *> *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
  258. #endif
  259. // remove devices that are gone..
  260. for (int i = feeds.size() - 1; i >= 0; i--) {
  261. Ref<CameraFeedMacOS> feed = (Ref<CameraFeedMacOS>)feeds[i];
  262. if (![devices containsObject:feed->get_device()]) {
  263. // remove it from our array, this will also destroy it ;)
  264. remove_feed(feed);
  265. };
  266. };
  267. for (AVCaptureDevice *device in devices) {
  268. bool found = false;
  269. for (int i = 0; i < feeds.size() && !found; i++) {
  270. Ref<CameraFeedMacOS> feed = (Ref<CameraFeedMacOS>)feeds[i];
  271. if (feed->get_device() == device) {
  272. found = true;
  273. };
  274. };
  275. if (!found) {
  276. Ref<CameraFeedMacOS> newfeed;
  277. newfeed.instantiate();
  278. newfeed->set_device(device);
  279. // assume display camera so inverse
  280. Transform2D transform = Transform2D(-1.0, 0.0, 0.0, -1.0, 1.0, 1.0);
  281. newfeed->set_transform(transform);
  282. add_feed(newfeed);
  283. };
  284. };
  285. }
  286. CameraMacOS::CameraMacOS() {
  287. // Find available cameras we have at this time
  288. update_feeds();
  289. // should only have one of these....
  290. device_notifications = [[MyDeviceNotifications alloc] initForServer:this];
  291. }