Debian Codegraph @

modules/camera/camera_macos.mm

raw
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
31 ///@TODO this is a near duplicate of CameraIOS, we should find a way to combine those to minimize code duplication!!!!
32 // If you fix something here, make sure you fix it there as well!
33
34 #import "camera_macos.h"
35
36 #include "servers/camera/camera_feed.h"
37
38 #import <AVFoundation/AVFoundation.h>
39
40 //////////////////////////////////////////////////////////////////////////
41 // MyCaptureSession - This is a little helper class so we can capture our frames
42
43 @interface MyCaptureSession : AVCaptureSession <AVCaptureVideoDataOutputSampleBufferDelegate> {
44 Ref<CameraFeed> feed;
45 size_t width[2];
46 size_t height[2];
47 Vector<uint8_t> img_data[2];
48
49 AVCaptureDeviceInput *input;
50 AVCaptureVideoDataOutput *output;
51 }
52
53 @end
54
55 @implementation MyCaptureSession
56
57 - (id)initForFeed:(Ref<CameraFeed>)p_feed andDevice:(AVCaptureDevice *)p_device {
58 if (self = [super init]) {
59 NSError *error;
60 feed = p_feed;
61 width[0] = 0;
62 height[0] = 0;
63 width[1] = 0;
64 height[1] = 0;
65
66 #ifdef APPLE_EMBEDDED_ENABLED
67 [p_device lockForConfiguration:&error];
68
69 [p_device setFocusMode:AVCaptureFocusModeLocked];
70 [p_device setExposureMode:AVCaptureExposureModeLocked];
71 [p_device setWhiteBalanceMode:AVCaptureWhiteBalanceModeLocked];
72
73 [p_device unlockForConfiguration];
74 #endif // APPLE_EMBEDDED_ENABLED
75
76 [self beginConfiguration];
77
78 #ifdef APPLE_EMBEDDED_ENABLED
79 self.sessionPreset = AVCaptureSessionPreset1280x720;
80 #endif // APPLE_EMBEDDED_ENABLED
81
82 input = [AVCaptureDeviceInput deviceInputWithDevice:p_device error:&error];
83 if (!input) {
84 print_line("Couldn't get input device for camera");
85 [self commitConfiguration];
86 return nil;
87 }
88 [self addInput:input];
89
90 output = [AVCaptureVideoDataOutput new];
91 if (!output) {
92 print_line("Couldn't get output device for camera");
93 [self commitConfiguration];
94 return nil;
95 }
96
97 NSDictionary *settings = @{ (NSString *)kCVPixelBufferPixelFormatTypeKey : @(kCVPixelFormatType_420YpCbCr8BiPlanarFullRange) };
98 output.videoSettings = settings;
99
100 // discard if the data output queue is blocked (as we process the still image)
101 [output setAlwaysDiscardsLateVideoFrames:YES];
102
103 // now set ourselves as the delegate to receive new frames.
104 [output setSampleBufferDelegate:self queue:dispatch_get_main_queue()];
105
106 // this takes ownership
107 [self addOutput:output];
108
109 [self commitConfiguration];
110
111 // kick off our session..
112 [self startRunning];
113 };
114 return self;
115 }
116
117 - (void)cleanup {
118 // stop running
119 [self stopRunning];
120
121 // cleanup
122 [self beginConfiguration];
123
124 // remove input
125 if (input) {
126 [self removeInput:input];
127 // don't release this
128 input = nullptr;
129 }
130
131 // free up our output
132 if (output) {
133 [self removeOutput:output];
134 [output setSampleBufferDelegate:nil queue:nullptr];
135 output = nullptr;
136 }
137
138 [self commitConfiguration];
139 }
140
141 - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {
142 // This gets called every time our camera has a new image for us to process.
143 // May need to investigate in a way to throttle this if we get more images then we're rendering frames..
144
145 // For now, version 1, we're just doing the bare minimum to make this work...
146 CVImageBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
147 if (pixelBuffer == nullptr) {
148 return;
149 }
150
151 // It says that we need to lock this on the documentation pages but it's not in the samples
152 // need to lock our base address so we can access our pixel buffers, better safe then sorry?
153 CVPixelBufferLockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly);
154
155 // Check if we have the expected number of planes (Y and CbCr).
156 size_t planeCount = CVPixelBufferGetPlaneCount(pixelBuffer);
157 if (planeCount < 2) {
158 static bool plane_count_error_logged = false;
159 if (!plane_count_error_logged) {
160 ERR_PRINT("Unexpected plane count in pixel buffer (expected 2, got " + itos(planeCount) + ")");
161 plane_count_error_logged = true;
162 }
163 CVPixelBufferUnlockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly);
164 return;
165 }
166
167 // get our buffers
168 unsigned char *dataY = (unsigned char *)CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, 0);
169 unsigned char *dataCbCr = (unsigned char *)CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, 1);
170 if (dataY == nullptr || dataCbCr == nullptr) {
171 static bool buffer_access_error_logged = false;
172 if (!buffer_access_error_logged) {
173 ERR_PRINT("Couldn't access pixel buffer plane data");
174 buffer_access_error_logged = true;
175 }
176 CVPixelBufferUnlockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly);
177 return;
178 }
179
180 Ref<Image> img[2];
181
182 {
183 // do Y
184 size_t new_width = CVPixelBufferGetWidthOfPlane(pixelBuffer, 0);
185 size_t new_height = CVPixelBufferGetHeightOfPlane(pixelBuffer, 0);
186
187 if ((width[0] != new_width) || (height[0] != new_height)) {
188 width[0] = new_width;
189 height[0] = new_height;
190 img_data[0].resize(new_width * new_height);
191 }
192
193 uint8_t *w = img_data[0].ptrw();
194 memcpy(w, dataY, new_width * new_height);
195
196 img[0].instantiate();
197 img[0]->set_data(new_width, new_height, 0, Image::FORMAT_R8, img_data[0]);
198 }
199
200 {
201 // do CbCr
202 size_t new_width = CVPixelBufferGetWidthOfPlane(pixelBuffer, 1);
203 size_t new_height = CVPixelBufferGetHeightOfPlane(pixelBuffer, 1);
204
205 if ((width[1] != new_width) || (height[1] != new_height)) {
206 width[1] = new_width;
207 height[1] = new_height;
208 img_data[1].resize(2 * new_width * new_height);
209 }
210
211 uint8_t *w = img_data[1].ptrw();
212 memcpy(w, dataCbCr, 2 * new_width * new_height);
213
214 ///TODO OpenGL doesn't support FORMAT_RG8, need to do some form of conversion
215 img[1].instantiate();
216 img[1]->set_data(new_width, new_height, 0, Image::FORMAT_RG8, img_data[1]);
217 }
218
219 // set our texture...
220 feed->set_ycbcr_images(img[0], img[1]);
221
222 // and unlock
223 CVPixelBufferUnlockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly);
224 }
225
226 @end
227
228 //////////////////////////////////////////////////////////////////////////
229 // CameraFeedMacOS - Subclass for camera feeds in macOS
230
231 class CameraFeedMacOS : public CameraFeed {
232 GDSOFTCLASS(CameraFeedMacOS, CameraFeed);
233
234 private:
235 AVCaptureDevice *device;
236 MyCaptureSession *capture_session;
237
238 public:
239 AVCaptureDevice *get_device() const;
240
241 CameraFeedMacOS();
242 ~CameraFeedMacOS();
243
244 void set_device(AVCaptureDevice *p_device);
245
246 bool activate_feed() override;
247 void deactivate_feed() override;
248 };
249
250 AVCaptureDevice *CameraFeedMacOS::get_device() const {
251 return device;
252 }
253
254 CameraFeedMacOS::CameraFeedMacOS() {
255 device = nullptr;
256 capture_session = nullptr;
257 }
258
259 CameraFeedMacOS::~CameraFeedMacOS() {
260 if (is_active()) {
261 deactivate_feed();
262 }
263 }
264
265 void CameraFeedMacOS::set_device(AVCaptureDevice *p_device) {
266 device = p_device;
267
268 // get some info
269 NSString *device_name = p_device.localizedName;
270 name = String::utf8(device_name.UTF8String);
271 position = CameraFeed::FEED_UNSPECIFIED;
272 if ([p_device position] == AVCaptureDevicePositionBack) {
273 position = CameraFeed::FEED_BACK;
274 } else if ([p_device position] == AVCaptureDevicePositionFront) {
275 position = CameraFeed::FEED_FRONT;
276 };
277 }
278
279 bool CameraFeedMacOS::activate_feed() {
280 if (capture_session) {
281 // Already recording.
282 return true;
283 }
284
285 // Start camera capture, check permission.
286 if (@available(macOS 10.14, *)) {
287 AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
288 if (status == AVAuthorizationStatusAuthorized) {
289 capture_session = [[MyCaptureSession alloc] initForFeed:this andDevice:device];
290 return capture_session != nullptr;
291 } else if (status == AVAuthorizationStatusNotDetermined) {
292 // Request permission asynchronously.
293 [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo
294 completionHandler:^(BOOL granted) {
295 if (granted) {
296 capture_session = [[MyCaptureSession alloc] initForFeed:this andDevice:device];
297 }
298 }];
299 return false;
300 } else if (status == AVAuthorizationStatusDenied) {
301 print_line("Camera permission denied by user.");
302 return false;
303 } else if (status == AVAuthorizationStatusRestricted) {
304 print_line("Camera access restricted.");
305 return false;
306 }
307 return false;
308 } else {
309 capture_session = [[MyCaptureSession alloc] initForFeed:this andDevice:device];
310 return capture_session != nullptr;
311 }
312 }
313
314 void CameraFeedMacOS::deactivate_feed() {
315 // end camera capture if we have one
316 if (capture_session) {
317 [capture_session cleanup];
318 capture_session = nullptr;
319 };
320 }
321
322 //////////////////////////////////////////////////////////////////////////
323 // MyDeviceNotifications - This is a little helper class gets notifications
324 // when devices are connected/disconnected
325
326 @interface MyDeviceNotifications : NSObject {
327 CameraMacOS *camera_server;
328 }
329
330 @end
331
332 @implementation MyDeviceNotifications
333
334 - (void)devices_changed:(NSNotification *)notification {
335 camera_server->update_feeds();
336 }
337
338 - (id)initForServer:(CameraMacOS *)p_server {
339 if (self = [super init]) {
340 camera_server = p_server;
341
342 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(devices_changed:) name:AVCaptureDeviceWasConnectedNotification object:nil];
343 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(devices_changed:) name:AVCaptureDeviceWasDisconnectedNotification object:nil];
344 };
345 return self;
346 }
347
348 - (void)dealloc {
349 // remove notifications
350 [[NSNotificationCenter defaultCenter] removeObserver:self name:AVCaptureDeviceWasConnectedNotification object:nil];
351 [[NSNotificationCenter defaultCenter] removeObserver:self name:AVCaptureDeviceWasDisconnectedNotification object:nil];
352 }
353
354 @end
355
356 MyDeviceNotifications *device_notifications = nil;
357
358 //////////////////////////////////////////////////////////////////////////
359 // CameraMacOS - Subclass for our camera server on macOS
360
361 void CameraMacOS::update_feeds() {
362 NSArray<AVCaptureDevice *> *devices = nullptr;
363 #if defined(__x86_64__)
364 if (@available(macOS 10.15, *)) {
365 #endif
366 AVCaptureDeviceDiscoverySession *session;
367 if (@available(macOS 14.0, *)) {
368 session = [AVCaptureDeviceDiscoverySession discoverySessionWithDeviceTypes:[NSArray arrayWithObjects:AVCaptureDeviceTypeExternal, AVCaptureDeviceTypeBuiltInWideAngleCamera, AVCaptureDeviceTypeContinuityCamera, nil] mediaType:AVMediaTypeVideo position:AVCaptureDevicePositionUnspecified];
369 } else {
370 session = [AVCaptureDeviceDiscoverySession discoverySessionWithDeviceTypes:[NSArray arrayWithObjects:AVCaptureDeviceTypeExternalUnknown, AVCaptureDeviceTypeBuiltInWideAngleCamera, nil] mediaType:AVMediaTypeVideo position:AVCaptureDevicePositionUnspecified];
371 }
372 devices = session.devices;
373 #if defined(__x86_64__)
374 } else {
375 devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
376 }
377 #endif
378
379 // Deactivate feeds that are gone before removing them.
380 for (int i = feeds.size() - 1; i >= 0; i--) {
381 Ref<CameraFeedMacOS> feed = (Ref<CameraFeedMacOS>)feeds[i];
382 if (feed.is_null()) {
383 continue;
384 }
385
386 if (![devices containsObject:feed->get_device()]) {
387 if (feed->is_active()) {
388 feed->deactivate_feed();
389 }
390 remove_feed(feed);
391 };
392 };
393
394 for (AVCaptureDevice *device in devices) {
395 bool found = false;
396 for (int i = 0; i < feeds.size() && !found; i++) {
397 Ref<CameraFeedMacOS> feed = (Ref<CameraFeedMacOS>)feeds[i];
398 if (feed.is_null()) {
399 continue;
400 }
401 if (feed->get_device() == device) {
402 found = true;
403 };
404 };
405
406 if (!found) {
407 Ref<CameraFeedMacOS> newfeed;
408 newfeed.instantiate();
409 newfeed->set_device(device);
410
411 add_feed(newfeed);
412 };
413 };
414 emit_signal(SNAME(CameraServer::feeds_updated_signal_name));
415 }
416
417 void CameraMacOS::set_monitoring_feeds(bool p_monitoring_feeds) {
418 if (p_monitoring_feeds == monitoring_feeds) {
419 return;
420 }
421
422 CameraServer::set_monitoring_feeds(p_monitoring_feeds);
423 if (p_monitoring_feeds) {
424 // Find available cameras we have at this time.
425 update_feeds();
426
427 // Get notified on feed changes.
428 device_notifications = [[MyDeviceNotifications alloc] initForServer:this];
429 } else {
430 // Stop monitoring feed changes.
431 device_notifications = nil;
432 }
433 }