mac-screen-capture.m 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085
  1. #include <AvailabilityMacros.h>
  2. #include <Cocoa/Cocoa.h>
  3. bool is_screen_capture_available(void)
  4. {
  5. if (@available(macOS 12.5, *)) {
  6. return true;
  7. } else {
  8. return false;
  9. }
  10. }
  11. #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 120300 // __MAC_12_3
  12. #pragma clang diagnostic push
  13. #pragma clang diagnostic ignored "-Wunguarded-availability-new"
  14. #include <stdlib.h>
  15. #include <obs-module.h>
  16. #include <util/threading.h>
  17. #include <pthread.h>
  18. #include <IOSurface/IOSurface.h>
  19. #include <ScreenCaptureKit/ScreenCaptureKit.h>
  20. #include <CoreMedia/CMSampleBuffer.h>
  21. #include <CoreVideo/CVPixelBuffer.h>
  22. #define MACCAP_LOG(level, msg, ...) \
  23. blog(level, "[ mac-screencapture ]: " msg, ##__VA_ARGS__)
  24. #define MACCAP_ERR(msg, ...) MACCAP_LOG(LOG_ERROR, msg, ##__VA_ARGS__)
  25. typedef enum {
  26. ScreenCaptureDisplayStream = 0,
  27. ScreenCaptureWindowStream = 1,
  28. ScreenCaptureApplicationStream = 2,
  29. } ScreenCaptureStreamType;
  30. @interface ScreenCaptureDelegate : NSObject <SCStreamOutput>
  31. @property struct screen_capture *sc;
  32. @end
  33. struct screen_capture {
  34. obs_source_t *source;
  35. gs_effect_t *effect;
  36. gs_texture_t *tex;
  37. NSRect frame;
  38. bool hide_cursor;
  39. bool show_hidden_windows;
  40. bool show_empty_names;
  41. SCStream *disp;
  42. SCStreamConfiguration *stream_properties;
  43. SCShareableContent *shareable_content;
  44. ScreenCaptureDelegate *capture_delegate;
  45. os_event_t *disp_finished;
  46. os_event_t *stream_start_completed;
  47. os_sem_t *shareable_content_available;
  48. IOSurfaceRef current, prev;
  49. pthread_mutex_t mutex;
  50. unsigned capture_type;
  51. CGDirectDisplayID display;
  52. CGWindowID window;
  53. NSString *application_id;
  54. };
  55. static void destroy_screen_stream(struct screen_capture *sc)
  56. {
  57. if (sc->disp) {
  58. [sc->disp stopCaptureWithCompletionHandler:^(
  59. NSError *_Nullable error) {
  60. if (error && error.code != 3808) {
  61. MACCAP_ERR(
  62. "destroy_screen_stream: Failed to stop stream with error %s\n",
  63. [[error localizedFailureReason]
  64. cStringUsingEncoding:
  65. NSUTF8StringEncoding]);
  66. }
  67. os_event_signal(sc->disp_finished);
  68. }];
  69. os_event_wait(sc->disp_finished);
  70. }
  71. if (sc->stream_properties) {
  72. [sc->stream_properties release];
  73. sc->stream_properties = NULL;
  74. }
  75. if (sc->tex) {
  76. gs_texture_destroy(sc->tex);
  77. sc->tex = NULL;
  78. }
  79. if (sc->current) {
  80. IOSurfaceDecrementUseCount(sc->current);
  81. CFRelease(sc->current);
  82. sc->current = NULL;
  83. }
  84. if (sc->prev) {
  85. IOSurfaceDecrementUseCount(sc->prev);
  86. CFRelease(sc->prev);
  87. sc->prev = NULL;
  88. }
  89. if (sc->disp) {
  90. [sc->disp release];
  91. sc->disp = NULL;
  92. }
  93. os_event_destroy(sc->disp_finished);
  94. os_event_destroy(sc->stream_start_completed);
  95. }
  96. static void screen_capture_destroy(void *data)
  97. {
  98. struct screen_capture *sc = data;
  99. if (!sc)
  100. return;
  101. obs_enter_graphics();
  102. destroy_screen_stream(sc);
  103. obs_leave_graphics();
  104. if (sc->shareable_content) {
  105. os_sem_wait(sc->shareable_content_available);
  106. [sc->shareable_content release];
  107. os_sem_destroy(sc->shareable_content_available);
  108. sc->shareable_content_available = NULL;
  109. }
  110. if (sc->capture_delegate) {
  111. [sc->capture_delegate release];
  112. }
  113. pthread_mutex_destroy(&sc->mutex);
  114. bfree(sc);
  115. }
  116. static inline void screen_stream_video_update(struct screen_capture *sc,
  117. CMSampleBufferRef sample_buffer)
  118. {
  119. bool frame_detail_errored = false;
  120. float scale_factor = 1.0f;
  121. CGRect window_rect = {};
  122. CFArrayRef attachments_array =
  123. CMSampleBufferGetSampleAttachmentsArray(sample_buffer, false);
  124. if (sc->capture_type == ScreenCaptureWindowStream &&
  125. attachments_array != NULL &&
  126. CFArrayGetCount(attachments_array) > 0) {
  127. CFDictionaryRef attachments_dict =
  128. CFArrayGetValueAtIndex(attachments_array, 0);
  129. if (attachments_dict != NULL) {
  130. CFTypeRef frame_scale_factor = CFDictionaryGetValue(
  131. attachments_dict, SCStreamFrameInfoScaleFactor);
  132. if (frame_scale_factor != NULL) {
  133. Boolean result = CFNumberGetValue(
  134. (CFNumberRef)frame_scale_factor,
  135. kCFNumberFloatType, &scale_factor);
  136. if (result == false) {
  137. scale_factor = 1.0f;
  138. frame_detail_errored = true;
  139. }
  140. }
  141. CFTypeRef content_rect_dict = CFDictionaryGetValue(
  142. attachments_dict, SCStreamFrameInfoContentRect);
  143. CFTypeRef content_scale_factor = CFDictionaryGetValue(
  144. attachments_dict,
  145. SCStreamFrameInfoContentScale);
  146. if ((content_rect_dict != NULL) &&
  147. (content_scale_factor != NULL)) {
  148. CGRect content_rect = {};
  149. float points_to_pixels = 0.0f;
  150. Boolean result =
  151. CGRectMakeWithDictionaryRepresentation(
  152. (__bridge CFDictionaryRef)
  153. content_rect_dict,
  154. &content_rect);
  155. if (result == false) {
  156. content_rect = CGRectZero;
  157. frame_detail_errored = true;
  158. }
  159. result = CFNumberGetValue(
  160. (CFNumberRef)content_scale_factor,
  161. kCFNumberFloatType, &points_to_pixels);
  162. if (result == false) {
  163. points_to_pixels = 1.0f;
  164. frame_detail_errored = true;
  165. }
  166. window_rect.origin = content_rect.origin;
  167. window_rect.size.width =
  168. content_rect.size.width /
  169. points_to_pixels * scale_factor;
  170. window_rect.size.height =
  171. content_rect.size.height /
  172. points_to_pixels * scale_factor;
  173. }
  174. }
  175. }
  176. CVImageBufferRef image_buffer =
  177. CMSampleBufferGetImageBuffer(sample_buffer);
  178. CVPixelBufferLockBaseAddress(image_buffer, 0);
  179. IOSurfaceRef frame_surface = CVPixelBufferGetIOSurface(image_buffer);
  180. CVPixelBufferUnlockBaseAddress(image_buffer, 0);
  181. IOSurfaceRef prev_current = NULL;
  182. if (frame_surface && !pthread_mutex_lock(&sc->mutex)) {
  183. bool needs_to_update_properties = false;
  184. if (!frame_detail_errored) {
  185. if (sc->capture_type == ScreenCaptureWindowStream) {
  186. if ((sc->frame.size.width !=
  187. window_rect.size.width) ||
  188. (sc->frame.size.height !=
  189. window_rect.size.height)) {
  190. sc->frame.size.width =
  191. window_rect.size.width;
  192. sc->frame.size.height =
  193. window_rect.size.height;
  194. needs_to_update_properties = true;
  195. }
  196. } else {
  197. size_t width =
  198. CVPixelBufferGetWidth(image_buffer);
  199. size_t height =
  200. CVPixelBufferGetHeight(image_buffer);
  201. if ((sc->frame.size.width != width) ||
  202. (sc->frame.size.height != height)) {
  203. sc->frame.size.width = width;
  204. sc->frame.size.height = height;
  205. needs_to_update_properties = true;
  206. }
  207. }
  208. }
  209. if (needs_to_update_properties) {
  210. [sc->stream_properties setWidth:sc->frame.size.width];
  211. [sc->stream_properties setHeight:sc->frame.size.height];
  212. [sc->disp
  213. updateConfiguration:sc->stream_properties
  214. completionHandler:^(
  215. NSError *_Nullable error) {
  216. if (error) {
  217. MACCAP_ERR(
  218. "screen_stream_video_update: Failed to update stream properties with error %s\n",
  219. [[error localizedFailureReason]
  220. cStringUsingEncoding:
  221. NSUTF8StringEncoding]);
  222. }
  223. }];
  224. }
  225. prev_current = sc->current;
  226. sc->current = frame_surface;
  227. CFRetain(sc->current);
  228. IOSurfaceIncrementUseCount(sc->current);
  229. pthread_mutex_unlock(&sc->mutex);
  230. }
  231. if (prev_current) {
  232. IOSurfaceDecrementUseCount(prev_current);
  233. CFRelease(prev_current);
  234. }
  235. }
  236. static inline void screen_stream_audio_update(struct screen_capture *sc,
  237. CMSampleBufferRef sample_buffer)
  238. {
  239. CMFormatDescriptionRef format_description =
  240. CMSampleBufferGetFormatDescription(sample_buffer);
  241. const AudioStreamBasicDescription *audio_description =
  242. CMAudioFormatDescriptionGetStreamBasicDescription(
  243. format_description);
  244. char *_Nullable bytes = NULL;
  245. CMBlockBufferRef data_buffer =
  246. CMSampleBufferGetDataBuffer(sample_buffer);
  247. size_t data_buffer_length = CMBlockBufferGetDataLength(data_buffer);
  248. CMBlockBufferGetDataPointer(data_buffer, 0, &data_buffer_length, NULL,
  249. &bytes);
  250. CMTime presentation_time =
  251. CMSampleBufferGetOutputPresentationTimeStamp(sample_buffer);
  252. struct obs_source_audio audio_data = {};
  253. for (uint32_t channel_idx = 0;
  254. channel_idx < audio_description->mChannelsPerFrame;
  255. ++channel_idx) {
  256. uint32_t offset =
  257. (uint32_t)(data_buffer_length /
  258. audio_description->mChannelsPerFrame) *
  259. channel_idx;
  260. audio_data.data[channel_idx] = (uint8_t *)bytes + offset;
  261. }
  262. audio_data.frames = (uint32_t)(data_buffer_length /
  263. audio_description->mBytesPerFrame /
  264. audio_description->mChannelsPerFrame);
  265. audio_data.speakers = audio_description->mChannelsPerFrame;
  266. audio_data.samples_per_sec = audio_description->mSampleRate;
  267. audio_data.timestamp =
  268. CMTimeGetSeconds(presentation_time) * NSEC_PER_SEC;
  269. audio_data.format = AUDIO_FORMAT_FLOAT_PLANAR;
  270. obs_source_output_audio(sc->source, &audio_data);
  271. }
  272. static bool init_screen_stream(struct screen_capture *sc)
  273. {
  274. SCContentFilter *content_filter;
  275. sc->frame = CGRectZero;
  276. sc->stream_properties = [[SCStreamConfiguration alloc] init];
  277. os_sem_wait(sc->shareable_content_available);
  278. SCDisplay * (^get_target_display)() = ^SCDisplay *()
  279. {
  280. __block SCDisplay *target_display = nil;
  281. [sc->shareable_content.displays
  282. indexOfObjectPassingTest:^BOOL(
  283. SCDisplay *_Nonnull display, NSUInteger idx,
  284. BOOL *_Nonnull stop) {
  285. if (display.displayID == sc->display) {
  286. target_display = sc->shareable_content
  287. .displays[idx];
  288. *stop = TRUE;
  289. }
  290. return *stop;
  291. }];
  292. return target_display;
  293. };
  294. void (^set_display_mode)(struct screen_capture *, SCDisplay *) = ^void(
  295. struct screen_capture *sc, SCDisplay *target_display) {
  296. CGDisplayModeRef display_mode =
  297. CGDisplayCopyDisplayMode(target_display.displayID);
  298. [sc->stream_properties
  299. setWidth:CGDisplayModeGetPixelWidth(display_mode)];
  300. [sc->stream_properties
  301. setHeight:CGDisplayModeGetPixelHeight(display_mode)];
  302. CGDisplayModeRelease(display_mode);
  303. };
  304. switch (sc->capture_type) {
  305. case ScreenCaptureDisplayStream: {
  306. SCDisplay *target_display = get_target_display();
  307. if (@available(macOS 13.0, *)) {
  308. content_filter = [[SCContentFilter alloc]
  309. initWithDisplay:target_display
  310. excludingWindows:[[NSArray alloc] init]];
  311. } else {
  312. NSArray *excluded = [sc->shareable_content.applications
  313. filteredArrayUsingPredicate:
  314. [NSPredicate predicateWithBlock:^BOOL(
  315. SCRunningApplication
  316. *application,
  317. NSDictionary<
  318. NSString *,
  319. id>
  320. *_Nullable bindings
  321. __attribute__((
  322. unused))) {
  323. return [application
  324. .bundleIdentifier
  325. isEqualToString:
  326. @"com.apple.controlcenter"];
  327. }]];
  328. content_filter = [[SCContentFilter alloc]
  329. initWithDisplay:target_display
  330. excludingApplications:excluded
  331. exceptingWindows:[[NSArray alloc] init]];
  332. }
  333. set_display_mode(sc, target_display);
  334. } break;
  335. case ScreenCaptureWindowStream: {
  336. __block SCWindow *target_window = nil;
  337. if (sc->window != 0) {
  338. [sc->shareable_content.windows
  339. indexOfObjectPassingTest:^BOOL(
  340. SCWindow *_Nonnull window,
  341. NSUInteger idx, BOOL *_Nonnull stop) {
  342. if (window.windowID == sc->window) {
  343. target_window =
  344. sc->shareable_content
  345. .windows[idx];
  346. *stop = TRUE;
  347. }
  348. return *stop;
  349. }];
  350. } else {
  351. target_window =
  352. [sc->shareable_content.windows objectAtIndex:0];
  353. sc->window = target_window.windowID;
  354. }
  355. content_filter = [[SCContentFilter alloc]
  356. initWithDesktopIndependentWindow:target_window];
  357. if (target_window) {
  358. [sc->stream_properties
  359. setWidth:target_window.frame.size.width];
  360. [sc->stream_properties
  361. setHeight:target_window.frame.size.height];
  362. }
  363. } break;
  364. case ScreenCaptureApplicationStream: {
  365. SCDisplay *target_display = get_target_display();
  366. __block SCRunningApplication *target_application = nil;
  367. {
  368. [sc->shareable_content.applications
  369. indexOfObjectPassingTest:^BOOL(
  370. SCRunningApplication
  371. *_Nonnull application,
  372. NSUInteger idx, BOOL *_Nonnull stop) {
  373. if ([application.bundleIdentifier
  374. isEqualToString:
  375. sc->
  376. application_id]) {
  377. target_application =
  378. sc->shareable_content
  379. .applications
  380. [idx];
  381. *stop = TRUE;
  382. }
  383. return *stop;
  384. }];
  385. }
  386. NSArray *target_application_array = [[NSArray alloc]
  387. initWithObjects:target_application, nil];
  388. content_filter = [[SCContentFilter alloc]
  389. initWithDisplay:target_display
  390. includingApplications:target_application_array
  391. exceptingWindows:[[NSArray alloc] init]];
  392. set_display_mode(sc, target_display);
  393. } break;
  394. }
  395. os_sem_post(sc->shareable_content_available);
  396. [sc->stream_properties setQueueDepth:8];
  397. [sc->stream_properties setShowsCursor:!sc->hide_cursor];
  398. [sc->stream_properties setColorSpaceName:kCGColorSpaceSRGB];
  399. [sc->stream_properties setPixelFormat:'BGRA'];
  400. #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 130000
  401. if (@available(macOS 13.0, *)) {
  402. [sc->stream_properties setCapturesAudio:TRUE];
  403. [sc->stream_properties setExcludesCurrentProcessAudio:TRUE];
  404. [sc->stream_properties setChannelCount:2];
  405. }
  406. #endif
  407. sc->disp = [[SCStream alloc] initWithFilter:content_filter
  408. configuration:sc->stream_properties
  409. delegate:nil];
  410. NSError *error = nil;
  411. BOOL did_add_output = [sc->disp addStreamOutput:sc->capture_delegate
  412. type:SCStreamOutputTypeScreen
  413. sampleHandlerQueue:nil
  414. error:&error];
  415. if (!did_add_output) {
  416. MACCAP_ERR(
  417. "init_screen_stream: Failed to add stream output with error %s\n",
  418. [[error localizedFailureReason]
  419. cStringUsingEncoding:NSUTF8StringEncoding]);
  420. [error release];
  421. return !did_add_output;
  422. }
  423. #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 130000
  424. if (__builtin_available(macOS 13.0, *)) {
  425. did_add_output = [sc->disp
  426. addStreamOutput:sc->capture_delegate
  427. type:SCStreamOutputTypeAudio
  428. sampleHandlerQueue:nil
  429. error:&error];
  430. if (!did_add_output) {
  431. MACCAP_ERR(
  432. "init_screen_stream: Failed to add audio stream output with error %s\n",
  433. [[error localizedFailureReason]
  434. cStringUsingEncoding:
  435. NSUTF8StringEncoding]);
  436. [error release];
  437. return !did_add_output;
  438. }
  439. }
  440. #endif
  441. os_event_init(&sc->disp_finished, OS_EVENT_TYPE_MANUAL);
  442. os_event_init(&sc->stream_start_completed, OS_EVENT_TYPE_MANUAL);
  443. __block BOOL did_stream_start = false;
  444. [sc->disp startCaptureWithCompletionHandler:^(
  445. NSError *_Nullable error) {
  446. did_stream_start = (BOOL)(error == nil);
  447. if (!did_stream_start) {
  448. MACCAP_ERR(
  449. "init_screen_stream: Failed to start capture with error %s\n",
  450. [[error localizedFailureReason]
  451. cStringUsingEncoding:
  452. NSUTF8StringEncoding]);
  453. // Clean up disp so it isn't stopped
  454. [sc->disp release];
  455. sc->disp = NULL;
  456. }
  457. os_event_signal(sc->stream_start_completed);
  458. }];
  459. os_event_wait(sc->stream_start_completed);
  460. return did_stream_start;
  461. }
  462. static void screen_capture_build_content_list(struct screen_capture *sc,
  463. bool display_capture)
  464. {
  465. typedef void (^shareable_content_callback)(SCShareableContent *,
  466. NSError *);
  467. shareable_content_callback new_content_received = ^void(
  468. SCShareableContent *shareable_content, NSError *error) {
  469. if (error == nil && sc->shareable_content_available != NULL) {
  470. sc->shareable_content = [shareable_content retain];
  471. } else {
  472. #ifdef DEBUG
  473. MACCAP_ERR(
  474. "screen_capture_properties: Failed to get shareable content with error %s\n",
  475. [[error localizedFailureReason]
  476. cStringUsingEncoding:
  477. NSUTF8StringEncoding]);
  478. #endif
  479. MACCAP_LOG(
  480. LOG_WARNING,
  481. "Unable to get list of available applications or windows. "
  482. "Please check if OBS has necessary screen capture permissions.");
  483. }
  484. os_sem_post(sc->shareable_content_available);
  485. };
  486. os_sem_wait(sc->shareable_content_available);
  487. [sc->shareable_content release];
  488. [SCShareableContent
  489. getShareableContentExcludingDesktopWindows:TRUE
  490. onScreenWindowsOnly:
  491. (display_capture
  492. ? FALSE
  493. : !sc->show_hidden_windows)
  494. completionHandler:new_content_received];
  495. }
  496. static void *screen_capture_create(obs_data_t *settings, obs_source_t *source)
  497. {
  498. struct screen_capture *sc = bzalloc(sizeof(struct screen_capture));
  499. sc->source = source;
  500. sc->hide_cursor = !obs_data_get_bool(settings, "show_cursor");
  501. sc->show_empty_names = obs_data_get_bool(settings, "show_empty_names");
  502. sc->show_hidden_windows =
  503. obs_data_get_bool(settings, "show_hidden_windows");
  504. sc->window = obs_data_get_int(settings, "window");
  505. sc->capture_type = obs_data_get_int(settings, "type");
  506. os_sem_init(&sc->shareable_content_available, 1);
  507. screen_capture_build_content_list(
  508. sc, sc->capture_type == ScreenCaptureDisplayStream);
  509. sc->capture_delegate = [[ScreenCaptureDelegate alloc] init];
  510. sc->capture_delegate.sc = sc;
  511. sc->effect = obs_get_base_effect(OBS_EFFECT_DEFAULT_RECT);
  512. if (!sc->effect)
  513. goto fail;
  514. sc->display = obs_data_get_int(settings, "display");
  515. sc->application_id = [[NSString alloc]
  516. initWithUTF8String:obs_data_get_string(settings,
  517. "application")];
  518. pthread_mutex_init(&sc->mutex, NULL);
  519. if (!init_screen_stream(sc))
  520. goto fail;
  521. return sc;
  522. fail:
  523. obs_leave_graphics();
  524. screen_capture_destroy(sc);
  525. return NULL;
  526. }
  527. static void screen_capture_video_tick(void *data,
  528. float seconds __attribute__((unused)))
  529. {
  530. struct screen_capture *sc = data;
  531. if (!sc->current)
  532. return;
  533. if (!obs_source_showing(sc->source))
  534. return;
  535. IOSurfaceRef prev_prev = sc->prev;
  536. if (pthread_mutex_lock(&sc->mutex))
  537. return;
  538. sc->prev = sc->current;
  539. sc->current = NULL;
  540. pthread_mutex_unlock(&sc->mutex);
  541. if (prev_prev == sc->prev)
  542. return;
  543. obs_enter_graphics();
  544. if (sc->tex)
  545. gs_texture_rebind_iosurface(sc->tex, sc->prev);
  546. else
  547. sc->tex = gs_texture_create_from_iosurface(sc->prev);
  548. obs_leave_graphics();
  549. if (prev_prev) {
  550. IOSurfaceDecrementUseCount(prev_prev);
  551. CFRelease(prev_prev);
  552. }
  553. }
  554. static void screen_capture_video_render(void *data, gs_effect_t *effect
  555. __attribute__((unused)))
  556. {
  557. struct screen_capture *sc = data;
  558. if (!sc->tex)
  559. return;
  560. const bool linear_srgb = gs_get_linear_srgb();
  561. const bool previous = gs_framebuffer_srgb_enabled();
  562. gs_enable_framebuffer_srgb(linear_srgb);
  563. gs_eparam_t *param = gs_effect_get_param_by_name(sc->effect, "image");
  564. if (linear_srgb)
  565. gs_effect_set_texture_srgb(param, sc->tex);
  566. else
  567. gs_effect_set_texture(param, sc->tex);
  568. while (gs_effect_loop(sc->effect, "Draw"))
  569. gs_draw_sprite(sc->tex, 0, 0, 0);
  570. gs_enable_framebuffer_srgb(previous);
  571. }
  572. static const char *screen_capture_getname(void *unused __attribute__((unused)))
  573. {
  574. if (@available(macOS 13.0, *))
  575. return obs_module_text("SCK.Name");
  576. else
  577. return obs_module_text("SCK.Name.Beta");
  578. }
  579. static uint32_t screen_capture_getwidth(void *data)
  580. {
  581. struct screen_capture *sc = data;
  582. return sc->frame.size.width;
  583. }
  584. static uint32_t screen_capture_getheight(void *data)
  585. {
  586. struct screen_capture *sc = data;
  587. return sc->frame.size.height;
  588. }
  589. static void screen_capture_defaults(obs_data_t *settings)
  590. {
  591. CGDirectDisplayID initial_display = 0;
  592. {
  593. NSScreen *mainScreen = [NSScreen mainScreen];
  594. if (mainScreen) {
  595. NSNumber *screen_num =
  596. mainScreen.deviceDescription[@"NSScreenNumber"];
  597. if (screen_num) {
  598. initial_display =
  599. (CGDirectDisplayID)(uintptr_t)
  600. screen_num.pointerValue;
  601. }
  602. }
  603. }
  604. obs_data_set_default_int(settings, "type", 0);
  605. obs_data_set_default_int(settings, "display", initial_display);
  606. obs_data_set_default_int(settings, "window", kCGNullWindowID);
  607. obs_data_set_default_obj(settings, "application", NULL);
  608. obs_data_set_default_bool(settings, "show_cursor", true);
  609. obs_data_set_default_bool(settings, "show_empty_names", false);
  610. obs_data_set_default_bool(settings, "show_hidden_windows", false);
  611. }
  612. static void screen_capture_update(void *data, obs_data_t *settings)
  613. {
  614. struct screen_capture *sc = data;
  615. CGWindowID old_window_id = sc->window;
  616. CGWindowID new_window_id = obs_data_get_int(settings, "window");
  617. if (new_window_id > 0 && new_window_id != old_window_id)
  618. sc->window = new_window_id;
  619. ScreenCaptureStreamType capture_type =
  620. (ScreenCaptureStreamType)obs_data_get_int(settings, "type");
  621. CGDirectDisplayID display =
  622. (CGDirectDisplayID)obs_data_get_int(settings, "display");
  623. NSString *application_id = [[NSString alloc]
  624. initWithUTF8String:obs_data_get_string(settings,
  625. "application")];
  626. bool show_cursor = obs_data_get_bool(settings, "show_cursor");
  627. bool show_empty_names = obs_data_get_bool(settings, "show_empty_names");
  628. bool show_hidden_windows =
  629. obs_data_get_bool(settings, "show_hidden_windows");
  630. if (capture_type == sc->capture_type) {
  631. switch (sc->capture_type) {
  632. case ScreenCaptureDisplayStream: {
  633. if (sc->display == display &&
  634. sc->hide_cursor != show_cursor)
  635. return;
  636. } break;
  637. case ScreenCaptureWindowStream: {
  638. if (old_window_id == sc->window &&
  639. sc->hide_cursor != show_cursor)
  640. return;
  641. } break;
  642. case ScreenCaptureApplicationStream: {
  643. if (sc->display == display &&
  644. [application_id
  645. isEqualToString:sc->application_id] &&
  646. sc->hide_cursor != show_cursor)
  647. return;
  648. } break;
  649. }
  650. }
  651. obs_enter_graphics();
  652. destroy_screen_stream(sc);
  653. sc->capture_type = capture_type;
  654. sc->display = display;
  655. sc->application_id = application_id;
  656. sc->hide_cursor = !show_cursor;
  657. sc->show_empty_names = show_empty_names;
  658. sc->show_hidden_windows = show_hidden_windows;
  659. init_screen_stream(sc);
  660. obs_leave_graphics();
  661. }
  662. static bool build_display_list(struct screen_capture *sc,
  663. obs_properties_t *props)
  664. {
  665. os_sem_wait(sc->shareable_content_available);
  666. obs_property_t *display_list = obs_properties_get(props, "display");
  667. obs_property_list_clear(display_list);
  668. [sc->shareable_content.displays enumerateObjectsUsingBlock:^(
  669. SCDisplay *_Nonnull display,
  670. NSUInteger idx
  671. __attribute__((unused)),
  672. BOOL *_Nonnull stop
  673. __attribute__((unused))) {
  674. NSUInteger screen_index = [NSScreen.screens
  675. indexOfObjectPassingTest:^BOOL(
  676. NSScreen *_Nonnull screen,
  677. NSUInteger index __attribute__((unused)),
  678. BOOL *_Nonnull stop) {
  679. NSNumber *screen_num =
  680. screen.deviceDescription
  681. [@"NSScreenNumber"];
  682. CGDirectDisplayID screen_display_id =
  683. (CGDirectDisplayID)screen_num.intValue;
  684. *stop = (screen_display_id ==
  685. display.displayID);
  686. return *stop;
  687. }];
  688. NSScreen *screen =
  689. [NSScreen.screens objectAtIndex:screen_index];
  690. char dimension_buffer[4][12] = {};
  691. char name_buffer[256] = {};
  692. sprintf(dimension_buffer[0], "%u",
  693. (uint32_t)screen.frame.size.width);
  694. sprintf(dimension_buffer[1], "%u",
  695. (uint32_t)screen.frame.size.height);
  696. sprintf(dimension_buffer[2], "%d",
  697. (int32_t)screen.frame.origin.x);
  698. sprintf(dimension_buffer[3], "%d",
  699. (int32_t)screen.frame.origin.y);
  700. sprintf(name_buffer, "%.200s: %.12sx%.12s @ %.12s,%.12s",
  701. screen.localizedName.UTF8String, dimension_buffer[0],
  702. dimension_buffer[1], dimension_buffer[2],
  703. dimension_buffer[3]);
  704. obs_property_list_add_int(display_list, name_buffer,
  705. display.displayID);
  706. }];
  707. os_sem_post(sc->shareable_content_available);
  708. return true;
  709. }
  710. static bool build_window_list(struct screen_capture *sc,
  711. obs_properties_t *props)
  712. {
  713. os_sem_wait(sc->shareable_content_available);
  714. obs_property_t *window_list = obs_properties_get(props, "window");
  715. obs_property_list_clear(window_list);
  716. [sc->shareable_content.windows enumerateObjectsUsingBlock:^(
  717. SCWindow *_Nonnull window,
  718. NSUInteger idx
  719. __attribute__((unused)),
  720. BOOL *_Nonnull stop
  721. __attribute__((unused))) {
  722. NSString *app_name = window.owningApplication.applicationName;
  723. NSString *title = window.title;
  724. if (!sc->show_empty_names) {
  725. if (app_name == NULL || title == NULL) {
  726. return;
  727. } else if ([app_name isEqualToString:@""] ||
  728. [title isEqualToString:@""]) {
  729. return;
  730. }
  731. }
  732. const char *list_text =
  733. [[NSString stringWithFormat:@"[%@] %@", app_name, title]
  734. UTF8String];
  735. obs_property_list_add_int(window_list, list_text,
  736. window.windowID);
  737. }];
  738. os_sem_post(sc->shareable_content_available);
  739. return true;
  740. }
  741. static bool build_application_list(struct screen_capture *sc,
  742. obs_properties_t *props)
  743. {
  744. os_sem_wait(sc->shareable_content_available);
  745. obs_property_t *application_list =
  746. obs_properties_get(props, "application");
  747. obs_property_list_clear(application_list);
  748. [sc->shareable_content.applications
  749. enumerateObjectsUsingBlock:^(
  750. SCRunningApplication *_Nonnull application,
  751. NSUInteger idx __attribute__((unused)),
  752. BOOL *_Nonnull stop __attribute__((unused))) {
  753. const char *name =
  754. [application.applicationName UTF8String];
  755. const char *bundle_id =
  756. [application.bundleIdentifier UTF8String];
  757. if (strcmp(name, "") != 0)
  758. obs_property_list_add_string(application_list,
  759. name, bundle_id);
  760. }];
  761. os_sem_post(sc->shareable_content_available);
  762. return true;
  763. }
  764. static bool content_settings_changed(void *data, obs_properties_t *props,
  765. obs_property_t *list
  766. __attribute__((unused)),
  767. obs_data_t *settings)
  768. {
  769. struct screen_capture *sc = data;
  770. unsigned int capture_type_id = obs_data_get_int(settings, "type");
  771. obs_property_t *display_list = obs_properties_get(props, "display");
  772. obs_property_t *window_list = obs_properties_get(props, "window");
  773. obs_property_t *app_list = obs_properties_get(props, "application");
  774. obs_property_t *empty = obs_properties_get(props, "show_empty_names");
  775. obs_property_t *hidden =
  776. obs_properties_get(props, "show_hidden_windows");
  777. if (sc->capture_type != capture_type_id) {
  778. switch (capture_type_id) {
  779. case 0: {
  780. obs_property_set_visible(display_list, true);
  781. obs_property_set_visible(window_list, false);
  782. obs_property_set_visible(app_list, false);
  783. obs_property_set_visible(empty, false);
  784. obs_property_set_visible(hidden, false);
  785. break;
  786. }
  787. case 1: {
  788. obs_property_set_visible(display_list, false);
  789. obs_property_set_visible(window_list, true);
  790. obs_property_set_visible(app_list, false);
  791. obs_property_set_visible(empty, true);
  792. obs_property_set_visible(hidden, true);
  793. break;
  794. }
  795. case 2: {
  796. obs_property_set_visible(display_list, true);
  797. obs_property_set_visible(app_list, true);
  798. obs_property_set_visible(window_list, false);
  799. obs_property_set_visible(empty, false);
  800. obs_property_set_visible(hidden, true);
  801. break;
  802. }
  803. }
  804. }
  805. sc->show_empty_names = obs_data_get_bool(settings, "show_empty_names");
  806. sc->show_hidden_windows =
  807. obs_data_get_bool(settings, "show_hidden_windows");
  808. screen_capture_build_content_list(
  809. sc, capture_type_id == ScreenCaptureDisplayStream);
  810. build_display_list(sc, props);
  811. build_window_list(sc, props);
  812. build_application_list(sc, props);
  813. return true;
  814. }
  815. static obs_properties_t *screen_capture_properties(void *data)
  816. {
  817. struct screen_capture *sc = data;
  818. obs_properties_t *props = obs_properties_create();
  819. obs_property_t *capture_type = obs_properties_add_list(
  820. props, "type", obs_module_text("SCK.Method"),
  821. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
  822. obs_property_list_add_int(capture_type,
  823. obs_module_text("DisplayCapture"), 0);
  824. obs_property_list_add_int(capture_type,
  825. obs_module_text("WindowCapture"), 1);
  826. obs_property_list_add_int(capture_type,
  827. obs_module_text("ApplicationCapture"), 2);
  828. obs_property_set_modified_callback2(capture_type,
  829. content_settings_changed, data);
  830. obs_property_t *display_list = obs_properties_add_list(
  831. props, "display", obs_module_text("DisplayCapture.Display"),
  832. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
  833. obs_property_t *app_list = obs_properties_add_list(
  834. props, "application", obs_module_text("Application"),
  835. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
  836. obs_property_t *window_list = obs_properties_add_list(
  837. props, "window", obs_module_text("WindowUtils.Window"),
  838. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
  839. obs_property_t *empty = obs_properties_add_bool(
  840. props, "show_empty_names",
  841. obs_module_text("WindowUtils.ShowEmptyNames"));
  842. obs_property_t *hidden = obs_properties_add_bool(
  843. props, "show_hidden_windows",
  844. obs_module_text("WindowUtils.ShowHidden"));
  845. obs_properties_add_bool(props, "show_cursor",
  846. obs_module_text("DisplayCapture.ShowCursor"));
  847. if (sc) {
  848. obs_property_set_modified_callback2(
  849. hidden, content_settings_changed, sc);
  850. switch (sc->capture_type) {
  851. case 0: {
  852. obs_property_set_visible(display_list, true);
  853. obs_property_set_visible(window_list, false);
  854. obs_property_set_visible(app_list, false);
  855. obs_property_set_visible(empty, false);
  856. obs_property_set_visible(hidden, false);
  857. break;
  858. }
  859. case 1: {
  860. obs_property_set_visible(display_list, false);
  861. obs_property_set_visible(window_list, true);
  862. obs_property_set_visible(app_list, false);
  863. obs_property_set_visible(empty, true);
  864. obs_property_set_visible(hidden, true);
  865. break;
  866. }
  867. case 2: {
  868. obs_property_set_visible(display_list, true);
  869. obs_property_set_visible(app_list, true);
  870. obs_property_set_visible(window_list, false);
  871. obs_property_set_visible(empty, false);
  872. obs_property_set_visible(hidden, true);
  873. break;
  874. }
  875. }
  876. obs_property_set_modified_callback2(
  877. empty, content_settings_changed, sc);
  878. }
  879. if (@available(macOS 13.0, *))
  880. ;
  881. else
  882. obs_properties_add_text(props, "audio_info",
  883. obs_module_text("SCK.AudioUnavailable"),
  884. OBS_TEXT_INFO);
  885. return props;
  886. }
  887. struct obs_source_info screen_capture_info = {
  888. .id = "screen_capture",
  889. .type = OBS_SOURCE_TYPE_INPUT,
  890. .get_name = screen_capture_getname,
  891. .create = screen_capture_create,
  892. .destroy = screen_capture_destroy,
  893. .output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CUSTOM_DRAW |
  894. OBS_SOURCE_DO_NOT_DUPLICATE | OBS_SOURCE_SRGB |
  895. OBS_SOURCE_AUDIO,
  896. .video_tick = screen_capture_video_tick,
  897. .video_render = screen_capture_video_render,
  898. .get_width = screen_capture_getwidth,
  899. .get_height = screen_capture_getheight,
  900. .get_defaults = screen_capture_defaults,
  901. .get_properties = screen_capture_properties,
  902. .update = screen_capture_update,
  903. .icon_type = OBS_ICON_TYPE_DESKTOP_CAPTURE,
  904. };
  905. @implementation ScreenCaptureDelegate
  906. - (void)stream:(SCStream *)stream
  907. didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer
  908. ofType:(SCStreamOutputType)type
  909. {
  910. if (self.sc != NULL) {
  911. if (type == SCStreamOutputTypeScreen) {
  912. screen_stream_video_update(self.sc, sampleBuffer);
  913. }
  914. #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 130000
  915. else if (@available(macOS 13.0, *)) {
  916. if (type == SCStreamOutputTypeAudio) {
  917. screen_stream_audio_update(self.sc,
  918. sampleBuffer);
  919. }
  920. }
  921. #endif
  922. }
  923. }
  924. @end
  925. // "-Wunguarded-availability-new"
  926. #pragma clang diagnostic pop
  927. #endif