av-capture.mm 57 KB

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