av-capture.mm 58 KB

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