av-capture.mm 64 KB

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