av-capture.mm 64 KB

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