mac-sck-common.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. #include "mac-sck-common.h"
  2. bool is_screen_capture_available(void)
  3. {
  4. if (@available(macOS 12.5, *)) {
  5. return true;
  6. } else {
  7. return false;
  8. }
  9. }
  10. #pragma mark - ScreenCaptureDelegate
  11. @implementation ScreenCaptureDelegate
  12. - (void)stream:(SCStream *)stream didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer ofType:(SCStreamOutputType)type
  13. {
  14. if (self.sc != NULL) {
  15. if (type == SCStreamOutputTypeScreen && !self.sc->audio_only) {
  16. screen_stream_video_update(self.sc, sampleBuffer);
  17. } else if (@available(macOS 13.0, *)) {
  18. if (type == SCStreamOutputTypeAudio) {
  19. screen_stream_audio_update(self.sc, sampleBuffer);
  20. }
  21. }
  22. }
  23. }
  24. - (void)stream:(SCStream *)stream didStopWithError:(NSError *)error
  25. {
  26. NSString *errorMessage;
  27. switch (error.code) {
  28. case SCStreamErrorUserStopped:
  29. errorMessage = @"User stopped stream.";
  30. break;
  31. case SCStreamErrorNoCaptureSource:
  32. errorMessage = @"Stream stopped as no capture source was not found.";
  33. break;
  34. default:
  35. errorMessage = [NSString stringWithFormat:@"Stream stopped with error %ld (\"%s\")", error.code,
  36. error.localizedDescription.UTF8String];
  37. break;
  38. }
  39. MACCAP_LOG(LOG_WARNING, "%s", errorMessage.UTF8String);
  40. self.sc->capture_failed = true;
  41. obs_source_update_properties(self.sc->source);
  42. }
  43. @end
  44. #pragma mark - obs_properties
  45. void screen_capture_build_content_list(struct screen_capture *sc, bool display_capture)
  46. {
  47. typedef void (^shareable_content_callback)(SCShareableContent *, NSError *);
  48. shareable_content_callback new_content_received = ^void(SCShareableContent *shareable_content, NSError *error) {
  49. if (error == nil && sc->shareable_content_available != NULL) {
  50. sc->shareable_content = [shareable_content retain];
  51. } else {
  52. #ifdef DEBUG
  53. MACCAP_ERR("screen_capture_properties: Failed to get shareable content with error %s\n",
  54. [[error localizedFailureReason] cStringUsingEncoding:NSUTF8StringEncoding]);
  55. #endif
  56. MACCAP_LOG(LOG_WARNING, "Unable to get list of available applications or windows. "
  57. "Please check if OBS has necessary screen capture permissions.");
  58. }
  59. os_sem_post(sc->shareable_content_available);
  60. };
  61. os_sem_wait(sc->shareable_content_available);
  62. [sc->shareable_content release];
  63. BOOL onScreenWindowsOnly = (display_capture) ? NO : !sc->show_hidden_windows;
  64. [SCShareableContent getShareableContentExcludingDesktopWindows:YES onScreenWindowsOnly:onScreenWindowsOnly
  65. completionHandler:new_content_received];
  66. }
  67. bool build_display_list(struct screen_capture *sc, obs_properties_t *props)
  68. {
  69. os_sem_wait(sc->shareable_content_available);
  70. obs_property_t *display_list = obs_properties_get(props, "display_uuid");
  71. obs_property_list_clear(display_list);
  72. for (SCDisplay *display in sc->shareable_content.displays) {
  73. NSScreen *display_screen = nil;
  74. for (NSScreen *screen in NSScreen.screens) {
  75. NSNumber *screen_num = screen.deviceDescription[@"NSScreenNumber"];
  76. CGDirectDisplayID screen_display_id = (CGDirectDisplayID) screen_num.intValue;
  77. if (screen_display_id == display.displayID) {
  78. display_screen = screen;
  79. break;
  80. }
  81. }
  82. if (!display_screen) {
  83. continue;
  84. }
  85. char dimension_buffer[4][12] = {};
  86. char name_buffer[256] = {};
  87. snprintf(dimension_buffer[0], sizeof(dimension_buffer[0]), "%u", (uint32_t) display_screen.frame.size.width);
  88. snprintf(dimension_buffer[1], sizeof(dimension_buffer[0]), "%u", (uint32_t) display_screen.frame.size.height);
  89. snprintf(dimension_buffer[2], sizeof(dimension_buffer[0]), "%d", (int32_t) display_screen.frame.origin.x);
  90. snprintf(dimension_buffer[3], sizeof(dimension_buffer[0]), "%d", (int32_t) display_screen.frame.origin.y);
  91. snprintf(name_buffer, sizeof(name_buffer), "%.200s: %.12sx%.12s @ %.12s,%.12s",
  92. display_screen.localizedName.UTF8String, dimension_buffer[0], dimension_buffer[1], dimension_buffer[2],
  93. dimension_buffer[3]);
  94. CFUUIDRef display_uuid = CGDisplayCreateUUIDFromDisplayID(display.displayID);
  95. CFStringRef uuid_string = CFUUIDCreateString(kCFAllocatorDefault, display_uuid);
  96. obs_property_list_add_string(display_list, name_buffer,
  97. CFStringGetCStringPtr(uuid_string, kCFStringEncodingUTF8));
  98. CFRelease(uuid_string);
  99. CFRelease(display_uuid);
  100. }
  101. os_sem_post(sc->shareable_content_available);
  102. return true;
  103. }
  104. bool build_window_list(struct screen_capture *sc, obs_properties_t *props)
  105. {
  106. os_sem_wait(sc->shareable_content_available);
  107. obs_property_t *window_list = obs_properties_get(props, "window");
  108. obs_property_list_clear(window_list);
  109. NSPredicate *filteredWindowPredicate =
  110. [NSPredicate predicateWithBlock:^BOOL(SCWindow *window, NSDictionary *bindings __unused) {
  111. NSString *app_name = window.owningApplication.applicationName;
  112. NSString *title = window.title;
  113. if (!sc->show_empty_names) {
  114. return (app_name.length > 0) && (title.length > 0);
  115. } else {
  116. return YES;
  117. }
  118. }];
  119. NSArray<SCWindow *> *filteredWindows;
  120. filteredWindows = [sc->shareable_content.windows filteredArrayUsingPredicate:filteredWindowPredicate];
  121. NSArray<SCWindow *> *sortedWindows;
  122. sortedWindows = [filteredWindows sortedArrayUsingComparator:^NSComparisonResult(SCWindow *window, SCWindow *other) {
  123. NSComparisonResult appNameCmp = [window.owningApplication.applicationName
  124. compare:other.owningApplication.applicationName
  125. options:NSCaseInsensitiveSearch];
  126. if (appNameCmp == NSOrderedAscending) {
  127. return NSOrderedAscending;
  128. } else if (appNameCmp == NSOrderedSame) {
  129. return [window.title compare:other.title options:NSCaseInsensitiveSearch];
  130. } else {
  131. return NSOrderedDescending;
  132. }
  133. }];
  134. for (SCWindow *window in sortedWindows) {
  135. NSString *app_name = window.owningApplication.applicationName;
  136. NSString *title = window.title;
  137. const char *list_text = [[NSString stringWithFormat:@"[%@] %@", app_name, title] UTF8String];
  138. obs_property_list_add_int(window_list, list_text, window.windowID);
  139. }
  140. os_sem_post(sc->shareable_content_available);
  141. return true;
  142. }
  143. bool build_application_list(struct screen_capture *sc, obs_properties_t *props)
  144. {
  145. os_sem_wait(sc->shareable_content_available);
  146. obs_property_t *application_list = obs_properties_get(props, "application");
  147. obs_property_list_clear(application_list);
  148. NSArray<SCRunningApplication *> *filteredApplications;
  149. filteredApplications = [sc->shareable_content.applications
  150. filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(SCRunningApplication *app,
  151. NSDictionary *bindings __unused) {
  152. return app.applicationName.length > 0;
  153. }]];
  154. NSArray<SCRunningApplication *> *sortedApplications;
  155. sortedApplications = [filteredApplications
  156. sortedArrayUsingComparator:^NSComparisonResult(SCRunningApplication *app, SCRunningApplication *other) {
  157. return [app.applicationName compare:other.applicationName options:NSCaseInsensitiveSearch];
  158. }];
  159. for (SCRunningApplication *application in sortedApplications) {
  160. const char *name = [application.applicationName UTF8String];
  161. const char *bundle_id = [application.bundleIdentifier UTF8String];
  162. obs_property_list_add_string(application_list, name, bundle_id);
  163. }
  164. os_sem_post(sc->shareable_content_available);
  165. return true;
  166. }
  167. #pragma mark - audio/video
  168. API_AVAILABLE(macos(12.5)) void screen_stream_video_update(struct screen_capture *sc, CMSampleBufferRef sample_buffer)
  169. {
  170. bool frame_detail_errored = false;
  171. float scale_factor = 1.0f;
  172. CGRect window_rect = {};
  173. CFArrayRef attachments_array = CMSampleBufferGetSampleAttachmentsArray(sample_buffer, false);
  174. if (sc->capture_type == ScreenCaptureWindowStream && attachments_array != NULL &&
  175. CFArrayGetCount(attachments_array) > 0) {
  176. CFDictionaryRef attachments_dict = CFArrayGetValueAtIndex(attachments_array, 0);
  177. if (attachments_dict != NULL) {
  178. CFTypeRef frame_scale_factor = CFDictionaryGetValue(attachments_dict, SCStreamFrameInfoScaleFactor);
  179. if (frame_scale_factor != NULL) {
  180. Boolean result = CFNumberGetValue((CFNumberRef) frame_scale_factor, kCFNumberFloatType, &scale_factor);
  181. if (result == false) {
  182. scale_factor = 1.0f;
  183. frame_detail_errored = true;
  184. }
  185. }
  186. CFTypeRef content_rect_dict = CFDictionaryGetValue(attachments_dict, SCStreamFrameInfoContentRect);
  187. CFTypeRef content_scale_factor = CFDictionaryGetValue(attachments_dict, SCStreamFrameInfoContentScale);
  188. if ((content_rect_dict != NULL) && (content_scale_factor != NULL)) {
  189. CGRect content_rect = {};
  190. float points_to_pixels = 0.0f;
  191. Boolean result =
  192. CGRectMakeWithDictionaryRepresentation((__bridge CFDictionaryRef) content_rect_dict, &content_rect);
  193. if (result == false) {
  194. content_rect = CGRectZero;
  195. frame_detail_errored = true;
  196. }
  197. result = CFNumberGetValue((CFNumberRef) content_scale_factor, kCFNumberFloatType, &points_to_pixels);
  198. if (result == false) {
  199. points_to_pixels = 1.0f;
  200. frame_detail_errored = true;
  201. }
  202. window_rect.origin = content_rect.origin;
  203. window_rect.size.width = content_rect.size.width / points_to_pixels * scale_factor;
  204. window_rect.size.height = content_rect.size.height / points_to_pixels * scale_factor;
  205. }
  206. }
  207. }
  208. CVImageBufferRef image_buffer = CMSampleBufferGetImageBuffer(sample_buffer);
  209. CVPixelBufferLockBaseAddress(image_buffer, 0);
  210. IOSurfaceRef frame_surface = CVPixelBufferGetIOSurface(image_buffer);
  211. CVPixelBufferUnlockBaseAddress(image_buffer, 0);
  212. IOSurfaceRef prev_current = NULL;
  213. if (frame_surface && !pthread_mutex_lock(&sc->mutex)) {
  214. bool needs_to_update_properties = false;
  215. if (!frame_detail_errored) {
  216. if (sc->capture_type == ScreenCaptureWindowStream) {
  217. if ((sc->frame.size.width != window_rect.size.width) ||
  218. (sc->frame.size.height != window_rect.size.height)) {
  219. sc->frame.size.width = window_rect.size.width;
  220. sc->frame.size.height = window_rect.size.height;
  221. needs_to_update_properties = true;
  222. }
  223. } else {
  224. size_t width = CVPixelBufferGetWidth(image_buffer);
  225. size_t height = CVPixelBufferGetHeight(image_buffer);
  226. if ((sc->frame.size.width != width) || (sc->frame.size.height != height)) {
  227. sc->frame.size.width = width;
  228. sc->frame.size.height = height;
  229. needs_to_update_properties = true;
  230. }
  231. }
  232. }
  233. if (needs_to_update_properties) {
  234. [sc->stream_properties setWidth:(size_t) sc->frame.size.width];
  235. [sc->stream_properties setHeight:(size_t) sc->frame.size.height];
  236. [sc->disp updateConfiguration:sc->stream_properties completionHandler:^(NSError *_Nullable error) {
  237. if (error) {
  238. MACCAP_ERR("screen_stream_video_update: Failed to update stream properties with error %s\n",
  239. [[error localizedFailureReason] cStringUsingEncoding:NSUTF8StringEncoding]);
  240. }
  241. }];
  242. }
  243. prev_current = sc->current;
  244. sc->current = frame_surface;
  245. CFRetain(sc->current);
  246. IOSurfaceIncrementUseCount(sc->current);
  247. pthread_mutex_unlock(&sc->mutex);
  248. }
  249. if (prev_current) {
  250. IOSurfaceDecrementUseCount(prev_current);
  251. CFRelease(prev_current);
  252. }
  253. }
  254. void screen_stream_audio_update(struct screen_capture *sc, CMSampleBufferRef sample_buffer)
  255. {
  256. CMFormatDescriptionRef format_description = CMSampleBufferGetFormatDescription(sample_buffer);
  257. const AudioStreamBasicDescription *audio_description =
  258. CMAudioFormatDescriptionGetStreamBasicDescription(format_description);
  259. if (audio_description->mChannelsPerFrame < 1) {
  260. MACCAP_ERR(
  261. "screen_stream_audio_update: Received sample buffer has less than 1 channel per frame (mChannelsPerFrame set to '%d')\n",
  262. audio_description->mChannelsPerFrame);
  263. return;
  264. }
  265. char *_Nullable bytes = NULL;
  266. CMBlockBufferRef data_buffer = CMSampleBufferGetDataBuffer(sample_buffer);
  267. size_t data_buffer_length = CMBlockBufferGetDataLength(data_buffer);
  268. CMBlockBufferGetDataPointer(data_buffer, 0, &data_buffer_length, NULL, &bytes);
  269. CMTime presentation_time = CMSampleBufferGetOutputPresentationTimeStamp(sample_buffer);
  270. struct obs_source_audio audio_data = {};
  271. for (uint32_t channel_idx = 0; channel_idx < audio_description->mChannelsPerFrame; ++channel_idx) {
  272. uint32_t offset = (uint32_t) (data_buffer_length / audio_description->mChannelsPerFrame) * channel_idx;
  273. audio_data.data[channel_idx] = (uint8_t *) bytes + offset;
  274. }
  275. audio_data.frames =
  276. (uint32_t) (data_buffer_length / audio_description->mBytesPerFrame / audio_description->mChannelsPerFrame);
  277. audio_data.speakers = audio_description->mChannelsPerFrame;
  278. audio_data.samples_per_sec = (uint32_t) audio_description->mSampleRate;
  279. audio_data.timestamp = (uint64_t) (CMTimeGetSeconds(presentation_time) * NSEC_PER_SEC);
  280. audio_data.format = AUDIO_FORMAT_FLOAT_PLANAR;
  281. obs_source_output_audio(sc->source, &audio_data);
  282. }