av-capture.mm 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198
  1. #import <AVFoundation/AVFoundation.h>
  2. #import <CoreFoundation/CoreFoundation.h>
  3. #import <CoreMedia/CoreMedia.h>
  4. #import <CoreVideo/CoreVideo.h>
  5. #import <CoreMediaIO/CMIOHardware.h>
  6. #include <AvailabilityMacros.h>
  7. #include <obs-module.h>
  8. #include <obs.hpp>
  9. #include <media-io/video-io.h>
  10. #include <util/dstr.hpp>
  11. #include <algorithm>
  12. #include <initializer_list>
  13. #include <cinttypes>
  14. #include <limits>
  15. #include <memory>
  16. #include <vector>
  17. #include "left-right.hpp"
  18. #include "scope-guard.hpp"
  19. #define NBSP "\xC2\xA0"
  20. using namespace std;
  21. namespace std {
  22. template<> struct default_delete<obs_data_t> {
  23. void operator()(obs_data_t *data)
  24. {
  25. obs_data_release(data);
  26. }
  27. };
  28. template<> struct default_delete<obs_data_item_t> {
  29. void operator()(obs_data_item_t *item)
  30. {
  31. obs_data_item_release(&item);
  32. }
  33. };
  34. } // namespace std
  35. #define TEXT_AVCAPTURE obs_module_text("AVCapture")
  36. #define TEXT_DEVICE obs_module_text("Device")
  37. #define TEXT_USE_PRESET obs_module_text("UsePreset")
  38. #define TEXT_PRESET obs_module_text("Preset")
  39. #define TEXT_RESOLUTION obs_module_text("Resolution")
  40. #define TEXT_FRAME_RATE obs_module_text("FrameRate")
  41. #define TEXT_MATCH_OBS obs_module_text("MatchOBS")
  42. #define TEXT_INPUT_FORMAT obs_module_text("InputFormat")
  43. #define TEXT_COLOR_SPACE obs_module_text("ColorSpace")
  44. #define TEXT_VIDEO_RANGE obs_module_text("VideoRange")
  45. #define TEXT_RANGE_PARTIAL obs_module_text("VideoRange.Partial")
  46. #define TEXT_RANGE_FULL obs_module_text("VideoRange.Full")
  47. #define TEXT_AUTO obs_module_text("Auto")
  48. #define TEXT_COLOR_UNKNOWN_NAME "Unknown"
  49. #define TEXT_RANGE_UNKNOWN_NAME "Unknown"
  50. static const FourCharCode INPUT_FORMAT_AUTO = -1;
  51. static const int COLOR_SPACE_AUTO = -1;
  52. static const int VIDEO_RANGE_AUTO = -1;
  53. #define MILLI_TIMESCALE 1000
  54. #define MICRO_TIMESCALE (MILLI_TIMESCALE * 1000)
  55. #define NANO_TIMESCALE (MICRO_TIMESCALE * 1000)
  56. #define AV_FOURCC_STR(code) \
  57. (char[5]) \
  58. { \
  59. static_cast<char>((code >> 24) & 0xFF), static_cast<char>((code >> 16) & 0xFF), \
  60. static_cast<char>((code >> 8) & 0xFF), static_cast<char>(code & 0xFF), 0 \
  61. }
  62. struct av_capture;
  63. #define AVLOG(level, format, ...) blog(level, "%s: " format, obs_source_get_name(capture->source), ##__VA_ARGS__)
  64. @interface OBSAVCaptureDelegate
  65. : NSObject <AVCaptureVideoDataOutputSampleBufferDelegate, AVCaptureAudioDataOutputSampleBufferDelegate> {
  66. @public
  67. struct av_capture *capture;
  68. }
  69. - (void)captureOutput:(AVCaptureOutput *)out
  70. didDropSampleBuffer:(CMSampleBufferRef)sampleBuffer
  71. fromConnection:(AVCaptureConnection *)connection;
  72. - (void)captureOutput:(AVCaptureOutput *)captureOutput
  73. didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer
  74. fromConnection:(AVCaptureConnection *)connection;
  75. @end
  76. namespace {
  77. static auto remove_observer = [](id observer) {
  78. [[NSNotificationCenter defaultCenter] removeObserver:observer];
  79. };
  80. struct observer_handle : unique_ptr<remove_pointer<id>::type, decltype(remove_observer)> {
  81. using base = unique_ptr<remove_pointer<id>::type, decltype(remove_observer)>;
  82. explicit observer_handle(id observer = nullptr) : base(observer, remove_observer)
  83. {}
  84. };
  85. struct av_video_info {
  86. video_colorspace colorspace;
  87. video_range_type video_range;
  88. bool video_params_valid = false;
  89. };
  90. } // namespace
  91. struct av_capture {
  92. OBSAVCaptureDelegate *delegate;
  93. dispatch_queue_t queue;
  94. dispatch_queue_t audioQueue;
  95. bool has_clock;
  96. bool device_locked;
  97. left_right::left_right<av_video_info> video_info;
  98. AVCaptureVideoDataOutput *out;
  99. AVCaptureAudioDataOutput *audioOut;
  100. AVCaptureDevice *device;
  101. AVCaptureDeviceInput *device_input;
  102. AVCaptureSession *session;
  103. NSString *uid;
  104. observer_handle connect_observer;
  105. observer_handle disconnect_observer;
  106. FourCharCode fourcc;
  107. video_format video_format;
  108. bool use_preset = false;
  109. int requested_colorspace = COLOR_SPACE_AUTO;
  110. int requested_video_range = VIDEO_RANGE_AUTO;
  111. bool enable_audio;
  112. obs_source_t *source;
  113. obs_source_frame frame;
  114. obs_source_audio audio;
  115. };
  116. static NSString *get_string(obs_data_t *data, char const *name)
  117. {
  118. return @(obs_data_get_string(data, name));
  119. }
  120. static AVCaptureDevice *get_device(obs_data_t *settings)
  121. {
  122. auto uid = get_string(settings, "device");
  123. return [AVCaptureDevice deviceWithUniqueID:uid];
  124. }
  125. template<typename T, typename U>
  126. static void clamp(T &store, U val, T low = numeric_limits<T>::min(), T high = numeric_limits<T>::max())
  127. {
  128. store = static_cast<intmax_t>(val) < static_cast<intmax_t>(low)
  129. ? low
  130. : (static_cast<intmax_t>(val) > static_cast<intmax_t>(high) ? high : static_cast<T>(val));
  131. }
  132. static bool get_resolution(obs_data_t *settings, CMVideoDimensions &dims)
  133. {
  134. using item_ptr = unique_ptr<obs_data_item_t>;
  135. item_ptr item {obs_data_item_byname(settings, "resolution")};
  136. if (!item)
  137. return false;
  138. auto res_str = obs_data_item_get_string(item.get());
  139. unique_ptr<obs_data_t> res {obs_data_create_from_json(res_str)};
  140. if (!res)
  141. return false;
  142. item_ptr width {obs_data_item_byname(res.get(), "width")};
  143. item_ptr height {obs_data_item_byname(res.get(), "height")};
  144. if (!width || !height)
  145. return false;
  146. clamp(dims.width, obs_data_item_get_int(width.get()), 0);
  147. clamp(dims.height, obs_data_item_get_int(height.get()), 0);
  148. if (!dims.width || !dims.height)
  149. return false;
  150. return true;
  151. }
  152. static bool get_input_format(obs_data_t *settings, FourCharCode &fourcc)
  153. {
  154. auto item = unique_ptr<obs_data_item_t> {obs_data_item_byname(settings, "input_format")};
  155. if (!item)
  156. return false;
  157. fourcc = (FourCharCode) obs_data_item_get_int(item.get());
  158. return true;
  159. }
  160. namespace {
  161. struct config_helper {
  162. obs_data_t *settings = nullptr;
  163. AVCaptureDevice *dev_ = nullptr;
  164. bool dims_valid : 1;
  165. bool fr_valid : 1;
  166. bool fps_valid : 1;
  167. bool if_valid : 1;
  168. CMVideoDimensions dims_ {};
  169. const char *frame_rate_ = nullptr;
  170. media_frames_per_second fps_ {};
  171. FourCharCode input_format_ = INPUT_FORMAT_AUTO;
  172. explicit config_helper(obs_data_t *settings) : settings(settings)
  173. {
  174. dev_ = get_device(settings);
  175. dims_valid = get_resolution(settings, dims_);
  176. fr_valid = obs_data_get_frames_per_second(settings, "frame_rate", nullptr, &frame_rate_);
  177. fps_valid = obs_data_get_frames_per_second(settings, "frame_rate", &fps_, nullptr);
  178. if_valid = get_input_format(settings, input_format_);
  179. }
  180. AVCaptureDevice *dev() const
  181. {
  182. return dev_;
  183. }
  184. const CMVideoDimensions *dims() const
  185. {
  186. return dims_valid ? &dims_ : nullptr;
  187. }
  188. const char *frame_rate() const
  189. {
  190. return fr_valid ? frame_rate_ : nullptr;
  191. }
  192. const media_frames_per_second *fps() const
  193. {
  194. return fps_valid ? &fps_ : nullptr;
  195. }
  196. const FourCharCode *input_format() const
  197. {
  198. return if_valid ? &input_format_ : nullptr;
  199. }
  200. };
  201. struct av_capture_ref {
  202. av_capture *capture = nullptr;
  203. OBSSource source;
  204. av_capture_ref() = default;
  205. av_capture_ref(av_capture *capture_, obs_weak_source_t *weak_source) : source(OBSGetStrongRef(weak_source))
  206. {
  207. if (!source)
  208. return;
  209. capture = capture_;
  210. }
  211. operator av_capture *()
  212. {
  213. return capture;
  214. }
  215. av_capture *operator->()
  216. {
  217. return capture;
  218. }
  219. };
  220. struct properties_param {
  221. av_capture *capture = nullptr;
  222. OBSWeakSource weak_source;
  223. properties_param(av_capture *capture) : capture(capture)
  224. {
  225. if (!capture)
  226. return;
  227. weak_source = OBSGetWeakRef(capture->source);
  228. }
  229. av_capture_ref get_ref()
  230. {
  231. return {capture, weak_source};
  232. }
  233. };
  234. } // namespace
  235. static av_capture_ref get_ref(obs_properties_t *props)
  236. {
  237. void *param = obs_properties_get_param(props);
  238. if (!param)
  239. return {};
  240. return static_cast<properties_param *>(param)->get_ref();
  241. }
  242. static inline video_format format_from_subtype(FourCharCode subtype)
  243. {
  244. //TODO: uncomment VIDEO_FORMAT_NV12 and VIDEO_FORMAT_ARGB once libobs
  245. // gains matching GPU conversions or a CPU fallback is implemented
  246. switch (subtype) {
  247. case kCVPixelFormatType_422YpCbCr8:
  248. return VIDEO_FORMAT_UYVY;
  249. case kCVPixelFormatType_422YpCbCr8_yuvs:
  250. return VIDEO_FORMAT_YUY2;
  251. /* case kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange:
  252. * case kCVPixelFormatType_420YpCbCr8BiPlanarFullRange:
  253. * return VIDEO_FORMAT_NV12;
  254. * case kCVPixelFormatType_32ARGB:
  255. * return VIDEO_FORMAT_ARGB;
  256. */
  257. case kCVPixelFormatType_32BGRA:
  258. return VIDEO_FORMAT_BGRA;
  259. default:
  260. return VIDEO_FORMAT_NONE;
  261. }
  262. }
  263. static const char *fourcc_subtype_name(FourCharCode fourcc);
  264. static const char *format_description_subtype_name(CMFormatDescriptionRef desc, FourCharCode *fourcc_ = nullptr)
  265. {
  266. FourCharCode fourcc = CMFormatDescriptionGetMediaSubType(desc);
  267. if (fourcc_)
  268. *fourcc_ = fourcc;
  269. return fourcc_subtype_name(fourcc);
  270. }
  271. static const char *fourcc_subtype_name(FourCharCode fourcc)
  272. {
  273. switch (fourcc) {
  274. case kCVPixelFormatType_422YpCbCr8:
  275. return "UYVY - 422YpCbCr8"; //VIDEO_FORMAT_UYVY;
  276. case kCVPixelFormatType_422YpCbCr8_yuvs:
  277. return "YUY2 - 422YpCbCr8_yuvs"; //VIDEO_FORMAT_YUY2;
  278. case kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange:
  279. case kCVPixelFormatType_420YpCbCr8BiPlanarFullRange:
  280. return "NV12 - 420YpCbCr8BiPlanar"; //VIDEO_FORMAT_NV12;
  281. case kCVPixelFormatType_32ARGB:
  282. return "ARGB - 32ARGB"; //VIDEO_FORMAT_ARGB;*/
  283. case kCVPixelFormatType_32BGRA:
  284. return "BGRA - 32BGRA"; //VIDEO_FORMAT_BGRA;
  285. case kCMVideoCodecType_Animation:
  286. return "Apple Animation";
  287. case kCMVideoCodecType_Cinepak:
  288. return "Cinepak";
  289. case kCMVideoCodecType_JPEG:
  290. return "JPEG";
  291. case kCMVideoCodecType_JPEG_OpenDML:
  292. return "MJPEG - JPEG OpenDML";
  293. case kCMVideoCodecType_SorensonVideo:
  294. return "Sorenson Video";
  295. case kCMVideoCodecType_SorensonVideo3:
  296. return "Sorenson Video 3";
  297. case kCMVideoCodecType_H263:
  298. return "H.263";
  299. case kCMVideoCodecType_H264:
  300. return "H.264";
  301. case kCMVideoCodecType_MPEG4Video:
  302. return "MPEG-4";
  303. case kCMVideoCodecType_MPEG2Video:
  304. return "MPEG-2";
  305. case kCMVideoCodecType_MPEG1Video:
  306. return "MPEG-1";
  307. case kCMVideoCodecType_DVCNTSC:
  308. return "DV NTSC";
  309. case kCMVideoCodecType_DVCPAL:
  310. return "DV PAL";
  311. case kCMVideoCodecType_DVCProPAL:
  312. return "Panasonic DVCPro PAL";
  313. case kCMVideoCodecType_DVCPro50NTSC:
  314. return "Panasonic DVCPro-50 NTSC";
  315. case kCMVideoCodecType_DVCPro50PAL:
  316. return "Panasonic DVCPro-50 PAL";
  317. case kCMVideoCodecType_DVCPROHD720p60:
  318. return "Panasonic DVCPro-HD 720p60";
  319. case kCMVideoCodecType_DVCPROHD720p50:
  320. return "Panasonic DVCPro-HD 720p50";
  321. case kCMVideoCodecType_DVCPROHD1080i60:
  322. return "Panasonic DVCPro-HD 1080i60";
  323. case kCMVideoCodecType_DVCPROHD1080i50:
  324. return "Panasonic DVCPro-HD 1080i50";
  325. case kCMVideoCodecType_DVCPROHD1080p30:
  326. return "Panasonic DVCPro-HD 1080p30";
  327. case kCMVideoCodecType_DVCPROHD1080p25:
  328. return "Panasonic DVCPro-HD 1080p25";
  329. case kCMVideoCodecType_AppleProRes4444:
  330. return "Apple ProRes 4444";
  331. case kCMVideoCodecType_AppleProRes422HQ:
  332. return "Apple ProRes 422 HQ";
  333. case kCMVideoCodecType_AppleProRes422:
  334. return "Apple ProRes 422";
  335. case kCMVideoCodecType_AppleProRes422LT:
  336. return "Apple ProRes 422 LT";
  337. case kCMVideoCodecType_AppleProRes422Proxy:
  338. return "Apple ProRes 422 Proxy";
  339. default:
  340. blog(LOG_INFO, "Unknown format %s", AV_FOURCC_STR(fourcc));
  341. return "unknown";
  342. }
  343. }
  344. static inline bool is_fullrange_yuv(FourCharCode pixel_format)
  345. {
  346. switch (pixel_format) {
  347. case kCVPixelFormatType_420YpCbCr8PlanarFullRange:
  348. case kCVPixelFormatType_420YpCbCr8BiPlanarFullRange:
  349. case kCVPixelFormatType_422YpCbCr8FullRange:
  350. return true;
  351. default:
  352. return false;
  353. }
  354. }
  355. static inline video_colorspace get_colorspace(CMFormatDescriptionRef desc)
  356. {
  357. CFPropertyListRef matrix = CMFormatDescriptionGetExtension(desc, kCMFormatDescriptionExtension_YCbCrMatrix);
  358. if (!matrix)
  359. return VIDEO_CS_DEFAULT;
  360. if (CFStringCompare(static_cast<CFStringRef>(matrix), kCVImageBufferYCbCrMatrix_ITU_R_601_4, 0) ==
  361. kCFCompareEqualTo)
  362. return VIDEO_CS_601;
  363. return VIDEO_CS_709;
  364. }
  365. static inline bool update_colorspace(av_capture *capture, obs_source_frame *frame, CMFormatDescriptionRef desc,
  366. bool full_range, av_video_info &vi)
  367. {
  368. auto cs_auto = capture->use_preset || capture->requested_colorspace == COLOR_SPACE_AUTO;
  369. auto vr_auto = capture->use_preset || capture->requested_video_range == VIDEO_RANGE_AUTO;
  370. video_colorspace colorspace = get_colorspace(desc);
  371. video_range_type range = full_range ? VIDEO_RANGE_FULL : VIDEO_RANGE_PARTIAL;
  372. bool cs_matches = false;
  373. if (cs_auto) {
  374. cs_matches = colorspace == vi.colorspace;
  375. } else {
  376. colorspace = static_cast<video_colorspace>(capture->requested_colorspace);
  377. cs_matches = colorspace == vi.colorspace;
  378. }
  379. bool vr_matches = false;
  380. if (vr_auto) {
  381. vr_matches = range == vi.video_range;
  382. } else {
  383. range = static_cast<video_range_type>(capture->requested_video_range);
  384. vr_matches = range == vi.video_range;
  385. full_range = range == VIDEO_RANGE_FULL;
  386. }
  387. if (cs_matches && vr_matches) {
  388. if (!vi.video_params_valid)
  389. capture->video_info.update([&](av_video_info &vi_) {
  390. vi_.video_params_valid = vi.video_params_valid = true;
  391. });
  392. return true;
  393. }
  394. frame->full_range = full_range;
  395. if (!video_format_get_parameters_for_format(colorspace, range, frame->format, frame->color_matrix,
  396. frame->color_range_min, frame->color_range_max)) {
  397. AVLOG(LOG_ERROR,
  398. "Failed to get colorspace parameters for "
  399. "colorspace %u range %u",
  400. colorspace, range);
  401. if (vi.video_params_valid)
  402. capture->video_info.update([&](av_video_info &vi_) {
  403. vi_.video_params_valid = vi.video_params_valid = false;
  404. });
  405. return false;
  406. }
  407. capture->video_info.update([&](av_video_info &vi_) {
  408. vi_.colorspace = colorspace;
  409. vi_.video_range = range;
  410. vi_.video_params_valid = vi.video_params_valid = true;
  411. });
  412. return true;
  413. }
  414. static inline bool update_frame(av_capture *capture, obs_source_frame *frame, CMSampleBufferRef sample_buffer)
  415. {
  416. CMFormatDescriptionRef desc = CMSampleBufferGetFormatDescription(sample_buffer);
  417. FourCharCode fourcc = CMFormatDescriptionGetMediaSubType(desc);
  418. video_format format = format_from_subtype(fourcc);
  419. CMVideoDimensions dims = CMVideoFormatDescriptionGetDimensions(desc);
  420. CVImageBufferRef img = CMSampleBufferGetImageBuffer(sample_buffer);
  421. auto vi = capture->video_info.read();
  422. bool video_params_were_valid = vi.video_params_valid;
  423. SCOPE_EXIT
  424. {
  425. if (video_params_were_valid != vi.video_params_valid)
  426. obs_source_update_properties(capture->source);
  427. };
  428. if (format == VIDEO_FORMAT_NONE) {
  429. if (capture->fourcc == fourcc)
  430. return false;
  431. capture->fourcc = fourcc;
  432. AVLOG(LOG_ERROR, "Unhandled fourcc: %s (0x%x) (%zu planes)", AV_FOURCC_STR(fourcc), fourcc,
  433. CVPixelBufferGetPlaneCount(img));
  434. return false;
  435. }
  436. if (frame->format != format)
  437. AVLOG(LOG_DEBUG,
  438. "Switching fourcc: "
  439. "'%s' (0x%x) -> '%s' (0x%x)",
  440. AV_FOURCC_STR(capture->fourcc), capture->fourcc, AV_FOURCC_STR(fourcc), fourcc);
  441. bool was_yuv = format_is_yuv(frame->format);
  442. capture->fourcc = fourcc;
  443. frame->format = format;
  444. frame->width = dims.width;
  445. frame->height = dims.height;
  446. if (format_is_yuv(format) && !update_colorspace(capture, frame, desc, is_fullrange_yuv(fourcc), vi)) {
  447. return false;
  448. } else if (was_yuv == format_is_yuv(format)) {
  449. capture->video_info.update([&](av_video_info &vi_) {
  450. vi_.video_params_valid = vi.video_params_valid = true;
  451. });
  452. }
  453. CVPixelBufferLockBaseAddress(img, kCVPixelBufferLock_ReadOnly);
  454. if (!CVPixelBufferIsPlanar(img)) {
  455. frame->linesize[0] = (uint32_t) CVPixelBufferGetBytesPerRow(img);
  456. frame->data[0] = static_cast<uint8_t *>(CVPixelBufferGetBaseAddress(img));
  457. return true;
  458. }
  459. size_t count = CVPixelBufferGetPlaneCount(img);
  460. for (size_t i = 0; i < count; i++) {
  461. frame->linesize[i] = (uint32_t) CVPixelBufferGetBytesPerRowOfPlane(img, i);
  462. frame->data[i] = static_cast<uint8_t *>(CVPixelBufferGetBaseAddressOfPlane(img, i));
  463. }
  464. return true;
  465. }
  466. static inline bool update_audio(obs_source_audio *audio, CMSampleBufferRef sample_buffer)
  467. {
  468. size_t requiredSize;
  469. OSStatus status = CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(
  470. sample_buffer, &requiredSize, nullptr, 0, nullptr, nullptr,
  471. kCMSampleBufferFlag_AudioBufferList_Assure16ByteAlignment, nullptr);
  472. if (status != noErr) {
  473. blog(LOG_WARNING, "[mac-avcapture]: Error while getting size of sample buffer");
  474. return false;
  475. }
  476. AudioBufferList *list = (AudioBufferList *) bmalloc(requiredSize);
  477. CMBlockBufferRef buffer;
  478. status = CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(
  479. sample_buffer, nullptr, list, requiredSize, nullptr, nullptr,
  480. kCMSampleBufferFlag_AudioBufferList_Assure16ByteAlignment, &buffer);
  481. if (status != noErr || !list) {
  482. if (list)
  483. bfree(list);
  484. blog(LOG_WARNING, "[mac-avcapture]: Error while copying sample buffer to audio buffer list");
  485. return false;
  486. }
  487. for (size_t i = 0; i < list->mNumberBuffers; i++)
  488. audio->data[i] = (uint8_t *) list->mBuffers[i].mData;
  489. audio->frames = (uint32_t) CMSampleBufferGetNumSamples(sample_buffer);
  490. CMFormatDescriptionRef desc = CMSampleBufferGetFormatDescription(sample_buffer);
  491. const AudioStreamBasicDescription *asbd = CMAudioFormatDescriptionGetStreamBasicDescription(desc);
  492. audio->samples_per_sec = (uint32_t) asbd->mSampleRate;
  493. audio->speakers = (enum speaker_layout) asbd->mChannelsPerFrame;
  494. switch (asbd->mBitsPerChannel) {
  495. case 8:
  496. audio->format = AUDIO_FORMAT_U8BIT;
  497. break;
  498. case 16:
  499. audio->format = AUDIO_FORMAT_16BIT;
  500. break;
  501. case 32:
  502. audio->format = AUDIO_FORMAT_32BIT;
  503. break;
  504. default:
  505. audio->format = AUDIO_FORMAT_UNKNOWN;
  506. }
  507. if (buffer)
  508. CFRelease(buffer);
  509. bfree(list);
  510. return true;
  511. }
  512. @implementation OBSAVCaptureDelegate
  513. - (void)captureOutput:(AVCaptureOutput *)out
  514. didDropSampleBuffer:(CMSampleBufferRef)sampleBuffer
  515. fromConnection:(AVCaptureConnection *)connection
  516. {
  517. UNUSED_PARAMETER(out);
  518. UNUSED_PARAMETER(sampleBuffer);
  519. UNUSED_PARAMETER(connection);
  520. }
  521. - (void)captureOutput:(AVCaptureOutput *)captureOutput
  522. didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer
  523. fromConnection:(AVCaptureConnection *)connection
  524. {
  525. UNUSED_PARAMETER(captureOutput);
  526. UNUSED_PARAMETER(connection);
  527. CMItemCount count = CMSampleBufferGetNumSamples(sampleBuffer);
  528. if (count < 1 || !capture)
  529. return;
  530. CMTime target_pts = CMSampleBufferGetOutputPresentationTimeStamp(sampleBuffer);
  531. CMTime target_pts_nano = CMTimeConvertScale(target_pts, NANO_TIMESCALE, kCMTimeRoundingMethod_Default);
  532. CMFormatDescriptionRef desc = CMSampleBufferGetFormatDescription(sampleBuffer);
  533. CMMediaType type = CMFormatDescriptionGetMediaType(desc);
  534. if (type == kCMMediaType_Video) {
  535. obs_source_frame *frame = &capture->frame;
  536. frame->timestamp = target_pts_nano.value;
  537. if (!update_frame(capture, frame, sampleBuffer)) {
  538. obs_source_output_video(capture->source, nullptr);
  539. return;
  540. }
  541. obs_source_output_video(capture->source, frame);
  542. CVImageBufferRef img = CMSampleBufferGetImageBuffer(sampleBuffer);
  543. CVPixelBufferUnlockBaseAddress(img, kCVPixelBufferLock_ReadOnly);
  544. } else if (type == kCMMediaType_Audio) {
  545. if (!capture->enable_audio)
  546. return;
  547. obs_source_audio *audio = &capture->audio;
  548. audio->timestamp = target_pts_nano.value;
  549. if (!update_audio(audio, sampleBuffer)) {
  550. obs_source_output_audio(capture->source, nullptr);
  551. return;
  552. }
  553. obs_source_output_audio(capture->source, audio);
  554. }
  555. }
  556. @end
  557. static void av_capture_enable_buffering(av_capture *capture, bool enabled)
  558. {
  559. obs_source_set_async_unbuffered(capture->source, !enabled);
  560. }
  561. static const char *av_capture_getname(void *)
  562. {
  563. return TEXT_AVCAPTURE;
  564. }
  565. static void unlock_device(av_capture *capture, AVCaptureDevice *dev = nullptr)
  566. {
  567. if (!dev)
  568. dev = capture->device;
  569. if (dev && capture->device_locked)
  570. [dev unlockForConfiguration];
  571. capture->device_locked = false;
  572. }
  573. static void start_capture(av_capture *capture)
  574. {
  575. if (capture->session && !capture->session.running)
  576. [capture->session startRunning];
  577. }
  578. static void clear_capture(av_capture *capture)
  579. {
  580. if (capture->session && capture->session.running)
  581. [capture->session stopRunning];
  582. obs_source_output_video(capture->source, nullptr);
  583. obs_source_output_audio(capture->source, nullptr);
  584. }
  585. static void remove_device(av_capture *capture)
  586. {
  587. clear_capture(capture);
  588. [capture->session removeInput:capture->device_input];
  589. unlock_device(capture);
  590. capture->device_input = nullptr;
  591. capture->device = nullptr;
  592. }
  593. static void av_capture_destroy(void *data)
  594. {
  595. auto capture = static_cast<av_capture *>(data);
  596. delete capture;
  597. }
  598. static bool init_session(av_capture *capture)
  599. {
  600. auto session = [[AVCaptureSession alloc] init];
  601. if (!session) {
  602. AVLOG(LOG_ERROR, "Could not create AVCaptureSession");
  603. return false;
  604. }
  605. auto delegate = [[OBSAVCaptureDelegate alloc] init];
  606. if (!delegate) {
  607. AVLOG(LOG_ERROR, "Could not create OBSAVCaptureDelegate");
  608. return false;
  609. }
  610. delegate->capture = capture;
  611. auto out = [[AVCaptureVideoDataOutput alloc] init];
  612. if (!out) {
  613. AVLOG(LOG_ERROR, "Could not create AVCaptureVideoDataOutput");
  614. return false;
  615. }
  616. auto audioOut = [[AVCaptureAudioDataOutput alloc] init];
  617. if (!audioOut) {
  618. AVLOG(LOG_ERROR, "Could not create AVCaptureAudioDataOutput");
  619. return false;
  620. }
  621. auto queue = dispatch_queue_create(NULL, NULL);
  622. if (!queue) {
  623. AVLOG(LOG_ERROR, "Could not create dispatch queue");
  624. return false;
  625. }
  626. auto audioQueue = dispatch_queue_create(NULL, NULL);
  627. if (!queue) {
  628. AVLOG(LOG_ERROR, "Could not create dispatch queue for audio");
  629. return false;
  630. }
  631. capture->session = session;
  632. capture->delegate = delegate;
  633. capture->out = out;
  634. capture->audioOut = audioOut;
  635. capture->queue = queue;
  636. capture->audioQueue = audioQueue;
  637. [capture->session addOutput:capture->out];
  638. [capture->out setSampleBufferDelegate:capture->delegate queue:capture->queue];
  639. [capture->session addOutput:capture->audioOut];
  640. [capture->audioOut setSampleBufferDelegate:capture->delegate queue:capture->audioQueue];
  641. return true;
  642. }
  643. static bool init_format(av_capture *capture, AVCaptureDevice *dev);
  644. static bool init_device_input(av_capture *capture, AVCaptureDevice *dev)
  645. {
  646. NSError *err = nil;
  647. AVCaptureDeviceInput *device_input = [AVCaptureDeviceInput deviceInputWithDevice:dev error:&err];
  648. if (!device_input) {
  649. AVLOG(LOG_ERROR, "Error while initializing device input: %s", err.localizedFailureReason.UTF8String);
  650. return false;
  651. }
  652. [capture->session addInput:device_input];
  653. if (!init_format(capture, dev)) {
  654. [capture->session removeInput:device_input];
  655. return false;
  656. }
  657. capture->device_input = device_input;
  658. return true;
  659. }
  660. static uint32_t uint_from_dict(NSDictionary *dict, CFStringRef key)
  661. {
  662. return ((NSNumber *) dict[(__bridge NSString *) key]).unsignedIntValue;
  663. }
  664. static bool init_format(av_capture *capture, AVCaptureDevice *dev)
  665. {
  666. AVCaptureDeviceFormat *format = dev.activeFormat;
  667. CMMediaType mtype = CMFormatDescriptionGetMediaType(format.formatDescription);
  668. // TODO: support other media types
  669. if (mtype != kCMMediaType_Video && mtype != kCMMediaType_Muxed) {
  670. AVLOG(LOG_ERROR, "CMMediaType '%s' is unsupported", AV_FOURCC_STR(mtype));
  671. return false;
  672. }
  673. capture->out.videoSettings = nil;
  674. FourCharCode subtype = uint_from_dict(capture->out.videoSettings, kCVPixelBufferPixelFormatTypeKey);
  675. if (format_from_subtype(subtype) != VIDEO_FORMAT_NONE) {
  676. AVLOG(LOG_DEBUG, "Using native fourcc '%s'", AV_FOURCC_STR(subtype));
  677. return true;
  678. }
  679. AVLOG(LOG_DEBUG, "Using fallback fourcc '%s' ('%s' 0x%08x unsupported)", AV_FOURCC_STR(kCVPixelFormatType_32BGRA),
  680. AV_FOURCC_STR(subtype), subtype);
  681. capture->out.videoSettings =
  682. @{(__bridge NSString *) kCVPixelBufferPixelFormatTypeKey: @(kCVPixelFormatType_32BGRA)};
  683. return true;
  684. }
  685. static NSArray *presets(void);
  686. static NSString *preset_names(NSString *preset);
  687. static NSString *select_preset(AVCaptureDevice *dev, NSString *cur_preset)
  688. {
  689. NSString *new_preset = nil;
  690. bool found_previous_preset = false;
  691. for (NSString *preset in presets().reverseObjectEnumerator) {
  692. if (!found_previous_preset)
  693. found_previous_preset = [cur_preset isEqualToString:preset];
  694. if (![dev supportsAVCaptureSessionPreset:preset])
  695. continue;
  696. if (!new_preset || !found_previous_preset)
  697. new_preset = preset;
  698. }
  699. return new_preset;
  700. }
  701. static bool init_preset(av_capture *capture, AVCaptureDevice *dev, obs_data_t *settings)
  702. {
  703. clear_capture(capture);
  704. unlock_device(capture, dev);
  705. NSString *preset = get_string(settings, "preset");
  706. if (![dev supportsAVCaptureSessionPreset:preset]) {
  707. AVLOG(LOG_WARNING, "Preset %s not available", preset_names(preset).UTF8String);
  708. preset = select_preset(dev, preset);
  709. }
  710. if (!preset) {
  711. AVLOG(LOG_WARNING, "Could not select a preset, "
  712. "initialization failed");
  713. return false;
  714. }
  715. capture->session.sessionPreset = preset;
  716. AVLOG(LOG_INFO, "Using preset %s", preset_names(preset).UTF8String);
  717. return true;
  718. }
  719. static bool operator==(const CMVideoDimensions &a, const CMVideoDimensions &b);
  720. static CMVideoDimensions get_dimensions(AVCaptureDeviceFormat *format);
  721. static AVCaptureDeviceFormat *find_format(AVCaptureDevice *dev, CMVideoDimensions dims)
  722. {
  723. for (AVCaptureDeviceFormat *format in dev.formats) {
  724. if (get_dimensions(format) == dims)
  725. return format;
  726. }
  727. return nullptr;
  728. }
  729. static CMTime convert(media_frames_per_second fps)
  730. {
  731. CMTime time {};
  732. time.value = fps.denominator;
  733. time.timescale = fps.numerator;
  734. time.flags = 1;
  735. return time;
  736. }
  737. static bool lock_device(av_capture *capture, AVCaptureDevice *dev)
  738. {
  739. if (!dev)
  740. dev = capture->device;
  741. NSError *err;
  742. if (![dev lockForConfiguration:&err]) {
  743. AVLOG(LOG_WARNING,
  744. "Could not lock device for configuration: "
  745. "%s",
  746. err.localizedDescription.UTF8String);
  747. return false;
  748. }
  749. capture->device_locked = true;
  750. return true;
  751. }
  752. template<typename Func>
  753. static void find_formats(media_frames_per_second fps, AVCaptureDevice *dev, const CMVideoDimensions *dims, Func &&f)
  754. {
  755. auto time = convert(fps);
  756. for (AVCaptureDeviceFormat *format in dev.formats) {
  757. if (!(get_dimensions(format) == *dims))
  758. continue;
  759. for (AVFrameRateRange *range in format.videoSupportedFrameRateRanges) {
  760. if (CMTimeCompare(range.maxFrameDuration, time) >= 0 && CMTimeCompare(range.minFrameDuration, time) <= 0)
  761. if (f(format))
  762. return;
  763. }
  764. }
  765. }
  766. static bool color_space_valid(int color_space)
  767. {
  768. switch (color_space) {
  769. case COLOR_SPACE_AUTO:
  770. case VIDEO_CS_DEFAULT:
  771. case VIDEO_CS_601:
  772. case VIDEO_CS_709:
  773. return true;
  774. }
  775. return false;
  776. }
  777. static const char *color_space_name(int color_space)
  778. {
  779. switch (color_space) {
  780. case COLOR_SPACE_AUTO:
  781. return "Auto";
  782. case VIDEO_CS_DEFAULT:
  783. return "Default";
  784. case VIDEO_CS_601:
  785. return "CS 601";
  786. case VIDEO_CS_709:
  787. return "CS 709";
  788. }
  789. return "Unknown";
  790. }
  791. static bool video_range_valid(int video_range)
  792. {
  793. switch (video_range) {
  794. case VIDEO_RANGE_AUTO:
  795. case VIDEO_RANGE_DEFAULT:
  796. case VIDEO_RANGE_PARTIAL:
  797. case VIDEO_RANGE_FULL:
  798. return true;
  799. }
  800. return false;
  801. }
  802. static const char *video_range_name(int video_range)
  803. {
  804. switch (video_range) {
  805. case VIDEO_RANGE_AUTO:
  806. return "Auto";
  807. case VIDEO_RANGE_DEFAULT:
  808. return "Default";
  809. case VIDEO_RANGE_PARTIAL:
  810. return "Partial";
  811. case VIDEO_RANGE_FULL:
  812. return "Full";
  813. }
  814. return "Unknown";
  815. }
  816. static bool init_manual(av_capture *capture, AVCaptureDevice *dev, obs_data_t *settings)
  817. {
  818. clear_capture(capture);
  819. auto input_format = obs_data_get_int(settings, "input_format");
  820. FourCharCode actual_format = (FourCharCode) input_format;
  821. SCOPE_EXIT
  822. {
  823. bool refresh = false;
  824. if (input_format != actual_format) {
  825. refresh = obs_data_get_autoselect_int(settings, "input_format") != actual_format;
  826. obs_data_set_autoselect_int(settings, "input_format", actual_format);
  827. } else {
  828. refresh = obs_data_has_autoselect_value(settings, "input_format");
  829. obs_data_unset_autoselect_value(settings, "input_format");
  830. }
  831. if (refresh)
  832. obs_source_update_properties(capture->source);
  833. };
  834. capture->requested_colorspace = (int) obs_data_get_int(settings, "color_space");
  835. if (!color_space_valid(capture->requested_colorspace)) {
  836. AVLOG(LOG_WARNING, "Unsupported color space: %d", capture->requested_colorspace);
  837. return false;
  838. }
  839. capture->requested_video_range = (int) obs_data_get_int(settings, "video_range");
  840. if (!video_range_valid(capture->requested_video_range)) {
  841. AVLOG(LOG_WARNING, "Unsupported color range: %d", capture->requested_video_range);
  842. return false;
  843. }
  844. CMVideoDimensions dims {};
  845. if (!get_resolution(settings, dims)) {
  846. AVLOG(LOG_WARNING, "Could not load resolution");
  847. return false;
  848. }
  849. media_frames_per_second fps {};
  850. if (!obs_data_get_frames_per_second(settings, "frame_rate", &fps, nullptr)) {
  851. AVLOG(LOG_WARNING, "Could not load frame rate");
  852. return false;
  853. }
  854. AVCaptureDeviceFormat *format = nullptr;
  855. find_formats(fps, dev, &dims, [&](AVCaptureDeviceFormat *format_) {
  856. auto desc = format_.formatDescription;
  857. auto fourcc = CMFormatDescriptionGetMediaSubType(desc);
  858. if (input_format != INPUT_FORMAT_AUTO && fourcc != input_format)
  859. return false;
  860. actual_format = fourcc;
  861. format = format_;
  862. return true;
  863. });
  864. if (!format) {
  865. AVLOG(LOG_WARNING,
  866. "Frame rate is not supported: %g FPS "
  867. "(%u/%u)",
  868. media_frames_per_second_to_fps(fps), fps.numerator, fps.denominator);
  869. return false;
  870. }
  871. if (!lock_device(capture, dev))
  872. return false;
  873. const char *if_name = input_format == INPUT_FORMAT_AUTO ? "Auto" : fourcc_subtype_name((FourCharCode) input_format);
  874. #define IF_AUTO(x) (input_format != INPUT_FORMAT_AUTO ? "" : x)
  875. AVLOG(LOG_INFO,
  876. "Capturing '%s' (%s):\n"
  877. " Resolution: %ux%u\n"
  878. " FPS: %g (%" PRIu32 "/%" PRIu32 ")\n"
  879. " Frame interval: %g" NBSP "s\n"
  880. " Input format: %s%s%s (%s)%s\n"
  881. " Requested color space: %s (%d)\n"
  882. " Requested video range: %s (%d)\n"
  883. " Using format: %s",
  884. dev.localizedName.UTF8String, dev.uniqueID.UTF8String, dims.width, dims.height,
  885. media_frames_per_second_to_fps(fps), fps.numerator, fps.denominator,
  886. media_frames_per_second_to_frame_interval(fps), if_name, IF_AUTO(" (actual: "),
  887. IF_AUTO(fourcc_subtype_name(actual_format)), AV_FOURCC_STR(actual_format), IF_AUTO(")"),
  888. color_space_name(capture->requested_colorspace), capture->requested_colorspace,
  889. video_range_name(capture->requested_video_range), capture->requested_video_range,
  890. format.description.UTF8String);
  891. #undef IF_AUTO
  892. dev.activeFormat = format;
  893. dev.activeVideoMinFrameDuration = convert(fps);
  894. dev.activeVideoMaxFrameDuration = convert(fps);
  895. capture->video_info.update([&](av_video_info &vi) {
  896. vi.video_params_valid = false;
  897. });
  898. return true;
  899. }
  900. static inline void av_capture_set_audio_active(av_capture *capture, bool active)
  901. {
  902. obs_source_set_audio_active(capture->source, active);
  903. capture->enable_audio = active;
  904. }
  905. static void capture_device(av_capture *capture, AVCaptureDevice *dev, obs_data_t *settings)
  906. {
  907. const char *name = dev.localizedName.UTF8String;
  908. obs_data_set_string(settings, "device_name", name);
  909. obs_data_set_string(settings, "device", dev.uniqueID.UTF8String);
  910. AVLOG(LOG_INFO, "Selected device '%s'", name);
  911. if ((capture->use_preset = obs_data_get_bool(settings, "use_preset"))) {
  912. if (!init_preset(capture, dev, settings))
  913. return;
  914. } else {
  915. if (!init_manual(capture, dev, settings))
  916. return;
  917. }
  918. av_capture_set_audio_active(capture,
  919. obs_data_get_bool(settings, "enable_audio") &&
  920. ([dev hasMediaType:AVMediaTypeAudio] || [dev hasMediaType:AVMediaTypeMuxed]));
  921. if (!init_device_input(capture, dev))
  922. return;
  923. AVCaptureInputPort *port = capture->device_input.ports[0];
  924. capture->has_clock = [port respondsToSelector:@selector(clock)];
  925. capture->device = dev;
  926. start_capture(capture);
  927. return;
  928. }
  929. static inline void handle_disconnect_capture(av_capture *capture, AVCaptureDevice *dev)
  930. {
  931. if (![dev.uniqueID isEqualTo:capture->uid])
  932. return;
  933. if (!capture->device) {
  934. AVLOG(LOG_INFO, "Received disconnect for inactive device '%s'", capture->uid.UTF8String);
  935. return;
  936. }
  937. AVLOG(LOG_WARNING, "Device with unique ID '%s' disconnected", dev.uniqueID.UTF8String);
  938. remove_device(capture);
  939. }
  940. static inline void handle_disconnect(av_capture *capture, AVCaptureDevice *dev)
  941. {
  942. if (!dev)
  943. return;
  944. handle_disconnect_capture(capture, dev);
  945. obs_source_update_properties(capture->source);
  946. }
  947. static inline void handle_connect_capture(av_capture *capture, AVCaptureDevice *dev, obs_data_t *settings)
  948. {
  949. if (![dev.uniqueID isEqualTo:capture->uid])
  950. return;
  951. if (capture->device) {
  952. AVLOG(LOG_ERROR, "Received connect for in-use device '%s'", capture->uid.UTF8String);
  953. return;
  954. }
  955. AVLOG(LOG_INFO,
  956. "Device with unique ID '%s' connected, "
  957. "resuming capture",
  958. dev.uniqueID.UTF8String);
  959. capture_device(capture, dev, settings);
  960. }
  961. static inline void handle_connect(av_capture *capture, AVCaptureDevice *dev, obs_data_t *settings)
  962. {
  963. if (!dev)
  964. return;
  965. handle_connect_capture(capture, dev, settings);
  966. obs_source_update_properties(capture->source);
  967. }
  968. static bool av_capture_init(av_capture *capture, obs_data_t *settings)
  969. {
  970. if (!init_session(capture))
  971. return false;
  972. capture->uid = get_string(settings, "device");
  973. NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
  974. capture->disconnect_observer.reset([nc addObserverForName:AVCaptureDeviceWasDisconnectedNotification object:nil
  975. queue:[NSOperationQueue mainQueue]
  976. usingBlock:^(NSNotification *note) {
  977. handle_disconnect(capture, note.object);
  978. }]);
  979. capture->connect_observer.reset([nc addObserverForName:AVCaptureDeviceWasConnectedNotification object:nil
  980. queue:[NSOperationQueue mainQueue]
  981. usingBlock:^(NSNotification *note) {
  982. handle_connect(capture, note.object, settings);
  983. }]);
  984. AVCaptureDevice *dev = [AVCaptureDevice deviceWithUniqueID:capture->uid];
  985. if (!dev) {
  986. if (capture->uid.length < 1)
  987. AVLOG(LOG_INFO, "No device selected");
  988. else
  989. AVLOG(LOG_WARNING,
  990. "Could not initialize device "
  991. "with unique ID '%s'",
  992. capture->uid.UTF8String);
  993. return true;
  994. }
  995. capture_device(capture, dev, settings);
  996. return true;
  997. }
  998. static void *av_capture_create(obs_data_t *settings, obs_source_t *source)
  999. {
  1000. unique_ptr<av_capture> capture;
  1001. try {
  1002. capture.reset(new av_capture());
  1003. } catch (...) {
  1004. return capture.release();
  1005. }
  1006. capture->source = source;
  1007. if (!av_capture_init(capture.get(), settings)) {
  1008. AVLOG(LOG_ERROR, "av_capture_init failed");
  1009. return nullptr;
  1010. }
  1011. av_capture_enable_buffering(capture.get(), obs_data_get_bool(settings, "buffering"));
  1012. return capture.release();
  1013. }
  1014. static NSArray *presets(void)
  1015. {
  1016. return @[
  1017. //AVCaptureSessionPresetiFrame1280x720,
  1018. //AVCaptureSessionPresetiFrame960x540,
  1019. AVCaptureSessionPreset3840x2160, AVCaptureSessionPreset1920x1080, AVCaptureSessionPreset1280x720,
  1020. AVCaptureSessionPreset960x540, AVCaptureSessionPreset640x480, AVCaptureSessionPreset352x288,
  1021. AVCaptureSessionPreset320x240, AVCaptureSessionPresetHigh,
  1022. //AVCaptureSessionPresetMedium,
  1023. //AVCaptureSessionPresetLow,
  1024. //AVCaptureSessionPresetPhoto,
  1025. ];
  1026. }
  1027. static NSString *preset_names(NSString *preset)
  1028. {
  1029. NSDictionary *preset_names = nil;
  1030. preset_names = @ {
  1031. AVCaptureSessionPresetLow: @"Low",
  1032. AVCaptureSessionPresetMedium: @"Medium",
  1033. AVCaptureSessionPresetHigh: @"High",
  1034. AVCaptureSessionPreset320x240: @"320x240",
  1035. AVCaptureSessionPreset352x288: @"352x288",
  1036. AVCaptureSessionPreset640x480: @"640x480",
  1037. AVCaptureSessionPreset960x540: @"960x540",
  1038. AVCaptureSessionPreset1280x720: @"1280x720",
  1039. AVCaptureSessionPreset1920x1080: @"1920x1080",
  1040. AVCaptureSessionPreset3840x2160: @"3840x2160",
  1041. AVCaptureSessionPresetHigh: @"High",
  1042. };
  1043. NSString *name = preset_names[preset];
  1044. if (name)
  1045. return name;
  1046. return [NSString stringWithFormat:@"Unknown (%@)", preset];
  1047. }
  1048. inline static void av_capture_defaults(obs_data_t *settings, bool enable_audio_and_high_preset)
  1049. {
  1050. obs_data_set_default_string(settings, "uid", "");
  1051. obs_data_set_default_bool(settings, "use_preset", true);
  1052. obs_data_set_default_string(settings, "preset",
  1053. enable_audio_and_high_preset ? AVCaptureSessionPresetHigh.UTF8String
  1054. : AVCaptureSessionPreset1280x720.UTF8String);
  1055. obs_data_set_default_int(settings, "input_format", INPUT_FORMAT_AUTO);
  1056. obs_data_set_default_int(settings, "color_space", COLOR_SPACE_AUTO);
  1057. obs_data_set_default_int(settings, "video_range", VIDEO_RANGE_AUTO);
  1058. obs_data_set_default_bool(settings, "enable_audio", enable_audio_and_high_preset);
  1059. }
  1060. static void av_capture_defaults_v1(obs_data_t *settings)
  1061. {
  1062. av_capture_defaults(settings, false);
  1063. }
  1064. static void av_capture_defaults_v2(obs_data_t *settings)
  1065. {
  1066. av_capture_defaults(settings, true);
  1067. }
  1068. static bool update_device_list(obs_property_t *list, NSString *uid, NSString *name, bool disconnected)
  1069. {
  1070. bool dev_found = false;
  1071. bool list_modified = false;
  1072. size_t size = obs_property_list_item_count(list);
  1073. for (size_t i = 0; i < size;) {
  1074. const char *uid_ = obs_property_list_item_string(list, i);
  1075. bool found = [uid isEqualToString:@(uid_ ? uid_ : "")];
  1076. bool disabled = obs_property_list_item_disabled(list, i);
  1077. if (!found && !disabled) {
  1078. i += 1;
  1079. continue;
  1080. }
  1081. if (disabled && !found) {
  1082. list_modified = true;
  1083. obs_property_list_item_remove(list, i);
  1084. continue;
  1085. }
  1086. if (disabled != disconnected)
  1087. list_modified = true;
  1088. dev_found = true;
  1089. obs_property_list_item_disable(list, i, disconnected);
  1090. i += 1;
  1091. }
  1092. if (dev_found)
  1093. return list_modified;
  1094. size_t idx = obs_property_list_add_string(list, name.UTF8String, uid.UTF8String);
  1095. obs_property_list_item_disable(list, idx, disconnected);
  1096. return true;
  1097. }
  1098. static void fill_presets(AVCaptureDevice *dev, obs_property_t *list, NSString *current_preset)
  1099. {
  1100. obs_property_list_clear(list);
  1101. bool preset_found = false;
  1102. for (NSString *preset in presets()) {
  1103. bool is_current = [preset isEqualToString:current_preset];
  1104. bool supported = dev && [dev supportsAVCaptureSessionPreset:preset];
  1105. if (is_current)
  1106. preset_found = true;
  1107. if (!supported && !is_current)
  1108. continue;
  1109. size_t idx = obs_property_list_add_string(list, preset_names(preset).UTF8String, preset.UTF8String);
  1110. obs_property_list_item_disable(list, idx, !supported);
  1111. }
  1112. if (preset_found)
  1113. return;
  1114. size_t idx = obs_property_list_add_string(list, preset_names(current_preset).UTF8String, current_preset.UTF8String);
  1115. obs_property_list_item_disable(list, idx, true);
  1116. }
  1117. static bool check_preset(AVCaptureDevice *dev, obs_property_t *list, obs_data_t *settings)
  1118. {
  1119. NSString *current_preset = get_string(settings, "preset");
  1120. size_t size = obs_property_list_item_count(list);
  1121. NSMutableSet *listed = [NSMutableSet setWithCapacity:size];
  1122. for (size_t i = 0; i < size; i++)
  1123. [listed addObject:@(obs_property_list_item_string(list, i))];
  1124. bool presets_changed = false;
  1125. for (NSString *preset in presets()) {
  1126. bool is_listed = [listed member:preset] != nil;
  1127. bool supported = dev && [dev supportsAVCaptureSessionPreset:preset];
  1128. if (supported == is_listed)
  1129. continue;
  1130. presets_changed = true;
  1131. }
  1132. if (!presets_changed && [listed member:current_preset] != nil)
  1133. return false;
  1134. fill_presets(dev, list, current_preset);
  1135. return true;
  1136. }
  1137. static bool autoselect_preset(AVCaptureDevice *dev, obs_data_t *settings)
  1138. {
  1139. NSString *preset = get_string(settings, "preset");
  1140. if (!dev || [dev supportsAVCaptureSessionPreset:preset]) {
  1141. if (obs_data_has_autoselect_value(settings, "preset")) {
  1142. obs_data_unset_autoselect_value(settings, "preset");
  1143. return true;
  1144. }
  1145. } else {
  1146. preset = select_preset(dev, preset);
  1147. const char *autoselect = obs_data_get_autoselect_string(settings, "preset");
  1148. if (![preset isEqualToString:@(autoselect)]) {
  1149. obs_data_set_autoselect_string(settings, "preset", preset.UTF8String);
  1150. return true;
  1151. }
  1152. }
  1153. return false;
  1154. }
  1155. static CMVideoDimensions get_dimensions(AVCaptureDeviceFormat *format)
  1156. {
  1157. auto desc = format.formatDescription;
  1158. return CMVideoFormatDescriptionGetDimensions(desc);
  1159. }
  1160. using resolutions_t = vector<CMVideoDimensions>;
  1161. static resolutions_t enumerate_resolutions(AVCaptureDevice *dev)
  1162. {
  1163. resolutions_t res;
  1164. if (!dev)
  1165. return res;
  1166. res.reserve(dev.formats.count + 1);
  1167. for (AVCaptureDeviceFormat *format in dev.formats) {
  1168. auto dims = get_dimensions(format);
  1169. if (find(begin(res), end(res), dims) == end(res))
  1170. res.push_back(dims);
  1171. }
  1172. return res;
  1173. }
  1174. static void sort_resolutions(vector<CMVideoDimensions> &resolutions)
  1175. {
  1176. auto cmp = [](const CMVideoDimensions &a, const CMVideoDimensions &b) {
  1177. return a.width * a.height > b.width * b.height;
  1178. };
  1179. sort(begin(resolutions), end(resolutions), cmp);
  1180. }
  1181. static void data_set_resolution(obs_data_t *data, const CMVideoDimensions &dims)
  1182. {
  1183. obs_data_set_int(data, "width", dims.width);
  1184. obs_data_set_int(data, "height", dims.height);
  1185. }
  1186. static void data_set_resolution(const unique_ptr<obs_data_t> &data, const CMVideoDimensions &dims)
  1187. {
  1188. data_set_resolution(data.get(), dims);
  1189. }
  1190. static bool add_resolution_to_list(vector<CMVideoDimensions> &res, const CMVideoDimensions &dims)
  1191. {
  1192. if (find(begin(res), end(res), dims) != end(res))
  1193. return false;
  1194. res.push_back(dims);
  1195. return true;
  1196. }
  1197. static const char *obs_data_get_json(const unique_ptr<obs_data_t> &data)
  1198. {
  1199. return obs_data_get_json(data.get());
  1200. }
  1201. static bool operator==(const CMVideoDimensions &a, const CMVideoDimensions &b)
  1202. {
  1203. return a.width == b.width && a.height == b.height;
  1204. }
  1205. static bool resolution_property_needs_update(obs_property_t *p, const resolutions_t &resolutions)
  1206. {
  1207. vector<bool> res_found(resolutions.size());
  1208. auto num = obs_property_list_item_count(p);
  1209. for (size_t i = 1; i < num; i++) { // skip empty entry
  1210. const char *json = obs_property_list_item_string(p, i);
  1211. unique_ptr<obs_data_t> buffer {obs_data_create_from_json(json)};
  1212. CMVideoDimensions dims {};
  1213. if (!get_resolution(buffer.get(), dims))
  1214. return true;
  1215. auto pos = find(begin(resolutions), end(resolutions), dims);
  1216. if (pos == end(resolutions))
  1217. return true;
  1218. res_found[pos - begin(resolutions)] = true;
  1219. }
  1220. return any_of(begin(res_found), end(res_found), [](bool b) {
  1221. return !b;
  1222. });
  1223. }
  1224. static bool update_resolution_property(obs_properties_t *props, const config_helper &conf, obs_property_t *p = nullptr)
  1225. {
  1226. if (!p)
  1227. p = obs_properties_get(props, "resolution");
  1228. if (!p)
  1229. return false;
  1230. auto valid_dims = conf.dims();
  1231. auto resolutions = enumerate_resolutions(conf.dev());
  1232. bool unsupported = true;
  1233. if (valid_dims)
  1234. unsupported = add_resolution_to_list(resolutions, *valid_dims);
  1235. bool was_enabled = obs_property_enabled(p);
  1236. obs_property_set_enabled(p, !!conf.dev());
  1237. if (!resolution_property_needs_update(p, resolutions))
  1238. return was_enabled != obs_property_enabled(p);
  1239. sort_resolutions(resolutions);
  1240. obs_property_list_clear(p);
  1241. obs_property_list_add_string(p, "", "{}");
  1242. DStr name;
  1243. unique_ptr<obs_data_t> buffer {obs_data_create()};
  1244. for (const CMVideoDimensions &dims : resolutions) {
  1245. data_set_resolution(buffer, dims);
  1246. auto json = obs_data_get_json(buffer);
  1247. dstr_printf(name, "%dx%d", dims.width, dims.height);
  1248. size_t idx = obs_property_list_add_string(p, name->array, json);
  1249. if (unsupported && valid_dims && dims == *valid_dims)
  1250. obs_property_list_item_disable(p, idx, true);
  1251. }
  1252. return true;
  1253. }
  1254. static media_frames_per_second convert(CMTime time_)
  1255. {
  1256. media_frames_per_second res {};
  1257. clamp(res.numerator, time_.timescale);
  1258. clamp(res.denominator, time_.value);
  1259. return res;
  1260. }
  1261. using frame_rates_t = vector<pair<media_frames_per_second, media_frames_per_second>>;
  1262. static frame_rates_t enumerate_frame_rates(AVCaptureDevice *dev, const CMVideoDimensions *dims = nullptr)
  1263. {
  1264. frame_rates_t res;
  1265. if (!dev || !dims)
  1266. return res;
  1267. auto add_unique_frame_rate_range = [&](AVFrameRateRange *range) {
  1268. auto min = convert(range.maxFrameDuration);
  1269. auto max = convert(range.minFrameDuration);
  1270. auto pair = make_pair(min, max);
  1271. if (find(begin(res), end(res), pair) != end(res))
  1272. return;
  1273. res.push_back(pair);
  1274. };
  1275. for (AVCaptureDeviceFormat *format in dev.formats) {
  1276. if (!(get_dimensions(format) == *dims))
  1277. continue;
  1278. for (AVFrameRateRange *range in format.videoSupportedFrameRateRanges) {
  1279. add_unique_frame_rate_range(range);
  1280. if (CMTimeCompare(range.minFrameDuration, range.maxFrameDuration) != 0) {
  1281. blog(LOG_WARNING,
  1282. "Got actual frame rate range:"
  1283. " %g - %g "
  1284. "({%lld, %d} - {%lld, %d})",
  1285. range.minFrameRate, range.maxFrameRate, range.maxFrameDuration.value,
  1286. range.maxFrameDuration.timescale, range.minFrameDuration.value, range.minFrameDuration.timescale);
  1287. }
  1288. }
  1289. }
  1290. return res;
  1291. }
  1292. static bool operator==(const media_frames_per_second &a, const media_frames_per_second &b)
  1293. {
  1294. return a.numerator == b.numerator && a.denominator == b.denominator;
  1295. }
  1296. static bool operator!=(const media_frames_per_second &a, const media_frames_per_second &b)
  1297. {
  1298. return !(a == b);
  1299. }
  1300. static bool frame_rate_property_needs_update(obs_property_t *p, const frame_rates_t &frame_rates)
  1301. {
  1302. auto fps_num = frame_rates.size();
  1303. auto num = obs_property_frame_rate_fps_ranges_count(p);
  1304. if (fps_num != num)
  1305. return true;
  1306. vector<bool> fps_found(fps_num);
  1307. for (size_t i = 0; i < num; i++) {
  1308. auto min_ = obs_property_frame_rate_fps_range_min(p, i);
  1309. auto max_ = obs_property_frame_rate_fps_range_max(p, i);
  1310. auto it = find(begin(frame_rates), end(frame_rates), make_pair(min_, max_));
  1311. if (it == end(frame_rates))
  1312. return true;
  1313. fps_found[it - begin(frame_rates)] = true;
  1314. }
  1315. return any_of(begin(fps_found), end(fps_found), [](bool b) {
  1316. return !b;
  1317. });
  1318. }
  1319. static bool update_frame_rate_property(obs_properties_t *props, const config_helper &conf, obs_property_t *p = nullptr)
  1320. {
  1321. if (!p)
  1322. p = obs_properties_get(props, "frame_rate");
  1323. if (!p)
  1324. return false;
  1325. auto valid_dims = conf.dims();
  1326. auto frame_rates = enumerate_frame_rates(conf.dev(), valid_dims);
  1327. bool was_enabled = obs_property_enabled(p);
  1328. obs_property_set_enabled(p, !frame_rates.empty());
  1329. if (!frame_rate_property_needs_update(p, frame_rates))
  1330. return was_enabled != obs_property_enabled(p);
  1331. obs_property_frame_rate_fps_ranges_clear(p);
  1332. for (auto &pair : frame_rates)
  1333. obs_property_frame_rate_fps_range_add(p, pair.first, pair.second);
  1334. return true;
  1335. }
  1336. static vector<AVCaptureDeviceFormat *> enumerate_formats(AVCaptureDevice *dev, const CMVideoDimensions &dims,
  1337. const media_frames_per_second &fps)
  1338. {
  1339. vector<AVCaptureDeviceFormat *> result;
  1340. find_formats(fps, dev, &dims, [&](AVCaptureDeviceFormat *format) {
  1341. result.push_back(format);
  1342. return false;
  1343. });
  1344. return result;
  1345. }
  1346. static bool input_format_property_needs_update(obs_property_t *p, const vector<AVCaptureDeviceFormat *> &formats,
  1347. const FourCharCode *fourcc_)
  1348. {
  1349. bool fourcc_found = !fourcc_;
  1350. vector<bool> if_found(formats.size());
  1351. auto num = obs_property_list_item_count(p);
  1352. for (size_t i = 1; i < num; i++) { // skip auto entry
  1353. FourCharCode fourcc = (FourCharCode) obs_property_list_item_int(p, i);
  1354. fourcc_found = fourcc_found || fourcc == *fourcc_;
  1355. auto pos = find_if(begin(formats), end(formats), [&](AVCaptureDeviceFormat *format) {
  1356. FourCharCode fourcc_ = 0;
  1357. format_description_subtype_name(format.formatDescription, &fourcc_);
  1358. return fourcc_ == fourcc;
  1359. });
  1360. if (pos == end(formats))
  1361. return true;
  1362. if_found[pos - begin(formats)] = true;
  1363. }
  1364. return fourcc_found || any_of(begin(if_found), end(if_found), [](bool b) {
  1365. return !b;
  1366. });
  1367. }
  1368. static bool update_input_format_property(obs_properties_t *props, const config_helper &conf,
  1369. obs_property_t *p = nullptr)
  1370. {
  1371. if (!p)
  1372. p = obs_properties_get(props, "input_format");
  1373. if (!p)
  1374. return false;
  1375. auto update_enabled = [&](bool enabled) {
  1376. bool was_enabled = obs_property_enabled(p);
  1377. obs_property_set_enabled(p, enabled);
  1378. return was_enabled != enabled;
  1379. };
  1380. auto valid_dims = conf.dims();
  1381. auto valid_fps = conf.fps();
  1382. auto valid_if = conf.input_format();
  1383. if (!valid_dims || !valid_fps)
  1384. return update_enabled(false);
  1385. auto formats = enumerate_formats(conf.dev(), *valid_dims, *valid_fps);
  1386. if (!input_format_property_needs_update(p, formats, valid_if))
  1387. return update_enabled(!formats.empty());
  1388. while (obs_property_list_item_count(p) > 1)
  1389. obs_property_list_item_remove(p, 1);
  1390. bool fourcc_found = !valid_if || *valid_if == INPUT_FORMAT_AUTO;
  1391. for (auto &format : formats) {
  1392. FourCharCode fourcc = 0;
  1393. const char *name = format_description_subtype_name(format.formatDescription, &fourcc);
  1394. obs_property_list_add_int(p, name, fourcc);
  1395. fourcc_found = fourcc_found || fourcc == *valid_if;
  1396. }
  1397. if (!fourcc_found) {
  1398. const char *name = fourcc_subtype_name(*valid_if);
  1399. obs_property_list_add_int(p, name, *valid_if);
  1400. }
  1401. return update_enabled(!formats.empty());
  1402. }
  1403. static bool update_int_list_property(obs_property_t *p, const int *val, const size_t count,
  1404. const char *localization_name)
  1405. {
  1406. size_t num = obs_property_list_item_count(p);
  1407. if (num > count) {
  1408. if (!val || obs_property_list_item_int(p, count) != *val) {
  1409. obs_property_list_item_remove(p, count);
  1410. if (!val)
  1411. return true;
  1412. } else {
  1413. return false;
  1414. }
  1415. }
  1416. if (!val)
  1417. return false;
  1418. DStr buf, label;
  1419. dstr_printf(buf, "%d", *val);
  1420. dstr_init_copy(label, obs_module_text(localization_name));
  1421. dstr_replace(label, "%1", buf->array);
  1422. size_t idx = obs_property_list_add_int(p, label->array, *val);
  1423. obs_property_list_item_disable(p, idx, true);
  1424. return true;
  1425. }
  1426. template<typename Func>
  1427. static bool update_int_list_property(const char *prop_name, const char *localization_name, size_t count, int auto_val,
  1428. bool (*valid_func)(int), obs_properties_t *props, const config_helper &conf,
  1429. obs_property_t *p, Func get_val)
  1430. {
  1431. auto ref = get_ref(props);
  1432. if (!p)
  1433. p = obs_properties_get(props, prop_name);
  1434. int val = (int) obs_data_get_int(conf.settings, prop_name);
  1435. av_video_info vi;
  1436. if (ref)
  1437. vi = ref->video_info.read();
  1438. bool params_valid = vi.video_params_valid;
  1439. bool enabled = obs_property_enabled(p);
  1440. bool should_enable = false;
  1441. bool has_autoselect = obs_data_has_autoselect_value(conf.settings, prop_name);
  1442. if ((params_valid && format_is_yuv(ref->frame.format)) || !valid_func(val))
  1443. should_enable = true;
  1444. obs_property_set_enabled(p, should_enable);
  1445. bool updated = enabled != should_enable;
  1446. updated = update_int_list_property(p, valid_func(val) ? nullptr : &val, count, localization_name) || updated;
  1447. if (!should_enable) {
  1448. if (has_autoselect)
  1449. obs_data_unset_autoselect_value(conf.settings, prop_name);
  1450. return updated || has_autoselect;
  1451. }
  1452. bool use_autoselect = ref && val == auto_val;
  1453. if (!use_autoselect) {
  1454. if (has_autoselect)
  1455. obs_data_unset_autoselect_value(conf.settings, prop_name);
  1456. return updated || has_autoselect;
  1457. }
  1458. if (params_valid && get_val(vi) != obs_data_get_autoselect_int(conf.settings, prop_name)) {
  1459. obs_data_set_autoselect_int(conf.settings, prop_name, get_val(vi));
  1460. return true;
  1461. }
  1462. return updated;
  1463. }
  1464. static bool update_color_space_property(obs_properties_t *props, const config_helper &conf, obs_property_t *p = nullptr)
  1465. {
  1466. return update_int_list_property("color_space", TEXT_COLOR_UNKNOWN_NAME, 4, COLOR_SPACE_AUTO, color_space_valid,
  1467. props, conf, p, [](av_video_info vi) {
  1468. return vi.colorspace;
  1469. });
  1470. }
  1471. static bool update_video_range_property(obs_properties_t *props, const config_helper &conf, obs_property_t *p = nullptr)
  1472. {
  1473. return update_int_list_property("video_range", TEXT_RANGE_UNKNOWN_NAME, 5, VIDEO_RANGE_AUTO, video_range_valid,
  1474. props, conf, p, [](av_video_info vi) {
  1475. return vi.video_range;
  1476. });
  1477. }
  1478. static bool properties_device_changed(obs_properties_t *props, obs_property_t *p, obs_data_t *settings)
  1479. {
  1480. NSString *uid = get_string(settings, "device");
  1481. AVCaptureDevice *dev = [AVCaptureDevice deviceWithUniqueID:uid];
  1482. NSString *name = get_string(settings, "device_name");
  1483. bool dev_list_updated = update_device_list(p, uid, name, !dev && uid.length);
  1484. p = obs_properties_get(props, "preset");
  1485. bool preset_list_changed = check_preset(dev, p, settings);
  1486. bool autoselect_changed = autoselect_preset(dev, settings);
  1487. config_helper conf {settings};
  1488. bool res_changed = update_resolution_property(props, conf);
  1489. bool fps_changed = update_frame_rate_property(props, conf);
  1490. bool if_changed = update_input_format_property(props, conf);
  1491. return preset_list_changed || autoselect_changed || dev_list_updated || res_changed || fps_changed || if_changed;
  1492. }
  1493. static bool properties_use_preset_changed(obs_properties_t *props, obs_property_t *, obs_data_t *settings)
  1494. {
  1495. auto use_preset = obs_data_get_bool(settings, "use_preset");
  1496. config_helper conf {settings};
  1497. bool updated = false;
  1498. bool visible = false;
  1499. obs_property_t *p = nullptr;
  1500. auto noop = [](obs_properties_t *, const config_helper &, obs_property_t *) {
  1501. return false;
  1502. };
  1503. #define UPDATE_PROPERTY(prop, uses_preset, func) \
  1504. p = obs_properties_get(props, prop); \
  1505. visible = use_preset == uses_preset; \
  1506. updated = obs_property_visible(p) != visible || updated; \
  1507. obs_property_set_visible(p, visible); \
  1508. updated = func(props, conf, p) || updated;
  1509. UPDATE_PROPERTY("preset", true, noop);
  1510. UPDATE_PROPERTY("resolution", false, update_resolution_property);
  1511. UPDATE_PROPERTY("frame_rate", false, update_frame_rate_property);
  1512. UPDATE_PROPERTY("input_format", false, update_input_format_property);
  1513. UPDATE_PROPERTY("color_space", false, update_color_space_property);
  1514. UPDATE_PROPERTY("video_range", false, update_video_range_property);
  1515. return updated;
  1516. }
  1517. static bool properties_preset_changed(obs_properties_t *, obs_property_t *p, obs_data_t *settings)
  1518. {
  1519. NSString *uid = get_string(settings, "device");
  1520. AVCaptureDevice *dev = [AVCaptureDevice deviceWithUniqueID:uid];
  1521. bool preset_list_changed = check_preset(dev, p, settings);
  1522. bool autoselect_changed = autoselect_preset(dev, settings);
  1523. return preset_list_changed || autoselect_changed;
  1524. }
  1525. static bool properties_resolution_changed(obs_properties_t *props, obs_property_t *p, obs_data_t *settings)
  1526. {
  1527. config_helper conf {settings};
  1528. bool res_updated = update_resolution_property(props, conf, p);
  1529. bool fps_updated = update_frame_rate_property(props, conf);
  1530. bool if_updated = update_input_format_property(props, conf);
  1531. bool cs_updated = update_color_space_property(props, conf);
  1532. bool cr_updated = update_video_range_property(props, conf);
  1533. return res_updated || fps_updated || if_updated || cs_updated || cr_updated;
  1534. }
  1535. static bool properties_frame_rate_changed(obs_properties_t *props, obs_property_t *p, obs_data_t *settings)
  1536. {
  1537. config_helper conf {settings};
  1538. bool fps_updated = update_frame_rate_property(props, conf, p);
  1539. bool if_updated = update_input_format_property(props, conf);
  1540. bool cs_updated = update_color_space_property(props, conf);
  1541. bool cr_updated = update_video_range_property(props, conf);
  1542. return fps_updated || if_updated || cs_updated || cr_updated;
  1543. }
  1544. static bool properties_input_format_changed(obs_properties_t *props, obs_property_t *p, obs_data_t *settings)
  1545. {
  1546. config_helper conf {settings};
  1547. bool if_updated = update_input_format_property(props, conf, p);
  1548. bool cs_updated = update_color_space_property(props, conf);
  1549. bool cr_updated = update_video_range_property(props, conf);
  1550. return if_updated || cs_updated || cr_updated;
  1551. }
  1552. static bool properties_color_space_changed(obs_properties_t *props, obs_property_t *p, obs_data_t *settings)
  1553. {
  1554. config_helper conf {settings};
  1555. return update_color_space_property(props, conf, p);
  1556. }
  1557. static bool properties_video_range_changed(obs_properties_t *props, obs_property_t *p, obs_data_t *settings)
  1558. {
  1559. config_helper conf {settings};
  1560. return update_video_range_property(props, conf, p);
  1561. }
  1562. static void add_properties_param(obs_properties_t *props, av_capture *capture)
  1563. {
  1564. auto param = unique_ptr<properties_param>(new properties_param(capture));
  1565. obs_properties_set_param(props, param.release(), [](void *param) {
  1566. delete static_cast<properties_param *>(param);
  1567. });
  1568. }
  1569. static void add_preset_properties(obs_properties_t *props)
  1570. {
  1571. obs_property_t *preset_list =
  1572. obs_properties_add_list(props, "preset", TEXT_PRESET, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
  1573. for (NSString *preset in presets())
  1574. obs_property_list_add_string(preset_list, preset_names(preset).UTF8String, preset.UTF8String);
  1575. obs_property_set_modified_callback(preset_list, properties_preset_changed);
  1576. }
  1577. static void add_manual_properties(obs_properties_t *props)
  1578. {
  1579. obs_property_t *resolutions =
  1580. obs_properties_add_list(props, "resolution", TEXT_RESOLUTION, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
  1581. obs_property_set_enabled(resolutions, false);
  1582. obs_property_set_modified_callback(resolutions, properties_resolution_changed);
  1583. obs_property_t *frame_rates = obs_properties_add_frame_rate(props, "frame_rate", TEXT_FRAME_RATE);
  1584. /*obs_property_frame_rate_option_add(frame_rates, "match obs",
  1585. TEXT_MATCH_OBS);*/
  1586. obs_property_set_enabled(frame_rates, false);
  1587. obs_property_set_modified_callback(frame_rates, properties_frame_rate_changed);
  1588. obs_property_t *input_format =
  1589. obs_properties_add_list(props, "input_format", TEXT_INPUT_FORMAT, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
  1590. obs_property_list_add_int(input_format, TEXT_AUTO, INPUT_FORMAT_AUTO);
  1591. obs_property_set_enabled(input_format, false);
  1592. obs_property_set_modified_callback(input_format, properties_input_format_changed);
  1593. obs_property_t *color_space =
  1594. obs_properties_add_list(props, "color_space", TEXT_COLOR_SPACE, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
  1595. obs_property_list_add_int(color_space, TEXT_AUTO, COLOR_SPACE_AUTO);
  1596. obs_property_list_add_int(color_space, "Rec. 601", VIDEO_CS_601);
  1597. obs_property_list_add_int(color_space, "Rec. 709", VIDEO_CS_709);
  1598. obs_property_set_enabled(color_space, false);
  1599. obs_property_set_modified_callback(color_space, properties_color_space_changed);
  1600. #define ADD_RANGE(x) obs_property_list_add_int(video_range, TEXT_##x, VIDEO_##x)
  1601. obs_property_t *video_range =
  1602. obs_properties_add_list(props, "video_range", TEXT_VIDEO_RANGE, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
  1603. obs_property_list_add_int(video_range, TEXT_AUTO, VIDEO_RANGE_AUTO);
  1604. ADD_RANGE(RANGE_PARTIAL);
  1605. ADD_RANGE(RANGE_FULL);
  1606. obs_property_set_enabled(video_range, false);
  1607. obs_property_set_modified_callback(video_range, properties_video_range_changed);
  1608. #undef ADD_RANGE
  1609. }
  1610. static obs_properties_t *av_capture_properties(void *data)
  1611. {
  1612. obs_properties_t *props = obs_properties_create();
  1613. obs_property_t *dev_list =
  1614. obs_properties_add_list(props, "device", TEXT_DEVICE, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
  1615. obs_property_list_add_string(dev_list, "", "");
  1616. NSMutableArray *device_types = [NSMutableArray
  1617. arrayWithObjects:AVCaptureDeviceTypeBuiltInWideAngleCamera, AVCaptureDeviceTypeExternalUnknown, nil];
  1618. #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 130000
  1619. if (__builtin_available(macOS 13.0, *)) {
  1620. [device_types addObject:AVCaptureDeviceTypeDeskViewCamera];
  1621. }
  1622. #endif
  1623. AVCaptureDeviceDiscoverySession *video_discovery =
  1624. [AVCaptureDeviceDiscoverySession discoverySessionWithDeviceTypes:device_types mediaType:AVMediaTypeVideo
  1625. position:AVCaptureDevicePositionUnspecified];
  1626. for (AVCaptureDevice *dev in [video_discovery devices]) {
  1627. obs_property_list_add_string(dev_list, dev.localizedName.UTF8String, dev.uniqueID.UTF8String);
  1628. }
  1629. AVCaptureDeviceDiscoverySession *muxed_discovery =
  1630. [AVCaptureDeviceDiscoverySession discoverySessionWithDeviceTypes:device_types mediaType:AVMediaTypeMuxed
  1631. position:AVCaptureDevicePositionUnspecified];
  1632. for (AVCaptureDevice *dev in [muxed_discovery devices]) {
  1633. obs_property_list_add_string(dev_list, dev.localizedName.UTF8String, dev.uniqueID.UTF8String);
  1634. }
  1635. obs_property_set_modified_callback(dev_list, properties_device_changed);
  1636. obs_property_t *use_preset = obs_properties_add_bool(props, "use_preset", TEXT_USE_PRESET);
  1637. obs_property_set_modified_callback(use_preset, properties_use_preset_changed);
  1638. add_preset_properties(props);
  1639. add_manual_properties(props);
  1640. obs_properties_add_bool(props, "buffering", obs_module_text("Buffering"));
  1641. if (data) {
  1642. struct av_capture *capture = static_cast<av_capture *>(data);
  1643. add_properties_param(props, capture);
  1644. OBSDataAutoRelease current_settings = obs_source_get_settings(capture->source);
  1645. if (!obs_data_get_bool(current_settings, "enable_audio")) {
  1646. auto cb = [](obs_properties_t *, obs_property_t *prop, void *data) {
  1647. struct av_capture *capture = static_cast<av_capture *>(data);
  1648. OBSDataAutoRelease settings = obs_data_create();
  1649. obs_data_set_bool(settings, "enable_audio", true);
  1650. obs_source_update(capture->source, settings);
  1651. // Enable all audio tracks
  1652. obs_source_set_audio_mixers(capture->source, 0x3F);
  1653. obs_property_set_visible(prop, false);
  1654. return true;
  1655. };
  1656. obs_properties_add_button2(props, "enable_audio_button", obs_module_text("EnableAudio"), cb, capture);
  1657. }
  1658. }
  1659. return props;
  1660. }
  1661. static void switch_device(av_capture *capture, NSString *uid, obs_data_t *settings)
  1662. {
  1663. if (!uid)
  1664. return;
  1665. if (capture->device)
  1666. remove_device(capture);
  1667. capture->uid = uid;
  1668. if (!uid.length) {
  1669. AVLOG(LOG_INFO, "No device selected, stopping capture");
  1670. return;
  1671. }
  1672. AVCaptureDevice *dev = [AVCaptureDevice deviceWithUniqueID:uid];
  1673. if (!dev) {
  1674. AVLOG(LOG_WARNING, "Device with unique id '%s' not found", uid.UTF8String);
  1675. return;
  1676. }
  1677. capture_device(capture, dev, settings);
  1678. }
  1679. static void update_preset(av_capture *capture, obs_data_t *settings)
  1680. {
  1681. unlock_device(capture);
  1682. NSString *preset = get_string(settings, "preset");
  1683. if (![capture->device supportsAVCaptureSessionPreset:preset]) {
  1684. AVLOG(LOG_WARNING, "Preset %s not available", preset.UTF8String);
  1685. preset = select_preset(capture->device, preset);
  1686. }
  1687. capture->session.sessionPreset = preset;
  1688. AVLOG(LOG_INFO, "Selected preset %s", preset.UTF8String);
  1689. start_capture(capture);
  1690. }
  1691. static void update_manual(av_capture *capture, obs_data_t *settings)
  1692. {
  1693. if (init_manual(capture, capture->device, settings))
  1694. start_capture(capture);
  1695. }
  1696. static void av_capture_update(void *data, obs_data_t *settings)
  1697. {
  1698. auto capture = static_cast<av_capture *>(data);
  1699. NSString *uid = get_string(settings, "device");
  1700. if (!capture->device || ![capture->device.uniqueID isEqualToString:uid])
  1701. return switch_device(capture, uid, settings);
  1702. if ((capture->use_preset = obs_data_get_bool(settings, "use_preset"))) {
  1703. update_preset(capture, settings);
  1704. } else {
  1705. update_manual(capture, settings);
  1706. }
  1707. av_capture_enable_buffering(capture, obs_data_get_bool(settings, "buffering"));
  1708. av_capture_set_audio_active(capture, obs_data_get_bool(settings, "enable_audio") &&
  1709. ([capture->device hasMediaType:AVMediaTypeAudio] ||
  1710. [capture->device hasMediaType:AVMediaTypeMuxed]));
  1711. }
  1712. OBS_DECLARE_MODULE()
  1713. OBS_MODULE_USE_DEFAULT_LOCALE("mac-avcapture", "en-US")
  1714. MODULE_EXPORT const char *obs_module_description(void)
  1715. {
  1716. return "MacOS AVFoundation Capture source";
  1717. }
  1718. bool obs_module_load(void)
  1719. {
  1720. // Enable iOS device to show up as AVCapture devices
  1721. // From WWDC video 2014 #508 at 5:34
  1722. // https://developer.apple.com/videos/wwdc/2014/#508
  1723. CMIOObjectPropertyAddress prop = {kCMIOHardwarePropertyAllowScreenCaptureDevices, kCMIOObjectPropertyScopeGlobal,
  1724. kCMIOObjectPropertyElementMaster};
  1725. UInt32 allow = 1;
  1726. CMIOObjectSetPropertyData(kCMIOObjectSystemObject, &prop, 0, NULL, sizeof(allow), &allow);
  1727. obs_source_info av_capture_info = {
  1728. .id = "av_capture_input",
  1729. .type = OBS_SOURCE_TYPE_INPUT,
  1730. .output_flags = OBS_SOURCE_ASYNC_VIDEO | OBS_SOURCE_AUDIO | OBS_SOURCE_DO_NOT_DUPLICATE |
  1731. OBS_SOURCE_CAP_OBSOLETE,
  1732. .get_name = av_capture_getname,
  1733. .create = av_capture_create,
  1734. .destroy = av_capture_destroy,
  1735. .get_defaults = av_capture_defaults_v1,
  1736. .get_properties = av_capture_properties,
  1737. .update = av_capture_update,
  1738. .icon_type = OBS_ICON_TYPE_CAMERA,
  1739. };
  1740. obs_register_source(&av_capture_info);
  1741. av_capture_info.version = 2;
  1742. av_capture_info.output_flags = OBS_SOURCE_ASYNC_VIDEO | OBS_SOURCE_AUDIO | OBS_SOURCE_DO_NOT_DUPLICATE;
  1743. av_capture_info.get_defaults = av_capture_defaults_v2;
  1744. obs_register_source(&av_capture_info);
  1745. return true;
  1746. }