win-dshow.cpp 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577
  1. #include <objbase.h>
  2. #include <obs-module.h>
  3. #include <obs.hpp>
  4. #include <util/dstr.hpp>
  5. #include <util/platform.h>
  6. #include <util/windows/WinHandle.hpp>
  7. #include "libdshowcapture/dshowcapture.hpp"
  8. #include "ffmpeg-decode.h"
  9. #include "encode-dstr.hpp"
  10. #include <algorithm>
  11. #include <limits>
  12. #include <set>
  13. #include <string>
  14. #include <vector>
  15. /*
  16. * TODO:
  17. * - handle disconnections and reconnections
  18. * - if device not present, wait for device to be plugged in
  19. */
  20. #undef min
  21. #undef max
  22. using namespace std;
  23. using namespace DShow;
  24. /* settings defines that will cause errors if there are typos */
  25. #define VIDEO_DEVICE_ID "video_device_id"
  26. #define RES_TYPE "res_type"
  27. #define RESOLUTION "resolution"
  28. #define FRAME_INTERVAL "frame_interval"
  29. #define VIDEO_FORMAT "video_format"
  30. #define LAST_VIDEO_DEV_ID "last_video_device_id"
  31. #define LAST_RESOLUTION "last_resolution"
  32. #define USE_CUSTOM_AUDIO "use_custom_audio_device"
  33. #define AUDIO_DEVICE_ID "audio_device_id"
  34. #define TEXT_INPUT_NAME obs_module_text("VideoCaptureDevice")
  35. #define TEXT_DEVICE obs_module_text("Device")
  36. #define TEXT_CONFIG_VIDEO obs_module_text("ConfigureVideo")
  37. #define TEXT_CONFIG_XBAR obs_module_text("ConfigureCrossbar")
  38. #define TEXT_RES_FPS_TYPE obs_module_text("ResFPSType")
  39. #define TEXT_CUSTOM_RES obs_module_text("ResFPSType.Custom")
  40. #define TEXT_PREFERRED_RES obs_module_text("ResFPSType.DevPreferred")
  41. #define TEXT_FPS_MATCHING obs_module_text("FPS.Matching")
  42. #define TEXT_FPS_HIGHEST obs_module_text("FPS.Highest")
  43. #define TEXT_RESOLUTION obs_module_text("Resolution")
  44. #define TEXT_VIDEO_FORMAT obs_module_text("VideoFormat")
  45. #define TEXT_FORMAT_UNKNOWN obs_module_text("VideoFormat.Unknown")
  46. #define TEXT_CUSTOM_AUDIO obs_module_text("UseCustomAudioDevice")
  47. #define TEXT_AUDIO_DEVICE obs_module_text("AudioDevice")
  48. enum ResType {
  49. ResType_Preferred,
  50. ResType_Custom
  51. };
  52. void ffmpeg_log(void *bla, int level, const char *msg, va_list args)
  53. {
  54. DStr str;
  55. if (level == AV_LOG_WARNING)
  56. dstr_copy(str, "warning: ");
  57. else if (level == AV_LOG_ERROR)
  58. dstr_copy(str, "error: ");
  59. else if (level < AV_LOG_ERROR)
  60. dstr_copy(str, "fatal: ");
  61. else
  62. return;
  63. dstr_cat(str, msg);
  64. if (dstr_end(str) == '\n')
  65. dstr_resize(str, str->len - 1);
  66. blogva(LOG_WARNING, str, args);
  67. av_log_default_callback(bla, level, msg, args);
  68. }
  69. class Decoder {
  70. struct ffmpeg_decode decode;
  71. public:
  72. inline Decoder() {memset(&decode, 0, sizeof(decode));}
  73. inline ~Decoder() {ffmpeg_decode_free(&decode);}
  74. inline operator ffmpeg_decode*() {return &decode;}
  75. };
  76. class CriticalSection {
  77. CRITICAL_SECTION mutex;
  78. public:
  79. inline CriticalSection() {InitializeCriticalSection(&mutex);}
  80. inline ~CriticalSection() {DeleteCriticalSection(&mutex);}
  81. inline operator CRITICAL_SECTION*() {return &mutex;}
  82. };
  83. class CriticalScope {
  84. CriticalSection &mutex;
  85. CriticalScope() = delete;
  86. CriticalScope& operator=(CriticalScope &cs) = delete;
  87. public:
  88. inline CriticalScope(CriticalSection &mutex_) : mutex(mutex_)
  89. {
  90. EnterCriticalSection(mutex);
  91. }
  92. inline ~CriticalScope()
  93. {
  94. LeaveCriticalSection(mutex);
  95. }
  96. };
  97. enum class Action {
  98. None,
  99. Update,
  100. Shutdown,
  101. ConfigVideo,
  102. ConfigAudio,
  103. ConfigCrossbar1,
  104. ConfigCrossbar2,
  105. };
  106. static DWORD CALLBACK DShowThread(LPVOID ptr);
  107. struct DShowInput {
  108. obs_source_t *source;
  109. Device device;
  110. bool deviceHasAudio;
  111. Decoder audio_decoder;
  112. Decoder video_decoder;
  113. VideoConfig videoConfig;
  114. AudioConfig audioConfig;
  115. obs_source_frame frame;
  116. obs_source_audio audio;
  117. WinHandle semaphore;
  118. WinHandle thread;
  119. CriticalSection mutex;
  120. vector<Action> actions;
  121. inline void QueueAction(Action action)
  122. {
  123. CriticalScope scope(mutex);
  124. actions.push_back(action);
  125. ReleaseSemaphore(semaphore, 1, nullptr);
  126. }
  127. inline DShowInput(obs_source_t *source_)
  128. : source (source_),
  129. device (InitGraph::False)
  130. {
  131. memset(&audio, 0, sizeof(audio));
  132. memset(&frame, 0, sizeof(frame));
  133. av_log_set_level(AV_LOG_WARNING);
  134. av_log_set_callback(ffmpeg_log);
  135. semaphore = CreateSemaphore(nullptr, 0, 0x7FFFFFFF, nullptr);
  136. if (!semaphore)
  137. throw "Failed to create semaphore";
  138. thread = CreateThread(nullptr, 0, DShowThread, this, 0,
  139. nullptr);
  140. if (!thread)
  141. throw "Failed to create thread";
  142. QueueAction(Action::Update);
  143. }
  144. inline ~DShowInput()
  145. {
  146. {
  147. CriticalScope scope(mutex);
  148. actions.resize(1);
  149. actions[0] = Action::Shutdown;
  150. }
  151. ReleaseSemaphore(semaphore, 1, nullptr);
  152. WaitForSingleObject(thread, INFINITE);
  153. }
  154. void OnEncodedVideoData(enum AVCodecID id,
  155. unsigned char *data, size_t size, long long ts);
  156. void OnEncodedAudioData(enum AVCodecID id,
  157. unsigned char *data, size_t size, long long ts);
  158. void OnVideoData(const VideoConfig &config,
  159. unsigned char *data, size_t size,
  160. long long startTime, long long endTime);
  161. void OnAudioData(const AudioConfig &config,
  162. unsigned char *data, size_t size,
  163. long long startTime, long long endTime);
  164. bool UpdateVideoConfig(obs_data_t *settings);
  165. bool UpdateAudioConfig(obs_data_t *settings);
  166. void Update(obs_data_t *settings);
  167. void DShowLoop();
  168. };
  169. static DWORD CALLBACK DShowThread(LPVOID ptr)
  170. {
  171. DShowInput *dshowInput = (DShowInput*)ptr;
  172. CoInitialize(nullptr);
  173. dshowInput->DShowLoop();
  174. CoUninitialize();
  175. return 0;
  176. }
  177. static inline void ProcessMessages()
  178. {
  179. MSG msg;
  180. while (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)) {
  181. TranslateMessage(&msg);
  182. DispatchMessage(&msg);
  183. }
  184. }
  185. /* Always keep directshow in a single thread for a given device */
  186. void DShowInput::DShowLoop()
  187. {
  188. while (true) {
  189. DWORD ret = MsgWaitForMultipleObjects(1, &semaphore, false,
  190. INFINITE, QS_ALLINPUT);
  191. if (ret == (WAIT_OBJECT_0 + 1)) {
  192. ProcessMessages();
  193. continue;
  194. } else if (ret != WAIT_OBJECT_0) {
  195. break;
  196. }
  197. Action action = Action::None;
  198. {
  199. CriticalScope scope(mutex);
  200. if (actions.size()) {
  201. action = actions.front();
  202. actions.erase(actions.begin());
  203. }
  204. }
  205. switch (action) {
  206. case Action::Update:
  207. {
  208. obs_data_t *settings;
  209. settings = obs_source_get_settings(source);
  210. Update(settings);
  211. obs_data_release(settings);
  212. break;
  213. }
  214. case Action::Shutdown:
  215. device.ShutdownGraph();
  216. return;
  217. case Action::ConfigVideo:
  218. device.OpenDialog(nullptr, DialogType::ConfigVideo);
  219. break;
  220. case Action::ConfigAudio:
  221. device.OpenDialog(nullptr, DialogType::ConfigAudio);
  222. break;
  223. case Action::ConfigCrossbar1:
  224. device.OpenDialog(nullptr, DialogType::ConfigCrossbar);
  225. break;
  226. case Action::ConfigCrossbar2:
  227. device.OpenDialog(nullptr, DialogType::ConfigCrossbar2);
  228. break;
  229. case Action::None:;
  230. }
  231. }
  232. }
  233. #define FPS_HIGHEST 0LL
  234. #define FPS_MATCHING -1LL
  235. template <typename T, typename U, typename V>
  236. static bool between(T &&lower, U &&value, V &&upper)
  237. {
  238. return value >= lower && value <= upper;
  239. }
  240. static bool ResolutionAvailable(const VideoInfo &cap, int cx, int cy)
  241. {
  242. return between(cap.minCX, cx, cap.maxCX) &&
  243. between(cap.minCY, cy, cap.maxCY);
  244. }
  245. #define DEVICE_INTERVAL_DIFF_LIMIT 20
  246. static bool FrameRateAvailable(const VideoInfo &cap, long long interval)
  247. {
  248. return interval == FPS_HIGHEST || interval == FPS_MATCHING ||
  249. between(cap.minInterval - DEVICE_INTERVAL_DIFF_LIMIT,
  250. interval,
  251. cap.maxInterval + DEVICE_INTERVAL_DIFF_LIMIT);
  252. }
  253. static long long FrameRateInterval(const VideoInfo &cap,
  254. long long desired_interval)
  255. {
  256. return desired_interval < cap.minInterval ?
  257. cap.minInterval :
  258. min(desired_interval, cap.maxInterval);
  259. }
  260. static inline video_format ConvertVideoFormat(VideoFormat format)
  261. {
  262. switch (format) {
  263. case VideoFormat::ARGB: return VIDEO_FORMAT_BGRA;
  264. case VideoFormat::XRGB: return VIDEO_FORMAT_BGRX;
  265. case VideoFormat::I420: return VIDEO_FORMAT_I420;
  266. case VideoFormat::YV12: return VIDEO_FORMAT_I420;
  267. case VideoFormat::NV12: return VIDEO_FORMAT_NV12;
  268. case VideoFormat::YVYU: return VIDEO_FORMAT_YVYU;
  269. case VideoFormat::YUY2: return VIDEO_FORMAT_YUY2;
  270. case VideoFormat::UYVY: return VIDEO_FORMAT_UYVY;
  271. case VideoFormat::HDYC: return VIDEO_FORMAT_UYVY;
  272. case VideoFormat::MJPEG: return VIDEO_FORMAT_YUY2;
  273. default: return VIDEO_FORMAT_NONE;
  274. }
  275. }
  276. static inline audio_format ConvertAudioFormat(AudioFormat format)
  277. {
  278. switch (format) {
  279. case AudioFormat::Wave16bit: return AUDIO_FORMAT_16BIT;
  280. case AudioFormat::WaveFloat: return AUDIO_FORMAT_FLOAT;
  281. default: return AUDIO_FORMAT_UNKNOWN;
  282. }
  283. }
  284. //#define LOG_ENCODED_VIDEO_TS 1
  285. //#define LOG_ENCODED_AUDIO_TS 1
  286. void DShowInput::OnEncodedVideoData(enum AVCodecID id,
  287. unsigned char *data, size_t size, long long ts)
  288. {
  289. if (!ffmpeg_decode_valid(video_decoder)) {
  290. if (ffmpeg_decode_init(video_decoder, id) < 0) {
  291. blog(LOG_WARNING, "Could not initialize video decoder");
  292. return;
  293. }
  294. }
  295. bool got_output;
  296. int len = ffmpeg_decode_video(video_decoder, data, size, &ts,
  297. &frame, &got_output);
  298. if (len < 0) {
  299. blog(LOG_WARNING, "Error decoding video");
  300. return;
  301. }
  302. if (got_output) {
  303. frame.timestamp = (uint64_t)ts * 100;
  304. #if LOG_ENCODED_VIDEO_TS
  305. blog(LOG_DEBUG, "video ts: %llu", frame.timestamp);
  306. #endif
  307. obs_source_output_video(source, &frame);
  308. }
  309. }
  310. void DShowInput::OnVideoData(const VideoConfig &config,
  311. unsigned char *data, size_t size,
  312. long long startTime, long long endTime)
  313. {
  314. if (videoConfig.format == VideoFormat::H264) {
  315. OnEncodedVideoData(AV_CODEC_ID_H264, data, size, startTime);
  316. return;
  317. }
  318. const int cx = config.cx;
  319. const int cy = config.cy;
  320. frame.timestamp = (uint64_t)startTime * 100;
  321. frame.width = config.cx;
  322. frame.height = config.cy;
  323. frame.format = ConvertVideoFormat(config.format);
  324. frame.full_range = false;
  325. frame.flip = (config.format == VideoFormat::XRGB ||
  326. config.format == VideoFormat::ARGB);
  327. if (videoConfig.format == VideoFormat::XRGB ||
  328. videoConfig.format == VideoFormat::ARGB) {
  329. frame.data[0] = data;
  330. frame.linesize[0] = cx * 4;
  331. } else if (videoConfig.format == VideoFormat::YVYU ||
  332. videoConfig.format == VideoFormat::YUY2 ||
  333. videoConfig.format == VideoFormat::HDYC ||
  334. videoConfig.format == VideoFormat::UYVY) {
  335. frame.data[0] = data;
  336. frame.linesize[0] = cx * 2;
  337. } else if (videoConfig.format == VideoFormat::I420) {
  338. frame.data[0] = data;
  339. frame.data[1] = frame.data[0] + (cx * cy);
  340. frame.data[2] = frame.data[1] + (cx * cy / 4);
  341. frame.linesize[0] = cx;
  342. frame.linesize[1] = cx / 2;
  343. frame.linesize[2] = cx / 2;
  344. } else if (videoConfig.format == VideoFormat::YV12) {
  345. frame.data[0] = data;
  346. frame.data[2] = frame.data[0] + (cx * cy);
  347. frame.data[1] = frame.data[2] + (cx * cy / 4);
  348. frame.linesize[0] = cx;
  349. frame.linesize[1] = cx / 2;
  350. frame.linesize[2] = cx / 2;
  351. } else if (videoConfig.format == VideoFormat::NV12) {
  352. frame.data[0] = data;
  353. frame.data[1] = frame.data[0] + (cx * cy);
  354. frame.linesize[0] = cx;
  355. frame.linesize[1] = cx;
  356. } else {
  357. /* TODO: other formats */
  358. return;
  359. }
  360. obs_source_output_video(source, &frame);
  361. UNUSED_PARAMETER(endTime); /* it's the enndd tiimmes! */
  362. UNUSED_PARAMETER(size);
  363. }
  364. void DShowInput::OnEncodedAudioData(enum AVCodecID id,
  365. unsigned char *data, size_t size, long long ts)
  366. {
  367. if (!ffmpeg_decode_valid(audio_decoder)) {
  368. if (ffmpeg_decode_init(audio_decoder, id) < 0) {
  369. blog(LOG_WARNING, "Could not initialize audio decoder");
  370. return;
  371. }
  372. }
  373. bool got_output;
  374. int len = ffmpeg_decode_audio(audio_decoder, data, size,
  375. &audio, &got_output);
  376. if (len < 0) {
  377. blog(LOG_WARNING, "Error decoding audio");
  378. return;
  379. }
  380. if (got_output) {
  381. audio.timestamp = (uint64_t)ts * 100;
  382. #if LOG_ENCODED_AUDIO_TS
  383. blog(LOG_DEBUG, "audio ts: %llu", audio.timestamp);
  384. #endif
  385. obs_source_output_audio(source, &audio);
  386. }
  387. }
  388. void DShowInput::OnAudioData(const AudioConfig &config,
  389. unsigned char *data, size_t size,
  390. long long startTime, long long endTime)
  391. {
  392. size_t block_size;
  393. if (config.format == AudioFormat::AAC) {
  394. OnEncodedAudioData(AV_CODEC_ID_AAC, data, size, startTime);
  395. return;
  396. } else if (config.format == AudioFormat::AC3) {
  397. OnEncodedAudioData(AV_CODEC_ID_AC3, data, size, startTime);
  398. return;
  399. } else if (config.format == AudioFormat::MPGA) {
  400. OnEncodedAudioData(AV_CODEC_ID_MP2, data, size, startTime);
  401. return;
  402. }
  403. audio.speakers = (enum speaker_layout)config.channels;
  404. audio.format = ConvertAudioFormat(config.format);
  405. audio.samples_per_sec = (uint32_t)config.sampleRate;
  406. audio.data[0] = data;
  407. block_size = get_audio_bytes_per_channel(audio.format) *
  408. get_audio_channels(audio.speakers);
  409. audio.frames = (uint32_t)(size / block_size);
  410. audio.timestamp = (uint64_t)startTime * 100;
  411. if (audio.format != AUDIO_FORMAT_UNKNOWN)
  412. obs_source_output_audio(source, &audio);
  413. UNUSED_PARAMETER(endTime);
  414. }
  415. struct PropertiesData {
  416. vector<VideoDevice> devices;
  417. vector<AudioDevice> audioDevices;
  418. bool GetDevice(VideoDevice &device, const char *encoded_id) const
  419. {
  420. DeviceId deviceId;
  421. DecodeDeviceId(deviceId, encoded_id);
  422. for (const VideoDevice &curDevice : devices) {
  423. if (deviceId.name == curDevice.name &&
  424. deviceId.path == curDevice.path) {
  425. device = curDevice;
  426. return true;
  427. }
  428. }
  429. return false;
  430. }
  431. };
  432. static inline bool ConvertRes(int &cx, int &cy, const char *res)
  433. {
  434. return sscanf(res, "%dx%d", &cx, &cy) == 2;
  435. }
  436. static inline bool FormatMatches(VideoFormat left, VideoFormat right)
  437. {
  438. return left == VideoFormat::Any || right == VideoFormat::Any ||
  439. left == right;
  440. }
  441. static inline bool ResolutionValid(string res, int &cx, int &cy)
  442. {
  443. if (!res.size())
  444. return false;
  445. return ConvertRes(cx, cy, res.c_str());
  446. }
  447. template <typename F, typename ... Fs>
  448. static inline bool CapsMatch(const VideoInfo &info, F&& f, Fs ... fs)
  449. {
  450. return f(info) && CapsMatch(info, fs ...);
  451. }
  452. static inline bool CapsMatch(const VideoInfo&)
  453. {
  454. return true;
  455. }
  456. template <typename ... F>
  457. static bool CapsMatch(const VideoDevice &dev, F ... fs)
  458. {
  459. auto matcher = [&](const VideoInfo &info)
  460. {
  461. return CapsMatch(info, fs ...);
  462. };
  463. return any_of(begin(dev.caps), end(dev.caps), matcher);
  464. }
  465. static inline bool MatcherMatchVideoFormat(VideoFormat format,
  466. bool &did_match, const VideoInfo &info)
  467. {
  468. bool match = FormatMatches(format, info.format);
  469. did_match = did_match || match;
  470. return match;
  471. }
  472. static inline bool MatcherClosestFrameRateSelector(long long interval,
  473. long long &best_match, const VideoInfo &info)
  474. {
  475. long long current = FrameRateInterval(info, interval);
  476. if (llabs(interval - best_match) > llabs(interval - current))
  477. best_match = current;
  478. return true;
  479. }
  480. #if 0
  481. auto ResolutionMatcher = [](int cx, int cy)
  482. {
  483. return [cx, cy](const VideoInfo &info)
  484. {
  485. return ResolutionAvailable(info, cx, cy);
  486. };
  487. };
  488. auto FrameRateMatcher = [](long long interval)
  489. {
  490. return [interval](const VideoInfo &info)
  491. {
  492. return FrameRateAvailable(info, interval);
  493. };
  494. };
  495. auto VideoFormatMatcher = [](VideoFormat format, bool &did_match)
  496. {
  497. return [format, &did_match](const VideoInfo &info)
  498. {
  499. return MatcherMatchVideoFormat(format, did_match, info);
  500. };
  501. };
  502. auto ClosestFrameRateSelector = [](long long interval, long long &best_match)
  503. {
  504. return [interval, &best_match](const VideoInfo &info) mutable -> bool
  505. {
  506. MatcherClosestFrameRateSelector(interval, best_match, info);
  507. };
  508. }
  509. #else
  510. #define ResolutionMatcher(cx, cy) \
  511. [cx, cy](const VideoInfo &info) -> bool \
  512. { return ResolutionAvailable(info, cx, cy); }
  513. #define FrameRateMatcher(interval) \
  514. [interval](const VideoInfo &info) -> bool \
  515. { return FrameRateAvailable(info, interval); }
  516. #define VideoFormatMatcher(format, did_match) \
  517. [format, &did_match](const VideoInfo &info) mutable -> bool \
  518. { return MatcherMatchVideoFormat(format, did_match, info); }
  519. #define ClosestFrameRateSelector(interval, best_match) \
  520. [interval, &best_match](const VideoInfo &info) mutable -> bool \
  521. { return MatcherClosestFrameRateSelector(interval, best_match, info); }
  522. #endif
  523. static bool ResolutionAvailable(const VideoDevice &dev, int cx, int cy)
  524. {
  525. return CapsMatch(dev, ResolutionMatcher(cx, cy));
  526. }
  527. static bool DetermineResolution(int &cx, int &cy, obs_data_t *settings,
  528. VideoDevice dev)
  529. {
  530. const char *res = obs_data_get_autoselect_string(settings, RESOLUTION);
  531. if (obs_data_has_autoselect_value(settings, RESOLUTION) &&
  532. ConvertRes(cx, cy, res) &&
  533. ResolutionAvailable(dev, cx, cy))
  534. return true;
  535. res = obs_data_get_string(settings, RESOLUTION);
  536. if (ConvertRes(cx, cy, res) && ResolutionAvailable(dev, cx, cy))
  537. return true;
  538. res = obs_data_get_string(settings, LAST_RESOLUTION);
  539. if (ConvertRes(cx, cy, res) && ResolutionAvailable(dev, cx, cy))
  540. return true;
  541. return false;
  542. }
  543. static long long GetOBSFPS();
  544. bool DShowInput::UpdateVideoConfig(obs_data_t *settings)
  545. {
  546. string video_device_id = obs_data_get_string(settings, VIDEO_DEVICE_ID);
  547. DeviceId id;
  548. if (!DecodeDeviceId(id, video_device_id.c_str()))
  549. return false;
  550. PropertiesData data;
  551. Device::EnumVideoDevices(data.devices);
  552. VideoDevice dev;
  553. if (!data.GetDevice(dev, video_device_id.c_str()))
  554. return false;
  555. int resType = (int)obs_data_get_int(settings, RES_TYPE);
  556. int cx = 0, cy = 0;
  557. long long interval = 0;
  558. VideoFormat format = VideoFormat::Any;
  559. if (resType == ResType_Custom) {
  560. bool has_autosel_val;
  561. string resolution = obs_data_get_string(settings, RESOLUTION);
  562. if (!ResolutionValid(resolution, cx, cy))
  563. return false;
  564. has_autosel_val = obs_data_has_autoselect_value(settings,
  565. FRAME_INTERVAL);
  566. interval = has_autosel_val ?
  567. obs_data_get_autoselect_int(settings, FRAME_INTERVAL) :
  568. obs_data_get_int(settings, FRAME_INTERVAL);
  569. if (interval == FPS_MATCHING)
  570. interval = GetOBSFPS();
  571. format = (VideoFormat)obs_data_get_int(settings, VIDEO_FORMAT);
  572. long long best_interval = numeric_limits<long long>::max();
  573. bool video_format_match = false;
  574. if (!CapsMatch(dev,
  575. ResolutionMatcher(cx, cy),
  576. VideoFormatMatcher(format, video_format_match),
  577. ClosestFrameRateSelector(interval, best_interval),
  578. FrameRateMatcher(interval)) && !video_format_match)
  579. return false;
  580. interval = best_interval;
  581. blog(LOG_INFO, "%s: Using interval %lld",
  582. obs_source_get_name(source), interval);
  583. }
  584. videoConfig.name = id.name.c_str();
  585. videoConfig.path = id.path.c_str();
  586. videoConfig.useDefaultConfig = resType == ResType_Preferred;
  587. videoConfig.cx = cx;
  588. videoConfig.cy = cy;
  589. videoConfig.frameInterval = interval;
  590. videoConfig.internalFormat = format;
  591. deviceHasAudio = dev.audioAttached;
  592. videoConfig.callback = std::bind(&DShowInput::OnVideoData, this,
  593. placeholders::_1, placeholders::_2,
  594. placeholders::_3, placeholders::_4,
  595. placeholders::_5);
  596. if (videoConfig.internalFormat != VideoFormat::MJPEG)
  597. videoConfig.format = videoConfig.internalFormat;
  598. if (!device.SetVideoConfig(&videoConfig))
  599. return false;
  600. if (videoConfig.internalFormat == VideoFormat::MJPEG) {
  601. videoConfig.format = VideoFormat::XRGB;
  602. if (!device.SetVideoConfig(&videoConfig))
  603. return false;
  604. }
  605. return true;
  606. }
  607. bool DShowInput::UpdateAudioConfig(obs_data_t *settings)
  608. {
  609. string audio_device_id = obs_data_get_string(settings, AUDIO_DEVICE_ID);
  610. bool useCustomAudio = obs_data_get_bool(settings, USE_CUSTOM_AUDIO);
  611. if (useCustomAudio) {
  612. DeviceId id;
  613. if (!DecodeDeviceId(id, audio_device_id.c_str()))
  614. return false;
  615. audioConfig.name = id.name.c_str();
  616. audioConfig.path = id.path.c_str();
  617. } else if (!deviceHasAudio) {
  618. return true;
  619. }
  620. audioConfig.useVideoDevice = !useCustomAudio;
  621. audioConfig.callback = std::bind(&DShowInput::OnAudioData, this,
  622. placeholders::_1, placeholders::_2,
  623. placeholders::_3, placeholders::_4,
  624. placeholders::_5);
  625. return device.SetAudioConfig(&audioConfig);
  626. }
  627. void DShowInput::Update(obs_data_t *settings)
  628. {
  629. if (!device.ResetGraph())
  630. return;
  631. if (!UpdateVideoConfig(settings)) {
  632. blog(LOG_WARNING, "%s: Video configuration failed",
  633. obs_source_get_name(source));
  634. return;
  635. }
  636. if (!UpdateAudioConfig(settings))
  637. blog(LOG_WARNING, "%s: Audio configuration failed, ignoring "
  638. "audio", obs_source_get_name(source));
  639. if (!device.ConnectFilters())
  640. return;
  641. if (device.Start() != Result::Success)
  642. return;
  643. enum video_colorspace cs = (videoConfig.format == VideoFormat::HDYC) ?
  644. VIDEO_CS_709 : VIDEO_CS_601;
  645. if (!video_format_get_parameters(cs, VIDEO_RANGE_PARTIAL,
  646. frame.color_matrix,
  647. frame.color_range_min,
  648. frame.color_range_max)) {
  649. blog(LOG_ERROR, "Failed to get video format parameters for " \
  650. "video format %u", cs);
  651. }
  652. }
  653. /* ------------------------------------------------------------------------- */
  654. static const char *GetDShowInputName(void)
  655. {
  656. return TEXT_INPUT_NAME;
  657. }
  658. static void *CreateDShowInput(obs_data_t *settings, obs_source_t *source)
  659. {
  660. DShowInput *dshow = nullptr;
  661. try {
  662. dshow = new DShowInput(source);
  663. } catch (const char *error) {
  664. blog(LOG_ERROR, "Could not create device '%s': %s",
  665. obs_source_get_name(source), error);
  666. }
  667. UNUSED_PARAMETER(settings);
  668. return dshow;
  669. }
  670. static void DestroyDShowInput(void *data)
  671. {
  672. delete reinterpret_cast<DShowInput*>(data);
  673. }
  674. static void UpdateDShowInput(void *data, obs_data_t *settings)
  675. {
  676. UNUSED_PARAMETER(settings);
  677. reinterpret_cast<DShowInput*>(data)->QueueAction(Action::Update);
  678. }
  679. static void GetDShowDefaults(obs_data_t *settings)
  680. {
  681. obs_data_set_default_int(settings, FRAME_INTERVAL, FPS_MATCHING);
  682. obs_data_set_default_int(settings, RES_TYPE, ResType_Preferred);
  683. obs_data_set_default_int(settings, VIDEO_FORMAT, (int)VideoFormat::Any);
  684. }
  685. struct Resolution {
  686. int cx, cy;
  687. inline Resolution(int cx, int cy) : cx(cx), cy(cy) {}
  688. };
  689. static void InsertResolution(vector<Resolution> &resolutions, int cx, int cy)
  690. {
  691. int bestCY = 0;
  692. size_t idx = 0;
  693. for (; idx < resolutions.size(); idx++) {
  694. const Resolution &res = resolutions[idx];
  695. if (res.cx > cx)
  696. break;
  697. if (res.cx == cx) {
  698. if (res.cy == cy)
  699. return;
  700. if (!bestCY)
  701. bestCY = res.cy;
  702. else if (res.cy > bestCY)
  703. break;
  704. }
  705. }
  706. resolutions.insert(resolutions.begin() + idx, Resolution(cx, cy));
  707. }
  708. static inline void AddCap(vector<Resolution> &resolutions, const VideoInfo &cap)
  709. {
  710. InsertResolution(resolutions, cap.minCX, cap.minCY);
  711. InsertResolution(resolutions, cap.maxCX, cap.maxCY);
  712. }
  713. #define MAKE_DSHOW_FPS(fps) (10000000LL/(fps))
  714. #define MAKE_DSHOW_FRACTIONAL_FPS(den, num) ((num)*10000000LL/(den))
  715. static long long GetOBSFPS()
  716. {
  717. obs_video_info ovi;
  718. if (!obs_get_video_info(&ovi))
  719. return 0;
  720. return MAKE_DSHOW_FRACTIONAL_FPS(ovi.fps_num, ovi.fps_den);
  721. }
  722. struct FPSFormat {
  723. const char *text;
  724. long long interval;
  725. };
  726. static const FPSFormat validFPSFormats[] = {
  727. {"60", MAKE_DSHOW_FPS(60)},
  728. {"59.94 NTSC", MAKE_DSHOW_FRACTIONAL_FPS(60000, 1001)},
  729. {"50", MAKE_DSHOW_FPS(50)},
  730. {"48 film", MAKE_DSHOW_FRACTIONAL_FPS(48000, 1001)},
  731. {"40", MAKE_DSHOW_FPS(40)},
  732. {"30", MAKE_DSHOW_FPS(30)},
  733. {"29.97 NTSC", MAKE_DSHOW_FRACTIONAL_FPS(30000, 1001)},
  734. {"25", MAKE_DSHOW_FPS(25)},
  735. {"24 film", MAKE_DSHOW_FRACTIONAL_FPS(24000, 1001)},
  736. {"20", MAKE_DSHOW_FPS(20)},
  737. {"15", MAKE_DSHOW_FPS(15)},
  738. {"10", MAKE_DSHOW_FPS(10)},
  739. {"5", MAKE_DSHOW_FPS(5)},
  740. {"4", MAKE_DSHOW_FPS(4)},
  741. {"3", MAKE_DSHOW_FPS(3)},
  742. {"2", MAKE_DSHOW_FPS(2)},
  743. {"1", MAKE_DSHOW_FPS(1)},
  744. };
  745. static bool DeviceIntervalChanged(obs_properties_t *props, obs_property_t *p,
  746. obs_data_t *settings);
  747. static bool TryResolution(VideoDevice &dev, string res)
  748. {
  749. int cx, cy;
  750. if (!ConvertRes(cx, cy, res.c_str()))
  751. return false;
  752. return ResolutionAvailable(dev, cx, cy);
  753. }
  754. static bool SetResolution(obs_properties_t *props, obs_data_t *settings,
  755. string res, bool autoselect=false)
  756. {
  757. if (autoselect)
  758. obs_data_set_autoselect_string(settings, RESOLUTION,
  759. res.c_str());
  760. else
  761. obs_data_unset_autoselect_value(settings, RESOLUTION);
  762. DeviceIntervalChanged(props, obs_properties_get(props, FRAME_INTERVAL),
  763. settings);
  764. if (!autoselect)
  765. obs_data_set_string(settings, LAST_RESOLUTION, res.c_str());
  766. return true;
  767. }
  768. static bool DeviceResolutionChanged(obs_properties_t *props, obs_property_t *p,
  769. obs_data_t *settings)
  770. {
  771. UNUSED_PARAMETER(p);
  772. PropertiesData *data = (PropertiesData*)obs_properties_get_param(props);
  773. const char *id;
  774. VideoDevice device;
  775. id = obs_data_get_string(settings, VIDEO_DEVICE_ID);
  776. string res = obs_data_get_string(settings, RESOLUTION);
  777. string last_res = obs_data_get_string(settings, LAST_RESOLUTION);
  778. if (!data->GetDevice(device, id))
  779. return false;
  780. if (TryResolution(device, res))
  781. return SetResolution(props, settings, res);
  782. if (TryResolution(device, last_res))
  783. return SetResolution(props, settings, last_res, true);
  784. return false;
  785. }
  786. struct VideoFormatName {
  787. VideoFormat format;
  788. const char *name;
  789. };
  790. static const VideoFormatName videoFormatNames[] = {
  791. /* autoselect format*/
  792. {VideoFormat::Any, "VideoFormat.Any"},
  793. /* raw formats */
  794. {VideoFormat::ARGB, "ARGB"},
  795. {VideoFormat::XRGB, "XRGB"},
  796. /* planar YUV formats */
  797. {VideoFormat::I420, "I420"},
  798. {VideoFormat::NV12, "NV12"},
  799. {VideoFormat::YV12, "YV12"},
  800. /* packed YUV formats */
  801. {VideoFormat::YVYU, "YVYU"},
  802. {VideoFormat::YUY2, "YUY2"},
  803. {VideoFormat::UYVY, "UYVY"},
  804. {VideoFormat::HDYC, "HDYC"},
  805. /* encoded formats */
  806. {VideoFormat::MJPEG, "MJPEG"},
  807. {VideoFormat::H264, "H264"}
  808. };
  809. static bool ResTypeChanged(obs_properties_t *props, obs_property_t *p,
  810. obs_data_t *settings);
  811. static size_t AddDevice(obs_property_t *device_list, const string &id)
  812. {
  813. DStr name, path;
  814. if (!DecodeDeviceDStr(name, path, id.c_str()))
  815. return numeric_limits<size_t>::max();
  816. return obs_property_list_add_string(device_list, name, id.c_str());
  817. }
  818. static bool UpdateDeviceList(obs_property_t *list, const string &id)
  819. {
  820. size_t size = obs_property_list_item_count(list);
  821. bool found = false;
  822. bool disabled_unknown_found = false;
  823. for (size_t i = 0; i < size; i++) {
  824. if (obs_property_list_item_string(list, i) == id) {
  825. found = true;
  826. continue;
  827. }
  828. if (obs_property_list_item_disabled(list, i))
  829. disabled_unknown_found = true;
  830. }
  831. if (!found && !disabled_unknown_found) {
  832. size_t idx = AddDevice(list, id);
  833. obs_property_list_item_disable(list, idx, true);
  834. return true;
  835. }
  836. if (found && !disabled_unknown_found)
  837. return false;
  838. for (size_t i = 0; i < size;) {
  839. if (obs_property_list_item_disabled(list, i)) {
  840. obs_property_list_item_remove(list, i);
  841. continue;
  842. }
  843. i += 1;
  844. }
  845. return true;
  846. }
  847. static bool DeviceSelectionChanged(obs_properties_t *props, obs_property_t *p,
  848. obs_data_t *settings)
  849. {
  850. PropertiesData *data = (PropertiesData*)obs_properties_get_param(props);
  851. VideoDevice device;
  852. string id = obs_data_get_string(settings, VIDEO_DEVICE_ID);
  853. string old_id = obs_data_get_string(settings, LAST_VIDEO_DEV_ID);
  854. bool device_list_updated = UpdateDeviceList(p, id);
  855. if (!data->GetDevice(device, id.c_str()))
  856. return !device_list_updated;
  857. vector<Resolution> resolutions;
  858. for (const VideoInfo &cap : device.caps)
  859. AddCap(resolutions, cap);
  860. p = obs_properties_get(props, RESOLUTION);
  861. obs_property_list_clear(p);
  862. for (size_t idx = resolutions.size(); idx > 0; idx--) {
  863. const Resolution &res = resolutions[idx-1];
  864. string strRes;
  865. strRes += to_string(res.cx);
  866. strRes += "x";
  867. strRes += to_string(res.cy);
  868. obs_property_list_add_string(p, strRes.c_str(), strRes.c_str());
  869. }
  870. /* only refresh properties if device legitimately changed */
  871. if (!id.size() || !old_id.size() || id != old_id) {
  872. p = obs_properties_get(props, RES_TYPE);
  873. ResTypeChanged(props, p, settings);
  874. obs_data_set_string(settings, LAST_VIDEO_DEV_ID, id.c_str());
  875. }
  876. return true;
  877. }
  878. static bool VideoConfigClicked(obs_properties_t *props, obs_property_t *p,
  879. void *data)
  880. {
  881. DShowInput *input = reinterpret_cast<DShowInput*>(data);
  882. input->QueueAction(Action::ConfigVideo);
  883. UNUSED_PARAMETER(props);
  884. UNUSED_PARAMETER(p);
  885. return false;
  886. }
  887. /*static bool AudioConfigClicked(obs_properties_t *props, obs_property_t *p,
  888. void *data)
  889. {
  890. DShowInput *input = reinterpret_cast<DShowInput*>(data);
  891. input->QueueAction(Action::ConfigAudio);
  892. UNUSED_PARAMETER(props);
  893. UNUSED_PARAMETER(p);
  894. return false;
  895. }*/
  896. static bool CrossbarConfigClicked(obs_properties_t *props, obs_property_t *p,
  897. void *data)
  898. {
  899. DShowInput *input = reinterpret_cast<DShowInput*>(data);
  900. input->QueueAction(Action::ConfigCrossbar1);
  901. UNUSED_PARAMETER(props);
  902. UNUSED_PARAMETER(p);
  903. return false;
  904. }
  905. /*static bool Crossbar2ConfigClicked(obs_properties_t *props, obs_property_t *p,
  906. void *data)
  907. {
  908. DShowInput *input = reinterpret_cast<DShowInput*>(data);
  909. input->QueueAction(Action::ConfigCrossbar2);
  910. UNUSED_PARAMETER(props);
  911. UNUSED_PARAMETER(p);
  912. return false;
  913. }*/
  914. static bool AddDevice(obs_property_t *device_list, const VideoDevice &device)
  915. {
  916. DStr name, path, device_id;
  917. dstr_from_wcs(name, device.name.c_str());
  918. dstr_from_wcs(path, device.path.c_str());
  919. encode_dstr(path);
  920. dstr_copy_dstr(device_id, name);
  921. encode_dstr(device_id);
  922. dstr_cat(device_id, ":");
  923. dstr_cat_dstr(device_id, path);
  924. obs_property_list_add_string(device_list, name, device_id);
  925. return true;
  926. }
  927. static bool AddAudioDevice(obs_property_t *device_list,
  928. const AudioDevice &device)
  929. {
  930. DStr name, path, device_id;
  931. dstr_from_wcs(name, device.name.c_str());
  932. dstr_from_wcs(path, device.path.c_str());
  933. encode_dstr(path);
  934. dstr_copy_dstr(device_id, name);
  935. encode_dstr(device_id);
  936. dstr_cat(device_id, ":");
  937. dstr_cat_dstr(device_id, path);
  938. obs_property_list_add_string(device_list, name, device_id);
  939. return true;
  940. }
  941. static void PropertiesDataDestroy(void *data)
  942. {
  943. delete reinterpret_cast<PropertiesData*>(data);
  944. }
  945. static bool ResTypeChanged(obs_properties_t *props, obs_property_t *p,
  946. obs_data_t *settings)
  947. {
  948. int val = (int)obs_data_get_int(settings, RES_TYPE);
  949. bool enabled = (val != ResType_Preferred);
  950. p = obs_properties_get(props, RESOLUTION);
  951. obs_property_set_enabled(p, enabled);
  952. p = obs_properties_get(props, FRAME_INTERVAL);
  953. obs_property_set_enabled(p, enabled);
  954. p = obs_properties_get(props, VIDEO_FORMAT);
  955. obs_property_set_enabled(p, enabled);
  956. if (val == ResType_Custom) {
  957. p = obs_properties_get(props, RESOLUTION);
  958. DeviceResolutionChanged(props, p, settings);
  959. } else {
  960. obs_data_unset_autoselect_value(settings, FRAME_INTERVAL);
  961. }
  962. return true;
  963. }
  964. static DStr GetFPSName(long long interval)
  965. {
  966. DStr name;
  967. if (interval == FPS_MATCHING) {
  968. dstr_cat(name, TEXT_FPS_MATCHING);
  969. return name;
  970. }
  971. if (interval == FPS_HIGHEST) {
  972. dstr_cat(name, TEXT_FPS_HIGHEST);
  973. return name;
  974. }
  975. for (const FPSFormat &format : validFPSFormats) {
  976. if (format.interval != interval)
  977. continue;
  978. dstr_cat(name, format.text);
  979. return name;
  980. }
  981. dstr_cat(name, to_string(10000000. / interval).c_str());
  982. return name;
  983. }
  984. static void UpdateFPS(VideoDevice &device, VideoFormat format,
  985. long long interval, int cx, int cy, obs_properties_t *props)
  986. {
  987. obs_property_t *list = obs_properties_get(props, FRAME_INTERVAL);
  988. obs_property_list_clear(list);
  989. obs_property_list_add_int(list, TEXT_FPS_MATCHING, FPS_MATCHING);
  990. obs_property_list_add_int(list, TEXT_FPS_HIGHEST, FPS_HIGHEST);
  991. bool interval_added = interval == FPS_HIGHEST ||
  992. interval == FPS_MATCHING;
  993. for (const FPSFormat &fps_format : validFPSFormats) {
  994. bool video_format_match = false;
  995. long long format_interval = fps_format.interval;
  996. bool available = CapsMatch(device,
  997. ResolutionMatcher(cx, cy),
  998. VideoFormatMatcher(format, video_format_match),
  999. FrameRateMatcher(format_interval));
  1000. if (!available && interval != fps_format.interval)
  1001. continue;
  1002. if (interval == fps_format.interval)
  1003. interval_added = true;
  1004. size_t idx = obs_property_list_add_int(list, fps_format.text,
  1005. fps_format.interval);
  1006. obs_property_list_item_disable(list, idx, !available);
  1007. }
  1008. if (interval_added)
  1009. return;
  1010. size_t idx = obs_property_list_add_int(list, GetFPSName(interval),
  1011. interval);
  1012. obs_property_list_item_disable(list, idx, true);
  1013. }
  1014. static DStr GetVideoFormatName(VideoFormat format)
  1015. {
  1016. DStr name;
  1017. for (const VideoFormatName &format_ : videoFormatNames) {
  1018. if (format_.format == format) {
  1019. dstr_cat(name, obs_module_text(format_.name));
  1020. return name;
  1021. }
  1022. }
  1023. dstr_cat(name, TEXT_FORMAT_UNKNOWN);
  1024. dstr_replace(name, "%1", std::to_string((long long)format).c_str());
  1025. return name;
  1026. }
  1027. static void UpdateVideoFormats(VideoDevice &device, VideoFormat format_,
  1028. int cx, int cy, long long interval, obs_properties_t *props)
  1029. {
  1030. set<VideoFormat> formats = { VideoFormat::Any };
  1031. auto format_gatherer = [&formats](const VideoInfo &info) mutable -> bool
  1032. {
  1033. formats.insert(info.format);
  1034. return false;
  1035. };
  1036. CapsMatch(device,
  1037. ResolutionMatcher(cx, cy),
  1038. FrameRateMatcher(interval),
  1039. format_gatherer);
  1040. obs_property_t *list = obs_properties_get(props, VIDEO_FORMAT);
  1041. obs_property_list_clear(list);
  1042. bool format_added = false;
  1043. for (const VideoFormatName &format : videoFormatNames) {
  1044. bool available = formats.find(format.format) != end(formats);
  1045. if (!available && format.format != format_)
  1046. continue;
  1047. if (format.format == format_)
  1048. format_added = true;
  1049. size_t idx = obs_property_list_add_int(list,
  1050. obs_module_text(format.name),
  1051. (long long)format.format);
  1052. obs_property_list_item_disable(list, idx, !available);
  1053. }
  1054. if (format_added)
  1055. return;
  1056. size_t idx = obs_property_list_add_int(list,
  1057. GetVideoFormatName(format_), (long long)format_);
  1058. obs_property_list_item_disable(list, idx, true);
  1059. }
  1060. static bool UpdateFPS(long long interval, obs_property_t *list)
  1061. {
  1062. size_t size = obs_property_list_item_count(list);
  1063. bool fps_found = false;
  1064. DStr name;
  1065. for (size_t i = 0; i < size; i++) {
  1066. if (obs_property_list_item_int(list, i) != interval)
  1067. continue;
  1068. obs_property_list_item_disable(list, i, true);
  1069. if (size == 1)
  1070. return false;
  1071. dstr_cat(name, obs_property_list_item_name(list, i));
  1072. fps_found = true;
  1073. break;
  1074. }
  1075. obs_property_list_clear(list);
  1076. if (!name->len)
  1077. name = GetFPSName(interval);
  1078. obs_property_list_add_int(list, name, interval);
  1079. obs_property_list_item_disable(list, 0, true);
  1080. return true;
  1081. }
  1082. static bool DeviceIntervalChanged(obs_properties_t *props, obs_property_t *p,
  1083. obs_data_t *settings)
  1084. {
  1085. long long val = obs_data_get_int(settings, FRAME_INTERVAL);
  1086. PropertiesData *data = (PropertiesData*)obs_properties_get_param(props);
  1087. const char *id = obs_data_get_string(settings, VIDEO_DEVICE_ID);
  1088. VideoDevice device;
  1089. if (!data->GetDevice(device, id))
  1090. return UpdateFPS(val, p);
  1091. int cx = 0, cy = 0;
  1092. if (!DetermineResolution(cx, cy, settings, device)) {
  1093. UpdateVideoFormats(device, VideoFormat::Any, 0, 0, 0, props);
  1094. UpdateFPS(device, VideoFormat::Any, 0, 0, 0, props);
  1095. return true;
  1096. }
  1097. int resType = (int)obs_data_get_int(settings, RES_TYPE);
  1098. if (resType != ResType_Custom)
  1099. return true;
  1100. if (val == FPS_MATCHING)
  1101. val = GetOBSFPS();
  1102. VideoFormat format = (VideoFormat)obs_data_get_int(settings,
  1103. VIDEO_FORMAT);
  1104. bool video_format_matches = false;
  1105. long long best_interval = numeric_limits<long long>::max();
  1106. bool frameRateSupported = CapsMatch(device,
  1107. ResolutionMatcher(cx, cy),
  1108. VideoFormatMatcher(format, video_format_matches),
  1109. ClosestFrameRateSelector(val, best_interval),
  1110. FrameRateMatcher(val));
  1111. if (video_format_matches &&
  1112. !frameRateSupported &&
  1113. best_interval != val) {
  1114. long long listed_val = 0;
  1115. for (const FPSFormat &format : validFPSFormats) {
  1116. long long diff = llabs(format.interval - best_interval);
  1117. if (diff < DEVICE_INTERVAL_DIFF_LIMIT) {
  1118. listed_val = format.interval;
  1119. break;
  1120. }
  1121. }
  1122. if (listed_val != val)
  1123. obs_data_set_autoselect_int(settings, FRAME_INTERVAL,
  1124. listed_val);
  1125. } else {
  1126. obs_data_unset_autoselect_value(settings, FRAME_INTERVAL);
  1127. }
  1128. UpdateVideoFormats(device, format, cx, cy, val, props);
  1129. UpdateFPS(device, format, val, cx, cy, props);
  1130. UNUSED_PARAMETER(p);
  1131. return true;
  1132. }
  1133. static bool UpdateVideoFormats(VideoFormat format, obs_property_t *list)
  1134. {
  1135. size_t size = obs_property_list_item_count(list);
  1136. DStr name;
  1137. for (size_t i = 0; i < size; i++) {
  1138. if ((VideoFormat)obs_property_list_item_int(list, i) != format)
  1139. continue;
  1140. if (size == 1)
  1141. return false;
  1142. dstr_cat(name, obs_property_list_item_name(list, i));
  1143. break;
  1144. }
  1145. obs_property_list_clear(list);
  1146. if (!name->len)
  1147. name = GetVideoFormatName(format);
  1148. obs_property_list_add_int(list, name, (long long)format);
  1149. obs_property_list_item_disable(list, 0, true);
  1150. return true;
  1151. }
  1152. static bool VideoFormatChanged(obs_properties_t *props, obs_property_t *p,
  1153. obs_data_t *settings)
  1154. {
  1155. PropertiesData *data = (PropertiesData*)obs_properties_get_param(props);
  1156. const char *id = obs_data_get_string(settings, VIDEO_DEVICE_ID);
  1157. VideoDevice device;
  1158. VideoFormat curFormat =
  1159. (VideoFormat)obs_data_get_int(settings, VIDEO_FORMAT);
  1160. if (!data->GetDevice(device, id))
  1161. return UpdateVideoFormats(curFormat, p);
  1162. int cx, cy;
  1163. if (!DetermineResolution(cx, cy, settings, device)) {
  1164. UpdateVideoFormats(device, VideoFormat::Any, cx, cy, 0, props);
  1165. UpdateFPS(device, VideoFormat::Any, 0, 0, 0, props);
  1166. return true;
  1167. }
  1168. long long interval = obs_data_get_int(settings, FRAME_INTERVAL);
  1169. UpdateVideoFormats(device, curFormat, cx, cy, interval, props);
  1170. UpdateFPS(device, curFormat, interval, cx, cy, props);
  1171. return true;
  1172. }
  1173. static bool CustomAudioClicked(obs_properties_t *props, obs_property_t *p,
  1174. obs_data_t *settings)
  1175. {
  1176. bool useCustomAudio = obs_data_get_bool(settings, USE_CUSTOM_AUDIO);
  1177. p = obs_properties_get(props, AUDIO_DEVICE_ID);
  1178. obs_property_set_visible(p, useCustomAudio);
  1179. return true;
  1180. }
  1181. static obs_properties_t *GetDShowProperties(void *)
  1182. {
  1183. obs_properties_t *ppts = obs_properties_create();
  1184. PropertiesData *data = new PropertiesData;
  1185. obs_properties_set_param(ppts, data, PropertiesDataDestroy);
  1186. obs_property_t *p = obs_properties_add_list(ppts,
  1187. VIDEO_DEVICE_ID, TEXT_DEVICE,
  1188. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
  1189. obs_property_set_modified_callback(p, DeviceSelectionChanged);
  1190. Device::EnumVideoDevices(data->devices);
  1191. for (const VideoDevice &device : data->devices)
  1192. AddDevice(p, device);
  1193. obs_properties_add_button(ppts, "video_config", TEXT_CONFIG_VIDEO,
  1194. VideoConfigClicked);
  1195. obs_properties_add_button(ppts, "xbar_config", TEXT_CONFIG_XBAR,
  1196. CrossbarConfigClicked);
  1197. /* ------------------------------------- */
  1198. /* video settings */
  1199. p = obs_properties_add_list(ppts, RES_TYPE, TEXT_RES_FPS_TYPE,
  1200. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
  1201. obs_property_set_modified_callback(p, ResTypeChanged);
  1202. obs_property_list_add_int(p, TEXT_PREFERRED_RES, ResType_Preferred);
  1203. obs_property_list_add_int(p, TEXT_CUSTOM_RES, ResType_Custom);
  1204. p = obs_properties_add_list(ppts, RESOLUTION, TEXT_RESOLUTION,
  1205. OBS_COMBO_TYPE_EDITABLE, OBS_COMBO_FORMAT_STRING);
  1206. obs_property_set_modified_callback(p, DeviceResolutionChanged);
  1207. p = obs_properties_add_list(ppts, FRAME_INTERVAL, "FPS",
  1208. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
  1209. obs_property_set_modified_callback(p, DeviceIntervalChanged);
  1210. p = obs_properties_add_list(ppts, VIDEO_FORMAT, TEXT_VIDEO_FORMAT,
  1211. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
  1212. obs_property_set_modified_callback(p, VideoFormatChanged);
  1213. /* ------------------------------------- */
  1214. /* audio settings */
  1215. Device::EnumAudioDevices(data->audioDevices);
  1216. if (!data->audioDevices.size())
  1217. return ppts;
  1218. p = obs_properties_add_bool(ppts, USE_CUSTOM_AUDIO, TEXT_CUSTOM_AUDIO);
  1219. obs_property_set_modified_callback(p, CustomAudioClicked);
  1220. p = obs_properties_add_list(ppts, AUDIO_DEVICE_ID, TEXT_AUDIO_DEVICE,
  1221. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
  1222. for (const AudioDevice &device : data->audioDevices)
  1223. AddAudioDevice(p, device);
  1224. return ppts;
  1225. }
  1226. void DShowModuleLogCallback(LogType type, const wchar_t *msg, void *param)
  1227. {
  1228. int obs_type = LOG_DEBUG;
  1229. switch (type) {
  1230. case LogType::Error: obs_type = LOG_ERROR; break;
  1231. case LogType::Warning: obs_type = LOG_WARNING; break;
  1232. case LogType::Info: obs_type = LOG_INFO; break;
  1233. case LogType::Debug: obs_type = LOG_DEBUG; break;
  1234. }
  1235. DStr dmsg;
  1236. dstr_from_wcs(dmsg, msg);
  1237. blog(obs_type, "DShow: %s", dmsg->array);
  1238. UNUSED_PARAMETER(param);
  1239. }
  1240. void RegisterDShowSource()
  1241. {
  1242. SetLogCallback(DShowModuleLogCallback, nullptr);
  1243. obs_source_info info = {};
  1244. info.id = "dshow_input";
  1245. info.type = OBS_SOURCE_TYPE_INPUT;
  1246. info.output_flags = OBS_SOURCE_VIDEO |
  1247. OBS_SOURCE_AUDIO |
  1248. OBS_SOURCE_ASYNC;
  1249. info.get_name = GetDShowInputName;
  1250. info.create = CreateDShowInput;
  1251. info.destroy = DestroyDShowInput;
  1252. info.update = UpdateDShowInput;
  1253. info.get_defaults = GetDShowDefaults;
  1254. info.get_properties = GetDShowProperties;
  1255. obs_register_source(&info);
  1256. }