win-dshow.cpp 43 KB

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