av-capture.mm 64 KB

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