mac-sck-common.m 14 KB

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