diff --git a/.clang-format b/.clang-format index f5d9aa749..c9dfc48e9 100644 --- a/.clang-format +++ b/.clang-format @@ -1,6 +1,5 @@ # please use clang-format version 8 or later -Language: Cpp Standard: Cpp11 AccessModifierOffset: -8 AlignAfterOpenBracket: Align @@ -104,3 +103,5 @@ TabWidth: 8 #TypenameMacros: # requires clang-format 9 # - 'DARRAY' UseTab: ForContinuationAndIndentation +--- +Language: ObjC diff --git a/UI/platform-osx.mm b/UI/platform-osx.mm index 37e7c0abc..bc400f5d2 100644 --- a/UI/platform-osx.mm +++ b/UI/platform-osx.mm @@ -58,7 +58,7 @@ bool InitApplicationBundle() throw "Could not change working directory to " "bundle path"; - } catch (const char* error) { + } catch (const char *error) { blog(LOG_ERROR, "InitBundle: %s", error); return false; } @@ -77,7 +77,7 @@ string GetDefaultVideoSavePath() appropriateForURL:nil create:true error:nil]; - + if (!url) return getenv("HOME"); @@ -97,7 +97,7 @@ vector GetPreferredLocales() return locale.first; if (!lang_match.size() && - locale.first.substr(0, 2) == lang.substr(0, 2)) + locale.first.substr(0, 2) == lang.substr(0, 2)) lang_match = locale.first; } @@ -150,12 +150,13 @@ void EnableOSXVSync(bool enable) if (!initialized) { void *quartzCore = dlopen("/System/Library/Frameworks/" - "QuartzCore.framework/QuartzCore", RTLD_LAZY); + "QuartzCore.framework/QuartzCore", + RTLD_LAZY); if (quartzCore) { - set_debug_options = (set_int_t)dlsym(quartzCore, - "CGSSetDebugOptions"); - deferred_updates = (set_int_t)dlsym(quartzCore, - "CGSDeferredUpdates"); + set_debug_options = (set_int_t)dlsym( + quartzCore, "CGSSetDebugOptions"); + deferred_updates = (set_int_t)dlsym( + quartzCore, "CGSDeferredUpdates"); valid = set_debug_options && deferred_updates; } @@ -174,5 +175,6 @@ void EnableOSXDockIcon(bool enable) if (enable) [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular]; else - [NSApp setActivationPolicy:NSApplicationActivationPolicyProhibited]; + [NSApp setActivationPolicy: + NSApplicationActivationPolicyProhibited]; } diff --git a/UI/sparkle-updater.mm b/UI/sparkle-updater.mm index 1baab8d18..932a3a705 100644 --- a/UI/sparkle-updater.mm +++ b/UI/sparkle-updater.mm @@ -6,15 +6,13 @@ static inline bool equali(NSString *a, NSString *b) return a && b && [a caseInsensitiveCompare:b] == NSOrderedSame; } -@interface OBSSparkleUpdateDelegate : - NSObject -{ +@interface OBSSparkleUpdateDelegate + : NSObject { } @property (nonatomic) bool updateToUndeployed; @end -@implementation OBSSparkleUpdateDelegate -{ +@implementation OBSSparkleUpdateDelegate { } @synthesize updateToUndeployed; @@ -50,11 +48,11 @@ static inline bool equali(NSString *a, NSString *b) item = mpkg; NSMutableDictionary *dict = [NSMutableDictionary - dictionaryWithDictionary:item.propertiesDictionary]; + dictionaryWithDictionary:item.propertiesDictionary]; NSString *build = [host objectForInfoDictionaryKey:@"CFBundleVersion"]; NSString *url = dict[@"sparkle:releaseNotesLink"]; - dict[@"sparkle:releaseNotesLink"] = [url stringByAppendingFormat:@"#%@", - build]; + dict[@"sparkle:releaseNotesLink"] = + [url stringByAppendingFormat:@"#%@", build]; return [[SUAppcastItem alloc] initWithDictionary:dict]; } @@ -62,9 +60,9 @@ static inline bool equali(NSString *a, NSString *b) - (SUAppcastItem *)bestValidUpdateInAppcast:(SUAppcast *)appcast forUpdater:(SUUpdater *)updater { - SUAppcastItem *selected = - [self bestValidUpdateWithDeltasInAppcast:appcast - forUpdater:updater]; + SUAppcastItem *selected = [self + bestValidUpdateWithDeltasInAppcast:appcast + forUpdater:updater]; NSBundle *host = updater.hostBundle; NSString *build = [host objectForInfoDictionaryKey:@"CFBundleVersion"]; @@ -91,8 +89,8 @@ static inline bool equali(NSString *a, NSString *b) return NSOrderedSame; } -- (id ) - versionComparatorForUpdater:(SUUpdater *)__unused updater +- (id)versionComparatorForUpdater:(SUUpdater *)__unused + updater { return self; } @@ -141,4 +139,3 @@ void trigger_sparkle_update() { [updater checkForUpdates:nil]; } - diff --git a/libobs-opengl/gl-cocoa.m b/libobs-opengl/gl-cocoa.m index 0bcbca2ce..2c65847bd 100644 --- a/libobs-opengl/gl-cocoa.m +++ b/libobs-opengl/gl-cocoa.m @@ -21,10 +21,8 @@ #import #import - //#include "util/darray.h" - struct gl_windowinfo { NSView *view; }; @@ -37,9 +35,15 @@ static NSOpenGLContext *gl_context_create(void) { unsigned attrib_count = 0; -#define ADD_ATTR(x) \ - { attributes[attrib_count++] = (NSOpenGLPixelFormatAttribute)x; } -#define ADD_ATTR2(x, y) { ADD_ATTR(x); ADD_ATTR(y); } +#define ADD_ATTR(x) \ + { \ + attributes[attrib_count++] = (NSOpenGLPixelFormatAttribute)x; \ + } +#define ADD_ATTR2(x, y) \ + { \ + ADD_ATTR(x); \ + ADD_ATTR(y); \ + } NSOpenGLPixelFormatAttribute attributes[40]; @@ -52,7 +56,7 @@ static NSOpenGLContext *gl_context_create(void) NSOpenGLPixelFormat *pf; pf = [[NSOpenGLPixelFormat alloc] initWithAttributes:attributes]; - if(!pf) { + if (!pf) { blog(LOG_ERROR, "Failed to create pixel format"); return NULL; } @@ -60,7 +64,7 @@ static NSOpenGLContext *gl_context_create(void) NSOpenGLContext *context; context = [[NSOpenGLContext alloc] initWithFormat:pf shareContext:nil]; [pf release]; - if(!context) { + if (!context) { blog(LOG_ERROR, "Failed to create context"); return NULL; } @@ -98,7 +102,7 @@ fail: void gl_platform_destroy(struct gl_platform *platform) { - if(!platform) + if (!platform) return; [platform->context release]; @@ -121,10 +125,10 @@ void gl_platform_cleanup_swapchain(struct gs_swap_chain *swap) struct gl_windowinfo *gl_windowinfo_create(const struct gs_init_data *info) { - if(!info) + if (!info) return NULL; - if(!info->window.view) + if (!info->window.view) return NULL; struct gl_windowinfo *wi = bzalloc(sizeof(struct gl_windowinfo)); @@ -137,7 +141,7 @@ struct gl_windowinfo *gl_windowinfo_create(const struct gs_init_data *info) void gl_windowinfo_destroy(struct gl_windowinfo *wi) { - if(!wi) + if (!wi) return; wi->view = nil; @@ -163,7 +167,7 @@ void device_leave_context(gs_device_t *device) void device_load_swapchain(gs_device_t *device, gs_swapchain_t *swap) { - if(device->cur_swap == swap) + if (device->cur_swap == swap) return; device->cur_swap = swap; @@ -180,14 +184,16 @@ void device_present(gs_device_t *device) } void gl_getclientsize(const struct gs_swap_chain *swap, uint32_t *width, - uint32_t *height) + uint32_t *height) { - if(width) *width = swap->info.cx; - if(height) *height = swap->info.cy; + if (width) + *width = swap->info.cx; + if (height) + *height = swap->info.cy; } gs_texture_t *device_texture_create_from_iosurface(gs_device_t *device, - void *iosurf) + void *iosurf) { IOSurfaceRef ref = (IOSurfaceRef)iosurf; struct gs_texture_2d *tex = bzalloc(sizeof(struct gs_texture_2d)); @@ -195,23 +201,23 @@ gs_texture_t *device_texture_create_from_iosurface(gs_device_t *device, OSType pf = IOSurfaceGetPixelFormat(ref); if (pf != 'BGRA') blog(LOG_ERROR, "Unexpected pixel format: %d (%c%c%c%c)", pf, - pf >> 24, pf >> 16, pf >> 8, pf); + pf >> 24, pf >> 16, pf >> 8, pf); const enum gs_color_format color_format = GS_BGRA; - tex->base.device = device; - tex->base.type = GS_TEXTURE_2D; - tex->base.format = GS_BGRA; - tex->base.levels = 1; - tex->base.gl_format = convert_gs_format(color_format); + tex->base.device = device; + tex->base.type = GS_TEXTURE_2D; + tex->base.format = GS_BGRA; + tex->base.levels = 1; + tex->base.gl_format = convert_gs_format(color_format); tex->base.gl_internal_format = convert_gs_internal_format(color_format); - tex->base.gl_type = GL_UNSIGNED_INT_8_8_8_8_REV; - tex->base.gl_target = GL_TEXTURE_RECTANGLE; - tex->base.is_dynamic = false; - tex->base.is_render_target = false; - tex->base.gen_mipmaps = false; - tex->width = IOSurfaceGetWidth(ref); - tex->height = IOSurfaceGetHeight(ref); + tex->base.gl_type = GL_UNSIGNED_INT_8_8_8_8_REV; + tex->base.gl_target = GL_TEXTURE_RECTANGLE; + tex->base.is_dynamic = false; + tex->base.is_render_target = false; + tex->base.gen_mipmaps = false; + tex->width = IOSurfaceGetWidth(ref); + tex->height = IOSurfaceGetHeight(ref); if (!gl_gen_textures(1, &tex->base.texture)) goto fail; @@ -220,34 +226,30 @@ gs_texture_t *device_texture_create_from_iosurface(gs_device_t *device, goto fail; CGLError err = CGLTexImageIOSurface2D( - [[NSOpenGLContext currentContext] CGLContextObj], - tex->base.gl_target, - tex->base.gl_internal_format, - tex->width, tex->height, - tex->base.gl_format, - tex->base.gl_type, - ref, 0); - - if(err != kCGLNoError) { - blog(LOG_ERROR, "CGLTexImageIOSurface2D: %u, %s" - " (device_texture_create_from_iosurface)", - err, CGLErrorString(err)); + [[NSOpenGLContext currentContext] CGLContextObj], + tex->base.gl_target, tex->base.gl_internal_format, tex->width, + tex->height, tex->base.gl_format, tex->base.gl_type, ref, 0); + + if (err != kCGLNoError) { + blog(LOG_ERROR, + "CGLTexImageIOSurface2D: %u, %s" + " (device_texture_create_from_iosurface)", + err, CGLErrorString(err)); gl_success("CGLTexImageIOSurface2D"); goto fail; } - if (!gl_tex_param_i(tex->base.gl_target, - GL_TEXTURE_MAX_LEVEL, 0)) + if (!gl_tex_param_i(tex->base.gl_target, GL_TEXTURE_MAX_LEVEL, 0)) goto fail; if (!gl_bind_texture(tex->base.gl_target, 0)) goto fail; - return (gs_texture_t*)tex; + return (gs_texture_t *)tex; fail: - gs_texture_destroy((gs_texture_t*)tex); + gs_texture_destroy((gs_texture_t *)tex); blog(LOG_ERROR, "device_texture_create_from_iosurface (GL) failed"); return NULL; } @@ -260,34 +262,31 @@ bool gs_texture_rebind_iosurface(gs_texture_t *texture, void *iosurf) if (!iosurf) return false; - struct gs_texture_2d *tex = (struct gs_texture_2d*)texture; + struct gs_texture_2d *tex = (struct gs_texture_2d *)texture; IOSurfaceRef ref = (IOSurfaceRef)iosurf; OSType pf = IOSurfaceGetPixelFormat(ref); if (pf != 'BGRA') blog(LOG_ERROR, "Unexpected pixel format: %d (%c%c%c%c)", pf, - pf >> 24, pf >> 16, pf >> 8, pf); + pf >> 24, pf >> 16, pf >> 8, pf); if (tex->width != IOSurfaceGetWidth(ref) || - tex->height != IOSurfaceGetHeight(ref)) + tex->height != IOSurfaceGetHeight(ref)) return false; if (!gl_bind_texture(tex->base.gl_target, tex->base.texture)) return false; CGLError err = CGLTexImageIOSurface2D( - [[NSOpenGLContext currentContext] CGLContextObj], - tex->base.gl_target, - tex->base.gl_internal_format, - tex->width, tex->height, - tex->base.gl_format, - tex->base.gl_type, - ref, 0); - - if(err != kCGLNoError) { - blog(LOG_ERROR, "CGLTexImageIOSurface2D: %u, %s" - " (gs_texture_rebind_iosurface)", - err, CGLErrorString(err)); + [[NSOpenGLContext currentContext] CGLContextObj], + tex->base.gl_target, tex->base.gl_internal_format, tex->width, + tex->height, tex->base.gl_format, tex->base.gl_type, ref, 0); + + if (err != kCGLNoError) { + blog(LOG_ERROR, + "CGLTexImageIOSurface2D: %u, %s" + " (gs_texture_rebind_iosurface)", + err, CGLErrorString(err)); gl_success("CGLTexImageIOSurface2D"); return false; diff --git a/libobs/obs-module.h b/libobs/obs-module.h index 5b79b19ae..ea57cb2ed 100644 --- a/libobs/obs-module.h +++ b/libobs/obs-module.h @@ -129,7 +129,7 @@ MODULE_EXPORT void obs_module_free_locale(void); void obs_module_free_locale(void) \ { \ text_lookup_destroy(obs_module_lookup); \ - obs_module_lookup = NULL; \ + obs_module_lookup = NULL; \ } /** Helper function for looking up locale if default locale handler was used */ diff --git a/libobs/util/platform-cocoa.m b/libobs/util/platform-cocoa.m index ff434d670..24ae448f5 100644 --- a/libobs/util/platform-cocoa.m +++ b/libobs/util/platform-cocoa.m @@ -54,7 +54,8 @@ static double ns_time_compute_factor() static uint64_t ns_time_full() { static double factor = 0.; - if (factor == 0.) factor = ns_time_compute_factor(); + if (factor == 0.) + factor = ns_time_compute_factor(); return (uint64_t)(mach_absolute_time() * factor); } @@ -72,18 +73,19 @@ static time_func ns_time_select_func() uint64_t os_gettime_ns(void) { static time_func f = NULL; - if (!f) f = ns_time_select_func(); + if (!f) + f = ns_time_select_func(); return f(); } /* gets the location [domain mask]/Library/Application Support/[name] */ static int os_get_path_internal(char *dst, size_t size, const char *name, - NSSearchPathDomainMask domainMask) + NSSearchPathDomainMask domainMask) { NSArray *paths = NSSearchPathForDirectoriesInDomains( - NSApplicationSupportDirectory, domainMask, YES); + NSApplicationSupportDirectory, domainMask, YES); - if([paths count] == 0) + if ([paths count] == 0) bcrash("Could not get home directory (platform-cocoa)"); NSString *application_support = paths[0]; @@ -96,12 +98,12 @@ static int os_get_path_internal(char *dst, size_t size, const char *name, } static char *os_get_path_ptr_internal(const char *name, - NSSearchPathDomainMask domainMask) + NSSearchPathDomainMask domainMask) { NSArray *paths = NSSearchPathForDirectoriesInDomains( - NSApplicationSupportDirectory, domainMask, YES); + NSApplicationSupportDirectory, domainMask, YES); - if([paths count] == 0) + if ([paths count] == 0) bcrash("Could not get home directory (platform-cocoa)"); NSString *application_support = paths[0]; @@ -109,7 +111,7 @@ static char *os_get_path_ptr_internal(const char *name, NSUInteger len = [application_support lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; - char *path_ptr = bmalloc(len+1); + char *path_ptr = bmalloc(len + 1); path_ptr[len] = 0; @@ -174,47 +176,47 @@ char *os_get_executable_path_ptr(const char *name) struct os_cpu_usage_info { int64_t last_cpu_time; int64_t last_sys_time; - int core_count; + int core_count; }; static inline void add_time_value(time_value_t *dst, time_value_t *a, - time_value_t *b) + time_value_t *b) { dst->microseconds = a->microseconds + b->microseconds; - dst->seconds = a->seconds + b->seconds; + dst->seconds = a->seconds + b->seconds; if (dst->microseconds >= 1000000) { - dst->seconds += dst->microseconds / 1000000; + dst->seconds += dst->microseconds / 1000000; dst->microseconds %= 1000000; } } static bool get_time_info(int64_t *cpu_time, int64_t *sys_time) { - mach_port_t task = mach_task_self(); + mach_port_t task = mach_task_self(); struct task_thread_times_info thread_data; - struct task_basic_info_64 task_data; - mach_msg_type_number_t count; - kern_return_t kern_ret; - time_value_t cur_time; + struct task_basic_info_64 task_data; + mach_msg_type_number_t count; + kern_return_t kern_ret; + time_value_t cur_time; *cpu_time = 0; *sys_time = 0; count = TASK_THREAD_TIMES_INFO_COUNT; kern_ret = task_info(task, TASK_THREAD_TIMES_INFO, - (task_info_t)&thread_data, &count); + (task_info_t)&thread_data, &count); if (kern_ret != KERN_SUCCESS) return false; count = TASK_BASIC_INFO_64_COUNT; - kern_ret = task_info(task, TASK_BASIC_INFO_64, - (task_info_t)&task_data, &count); + kern_ret = task_info(task, TASK_BASIC_INFO_64, (task_info_t)&task_data, + &count); if (kern_ret != KERN_SUCCESS) return false; add_time_value(&cur_time, &thread_data.user_time, - &thread_data.system_time); + &thread_data.system_time); add_time_value(&cur_time, &cur_time, &task_data.user_time); add_time_value(&cur_time, &cur_time, &task_data.system_time); @@ -238,7 +240,7 @@ os_cpu_usage_info_t *os_cpu_usage_info_start(void) double os_cpu_usage_info_query(os_cpu_usage_info_t *info) { - int64_t sys_time, cpu_time; + int64_t sys_time, cpu_time; int64_t sys_time_delta, cpu_time_delta; if (!info || !get_time_info(&cpu_time, &sys_time)) @@ -254,7 +256,7 @@ double os_cpu_usage_info_query(os_cpu_usage_info_t *info) info->last_cpu_time = cpu_time; return (double)sys_time_delta * 100.0 / (double)cpu_time_delta / - (double)info->core_count; + (double)info->core_count; } void os_cpu_usage_info_destroy(os_cpu_usage_info_t *info) @@ -272,7 +274,7 @@ os_performance_token_t *os_request_high_performance(const char *reason) return nil; //taken from http://stackoverflow.com/a/20100906 - id activity = [pi beginActivityWithOptions:0x00FFFFFF + id activity = [pi beginActivityWithOptions:0x00FFFFFF reason:@(reason)]; return CFBridgingRetain(activity); @@ -302,11 +304,11 @@ os_inhibit_t *os_inhibit_sleep_create(const char *reason) { struct os_inhibit_info *info = bzalloc(sizeof(*info)); if (!reason) - info->reason = CFStringCreateWithCString(kCFAllocatorDefault, - reason, kCFStringEncodingUTF8); + info->reason = CFStringCreateWithCString( + kCFAllocatorDefault, reason, kCFStringEncodingUTF8); else - info->reason = CFStringCreateCopy(kCFAllocatorDefault, - CFSTR("")); + info->reason = + CFStringCreateCopy(kCFAllocatorDefault, CFSTR("")); return info; } @@ -321,12 +323,11 @@ bool os_inhibit_sleep_set_active(os_inhibit_t *info, bool active) return false; if (active) { - IOPMAssertionDeclareUserActivity(info->reason, - kIOPMUserActiveLocal, &info->user_id); + IOPMAssertionDeclareUserActivity( + info->reason, kIOPMUserActiveLocal, &info->user_id); success = IOPMAssertionCreateWithName( - kIOPMAssertionTypeNoDisplaySleep, - kIOPMAssertionLevelOn, info->reason, - &info->sleep_id); + kIOPMAssertionTypeNoDisplaySleep, kIOPMAssertionLevelOn, + info->reason, &info->sleep_id); if (success != kIOReturnSuccess) { blog(LOG_WARNING, "Failed to disable sleep"); @@ -361,16 +362,16 @@ static void os_get_cores_internal(void) core_count_initialized = true; size_t size; - int ret; + int ret; size = sizeof(physical_cores); - ret = sysctlbyname("machdep.cpu.core_count", &physical_cores, - &size, NULL, 0); + ret = sysctlbyname("machdep.cpu.core_count", &physical_cores, &size, + NULL, 0); if (ret != 0) return; - ret = sysctlbyname("machdep.cpu.thread_count", &logical_cores, - &size, NULL, 0); + ret = sysctlbyname("machdep.cpu.thread_count", &logical_cores, &size, + NULL, 0); } int os_get_physical_cores(void) @@ -390,8 +391,8 @@ int os_get_logical_cores(void) static inline bool os_get_sys_memory_usage_internal(vm_statistics_t vmstat) { mach_msg_type_number_t out_count = HOST_VM_INFO_COUNT; - if (host_statistics(mach_host_self(), HOST_VM_INFO, - (host_info_t)vmstat, &out_count) != KERN_SUCCESS) + if (host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)vmstat, + &out_count) != KERN_SUCCESS) return false; return true; } @@ -409,8 +410,8 @@ uint64_t os_get_sys_free_size(void) typedef task_basic_info_data_t mach_task_basic_info_data_t; #endif -static inline bool os_get_proc_memory_usage_internal( - mach_task_basic_info_data_t *taskinfo) +static inline bool +os_get_proc_memory_usage_internal(mach_task_basic_info_data_t *taskinfo) { #ifdef MACH_TASK_BASIC_INFO const task_flavor_t flavor = MACH_TASK_BASIC_INFO; @@ -419,8 +420,8 @@ static inline bool os_get_proc_memory_usage_internal( const task_flavor_t flavor = TASK_BASIC_INFO; mach_msg_type_number_t out_count = TASK_BASIC_INFO_COUNT; #endif - if (task_info(mach_task_self(), flavor, - (task_info_t)taskinfo, &out_count) != KERN_SUCCESS) + if (task_info(mach_task_self(), flavor, (task_info_t)taskinfo, + &out_count) != KERN_SUCCESS) return false; return true; } @@ -432,7 +433,7 @@ bool os_get_proc_memory_usage(os_proc_memory_usage_t *usage) return false; usage->resident_size = taskinfo.resident_size; - usage->virtual_size = taskinfo.virtual_size; + usage->virtual_size = taskinfo.virtual_size; return true; } @@ -461,8 +462,8 @@ char *cfstr_copy_cstr(CFStringRef cfstring, CFStringEncoding cfstring_encoding) return NULL; // Try the quick way to obtain the buffer - const char *tmp_buffer = CFStringGetCStringPtr(cfstring, - cfstring_encoding); + const char *tmp_buffer = + CFStringGetCStringPtr(cfstring, cfstring_encoding); if (tmp_buffer != NULL) return bstrdup(tmp_buffer); @@ -486,8 +487,8 @@ char *cfstr_copy_cstr(CFStringRef cfstring, CFStringEncoding cfstring_encoding) } // Copy CFString in requested encoding to buffer - Boolean success = - CFStringGetCString(cfstring, buffer, max_size, cfstring_encoding); + Boolean success = CFStringGetCString(cfstring, buffer, max_size, + cfstring_encoding); if (!success) { bfree(buffer); @@ -500,15 +501,15 @@ char *cfstr_copy_cstr(CFStringRef cfstring, CFStringEncoding cfstring_encoding) * Returns true on success or false on failure. * In case of failure, the dstr capacity but not size is changed. */ -bool cfstr_copy_dstr(CFStringRef cfstring, - CFStringEncoding cfstring_encoding, struct dstr *str) +bool cfstr_copy_dstr(CFStringRef cfstring, CFStringEncoding cfstring_encoding, + struct dstr *str) { if (!cfstring) return false; // Try the quick way to obtain the buffer - const char *tmp_buffer = CFStringGetCStringPtr(cfstring, - cfstring_encoding); + const char *tmp_buffer = + CFStringGetCStringPtr(cfstring, cfstring_encoding); if (tmp_buffer != NULL) { dstr_copy(str, tmp_buffer); @@ -530,8 +531,8 @@ bool cfstr_copy_dstr(CFStringRef cfstring, dstr_ensure_capacity(str, max_size); // Copy CFString in requested encoding to dstr buffer - Boolean success = CFStringGetCString( - cfstring, str->array, max_size, cfstring_encoding); + Boolean success = CFStringGetCString(cfstring, str->array, max_size, + cfstring_encoding); if (success) dstr_resize(str, max_size); diff --git a/plugins/mac-avcapture/av-capture.mm b/plugins/mac-avcapture/av-capture.mm index 446ba910d..1718bb53b 100644 --- a/plugins/mac-avcapture/av-capture.mm +++ b/plugins/mac-avcapture/av-capture.mm @@ -26,37 +26,29 @@ using namespace std; namespace std { -template <> -struct default_delete { - void operator()(obs_data_t *data) - { - obs_data_release(data); - } +template<> struct default_delete { + void operator()(obs_data_t *data) { obs_data_release(data); } }; -template <> -struct default_delete { - void operator()(obs_data_item_t *item) - { - obs_data_item_release(&item); - } +template<> struct default_delete { + void operator()(obs_data_item_t *item) { obs_data_item_release(&item); } }; } -#define TEXT_AVCAPTURE obs_module_text("AVCapture") -#define TEXT_DEVICE obs_module_text("Device") +#define TEXT_AVCAPTURE obs_module_text("AVCapture") +#define TEXT_DEVICE obs_module_text("Device") #define TEXT_USE_PRESET obs_module_text("UsePreset") -#define TEXT_PRESET obs_module_text("Preset") +#define TEXT_PRESET obs_module_text("Preset") #define TEXT_RESOLUTION obs_module_text("Resolution") #define TEXT_FRAME_RATE obs_module_text("FrameRate") -#define TEXT_MATCH_OBS obs_module_text("MatchOBS") +#define TEXT_MATCH_OBS obs_module_text("MatchOBS") #define TEXT_INPUT_FORMAT obs_module_text("InputFormat") #define TEXT_COLOR_SPACE obs_module_text("ColorSpace") #define TEXT_VIDEO_RANGE obs_module_text("VideoRange") #define TEXT_RANGE_PARTIAL obs_module_text("VideoRange.Partial") #define TEXT_RANGE_FULL obs_module_text("VideoRange.Full") -#define TEXT_AUTO obs_module_text("Auto") +#define TEXT_AUTO obs_module_text("Auto") #define TEXT_COLOR_UNKNOWN_NAME "Unknown" #define TEXT_RANGE_UNKNOWN_NAME "Unknown" @@ -67,53 +59,52 @@ static const int VIDEO_RANGE_AUTO = -1; #define MILLI_TIMESCALE 1000 #define MICRO_TIMESCALE (MILLI_TIMESCALE * 1000) -#define NANO_TIMESCALE (MICRO_TIMESCALE * 1000) +#define NANO_TIMESCALE (MICRO_TIMESCALE * 1000) -#define AV_FOURCC_STR(code) \ - (char[5]) { \ - static_cast((code >> 24) & 0xFF), \ - static_cast((code >> 16) & 0xFF), \ - static_cast((code >> 8) & 0xFF), \ - static_cast( code & 0xFF), \ - 0 \ +#define AV_FOURCC_STR(code) \ + (char[5]) \ + { \ + static_cast((code >> 24) & 0xFF), \ + static_cast((code >> 16) & 0xFF), \ + static_cast((code >> 8) & 0xFF), \ + static_cast(code & 0xFF), 0 \ } struct av_capture; -#define AVLOG(level, format, ...) \ - blog(level, "%s: " format, \ - obs_source_get_name(capture->source), ##__VA_ARGS__) +#define AVLOG(level, format, ...) \ + blog(level, "%s: " format, obs_source_get_name(capture->source), \ + ##__VA_ARGS__) -@interface OBSAVCaptureDelegate : - NSObject -{ +@interface OBSAVCaptureDelegate + : NSObject { @public struct av_capture *capture; } - (void)captureOutput:(AVCaptureOutput *)out - didDropSampleBuffer:(CMSampleBufferRef)sampleBuffer - fromConnection:(AVCaptureConnection *)connection; + didDropSampleBuffer:(CMSampleBufferRef)sampleBuffer + fromConnection:(AVCaptureConnection *)connection; - (void)captureOutput:(AVCaptureOutput *)captureOutput - didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer - fromConnection:(AVCaptureConnection *)connection; + didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer + fromConnection:(AVCaptureConnection *)connection; @end namespace { -static auto remove_observer = [](id observer) -{ +static auto remove_observer = [](id observer) { [[NSNotificationCenter defaultCenter] removeObserver:observer]; }; -struct observer_handle : - unique_ptr::type, decltype(remove_observer)> { - - using base = unique_ptr::type, - decltype(remove_observer)>; +struct observer_handle + : unique_ptr::type, decltype(remove_observer)> { + + using base = + unique_ptr::type, decltype(remove_observer)>; explicit observer_handle(id observer = nullptr) : base(observer, remove_observer) - {} + { + } }; struct av_video_info { @@ -134,10 +125,10 @@ struct av_capture { left_right::left_right video_info; AVCaptureVideoDataOutput *out; - AVCaptureDevice *device; - AVCaptureDeviceInput *device_input; - AVCaptureSession *session; - + AVCaptureDevice *device; + AVCaptureDeviceInput *device_input; + AVCaptureSession *session; + NSString *uid; observer_handle connect_observer; observer_handle disconnect_observer; @@ -146,7 +137,7 @@ struct av_capture { video_format video_format; bool use_preset = false; - int requested_colorspace = COLOR_SPACE_AUTO; + int requested_colorspace = COLOR_SPACE_AUTO; int requested_video_range = VIDEO_RANGE_AUTO; obs_source_t *source; @@ -165,13 +156,16 @@ static AVCaptureDevice *get_device(obs_data_t *settings) return [AVCaptureDevice deviceWithUniqueID:uid]; } -template -static void clamp(T& store, U val, T low = numeric_limits::min(), - T high = numeric_limits::max()) +template +static void clamp(T &store, U val, T low = numeric_limits::min(), + T high = numeric_limits::max()) { - store = static_cast(val) < static_cast(low) ? low : - (static_cast(val) > static_cast(high) ? - high : static_cast(val)); + store = static_cast(val) < static_cast(low) + ? low + : (static_cast(val) > + static_cast(high) + ? high + : static_cast(val)); } static bool get_resolution(obs_data_t *settings, CMVideoDimensions &dims) @@ -220,9 +214,9 @@ struct config_helper { AVCaptureDevice *dev_ = nullptr; bool dims_valid : 1; - bool fr_valid : 1; - bool fps_valid : 1; - bool if_valid : 1; + bool fr_valid : 1; + bool fps_valid : 1; + bool if_valid : 1; CMVideoDimensions dims_{}; @@ -231,25 +225,21 @@ struct config_helper { FourCharCode input_format_ = INPUT_FORMAT_AUTO; - explicit config_helper(obs_data_t *settings) - : settings(settings) + explicit config_helper(obs_data_t *settings) : settings(settings) { dev_ = get_device(settings); dims_valid = get_resolution(settings, dims_); - fr_valid = obs_data_get_frames_per_second(settings, - "frame_rate", nullptr, &frame_rate_); - fps_valid = obs_data_get_frames_per_second(settings, - "frame_rate", &fps_, nullptr); + fr_valid = obs_data_get_frames_per_second( + settings, "frame_rate", nullptr, &frame_rate_); + fps_valid = obs_data_get_frames_per_second( + settings, "frame_rate", &fps_, nullptr); if_valid = get_input_format(settings, input_format_); } - AVCaptureDevice *dev() const - { - return dev_; - } + AVCaptureDevice *dev() const { return dev_; } const CMVideoDimensions *dims() const { @@ -287,23 +277,16 @@ struct av_capture_ref { capture = capture_; } - operator av_capture *() - { - return capture; - } + operator av_capture *() { return capture; } - av_capture *operator->() - { - return capture; - } + av_capture *operator->() { return capture; } }; struct properties_param { av_capture *capture = nullptr; OBSWeakSource weak_source; - properties_param(av_capture *capture) - : capture(capture) + properties_param(av_capture *capture) : capture(capture) { if (!capture) return; @@ -311,10 +294,7 @@ struct properties_param { weak_source = OBSGetWeakRef(capture->source); } - av_capture_ref get_ref() - { - return {capture, weak_source}; - } + av_capture_ref get_ref() { return {capture, weak_source}; } }; } @@ -325,7 +305,7 @@ static av_capture_ref get_ref(obs_properties_t *props) if (!param) return {}; - return static_cast(param)->get_ref(); + return static_cast(param)->get_ref(); } static inline video_format format_from_subtype(FourCharCode subtype) @@ -351,8 +331,9 @@ static inline video_format format_from_subtype(FourCharCode subtype) static const char *fourcc_subtype_name(FourCharCode fourcc); -static const char *format_description_subtype_name(CMFormatDescriptionRef desc, - FourCharCode *fourcc_=nullptr) +static const char * +format_description_subtype_name(CMFormatDescriptionRef desc, + FourCharCode *fourcc_ = nullptr) { FourCharCode fourcc = CMFormatDescriptionGetMediaSubType(desc); if (fourcc_) @@ -376,17 +357,28 @@ static const char *fourcc_subtype_name(FourCharCode fourcc) case kCVPixelFormatType_32BGRA: return "BGRA - 32BGRA"; //VIDEO_FORMAT_BGRA; - case kCMVideoCodecType_Animation: return "Apple Animation"; - case kCMVideoCodecType_Cinepak: return "Cinepak"; - case kCMVideoCodecType_JPEG: return "JPEG"; - case kCMVideoCodecType_JPEG_OpenDML: return "MJPEG - JPEG OpenDML"; - case kCMVideoCodecType_SorensonVideo: return "Sorenson Video"; - case kCMVideoCodecType_SorensonVideo3: return "Sorenson Video 3"; - case kCMVideoCodecType_H263: return "H.263"; - case kCMVideoCodecType_H264: return "H.264"; - case kCMVideoCodecType_MPEG4Video: return "MPEG-4"; - case kCMVideoCodecType_MPEG2Video: return "MPEG-2"; - case kCMVideoCodecType_MPEG1Video: return "MPEG-1"; + case kCMVideoCodecType_Animation: + return "Apple Animation"; + case kCMVideoCodecType_Cinepak: + return "Cinepak"; + case kCMVideoCodecType_JPEG: + return "JPEG"; + case kCMVideoCodecType_JPEG_OpenDML: + return "MJPEG - JPEG OpenDML"; + case kCMVideoCodecType_SorensonVideo: + return "Sorenson Video"; + case kCMVideoCodecType_SorensonVideo3: + return "Sorenson Video 3"; + case kCMVideoCodecType_H263: + return "H.263"; + case kCMVideoCodecType_H264: + return "H.264"; + case kCMVideoCodecType_MPEG4Video: + return "MPEG-4"; + case kCMVideoCodecType_MPEG2Video: + return "MPEG-2"; + case kCMVideoCodecType_MPEG1Video: + return "MPEG-1"; case kCMVideoCodecType_DVCNTSC: return "DV NTSC"; @@ -443,39 +435,40 @@ static inline bool is_fullrange_yuv(FourCharCode pixel_format) static inline video_colorspace get_colorspace(CMFormatDescriptionRef desc) { - CFPropertyListRef matrix = CMFormatDescriptionGetExtension(desc, - kCMFormatDescriptionExtension_YCbCrMatrix); + CFPropertyListRef matrix = CMFormatDescriptionGetExtension( + desc, kCMFormatDescriptionExtension_YCbCrMatrix); if (!matrix) return VIDEO_CS_DEFAULT; if (CFStringCompare(static_cast(matrix), - kCVImageBufferYCbCrMatrix_ITU_R_709_2, 0) - == kCFCompareEqualTo) + kCVImageBufferYCbCrMatrix_ITU_R_709_2, + 0) == kCFCompareEqualTo) return VIDEO_CS_709; return VIDEO_CS_601; } static inline bool update_colorspace(av_capture *capture, - obs_source_frame *frame, CMFormatDescriptionRef desc, - bool full_range, av_video_info &vi) + obs_source_frame *frame, + CMFormatDescriptionRef desc, + bool full_range, av_video_info &vi) { auto cs_auto = capture->use_preset || - capture->requested_colorspace == COLOR_SPACE_AUTO; + capture->requested_colorspace == COLOR_SPACE_AUTO; auto vr_auto = capture->use_preset || - capture->requested_video_range == VIDEO_RANGE_AUTO; + capture->requested_video_range == VIDEO_RANGE_AUTO; video_colorspace colorspace = get_colorspace(desc); - video_range_type range = full_range ? - VIDEO_RANGE_FULL : VIDEO_RANGE_PARTIAL; + video_range_type range = full_range ? VIDEO_RANGE_FULL + : VIDEO_RANGE_PARTIAL; bool cs_matches = false; if (cs_auto) { cs_matches = colorspace == vi.colorspace; } else { colorspace = static_cast( - capture->requested_colorspace); + capture->requested_colorspace); cs_matches = colorspace == vi.colorspace; } @@ -484,43 +477,41 @@ static inline bool update_colorspace(av_capture *capture, vr_matches = range == vi.video_range; } else { range = static_cast( - capture->requested_video_range); + capture->requested_video_range); vr_matches = range == vi.video_range; full_range = range == VIDEO_RANGE_FULL; } if (cs_matches && vr_matches) { if (!vi.video_params_valid) - capture->video_info.update([&](av_video_info &vi_) - { - vi_.video_params_valid = - vi.video_params_valid = true; + capture->video_info.update([&](av_video_info &vi_) { + vi_.video_params_valid = vi.video_params_valid = + true; }); return true; } frame->full_range = full_range; - if (!video_format_get_parameters(colorspace, range, - frame->color_matrix, - frame->color_range_min, - frame->color_range_max)) { - AVLOG(LOG_ERROR, "Failed to get colorspace parameters for " - "colorspace %u range %u", colorspace, range); + if (!video_format_get_parameters(colorspace, range, frame->color_matrix, + frame->color_range_min, + frame->color_range_max)) { + AVLOG(LOG_ERROR, + "Failed to get colorspace parameters for " + "colorspace %u range %u", + colorspace, range); if (vi.video_params_valid) - capture->video_info.update([&](av_video_info &vi_) - { - vi_.video_params_valid = - vi.video_params_valid = false; + capture->video_info.update([&](av_video_info &vi_) { + vi_.video_params_valid = vi.video_params_valid = + false; }); return false; } - capture->video_info.update([&](av_video_info &vi_) - { - vi_.colorspace = colorspace; + capture->video_info.update([&](av_video_info &vi_) { + vi_.colorspace = colorspace; vi_.video_range = range; vi_.video_params_valid = vi.video_params_valid = true; }); @@ -528,17 +519,17 @@ static inline bool update_colorspace(av_capture *capture, return true; } -static inline bool update_frame(av_capture *capture, - obs_source_frame *frame, CMSampleBufferRef sample_buffer) +static inline bool update_frame(av_capture *capture, obs_source_frame *frame, + CMSampleBufferRef sample_buffer) { CMFormatDescriptionRef desc = CMSampleBufferGetFormatDescription(sample_buffer); - FourCharCode fourcc = CMFormatDescriptionGetMediaSubType(desc); - video_format format = format_from_subtype(fourcc); + FourCharCode fourcc = CMFormatDescriptionGetMediaSubType(desc); + video_format format = format_from_subtype(fourcc); CMVideoDimensions dims = CMVideoFormatDescriptionGetDimensions(desc); - CVImageBufferRef img = CMSampleBufferGetImageBuffer(sample_buffer); + CVImageBufferRef img = CMSampleBufferGetImageBuffer(sample_buffer); auto vi = capture->video_info.read(); @@ -555,32 +546,32 @@ static inline bool update_frame(av_capture *capture, capture->fourcc = fourcc; AVLOG(LOG_ERROR, "Unhandled fourcc: %s (0x%x) (%zu planes)", - AV_FOURCC_STR(fourcc), fourcc, - CVPixelBufferGetPlaneCount(img)); + AV_FOURCC_STR(fourcc), fourcc, + CVPixelBufferGetPlaneCount(img)); return false; } if (frame->format != format) - AVLOG(LOG_DEBUG, "Switching fourcc: " - "'%s' (0x%x) -> '%s' (0x%x)", - AV_FOURCC_STR(capture->fourcc), capture->fourcc, - AV_FOURCC_STR(fourcc), fourcc); + AVLOG(LOG_DEBUG, + "Switching fourcc: " + "'%s' (0x%x) -> '%s' (0x%x)", + AV_FOURCC_STR(capture->fourcc), capture->fourcc, + AV_FOURCC_STR(fourcc), fourcc); bool was_yuv = format_is_yuv(frame->format); capture->fourcc = fourcc; - frame->format = format; - frame->width = dims.width; - frame->height = dims.height; + frame->format = format; + frame->width = dims.width; + frame->height = dims.height; - if (format_is_yuv(format) && !update_colorspace(capture, frame, desc, - is_fullrange_yuv(fourcc), vi)) { + if (format_is_yuv(format) && + !update_colorspace(capture, frame, desc, is_fullrange_yuv(fourcc), + vi)) { return false; } else if (was_yuv == format_is_yuv(format)) { - capture->video_info.update([&](av_video_info &vi_) - { - vi_.video_params_valid = - vi.video_params_valid = true; + capture->video_info.update([&](av_video_info &vi_) { + vi_.video_params_valid = vi.video_params_valid = true; }); } @@ -588,24 +579,24 @@ static inline bool update_frame(av_capture *capture, if (!CVPixelBufferIsPlanar(img)) { frame->linesize[0] = CVPixelBufferGetBytesPerRow(img); - frame->data[0] = static_cast( - CVPixelBufferGetBaseAddress(img)); + frame->data[0] = static_cast( + CVPixelBufferGetBaseAddress(img)); return true; } size_t count = CVPixelBufferGetPlaneCount(img); for (size_t i = 0; i < count; i++) { frame->linesize[i] = CVPixelBufferGetBytesPerRowOfPlane(img, i); - frame->data[i] = static_cast( - CVPixelBufferGetBaseAddressOfPlane(img, i)); + frame->data[i] = static_cast( + CVPixelBufferGetBaseAddressOfPlane(img, i)); } return true; } @implementation OBSAVCaptureDelegate - (void)captureOutput:(AVCaptureOutput *)out - didDropSampleBuffer:(CMSampleBufferRef)sampleBuffer - fromConnection:(AVCaptureConnection *)connection + didDropSampleBuffer:(CMSampleBufferRef)sampleBuffer + fromConnection:(AVCaptureConnection *)connection { UNUSED_PARAMETER(out); UNUSED_PARAMETER(sampleBuffer); @@ -613,8 +604,8 @@ static inline bool update_frame(av_capture *capture, } - (void)captureOutput:(AVCaptureOutput *)captureOutput - didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer - fromConnection:(AVCaptureConnection *)connection + didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer + fromConnection:(AVCaptureConnection *)connection { UNUSED_PARAMETER(captureOutput); UNUSED_PARAMETER(connection); @@ -627,8 +618,8 @@ static inline bool update_frame(av_capture *capture, CMTime target_pts = CMSampleBufferGetOutputPresentationTimeStamp(sampleBuffer); - CMTime target_pts_nano = CMTimeConvertScale(target_pts, NANO_TIMESCALE, - kCMTimeRoundingMethod_Default); + CMTime target_pts_nano = CMTimeConvertScale( + target_pts, NANO_TIMESCALE, kCMTimeRoundingMethod_Default); frame->timestamp = target_pts_nano.value; if (!update_frame(capture, frame, sampleBuffer)) { @@ -648,12 +639,12 @@ static void av_capture_enable_buffering(av_capture *capture, bool enabled) obs_source_set_async_unbuffered(capture->source, !enabled); } -static const char *av_capture_getname(void*) +static const char *av_capture_getname(void *) { return TEXT_AVCAPTURE; } -static void unlock_device(av_capture *capture, AVCaptureDevice *dev=nullptr) +static void unlock_device(av_capture *capture, AVCaptureDevice *dev = nullptr) { if (!dev) dev = capture->device; @@ -692,7 +683,7 @@ static void remove_device(av_capture *capture) static void av_capture_destroy(void *data) { - auto capture = static_cast(data); + auto capture = static_cast(data); delete capture; } @@ -731,9 +722,8 @@ static bool init_session(av_capture *capture) capture->queue = queue; [capture->session addOutput:capture->out]; - [capture->out - setSampleBufferDelegate:capture->delegate - queue:capture->queue]; + [capture->out setSampleBufferDelegate:capture->delegate + queue:capture->queue]; return true; } @@ -743,11 +733,11 @@ static bool init_format(av_capture *capture, AVCaptureDevice *dev); static bool init_device_input(av_capture *capture, AVCaptureDevice *dev) { NSError *err = nil; - AVCaptureDeviceInput *device_input = [AVCaptureDeviceInput - deviceInputWithDevice:dev error:&err]; + AVCaptureDeviceInput *device_input = + [AVCaptureDeviceInput deviceInputWithDevice:dev error:&err]; if (!device_input) { AVLOG(LOG_ERROR, "Error while initializing device input: %s", - err.localizedFailureReason.UTF8String); + err.localizedFailureReason.UTF8String); return false; } @@ -765,38 +755,38 @@ static bool init_device_input(av_capture *capture, AVCaptureDevice *dev) static uint32_t uint_from_dict(NSDictionary *dict, CFStringRef key) { - return ((NSNumber*)dict[(__bridge NSString*)key]).unsignedIntValue; + return ((NSNumber *)dict[(__bridge NSString *)key]).unsignedIntValue; } static bool init_format(av_capture *capture, AVCaptureDevice *dev) { AVCaptureDeviceFormat *format = dev.activeFormat; - CMMediaType mtype = CMFormatDescriptionGetMediaType( - format.formatDescription); + CMMediaType mtype = + CMFormatDescriptionGetMediaType(format.formatDescription); // TODO: support other media types if (mtype != kCMMediaType_Video && mtype != kCMMediaType_Muxed) { AVLOG(LOG_ERROR, "CMMediaType '%s' is unsupported", - AV_FOURCC_STR(mtype)); + AV_FOURCC_STR(mtype)); return false; } capture->out.videoSettings = nil; FourCharCode subtype = uint_from_dict(capture->out.videoSettings, - kCVPixelBufferPixelFormatTypeKey); + kCVPixelBufferPixelFormatTypeKey); if (format_from_subtype(subtype) != VIDEO_FORMAT_NONE) { AVLOG(LOG_DEBUG, "Using native fourcc '%s'", - AV_FOURCC_STR(subtype)); + AV_FOURCC_STR(subtype)); return true; } AVLOG(LOG_DEBUG, "Using fallback fourcc '%s' ('%s' 0x%08x unsupported)", - AV_FOURCC_STR(kCVPixelFormatType_32BGRA), - AV_FOURCC_STR(subtype), subtype); + AV_FOURCC_STR(kCVPixelFormatType_32BGRA), AV_FOURCC_STR(subtype), + subtype); capture->out.videoSettings = @{ - (__bridge NSString*)kCVPixelBufferPixelFormatTypeKey: - @(kCVPixelFormatType_32BGRA) + (__bridge NSString *) + kCVPixelBufferPixelFormatTypeKey: @(kCVPixelFormatType_32BGRA) }; return true; } @@ -824,7 +814,7 @@ static NSString *select_preset(AVCaptureDevice *dev, NSString *cur_preset) } static bool init_preset(av_capture *capture, AVCaptureDevice *dev, - obs_data_t *settings) + obs_data_t *settings) { clear_capture(capture); @@ -833,19 +823,18 @@ static bool init_preset(av_capture *capture, AVCaptureDevice *dev, NSString *preset = get_string(settings, "preset"); if (![dev supportsAVCaptureSessionPreset:preset]) { AVLOG(LOG_WARNING, "Preset %s not available", - preset_names(preset).UTF8String); + preset_names(preset).UTF8String); preset = select_preset(dev, preset); } if (!preset) { AVLOG(LOG_WARNING, "Could not select a preset, " - "initialization failed"); + "initialization failed"); return false; } capture->session.sessionPreset = preset; - AVLOG(LOG_INFO, "Using preset %s", - preset_names(preset).UTF8String); + AVLOG(LOG_INFO, "Using preset %s", preset_names(preset).UTF8String); return true; } @@ -854,7 +843,7 @@ static bool operator==(const CMVideoDimensions &a, const CMVideoDimensions &b); static CMVideoDimensions get_dimensions(AVCaptureDeviceFormat *format); static AVCaptureDeviceFormat *find_format(AVCaptureDevice *dev, - CMVideoDimensions dims) + CMVideoDimensions dims) { for (AVCaptureDeviceFormat *format in dev.formats) { if (get_dimensions(format) == dims) @@ -880,8 +869,10 @@ static bool lock_device(av_capture *capture, AVCaptureDevice *dev) NSError *err; if (![dev lockForConfiguration:&err]) { - AVLOG(LOG_WARNING, "Could not lock device for configuration: " - "%s", err.localizedDescription.UTF8String); + AVLOG(LOG_WARNING, + "Could not lock device for configuration: " + "%s", + err.localizedDescription.UTF8String); return false; } @@ -889,9 +880,9 @@ static bool lock_device(av_capture *capture, AVCaptureDevice *dev) return true; } -template +template static void find_formats(media_frames_per_second fps, AVCaptureDevice *dev, - const CMVideoDimensions *dims, Func &&f) + const CMVideoDimensions *dims, Func &&f) { auto time = convert(fps); @@ -899,11 +890,10 @@ static void find_formats(media_frames_per_second fps, AVCaptureDevice *dev, if (!(get_dimensions(format) == *dims)) continue; - for (AVFrameRateRange *range in - format.videoSupportedFrameRateRanges) { + for (AVFrameRateRange *range in format + .videoSupportedFrameRateRanges) { if (CMTimeCompare(range.maxFrameDuration, time) >= 0 && - CMTimeCompare(range.minFrameDuration, - time) <= 0) + CMTimeCompare(range.minFrameDuration, time) <= 0) if (f(format)) return; } @@ -926,10 +916,14 @@ static bool color_space_valid(int color_space) static const char *color_space_name(int color_space) { switch (color_space) { - case COLOR_SPACE_AUTO: return "Auto"; - case VIDEO_CS_DEFAULT: return "Default"; - case VIDEO_CS_601: return "CS 601"; - case VIDEO_CS_709: return "CS 709"; + case COLOR_SPACE_AUTO: + return "Auto"; + case VIDEO_CS_DEFAULT: + return "Default"; + case VIDEO_CS_601: + return "CS 601"; + case VIDEO_CS_709: + return "CS 709"; } return "Unknown"; @@ -951,17 +945,21 @@ static bool video_range_valid(int video_range) static const char *video_range_name(int video_range) { switch (video_range) { - case VIDEO_RANGE_AUTO: return "Auto"; - case VIDEO_RANGE_DEFAULT: return "Default"; - case VIDEO_RANGE_PARTIAL: return "Partial"; - case VIDEO_RANGE_FULL: return "Full"; + case VIDEO_RANGE_AUTO: + return "Auto"; + case VIDEO_RANGE_DEFAULT: + return "Default"; + case VIDEO_RANGE_PARTIAL: + return "Partial"; + case VIDEO_RANGE_FULL: + return "Full"; } return "Unknown"; } static bool init_manual(av_capture *capture, AVCaptureDevice *dev, - obs_data_t *settings) + obs_data_t *settings) { clear_capture(capture); @@ -973,14 +971,15 @@ static bool init_manual(av_capture *capture, AVCaptureDevice *dev, bool refresh = false; if (input_format != actual_format) { refresh = obs_data_get_autoselect_int(settings, - "input_format") != actual_format; + "input_format") != + actual_format; obs_data_set_autoselect_int(settings, "input_format", - actual_format); + actual_format); } else { refresh = obs_data_has_autoselect_value(settings, - "input_format"); + "input_format"); obs_data_unset_autoselect_value(settings, - "input_format"); + "input_format"); } if (refresh) @@ -991,7 +990,7 @@ static bool init_manual(av_capture *capture, AVCaptureDevice *dev, obs_data_get_int(settings, "color_space"); if (!color_space_valid(capture->requested_colorspace)) { AVLOG(LOG_WARNING, "Unsupported color space: %d", - capture->requested_colorspace); + capture->requested_colorspace); return false; } @@ -999,7 +998,7 @@ static bool init_manual(av_capture *capture, AVCaptureDevice *dev, obs_data_get_int(settings, "video_range"); if (!video_range_valid(capture->requested_video_range)) { AVLOG(LOG_WARNING, "Unsupported color range: %d", - capture->requested_video_range); + capture->requested_video_range); return false; } @@ -1011,14 +1010,13 @@ static bool init_manual(av_capture *capture, AVCaptureDevice *dev, media_frames_per_second fps{}; if (!obs_data_get_frames_per_second(settings, "frame_rate", &fps, - nullptr)) { + nullptr)) { AVLOG(LOG_WARNING, "Could not load frame rate"); return false; } AVCaptureDeviceFormat *format = nullptr; - find_formats(fps, dev, &dims, [&](AVCaptureDeviceFormat *format_) - { + find_formats(fps, dev, &dims, [&](AVCaptureDeviceFormat *format_) { auto desc = format_.formatDescription; auto fourcc = CMFormatDescriptionGetMediaSubType(desc); if (input_format != INPUT_FORMAT_AUTO && fourcc != input_format) @@ -1030,57 +1028,55 @@ static bool init_manual(av_capture *capture, AVCaptureDevice *dev, }); if (!format) { - AVLOG(LOG_WARNING, "Frame rate is not supported: %g FPS " - "(%u/%u)", - media_frames_per_second_to_fps(fps), - fps.numerator, fps.denominator); + AVLOG(LOG_WARNING, + "Frame rate is not supported: %g FPS " + "(%u/%u)", + media_frames_per_second_to_fps(fps), fps.numerator, + fps.denominator); return false; } if (!lock_device(capture, dev)) return false; - const char *if_name = input_format == INPUT_FORMAT_AUTO ? - "Auto" : fourcc_subtype_name(input_format); + const char *if_name = input_format == INPUT_FORMAT_AUTO + ? "Auto" + : fourcc_subtype_name(input_format); #define IF_AUTO(x) (input_format != INPUT_FORMAT_AUTO ? "" : x) - AVLOG(LOG_INFO, "Capturing '%s' (%s):\n" - " Resolution: %ux%u\n" - " FPS: %g (%" PRIu32 "/%" PRIu32 ")\n" - " Frame interval: %g" NBSP "s\n" - " Input format: %s%s%s (%s)%s\n" - " Requested color space: %s (%d)\n" - " Requested video range: %s (%d)\n" - " Using format: %s", - dev.localizedName.UTF8String, dev.uniqueID.UTF8String, - dims.width, dims.height, - media_frames_per_second_to_fps(fps), - fps.numerator, fps.denominator, - media_frames_per_second_to_frame_interval(fps), - if_name, IF_AUTO(" (actual: "), - IF_AUTO(fourcc_subtype_name(actual_format)), - AV_FOURCC_STR(actual_format), IF_AUTO(")"), - color_space_name(capture->requested_colorspace), - capture->requested_colorspace, - video_range_name(capture->requested_video_range), - capture->requested_video_range, - format.description.UTF8String); + AVLOG(LOG_INFO, + "Capturing '%s' (%s):\n" + " Resolution: %ux%u\n" + " FPS: %g (%" PRIu32 "/%" PRIu32 ")\n" + " Frame interval: %g" NBSP "s\n" + " Input format: %s%s%s (%s)%s\n" + " Requested color space: %s (%d)\n" + " Requested video range: %s (%d)\n" + " Using format: %s", + dev.localizedName.UTF8String, dev.uniqueID.UTF8String, dims.width, + dims.height, media_frames_per_second_to_fps(fps), fps.numerator, + fps.denominator, media_frames_per_second_to_frame_interval(fps), + if_name, IF_AUTO(" (actual: "), + IF_AUTO(fourcc_subtype_name(actual_format)), + AV_FOURCC_STR(actual_format), IF_AUTO(")"), + color_space_name(capture->requested_colorspace), + capture->requested_colorspace, + video_range_name(capture->requested_video_range), + capture->requested_video_range, format.description.UTF8String); #undef IF_AUTO dev.activeFormat = format; dev.activeVideoMinFrameDuration = convert(fps); dev.activeVideoMaxFrameDuration = convert(fps); - capture->video_info.update([&](av_video_info &vi) - { - vi.video_params_valid = false; - }); + capture->video_info.update( + [&](av_video_info &vi) { vi.video_params_valid = false; }); return true; } static void capture_device(av_capture *capture, AVCaptureDevice *dev, - obs_data_t *settings) + obs_data_t *settings) { const char *name = dev.localizedName.UTF8String; obs_data_set_string(settings, "device_name", name); @@ -1108,25 +1104,24 @@ static void capture_device(av_capture *capture, AVCaptureDevice *dev, } static inline void handle_disconnect_capture(av_capture *capture, - AVCaptureDevice *dev) + AVCaptureDevice *dev) { if (![dev.uniqueID isEqualTo:capture->uid]) return; if (!capture->device) { AVLOG(LOG_INFO, "Received disconnect for inactive device '%s'", - capture->uid.UTF8String); + capture->uid.UTF8String); return; } AVLOG(LOG_WARNING, "Device with unique ID '%s' disconnected", - dev.uniqueID.UTF8String); + dev.uniqueID.UTF8String); remove_device(capture); } -static inline void handle_disconnect(av_capture *capture, - AVCaptureDevice *dev) +static inline void handle_disconnect(av_capture *capture, AVCaptureDevice *dev) { if (!dev) return; @@ -1136,25 +1131,28 @@ static inline void handle_disconnect(av_capture *capture, } static inline void handle_connect_capture(av_capture *capture, - AVCaptureDevice *dev, obs_data_t *settings) + AVCaptureDevice *dev, + obs_data_t *settings) { if (![dev.uniqueID isEqualTo:capture->uid]) return; if (capture->device) { AVLOG(LOG_ERROR, "Received connect for in-use device '%s'", - capture->uid.UTF8String); + capture->uid.UTF8String); return; } - AVLOG(LOG_INFO, "Device with unique ID '%s' connected, " - "resuming capture", dev.uniqueID.UTF8String); + AVLOG(LOG_INFO, + "Device with unique ID '%s' connected, " + "resuming capture", + dev.uniqueID.UTF8String); capture_device(capture, dev, settings); } -static inline void handle_connect(av_capture *capture, - AVCaptureDevice *dev, obs_data_t *settings) +static inline void handle_connect(av_capture *capture, AVCaptureDevice *dev, + obs_data_t *settings) { if (!dev) return; @@ -1175,21 +1173,17 @@ static bool av_capture_init(av_capture *capture, obs_data_t *settings) addObserverForName:AVCaptureDeviceWasDisconnectedNotification object:nil queue:[NSOperationQueue mainQueue] - usingBlock:^(NSNotification *note) - { + usingBlock:^(NSNotification *note) { handle_disconnect(capture, note.object); - } - ]); + }]); capture->connect_observer.reset([nc addObserverForName:AVCaptureDeviceWasConnectedNotification object:nil queue:[NSOperationQueue mainQueue] - usingBlock:^(NSNotification *note) - { + usingBlock:^(NSNotification *note) { handle_connect(capture, note.object, settings); - } - ]); + }]); AVCaptureDevice *dev = [AVCaptureDevice deviceWithUniqueID:capture->uid]; @@ -1198,9 +1192,10 @@ static bool av_capture_init(av_capture *capture, obs_data_t *settings) if (capture->uid.length < 1) AVLOG(LOG_INFO, "No device selected"); else - AVLOG(LOG_WARNING, "Could not initialize device " \ - "with unique ID '%s'", - capture->uid.UTF8String); + AVLOG(LOG_WARNING, + "Could not initialize device " + "with unique ID '%s'", + capture->uid.UTF8String); return true; } @@ -1227,7 +1222,7 @@ static void *av_capture_create(obs_data_t *settings, obs_source_t *source) } av_capture_enable_buffering(capture.get(), - obs_data_get_bool(settings, "buffering")); + obs_data_get_bool(settings, "buffering")); return capture.release(); } @@ -1237,12 +1232,9 @@ static NSArray *presets(void) return @[ //AVCaptureSessionPresetiFrame1280x720, //AVCaptureSessionPresetiFrame960x540, - AVCaptureSessionPreset1280x720, - AVCaptureSessionPreset960x540, - AVCaptureSessionPreset640x480, - AVCaptureSessionPreset352x288, - AVCaptureSessionPreset320x240, - AVCaptureSessionPresetHigh, + AVCaptureSessionPreset1280x720, AVCaptureSessionPreset960x540, + AVCaptureSessionPreset640x480, AVCaptureSessionPreset352x288, + AVCaptureSessionPreset320x240, AVCaptureSessionPresetHigh, //AVCaptureSessionPresetMedium, //AVCaptureSessionPresetLow, //AVCaptureSessionPresetPhoto, @@ -1252,15 +1244,15 @@ static NSArray *presets(void) static NSString *preset_names(NSString *preset) { NSDictionary *preset_names = @{ - AVCaptureSessionPresetLow:@"Low", - AVCaptureSessionPresetMedium:@"Medium", - AVCaptureSessionPresetHigh:@"High", - AVCaptureSessionPreset320x240:@"320x240", - AVCaptureSessionPreset352x288:@"352x288", - AVCaptureSessionPreset640x480:@"640x480", - AVCaptureSessionPreset960x540:@"960x540", - AVCaptureSessionPreset1280x720:@"1280x720", - AVCaptureSessionPresetHigh:@"High", + AVCaptureSessionPresetLow: @"Low", + AVCaptureSessionPresetMedium: @"Medium", + AVCaptureSessionPresetHigh: @"High", + AVCaptureSessionPreset320x240: @"320x240", + AVCaptureSessionPreset352x288: @"352x288", + AVCaptureSessionPreset640x480: @"640x480", + AVCaptureSessionPreset960x540: @"960x540", + AVCaptureSessionPreset1280x720: @"1280x720", + AVCaptureSessionPresetHigh: @"High", }; NSString *name = preset_names[preset]; if (name) @@ -1268,31 +1260,30 @@ static NSString *preset_names(NSString *preset) return [NSString stringWithFormat:@"Unknown (%@)", preset]; } - static void av_capture_defaults(obs_data_t *settings) { obs_data_set_default_string(settings, "uid", ""); obs_data_set_default_bool(settings, "use_preset", true); obs_data_set_default_string(settings, "preset", - AVCaptureSessionPreset1280x720.UTF8String); + AVCaptureSessionPreset1280x720.UTF8String); obs_data_set_default_int(settings, "input_format", INPUT_FORMAT_AUTO); obs_data_set_default_int(settings, "color_space", COLOR_SPACE_AUTO); obs_data_set_default_int(settings, "video_range", VIDEO_RANGE_AUTO); } -static bool update_device_list(obs_property_t *list, - NSString *uid, NSString *name, bool disconnected) +static bool update_device_list(obs_property_t *list, NSString *uid, + NSString *name, bool disconnected) { - bool dev_found = false; + bool dev_found = false; bool list_modified = false; size_t size = obs_property_list_item_count(list); for (size_t i = 0; i < size;) { const char *uid_ = obs_property_list_item_string(list, i); - bool found = [uid isEqualToString:@(uid_ ? uid_ : "")]; - bool disabled = obs_property_list_item_disabled(list, i); + bool found = [uid isEqualToString:@(uid_ ? uid_ : "")]; + bool disabled = obs_property_list_item_disabled(list, i); if (!found && !disabled) { i += 1; continue; @@ -1303,7 +1294,7 @@ static bool update_device_list(obs_property_t *list, obs_property_list_item_remove(list, i); continue; } - + if (disabled != disconnected) list_modified = true; @@ -1316,22 +1307,22 @@ static bool update_device_list(obs_property_t *list, return list_modified; size_t idx = obs_property_list_add_string(list, name.UTF8String, - uid.UTF8String); + uid.UTF8String); obs_property_list_item_disable(list, idx, disconnected); return true; } static void fill_presets(AVCaptureDevice *dev, obs_property_t *list, - NSString *current_preset) + NSString *current_preset) { obs_property_list_clear(list); bool preset_found = false; for (NSString *preset in presets()) { bool is_current = [preset isEqualToString:current_preset]; - bool supported = dev && - [dev supportsAVCaptureSessionPreset:preset]; + bool supported = dev && + [dev supportsAVCaptureSessionPreset:preset]; if (is_current) preset_found = true; @@ -1339,23 +1330,23 @@ static void fill_presets(AVCaptureDevice *dev, obs_property_t *list, if (!supported && !is_current) continue; - size_t idx = obs_property_list_add_string(list, - preset_names(preset).UTF8String, - preset.UTF8String); + size_t idx = obs_property_list_add_string( + list, preset_names(preset).UTF8String, + preset.UTF8String); obs_property_list_item_disable(list, idx, !supported); } if (preset_found) return; - size_t idx = obs_property_list_add_string(list, - preset_names(current_preset).UTF8String, - current_preset.UTF8String); + size_t idx = obs_property_list_add_string( + list, preset_names(current_preset).UTF8String, + current_preset.UTF8String); obs_property_list_item_disable(list, idx, true); } -static bool check_preset(AVCaptureDevice *dev, - obs_property_t *list, obs_data_t *settings) +static bool check_preset(AVCaptureDevice *dev, obs_property_t *list, + obs_data_t *settings) { NSString *current_preset = get_string(settings, "preset"); @@ -1368,8 +1359,8 @@ static bool check_preset(AVCaptureDevice *dev, bool presets_changed = false; for (NSString *preset in presets()) { bool is_listed = [listed member:preset] != nil; - bool supported = dev && - [dev supportsAVCaptureSessionPreset:preset]; + bool supported = dev && + [dev supportsAVCaptureSessionPreset:preset]; if (supported == is_listed) continue; @@ -1399,7 +1390,7 @@ static bool autoselect_preset(AVCaptureDevice *dev, obs_data_t *settings) obs_data_get_autoselect_string(settings, "preset"); if (![preset isEqualToString:@(autoselect)]) { obs_data_set_autoselect_string(settings, "preset", - preset.UTF8String); + preset.UTF8String); return true; } } @@ -1436,8 +1427,7 @@ static resolutions_t enumerate_resolutions(AVCaptureDevice *dev) static void sort_resolutions(vector &resolutions) { - auto cmp = [](const CMVideoDimensions &a, const CMVideoDimensions &b) - { + auto cmp = [](const CMVideoDimensions &a, const CMVideoDimensions &b) { return a.width * a.height > b.width * b.height; }; @@ -1446,18 +1436,18 @@ static void sort_resolutions(vector &resolutions) static void data_set_resolution(obs_data_t *data, const CMVideoDimensions &dims) { - obs_data_set_int(data, "width", dims.width); + obs_data_set_int(data, "width", dims.width); obs_data_set_int(data, "height", dims.height); } static void data_set_resolution(const unique_ptr &data, - const CMVideoDimensions &dims) + const CMVideoDimensions &dims) { data_set_resolution(data.get(), dims); } static bool add_resolution_to_list(vector &res, - const CMVideoDimensions &dims) + const CMVideoDimensions &dims) { if (find(begin(res), end(res), dims) != end(res)) return false; @@ -1477,7 +1467,7 @@ static bool operator==(const CMVideoDimensions &a, const CMVideoDimensions &b) } static bool resolution_property_needs_update(obs_property_t *p, - const resolutions_t &resolutions) + const resolutions_t &resolutions) { vector res_found(resolutions.size()); @@ -1498,11 +1488,12 @@ static bool resolution_property_needs_update(obs_property_t *p, } return any_of(begin(res_found), end(res_found), - [](bool b) { return !b; }); + [](bool b) { return !b; }); } static bool update_resolution_property(obs_properties_t *props, - const config_helper &conf, obs_property_t *p=nullptr) + const config_helper &conf, + obs_property_t *p = nullptr) { if (!p) p = obs_properties_get(props, "resolution"); @@ -1546,23 +1537,23 @@ static bool update_resolution_property(obs_properties_t *props, static media_frames_per_second convert(CMTime time_) { media_frames_per_second res{}; - clamp(res.numerator, time_.timescale); + clamp(res.numerator, time_.timescale); clamp(res.denominator, time_.value); return res; } -using frame_rates_t = vector>; -static frame_rates_t enumerate_frame_rates(AVCaptureDevice *dev, - const CMVideoDimensions *dims = nullptr) +using frame_rates_t = + vector>; +static frame_rates_t +enumerate_frame_rates(AVCaptureDevice *dev, + const CMVideoDimensions *dims = nullptr) { frame_rates_t res; if (!dev || !dims) return res; - auto add_unique_frame_rate_range = [&](AVFrameRateRange *range) - { + auto add_unique_frame_rate_range = [&](AVFrameRateRange *range) { auto min = convert(range.maxFrameDuration); auto max = convert(range.minFrameDuration); @@ -1578,22 +1569,21 @@ static frame_rates_t enumerate_frame_rates(AVCaptureDevice *dev, if (!(get_dimensions(format) == *dims)) continue; - for (AVFrameRateRange *range in - format.videoSupportedFrameRateRanges) { + for (AVFrameRateRange *range in format + .videoSupportedFrameRateRanges) { add_unique_frame_rate_range(range); if (CMTimeCompare(range.minFrameDuration, - range.maxFrameDuration) != 0) { - blog(LOG_WARNING, "Got actual frame rate range:" - " %g - %g " - "({%lld, %d} - {%lld, %d})", - range.minFrameRate, - range.maxFrameRate, - range.maxFrameDuration.value, - range.maxFrameDuration.timescale, - range.minFrameDuration.value, - range.minFrameDuration.timescale - ); + range.maxFrameDuration) != 0) { + blog(LOG_WARNING, + "Got actual frame rate range:" + " %g - %g " + "({%lld, %d} - {%lld, %d})", + range.minFrameRate, range.maxFrameRate, + range.maxFrameDuration.value, + range.maxFrameDuration.timescale, + range.minFrameDuration.value, + range.minFrameDuration.timescale); } } } @@ -1602,19 +1592,19 @@ static frame_rates_t enumerate_frame_rates(AVCaptureDevice *dev, } static bool operator==(const media_frames_per_second &a, - const media_frames_per_second &b) + const media_frames_per_second &b) { return a.numerator == b.numerator && a.denominator == b.denominator; } static bool operator!=(const media_frames_per_second &a, - const media_frames_per_second &b) + const media_frames_per_second &b) { return !(a == b); } static bool frame_rate_property_needs_update(obs_property_t *p, - const frame_rates_t &frame_rates) + const frame_rates_t &frame_rates) { auto fps_num = frame_rates.size(); auto num = obs_property_frame_rate_fps_ranges_count(p); @@ -1627,7 +1617,7 @@ static bool frame_rate_property_needs_update(obs_property_t *p, auto max_ = obs_property_frame_rate_fps_range_max(p, i); auto it = find(begin(frame_rates), end(frame_rates), - make_pair(min_, max_)); + make_pair(min_, max_)); if (it == end(frame_rates)) return true; @@ -1635,11 +1625,12 @@ static bool frame_rate_property_needs_update(obs_property_t *p, } return any_of(begin(fps_found), end(fps_found), - [](bool b) { return !b; }); + [](bool b) { return !b; }); } static bool update_frame_rate_property(obs_properties_t *props, - const config_helper &conf, obs_property_t *p=nullptr) + const config_helper &conf, + obs_property_t *p = nullptr) { if (!p) p = obs_properties_get(props, "frame_rate"); @@ -1658,20 +1649,19 @@ static bool update_frame_rate_property(obs_properties_t *props, obs_property_frame_rate_fps_ranges_clear(p); for (auto &pair : frame_rates) - obs_property_frame_rate_fps_range_add(p, - pair.first, pair.second); + obs_property_frame_rate_fps_range_add(p, pair.first, + pair.second); return true; } -static vector enumerate_formats(AVCaptureDevice *dev, - const CMVideoDimensions &dims, - const media_frames_per_second &fps) +static vector +enumerate_formats(AVCaptureDevice *dev, const CMVideoDimensions &dims, + const media_frames_per_second &fps) { - vector result; + vector result; - find_formats(fps, dev, &dims, [&](AVCaptureDeviceFormat *format) - { + find_formats(fps, dev, &dims, [&](AVCaptureDeviceFormat *format) { result.push_back(format); return false; }); @@ -1679,9 +1669,9 @@ static vector enumerate_formats(AVCaptureDevice *dev, return result; } -static bool input_format_property_needs_update(obs_property_t *p, - const vector &formats, - const FourCharCode *fourcc_) +static bool input_format_property_needs_update( + obs_property_t *p, const vector &formats, + const FourCharCode *fourcc_) { bool fourcc_found = !fourcc_; vector if_found(formats.size()); @@ -1692,13 +1682,13 @@ static bool input_format_property_needs_update(obs_property_t *p, fourcc_found = fourcc_found || fourcc == *fourcc_; auto pos = find_if(begin(formats), end(formats), - [&](AVCaptureDeviceFormat *format) - { - FourCharCode fourcc_ = 0; - format_description_subtype_name( - format.formatDescription, &fourcc_); - return fourcc_ == fourcc; - }); + [&](AVCaptureDeviceFormat *format) { + FourCharCode fourcc_ = 0; + format_description_subtype_name( + format.formatDescription, + &fourcc_); + return fourcc_ == fourcc; + }); if (pos == end(formats)) return true; @@ -1706,11 +1696,12 @@ static bool input_format_property_needs_update(obs_property_t *p, } return fourcc_found || any_of(begin(if_found), end(if_found), - [](bool b) { return !b; }); + [](bool b) { return !b; }); } static bool update_input_format_property(obs_properties_t *props, - const config_helper &conf, obs_property_t *p=nullptr) + const config_helper &conf, + obs_property_t *p = nullptr) { if (!p) p = obs_properties_get(props, "input_format"); @@ -1718,16 +1709,15 @@ static bool update_input_format_property(obs_properties_t *props, if (!p) return false; - auto update_enabled = [&](bool enabled) - { + auto update_enabled = [&](bool enabled) { bool was_enabled = obs_property_enabled(p); obs_property_set_enabled(p, enabled); return was_enabled != enabled; }; auto valid_dims = conf.dims(); - auto valid_fps = conf.fps(); - auto valid_if = conf.input_format(); + auto valid_fps = conf.fps(); + auto valid_if = conf.input_format(); if (!valid_dims || !valid_fps) return update_enabled(false); @@ -1743,7 +1733,7 @@ static bool update_input_format_property(obs_properties_t *props, for (auto &format : formats) { FourCharCode fourcc = 0; const char *name = format_description_subtype_name( - format.formatDescription, &fourcc); + format.formatDescription, &fourcc); obs_property_list_add_int(p, name, fourcc); fourcc_found = fourcc_found || fourcc == *valid_if; } @@ -1757,7 +1747,8 @@ static bool update_input_format_property(obs_properties_t *props, } static bool update_int_list_property(obs_property_t *p, const int *val, - const size_t count, const char *localization_name) + const size_t count, + const char *localization_name) { size_t num = obs_property_list_item_count(p); if (num > count) { @@ -1784,12 +1775,12 @@ static bool update_int_list_property(obs_property_t *p, const int *val, return true; } -template -static bool update_int_list_property(const char *prop_name, - const char *localization_name, size_t count, - int auto_val, bool (*valid_func)(int), - obs_properties_t *props, const config_helper &conf, - obs_property_t *p, Func get_val) +template +static bool +update_int_list_property(const char *prop_name, const char *localization_name, + size_t count, int auto_val, bool (*valid_func)(int), + obs_properties_t *props, const config_helper &conf, + obs_property_t *p, Func get_val) { auto ref = get_ref(props); if (!p) @@ -1808,20 +1799,20 @@ static bool update_int_list_property(const char *prop_name, obs_data_has_autoselect_value(conf.settings, prop_name); if ((params_valid && format_is_yuv(ref->frame.format)) || - !valid_func(val)) + !valid_func(val)) should_enable = true; obs_property_set_enabled(p, should_enable); bool updated = enabled != should_enable; - updated = update_int_list_property(p, - valid_func(val) ? nullptr : &val, - count, localization_name) || updated; + updated = update_int_list_property(p, valid_func(val) ? nullptr : &val, + count, localization_name) || + updated; if (!should_enable) { if (has_autoselect) obs_data_unset_autoselect_value(conf.settings, - prop_name); + prop_name); return updated || has_autoselect; } @@ -1829,14 +1820,14 @@ static bool update_int_list_property(const char *prop_name, if (!use_autoselect) { if (has_autoselect) obs_data_unset_autoselect_value(conf.settings, - prop_name); + prop_name); return updated || has_autoselect; } - if (params_valid && get_val(vi) != - obs_data_get_autoselect_int(conf.settings, prop_name)) { + if (params_valid && get_val(vi) != obs_data_get_autoselect_int( + conf.settings, prop_name)) { obs_data_set_autoselect_int(conf.settings, prop_name, - get_val(vi)); + get_val(vi)); return true; } @@ -1844,52 +1835,53 @@ static bool update_int_list_property(const char *prop_name, } static bool update_color_space_property(obs_properties_t *props, - const config_helper &conf, obs_property_t *p=nullptr) + const config_helper &conf, + obs_property_t *p = nullptr) { return update_int_list_property("color_space", TEXT_COLOR_UNKNOWN_NAME, - 4, COLOR_SPACE_AUTO, color_space_valid, props, conf, p, - [](av_video_info vi) - { - return vi.colorspace; - }); + 4, COLOR_SPACE_AUTO, color_space_valid, + props, conf, p, [](av_video_info vi) { + return vi.colorspace; + }); } static bool update_video_range_property(obs_properties_t *props, - const config_helper &conf, obs_property_t *p=nullptr) + const config_helper &conf, + obs_property_t *p = nullptr) { return update_int_list_property("video_range", TEXT_RANGE_UNKNOWN_NAME, - 5, VIDEO_RANGE_AUTO, video_range_valid, props, conf, p, - [](av_video_info vi) - { - return vi.video_range; - }); + 5, VIDEO_RANGE_AUTO, video_range_valid, + props, conf, p, [](av_video_info vi) { + return vi.video_range; + }); } -static bool properties_device_changed(obs_properties_t *props, obs_property_t *p, - obs_data_t *settings) +static bool properties_device_changed(obs_properties_t *props, + obs_property_t *p, obs_data_t *settings) { NSString *uid = get_string(settings, "device"); AVCaptureDevice *dev = [AVCaptureDevice deviceWithUniqueID:uid]; NSString *name = get_string(settings, "device_name"); - bool dev_list_updated = update_device_list(p, uid, name, - !dev && uid.length); + bool dev_list_updated = + update_device_list(p, uid, name, !dev && uid.length); p = obs_properties_get(props, "preset"); bool preset_list_changed = check_preset(dev, p, settings); - bool autoselect_changed = autoselect_preset(dev, settings); + bool autoselect_changed = autoselect_preset(dev, settings); config_helper conf{settings}; bool res_changed = update_resolution_property(props, conf); bool fps_changed = update_frame_rate_property(props, conf); - bool if_changed = update_input_format_property(props, conf); + bool if_changed = update_input_format_property(props, conf); - return preset_list_changed || autoselect_changed || dev_list_updated - || res_changed || fps_changed || if_changed; + return preset_list_changed || autoselect_changed || dev_list_updated || + res_changed || fps_changed || if_changed; } static bool properties_use_preset_changed(obs_properties_t *props, - obs_property_t *, obs_data_t *settings) + obs_property_t *, + obs_data_t *settings) { auto use_preset = obs_data_get_bool(settings, "use_preset"); @@ -1899,83 +1891,84 @@ static bool properties_use_preset_changed(obs_properties_t *props, bool visible = false; obs_property_t *p = nullptr; - auto noop = [](obs_properties_t *, const config_helper&, - obs_property_t *) - { - return false; - }; + auto noop = [](obs_properties_t *, const config_helper &, + obs_property_t *) { return false; }; -#define UPDATE_PROPERTY(prop, uses_preset, func) \ - p = obs_properties_get(props, prop); \ - visible = use_preset == uses_preset; \ +#define UPDATE_PROPERTY(prop, uses_preset, func) \ + p = obs_properties_get(props, prop); \ + visible = use_preset == uses_preset; \ updated = obs_property_visible(p) != visible || updated; \ - obs_property_set_visible(p, visible);\ + obs_property_set_visible(p, visible); \ updated = func(props, conf, p) || updated; - UPDATE_PROPERTY("preset", true, noop); - UPDATE_PROPERTY("resolution", false, update_resolution_property); - UPDATE_PROPERTY("frame_rate", false, update_frame_rate_property); + UPDATE_PROPERTY("preset", true, noop); + UPDATE_PROPERTY("resolution", false, update_resolution_property); + UPDATE_PROPERTY("frame_rate", false, update_frame_rate_property); UPDATE_PROPERTY("input_format", false, update_input_format_property); - UPDATE_PROPERTY("color_space", false, update_color_space_property); - UPDATE_PROPERTY("video_range", false, update_video_range_property); + UPDATE_PROPERTY("color_space", false, update_color_space_property); + UPDATE_PROPERTY("video_range", false, update_video_range_property); return updated; } static bool properties_preset_changed(obs_properties_t *, obs_property_t *p, - obs_data_t *settings) + obs_data_t *settings) { NSString *uid = get_string(settings, "device"); AVCaptureDevice *dev = [AVCaptureDevice deviceWithUniqueID:uid]; bool preset_list_changed = check_preset(dev, p, settings); - bool autoselect_changed = autoselect_preset(dev, settings); + bool autoselect_changed = autoselect_preset(dev, settings); return preset_list_changed || autoselect_changed; } static bool properties_resolution_changed(obs_properties_t *props, - obs_property_t *p, obs_data_t *settings) + obs_property_t *p, + obs_data_t *settings) { config_helper conf{settings}; bool res_updated = update_resolution_property(props, conf, p); bool fps_updated = update_frame_rate_property(props, conf); - bool if_updated = update_input_format_property(props, conf); - bool cs_updated = update_color_space_property(props, conf); - bool cr_updated = update_video_range_property(props, conf); + bool if_updated = update_input_format_property(props, conf); + bool cs_updated = update_color_space_property(props, conf); + bool cr_updated = update_video_range_property(props, conf); - return res_updated || fps_updated || - if_updated || cs_updated || cr_updated; + return res_updated || fps_updated || if_updated || cs_updated || + cr_updated; } static bool properties_frame_rate_changed(obs_properties_t *props, - obs_property_t *p, obs_data_t *settings) + obs_property_t *p, + obs_data_t *settings) { config_helper conf{settings}; bool fps_updated = update_frame_rate_property(props, conf, p); - bool if_updated = update_input_format_property(props, conf); - bool cs_updated = update_color_space_property(props, conf); - bool cr_updated = update_video_range_property(props, conf); + bool if_updated = update_input_format_property(props, conf); + bool cs_updated = update_color_space_property(props, conf); + bool cr_updated = update_video_range_property(props, conf); return fps_updated || if_updated || cs_updated || cr_updated; } static bool properties_input_format_changed(obs_properties_t *props, - obs_property_t *p, obs_data_t *settings) + obs_property_t *p, + obs_data_t *settings) { config_helper conf{settings}; - bool if_updated = update_input_format_property(props, conf, p); - bool cs_updated = update_color_space_property(props, conf); - bool cr_updated = update_video_range_property(props, conf); + bool if_updated = update_input_format_property(props, conf, p); + bool cs_updated = update_color_space_property(props, conf); + bool cr_updated = update_video_range_property(props, conf); return if_updated || cs_updated || cr_updated; } static bool properties_color_space_changed(obs_properties_t *props, - obs_property_t *p, obs_data_t *settings) + obs_property_t *p, + obs_data_t *settings) { config_helper conf{settings}; @@ -1983,7 +1976,8 @@ static bool properties_color_space_changed(obs_properties_t *props, } static bool properties_video_range_changed(obs_properties_t *props, - obs_property_t *p, obs_data_t *settings) + obs_property_t *p, + obs_data_t *settings) { config_helper conf{settings}; @@ -1992,77 +1986,73 @@ static bool properties_video_range_changed(obs_properties_t *props, static void add_properties_param(obs_properties_t *props, av_capture *capture) { - auto param = unique_ptr( - new properties_param(capture)); + auto param = + unique_ptr(new properties_param(capture)); - obs_properties_set_param(props, param.release(), - [](void *param) - { - delete static_cast(param); + obs_properties_set_param(props, param.release(), [](void *param) { + delete static_cast(param); }); } static void add_preset_properties(obs_properties_t *props) { - obs_property_t *preset_list = obs_properties_add_list(props, "preset", - TEXT_PRESET, OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_STRING); + obs_property_t *preset_list = obs_properties_add_list( + props, "preset", TEXT_PRESET, OBS_COMBO_TYPE_LIST, + OBS_COMBO_FORMAT_STRING); for (NSString *preset in presets()) obs_property_list_add_string(preset_list, - preset_names(preset).UTF8String, - preset.UTF8String); + preset_names(preset).UTF8String, + preset.UTF8String); obs_property_set_modified_callback(preset_list, - properties_preset_changed); + properties_preset_changed); } static void add_manual_properties(obs_properties_t *props) { - obs_property_t *resolutions = obs_properties_add_list(props, - "resolution", TEXT_RESOLUTION, OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_STRING); + obs_property_t *resolutions = obs_properties_add_list( + props, "resolution", TEXT_RESOLUTION, OBS_COMBO_TYPE_LIST, + OBS_COMBO_FORMAT_STRING); obs_property_set_enabled(resolutions, false); obs_property_set_modified_callback(resolutions, - properties_resolution_changed); + properties_resolution_changed); - obs_property_t *frame_rates = obs_properties_add_frame_rate(props, - "frame_rate", TEXT_FRAME_RATE); + obs_property_t *frame_rates = obs_properties_add_frame_rate( + props, "frame_rate", TEXT_FRAME_RATE); /*obs_property_frame_rate_option_add(frame_rates, "match obs", TEXT_MATCH_OBS);*/ obs_property_set_enabled(frame_rates, false); obs_property_set_modified_callback(frame_rates, - properties_frame_rate_changed); + properties_frame_rate_changed); - obs_property_t *input_format = obs_properties_add_list(props, - "input_format", TEXT_INPUT_FORMAT, - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); - obs_property_list_add_int(input_format, TEXT_AUTO, - INPUT_FORMAT_AUTO); + obs_property_t *input_format = obs_properties_add_list( + props, "input_format", TEXT_INPUT_FORMAT, OBS_COMBO_TYPE_LIST, + OBS_COMBO_FORMAT_INT); + obs_property_list_add_int(input_format, TEXT_AUTO, INPUT_FORMAT_AUTO); obs_property_set_enabled(input_format, false); obs_property_set_modified_callback(input_format, - properties_input_format_changed); + properties_input_format_changed); - obs_property_t *color_space = obs_properties_add_list(props, - "color_space", TEXT_COLOR_SPACE, - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); + obs_property_t *color_space = obs_properties_add_list( + props, "color_space", TEXT_COLOR_SPACE, OBS_COMBO_TYPE_LIST, + OBS_COMBO_FORMAT_INT); obs_property_list_add_int(color_space, TEXT_AUTO, COLOR_SPACE_AUTO); obs_property_list_add_int(color_space, "Rec. 601", VIDEO_CS_601); obs_property_list_add_int(color_space, "Rec. 709", VIDEO_CS_709); obs_property_set_enabled(color_space, false); obs_property_set_modified_callback(color_space, - properties_color_space_changed); + properties_color_space_changed); -#define ADD_RANGE(x) \ - obs_property_list_add_int(video_range, TEXT_ ## x, VIDEO_ ## x) - obs_property_t *video_range = obs_properties_add_list(props, - "video_range", TEXT_VIDEO_RANGE, - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); +#define ADD_RANGE(x) obs_property_list_add_int(video_range, TEXT_##x, VIDEO_##x) + obs_property_t *video_range = obs_properties_add_list( + props, "video_range", TEXT_VIDEO_RANGE, OBS_COMBO_TYPE_LIST, + OBS_COMBO_FORMAT_INT); obs_property_list_add_int(video_range, TEXT_AUTO, VIDEO_RANGE_AUTO); ADD_RANGE(RANGE_PARTIAL); ADD_RANGE(RANGE_FULL); obs_property_set_enabled(video_range, false); obs_property_set_modified_callback(video_range, - properties_video_range_changed); + properties_video_range_changed); #undef ADD_RANGE } @@ -2070,43 +2060,41 @@ static obs_properties_t *av_capture_properties(void *capture) { obs_properties_t *props = obs_properties_create(); - add_properties_param(props, static_cast(capture)); + add_properties_param(props, static_cast(capture)); - obs_property_t *dev_list = obs_properties_add_list(props, "device", - TEXT_DEVICE, OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_STRING); + obs_property_t *dev_list = obs_properties_add_list( + props, "device", TEXT_DEVICE, OBS_COMBO_TYPE_LIST, + OBS_COMBO_FORMAT_STRING); obs_property_list_add_string(dev_list, "", ""); - for (AVCaptureDevice *dev in [AVCaptureDevice - devices]) { - if ([dev hasMediaType: AVMediaTypeVideo] || - [dev hasMediaType: AVMediaTypeMuxed]) { - obs_property_list_add_string(dev_list, - dev.localizedName.UTF8String, - dev.uniqueID.UTF8String); + for (AVCaptureDevice *dev in [AVCaptureDevice devices]) { + if ([dev hasMediaType:AVMediaTypeVideo] || + [dev hasMediaType:AVMediaTypeMuxed]) { + obs_property_list_add_string( + dev_list, dev.localizedName.UTF8String, + dev.uniqueID.UTF8String); } } - obs_property_set_modified_callback(dev_list, - properties_device_changed); + obs_property_set_modified_callback(dev_list, properties_device_changed); - obs_property_t *use_preset = obs_properties_add_bool(props, - "use_preset", TEXT_USE_PRESET); + obs_property_t *use_preset = + obs_properties_add_bool(props, "use_preset", TEXT_USE_PRESET); obs_property_set_modified_callback(use_preset, - properties_use_preset_changed); + properties_use_preset_changed); add_preset_properties(props); add_manual_properties(props); obs_properties_add_bool(props, "buffering", - obs_module_text("Buffering")); + obs_module_text("Buffering")); return props; } static void switch_device(av_capture *capture, NSString *uid, - obs_data_t *settings) + obs_data_t *settings) { if (!uid) return; @@ -2124,7 +2112,7 @@ static void switch_device(av_capture *capture, NSString *uid, AVCaptureDevice *dev = [AVCaptureDevice deviceWithUniqueID:uid]; if (!dev) { AVLOG(LOG_WARNING, "Device with unique id '%s' not found", - uid.UTF8String); + uid.UTF8String); return; } @@ -2138,7 +2126,7 @@ static void update_preset(av_capture *capture, obs_data_t *settings) NSString *preset = get_string(settings, "preset"); if (![capture->device supportsAVCaptureSessionPreset:preset]) { AVLOG(LOG_WARNING, "Preset %s not available", - preset.UTF8String); + preset.UTF8String); preset = select_preset(capture->device, preset); } @@ -2156,7 +2144,7 @@ static void update_manual(av_capture *capture, obs_data_t *settings) static void av_capture_update(void *data, obs_data_t *settings) { - auto capture = static_cast(data); + auto capture = static_cast(data); NSString *uid = get_string(settings, "device"); @@ -2170,7 +2158,7 @@ static void av_capture_update(void *data, obs_data_t *settings) } av_capture_enable_buffering(capture, - obs_data_get_bool(settings, "buffering")); + obs_data_get_bool(settings, "buffering")); } OBS_DECLARE_MODULE() @@ -2187,26 +2175,25 @@ bool obs_module_load(void) // From WWDC video 2014 #508 at 5:34 // https://developer.apple.com/videos/wwdc/2014/#508 CMIOObjectPropertyAddress prop = { - kCMIOHardwarePropertyAllowScreenCaptureDevices, - kCMIOObjectPropertyScopeGlobal, - kCMIOObjectPropertyElementMaster - }; + kCMIOHardwarePropertyAllowScreenCaptureDevices, + kCMIOObjectPropertyScopeGlobal, + kCMIOObjectPropertyElementMaster}; UInt32 allow = 1; CMIOObjectSetPropertyData(kCMIOObjectSystemObject, &prop, 0, NULL, - sizeof(allow), &allow); + sizeof(allow), &allow); #endif obs_source_info av_capture_info = { - .id = "av_capture_input", - .type = OBS_SOURCE_TYPE_INPUT, - .output_flags = OBS_SOURCE_ASYNC_VIDEO | - OBS_SOURCE_DO_NOT_DUPLICATE, - .get_name = av_capture_getname, - .create = av_capture_create, - .destroy = av_capture_destroy, - .get_defaults = av_capture_defaults, + .id = "av_capture_input", + .type = OBS_SOURCE_TYPE_INPUT, + .output_flags = OBS_SOURCE_ASYNC_VIDEO | + OBS_SOURCE_DO_NOT_DUPLICATE, + .get_name = av_capture_getname, + .create = av_capture_create, + .destroy = av_capture_destroy, + .get_defaults = av_capture_defaults, .get_properties = av_capture_properties, - .update = av_capture_update, + .update = av_capture_update, }; obs_register_source(&av_capture_info); diff --git a/plugins/mac-capture/mac-display-capture.m b/plugins/mac-capture/mac-display-capture.m index 67fd56ea5..392a7a74c 100644 --- a/plugins/mac-capture/mac-display-capture.m +++ b/plugins/mac-capture/mac-display-capture.m @@ -120,16 +120,15 @@ static inline void update_window_params(struct display_capture *dc) if (!requires_window(dc->crop)) return; - NSArray *arr = (NSArray*)CGWindowListCopyWindowInfo( - kCGWindowListOptionIncludingWindow, - dc->window.window_id); - + NSArray *arr = (NSArray *)CGWindowListCopyWindowInfo( + kCGWindowListOptionIncludingWindow, dc->window.window_id); + if (arr.count) { NSDictionary *dict = arr[0]; - NSDictionary *ref = dict[(NSString*)kCGWindowBounds]; + NSDictionary *ref = dict[(NSString *)kCGWindowBounds]; CGRectMakeWithDictionaryRepresentation((CFDictionaryRef)ref, - &dc->window_rect); - dc->on_screen = dict[(NSString*)kCGWindowIsOnscreen] != nil; + &dc->window_rect); + dc->on_screen = dict[(NSString *)kCGWindowIsOnscreen] != nil; dc->window_rect = [dc->screen convertRectToBacking:dc->window_rect]; @@ -144,8 +143,10 @@ static inline void update_window_params(struct display_capture *dc) } static inline void display_stream_update(struct display_capture *dc, - CGDisplayStreamFrameStatus status, uint64_t display_time, - IOSurfaceRef frame_surface, CGDisplayStreamUpdateRef update_ref) + CGDisplayStreamFrameStatus status, + uint64_t display_time, + IOSurfaceRef frame_surface, + CGDisplayStreamUpdateRef update_ref) { UNUSED_PARAMETER(display_time); UNUSED_PARAMETER(update_ref); @@ -176,8 +177,7 @@ static inline void display_stream_update(struct display_capture *dc, size_t dropped_frames = CGDisplayStreamUpdateGetDropCount(update_ref); if (dropped_frames > 0) blog(LOG_INFO, "%s: Dropped %zu frames", - obs_source_get_name(dc->source), - dropped_frames); + obs_source_get_name(dc->source), dropped_frames); } static bool init_display_stream(struct display_capture *dc) @@ -192,38 +192,34 @@ static bool init_display_stream(struct display_capture *dc) NSNumber *screen_num = dc->screen.deviceDescription[@"NSScreenNumber"]; CGDirectDisplayID disp_id = (CGDirectDisplayID)screen_num.pointerValue; - NSDictionary *rect_dict = CFBridgingRelease( - CGRectCreateDictionaryRepresentation( - CGRectMake(0, 0, - dc->screen.frame.size.width, - dc->screen.frame.size.height))); + NSDictionary *rect_dict = + CFBridgingRelease(CGRectCreateDictionaryRepresentation( + CGRectMake(0, 0, dc->screen.frame.size.width, + dc->screen.frame.size.height))); - CFBooleanRef show_cursor_cf = - dc->hide_cursor ? kCFBooleanFalse : kCFBooleanTrue; + CFBooleanRef show_cursor_cf = dc->hide_cursor ? kCFBooleanFalse + : kCFBooleanTrue; NSDictionary *dict = @{ - (__bridge NSString*)kCGDisplayStreamSourceRect: rect_dict, - (__bridge NSString*)kCGDisplayStreamQueueDepth: @5, - (__bridge NSString*)kCGDisplayStreamShowCursor: - (id)show_cursor_cf, + (__bridge NSString *)kCGDisplayStreamSourceRect: rect_dict, + (__bridge NSString *)kCGDisplayStreamQueueDepth: @5, + (__bridge NSString *) + kCGDisplayStreamShowCursor: (id)show_cursor_cf, }; os_event_init(&dc->disp_finished, OS_EVENT_TYPE_MANUAL); const CGSize *size = &dc->frame.size; - dc->disp = CGDisplayStreamCreateWithDispatchQueue(disp_id, - size->width, size->height, 'BGRA', - (__bridge CFDictionaryRef)dict, - dispatch_queue_create(NULL, NULL), - ^(CGDisplayStreamFrameStatus status, - uint64_t displayTime, - IOSurfaceRef frameSurface, - CGDisplayStreamUpdateRef updateRef) - { - display_stream_update(dc, status, displayTime, - frameSurface, updateRef); - } - ); + dc->disp = CGDisplayStreamCreateWithDispatchQueue( + disp_id, size->width, size->height, 'BGRA', + (__bridge CFDictionaryRef)dict, + dispatch_queue_create(NULL, NULL), + ^(CGDisplayStreamFrameStatus status, uint64_t displayTime, + IOSurfaceRef frameSurface, + CGDisplayStreamUpdateRef updateRef) { + display_stream_update(dc, status, displayTime, + frameSurface, updateRef); + }); return !CGDisplayStreamStart(dc->disp); } @@ -252,8 +248,7 @@ bool init_vertbuf(struct display_capture *dc) void load_crop(struct display_capture *dc, obs_data_t *settings); -static void *display_capture_create(obs_data_t *settings, - obs_source_t *source) +static void *display_capture_create(obs_data_t *settings, obs_source_t *source) { UNUSED_PARAMETER(source); UNUSED_PARAMETER(settings); @@ -303,25 +298,24 @@ fail: } static void build_sprite(struct gs_vb_data *data, float fcx, float fcy, - float start_u, float end_u, float start_v, float end_v) + float start_u, float end_u, float start_v, float end_v) { struct vec2 *tvarray = data->tvarray[0].array; - vec3_set(data->points+1, fcx, 0.0f, 0.0f); - vec3_set(data->points+2, 0.0f, fcy, 0.0f); - vec3_set(data->points+3, fcx, fcy, 0.0f); - vec2_set(tvarray, start_u, start_v); - vec2_set(tvarray+1, end_u, start_v); - vec2_set(tvarray+2, start_u, end_v); - vec2_set(tvarray+3, end_u, end_v); + vec3_set(data->points + 1, fcx, 0.0f, 0.0f); + vec3_set(data->points + 2, 0.0f, fcy, 0.0f); + vec3_set(data->points + 3, fcx, fcy, 0.0f); + vec2_set(tvarray, start_u, start_v); + vec2_set(tvarray + 1, end_u, start_v); + vec2_set(tvarray + 2, start_u, end_v); + vec2_set(tvarray + 3, end_u, end_v); } -static inline void build_sprite_rect(struct gs_vb_data *data, - float origin_x, float origin_y, float end_x, float end_y) +static inline void build_sprite_rect(struct gs_vb_data *data, float origin_x, + float origin_y, float end_x, float end_y) { build_sprite(data, fabs(end_x - origin_x), fabs(end_y - origin_y), - origin_x, end_x, - origin_y, end_y); + origin_x, end_x, origin_y, end_y); } static void display_capture_video_tick(void *data, float seconds) @@ -348,8 +342,8 @@ static void display_capture_video_tick(void *data, float seconds) if (requires_window(dc->crop) && !dc->on_screen) goto cleanup; - CGPoint origin = { 0.f }; - CGPoint end = { 0.f }; + CGPoint origin = {0.f}; + CGPoint end = {0.f}; switch (dc->crop) { float x, y; @@ -379,10 +373,9 @@ static void display_capture_video_tick(void *data, float seconds) break; } - obs_enter_graphics(); - build_sprite_rect(gs_vertexbuffer_get_data(dc->vertbuf), - origin.x, origin.y, end.x, end.y); + build_sprite_rect(gs_vertexbuffer_get_data(dc->vertbuf), origin.x, + origin.y, end.x, end.y); if (dc->tex) gs_texture_rebind_iosurface(dc->tex, dc->prev); @@ -412,7 +405,7 @@ static void display_capture_video_render(void *data, gs_effect_t *effect) gs_load_samplerstate(dc->sampler, 0); gs_technique_t *tech = gs_effect_get_technique(dc->effect, "Draw"); gs_effect_set_texture(gs_effect_get_param_by_name(dc->effect, "image"), - dc->tex); + dc->tex); gs_technique_begin(tech); gs_technique_begin_pass(tech, 0); @@ -428,9 +421,9 @@ static const char *display_capture_getname(void *unused) return obs_module_text("DisplayCapture"); } -#define CROPPED_LENGTH(rect, origin_, length) \ - fabs((rect ## .size. ## length - dc->crop_rect.size. ## length) - \ - (rect ## .origin. ## origin_ + dc->crop_rect.origin. ## origin_)) +#define CROPPED_LENGTH(rect, origin_, length) \ + fabs((rect##.size.##length - dc->crop_rect.size.##length) - \ + (rect##.origin.##origin_ + dc->crop_rect.origin.##origin_)) static uint32_t display_capture_getwidth(void *data) { @@ -502,20 +495,20 @@ void load_crop(struct display_capture *dc, obs_data_t *settings) #define CROP_VAR_NAME(var, mode) (mode "." #var) #define LOAD_CROP_VAR(var, mode) \ - dc->crop_rect.var = obs_data_get_double(settings, \ - CROP_VAR_NAME(var, mode)); + dc->crop_rect.var = \ + obs_data_get_double(settings, CROP_VAR_NAME(var, mode)); switch (dc->crop) { case CROP_MANUAL: - LOAD_CROP_VAR(origin.x, "manual"); - LOAD_CROP_VAR(origin.y, "manual"); - LOAD_CROP_VAR(size.width, "manual"); + LOAD_CROP_VAR(origin.x, "manual"); + LOAD_CROP_VAR(origin.y, "manual"); + LOAD_CROP_VAR(size.width, "manual"); LOAD_CROP_VAR(size.height, "manual"); break; case CROP_TO_WINDOW_AND_MANUAL: - LOAD_CROP_VAR(origin.x, "window"); - LOAD_CROP_VAR(origin.y, "window"); - LOAD_CROP_VAR(size.width, "window"); + LOAD_CROP_VAR(origin.x, "window"); + LOAD_CROP_VAR(origin.y, "window"); + LOAD_CROP_VAR(size.width, "window"); LOAD_CROP_VAR(size.height, "window"); break; @@ -552,7 +545,7 @@ static void display_capture_update(void *data, obs_data_t *settings) } static bool switch_crop_mode(obs_properties_t *props, obs_property_t *p, - obs_data_t *settings) + obs_data_t *settings) { UNUSED_PARAMETER(p); @@ -561,20 +554,20 @@ static bool switch_crop_mode(obs_properties_t *props, obs_property_t *p, const char *name; bool visible; -#define LOAD_CROP_VAR(var, mode) \ +#define LOAD_CROP_VAR(var, mode) \ name = CROP_VAR_NAME(var, mode); \ obs_property_set_visible(obs_properties_get(props, name), visible); visible = crop == CROP_MANUAL; - LOAD_CROP_VAR(origin.x, "manual"); - LOAD_CROP_VAR(origin.y, "manual"); - LOAD_CROP_VAR(size.width, "manual"); + LOAD_CROP_VAR(origin.x, "manual"); + LOAD_CROP_VAR(origin.y, "manual"); + LOAD_CROP_VAR(size.width, "manual"); LOAD_CROP_VAR(size.height, "manual"); visible = crop == CROP_TO_WINDOW_AND_MANUAL; - LOAD_CROP_VAR(origin.x, "window"); - LOAD_CROP_VAR(origin.y, "window"); - LOAD_CROP_VAR(size.width, "window"); + LOAD_CROP_VAR(origin.x, "window"); + LOAD_CROP_VAR(origin.y, "window"); + LOAD_CROP_VAR(size.width, "window"); LOAD_CROP_VAR(size.height, "window"); #undef LOAD_CROP_VAR @@ -582,15 +575,12 @@ static bool switch_crop_mode(obs_properties_t *props, obs_property_t *p, return true; } -static const char *crop_names[] = { - "CropMode.None", - "CropMode.Manual", - "CropMode.ToWindow", - "CropMode.ToWindowAndManual" -}; +static const char *crop_names[] = {"CropMode.None", "CropMode.Manual", + "CropMode.ToWindow", + "CropMode.ToWindowAndManual"}; #ifndef COUNTOF -#define COUNTOF(x) (sizeof(x)/sizeof(x[0])) +#define COUNTOF(x) (sizeof(x) / sizeof(x[0])) #endif static obs_properties_t *display_capture_properties(void *unused) { @@ -598,9 +588,9 @@ static obs_properties_t *display_capture_properties(void *unused) obs_properties_t *props = obs_properties_create(); - obs_property_t *list = obs_properties_add_list(props, - "display", obs_module_text("DisplayCapture.Display"), - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); + obs_property_t *list = obs_properties_add_list( + props, "display", obs_module_text("DisplayCapture.Display"), + OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); for (unsigned i = 0; i < [NSScreen screens].count; i++) { char buf[10]; @@ -609,11 +599,11 @@ static obs_properties_t *display_capture_properties(void *unused) } obs_properties_add_bool(props, "show_cursor", - obs_module_text("DisplayCapture.ShowCursor")); + obs_module_text("DisplayCapture.ShowCursor")); - obs_property_t *crop = obs_properties_add_list(props, "crop_mode", - obs_module_text("CropMode"), - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); + obs_property_t *crop = obs_properties_add_list( + props, "crop_mode", obs_module_text("CropMode"), + OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); obs_property_set_modified_callback(crop, switch_crop_mode); for (unsigned i = 0; i < COUNTOF(crop_names); i++) { @@ -627,22 +617,22 @@ static obs_properties_t *display_capture_properties(void *unused) obs_property_t *p; const char *name; float min; -#define LOAD_CROP_VAR(var, mode) \ - name = CROP_VAR_NAME(var, mode); \ - p = obs_properties_add_float(props, name, \ - obs_module_text("Crop."#var), min, 4096.f, .5f); \ +#define LOAD_CROP_VAR(var, mode) \ + name = CROP_VAR_NAME(var, mode); \ + p = obs_properties_add_float( \ + props, name, obs_module_text("Crop." #var), min, 4096.f, .5f); \ obs_property_set_visible(p, false); min = 0.f; - LOAD_CROP_VAR(origin.x, "manual"); - LOAD_CROP_VAR(origin.y, "manual"); - LOAD_CROP_VAR(size.width, "manual"); + LOAD_CROP_VAR(origin.x, "manual"); + LOAD_CROP_VAR(origin.y, "manual"); + LOAD_CROP_VAR(size.width, "manual"); LOAD_CROP_VAR(size.height, "manual"); min = -4096.f; - LOAD_CROP_VAR(origin.x, "window"); - LOAD_CROP_VAR(origin.y, "window"); - LOAD_CROP_VAR(size.width, "window"); + LOAD_CROP_VAR(origin.x, "window"); + LOAD_CROP_VAR(origin.y, "window"); + LOAD_CROP_VAR(size.width, "window"); LOAD_CROP_VAR(size.height, "window"); #undef LOAD_CROP_VAR @@ -650,22 +640,22 @@ static obs_properties_t *display_capture_properties(void *unused) } struct obs_source_info display_capture_info = { - .id = "display_capture", - .type = OBS_SOURCE_TYPE_INPUT, - .get_name = display_capture_getname, + .id = "display_capture", + .type = OBS_SOURCE_TYPE_INPUT, + .get_name = display_capture_getname, - .create = display_capture_create, - .destroy = display_capture_destroy, + .create = display_capture_create, + .destroy = display_capture_destroy, - .output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CUSTOM_DRAW | - OBS_SOURCE_DO_NOT_DUPLICATE, - .video_tick = display_capture_video_tick, - .video_render = display_capture_video_render, + .output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CUSTOM_DRAW | + OBS_SOURCE_DO_NOT_DUPLICATE, + .video_tick = display_capture_video_tick, + .video_render = display_capture_video_render, - .get_width = display_capture_getwidth, - .get_height = display_capture_getheight, + .get_width = display_capture_getwidth, + .get_height = display_capture_getheight, - .get_defaults = display_capture_defaults, + .get_defaults = display_capture_defaults, .get_properties = display_capture_properties, - .update = display_capture_update, + .update = display_capture_update, }; diff --git a/plugins/mac-capture/mac-window-capture.m b/plugins/mac-capture/mac-window-capture.m index 48f2da7ad..110ff4d83 100644 --- a/plugins/mac-capture/mac-window-capture.m +++ b/plugins/mac-capture/mac-window-capture.m @@ -21,61 +21,59 @@ struct window_capture { DARRAY(uint8_t) buffer; - pthread_t capture_thread; + pthread_t capture_thread; os_event_t *capture_event; os_event_t *stop_event; }; static CGImageRef get_image(struct window_capture *wc) { - NSArray *arr = (NSArray*)CGWindowListCreate( - kCGWindowListOptionIncludingWindow, - wc->window.window_id); + NSArray *arr = (NSArray *)CGWindowListCreate( + kCGWindowListOptionIncludingWindow, wc->window.window_id); [arr autorelease]; if (arr.count) - return CGWindowListCreateImage(CGRectNull, - kCGWindowListOptionIncludingWindow, - wc->window.window_id, wc->image_option); + return CGWindowListCreateImage( + CGRectNull, kCGWindowListOptionIncludingWindow, + wc->window.window_id, wc->image_option); if (!find_window(&wc->window, NULL, false)) return NULL; return CGWindowListCreateImage(CGRectNull, - kCGWindowListOptionIncludingWindow, - wc->window.window_id, wc->image_option); + kCGWindowListOptionIncludingWindow, + wc->window.window_id, wc->image_option); } static inline void capture_frame(struct window_capture *wc) { - uint64_t ts = os_gettime_ns(); + uint64_t ts = os_gettime_ns(); CGImageRef img = get_image(wc); if (!img) return; - size_t width = CGImageGetWidth(img); + size_t width = CGImageGetWidth(img); size_t height = CGImageGetHeight(img); CGRect rect = {{0, 0}, {width, height}}; da_reserve(wc->buffer, width * height * 4); uint8_t *data = wc->buffer.array; - CGContextRef cg_context = CGBitmapContextCreate(data, width, height, - 8, width * 4, wc->color_space, - kCGBitmapByteOrder32Host | - kCGImageAlphaPremultipliedFirst); + CGContextRef cg_context = CGBitmapContextCreate( + data, width, height, 8, width * 4, wc->color_space, + kCGBitmapByteOrder32Host | kCGImageAlphaPremultipliedFirst); CGContextSetBlendMode(cg_context, kCGBlendModeCopy); CGContextDrawImage(cg_context, rect, img); CGContextRelease(cg_context); CGImageRelease(img); struct obs_source_frame frame = { - .format = VIDEO_FORMAT_BGRA, - .width = width, - .height = height, - .data[0] = data, + .format = VIDEO_FORMAT_BGRA, + .width = width, + .height = height, + .data[0] = data, .linesize[0] = width * 4, - .timestamp = ts, + .timestamp = ts, }; obs_source_output_video(wc->source, &frame); @@ -99,7 +97,7 @@ static void *capture_thread(void *data) } static inline void *window_capture_create_internal(obs_data_t *settings, - obs_source_t *source) + obs_source_t *source) { struct window_capture *wc = bzalloc(sizeof(struct window_capture)); @@ -111,8 +109,9 @@ static inline void *window_capture_create_internal(obs_data_t *settings, init_window(&wc->window, settings); - wc->image_option = obs_data_get_bool(settings, "show_shadow") ? - kCGWindowImageDefault : kCGWindowImageBoundsIgnoreFraming; + wc->image_option = obs_data_get_bool(settings, "show_shadow") + ? kCGWindowImageDefault + : kCGWindowImageBoundsIgnoreFraming; os_event_init(&wc->capture_event, OS_EVENT_TYPE_AUTO); os_event_init(&wc->stop_event, OS_EVENT_TYPE_MANUAL); @@ -135,7 +134,7 @@ static void window_capture_destroy(void *data) os_event_signal(cap->stop_event); os_event_signal(cap->capture_event); - + pthread_join(cap->capture_thread, NULL); CGColorSpaceRelease(cap->color_space); @@ -165,26 +164,28 @@ static obs_properties_t *window_capture_properties(void *unused) add_window_properties(props); obs_properties_add_bool(props, "show_shadow", - obs_module_text("WindowCapture.ShowShadow")); + obs_module_text("WindowCapture.ShowShadow")); return props; } static inline void window_capture_update_internal(struct window_capture *wc, - obs_data_t *settings) + obs_data_t *settings) { - wc->image_option = obs_data_get_bool(settings, "show_shadow") ? - kCGWindowImageDefault : kCGWindowImageBoundsIgnoreFraming; + wc->image_option = obs_data_get_bool(settings, "show_shadow") + ? kCGWindowImageDefault + : kCGWindowImageBoundsIgnoreFraming; update_window(&wc->window, settings); if (wc->window.window_name.length) { - blog(LOG_INFO, "[window-capture: '%s'] update settings:\n" - "\twindow: %s\n" - "\towner: %s", - obs_source_get_name(wc->source), - [wc->window.window_name UTF8String], - [wc->window.owner_name UTF8String]); + blog(LOG_INFO, + "[window-capture: '%s'] update settings:\n" + "\twindow: %s\n" + "\towner: %s", + obs_source_get_name(wc->source), + [wc->window.window_name UTF8String], + [wc->window.owner_name UTF8String]); } } @@ -202,7 +203,7 @@ static const char *window_capture_getname(void *unused) } static inline void window_capture_tick_internal(struct window_capture *wc, - float seconds) + float seconds) { UNUSED_PARAMETER(seconds); os_event_signal(wc->capture_event); @@ -221,17 +222,17 @@ static void window_capture_tick(void *data, float seconds) } struct obs_source_info window_capture_info = { - .id = "window_capture", - .type = OBS_SOURCE_TYPE_INPUT, - .get_name = window_capture_getname, + .id = "window_capture", + .type = OBS_SOURCE_TYPE_INPUT, + .get_name = window_capture_getname, - .create = window_capture_create, - .destroy = window_capture_destroy, + .create = window_capture_create, + .destroy = window_capture_destroy, - .output_flags = OBS_SOURCE_ASYNC_VIDEO, - .video_tick = window_capture_tick, + .output_flags = OBS_SOURCE_ASYNC_VIDEO, + .video_tick = window_capture_tick, - .get_defaults = window_capture_defaults, + .get_defaults = window_capture_defaults, .get_properties = window_capture_properties, - .update = window_capture_update, + .update = window_capture_update, }; diff --git a/plugins/mac-capture/window-utils.h b/plugins/mac-capture/window-utils.h index bdc3ed26a..da0743acb 100644 --- a/plugins/mac-capture/window-utils.h +++ b/plugins/mac-capture/window-utils.h @@ -5,11 +5,11 @@ #include struct cocoa_window { - CGWindowID window_id; + CGWindowID window_id; pthread_mutex_t name_lock; - NSString *owner_name; - NSString *window_name; + NSString *owner_name; + NSString *window_name; uint64_t next_search_time; }; diff --git a/plugins/mac-capture/window-utils.m b/plugins/mac-capture/window-utils.m index d2a19781d..0380df656 100644 --- a/plugins/mac-capture/window-utils.m +++ b/plugins/mac-capture/window-utils.m @@ -2,13 +2,12 @@ #include -#define WINDOW_NAME ((NSString*)kCGWindowName) -#define WINDOW_NUMBER ((NSString*)kCGWindowNumber) -#define OWNER_NAME ((NSString*)kCGWindowOwnerName) -#define OWNER_PID ((NSNumber*)kCGWindowOwnerPID) +#define WINDOW_NAME ((NSString *)kCGWindowName) +#define WINDOW_NUMBER ((NSString *)kCGWindowNumber) +#define OWNER_NAME ((NSString *)kCGWindowOwnerName) +#define OWNER_PID ((NSNumber *)kCGWindowOwnerPID) -static NSComparator win_info_cmp = ^(NSDictionary *o1, NSDictionary *o2) -{ +static NSComparator win_info_cmp = ^(NSDictionary *o1, NSDictionary *o2) { NSComparisonResult res = [o1[OWNER_NAME] compare:o2[OWNER_NAME]]; if (res != NSOrderedSame) return res; @@ -26,9 +25,8 @@ static NSComparator win_info_cmp = ^(NSDictionary *o1, NSDictionary *o2) NSArray *enumerate_windows(void) { - NSArray *arr = (NSArray*)CGWindowListCopyWindowInfo( - kCGWindowListOptionOnScreenOnly, - kCGNullWindowID); + NSArray *arr = (NSArray *)CGWindowListCopyWindowInfo( + kCGWindowListOptionOnScreenOnly, kCGNullWindowID); [arr autorelease]; @@ -60,8 +58,8 @@ bool find_window(cocoa_window_t cw, obs_data_t *settings, bool force) pthread_mutex_unlock(&cw->name_lock); - NSNumber *window_id = (NSNumber*)dict[WINDOW_NUMBER]; - cw->window_id = window_id.intValue; + NSNumber *window_id = (NSNumber *)dict[WINDOW_NUMBER]; + cw->window_id = window_id.intValue; obs_data_set_int(settings, "window", cw->window_id); return true; @@ -76,9 +74,9 @@ void init_window(cocoa_window_t cw, obs_data_t *settings) { pthread_mutex_init(&cw->name_lock, NULL); - cw->owner_name = @(obs_data_get_string(settings, "owner_name")); + cw->owner_name = @(obs_data_get_string(settings, "owner_name")); cw->window_name = @(obs_data_get_string(settings, "window_name")); - [cw->owner_name retain]; + [cw->owner_name retain]; [cw->window_name retain]; find_window(cw, settings, true); } @@ -86,22 +84,22 @@ void init_window(cocoa_window_t cw, obs_data_t *settings) void destroy_window(cocoa_window_t cw) { pthread_mutex_destroy(&cw->name_lock); - [cw->owner_name release]; + [cw->owner_name release]; [cw->window_name release]; } void update_window(cocoa_window_t cw, obs_data_t *settings) { pthread_mutex_lock(&cw->name_lock); - [cw->owner_name release]; + [cw->owner_name release]; [cw->window_name release]; - cw->owner_name = @(obs_data_get_string(settings, "owner_name")); - cw->window_name = @(obs_data_get_string(settings, "window_name")); - [cw->owner_name retain]; + cw->owner_name = @(obs_data_get_string(settings, "owner_name")); + cw->window_name = @(obs_data_get_string(settings, "window_name")); + [cw->owner_name retain]; [cw->window_name retain]; pthread_mutex_unlock(&cw->name_lock); - cw->window_id = obs_data_get_int(settings, "window"); + cw->window_id = obs_data_get_int(settings, "window"); } static inline const char *make_name(NSString *owner, NSString *name) @@ -116,7 +114,7 @@ static inline const char *make_name(NSString *owner, NSString *name) static inline NSDictionary *find_window_dict(NSArray *arr, int window_id) { for (NSDictionary *dict in arr) { - NSNumber *wid = (NSNumber*)dict[WINDOW_NUMBER]; + NSNumber *wid = (NSNumber *)dict[WINDOW_NUMBER]; if (wid.intValue == window_id) return dict; } @@ -125,12 +123,11 @@ static inline NSDictionary *find_window_dict(NSArray *arr, int window_id) } static inline bool window_changed_internal(obs_property_t *p, - obs_data_t *settings) + obs_data_t *settings) { - int window_id = obs_data_get_int(settings, "window"); + int window_id = obs_data_get_int(settings, "window"); NSString *window_owner = @(obs_data_get_string(settings, "owner_name")); - NSString *window_name = - @(obs_data_get_string(settings, "window_name")); + NSString *window_name = @(obs_data_get_string(settings, "window_name")); NSDictionary *win_info = @{ OWNER_NAME: window_owner, @@ -147,39 +144,38 @@ static inline bool window_changed_internal(obs_property_t *p, obs_property_list_clear(p); for (NSDictionary *dict in arr) { - NSString *owner = (NSString*)dict[OWNER_NAME]; - NSString *name = (NSString*)dict[WINDOW_NAME]; - NSNumber *wid = (NSNumber*)dict[WINDOW_NUMBER]; + NSString *owner = (NSString *)dict[OWNER_NAME]; + NSString *name = (NSString *)dict[WINDOW_NAME]; + NSNumber *wid = (NSNumber *)dict[WINDOW_NUMBER]; if (!window_added && - win_info_cmp(win_info, dict) == NSOrderedAscending) { + win_info_cmp(win_info, dict) == NSOrderedAscending) { window_added = true; - size_t idx = obs_property_list_add_int(p, - make_name(window_owner, window_name), - window_id); + size_t idx = obs_property_list_add_int( + p, make_name(window_owner, window_name), + window_id); obs_property_list_item_disable(p, idx, true); } if (!show_empty_names && !name.length && - window_id != wid.intValue) + window_id != wid.intValue) continue; obs_property_list_add_int(p, make_name(owner, name), - wid.intValue); + wid.intValue); } if (!window_added) { - size_t idx = obs_property_list_add_int(p, - make_name(window_owner, window_name), - window_id); + size_t idx = obs_property_list_add_int( + p, make_name(window_owner, window_name), window_id); obs_property_list_item_disable(p, idx, true); } if (!window_found) return true; - NSString *owner = (NSString*)cur[OWNER_NAME]; - NSString *window = (NSString*)cur[WINDOW_NAME]; + NSString *owner = (NSString *)cur[OWNER_NAME]; + NSString *window = (NSString *)cur[WINDOW_NAME]; obs_data_set_string(settings, "owner_name", owner.UTF8String); obs_data_set_string(settings, "window_name", window.UTF8String); @@ -188,7 +184,7 @@ static inline bool window_changed_internal(obs_property_t *p, } static bool window_changed(obs_properties_t *props, obs_property_t *p, - obs_data_t *settings) + obs_data_t *settings) { UNUSED_PARAMETER(props); @@ -198,12 +194,12 @@ static bool window_changed(obs_properties_t *props, obs_property_t *p, } static bool toggle_empty_names(obs_properties_t *props, obs_property_t *p, - obs_data_t *settings) + obs_data_t *settings) { UNUSED_PARAMETER(p); return window_changed(props, obs_properties_get(props, "window"), - settings); + settings); } void window_defaults(obs_data_t *settings) @@ -214,20 +210,20 @@ void window_defaults(obs_data_t *settings) void add_window_properties(obs_properties_t *props) { - obs_property_t *window_list = obs_properties_add_list(props, - "window", obs_module_text("WindowUtils.Window"), - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); + obs_property_t *window_list = obs_properties_add_list( + props, "window", obs_module_text("WindowUtils.Window"), + OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); obs_property_set_modified_callback(window_list, window_changed); - obs_property_t *empty = obs_properties_add_bool(props, - "show_empty_names", - obs_module_text("WindowUtils.ShowEmptyNames")); + obs_property_t *empty = obs_properties_add_bool( + props, "show_empty_names", + obs_module_text("WindowUtils.ShowEmptyNames")); obs_property_set_modified_callback(empty, toggle_empty_names); } void show_window_properties(obs_properties_t *props, bool show) { obs_property_set_visible(obs_properties_get(props, "window"), show); - obs_property_set_visible( - obs_properties_get(props, "show_empty_names"), show); + obs_property_set_visible(obs_properties_get(props, "show_empty_names"), + show); } diff --git a/plugins/mac-syphon/syphon.m b/plugins/mac-syphon/syphon.m index 6f53264cd..0dfe60e9a 100644 --- a/plugins/mac-syphon/syphon.m +++ b/plugins/mac-syphon/syphon.m @@ -3,40 +3,41 @@ #import "syphon-framework/Syphon.h" #include -#define LOG(level, message, ...) \ - blog(level, "%s: " message, obs_source_get_name(s->source), ##__VA_ARGS__) +#define LOG(level, message, ...) \ + blog(level, "%s: " message, obs_source_get_name(s->source), \ + ##__VA_ARGS__) struct syphon { SYPHON_CLIENT_UNIQUE_CLASS_NAME *client; IOSurfaceRef ref; gs_samplerstate_t *sampler; - gs_effect_t *effect; - gs_vertbuffer_t *vertbuffer; - gs_texture_t *tex; - uint32_t width, height; - bool crop; - CGRect crop_rect; - bool allow_transparency; + gs_effect_t *effect; + gs_vertbuffer_t *vertbuffer; + gs_texture_t *tex; + uint32_t width, height; + bool crop; + CGRect crop_rect; + bool allow_transparency; obs_source_t *source; bool active; bool uuid_changed; - id new_server_listener; - id retire_listener; + id new_server_listener; + id retire_listener; NSString *app_name; NSString *name; NSString *uuid; obs_data_t *inject_info; - NSString *inject_app; - NSString *inject_uuid; - bool inject_active; - id launch_listener; - bool inject_server_found; - float inject_wait_time; + NSString *inject_app; + NSString *inject_uuid; + bool inject_active; + id launch_listener; + bool inject_server_found; + float inject_wait_time; }; typedef struct syphon *syphon_t; @@ -55,9 +56,9 @@ static inline void find_and_inject_target(syphon_t s, NSArray *arr, bool retry); @interface OBSSyphonKVObserver : NSObject - (void)observeValueForKeyPath:(NSString *)keyPath - ofObject:(id)object - change:(NSDictionary *)change - context:(void *)context; + ofObject:(id)object + change:(NSDictionary *)change + context:(void *)context; @end static inline void handle_application_launch(syphon_t s, NSArray *new) @@ -73,9 +74,9 @@ static inline void handle_application_launch(syphon_t s, NSArray *new) @implementation OBSSyphonKVObserver - (void)observeValueForKeyPath:(NSString *)keyPath - ofObject:(id)object - change:(NSDictionary *)change - context:(void *)context + ofObject:(id)object + change:(NSDictionary *)change + context:(void *)context { UNUSED_PARAMETER(keyPath); UNUSED_PARAMETER(object); @@ -117,7 +118,7 @@ static void stop_client(syphon_t s) s->ref = NULL; } - s->width = 0; + s->width = 0; s->height = 0; obs_leave_graphics(); @@ -143,8 +144,10 @@ static inline void check_version(syphon_t s, NSDictionary *desc) "VersionKey"); if (version.unsignedIntValue > 0) - LOG(LOG_WARNING, "Got server description version %d, " - "expected 0", version.unsignedIntValue); + LOG(LOG_WARNING, + "Got server description version %d, " + "expected 0", + version.unsignedIntValue); } static inline void check_description(syphon_t s, NSDictionary *desc) @@ -169,9 +172,10 @@ static inline void check_description(syphon_t s, NSDictionary *desc) } NSString *surfaces_string = [NSString stringWithFormat:@"%@", surfaces]; - LOG(LOG_WARNING, "SyphonSurfaces does not contain" - "'SyphonSurfaceTypeIOSurface': %s", - surfaces_string.UTF8String); + LOG(LOG_WARNING, + "SyphonSurfaces does not contain" + "'SyphonSurfaceTypeIOSurface': %s", + surfaces_string.UTF8String); } static inline bool update_string(NSString **str, NSString *new) @@ -185,7 +189,7 @@ static inline bool update_string(NSString **str, NSString *new) } static inline void handle_new_frame(syphon_t s, - SYPHON_CLIENT_UNIQUE_CLASS_NAME *client) + SYPHON_CLIENT_UNIQUE_CLASS_NAME *client) { IOSurfaceRef ref = [client IOSurface]; @@ -206,9 +210,9 @@ static inline void handle_new_frame(syphon_t s, CFRelease(s->ref); } - s->ref = ref; - s->tex = gs_texture_create_from_iosurface(s->ref); - s->width = gs_texture_get_width(s->tex); + s->ref = ref; + s->tex = gs_texture_create_from_iosurface(s->ref); + s->width = gs_texture_get_width(s->tex); s->height = gs_texture_get_height(s->tex); obs_leave_graphics(); } @@ -230,7 +234,7 @@ static void create_client(syphon_t s) if (!desc) { desc = servers[0]; if (update_string(&s->uuid, - desc[SyphonServerDescriptionUUIDKey])) + desc[SyphonServerDescriptionUUIDKey])) s->uuid_changed = true; } @@ -241,11 +245,11 @@ static void create_client(syphon_t s) s->client = [[SYPHON_CLIENT_UNIQUE_CLASS_NAME alloc] initWithServerDescription:desc options:nil - newFrameHandler:^ - (SYPHON_CLIENT_UNIQUE_CLASS_NAME *client) - { - handle_new_frame(s, client); - }]; + newFrameHandler:^( + SYPHON_CLIENT_UNIQUE_CLASS_NAME + *client) { + handle_new_frame(s, client); + }]; } s->active = true; @@ -254,27 +258,27 @@ static void create_client(syphon_t s) static inline void release_settings(syphon_t s) { [s->app_name release]; - [s->name release]; - [s->uuid release]; + [s->name release]; + [s->uuid release]; } static inline bool load_syphon_settings(syphon_t s, obs_data_t *settings) { NSString *app_name = @(obs_data_get_string(settings, "app_name")); - NSString *name = @(obs_data_get_string(settings, "name")); - bool equal_names = [app_name isEqual:s->app_name] && - [name isEqual:s->name]; + NSString *name = @(obs_data_get_string(settings, "name")); + bool equal_names = [app_name isEqual:s->app_name] && + [name isEqual:s->name]; if (s->uuid_changed && equal_names) return false; - NSString *uuid = @(obs_data_get_string(settings, "uuid")); + NSString *uuid = @(obs_data_get_string(settings, "uuid")); if ([uuid isEqual:s->uuid] && equal_names) return false; release_settings(s); - s->app_name = [app_name retain]; - s->name = [name retain]; - s->uuid = [uuid retain]; + s->app_name = [app_name retain]; + s->name = [name retain]; + s->uuid = [uuid retain]; s->uuid_changed = false; return true; } @@ -288,15 +292,15 @@ static inline void update_from_announce(syphon_t s, NSDictionary *info) return; NSString *app_name = info[SyphonServerDescriptionAppNameKey]; - NSString *name = info[SyphonServerDescriptionNameKey]; - NSString *uuid = info[SyphonServerDescriptionUUIDKey]; + NSString *name = info[SyphonServerDescriptionNameKey]; + NSString *uuid = info[SyphonServerDescriptionUUIDKey]; if (![uuid isEqual:s->uuid] && - !([app_name isEqual:s->app_name] && [name isEqual:s->name])) + !([app_name isEqual:s->app_name] && [name isEqual:s->name])) return; update_string(&s->app_name, app_name); - update_string(&s->name, name); + update_string(&s->name, name); if (update_string(&s->uuid, uuid)) s->uuid_changed = true; @@ -304,27 +308,28 @@ static inline void update_from_announce(syphon_t s, NSDictionary *info) } static inline void update_inject_state(syphon_t s, NSDictionary *info, - bool announce) + bool announce) { if (!info) return; NSString *app_name = info[SyphonServerDescriptionAppNameKey]; - NSString *name = info[SyphonServerDescriptionNameKey]; - NSString *uuid = info[SyphonServerDescriptionUUIDKey]; + NSString *name = info[SyphonServerDescriptionNameKey]; + NSString *uuid = info[SyphonServerDescriptionUUIDKey]; if (![uuid isEqual:s->inject_uuid] && - (![app_name isEqual:s->inject_app] - || ![name isEqual:@"InjectedSyphon"])) + (![app_name isEqual:s->inject_app] || + ![name isEqual:@"InjectedSyphon"])) return; if (!(s->inject_server_found = announce)) { s->inject_wait_time = 0.f; objc_release(&s->inject_uuid); - LOG(LOG_INFO, "Injected server retired: " - "[%s] InjectedSyphon (%s)", - s->inject_app.UTF8String, uuid.UTF8String); + LOG(LOG_INFO, + "Injected server retired: " + "[%s] InjectedSyphon (%s)", + s->inject_app.UTF8String, uuid.UTF8String); return; } @@ -333,8 +338,7 @@ static inline void update_inject_state(syphon_t s, NSDictionary *info, s->inject_uuid = [uuid retain]; LOG(LOG_INFO, "Injected server found: [%s] %s (%s)", - app_name.UTF8String, name.UTF8String, - uuid.UTF8String); + app_name.UTF8String, name.UTF8String, uuid.UTF8String); } static inline void handle_announce(syphon_t s, NSNotification *note) @@ -406,15 +410,15 @@ fail_tvarray: static inline bool init_obs_graphics_objects(syphon_t s) { struct gs_sampler_info info = { - .filter = GS_FILTER_LINEAR, - .address_u = GS_ADDRESS_CLAMP, - .address_v = GS_ADDRESS_CLAMP, - .address_w = GS_ADDRESS_CLAMP, + .filter = GS_FILTER_LINEAR, + .address_u = GS_ADDRESS_CLAMP, + .address_v = GS_ADDRESS_CLAMP, + .address_w = GS_ADDRESS_CLAMP, .max_anisotropy = 1, }; obs_enter_graphics(); - s->sampler = gs_samplerstate_create(&info); + s->sampler = gs_samplerstate_create(&info); s->vertbuffer = create_vertbuffer(); obs_leave_graphics(); @@ -426,25 +430,21 @@ static inline bool init_obs_graphics_objects(syphon_t s) static inline bool create_syphon_listeners(syphon_t s) { NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; - s->new_server_listener = [nc + s->new_server_listener = [nc addObserverForName:SyphonServerAnnounceNotification object:nil queue:[NSOperationQueue mainQueue] - usingBlock:^(NSNotification *note) - { - handle_announce(s, note); - } - ]; + usingBlock:^(NSNotification *note) { + handle_announce(s, note); + }]; - s->retire_listener = [nc + s->retire_listener = [nc addObserverForName:SyphonServerRetireNotification object:nil queue:[NSOperationQueue mainQueue] - usingBlock:^(NSNotification *note) - { - handle_retire(s, note); - } - ]; + usingBlock:^(NSNotification *note) { + handle_retire(s, note); + }]; return s->new_server_listener != nil && s->retire_listener != nil; } @@ -456,9 +456,9 @@ static inline bool create_applications_observer(syphon_t s, NSWorkspace *ws) return false; [ws addObserver:s->launch_listener - forKeyPath:NSStringFromSelector(@selector(runningApplications)) - options:NSKeyValueObservingOptionNew - context:s]; + forKeyPath:NSStringFromSelector(@selector(runningApplications)) + options:NSKeyValueObservingOptionNew + context:s]; return true; } @@ -467,8 +467,7 @@ static inline void load_crop(syphon_t s, obs_data_t *settings) { s->crop = obs_data_get_bool(settings, "crop"); -#define LOAD_CROP(x) \ - s->crop_rect.x = obs_data_get_double(settings, "crop." #x) +#define LOAD_CROP(x) s->crop_rect.x = obs_data_get_double(settings, "crop." #x) LOAD_CROP(origin.x); LOAD_CROP(origin.y); LOAD_CROP(size.width); @@ -486,7 +485,7 @@ static void *syphon_create_internal(obs_data_t *settings, obs_source_t *source) if (!s) return s; - s->source = source; + s->source = source; if (!init_obs_graphics_objects(s)) goto fail; @@ -495,9 +494,9 @@ static void *syphon_create_internal(obs_data_t *settings, obs_source_t *source) goto fail; const char *inject_info = obs_data_get_string(settings, "application"); - s->inject_info = obs_data_create_from_json(inject_info); - s->inject_active = obs_data_get_bool(settings, "inject"); - s->inject_app = @(obs_data_get_string(s->inject_info, "name")); + s->inject_info = obs_data_create_from_json(inject_info); + s->inject_active = obs_data_get_bool(settings, "inject"); + s->inject_app = @(obs_data_get_string(s->inject_info, "name")); if (s->inject_app) [s->inject_app retain]; @@ -516,8 +515,8 @@ static void *syphon_create_internal(obs_data_t *settings, obs_source_t *source) load_crop(s, settings); - s->allow_transparency = obs_data_get_bool(settings, - "allow_transparency"); + s->allow_transparency = + obs_data_get_bool(settings, "allow_transparency"); return s; @@ -549,7 +548,8 @@ static inline void syphon_destroy_internal(syphon_t s) NSWorkspace *ws = [NSWorkspace sharedWorkspace]; [ws removeObserver:s->launch_listener - forKeyPath:NSStringFromSelector(@selector(runningApplications))]; + forKeyPath:NSStringFromSelector(@selector + (runningApplications))]; objc_release(&s->launch_listener); objc_release(&s->inject_app); @@ -561,7 +561,7 @@ static inline void syphon_destroy_internal(syphon_t s) obs_enter_graphics(); stop_client(s); - + if (s->sampler) gs_samplerstate_destroy(s->sampler); if (s->vertbuffer) @@ -587,44 +587,45 @@ static inline NSString *get_string(obs_data_t *settings, const char *name) } static inline void update_strings_from_context(syphon_t s, obs_data_t *settings, - NSString **app, NSString **name, NSString **uuid) + NSString **app, NSString **name, + NSString **uuid) { if (!s || !s->uuid_changed) return; s->uuid_changed = false; - *app = s->app_name; + *app = s->app_name; *name = s->name; *uuid = s->uuid; obs_data_set_string(settings, "app_name", s->app_name.UTF8String); - obs_data_set_string(settings, "name", s->name.UTF8String); - obs_data_set_string(settings, "uuid", s->uuid.UTF8String); + obs_data_set_string(settings, "name", s->name.UTF8String); + obs_data_set_string(settings, "uuid", s->uuid.UTF8String); } static inline void add_servers(syphon_t s, obs_property_t *list, - obs_data_t *settings) + obs_data_t *settings) { bool found_current = settings == NULL; - NSString *set_app = get_string(settings, "app_name"); + NSString *set_app = get_string(settings, "app_name"); NSString *set_name = get_string(settings, "name"); NSString *set_uuid = get_string(settings, "uuid"); - update_strings_from_context(s, settings, - &set_app, &set_name, &set_uuid); + update_strings_from_context(s, settings, &set_app, &set_name, + &set_uuid); obs_property_list_add_string(list, "", ""); NSArray *arr = [[SyphonServerDirectory sharedDirectory] servers]; for (NSDictionary *server in arr) { - NSString *app = server[SyphonServerDescriptionAppNameKey]; + NSString *app = server[SyphonServerDescriptionAppNameKey]; NSString *name = server[SyphonServerDescriptionNameKey]; NSString *uuid = server[SyphonServerDescriptionUUIDKey]; - NSString *serv = [NSString stringWithFormat:@"[%@] %@", - app, name]; + NSString *serv = + [NSString stringWithFormat:@"[%@] %@", app, name]; - obs_property_list_add_string(list, - serv.UTF8String, uuid.UTF8String); + obs_property_list_add_string(list, serv.UTF8String, + uuid.UTF8String); if (!found_current) found_current = [uuid isEqual:set_uuid]; @@ -633,15 +634,15 @@ static inline void add_servers(syphon_t s, obs_property_t *list, if (found_current || !set_uuid.length || !set_app.length) return; - NSString *serv = [NSString stringWithFormat:@"[%@] %@", - set_app, set_name]; - size_t idx = obs_property_list_add_string(list, - serv.UTF8String, set_uuid.UTF8String); + NSString *serv = + [NSString stringWithFormat:@"[%@] %@", set_app, set_name]; + size_t idx = obs_property_list_add_string(list, serv.UTF8String, + set_uuid.UTF8String); obs_property_list_item_disable(list, idx, true); } static bool servers_changed(obs_properties_t *props, obs_property_t *list, - obs_data_t *settings) + obs_data_t *settings) { @autoreleasepool { obs_property_list_clear(list); @@ -662,16 +663,15 @@ static inline bool is_inject_available_in_lib_dir(NSFileManager *fm, NSURL *url) if (!url.isFileURL) return false; - for (NSString *path in [fm - contentsOfDirectoryAtPath:url.path - error:nil]) { + for (NSString *path in [fm contentsOfDirectoryAtPath:url.path + error:nil]) { NSURL *bundle_url = [url URLByAppendingPathComponent:path]; - NSBundle *bundle = [NSBundle bundleWithURL:bundle_url]; + NSBundle *bundle = [NSBundle bundleWithURL:bundle_url]; if (!bundle) continue; if ([bundle.bundleIdentifier - isEqual:@"zakk.lol.SASyphonInjector"]) + isEqual:@"zakk.lol.SASyphonInjector"]) return true; } @@ -705,7 +705,7 @@ static inline void launch_syphon_inject_internal() } static bool launch_syphon_inject(obs_properties_t *props, obs_property_t *prop, - void *data) + void *data) { UNUSED_PARAMETER(props); UNUSED_PARAMETER(prop); @@ -720,13 +720,13 @@ static bool launch_syphon_inject(obs_properties_t *props, obs_property_t *prop, static int describes_app(obs_data_t *info, NSRunningApplication *app) { int score = 0; - if ([app.localizedName isEqual:get_string(info, "name")]) + if ([app.localizedName isEqual:get_string(info, "name")]) score += 2; if ([app.bundleIdentifier isEqual:get_string(info, "bundle")]) score += 2; - if ([app.executableURL isEqual:get_string(info, "executable")]) + if ([app.executableURL isEqual:get_string(info, "executable")]) score += 2; if (score && app.processIdentifier == obs_data_get_int(info, "pid")) @@ -739,10 +739,10 @@ static inline void app_to_data(NSRunningApplication *app, obs_data_t *app_data) { obs_data_set_string(app_data, "name", app.localizedName.UTF8String); obs_data_set_string(app_data, "bundle", - app.bundleIdentifier.UTF8String); + app.bundleIdentifier.UTF8String); // Until we drop 10.8, use path.fileSystemRepsentation obs_data_set_string(app_data, "executable", - app.executableURL.path.fileSystemRepresentation); + app.executableURL.path.fileSystemRepresentation); obs_data_set_int(app_data, "pid", app.processIdentifier); } @@ -760,8 +760,9 @@ static inline NSDictionary *get_duplicate_names(NSArray *apps) } static inline size_t add_app(obs_property_t *prop, NSDictionary *duplicates, - NSString *name, const char *bundle, const char *json_data, - bool is_duplicate, pid_t pid) + NSString *name, const char *bundle, + const char *json_data, bool is_duplicate, + pid_t pid) { if (!is_duplicate) { NSNumber *val = duplicates[name]; @@ -769,20 +770,21 @@ static inline size_t add_app(obs_property_t *prop, NSDictionary *duplicates, } if (is_duplicate) - name = [NSString stringWithFormat:@"%@ (%s: %d)", - name, bundle, pid]; + name = [NSString + stringWithFormat:@"%@ (%s: %d)", name, bundle, pid]; return obs_property_list_add_string(prop, name.UTF8String, json_data); } static void update_inject_list_internal(obs_properties_t *props, - obs_property_t *prop, obs_data_t *settings) + obs_property_t *prop, + obs_data_t *settings) { UNUSED_PARAMETER(props); - const char *current_str = obs_data_get_string(settings, "application"); - obs_data_t *current = obs_data_create_from_json(current_str); - NSString *current_name = @(obs_data_get_string(current, "name")); + const char *current_str = obs_data_get_string(settings, "application"); + obs_data_t *current = obs_data_create_from_json(current_str); + NSString *current_name = @(obs_data_get_string(current, "name")); bool current_found = !obs_data_has_user_value(current, "name"); @@ -790,10 +792,10 @@ static void update_inject_list_internal(obs_properties_t *props, obs_property_list_add_string(prop, "", ""); NSWorkspace *ws = [NSWorkspace sharedWorkspace]; - NSArray *apps = ws.runningApplications; + NSArray *apps = ws.runningApplications; NSDictionary *duplicates = get_duplicate_names(apps); - NSMapTable *candidates = [NSMapTable weakToStrongObjectsMapTable]; + NSMapTable *candidates = [NSMapTable weakToStrongObjectsMapTable]; obs_data_t *app_data = obs_data_create(); for (NSRunningApplication *app in apps) { @@ -801,11 +803,10 @@ static void update_inject_list_internal(obs_properties_t *props, int score = describes_app(current, app); NSString *name = app.localizedName; - add_app(prop, duplicates, name, - app.bundleIdentifier.UTF8String, - obs_data_get_json(app_data), - [name isEqual:current_name] && score < 4, - app.processIdentifier); + add_app(prop, duplicates, name, app.bundleIdentifier.UTF8String, + obs_data_get_json(app_data), + [name isEqual:current_name] && score < 4, + app.processIdentifier); if (score >= 4) { [candidates setObject:@(score) forKey:app]; @@ -816,10 +817,10 @@ static void update_inject_list_internal(obs_properties_t *props, if (!current_found) { size_t idx = add_app(prop, duplicates, current_name, - obs_data_get_string(current, "bundle"), - current_str, - duplicates[current_name] != nil, - obs_data_get_int(current, "pid")); + obs_data_get_string(current, "bundle"), + current_str, + duplicates[current_name] != nil, + obs_data_get_int(current, "pid")); obs_property_list_item_disable(prop, idx, true); } else if (candidates.count > 0) { @@ -829,7 +830,7 @@ static void update_inject_list_internal(obs_properties_t *props, for (NSRunningApplication *app in candidates.keyEnumerator) { NSNumber *score = [candidates objectForKey:app]; if ([score compare:best_match_score] == - NSOrderedDescending) { + NSOrderedDescending) { best_match = app; best_match_score = score; } @@ -839,7 +840,7 @@ static void update_inject_list_internal(obs_properties_t *props, if (best_match_score.intValue >= 4) { app_to_data(best_match, current); obs_data_set_string(settings, "application", - obs_data_get_json(current)); + obs_data_get_json(current)); } } @@ -847,7 +848,7 @@ static void update_inject_list_internal(obs_properties_t *props, } static void toggle_inject_internal(obs_properties_t *props, - obs_property_t *prop, obs_data_t *settings) + obs_property_t *prop, obs_data_t *settings) { bool enabled = obs_data_get_bool(settings, "inject"); obs_property_t *inject_list = obs_properties_get(props, "application"); @@ -857,7 +858,7 @@ static void toggle_inject_internal(obs_properties_t *props, } static bool toggle_inject(obs_properties_t *props, obs_property_t *prop, - obs_data_t *settings) + obs_data_t *settings) { @autoreleasepool { toggle_inject_internal(props, prop, settings); @@ -866,7 +867,7 @@ static bool toggle_inject(obs_properties_t *props, obs_property_t *prop, } static bool update_inject_list(obs_properties_t *props, obs_property_t *prop, - obs_data_t *settings) + obs_data_t *settings) { @autoreleasepool { update_inject_list_internal(props, prop, settings); @@ -875,11 +876,11 @@ static bool update_inject_list(obs_properties_t *props, obs_property_t *prop, } static bool update_crop(obs_properties_t *props, obs_property_t *prop, - obs_data_t *settings) + obs_data_t *settings) { bool enabled = obs_data_get_bool(settings, "crop"); -#define LOAD_CROP(x) \ +#define LOAD_CROP(x) \ prop = obs_properties_get(props, "crop." #x); \ obs_property_set_enabled(prop, enabled); LOAD_CROP(origin.x); @@ -903,7 +904,7 @@ static void show_syphon_license_internal(void) } static bool show_syphon_license(obs_properties_t *props, obs_property_t *prop, - void *data) + void *data) { UNUSED_PARAMETER(props); UNUSED_PARAMETER(prop); @@ -928,28 +929,28 @@ static inline obs_properties_t *syphon_properties_internal(syphon_t s) if (s) obs_source_addref(s->source); - obs_properties_t *props = obs_properties_create_param(s, - syphon_release); + obs_properties_t *props = + obs_properties_create_param(s, syphon_release); - obs_property_t *list = obs_properties_add_list(props, - "uuid", obs_module_text("Source"), - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); + obs_property_t *list = obs_properties_add_list( + props, "uuid", obs_module_text("Source"), OBS_COMBO_TYPE_LIST, + OBS_COMBO_FORMAT_STRING); obs_property_set_modified_callback(list, servers_changed); obs_properties_add_bool(props, "allow_transparency", - obs_module_text("AllowTransparency")); + obs_module_text("AllowTransparency")); - obs_property_t *launch = obs_properties_add_button(props, - "launch inject", obs_module_text("LaunchSyphonInject"), - launch_syphon_inject); + obs_property_t *launch = obs_properties_add_button( + props, "launch inject", obs_module_text("LaunchSyphonInject"), + launch_syphon_inject); - obs_property_t *inject = obs_properties_add_bool(props, - "inject", obs_module_text("Inject")); + obs_property_t *inject = obs_properties_add_bool( + props, "inject", obs_module_text("Inject")); obs_property_set_modified_callback(inject, toggle_inject); - obs_property_t *inject_list = obs_properties_add_list(props, - "application", obs_module_text("Application"), - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); + obs_property_t *inject_list = obs_properties_add_list( + props, "application", obs_module_text("Application"), + OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); obs_property_set_modified_callback(inject_list, update_inject_list); if (!get_inject_application_path()) @@ -960,13 +961,14 @@ static inline obs_properties_t *syphon_properties_internal(syphon_t s) obs_property_set_enabled(inject_list, false); } - obs_property_t *crop = obs_properties_add_bool(props, "crop", - obs_module_text("Crop")); + obs_property_t *crop = + obs_properties_add_bool(props, "crop", obs_module_text("Crop")); obs_property_set_modified_callback(crop, update_crop); -#define LOAD_CROP(x) \ - obs_properties_add_float(props, "crop." #x, \ - obs_module_text("Crop." #x), 0., 4096.f, .5f); +#define LOAD_CROP(x) \ + obs_properties_add_float(props, "crop." #x, \ + obs_module_text("Crop." #x), 0., 4096.f, \ + .5f); LOAD_CROP(origin.x); LOAD_CROP(origin.y); LOAD_CROP(size.width); @@ -974,8 +976,8 @@ static inline obs_properties_t *syphon_properties_internal(syphon_t s) #undef LOAD_CROP obs_properties_add_button(props, "syphon license", - obs_module_text("SyphonLicense"), - show_syphon_license); + obs_module_text("SyphonLicense"), + show_syphon_license); return props; } @@ -993,8 +995,8 @@ static inline void syphon_save_internal(syphon_t s, obs_data_t *settings) return; obs_data_set_string(settings, "app_name", s->app_name.UTF8String); - obs_data_set_string(settings, "name", s->name.UTF8String); - obs_data_set_string(settings, "uuid", s->uuid.UTF8String); + obs_data_set_string(settings, "name", s->name.UTF8String); + obs_data_set_string(settings, "uuid", s->uuid.UTF8String); } static void syphon_save(void *data, obs_data_t *settings) @@ -1005,25 +1007,25 @@ static void syphon_save(void *data, obs_data_t *settings) } static inline void build_sprite(struct gs_vb_data *data, float fcx, float fcy, - float start_u, float end_u, float start_v, float end_v) + float start_u, float end_u, float start_v, + float end_v) { struct vec2 *tvarray = data->tvarray[0].array; - vec3_set(data->points+1, fcx, 0.0f, 0.0f); - vec3_set(data->points+2, 0.0f, fcy, 0.0f); - vec3_set(data->points+3, fcx, fcy, 0.0f); - vec2_set(tvarray, start_u, start_v); - vec2_set(tvarray+1, end_u, start_v); - vec2_set(tvarray+2, start_u, end_v); - vec2_set(tvarray+3, end_u, end_v); + vec3_set(data->points + 1, fcx, 0.0f, 0.0f); + vec3_set(data->points + 2, 0.0f, fcy, 0.0f); + vec3_set(data->points + 3, fcx, fcy, 0.0f); + vec2_set(tvarray, start_u, start_v); + vec2_set(tvarray + 1, end_u, start_v); + vec2_set(tvarray + 2, start_u, end_v); + vec2_set(tvarray + 3, end_u, end_v); } -static inline void build_sprite_rect(struct gs_vb_data *data, - float origin_x, float origin_y, float end_x, float end_y) +static inline void build_sprite_rect(struct gs_vb_data *data, float origin_x, + float origin_y, float end_x, float end_y) { build_sprite(data, fabs(end_x - origin_x), fabs(end_y - origin_y), - origin_x, end_x, - origin_y, end_y); + origin_x, end_x, origin_y, end_y); } static inline void tick_inject_state(syphon_t s, float seconds) @@ -1050,17 +1052,15 @@ static void syphon_video_tick(void *data, float seconds) if (!s->tex) return; - static const CGRect null_crop = { { 0.f } }; + static const CGRect null_crop = {{0.f}}; const CGRect *crop = &null_crop; if (s->crop) crop = &s->crop_rect; obs_enter_graphics(); build_sprite_rect(gs_vertexbuffer_get_data(s->vertbuffer), - crop->origin.x, - s->height - crop->origin.y, - s->width - crop->size.width, - crop->size.height); + crop->origin.x, s->height - crop->origin.y, + s->width - crop->size.width, crop->size.height); obs_leave_graphics(); } @@ -1085,7 +1085,7 @@ static void syphon_video_render(void *data, gs_effect_t *effect) gs_load_samplerstate(s->sampler, 0); gs_technique_t *tech = gs_effect_get_technique(s->effect, "Draw"); gs_effect_set_texture(gs_effect_get_param_by_name(s->effect, "image"), - s->tex); + s->tex); gs_technique_begin(tech); gs_technique_begin_pass(tech, 0); @@ -1105,9 +1105,8 @@ static uint32_t syphon_get_width(void *data) syphon_t s = (syphon_t)data; if (!s->crop) return s->width; - int32_t width = s->width - - s->crop_rect.origin.x - - s->crop_rect.size.width; + int32_t width = + s->width - s->crop_rect.origin.x - s->crop_rect.size.width; return MAX(0, width); } @@ -1116,9 +1115,8 @@ static uint32_t syphon_get_height(void *data) syphon_t s = (syphon_t)data; if (!s->crop) return s->height; - int32_t height = s->height - - s->crop_rect.origin.y - - s->crop_rect.size.height; + int32_t height = + s->height - s->crop_rect.origin.y - s->crop_rect.size.height; return MAX(0, height); } @@ -1134,9 +1132,9 @@ static inline void inject_app(syphon_t s, NSRunningApplication *app, bool retry) if (!sbapp) return LOG(LOG_ERROR, "Could not inject %s", - app.localizedName.UTF8String); + app.localizedName.UTF8String); - sbapp.timeout = 10*60; + sbapp.timeout = 10 * 60; sbapp.sendMode = kAEWaitReply; [sbapp sendEvent:'ascr' id:'gdut' parameters:0]; sbapp.sendMode = kAENoReply; @@ -1145,9 +1143,8 @@ static inline void inject_app(syphon_t s, NSRunningApplication *app, bool retry) if (retry) return; - LOG(LOG_INFO, "Injected '%s' (%d, '%s')", - app.localizedName.UTF8String, - app.processIdentifier, app.bundleIdentifier.UTF8String); + LOG(LOG_INFO, "Injected '%s' (%d, '%s')", app.localizedName.UTF8String, + app.processIdentifier, app.bundleIdentifier.UTF8String); } static inline void find_and_inject_target(syphon_t s, NSArray *arr, bool retry) @@ -1174,20 +1171,17 @@ static inline void find_and_inject_target(syphon_t s, NSArray *arr, bool retry) static inline bool inject_info_equal(obs_data_t *prev, obs_data_t *new) { - if (![get_string(prev, "name") - isEqual:get_string(new, "name")]) + if (![get_string(prev, "name") isEqual:get_string(new, "name")]) return false; - if (![get_string(prev, "bundle") - isEqual:get_string(new, "bundle")]) + if (![get_string(prev, "bundle") isEqual:get_string(new, "bundle")]) return false; if (![get_string(prev, "executable") - isEqual:get_string(new, "executable")]) + isEqual:get_string(new, "executable")]) return false; - if (![get_string(prev, "pid") - isEqual:get_string(new, "pid")]) + if (![get_string(prev, "pid") isEqual:get_string(new, "pid")]) return false; return true; @@ -1195,15 +1189,15 @@ static inline bool inject_info_equal(obs_data_t *prev, obs_data_t *new) static inline void update_inject(syphon_t s, obs_data_t *settings) { - bool try_injecting = s->inject_active; - s->inject_active = obs_data_get_bool(settings, "inject"); + bool try_injecting = s->inject_active; + s->inject_active = obs_data_get_bool(settings, "inject"); const char *inject_str = obs_data_get_string(settings, "application"); try_injecting = !try_injecting && s->inject_active; obs_data_t *prev = s->inject_info; s->inject_info = obs_data_create_from_json(inject_str); - + NSString *prev_app = s->inject_app; s->inject_app = [@(obs_data_get_string(s->inject_info, "name")) retain]; [prev_app release]; @@ -1216,10 +1210,10 @@ static inline void update_inject(syphon_t s, obs_data_t *settings) s->inject_server_found = false; for (NSDictionary *server in servers) update_inject_state(s, server, true); - + if (!try_injecting) try_injecting = s->inject_active && - !inject_info_equal(prev, s->inject_info); + !inject_info_equal(prev, s->inject_info); obs_data_release(prev); @@ -1239,15 +1233,15 @@ static inline bool update_syphon(syphon_t s, obs_data_t *settings) NSDictionary *dict = find_by_uuid(arr, s->uuid); if (dict) { - NSString *app = dict[SyphonServerDescriptionAppNameKey]; + NSString *app = dict[SyphonServerDescriptionAppNameKey]; NSString *name = dict[SyphonServerDescriptionNameKey]; obs_data_set_string(settings, "app_name", app.UTF8String); - obs_data_set_string(settings, "name", name.UTF8String); + obs_data_set_string(settings, "name", name.UTF8String); load_syphon_settings(s, settings); } else if (!dict && !s->uuid.length) { obs_data_set_string(settings, "app_name", ""); - obs_data_set_string(settings, "name", ""); + obs_data_set_string(settings, "name", ""); load_syphon_settings(s, settings); } @@ -1256,8 +1250,8 @@ static inline bool update_syphon(syphon_t s, obs_data_t *settings) static void syphon_update_internal(syphon_t s, obs_data_t *settings) { - s->allow_transparency = obs_data_get_bool(settings, - "allow_transparency"); + s->allow_transparency = + obs_data_get_bool(settings, "allow_transparency"); load_crop(s, settings); update_inject(s, settings); @@ -1273,19 +1267,18 @@ static void syphon_update(void *data, obs_data_t *settings) } struct obs_source_info syphon_info = { - .id = "syphon-input", - .type = OBS_SOURCE_TYPE_INPUT, - .output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CUSTOM_DRAW | - OBS_SOURCE_DO_NOT_DUPLICATE, - .get_name = syphon_get_name, - .create = syphon_create, - .destroy = syphon_destroy, - .video_render = syphon_video_render, - .video_tick = syphon_video_tick, + .id = "syphon-input", + .type = OBS_SOURCE_TYPE_INPUT, + .output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CUSTOM_DRAW | + OBS_SOURCE_DO_NOT_DUPLICATE, + .get_name = syphon_get_name, + .create = syphon_create, + .destroy = syphon_destroy, + .video_render = syphon_video_render, + .video_tick = syphon_video_tick, .get_properties = syphon_properties, - .get_width = syphon_get_width, - .get_height = syphon_get_height, - .update = syphon_update, - .save = syphon_save, + .get_width = syphon_get_width, + .get_height = syphon_get_height, + .update = syphon_update, + .save = syphon_save, }; - diff --git a/plugins/text-freetype2/find-font-cocoa.m b/plugins/text-freetype2/find-font-cocoa.m index 9583cb67a..22b379266 100644 --- a/plugins/text-freetype2/find-font-cocoa.m +++ b/plugins/text-freetype2/find-font-cocoa.m @@ -30,12 +30,12 @@ static void add_path_fonts(NSFileManager *file_manager, NSString *path) files = [file_manager contentsOfDirectoryAtPath:path error:nil]; for (NSString *file in files) { - NSString *full_path = [path stringByAppendingPathComponent:file]; + NSString *full_path = + [path stringByAppendingPathComponent:file]; BOOL is_dir = FALSE; - bool folder_exists = [file_manager - fileExistsAtPath:full_path - isDirectory:&is_dir]; + bool folder_exists = [file_manager fileExistsAtPath:full_path + isDirectory:&is_dir]; if (folder_exists && is_dir) { add_path_fonts(file_manager, full_path); @@ -50,7 +50,7 @@ void load_os_font_list(void) @autoreleasepool { BOOL is_dir; NSArray *paths = NSSearchPathForDirectoriesInDomains( - NSLibraryDirectory, NSAllDomainsMask, true); + NSLibraryDirectory, NSAllDomainsMask, true); for (NSString *path in paths) { NSFileManager *file_manager = @@ -59,8 +59,8 @@ void load_os_font_list(void) [path stringByAppendingPathComponent:@"Fonts"]; bool folder_exists = [file_manager - fileExistsAtPath:font_path - isDirectory:&is_dir]; + fileExistsAtPath:font_path + isDirectory:&is_dir]; if (folder_exists && is_dir) add_path_fonts(file_manager, font_path); @@ -78,17 +78,19 @@ static uint32_t add_font_checksum(uint32_t checksum, const char *path) } static uint32_t add_font_checksum_path(uint32_t checksum, - NSFileManager *file_manager, NSString *path) + NSFileManager *file_manager, + NSString *path) { NSArray *files = NULL; files = [file_manager contentsOfDirectoryAtPath:path error:nil]; for (NSString *file in files) { - NSString *full_path = [path stringByAppendingPathComponent:file]; + NSString *full_path = + [path stringByAppendingPathComponent:file]; - checksum = add_font_checksum(checksum, - full_path.fileSystemRepresentation); + checksum = add_font_checksum( + checksum, full_path.fileSystemRepresentation); } return checksum; @@ -101,7 +103,7 @@ uint32_t get_font_checksum(void) @autoreleasepool { BOOL is_dir; NSArray *paths = NSSearchPathForDirectoriesInDomains( - NSLibraryDirectory, NSAllDomainsMask, true); + NSLibraryDirectory, NSAllDomainsMask, true); for (NSString *path in paths) { NSFileManager *file_manager = @@ -110,12 +112,12 @@ uint32_t get_font_checksum(void) [path stringByAppendingPathComponent:@"Fonts"]; bool folder_exists = [file_manager - fileExistsAtPath:font_path - isDirectory:&is_dir]; + fileExistsAtPath:font_path + isDirectory:&is_dir]; if (folder_exists && is_dir) - checksum = add_font_checksum_path(checksum, - file_manager, font_path); + checksum = add_font_checksum_path( + checksum, file_manager, font_path); } } diff --git a/test/osx/test.mm b/test/osx/test.mm index 136b51340..353884ba4 100644 --- a/test/osx/test.mm +++ b/test/osx/test.mm @@ -16,24 +16,23 @@ static const int cy = 600; /* --------------------------------------------------- */ -template -struct OBSUniqueHandle : std::unique_ptr> -{ +template +struct OBSUniqueHandle : std::unique_ptr> { using base = std::unique_ptr>; - explicit OBSUniqueHandle(T *obj=nullptr) : base(obj, D) {} - operator T*() { return base::get(); } + explicit OBSUniqueHandle(T *obj = nullptr) : base(obj, D) {} + operator T *() { return base::get(); } }; #define DECLARE_DELETER(x) decltype(x), x -using SourceContext = OBSUniqueHandle; +using SourceContext = + OBSUniqueHandle; -using SceneContext = OBSUniqueHandle; +using SceneContext = + OBSUniqueHandle; -using DisplayContext = OBSUniqueHandle; +using DisplayContext = + OBSUniqueHandle; #undef DECLARE_DELETER @@ -45,15 +44,15 @@ static void CreateOBS() throw "Couldn't create OBS"; struct obs_video_info ovi; - ovi.adapter = 0; - ovi.fps_num = 30000; - ovi.fps_den = 1001; + ovi.adapter = 0; + ovi.fps_num = 30000; + ovi.fps_den = 1001; ovi.graphics_module = DL_OPENGL; - ovi.output_format = VIDEO_FORMAT_RGBA; - ovi.base_width = cx; - ovi.base_height = cy; - ovi.output_width = cx; - ovi.output_height = cy; + ovi.output_format = VIDEO_FORMAT_RGBA; + ovi.base_width = cx; + ovi.base_height = cy; + ovi.output_width = cx; + ovi.output_height = cy; if (obs_reset_video(&ovi) != 0) throw "Couldn't initialize video"; @@ -61,12 +60,12 @@ static void CreateOBS() static DisplayContext CreateDisplay(NSView *view) { - gs_init_data info = {}; - info.cx = cx; - info.cy = cy; - info.format = GS_RGBA; - info.zsformat = GS_ZS_NONE; - info.window.view = view; + gs_init_data info = {}; + info.cx = cx; + info.cy = cy; + info.format = GS_RGBA; + info.zsformat = GS_ZS_NONE; + info.window.view = view; return DisplayContext{obs_display_create(&info)}; } @@ -79,8 +78,8 @@ static SceneContext SetupScene() /* ------------------------------------------------------ */ /* create source */ - SourceContext source{obs_source_create("random", "a test source", - nullptr, nullptr)}; + SourceContext source{ + obs_source_create("random", "a test source", nullptr, nullptr)}; if (!source) throw "Couldn't create random test source"; @@ -99,20 +98,19 @@ static SceneContext SetupScene() return scene; } -@interface OBSTest : NSObject -{ +@interface OBSTest : NSObject { NSWindow *win; NSView *view; DisplayContext display; SceneContext scene; } -- (void)applicationDidFinishLaunching:(NSNotification*)notification; -- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication*)app; -- (void)windowWillClose:(NSNotification*)notification; +- (void)applicationDidFinishLaunching:(NSNotification *)notification; +- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)app; +- (void)windowWillClose:(NSNotification *)notification; @end @implementation OBSTest -- (void)applicationDidFinishLaunching:(NSNotification*)notification +- (void)applicationDidFinishLaunching:(NSNotification *)notification { UNUSED_PARAMETER(notification); @@ -120,9 +118,10 @@ static SceneContext SetupScene() NSRect content_rect = NSMakeRect(0, 0, cx, cy); win = [[NSWindow alloc] initWithContentRect:content_rect - styleMask:NSTitledWindowMask | NSClosableWindowMask - backing:NSBackingStoreBuffered - defer:NO]; + styleMask:NSTitledWindowMask | + NSClosableWindowMask + backing:NSBackingStoreBuffered + defer:NO]; if (!win) throw "Could not create window"; @@ -144,10 +143,12 @@ static SceneContext SetupScene() scene = SetupScene(); - obs_display_add_draw_callback(display.get(), - [](void *, uint32_t, uint32_t) { - obs_render_main_texture(); - }, nullptr); + obs_display_add_draw_callback( + display.get(), + [](void *, uint32_t, uint32_t) { + obs_render_main_texture(); + }, + nullptr); } catch (char const *error) { NSLog(@"%s\n", error); @@ -156,14 +157,14 @@ static SceneContext SetupScene() } } -- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication*)app +- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)app { UNUSED_PARAMETER(app); return YES; } -- (void)windowWillClose:(NSNotification*)notification +- (void)windowWillClose:(NSNotification *)notification { UNUSED_PARAMETER(notification);