av-capture.mm 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240
  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_601_4,
  357. 0) == kCFCompareEqualTo)
  358. return VIDEO_CS_601;
  359. return VIDEO_CS_709;
  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. if (@available(macOS 10.15, *)) {
  997. return @[
  998. //AVCaptureSessionPresetiFrame1280x720,
  999. //AVCaptureSessionPresetiFrame960x540,
  1000. AVCaptureSessionPreset3840x2160,
  1001. AVCaptureSessionPreset1920x1080,
  1002. AVCaptureSessionPreset1280x720,
  1003. AVCaptureSessionPreset960x540,
  1004. AVCaptureSessionPreset640x480,
  1005. AVCaptureSessionPreset352x288,
  1006. AVCaptureSessionPreset320x240,
  1007. AVCaptureSessionPresetHigh,
  1008. //AVCaptureSessionPresetMedium,
  1009. //AVCaptureSessionPresetLow,
  1010. //AVCaptureSessionPresetPhoto,
  1011. ];
  1012. } else {
  1013. return @[
  1014. //AVCaptureSessionPresetiFrame1280x720,
  1015. //AVCaptureSessionPresetiFrame960x540,
  1016. AVCaptureSessionPreset1280x720,
  1017. AVCaptureSessionPreset960x540,
  1018. AVCaptureSessionPreset640x480,
  1019. AVCaptureSessionPreset352x288,
  1020. AVCaptureSessionPreset320x240,
  1021. AVCaptureSessionPresetHigh,
  1022. //AVCaptureSessionPresetMedium,
  1023. //AVCaptureSessionPresetLow,
  1024. //AVCaptureSessionPresetPhoto,
  1025. ];
  1026. }
  1027. }
  1028. static NSString *preset_names(NSString *preset)
  1029. {
  1030. NSDictionary *preset_names = nil;
  1031. if (@available(macOS 10.15, *)) {
  1032. preset_names = @{
  1033. AVCaptureSessionPresetLow: @"Low",
  1034. AVCaptureSessionPresetMedium: @"Medium",
  1035. AVCaptureSessionPresetHigh: @"High",
  1036. AVCaptureSessionPreset320x240: @"320x240",
  1037. AVCaptureSessionPreset352x288: @"352x288",
  1038. AVCaptureSessionPreset640x480: @"640x480",
  1039. AVCaptureSessionPreset960x540: @"960x540",
  1040. AVCaptureSessionPreset1280x720: @"1280x720",
  1041. AVCaptureSessionPreset1920x1080: @"1920x1080",
  1042. AVCaptureSessionPreset3840x2160: @"3840x2160",
  1043. AVCaptureSessionPresetHigh: @"High",
  1044. };
  1045. } else {
  1046. preset_names = @{
  1047. AVCaptureSessionPresetLow: @"Low",
  1048. AVCaptureSessionPresetMedium: @"Medium",
  1049. AVCaptureSessionPresetHigh: @"High",
  1050. AVCaptureSessionPreset320x240: @"320x240",
  1051. AVCaptureSessionPreset352x288: @"352x288",
  1052. AVCaptureSessionPreset640x480: @"640x480",
  1053. AVCaptureSessionPreset960x540: @"960x540",
  1054. AVCaptureSessionPreset1280x720: @"1280x720",
  1055. AVCaptureSessionPresetHigh: @"High",
  1056. };
  1057. }
  1058. NSString *name = preset_names[preset];
  1059. if (name)
  1060. return name;
  1061. return [NSString stringWithFormat:@"Unknown (%@)", preset];
  1062. }
  1063. static void av_capture_defaults(obs_data_t *settings)
  1064. {
  1065. obs_data_set_default_string(settings, "uid", "");
  1066. obs_data_set_default_bool(settings, "use_preset", true);
  1067. obs_data_set_default_string(settings, "preset",
  1068. AVCaptureSessionPreset1280x720.UTF8String);
  1069. obs_data_set_default_int(settings, "input_format", INPUT_FORMAT_AUTO);
  1070. obs_data_set_default_int(settings, "color_space", COLOR_SPACE_AUTO);
  1071. obs_data_set_default_int(settings, "video_range", VIDEO_RANGE_AUTO);
  1072. }
  1073. static bool update_device_list(obs_property_t *list, NSString *uid,
  1074. NSString *name, bool disconnected)
  1075. {
  1076. bool dev_found = false;
  1077. bool list_modified = false;
  1078. size_t size = obs_property_list_item_count(list);
  1079. for (size_t i = 0; i < size;) {
  1080. const char *uid_ = obs_property_list_item_string(list, i);
  1081. bool found = [uid isEqualToString:@(uid_ ? uid_ : "")];
  1082. bool disabled = obs_property_list_item_disabled(list, i);
  1083. if (!found && !disabled) {
  1084. i += 1;
  1085. continue;
  1086. }
  1087. if (disabled && !found) {
  1088. list_modified = true;
  1089. obs_property_list_item_remove(list, i);
  1090. continue;
  1091. }
  1092. if (disabled != disconnected)
  1093. list_modified = true;
  1094. dev_found = true;
  1095. obs_property_list_item_disable(list, i, disconnected);
  1096. i += 1;
  1097. }
  1098. if (dev_found)
  1099. return list_modified;
  1100. size_t idx = obs_property_list_add_string(list, name.UTF8String,
  1101. uid.UTF8String);
  1102. obs_property_list_item_disable(list, idx, disconnected);
  1103. return true;
  1104. }
  1105. static void fill_presets(AVCaptureDevice *dev, obs_property_t *list,
  1106. NSString *current_preset)
  1107. {
  1108. obs_property_list_clear(list);
  1109. bool preset_found = false;
  1110. for (NSString *preset in presets()) {
  1111. bool is_current = [preset isEqualToString:current_preset];
  1112. bool supported = dev &&
  1113. [dev supportsAVCaptureSessionPreset:preset];
  1114. if (is_current)
  1115. preset_found = true;
  1116. if (!supported && !is_current)
  1117. continue;
  1118. size_t idx = obs_property_list_add_string(
  1119. list, preset_names(preset).UTF8String,
  1120. preset.UTF8String);
  1121. obs_property_list_item_disable(list, idx, !supported);
  1122. }
  1123. if (preset_found)
  1124. return;
  1125. size_t idx = obs_property_list_add_string(
  1126. list, preset_names(current_preset).UTF8String,
  1127. current_preset.UTF8String);
  1128. obs_property_list_item_disable(list, idx, true);
  1129. }
  1130. static bool check_preset(AVCaptureDevice *dev, obs_property_t *list,
  1131. obs_data_t *settings)
  1132. {
  1133. NSString *current_preset = get_string(settings, "preset");
  1134. size_t size = obs_property_list_item_count(list);
  1135. NSMutableSet *listed = [NSMutableSet setWithCapacity:size];
  1136. for (size_t i = 0; i < size; i++)
  1137. [listed addObject:@(obs_property_list_item_string(list, i))];
  1138. bool presets_changed = false;
  1139. for (NSString *preset in presets()) {
  1140. bool is_listed = [listed member:preset] != nil;
  1141. bool supported = dev &&
  1142. [dev supportsAVCaptureSessionPreset:preset];
  1143. if (supported == is_listed)
  1144. continue;
  1145. presets_changed = true;
  1146. }
  1147. if (!presets_changed && [listed member:current_preset] != nil)
  1148. return false;
  1149. fill_presets(dev, list, current_preset);
  1150. return true;
  1151. }
  1152. static bool autoselect_preset(AVCaptureDevice *dev, obs_data_t *settings)
  1153. {
  1154. NSString *preset = get_string(settings, "preset");
  1155. if (!dev || [dev supportsAVCaptureSessionPreset:preset]) {
  1156. if (obs_data_has_autoselect_value(settings, "preset")) {
  1157. obs_data_unset_autoselect_value(settings, "preset");
  1158. return true;
  1159. }
  1160. } else {
  1161. preset = select_preset(dev, preset);
  1162. const char *autoselect =
  1163. obs_data_get_autoselect_string(settings, "preset");
  1164. if (![preset isEqualToString:@(autoselect)]) {
  1165. obs_data_set_autoselect_string(settings, "preset",
  1166. preset.UTF8String);
  1167. return true;
  1168. }
  1169. }
  1170. return false;
  1171. }
  1172. static CMVideoDimensions get_dimensions(AVCaptureDeviceFormat *format)
  1173. {
  1174. auto desc = format.formatDescription;
  1175. return CMVideoFormatDescriptionGetDimensions(desc);
  1176. }
  1177. using resolutions_t = vector<CMVideoDimensions>;
  1178. static resolutions_t enumerate_resolutions(AVCaptureDevice *dev)
  1179. {
  1180. resolutions_t res;
  1181. if (!dev)
  1182. return res;
  1183. res.reserve(dev.formats.count + 1);
  1184. for (AVCaptureDeviceFormat *format in dev.formats) {
  1185. auto dims = get_dimensions(format);
  1186. if (find(begin(res), end(res), dims) == end(res))
  1187. res.push_back(dims);
  1188. }
  1189. return res;
  1190. }
  1191. static void sort_resolutions(vector<CMVideoDimensions> &resolutions)
  1192. {
  1193. auto cmp = [](const CMVideoDimensions &a, const CMVideoDimensions &b) {
  1194. return a.width * a.height > b.width * b.height;
  1195. };
  1196. sort(begin(resolutions), end(resolutions), cmp);
  1197. }
  1198. static void data_set_resolution(obs_data_t *data, const CMVideoDimensions &dims)
  1199. {
  1200. obs_data_set_int(data, "width", dims.width);
  1201. obs_data_set_int(data, "height", dims.height);
  1202. }
  1203. static void data_set_resolution(const unique_ptr<obs_data_t> &data,
  1204. const CMVideoDimensions &dims)
  1205. {
  1206. data_set_resolution(data.get(), dims);
  1207. }
  1208. static bool add_resolution_to_list(vector<CMVideoDimensions> &res,
  1209. const CMVideoDimensions &dims)
  1210. {
  1211. if (find(begin(res), end(res), dims) != end(res))
  1212. return false;
  1213. res.push_back(dims);
  1214. return true;
  1215. }
  1216. static const char *obs_data_get_json(const unique_ptr<obs_data_t> &data)
  1217. {
  1218. return obs_data_get_json(data.get());
  1219. }
  1220. static bool operator==(const CMVideoDimensions &a, const CMVideoDimensions &b)
  1221. {
  1222. return a.width == b.width && a.height == b.height;
  1223. }
  1224. static bool resolution_property_needs_update(obs_property_t *p,
  1225. const resolutions_t &resolutions)
  1226. {
  1227. vector<bool> res_found(resolutions.size());
  1228. auto num = obs_property_list_item_count(p);
  1229. for (size_t i = 1; i < num; i++) { // skip empty entry
  1230. const char *json = obs_property_list_item_string(p, i);
  1231. unique_ptr<obs_data_t> buffer{obs_data_create_from_json(json)};
  1232. CMVideoDimensions dims{};
  1233. if (!get_resolution(buffer.get(), dims))
  1234. return true;
  1235. auto pos = find(begin(resolutions), end(resolutions), dims);
  1236. if (pos == end(resolutions))
  1237. return true;
  1238. res_found[pos - begin(resolutions)] = true;
  1239. }
  1240. return any_of(begin(res_found), end(res_found),
  1241. [](bool b) { return !b; });
  1242. }
  1243. static bool update_resolution_property(obs_properties_t *props,
  1244. const config_helper &conf,
  1245. obs_property_t *p = nullptr)
  1246. {
  1247. if (!p)
  1248. p = obs_properties_get(props, "resolution");
  1249. if (!p)
  1250. return false;
  1251. auto valid_dims = conf.dims();
  1252. auto resolutions = enumerate_resolutions(conf.dev());
  1253. bool unsupported = true;
  1254. if (valid_dims)
  1255. unsupported = add_resolution_to_list(resolutions, *valid_dims);
  1256. bool was_enabled = obs_property_enabled(p);
  1257. obs_property_set_enabled(p, !!conf.dev());
  1258. if (!resolution_property_needs_update(p, resolutions))
  1259. return was_enabled != obs_property_enabled(p);
  1260. sort_resolutions(resolutions);
  1261. obs_property_list_clear(p);
  1262. obs_property_list_add_string(p, "", "{}");
  1263. DStr name;
  1264. unique_ptr<obs_data_t> buffer{obs_data_create()};
  1265. for (const CMVideoDimensions &dims : resolutions) {
  1266. data_set_resolution(buffer, dims);
  1267. auto json = obs_data_get_json(buffer);
  1268. dstr_printf(name, "%dx%d", dims.width, dims.height);
  1269. size_t idx = obs_property_list_add_string(p, name->array, json);
  1270. if (unsupported && valid_dims && dims == *valid_dims)
  1271. obs_property_list_item_disable(p, idx, true);
  1272. }
  1273. return true;
  1274. }
  1275. static media_frames_per_second convert(CMTime time_)
  1276. {
  1277. media_frames_per_second res{};
  1278. clamp(res.numerator, time_.timescale);
  1279. clamp(res.denominator, time_.value);
  1280. return res;
  1281. }
  1282. using frame_rates_t =
  1283. vector<pair<media_frames_per_second, media_frames_per_second>>;
  1284. static frame_rates_t
  1285. enumerate_frame_rates(AVCaptureDevice *dev,
  1286. const CMVideoDimensions *dims = nullptr)
  1287. {
  1288. frame_rates_t res;
  1289. if (!dev || !dims)
  1290. return res;
  1291. auto add_unique_frame_rate_range = [&](AVFrameRateRange *range) {
  1292. auto min = convert(range.maxFrameDuration);
  1293. auto max = convert(range.minFrameDuration);
  1294. auto pair = make_pair(min, max);
  1295. if (find(begin(res), end(res), pair) != end(res))
  1296. return;
  1297. res.push_back(pair);
  1298. };
  1299. for (AVCaptureDeviceFormat *format in dev.formats) {
  1300. if (!(get_dimensions(format) == *dims))
  1301. continue;
  1302. for (AVFrameRateRange *range in format
  1303. .videoSupportedFrameRateRanges) {
  1304. add_unique_frame_rate_range(range);
  1305. if (CMTimeCompare(range.minFrameDuration,
  1306. range.maxFrameDuration) != 0) {
  1307. blog(LOG_WARNING,
  1308. "Got actual frame rate range:"
  1309. " %g - %g "
  1310. "({%lld, %d} - {%lld, %d})",
  1311. range.minFrameRate, range.maxFrameRate,
  1312. range.maxFrameDuration.value,
  1313. range.maxFrameDuration.timescale,
  1314. range.minFrameDuration.value,
  1315. range.minFrameDuration.timescale);
  1316. }
  1317. }
  1318. }
  1319. return res;
  1320. }
  1321. static bool operator==(const media_frames_per_second &a,
  1322. const media_frames_per_second &b)
  1323. {
  1324. return a.numerator == b.numerator && a.denominator == b.denominator;
  1325. }
  1326. static bool operator!=(const media_frames_per_second &a,
  1327. const media_frames_per_second &b)
  1328. {
  1329. return !(a == b);
  1330. }
  1331. static bool frame_rate_property_needs_update(obs_property_t *p,
  1332. const frame_rates_t &frame_rates)
  1333. {
  1334. auto fps_num = frame_rates.size();
  1335. auto num = obs_property_frame_rate_fps_ranges_count(p);
  1336. if (fps_num != num)
  1337. return true;
  1338. vector<bool> fps_found(fps_num);
  1339. for (size_t i = 0; i < num; i++) {
  1340. auto min_ = obs_property_frame_rate_fps_range_min(p, i);
  1341. auto max_ = obs_property_frame_rate_fps_range_max(p, i);
  1342. auto it = find(begin(frame_rates), end(frame_rates),
  1343. make_pair(min_, max_));
  1344. if (it == end(frame_rates))
  1345. return true;
  1346. fps_found[it - begin(frame_rates)] = true;
  1347. }
  1348. return any_of(begin(fps_found), end(fps_found),
  1349. [](bool b) { return !b; });
  1350. }
  1351. static bool update_frame_rate_property(obs_properties_t *props,
  1352. const config_helper &conf,
  1353. obs_property_t *p = nullptr)
  1354. {
  1355. if (!p)
  1356. p = obs_properties_get(props, "frame_rate");
  1357. if (!p)
  1358. return false;
  1359. auto valid_dims = conf.dims();
  1360. auto frame_rates = enumerate_frame_rates(conf.dev(), valid_dims);
  1361. bool was_enabled = obs_property_enabled(p);
  1362. obs_property_set_enabled(p, !frame_rates.empty());
  1363. if (!frame_rate_property_needs_update(p, frame_rates))
  1364. return was_enabled != obs_property_enabled(p);
  1365. obs_property_frame_rate_fps_ranges_clear(p);
  1366. for (auto &pair : frame_rates)
  1367. obs_property_frame_rate_fps_range_add(p, pair.first,
  1368. pair.second);
  1369. return true;
  1370. }
  1371. static vector<AVCaptureDeviceFormat *>
  1372. enumerate_formats(AVCaptureDevice *dev, const CMVideoDimensions &dims,
  1373. const media_frames_per_second &fps)
  1374. {
  1375. vector<AVCaptureDeviceFormat *> result;
  1376. find_formats(fps, dev, &dims, [&](AVCaptureDeviceFormat *format) {
  1377. result.push_back(format);
  1378. return false;
  1379. });
  1380. return result;
  1381. }
  1382. static bool input_format_property_needs_update(
  1383. obs_property_t *p, const vector<AVCaptureDeviceFormat *> &formats,
  1384. const FourCharCode *fourcc_)
  1385. {
  1386. bool fourcc_found = !fourcc_;
  1387. vector<bool> if_found(formats.size());
  1388. auto num = obs_property_list_item_count(p);
  1389. for (size_t i = 1; i < num; i++) { // skip auto entry
  1390. FourCharCode fourcc = obs_property_list_item_int(p, i);
  1391. fourcc_found = fourcc_found || fourcc == *fourcc_;
  1392. auto pos = find_if(begin(formats), end(formats),
  1393. [&](AVCaptureDeviceFormat *format) {
  1394. FourCharCode fourcc_ = 0;
  1395. format_description_subtype_name(
  1396. format.formatDescription,
  1397. &fourcc_);
  1398. return fourcc_ == fourcc;
  1399. });
  1400. if (pos == end(formats))
  1401. return true;
  1402. if_found[pos - begin(formats)] = true;
  1403. }
  1404. return fourcc_found || any_of(begin(if_found), end(if_found),
  1405. [](bool b) { return !b; });
  1406. }
  1407. static bool update_input_format_property(obs_properties_t *props,
  1408. const config_helper &conf,
  1409. obs_property_t *p = nullptr)
  1410. {
  1411. if (!p)
  1412. p = obs_properties_get(props, "input_format");
  1413. if (!p)
  1414. return false;
  1415. auto update_enabled = [&](bool enabled) {
  1416. bool was_enabled = obs_property_enabled(p);
  1417. obs_property_set_enabled(p, enabled);
  1418. return was_enabled != enabled;
  1419. };
  1420. auto valid_dims = conf.dims();
  1421. auto valid_fps = conf.fps();
  1422. auto valid_if = conf.input_format();
  1423. if (!valid_dims || !valid_fps)
  1424. return update_enabled(false);
  1425. auto formats = enumerate_formats(conf.dev(), *valid_dims, *valid_fps);
  1426. if (!input_format_property_needs_update(p, formats, valid_if))
  1427. return update_enabled(!formats.empty());
  1428. while (obs_property_list_item_count(p) > 1)
  1429. obs_property_list_item_remove(p, 1);
  1430. bool fourcc_found = !valid_if || *valid_if == INPUT_FORMAT_AUTO;
  1431. for (auto &format : formats) {
  1432. FourCharCode fourcc = 0;
  1433. const char *name = format_description_subtype_name(
  1434. format.formatDescription, &fourcc);
  1435. obs_property_list_add_int(p, name, fourcc);
  1436. fourcc_found = fourcc_found || fourcc == *valid_if;
  1437. }
  1438. if (!fourcc_found) {
  1439. const char *name = fourcc_subtype_name(*valid_if);
  1440. obs_property_list_add_int(p, name, *valid_if);
  1441. }
  1442. return update_enabled(!formats.empty());
  1443. }
  1444. static bool update_int_list_property(obs_property_t *p, const int *val,
  1445. const size_t count,
  1446. const char *localization_name)
  1447. {
  1448. size_t num = obs_property_list_item_count(p);
  1449. if (num > count) {
  1450. if (!val || obs_property_list_item_int(p, count) != *val) {
  1451. obs_property_list_item_remove(p, count);
  1452. if (!val)
  1453. return true;
  1454. } else {
  1455. return false;
  1456. }
  1457. }
  1458. if (!val)
  1459. return false;
  1460. DStr buf, label;
  1461. dstr_printf(buf, "%d", *val);
  1462. dstr_init_copy(label, obs_module_text(localization_name));
  1463. dstr_replace(label, "$1", buf->array);
  1464. size_t idx = obs_property_list_add_int(p, label->array, *val);
  1465. obs_property_list_item_disable(p, idx, true);
  1466. return true;
  1467. }
  1468. template<typename Func>
  1469. static bool
  1470. update_int_list_property(const char *prop_name, const char *localization_name,
  1471. size_t count, int auto_val, bool (*valid_func)(int),
  1472. obs_properties_t *props, const config_helper &conf,
  1473. obs_property_t *p, Func get_val)
  1474. {
  1475. auto ref = get_ref(props);
  1476. if (!p)
  1477. p = obs_properties_get(props, prop_name);
  1478. int val = obs_data_get_int(conf.settings, prop_name);
  1479. av_video_info vi;
  1480. if (ref)
  1481. vi = ref->video_info.read();
  1482. bool params_valid = vi.video_params_valid;
  1483. bool enabled = obs_property_enabled(p);
  1484. bool should_enable = false;
  1485. bool has_autoselect =
  1486. obs_data_has_autoselect_value(conf.settings, prop_name);
  1487. if ((params_valid && format_is_yuv(ref->frame.format)) ||
  1488. !valid_func(val))
  1489. should_enable = true;
  1490. obs_property_set_enabled(p, should_enable);
  1491. bool updated = enabled != should_enable;
  1492. updated = update_int_list_property(p, valid_func(val) ? nullptr : &val,
  1493. count, localization_name) ||
  1494. updated;
  1495. if (!should_enable) {
  1496. if (has_autoselect)
  1497. obs_data_unset_autoselect_value(conf.settings,
  1498. prop_name);
  1499. return updated || has_autoselect;
  1500. }
  1501. bool use_autoselect = ref && val == auto_val;
  1502. if (!use_autoselect) {
  1503. if (has_autoselect)
  1504. obs_data_unset_autoselect_value(conf.settings,
  1505. prop_name);
  1506. return updated || has_autoselect;
  1507. }
  1508. if (params_valid && get_val(vi) != obs_data_get_autoselect_int(
  1509. conf.settings, prop_name)) {
  1510. obs_data_set_autoselect_int(conf.settings, prop_name,
  1511. get_val(vi));
  1512. return true;
  1513. }
  1514. return updated;
  1515. }
  1516. static bool update_color_space_property(obs_properties_t *props,
  1517. const config_helper &conf,
  1518. obs_property_t *p = nullptr)
  1519. {
  1520. return update_int_list_property("color_space", TEXT_COLOR_UNKNOWN_NAME,
  1521. 4, COLOR_SPACE_AUTO, color_space_valid,
  1522. props, conf, p, [](av_video_info vi) {
  1523. return vi.colorspace;
  1524. });
  1525. }
  1526. static bool update_video_range_property(obs_properties_t *props,
  1527. const config_helper &conf,
  1528. obs_property_t *p = nullptr)
  1529. {
  1530. return update_int_list_property("video_range", TEXT_RANGE_UNKNOWN_NAME,
  1531. 5, VIDEO_RANGE_AUTO, video_range_valid,
  1532. props, conf, p, [](av_video_info vi) {
  1533. return vi.video_range;
  1534. });
  1535. }
  1536. static bool properties_device_changed(obs_properties_t *props,
  1537. obs_property_t *p, obs_data_t *settings)
  1538. {
  1539. NSString *uid = get_string(settings, "device");
  1540. AVCaptureDevice *dev = [AVCaptureDevice deviceWithUniqueID:uid];
  1541. NSString *name = get_string(settings, "device_name");
  1542. bool dev_list_updated =
  1543. update_device_list(p, uid, name, !dev && uid.length);
  1544. p = obs_properties_get(props, "preset");
  1545. bool preset_list_changed = check_preset(dev, p, settings);
  1546. bool autoselect_changed = autoselect_preset(dev, settings);
  1547. config_helper conf{settings};
  1548. bool res_changed = update_resolution_property(props, conf);
  1549. bool fps_changed = update_frame_rate_property(props, conf);
  1550. bool if_changed = update_input_format_property(props, conf);
  1551. return preset_list_changed || autoselect_changed || dev_list_updated ||
  1552. res_changed || fps_changed || if_changed;
  1553. }
  1554. static bool properties_use_preset_changed(obs_properties_t *props,
  1555. obs_property_t *,
  1556. obs_data_t *settings)
  1557. {
  1558. auto use_preset = obs_data_get_bool(settings, "use_preset");
  1559. config_helper conf{settings};
  1560. bool updated = false;
  1561. bool visible = false;
  1562. obs_property_t *p = nullptr;
  1563. auto noop = [](obs_properties_t *, const config_helper &,
  1564. obs_property_t *) { return false; };
  1565. #define UPDATE_PROPERTY(prop, uses_preset, func) \
  1566. p = obs_properties_get(props, prop); \
  1567. visible = use_preset == uses_preset; \
  1568. updated = obs_property_visible(p) != visible || updated; \
  1569. obs_property_set_visible(p, visible); \
  1570. updated = func(props, conf, p) || updated;
  1571. UPDATE_PROPERTY("preset", true, noop);
  1572. UPDATE_PROPERTY("resolution", false, update_resolution_property);
  1573. UPDATE_PROPERTY("frame_rate", false, update_frame_rate_property);
  1574. UPDATE_PROPERTY("input_format", false, update_input_format_property);
  1575. UPDATE_PROPERTY("color_space", false, update_color_space_property);
  1576. UPDATE_PROPERTY("video_range", false, update_video_range_property);
  1577. return updated;
  1578. }
  1579. static bool properties_preset_changed(obs_properties_t *, obs_property_t *p,
  1580. obs_data_t *settings)
  1581. {
  1582. NSString *uid = get_string(settings, "device");
  1583. AVCaptureDevice *dev = [AVCaptureDevice deviceWithUniqueID:uid];
  1584. bool preset_list_changed = check_preset(dev, p, settings);
  1585. bool autoselect_changed = autoselect_preset(dev, settings);
  1586. return preset_list_changed || autoselect_changed;
  1587. }
  1588. static bool properties_resolution_changed(obs_properties_t *props,
  1589. obs_property_t *p,
  1590. obs_data_t *settings)
  1591. {
  1592. config_helper conf{settings};
  1593. bool res_updated = update_resolution_property(props, conf, p);
  1594. bool fps_updated = update_frame_rate_property(props, conf);
  1595. bool if_updated = update_input_format_property(props, conf);
  1596. bool cs_updated = update_color_space_property(props, conf);
  1597. bool cr_updated = update_video_range_property(props, conf);
  1598. return res_updated || fps_updated || if_updated || cs_updated ||
  1599. cr_updated;
  1600. }
  1601. static bool properties_frame_rate_changed(obs_properties_t *props,
  1602. obs_property_t *p,
  1603. obs_data_t *settings)
  1604. {
  1605. config_helper conf{settings};
  1606. bool fps_updated = update_frame_rate_property(props, conf, p);
  1607. bool if_updated = update_input_format_property(props, conf);
  1608. bool cs_updated = update_color_space_property(props, conf);
  1609. bool cr_updated = update_video_range_property(props, conf);
  1610. return fps_updated || if_updated || cs_updated || cr_updated;
  1611. }
  1612. static bool properties_input_format_changed(obs_properties_t *props,
  1613. obs_property_t *p,
  1614. obs_data_t *settings)
  1615. {
  1616. config_helper conf{settings};
  1617. bool if_updated = update_input_format_property(props, conf, p);
  1618. bool cs_updated = update_color_space_property(props, conf);
  1619. bool cr_updated = update_video_range_property(props, conf);
  1620. return if_updated || cs_updated || cr_updated;
  1621. }
  1622. static bool properties_color_space_changed(obs_properties_t *props,
  1623. obs_property_t *p,
  1624. obs_data_t *settings)
  1625. {
  1626. config_helper conf{settings};
  1627. return update_color_space_property(props, conf, p);
  1628. }
  1629. static bool properties_video_range_changed(obs_properties_t *props,
  1630. obs_property_t *p,
  1631. obs_data_t *settings)
  1632. {
  1633. config_helper conf{settings};
  1634. return update_video_range_property(props, conf, p);
  1635. }
  1636. static void add_properties_param(obs_properties_t *props, av_capture *capture)
  1637. {
  1638. auto param =
  1639. unique_ptr<properties_param>(new properties_param(capture));
  1640. obs_properties_set_param(props, param.release(), [](void *param) {
  1641. delete static_cast<properties_param *>(param);
  1642. });
  1643. }
  1644. static void add_preset_properties(obs_properties_t *props)
  1645. {
  1646. obs_property_t *preset_list = obs_properties_add_list(
  1647. props, "preset", TEXT_PRESET, OBS_COMBO_TYPE_LIST,
  1648. OBS_COMBO_FORMAT_STRING);
  1649. for (NSString *preset in presets())
  1650. obs_property_list_add_string(preset_list,
  1651. preset_names(preset).UTF8String,
  1652. preset.UTF8String);
  1653. obs_property_set_modified_callback(preset_list,
  1654. properties_preset_changed);
  1655. }
  1656. static void add_manual_properties(obs_properties_t *props)
  1657. {
  1658. obs_property_t *resolutions = obs_properties_add_list(
  1659. props, "resolution", TEXT_RESOLUTION, OBS_COMBO_TYPE_LIST,
  1660. OBS_COMBO_FORMAT_STRING);
  1661. obs_property_set_enabled(resolutions, false);
  1662. obs_property_set_modified_callback(resolutions,
  1663. properties_resolution_changed);
  1664. obs_property_t *frame_rates = obs_properties_add_frame_rate(
  1665. props, "frame_rate", TEXT_FRAME_RATE);
  1666. /*obs_property_frame_rate_option_add(frame_rates, "match obs",
  1667. TEXT_MATCH_OBS);*/
  1668. obs_property_set_enabled(frame_rates, false);
  1669. obs_property_set_modified_callback(frame_rates,
  1670. properties_frame_rate_changed);
  1671. obs_property_t *input_format = obs_properties_add_list(
  1672. props, "input_format", TEXT_INPUT_FORMAT, OBS_COMBO_TYPE_LIST,
  1673. OBS_COMBO_FORMAT_INT);
  1674. obs_property_list_add_int(input_format, TEXT_AUTO, INPUT_FORMAT_AUTO);
  1675. obs_property_set_enabled(input_format, false);
  1676. obs_property_set_modified_callback(input_format,
  1677. properties_input_format_changed);
  1678. obs_property_t *color_space = obs_properties_add_list(
  1679. props, "color_space", TEXT_COLOR_SPACE, OBS_COMBO_TYPE_LIST,
  1680. OBS_COMBO_FORMAT_INT);
  1681. obs_property_list_add_int(color_space, TEXT_AUTO, COLOR_SPACE_AUTO);
  1682. obs_property_list_add_int(color_space, "Rec. 601", VIDEO_CS_601);
  1683. obs_property_list_add_int(color_space, "Rec. 709", VIDEO_CS_709);
  1684. obs_property_set_enabled(color_space, false);
  1685. obs_property_set_modified_callback(color_space,
  1686. properties_color_space_changed);
  1687. #define ADD_RANGE(x) obs_property_list_add_int(video_range, TEXT_##x, VIDEO_##x)
  1688. obs_property_t *video_range = obs_properties_add_list(
  1689. props, "video_range", TEXT_VIDEO_RANGE, OBS_COMBO_TYPE_LIST,
  1690. OBS_COMBO_FORMAT_INT);
  1691. obs_property_list_add_int(video_range, TEXT_AUTO, VIDEO_RANGE_AUTO);
  1692. ADD_RANGE(RANGE_PARTIAL);
  1693. ADD_RANGE(RANGE_FULL);
  1694. obs_property_set_enabled(video_range, false);
  1695. obs_property_set_modified_callback(video_range,
  1696. properties_video_range_changed);
  1697. #undef ADD_RANGE
  1698. }
  1699. static obs_properties_t *av_capture_properties(void *capture)
  1700. {
  1701. obs_properties_t *props = obs_properties_create();
  1702. add_properties_param(props, static_cast<av_capture *>(capture));
  1703. obs_property_t *dev_list = obs_properties_add_list(
  1704. props, "device", TEXT_DEVICE, OBS_COMBO_TYPE_LIST,
  1705. OBS_COMBO_FORMAT_STRING);
  1706. obs_property_list_add_string(dev_list, "", "");
  1707. for (AVCaptureDevice *dev in [AVCaptureDevice devices]) {
  1708. if ([dev hasMediaType:AVMediaTypeVideo] ||
  1709. [dev hasMediaType:AVMediaTypeMuxed]) {
  1710. obs_property_list_add_string(
  1711. dev_list, dev.localizedName.UTF8String,
  1712. dev.uniqueID.UTF8String);
  1713. }
  1714. }
  1715. obs_property_set_modified_callback(dev_list, properties_device_changed);
  1716. obs_property_t *use_preset =
  1717. obs_properties_add_bool(props, "use_preset", TEXT_USE_PRESET);
  1718. obs_property_set_modified_callback(use_preset,
  1719. properties_use_preset_changed);
  1720. add_preset_properties(props);
  1721. add_manual_properties(props);
  1722. obs_properties_add_bool(props, "buffering",
  1723. obs_module_text("Buffering"));
  1724. return props;
  1725. }
  1726. static void switch_device(av_capture *capture, NSString *uid,
  1727. obs_data_t *settings)
  1728. {
  1729. if (!uid)
  1730. return;
  1731. if (capture->device)
  1732. remove_device(capture);
  1733. capture->uid = uid;
  1734. if (!uid.length) {
  1735. AVLOG(LOG_INFO, "No device selected, stopping capture");
  1736. return;
  1737. }
  1738. AVCaptureDevice *dev = [AVCaptureDevice deviceWithUniqueID:uid];
  1739. if (!dev) {
  1740. AVLOG(LOG_WARNING, "Device with unique id '%s' not found",
  1741. uid.UTF8String);
  1742. return;
  1743. }
  1744. capture_device(capture, dev, settings);
  1745. }
  1746. static void update_preset(av_capture *capture, obs_data_t *settings)
  1747. {
  1748. unlock_device(capture);
  1749. NSString *preset = get_string(settings, "preset");
  1750. if (![capture->device supportsAVCaptureSessionPreset:preset]) {
  1751. AVLOG(LOG_WARNING, "Preset %s not available",
  1752. preset.UTF8String);
  1753. preset = select_preset(capture->device, preset);
  1754. }
  1755. capture->session.sessionPreset = preset;
  1756. AVLOG(LOG_INFO, "Selected preset %s", preset.UTF8String);
  1757. start_capture(capture);
  1758. }
  1759. static void update_manual(av_capture *capture, obs_data_t *settings)
  1760. {
  1761. if (init_manual(capture, capture->device, settings))
  1762. start_capture(capture);
  1763. }
  1764. static void av_capture_update(void *data, obs_data_t *settings)
  1765. {
  1766. auto capture = static_cast<av_capture *>(data);
  1767. NSString *uid = get_string(settings, "device");
  1768. if (!capture->device || ![capture->device.uniqueID isEqualToString:uid])
  1769. return switch_device(capture, uid, settings);
  1770. if ((capture->use_preset = obs_data_get_bool(settings, "use_preset"))) {
  1771. update_preset(capture, settings);
  1772. } else {
  1773. update_manual(capture, settings);
  1774. }
  1775. av_capture_enable_buffering(capture,
  1776. obs_data_get_bool(settings, "buffering"));
  1777. }
  1778. OBS_DECLARE_MODULE()
  1779. OBS_MODULE_USE_DEFAULT_LOCALE("mac-avcapture", "en-US")
  1780. MODULE_EXPORT const char *obs_module_description(void)
  1781. {
  1782. return "MacOS AVFoundation Capture source";
  1783. }
  1784. bool obs_module_load(void)
  1785. {
  1786. #ifdef __MAC_10_10
  1787. // Enable iOS device to show up as AVCapture devices
  1788. // From WWDC video 2014 #508 at 5:34
  1789. // https://developer.apple.com/videos/wwdc/2014/#508
  1790. CMIOObjectPropertyAddress prop = {
  1791. kCMIOHardwarePropertyAllowScreenCaptureDevices,
  1792. kCMIOObjectPropertyScopeGlobal,
  1793. kCMIOObjectPropertyElementMaster};
  1794. UInt32 allow = 1;
  1795. CMIOObjectSetPropertyData(kCMIOObjectSystemObject, &prop, 0, NULL,
  1796. sizeof(allow), &allow);
  1797. #endif
  1798. obs_source_info av_capture_info = {
  1799. .id = "av_capture_input",
  1800. .type = OBS_SOURCE_TYPE_INPUT,
  1801. .output_flags = OBS_SOURCE_ASYNC_VIDEO |
  1802. OBS_SOURCE_DO_NOT_DUPLICATE,
  1803. .get_name = av_capture_getname,
  1804. .create = av_capture_create,
  1805. .destroy = av_capture_destroy,
  1806. .get_defaults = av_capture_defaults,
  1807. .get_properties = av_capture_properties,
  1808. .update = av_capture_update,
  1809. .icon_type = OBS_ICON_TYPE_CAMERA,
  1810. };
  1811. obs_register_source(&av_capture_info);
  1812. return true;
  1813. }