mac-screen-capture.m 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169
  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. ScreenCaptureStreamType capture_type;
  51. CGDirectDisplayID display;
  52. CGWindowID window;
  53. NSString *application_id;
  54. };
  55. #pragma mark -
  56. static void destroy_screen_stream(struct screen_capture *sc)
  57. {
  58. if (sc->disp) {
  59. [sc->disp stopCaptureWithCompletionHandler:^(
  60. NSError *_Nullable error) {
  61. if (error && error.code != 3808) {
  62. MACCAP_ERR(
  63. "destroy_screen_stream: Failed to stop stream with error %s\n",
  64. [[error localizedFailureReason]
  65. cStringUsingEncoding:
  66. NSUTF8StringEncoding]);
  67. }
  68. os_event_signal(sc->disp_finished);
  69. }];
  70. os_event_wait(sc->disp_finished);
  71. }
  72. if (sc->stream_properties) {
  73. [sc->stream_properties release];
  74. sc->stream_properties = NULL;
  75. }
  76. if (sc->tex) {
  77. gs_texture_destroy(sc->tex);
  78. sc->tex = NULL;
  79. }
  80. if (sc->current) {
  81. IOSurfaceDecrementUseCount(sc->current);
  82. CFRelease(sc->current);
  83. sc->current = NULL;
  84. }
  85. if (sc->prev) {
  86. IOSurfaceDecrementUseCount(sc->prev);
  87. CFRelease(sc->prev);
  88. sc->prev = NULL;
  89. }
  90. if (sc->disp) {
  91. [sc->disp release];
  92. sc->disp = NULL;
  93. }
  94. os_event_destroy(sc->disp_finished);
  95. os_event_destroy(sc->stream_start_completed);
  96. }
  97. static void screen_capture_destroy(void *data)
  98. {
  99. struct screen_capture *sc = data;
  100. if (!sc)
  101. return;
  102. obs_enter_graphics();
  103. destroy_screen_stream(sc);
  104. obs_leave_graphics();
  105. if (sc->shareable_content) {
  106. os_sem_wait(sc->shareable_content_available);
  107. [sc->shareable_content release];
  108. os_sem_destroy(sc->shareable_content_available);
  109. sc->shareable_content_available = NULL;
  110. }
  111. if (sc->capture_delegate) {
  112. [sc->capture_delegate release];
  113. }
  114. [sc->application_id release];
  115. pthread_mutex_destroy(&sc->mutex);
  116. bfree(sc);
  117. }
  118. static inline void screen_stream_video_update(struct screen_capture *sc,
  119. CMSampleBufferRef sample_buffer)
  120. {
  121. bool frame_detail_errored = false;
  122. float scale_factor = 1.0f;
  123. CGRect window_rect = {};
  124. CFArrayRef attachments_array =
  125. CMSampleBufferGetSampleAttachmentsArray(sample_buffer, false);
  126. if (sc->capture_type == ScreenCaptureWindowStream &&
  127. attachments_array != NULL &&
  128. CFArrayGetCount(attachments_array) > 0) {
  129. CFDictionaryRef attachments_dict =
  130. CFArrayGetValueAtIndex(attachments_array, 0);
  131. if (attachments_dict != NULL) {
  132. CFTypeRef frame_scale_factor = CFDictionaryGetValue(
  133. attachments_dict, SCStreamFrameInfoScaleFactor);
  134. if (frame_scale_factor != NULL) {
  135. Boolean result = CFNumberGetValue(
  136. (CFNumberRef)frame_scale_factor,
  137. kCFNumberFloatType, &scale_factor);
  138. if (result == false) {
  139. scale_factor = 1.0f;
  140. frame_detail_errored = true;
  141. }
  142. }
  143. CFTypeRef content_rect_dict = CFDictionaryGetValue(
  144. attachments_dict, SCStreamFrameInfoContentRect);
  145. CFTypeRef content_scale_factor = CFDictionaryGetValue(
  146. attachments_dict,
  147. SCStreamFrameInfoContentScale);
  148. if ((content_rect_dict != NULL) &&
  149. (content_scale_factor != NULL)) {
  150. CGRect content_rect = {};
  151. float points_to_pixels = 0.0f;
  152. Boolean result =
  153. CGRectMakeWithDictionaryRepresentation(
  154. (__bridge CFDictionaryRef)
  155. content_rect_dict,
  156. &content_rect);
  157. if (result == false) {
  158. content_rect = CGRectZero;
  159. frame_detail_errored = true;
  160. }
  161. result = CFNumberGetValue(
  162. (CFNumberRef)content_scale_factor,
  163. kCFNumberFloatType, &points_to_pixels);
  164. if (result == false) {
  165. points_to_pixels = 1.0f;
  166. frame_detail_errored = true;
  167. }
  168. window_rect.origin = content_rect.origin;
  169. window_rect.size.width =
  170. content_rect.size.width /
  171. points_to_pixels * scale_factor;
  172. window_rect.size.height =
  173. content_rect.size.height /
  174. points_to_pixels * scale_factor;
  175. }
  176. }
  177. }
  178. CVImageBufferRef image_buffer =
  179. CMSampleBufferGetImageBuffer(sample_buffer);
  180. CVPixelBufferLockBaseAddress(image_buffer, 0);
  181. IOSurfaceRef frame_surface = CVPixelBufferGetIOSurface(image_buffer);
  182. CVPixelBufferUnlockBaseAddress(image_buffer, 0);
  183. IOSurfaceRef prev_current = NULL;
  184. if (frame_surface && !pthread_mutex_lock(&sc->mutex)) {
  185. bool needs_to_update_properties = false;
  186. if (!frame_detail_errored) {
  187. if (sc->capture_type == ScreenCaptureWindowStream) {
  188. if ((sc->frame.size.width !=
  189. window_rect.size.width) ||
  190. (sc->frame.size.height !=
  191. window_rect.size.height)) {
  192. sc->frame.size.width =
  193. window_rect.size.width;
  194. sc->frame.size.height =
  195. window_rect.size.height;
  196. needs_to_update_properties = true;
  197. }
  198. } else {
  199. size_t width =
  200. CVPixelBufferGetWidth(image_buffer);
  201. size_t height =
  202. CVPixelBufferGetHeight(image_buffer);
  203. if ((sc->frame.size.width != width) ||
  204. (sc->frame.size.height != height)) {
  205. sc->frame.size.width = width;
  206. sc->frame.size.height = height;
  207. needs_to_update_properties = true;
  208. }
  209. }
  210. }
  211. if (needs_to_update_properties) {
  212. [sc->stream_properties
  213. setWidth:(size_t)sc->frame.size.width];
  214. [sc->stream_properties
  215. setHeight:(size_t)sc->frame.size.height];
  216. [sc->disp
  217. updateConfiguration:sc->stream_properties
  218. completionHandler:^(
  219. NSError *_Nullable error) {
  220. if (error) {
  221. MACCAP_ERR(
  222. "screen_stream_video_update: Failed to update stream properties with error %s\n",
  223. [[error localizedFailureReason]
  224. cStringUsingEncoding:
  225. NSUTF8StringEncoding]);
  226. }
  227. }];
  228. }
  229. prev_current = sc->current;
  230. sc->current = frame_surface;
  231. CFRetain(sc->current);
  232. IOSurfaceIncrementUseCount(sc->current);
  233. pthread_mutex_unlock(&sc->mutex);
  234. }
  235. if (prev_current) {
  236. IOSurfaceDecrementUseCount(prev_current);
  237. CFRelease(prev_current);
  238. }
  239. }
  240. static inline void screen_stream_audio_update(struct screen_capture *sc,
  241. CMSampleBufferRef sample_buffer)
  242. {
  243. CMFormatDescriptionRef format_description =
  244. CMSampleBufferGetFormatDescription(sample_buffer);
  245. const AudioStreamBasicDescription *audio_description =
  246. CMAudioFormatDescriptionGetStreamBasicDescription(
  247. format_description);
  248. char *_Nullable bytes = NULL;
  249. CMBlockBufferRef data_buffer =
  250. CMSampleBufferGetDataBuffer(sample_buffer);
  251. size_t data_buffer_length = CMBlockBufferGetDataLength(data_buffer);
  252. CMBlockBufferGetDataPointer(data_buffer, 0, &data_buffer_length, NULL,
  253. &bytes);
  254. CMTime presentation_time =
  255. CMSampleBufferGetOutputPresentationTimeStamp(sample_buffer);
  256. struct obs_source_audio audio_data = {};
  257. for (uint32_t channel_idx = 0;
  258. channel_idx < audio_description->mChannelsPerFrame;
  259. ++channel_idx) {
  260. uint32_t offset =
  261. (uint32_t)(data_buffer_length /
  262. audio_description->mChannelsPerFrame) *
  263. channel_idx;
  264. audio_data.data[channel_idx] = (uint8_t *)bytes + offset;
  265. }
  266. audio_data.frames = (uint32_t)(data_buffer_length /
  267. audio_description->mBytesPerFrame /
  268. audio_description->mChannelsPerFrame);
  269. audio_data.speakers = audio_description->mChannelsPerFrame;
  270. audio_data.samples_per_sec = (uint32_t)audio_description->mSampleRate;
  271. audio_data.timestamp =
  272. (uint64_t)(CMTimeGetSeconds(presentation_time) * NSEC_PER_SEC);
  273. audio_data.format = AUDIO_FORMAT_FLOAT_PLANAR;
  274. obs_source_output_audio(sc->source, &audio_data);
  275. }
  276. static bool init_screen_stream(struct screen_capture *sc)
  277. {
  278. SCContentFilter *content_filter;
  279. sc->frame = CGRectZero;
  280. sc->stream_properties = [[SCStreamConfiguration alloc] init];
  281. os_sem_wait(sc->shareable_content_available);
  282. SCDisplay * (^get_target_display)() = ^SCDisplay *()
  283. {
  284. __block SCDisplay *target_display = nil;
  285. [sc->shareable_content.displays
  286. indexOfObjectPassingTest:^BOOL(
  287. SCDisplay *_Nonnull display, NSUInteger idx,
  288. BOOL *_Nonnull stop) {
  289. if (display.displayID == sc->display) {
  290. target_display = sc->shareable_content
  291. .displays[idx];
  292. *stop = TRUE;
  293. }
  294. return *stop;
  295. }];
  296. return target_display;
  297. };
  298. void (^set_display_mode)(struct screen_capture *, SCDisplay *) = ^void(
  299. struct screen_capture *capture_data,
  300. SCDisplay *target_display) {
  301. CGDisplayModeRef display_mode =
  302. CGDisplayCopyDisplayMode(target_display.displayID);
  303. [capture_data->stream_properties
  304. setWidth:CGDisplayModeGetPixelWidth(display_mode)];
  305. [capture_data->stream_properties
  306. setHeight:CGDisplayModeGetPixelHeight(display_mode)];
  307. CGDisplayModeRelease(display_mode);
  308. };
  309. switch (sc->capture_type) {
  310. case ScreenCaptureDisplayStream: {
  311. SCDisplay *target_display = get_target_display();
  312. NSArray *empty = [[NSArray alloc] init];
  313. content_filter = [[SCContentFilter alloc]
  314. initWithDisplay:target_display
  315. excludingWindows:empty];
  316. [empty release];
  317. set_display_mode(sc, target_display);
  318. } break;
  319. case ScreenCaptureWindowStream: {
  320. __block SCWindow *target_window = nil;
  321. if (sc->window != 0) {
  322. [sc->shareable_content.windows
  323. indexOfObjectPassingTest:^BOOL(
  324. SCWindow *_Nonnull window,
  325. NSUInteger idx, BOOL *_Nonnull stop) {
  326. if (window.windowID == sc->window) {
  327. target_window =
  328. sc->shareable_content
  329. .windows[idx];
  330. *stop = TRUE;
  331. }
  332. return *stop;
  333. }];
  334. } else {
  335. target_window =
  336. [sc->shareable_content.windows objectAtIndex:0];
  337. sc->window = target_window.windowID;
  338. }
  339. content_filter = [[SCContentFilter alloc]
  340. initWithDesktopIndependentWindow:target_window];
  341. if (target_window) {
  342. [sc->stream_properties
  343. setWidth:(size_t)target_window.frame.size.width];
  344. [sc->stream_properties
  345. setHeight:(size_t)target_window.frame.size
  346. .height];
  347. }
  348. } break;
  349. case ScreenCaptureApplicationStream: {
  350. SCDisplay *target_display = get_target_display();
  351. __block SCRunningApplication *target_application = nil;
  352. {
  353. [sc->shareable_content.applications
  354. indexOfObjectPassingTest:^BOOL(
  355. SCRunningApplication
  356. *_Nonnull application,
  357. NSUInteger idx, BOOL *_Nonnull stop) {
  358. if ([application.bundleIdentifier
  359. isEqualToString:
  360. sc->
  361. application_id]) {
  362. target_application =
  363. sc->shareable_content
  364. .applications
  365. [idx];
  366. *stop = TRUE;
  367. }
  368. return *stop;
  369. }];
  370. }
  371. NSArray *target_application_array = [[NSArray alloc]
  372. initWithObjects:target_application, nil];
  373. NSArray *empty_array = [[NSArray alloc] init];
  374. content_filter = [[SCContentFilter alloc]
  375. initWithDisplay:target_display
  376. includingApplications:target_application_array
  377. exceptingWindows:empty_array];
  378. [target_application_array release];
  379. [empty_array release];
  380. set_display_mode(sc, target_display);
  381. } break;
  382. }
  383. os_sem_post(sc->shareable_content_available);
  384. [sc->stream_properties setQueueDepth:8];
  385. [sc->stream_properties setShowsCursor:!sc->hide_cursor];
  386. [sc->stream_properties setColorSpaceName:kCGColorSpaceDisplayP3];
  387. FourCharCode l10r_type = 0;
  388. l10r_type = ('l' << 24) | ('1' << 16) | ('0' << 8) | 'r';
  389. [sc->stream_properties setPixelFormat:l10r_type];
  390. if (@available(macOS 13.0, *)) {
  391. #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 130000
  392. [sc->stream_properties setCapturesAudio:TRUE];
  393. [sc->stream_properties setExcludesCurrentProcessAudio:TRUE];
  394. [sc->stream_properties setChannelCount:2];
  395. #endif
  396. } else {
  397. if (sc->capture_type != ScreenCaptureWindowStream) {
  398. sc->disp = NULL;
  399. [content_filter release];
  400. os_event_init(&sc->disp_finished, OS_EVENT_TYPE_MANUAL);
  401. os_event_init(&sc->stream_start_completed,
  402. OS_EVENT_TYPE_MANUAL);
  403. return true;
  404. }
  405. }
  406. sc->disp = [[SCStream alloc] initWithFilter:content_filter
  407. configuration:sc->stream_properties
  408. delegate:nil];
  409. [content_filter release];
  410. NSError *addStreamOutputError = nil;
  411. BOOL did_add_output = [sc->disp addStreamOutput:sc->capture_delegate
  412. type:SCStreamOutputTypeScreen
  413. sampleHandlerQueue:nil
  414. error:&addStreamOutputError];
  415. if (!did_add_output) {
  416. MACCAP_ERR(
  417. "init_screen_stream: Failed to add stream output with error %s\n",
  418. [[addStreamOutputError localizedFailureReason]
  419. cStringUsingEncoding:NSUTF8StringEncoding]);
  420. [addStreamOutputError release];
  421. return !did_add_output;
  422. }
  423. #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 130000
  424. if (@available(macOS 13.0, *)) {
  425. did_add_output = [sc->disp
  426. addStreamOutput:sc->capture_delegate
  427. type:SCStreamOutputTypeAudio
  428. sampleHandlerQueue:nil
  429. error:&addStreamOutputError];
  430. if (!did_add_output) {
  431. MACCAP_ERR(
  432. "init_screen_stream: Failed to add audio stream output with error %s\n",
  433. [[addStreamOutputError localizedFailureReason]
  434. cStringUsingEncoding:
  435. NSUTF8StringEncoding]);
  436. [addStreamOutputError 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 = (CGWindowID)obs_data_get_int(settings, "window");
  505. sc->capture_type = (unsigned int)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 = (CGDirectDisplayID)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, float seconds __unused)
  528. {
  529. struct screen_capture *sc = data;
  530. if (!sc->current)
  531. return;
  532. if (!obs_source_showing(sc->source))
  533. return;
  534. IOSurfaceRef prev_prev = sc->prev;
  535. if (pthread_mutex_lock(&sc->mutex))
  536. return;
  537. sc->prev = sc->current;
  538. sc->current = NULL;
  539. pthread_mutex_unlock(&sc->mutex);
  540. if (prev_prev == sc->prev)
  541. return;
  542. obs_enter_graphics();
  543. if (sc->tex)
  544. gs_texture_rebind_iosurface(sc->tex, sc->prev);
  545. else
  546. sc->tex = gs_texture_create_from_iosurface(sc->prev);
  547. obs_leave_graphics();
  548. if (prev_prev) {
  549. IOSurfaceDecrementUseCount(prev_prev);
  550. CFRelease(prev_prev);
  551. }
  552. }
  553. static void screen_capture_video_render(void *data,
  554. gs_effect_t *effect __unused)
  555. {
  556. struct screen_capture *sc = data;
  557. if (!sc->tex)
  558. return;
  559. const bool previous = gs_framebuffer_srgb_enabled();
  560. gs_enable_framebuffer_srgb(true);
  561. gs_eparam_t *param = gs_effect_get_param_by_name(sc->effect, "image");
  562. gs_effect_set_texture(param, sc->tex);
  563. while (gs_effect_loop(sc->effect, "DrawD65P3"))
  564. gs_draw_sprite(sc->tex, 0, 0, 0);
  565. gs_enable_framebuffer_srgb(previous);
  566. }
  567. static const char *screen_capture_getname(void *unused __unused)
  568. {
  569. if (@available(macOS 13.0, *))
  570. return obs_module_text("SCK.Name");
  571. else
  572. return obs_module_text("SCK.Name.Beta");
  573. }
  574. static uint32_t screen_capture_getwidth(void *data)
  575. {
  576. struct screen_capture *sc = data;
  577. return (uint32_t)sc->frame.size.width;
  578. }
  579. static uint32_t screen_capture_getheight(void *data)
  580. {
  581. struct screen_capture *sc = data;
  582. return (uint32_t)sc->frame.size.height;
  583. }
  584. static void screen_capture_defaults(obs_data_t *settings)
  585. {
  586. CGDirectDisplayID initial_display = 0;
  587. {
  588. NSScreen *mainScreen = [NSScreen mainScreen];
  589. if (mainScreen) {
  590. NSNumber *screen_num =
  591. mainScreen.deviceDescription[@"NSScreenNumber"];
  592. if (screen_num) {
  593. initial_display =
  594. (CGDirectDisplayID)(uintptr_t)
  595. screen_num.pointerValue;
  596. }
  597. }
  598. }
  599. obs_data_set_default_int(settings, "display", initial_display);
  600. obs_data_set_default_obj(settings, "application", NULL);
  601. obs_data_set_default_int(settings, "type", ScreenCaptureDisplayStream);
  602. obs_data_set_default_int(settings, "window", kCGNullWindowID);
  603. obs_data_set_default_bool(settings, "show_cursor", true);
  604. obs_data_set_default_bool(settings, "show_empty_names", false);
  605. obs_data_set_default_bool(settings, "show_hidden_windows", false);
  606. }
  607. static void screen_capture_update(void *data, obs_data_t *settings)
  608. {
  609. struct screen_capture *sc = data;
  610. CGWindowID old_window_id = sc->window;
  611. CGWindowID new_window_id =
  612. (CGWindowID)obs_data_get_int(settings, "window");
  613. if (new_window_id > 0 && new_window_id != old_window_id)
  614. sc->window = new_window_id;
  615. ScreenCaptureStreamType capture_type =
  616. (ScreenCaptureStreamType)obs_data_get_int(settings, "type");
  617. CGDirectDisplayID display =
  618. (CGDirectDisplayID)obs_data_get_int(settings, "display");
  619. NSString *application_id = [[NSString alloc]
  620. initWithUTF8String:obs_data_get_string(settings,
  621. "application")];
  622. bool show_cursor = obs_data_get_bool(settings, "show_cursor");
  623. bool show_empty_names = obs_data_get_bool(settings, "show_empty_names");
  624. bool show_hidden_windows =
  625. obs_data_get_bool(settings, "show_hidden_windows");
  626. if (capture_type == sc->capture_type) {
  627. switch (sc->capture_type) {
  628. case ScreenCaptureDisplayStream: {
  629. if (sc->display == display &&
  630. sc->hide_cursor != show_cursor) {
  631. [application_id release];
  632. return;
  633. }
  634. } break;
  635. case ScreenCaptureWindowStream: {
  636. if (old_window_id == sc->window &&
  637. sc->hide_cursor != show_cursor) {
  638. [application_id release];
  639. return;
  640. }
  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. [application_id release];
  648. return;
  649. }
  650. } break;
  651. }
  652. }
  653. obs_enter_graphics();
  654. destroy_screen_stream(sc);
  655. sc->capture_type = capture_type;
  656. sc->display = display;
  657. [sc->application_id release];
  658. sc->application_id = application_id;
  659. sc->hide_cursor = !show_cursor;
  660. sc->show_empty_names = show_empty_names;
  661. sc->show_hidden_windows = show_hidden_windows;
  662. init_screen_stream(sc);
  663. obs_leave_graphics();
  664. }
  665. #pragma mark - obs_properties
  666. static bool build_display_list(struct screen_capture *sc,
  667. obs_properties_t *props)
  668. {
  669. os_sem_wait(sc->shareable_content_available);
  670. obs_property_t *display_list = obs_properties_get(props, "display");
  671. obs_property_list_clear(display_list);
  672. [sc->shareable_content.displays enumerateObjectsUsingBlock:^(
  673. SCDisplay *_Nonnull display,
  674. NSUInteger idx __unused,
  675. BOOL *_Nonnull _stop __unused) {
  676. NSUInteger screen_index =
  677. [NSScreen.screens indexOfObjectPassingTest:^BOOL(
  678. NSScreen *_Nonnull screen,
  679. NSUInteger index __unused,
  680. BOOL *_Nonnull stop) {
  681. NSNumber *screen_num =
  682. screen.deviceDescription
  683. [@"NSScreenNumber"];
  684. CGDirectDisplayID screen_display_id =
  685. (CGDirectDisplayID)screen_num.intValue;
  686. *stop = (screen_display_id ==
  687. display.displayID);
  688. return *stop;
  689. }];
  690. NSScreen *screen =
  691. [NSScreen.screens objectAtIndex:screen_index];
  692. char dimension_buffer[4][12] = {};
  693. char name_buffer[256] = {};
  694. snprintf(dimension_buffer[0], sizeof(dimension_buffer[0]), "%u",
  695. (uint32_t)screen.frame.size.width);
  696. snprintf(dimension_buffer[1], sizeof(dimension_buffer[0]), "%u",
  697. (uint32_t)screen.frame.size.height);
  698. snprintf(dimension_buffer[2], sizeof(dimension_buffer[0]), "%d",
  699. (int32_t)screen.frame.origin.x);
  700. snprintf(dimension_buffer[3], sizeof(dimension_buffer[0]), "%d",
  701. (int32_t)screen.frame.origin.y);
  702. snprintf(name_buffer, sizeof(name_buffer),
  703. "%.200s: %.12sx%.12s @ %.12s,%.12s",
  704. screen.localizedName.UTF8String, dimension_buffer[0],
  705. dimension_buffer[1], dimension_buffer[2],
  706. dimension_buffer[3]);
  707. obs_property_list_add_int(display_list, name_buffer,
  708. display.displayID);
  709. }];
  710. os_sem_post(sc->shareable_content_available);
  711. return true;
  712. }
  713. static bool build_window_list(struct screen_capture *sc,
  714. obs_properties_t *props)
  715. {
  716. os_sem_wait(sc->shareable_content_available);
  717. obs_property_t *window_list = obs_properties_get(props, "window");
  718. obs_property_list_clear(window_list);
  719. [sc->shareable_content.windows enumerateObjectsUsingBlock:^(
  720. SCWindow *_Nonnull window,
  721. NSUInteger idx __unused,
  722. BOOL *_Nonnull stop __unused) {
  723. NSString *app_name = window.owningApplication.applicationName;
  724. NSString *title = window.title;
  725. if (!sc->show_empty_names) {
  726. if (app_name == NULL || title == NULL) {
  727. return;
  728. } else if ([app_name isEqualToString:@""] ||
  729. [title isEqualToString:@""]) {
  730. return;
  731. }
  732. }
  733. const char *list_text =
  734. [[NSString stringWithFormat:@"[%@] %@", app_name, title]
  735. UTF8String];
  736. obs_property_list_add_int(window_list, list_text,
  737. window.windowID);
  738. }];
  739. os_sem_post(sc->shareable_content_available);
  740. return true;
  741. }
  742. static bool build_application_list(struct screen_capture *sc,
  743. obs_properties_t *props)
  744. {
  745. os_sem_wait(sc->shareable_content_available);
  746. obs_property_t *application_list =
  747. obs_properties_get(props, "application");
  748. obs_property_list_clear(application_list);
  749. [sc->shareable_content.applications
  750. enumerateObjectsUsingBlock:^(
  751. SCRunningApplication *_Nonnull application,
  752. NSUInteger idx __unused, BOOL *_Nonnull stop __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 __unused,
  766. obs_data_t *settings)
  767. {
  768. struct screen_capture *sc = data;
  769. unsigned int capture_type_id =
  770. (unsigned int)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. obs_property_t *capture_type_error =
  778. obs_properties_get(props, "capture_type_info");
  779. if (sc->capture_type != capture_type_id) {
  780. switch (capture_type_id) {
  781. case 0: {
  782. obs_property_set_visible(display_list, true);
  783. obs_property_set_visible(window_list, false);
  784. obs_property_set_visible(app_list, false);
  785. obs_property_set_visible(empty, false);
  786. obs_property_set_visible(hidden, false);
  787. if (capture_type_error) {
  788. obs_property_set_visible(capture_type_error,
  789. true);
  790. }
  791. break;
  792. }
  793. case 1: {
  794. obs_property_set_visible(display_list, false);
  795. obs_property_set_visible(window_list, true);
  796. obs_property_set_visible(app_list, false);
  797. obs_property_set_visible(empty, true);
  798. obs_property_set_visible(hidden, true);
  799. if (capture_type_error) {
  800. obs_property_set_visible(capture_type_error,
  801. false);
  802. }
  803. break;
  804. }
  805. case 2: {
  806. obs_property_set_visible(display_list, true);
  807. obs_property_set_visible(app_list, true);
  808. obs_property_set_visible(window_list, false);
  809. obs_property_set_visible(empty, false);
  810. obs_property_set_visible(hidden, true);
  811. if (capture_type_error) {
  812. obs_property_set_visible(capture_type_error,
  813. true);
  814. }
  815. break;
  816. }
  817. }
  818. }
  819. screen_capture_build_content_list(
  820. sc, capture_type_id == ScreenCaptureDisplayStream);
  821. build_display_list(sc, props);
  822. build_window_list(sc, props);
  823. build_application_list(sc, props);
  824. sc->show_empty_names = obs_data_get_bool(settings, "show_empty_names");
  825. sc->show_hidden_windows =
  826. obs_data_get_bool(settings, "show_hidden_windows");
  827. return true;
  828. }
  829. static obs_properties_t *screen_capture_properties(void *data)
  830. {
  831. struct screen_capture *sc = data;
  832. obs_properties_t *props = obs_properties_create();
  833. obs_property_t *capture_type = obs_properties_add_list(
  834. props, "type", obs_module_text("SCK.Method"),
  835. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
  836. obs_property_list_add_int(capture_type,
  837. obs_module_text("DisplayCapture"), 0);
  838. obs_property_list_add_int(capture_type,
  839. obs_module_text("WindowCapture"), 1);
  840. obs_property_list_add_int(capture_type,
  841. obs_module_text("ApplicationCapture"), 2);
  842. obs_property_set_modified_callback2(capture_type,
  843. content_settings_changed, data);
  844. obs_property_t *display_list = obs_properties_add_list(
  845. props, "display", obs_module_text("DisplayCapture.Display"),
  846. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
  847. obs_property_t *app_list = obs_properties_add_list(
  848. props, "application", obs_module_text("Application"),
  849. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
  850. obs_property_t *window_list = obs_properties_add_list(
  851. props, "window", obs_module_text("WindowUtils.Window"),
  852. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
  853. obs_property_t *empty = obs_properties_add_bool(
  854. props, "show_empty_names",
  855. obs_module_text("WindowUtils.ShowEmptyNames"));
  856. obs_property_t *hidden = obs_properties_add_bool(
  857. props, "show_hidden_windows",
  858. obs_module_text("WindowUtils.ShowHidden"));
  859. if (sc) {
  860. obs_property_set_modified_callback2(
  861. hidden, content_settings_changed, sc);
  862. switch (sc->capture_type) {
  863. case 0: {
  864. obs_property_set_visible(display_list, true);
  865. obs_property_set_visible(window_list, false);
  866. obs_property_set_visible(app_list, false);
  867. obs_property_set_visible(empty, false);
  868. obs_property_set_visible(hidden, false);
  869. break;
  870. }
  871. case 1: {
  872. obs_property_set_visible(display_list, false);
  873. obs_property_set_visible(window_list, true);
  874. obs_property_set_visible(app_list, false);
  875. obs_property_set_visible(empty, true);
  876. obs_property_set_visible(hidden, true);
  877. break;
  878. }
  879. case 2: {
  880. obs_property_set_visible(display_list, true);
  881. obs_property_set_visible(app_list, true);
  882. obs_property_set_visible(window_list, false);
  883. obs_property_set_visible(empty, false);
  884. obs_property_set_visible(hidden, true);
  885. break;
  886. }
  887. }
  888. obs_property_set_modified_callback2(
  889. empty, content_settings_changed, sc);
  890. }
  891. obs_properties_add_bool(props, "show_cursor",
  892. obs_module_text("DisplayCapture.ShowCursor"));
  893. if (@available(macOS 13.0, *))
  894. ;
  895. else {
  896. obs_property_t *audio_warning = obs_properties_add_text(
  897. props, "audio_info",
  898. obs_module_text("SCK.AudioUnavailable"), OBS_TEXT_INFO);
  899. obs_property_text_set_info_type(audio_warning,
  900. OBS_TEXT_INFO_WARNING);
  901. obs_property_t *capture_type_error = obs_properties_add_text(
  902. props, "capture_type_info",
  903. obs_module_text("SCK.CaptureTypeUnavailable"),
  904. OBS_TEXT_INFO);
  905. obs_property_text_set_info_type(capture_type_error,
  906. OBS_TEXT_INFO_ERROR);
  907. if (sc) {
  908. switch (sc->capture_type) {
  909. case ScreenCaptureDisplayStream: {
  910. obs_property_set_visible(capture_type_error,
  911. true);
  912. break;
  913. }
  914. case ScreenCaptureWindowStream: {
  915. obs_property_set_visible(capture_type_error,
  916. false);
  917. break;
  918. }
  919. case ScreenCaptureApplicationStream: {
  920. obs_property_set_visible(capture_type_error,
  921. true);
  922. break;
  923. }
  924. }
  925. } else {
  926. obs_property_set_visible(capture_type_error, false);
  927. }
  928. }
  929. return props;
  930. }
  931. enum gs_color_space screen_capture_video_get_color_space(
  932. void *data, size_t count, const enum gs_color_space *preferred_spaces)
  933. {
  934. UNUSED_PARAMETER(data);
  935. for (size_t i = 0; i < count; ++i) {
  936. if (preferred_spaces[i] == GS_CS_SRGB_16F)
  937. return GS_CS_SRGB_16F;
  938. }
  939. for (size_t i = 0; i < count; ++i) {
  940. if (preferred_spaces[i] == GS_CS_709_EXTENDED)
  941. return GS_CS_709_EXTENDED;
  942. }
  943. for (size_t i = 0; i < count; ++i) {
  944. if (preferred_spaces[i] == GS_CS_SRGB)
  945. return GS_CS_SRGB;
  946. }
  947. return GS_CS_SRGB_16F;
  948. }
  949. #pragma mark - obs_source_info
  950. struct obs_source_info screen_capture_info = {
  951. .id = "screen_capture",
  952. .type = OBS_SOURCE_TYPE_INPUT,
  953. .get_name = screen_capture_getname,
  954. .create = screen_capture_create,
  955. .destroy = screen_capture_destroy,
  956. .output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CUSTOM_DRAW |
  957. OBS_SOURCE_DO_NOT_DUPLICATE | OBS_SOURCE_SRGB |
  958. OBS_SOURCE_AUDIO,
  959. .video_tick = screen_capture_video_tick,
  960. .video_render = screen_capture_video_render,
  961. .get_width = screen_capture_getwidth,
  962. .get_height = screen_capture_getheight,
  963. .get_defaults = screen_capture_defaults,
  964. .get_properties = screen_capture_properties,
  965. .update = screen_capture_update,
  966. .icon_type = OBS_ICON_TYPE_DESKTOP_CAPTURE,
  967. .video_get_color_space = screen_capture_video_get_color_space,
  968. };
  969. #pragma mark - ScreenCaptureDelegate
  970. @implementation ScreenCaptureDelegate
  971. - (void)stream:(SCStream *)stream
  972. didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer
  973. ofType:(SCStreamOutputType)type
  974. {
  975. if (self.sc != NULL) {
  976. if (type == SCStreamOutputTypeScreen) {
  977. screen_stream_video_update(self.sc, sampleBuffer);
  978. }
  979. #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 130000
  980. else if (@available(macOS 13.0, *)) {
  981. if (type == SCStreamOutputTypeAudio) {
  982. screen_stream_audio_update(self.sc,
  983. sampleBuffer);
  984. }
  985. }
  986. #endif
  987. }
  988. }
  989. @end
  990. // "-Wunguarded-availability-new"
  991. #pragma clang diagnostic pop
  992. #endif