win-dshow.cpp 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620
  1. #include <objbase.h>
  2. #include <obs-module.h>
  3. #include <obs.hpp>
  4. #include <util/dstr.hpp>
  5. #include <util/util.hpp>
  6. #include <util/platform.h>
  7. #include <util/windows/WinHandle.hpp>
  8. #include "libdshowcapture/dshowcapture.hpp"
  9. #include "ffmpeg-decode.h"
  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 void encode_dstr(struct dstr *str)
  261. {
  262. dstr_replace(str, "#", "#22");
  263. dstr_replace(str, ":", "#3A");
  264. }
  265. static inline void decode_dstr(struct dstr *str)
  266. {
  267. dstr_replace(str, "#3A", ":");
  268. dstr_replace(str, "#22", "#");
  269. }
  270. static inline video_format ConvertVideoFormat(VideoFormat format)
  271. {
  272. switch (format) {
  273. case VideoFormat::ARGB: return VIDEO_FORMAT_BGRA;
  274. case VideoFormat::XRGB: return VIDEO_FORMAT_BGRX;
  275. case VideoFormat::I420: return VIDEO_FORMAT_I420;
  276. case VideoFormat::NV12: return VIDEO_FORMAT_NV12;
  277. case VideoFormat::YVYU: return VIDEO_FORMAT_YVYU;
  278. case VideoFormat::YUY2: return VIDEO_FORMAT_YUY2;
  279. case VideoFormat::UYVY: return VIDEO_FORMAT_UYVY;
  280. case VideoFormat::HDYC: return VIDEO_FORMAT_UYVY;
  281. case VideoFormat::MJPEG: return VIDEO_FORMAT_YUY2;
  282. default: return VIDEO_FORMAT_NONE;
  283. }
  284. }
  285. static inline audio_format ConvertAudioFormat(AudioFormat format)
  286. {
  287. switch (format) {
  288. case AudioFormat::Wave16bit: return AUDIO_FORMAT_16BIT;
  289. case AudioFormat::WaveFloat: return AUDIO_FORMAT_FLOAT;
  290. default: return AUDIO_FORMAT_UNKNOWN;
  291. }
  292. }
  293. //#define LOG_ENCODED_VIDEO_TS 1
  294. //#define LOG_ENCODED_AUDIO_TS 1
  295. void DShowInput::OnEncodedVideoData(enum AVCodecID id,
  296. unsigned char *data, size_t size, long long ts)
  297. {
  298. if (!ffmpeg_decode_valid(video_decoder)) {
  299. if (ffmpeg_decode_init(video_decoder, id) < 0) {
  300. blog(LOG_WARNING, "Could not initialize video decoder");
  301. return;
  302. }
  303. }
  304. bool got_output;
  305. int len = ffmpeg_decode_video(video_decoder, data, size, &ts,
  306. &frame, &got_output);
  307. if (len < 0) {
  308. blog(LOG_WARNING, "Error decoding video");
  309. return;
  310. }
  311. if (got_output) {
  312. frame.timestamp = (uint64_t)ts * 100;
  313. #if LOG_ENCODED_VIDEO_TS
  314. blog(LOG_DEBUG, "video ts: %llu", frame.timestamp);
  315. #endif
  316. obs_source_output_video(source, &frame);
  317. }
  318. }
  319. void DShowInput::OnVideoData(const VideoConfig &config,
  320. unsigned char *data, size_t size,
  321. long long startTime, long long endTime)
  322. {
  323. if (videoConfig.format == VideoFormat::H264) {
  324. OnEncodedVideoData(AV_CODEC_ID_H264, data, size, startTime);
  325. return;
  326. }
  327. const int cx = config.cx;
  328. const int cy = config.cy;
  329. frame.timestamp = (uint64_t)startTime * 100;
  330. frame.width = config.cx;
  331. frame.height = config.cy;
  332. frame.format = ConvertVideoFormat(config.format);
  333. frame.full_range = false;
  334. frame.flip = (config.format == VideoFormat::XRGB ||
  335. config.format == VideoFormat::ARGB);
  336. if (videoConfig.format == VideoFormat::XRGB ||
  337. videoConfig.format == VideoFormat::ARGB) {
  338. frame.data[0] = data;
  339. frame.linesize[0] = cx * 4;
  340. } else if (videoConfig.format == VideoFormat::YVYU ||
  341. videoConfig.format == VideoFormat::YUY2 ||
  342. videoConfig.format == VideoFormat::HDYC ||
  343. videoConfig.format == VideoFormat::UYVY) {
  344. frame.data[0] = data;
  345. frame.linesize[0] = cx * 2;
  346. } else if (videoConfig.format == VideoFormat::I420) {
  347. frame.data[0] = data;
  348. frame.data[1] = frame.data[0] + (cx * cy);
  349. frame.data[2] = frame.data[1] + (cx * cy / 4);
  350. frame.linesize[0] = cx;
  351. frame.linesize[1] = cx / 2;
  352. frame.linesize[2] = cx / 2;
  353. } else {
  354. /* TODO: other formats */
  355. return;
  356. }
  357. obs_source_output_video(source, &frame);
  358. UNUSED_PARAMETER(endTime); /* it's the enndd tiimmes! */
  359. UNUSED_PARAMETER(size);
  360. }
  361. void DShowInput::OnEncodedAudioData(enum AVCodecID id,
  362. unsigned char *data, size_t size, long long ts)
  363. {
  364. if (!ffmpeg_decode_valid(audio_decoder)) {
  365. if (ffmpeg_decode_init(audio_decoder, id) < 0) {
  366. blog(LOG_WARNING, "Could not initialize audio decoder");
  367. return;
  368. }
  369. }
  370. bool got_output;
  371. int len = ffmpeg_decode_audio(audio_decoder, data, size,
  372. &audio, &got_output);
  373. if (len < 0) {
  374. blog(LOG_WARNING, "Error decoding audio");
  375. return;
  376. }
  377. if (got_output) {
  378. audio.timestamp = (uint64_t)ts * 100;
  379. #if LOG_ENCODED_AUDIO_TS
  380. blog(LOG_DEBUG, "audio ts: %llu", audio.timestamp);
  381. #endif
  382. obs_source_output_audio(source, &audio);
  383. }
  384. }
  385. void DShowInput::OnAudioData(const AudioConfig &config,
  386. unsigned char *data, size_t size,
  387. long long startTime, long long endTime)
  388. {
  389. size_t block_size;
  390. if (config.format == AudioFormat::AAC) {
  391. OnEncodedAudioData(AV_CODEC_ID_AAC, data, size, startTime);
  392. return;
  393. } else if (config.format == AudioFormat::AC3) {
  394. OnEncodedAudioData(AV_CODEC_ID_AC3, data, size, startTime);
  395. return;
  396. } else if (config.format == AudioFormat::MPGA) {
  397. OnEncodedAudioData(AV_CODEC_ID_MP2, data, size, startTime);
  398. return;
  399. }
  400. audio.speakers = (enum speaker_layout)config.channels;
  401. audio.format = ConvertAudioFormat(config.format);
  402. audio.samples_per_sec = (uint32_t)config.sampleRate;
  403. audio.data[0] = data;
  404. block_size = get_audio_bytes_per_channel(audio.format) *
  405. get_audio_channels(audio.speakers);
  406. audio.frames = (uint32_t)(size / block_size);
  407. audio.timestamp = (uint64_t)startTime * 100;
  408. if (audio.format != AUDIO_FORMAT_UNKNOWN)
  409. obs_source_output_audio(source, &audio);
  410. UNUSED_PARAMETER(endTime);
  411. }
  412. static bool DecodeDeviceId(DStr &name, DStr &path, const char *device_id)
  413. {
  414. const char *path_str;
  415. if (!device_id || !*device_id)
  416. return false;
  417. path_str = strchr(device_id, ':');
  418. if (!path_str)
  419. return false;
  420. dstr_copy(path, path_str+1);
  421. dstr_copy(name, device_id);
  422. size_t len = path_str - device_id;
  423. name->array[len] = 0;
  424. name->len = len;
  425. decode_dstr(name);
  426. decode_dstr(path);
  427. return true;
  428. }
  429. static bool DecodeDeviceId(DeviceId &out, const char *device_id)
  430. {
  431. DStr name, path;
  432. if (!DecodeDeviceId(name, path, device_id))
  433. return false;
  434. BPtr<wchar_t> wname = dstr_to_wcs(name);
  435. out.name = wname;
  436. if (!dstr_is_empty(path)) {
  437. BPtr<wchar_t> wpath = dstr_to_wcs(path);
  438. out.path = wpath;
  439. }
  440. return true;
  441. }
  442. struct PropertiesData {
  443. vector<VideoDevice> devices;
  444. vector<AudioDevice> audioDevices;
  445. bool GetDevice(VideoDevice &device, const char *encoded_id) const
  446. {
  447. DeviceId deviceId;
  448. DecodeDeviceId(deviceId, encoded_id);
  449. for (const VideoDevice &curDevice : devices) {
  450. if (deviceId.name == curDevice.name &&
  451. deviceId.path == curDevice.path) {
  452. device = curDevice;
  453. return true;
  454. }
  455. }
  456. return false;
  457. }
  458. };
  459. static inline bool ConvertRes(int &cx, int &cy, const char *res)
  460. {
  461. return sscanf(res, "%dx%d", &cx, &cy) == 2;
  462. }
  463. static inline bool FormatMatches(VideoFormat left, VideoFormat right)
  464. {
  465. return left == VideoFormat::Any || right == VideoFormat::Any ||
  466. left == right;
  467. }
  468. static inline bool ResolutionValid(string res, int &cx, int &cy)
  469. {
  470. if (!res.size())
  471. return false;
  472. return ConvertRes(cx, cy, res.c_str());
  473. }
  474. template <typename F, typename ... Fs>
  475. static inline bool CapsMatch(const VideoInfo &info, F&& f, Fs ... fs)
  476. {
  477. return f(info) && CapsMatch(info, fs ...);
  478. }
  479. static inline bool CapsMatch(const VideoInfo&)
  480. {
  481. return true;
  482. }
  483. template <typename ... F>
  484. static bool CapsMatch(const VideoDevice &dev, F ... fs)
  485. {
  486. auto matcher = [&](const VideoInfo &info)
  487. {
  488. return CapsMatch(info, fs ...);
  489. };
  490. return any_of(begin(dev.caps), end(dev.caps), matcher);
  491. }
  492. static inline bool MatcherMatchVideoFormat(VideoFormat format,
  493. bool &did_match, const VideoInfo &info)
  494. {
  495. bool match = FormatMatches(format, info.format);
  496. did_match = did_match || match;
  497. return match;
  498. }
  499. static inline bool MatcherClosestFrameRateSelector(long long interval,
  500. long long &best_match, const VideoInfo &info)
  501. {
  502. long long current = FrameRateInterval(info, interval);
  503. if (llabs(interval - best_match) > llabs(interval - current))
  504. best_match = current;
  505. return true;
  506. }
  507. #if 0
  508. auto ResolutionMatcher = [](int cx, int cy)
  509. {
  510. return [cx, cy](const VideoInfo &info)
  511. {
  512. return ResolutionAvailable(info, cx, cy);
  513. };
  514. };
  515. auto FrameRateMatcher = [](long long interval)
  516. {
  517. return [interval](const VideoInfo &info)
  518. {
  519. return FrameRateAvailable(info, interval);
  520. };
  521. };
  522. auto VideoFormatMatcher = [](VideoFormat format, bool &did_match)
  523. {
  524. return [format, &did_match](const VideoInfo &info)
  525. {
  526. return MatcherMatchVideoFormat(format, did_match, info);
  527. };
  528. };
  529. auto ClosestFrameRateSelector = [](long long interval, long long &best_match)
  530. {
  531. return [interval, &best_match](const VideoInfo &info) mutable -> bool
  532. {
  533. MatcherClosestFrameRateSelector(interval, best_match, info);
  534. };
  535. }
  536. #else
  537. #define ResolutionMatcher(cx, cy) \
  538. [cx, cy](const VideoInfo &info) -> bool \
  539. { return ResolutionAvailable(info, cx, cy); }
  540. #define FrameRateMatcher(interval) \
  541. [interval](const VideoInfo &info) -> bool \
  542. { return FrameRateAvailable(info, interval); }
  543. #define VideoFormatMatcher(format, did_match) \
  544. [format, &did_match](const VideoInfo &info) mutable -> bool \
  545. { return MatcherMatchVideoFormat(format, did_match, info); }
  546. #define ClosestFrameRateSelector(interval, best_match) \
  547. [interval, &best_match](const VideoInfo &info) mutable -> bool \
  548. { return MatcherClosestFrameRateSelector(interval, best_match, info); }
  549. #endif
  550. static bool ResolutionAvailable(const VideoDevice &dev, int cx, int cy)
  551. {
  552. return CapsMatch(dev, ResolutionMatcher(cx, cy));
  553. }
  554. static bool DetermineResolution(int &cx, int &cy, obs_data_t *settings,
  555. VideoDevice dev)
  556. {
  557. const char *res = obs_data_get_autoselect_string(settings, RESOLUTION);
  558. if (obs_data_has_autoselect_value(settings, RESOLUTION) &&
  559. ConvertRes(cx, cy, res) &&
  560. ResolutionAvailable(dev, cx, cy))
  561. return true;
  562. res = obs_data_get_string(settings, RESOLUTION);
  563. if (ConvertRes(cx, cy, res) && ResolutionAvailable(dev, cx, cy))
  564. return true;
  565. res = obs_data_get_string(settings, LAST_RESOLUTION);
  566. if (ConvertRes(cx, cy, res) && ResolutionAvailable(dev, cx, cy))
  567. return true;
  568. return false;
  569. }
  570. static long long GetOBSFPS();
  571. bool DShowInput::UpdateVideoConfig(obs_data_t *settings)
  572. {
  573. string video_device_id = obs_data_get_string(settings, VIDEO_DEVICE_ID);
  574. DeviceId id;
  575. if (!DecodeDeviceId(id, video_device_id.c_str()))
  576. return false;
  577. PropertiesData data;
  578. Device::EnumVideoDevices(data.devices);
  579. VideoDevice dev;
  580. if (!data.GetDevice(dev, video_device_id.c_str()))
  581. return false;
  582. int resType = (int)obs_data_get_int(settings, RES_TYPE);
  583. int cx = 0, cy = 0;
  584. long long interval = 0;
  585. VideoFormat format = VideoFormat::Any;
  586. if (resType == ResType_Custom) {
  587. bool has_autosel_val;
  588. string resolution = obs_data_get_string(settings, RESOLUTION);
  589. if (!ResolutionValid(resolution, cx, cy))
  590. return false;
  591. has_autosel_val = obs_data_has_autoselect_value(settings,
  592. FRAME_INTERVAL);
  593. interval = has_autosel_val ?
  594. obs_data_get_autoselect_int(settings, FRAME_INTERVAL) :
  595. obs_data_get_int(settings, FRAME_INTERVAL);
  596. if (interval == FPS_MATCHING)
  597. interval = GetOBSFPS();
  598. format = (VideoFormat)obs_data_get_int(settings, VIDEO_FORMAT);
  599. long long best_interval = numeric_limits<long long>::max();
  600. bool video_format_match = false;
  601. if (!CapsMatch(dev,
  602. ResolutionMatcher(cx, cy),
  603. VideoFormatMatcher(format, video_format_match),
  604. ClosestFrameRateSelector(interval, best_interval),
  605. FrameRateMatcher(interval)) && !video_format_match)
  606. return false;
  607. interval = best_interval;
  608. blog(LOG_INFO, "%s: Using interval %lld",
  609. obs_source_get_name(source), interval);
  610. }
  611. videoConfig.name = id.name.c_str();
  612. videoConfig.path = id.path.c_str();
  613. videoConfig.useDefaultConfig = resType == ResType_Preferred;
  614. videoConfig.cx = cx;
  615. videoConfig.cy = cy;
  616. videoConfig.frameInterval = interval;
  617. videoConfig.internalFormat = format;
  618. deviceHasAudio = dev.audioAttached;
  619. videoConfig.callback = std::bind(&DShowInput::OnVideoData, this,
  620. placeholders::_1, placeholders::_2,
  621. placeholders::_3, placeholders::_4,
  622. placeholders::_5);
  623. if (videoConfig.internalFormat != VideoFormat::MJPEG)
  624. videoConfig.format = videoConfig.internalFormat;
  625. if (!device.SetVideoConfig(&videoConfig))
  626. return false;
  627. if (videoConfig.internalFormat == VideoFormat::MJPEG) {
  628. videoConfig.format = VideoFormat::XRGB;
  629. if (!device.SetVideoConfig(&videoConfig))
  630. return false;
  631. }
  632. return true;
  633. }
  634. bool DShowInput::UpdateAudioConfig(obs_data_t *settings)
  635. {
  636. string audio_device_id = obs_data_get_string(settings, AUDIO_DEVICE_ID);
  637. bool useCustomAudio = obs_data_get_bool(settings, USE_CUSTOM_AUDIO);
  638. if (useCustomAudio) {
  639. DeviceId id;
  640. if (!DecodeDeviceId(id, audio_device_id.c_str()))
  641. return false;
  642. audioConfig.name = id.name.c_str();
  643. audioConfig.path = id.path.c_str();
  644. } else if (!deviceHasAudio) {
  645. return true;
  646. }
  647. audioConfig.useVideoDevice = !useCustomAudio;
  648. audioConfig.callback = std::bind(&DShowInput::OnAudioData, this,
  649. placeholders::_1, placeholders::_2,
  650. placeholders::_3, placeholders::_4,
  651. placeholders::_5);
  652. return device.SetAudioConfig(&audioConfig);
  653. }
  654. void DShowInput::Update(obs_data_t *settings)
  655. {
  656. if (!device.ResetGraph())
  657. return;
  658. if (!UpdateVideoConfig(settings)) {
  659. blog(LOG_WARNING, "%s: Video configuration failed",
  660. obs_source_get_name(source));
  661. return;
  662. }
  663. if (!UpdateAudioConfig(settings))
  664. blog(LOG_WARNING, "%s: Audio configuration failed, ignoring "
  665. "audio", obs_source_get_name(source));
  666. if (!device.ConnectFilters())
  667. return;
  668. if (device.Start() != Result::Success)
  669. return;
  670. enum video_colorspace cs = (videoConfig.format == VideoFormat::HDYC) ?
  671. VIDEO_CS_709 : VIDEO_CS_601;
  672. if (!video_format_get_parameters(cs, VIDEO_RANGE_PARTIAL,
  673. frame.color_matrix,
  674. frame.color_range_min,
  675. frame.color_range_max)) {
  676. blog(LOG_ERROR, "Failed to get video format parameters for " \
  677. "video format %u", cs);
  678. }
  679. }
  680. /* ------------------------------------------------------------------------- */
  681. static const char *GetDShowInputName(void)
  682. {
  683. return TEXT_INPUT_NAME;
  684. }
  685. static void *CreateDShowInput(obs_data_t *settings, obs_source_t *source)
  686. {
  687. DShowInput *dshow = nullptr;
  688. try {
  689. dshow = new DShowInput(source);
  690. } catch (const char *error) {
  691. blog(LOG_ERROR, "Could not create device '%s': %s",
  692. obs_source_get_name(source), error);
  693. }
  694. UNUSED_PARAMETER(settings);
  695. return dshow;
  696. }
  697. static void DestroyDShowInput(void *data)
  698. {
  699. delete reinterpret_cast<DShowInput*>(data);
  700. }
  701. static void UpdateDShowInput(void *data, obs_data_t *settings)
  702. {
  703. UNUSED_PARAMETER(settings);
  704. reinterpret_cast<DShowInput*>(data)->QueueAction(Action::Update);
  705. }
  706. static void GetDShowDefaults(obs_data_t *settings)
  707. {
  708. obs_data_set_default_int(settings, FRAME_INTERVAL, FPS_MATCHING);
  709. obs_data_set_default_int(settings, RES_TYPE, ResType_Preferred);
  710. obs_data_set_default_int(settings, VIDEO_FORMAT, (int)VideoFormat::Any);
  711. }
  712. struct Resolution {
  713. int cx, cy;
  714. inline Resolution(int cx, int cy) : cx(cx), cy(cy) {}
  715. };
  716. static void InsertResolution(vector<Resolution> &resolutions, int cx, int cy)
  717. {
  718. int bestCY = 0;
  719. size_t idx = 0;
  720. for (; idx < resolutions.size(); idx++) {
  721. const Resolution &res = resolutions[idx];
  722. if (res.cx > cx)
  723. break;
  724. if (res.cx == cx) {
  725. if (res.cy == cy)
  726. return;
  727. if (!bestCY)
  728. bestCY = res.cy;
  729. else if (res.cy > bestCY)
  730. break;
  731. }
  732. }
  733. resolutions.insert(resolutions.begin() + idx, Resolution(cx, cy));
  734. }
  735. static inline void AddCap(vector<Resolution> &resolutions, const VideoInfo &cap)
  736. {
  737. InsertResolution(resolutions, cap.minCX, cap.minCY);
  738. InsertResolution(resolutions, cap.maxCX, cap.maxCY);
  739. }
  740. #define MAKE_DSHOW_FPS(fps) (10000000LL/(fps))
  741. #define MAKE_DSHOW_FRACTIONAL_FPS(den, num) ((num)*10000000LL/(den))
  742. static long long GetOBSFPS()
  743. {
  744. obs_video_info ovi;
  745. if (!obs_get_video_info(&ovi))
  746. return 0;
  747. return MAKE_DSHOW_FRACTIONAL_FPS(ovi.fps_num, ovi.fps_den);
  748. }
  749. struct FPSFormat {
  750. const char *text;
  751. long long interval;
  752. };
  753. static const FPSFormat validFPSFormats[] = {
  754. {"60", MAKE_DSHOW_FPS(60)},
  755. {"59.94 NTSC", MAKE_DSHOW_FRACTIONAL_FPS(60000, 1001)},
  756. {"50", MAKE_DSHOW_FPS(50)},
  757. {"48 film", MAKE_DSHOW_FRACTIONAL_FPS(48000, 1001)},
  758. {"40", MAKE_DSHOW_FPS(40)},
  759. {"30", MAKE_DSHOW_FPS(30)},
  760. {"29.97 NTSC", MAKE_DSHOW_FRACTIONAL_FPS(30000, 1001)},
  761. {"25", MAKE_DSHOW_FPS(25)},
  762. {"24 film", MAKE_DSHOW_FRACTIONAL_FPS(24000, 1001)},
  763. {"20", MAKE_DSHOW_FPS(20)},
  764. {"15", MAKE_DSHOW_FPS(15)},
  765. {"10", MAKE_DSHOW_FPS(10)},
  766. {"5", MAKE_DSHOW_FPS(5)},
  767. {"4", MAKE_DSHOW_FPS(4)},
  768. {"3", MAKE_DSHOW_FPS(3)},
  769. {"2", MAKE_DSHOW_FPS(2)},
  770. {"1", MAKE_DSHOW_FPS(1)},
  771. };
  772. static bool DeviceIntervalChanged(obs_properties_t *props, obs_property_t *p,
  773. obs_data_t *settings);
  774. static bool TryResolution(VideoDevice &dev, string res)
  775. {
  776. int cx, cy;
  777. if (!ConvertRes(cx, cy, res.c_str()))
  778. return false;
  779. return ResolutionAvailable(dev, cx, cy);
  780. }
  781. static bool SetResolution(obs_properties_t *props, obs_data_t *settings,
  782. string res, bool autoselect=false)
  783. {
  784. if (autoselect)
  785. obs_data_set_autoselect_string(settings, RESOLUTION,
  786. res.c_str());
  787. else
  788. obs_data_unset_autoselect_value(settings, RESOLUTION);
  789. DeviceIntervalChanged(props, obs_properties_get(props, FRAME_INTERVAL),
  790. settings);
  791. if (!autoselect)
  792. obs_data_set_string(settings, LAST_RESOLUTION, res.c_str());
  793. return true;
  794. }
  795. static bool DeviceResolutionChanged(obs_properties_t *props, obs_property_t *p,
  796. obs_data_t *settings)
  797. {
  798. UNUSED_PARAMETER(p);
  799. PropertiesData *data = (PropertiesData*)obs_properties_get_param(props);
  800. const char *id;
  801. VideoDevice device;
  802. id = obs_data_get_string(settings, VIDEO_DEVICE_ID);
  803. string res = obs_data_get_string(settings, RESOLUTION);
  804. string last_res = obs_data_get_string(settings, LAST_RESOLUTION);
  805. if (!data->GetDevice(device, id))
  806. return false;
  807. if (TryResolution(device, res))
  808. return SetResolution(props, settings, res);
  809. if (TryResolution(device, last_res))
  810. return SetResolution(props, settings, last_res, true);
  811. return false;
  812. }
  813. struct VideoFormatName {
  814. VideoFormat format;
  815. const char *name;
  816. };
  817. static const VideoFormatName videoFormatNames[] = {
  818. /* autoselect format*/
  819. {VideoFormat::Any, "VideoFormat.Any"},
  820. /* raw formats */
  821. {VideoFormat::ARGB, "ARGB"},
  822. {VideoFormat::XRGB, "XRGB"},
  823. /* planar YUV formats */
  824. {VideoFormat::I420, "I420"},
  825. {VideoFormat::NV12, "NV12"},
  826. /* packed YUV formats */
  827. {VideoFormat::YVYU, "YVYU"},
  828. {VideoFormat::YUY2, "YUY2"},
  829. {VideoFormat::UYVY, "UYVY"},
  830. {VideoFormat::HDYC, "HDYC"},
  831. /* encoded formats */
  832. {VideoFormat::MJPEG, "MJPEG"},
  833. {VideoFormat::H264, "H264"}
  834. };
  835. static bool ResTypeChanged(obs_properties_t *props, obs_property_t *p,
  836. obs_data_t *settings);
  837. static size_t AddDevice(obs_property_t *device_list, const string &id)
  838. {
  839. DStr name, path;
  840. if (!DecodeDeviceId(name, path, id.c_str()))
  841. return numeric_limits<size_t>::max();
  842. return obs_property_list_add_string(device_list, name, id.c_str());
  843. }
  844. static bool UpdateDeviceList(obs_property_t *list, const string &id)
  845. {
  846. size_t size = obs_property_list_item_count(list);
  847. bool found = false;
  848. bool disabled_unknown_found = false;
  849. for (size_t i = 0; i < size; i++) {
  850. if (obs_property_list_item_string(list, i) == id) {
  851. found = true;
  852. continue;
  853. }
  854. if (obs_property_list_item_disabled(list, i))
  855. disabled_unknown_found = true;
  856. }
  857. if (!found && !disabled_unknown_found) {
  858. size_t idx = AddDevice(list, id);
  859. obs_property_list_item_disable(list, idx, true);
  860. return true;
  861. }
  862. if (found && !disabled_unknown_found)
  863. return false;
  864. for (size_t i = 0; i < size;) {
  865. if (obs_property_list_item_disabled(list, i)) {
  866. obs_property_list_item_remove(list, i);
  867. continue;
  868. }
  869. i += 1;
  870. }
  871. return true;
  872. }
  873. static bool DeviceSelectionChanged(obs_properties_t *props, obs_property_t *p,
  874. obs_data_t *settings)
  875. {
  876. PropertiesData *data = (PropertiesData*)obs_properties_get_param(props);
  877. VideoDevice device;
  878. string id = obs_data_get_string(settings, VIDEO_DEVICE_ID);
  879. string old_id = obs_data_get_string(settings, LAST_VIDEO_DEV_ID);
  880. bool device_list_updated = UpdateDeviceList(p, id);
  881. if (!data->GetDevice(device, id.c_str()))
  882. return !device_list_updated;
  883. vector<Resolution> resolutions;
  884. for (const VideoInfo &cap : device.caps)
  885. AddCap(resolutions, cap);
  886. p = obs_properties_get(props, RESOLUTION);
  887. obs_property_list_clear(p);
  888. for (size_t idx = resolutions.size(); idx > 0; idx--) {
  889. const Resolution &res = resolutions[idx-1];
  890. string strRes;
  891. strRes += to_string(res.cx);
  892. strRes += "x";
  893. strRes += to_string(res.cy);
  894. obs_property_list_add_string(p, strRes.c_str(), strRes.c_str());
  895. }
  896. /* only refresh properties if device legitimately changed */
  897. if (!id.size() || !old_id.size() || id != old_id) {
  898. p = obs_properties_get(props, RES_TYPE);
  899. ResTypeChanged(props, p, settings);
  900. obs_data_set_string(settings, LAST_VIDEO_DEV_ID, id.c_str());
  901. }
  902. return true;
  903. }
  904. static bool VideoConfigClicked(obs_properties_t *props, obs_property_t *p,
  905. void *data)
  906. {
  907. DShowInput *input = reinterpret_cast<DShowInput*>(data);
  908. input->QueueAction(Action::ConfigVideo);
  909. UNUSED_PARAMETER(props);
  910. UNUSED_PARAMETER(p);
  911. return false;
  912. }
  913. /*static bool AudioConfigClicked(obs_properties_t *props, obs_property_t *p,
  914. void *data)
  915. {
  916. DShowInput *input = reinterpret_cast<DShowInput*>(data);
  917. input->QueueAction(Action::ConfigAudio);
  918. UNUSED_PARAMETER(props);
  919. UNUSED_PARAMETER(p);
  920. return false;
  921. }*/
  922. static bool CrossbarConfigClicked(obs_properties_t *props, obs_property_t *p,
  923. void *data)
  924. {
  925. DShowInput *input = reinterpret_cast<DShowInput*>(data);
  926. input->QueueAction(Action::ConfigCrossbar1);
  927. UNUSED_PARAMETER(props);
  928. UNUSED_PARAMETER(p);
  929. return false;
  930. }
  931. /*static bool Crossbar2ConfigClicked(obs_properties_t *props, obs_property_t *p,
  932. void *data)
  933. {
  934. DShowInput *input = reinterpret_cast<DShowInput*>(data);
  935. input->QueueAction(Action::ConfigCrossbar2);
  936. UNUSED_PARAMETER(props);
  937. UNUSED_PARAMETER(p);
  938. return false;
  939. }*/
  940. static bool AddDevice(obs_property_t *device_list, const VideoDevice &device)
  941. {
  942. DStr name, path, device_id;
  943. dstr_from_wcs(name, device.name.c_str());
  944. dstr_from_wcs(path, device.path.c_str());
  945. encode_dstr(path);
  946. dstr_copy_dstr(device_id, name);
  947. encode_dstr(device_id);
  948. dstr_cat(device_id, ":");
  949. dstr_cat_dstr(device_id, path);
  950. obs_property_list_add_string(device_list, name, device_id);
  951. return true;
  952. }
  953. static bool AddAudioDevice(obs_property_t *device_list,
  954. const AudioDevice &device)
  955. {
  956. DStr name, path, device_id;
  957. dstr_from_wcs(name, device.name.c_str());
  958. dstr_from_wcs(path, device.path.c_str());
  959. encode_dstr(path);
  960. dstr_copy_dstr(device_id, name);
  961. encode_dstr(device_id);
  962. dstr_cat(device_id, ":");
  963. dstr_cat_dstr(device_id, path);
  964. obs_property_list_add_string(device_list, name, device_id);
  965. return true;
  966. }
  967. static void PropertiesDataDestroy(void *data)
  968. {
  969. delete reinterpret_cast<PropertiesData*>(data);
  970. }
  971. static bool ResTypeChanged(obs_properties_t *props, obs_property_t *p,
  972. obs_data_t *settings)
  973. {
  974. int val = (int)obs_data_get_int(settings, RES_TYPE);
  975. bool enabled = (val != ResType_Preferred);
  976. p = obs_properties_get(props, RESOLUTION);
  977. obs_property_set_enabled(p, enabled);
  978. p = obs_properties_get(props, FRAME_INTERVAL);
  979. obs_property_set_enabled(p, enabled);
  980. p = obs_properties_get(props, VIDEO_FORMAT);
  981. obs_property_set_enabled(p, enabled);
  982. if (val == ResType_Custom) {
  983. p = obs_properties_get(props, RESOLUTION);
  984. DeviceResolutionChanged(props, p, settings);
  985. } else {
  986. obs_data_unset_autoselect_value(settings, FRAME_INTERVAL);
  987. }
  988. return true;
  989. }
  990. static DStr GetFPSName(long long interval)
  991. {
  992. DStr name;
  993. if (interval == FPS_MATCHING) {
  994. dstr_cat(name, TEXT_FPS_MATCHING);
  995. return name;
  996. }
  997. if (interval == FPS_HIGHEST) {
  998. dstr_cat(name, TEXT_FPS_HIGHEST);
  999. return name;
  1000. }
  1001. for (const FPSFormat &format : validFPSFormats) {
  1002. if (format.interval != interval)
  1003. continue;
  1004. dstr_cat(name, format.text);
  1005. return name;
  1006. }
  1007. dstr_cat(name, to_string(10000000. / interval).c_str());
  1008. return name;
  1009. }
  1010. static void UpdateFPS(VideoDevice &device, VideoFormat format,
  1011. long long interval, int cx, int cy, obs_properties_t *props)
  1012. {
  1013. obs_property_t *list = obs_properties_get(props, FRAME_INTERVAL);
  1014. obs_property_list_clear(list);
  1015. obs_property_list_add_int(list, TEXT_FPS_MATCHING, FPS_MATCHING);
  1016. obs_property_list_add_int(list, TEXT_FPS_HIGHEST, FPS_HIGHEST);
  1017. bool interval_added = interval == FPS_HIGHEST ||
  1018. interval == FPS_MATCHING;
  1019. for (const FPSFormat &fps_format : validFPSFormats) {
  1020. bool video_format_match = false;
  1021. long long format_interval = fps_format.interval;
  1022. bool available = CapsMatch(device,
  1023. ResolutionMatcher(cx, cy),
  1024. VideoFormatMatcher(format, video_format_match),
  1025. FrameRateMatcher(format_interval));
  1026. if (!available && interval != fps_format.interval)
  1027. continue;
  1028. if (interval == fps_format.interval)
  1029. interval_added = true;
  1030. size_t idx = obs_property_list_add_int(list, fps_format.text,
  1031. fps_format.interval);
  1032. obs_property_list_item_disable(list, idx, !available);
  1033. }
  1034. if (interval_added)
  1035. return;
  1036. size_t idx = obs_property_list_add_int(list, GetFPSName(interval),
  1037. interval);
  1038. obs_property_list_item_disable(list, idx, true);
  1039. }
  1040. static DStr GetVideoFormatName(VideoFormat format)
  1041. {
  1042. DStr name;
  1043. for (const VideoFormatName &format_ : videoFormatNames) {
  1044. if (format_.format == format) {
  1045. dstr_cat(name, obs_module_text(format_.name));
  1046. return name;
  1047. }
  1048. }
  1049. dstr_cat(name, TEXT_FORMAT_UNKNOWN);
  1050. dstr_replace(name, "%1", std::to_string((long long)format).c_str());
  1051. return name;
  1052. }
  1053. static void UpdateVideoFormats(VideoDevice &device, VideoFormat format_,
  1054. int cx, int cy, long long interval, obs_properties_t *props)
  1055. {
  1056. set<VideoFormat> formats = { VideoFormat::Any };
  1057. auto format_gatherer = [&formats](const VideoInfo &info) mutable -> bool
  1058. {
  1059. formats.insert(info.format);
  1060. return false;
  1061. };
  1062. CapsMatch(device,
  1063. ResolutionMatcher(cx, cy),
  1064. FrameRateMatcher(interval),
  1065. format_gatherer);
  1066. obs_property_t *list = obs_properties_get(props, VIDEO_FORMAT);
  1067. obs_property_list_clear(list);
  1068. bool format_added = false;
  1069. for (const VideoFormatName &format : videoFormatNames) {
  1070. bool available = formats.find(format.format) != end(formats);
  1071. if (!available && format.format != format_)
  1072. continue;
  1073. if (format.format == format_)
  1074. format_added = true;
  1075. size_t idx = obs_property_list_add_int(list,
  1076. obs_module_text(format.name),
  1077. (long long)format.format);
  1078. obs_property_list_item_disable(list, idx, !available);
  1079. }
  1080. if (format_added)
  1081. return;
  1082. size_t idx = obs_property_list_add_int(list,
  1083. GetVideoFormatName(format_), (long long)format_);
  1084. obs_property_list_item_disable(list, idx, true);
  1085. }
  1086. static bool UpdateFPS(long long interval, obs_property_t *list)
  1087. {
  1088. size_t size = obs_property_list_item_count(list);
  1089. bool fps_found = false;
  1090. DStr name;
  1091. for (size_t i = 0; i < size; i++) {
  1092. if (obs_property_list_item_int(list, i) != interval)
  1093. continue;
  1094. obs_property_list_item_disable(list, i, true);
  1095. if (size == 1)
  1096. return false;
  1097. dstr_cat(name, obs_property_list_item_name(list, i));
  1098. fps_found = true;
  1099. break;
  1100. }
  1101. obs_property_list_clear(list);
  1102. if (!name->len)
  1103. name = GetFPSName(interval);
  1104. obs_property_list_add_int(list, name, interval);
  1105. obs_property_list_item_disable(list, 0, true);
  1106. return true;
  1107. }
  1108. static bool DeviceIntervalChanged(obs_properties_t *props, obs_property_t *p,
  1109. obs_data_t *settings)
  1110. {
  1111. long long val = obs_data_get_int(settings, FRAME_INTERVAL);
  1112. PropertiesData *data = (PropertiesData*)obs_properties_get_param(props);
  1113. const char *id = obs_data_get_string(settings, VIDEO_DEVICE_ID);
  1114. VideoDevice device;
  1115. if (!data->GetDevice(device, id))
  1116. return UpdateFPS(val, p);
  1117. int cx = 0, cy = 0;
  1118. if (!DetermineResolution(cx, cy, settings, device)) {
  1119. UpdateVideoFormats(device, VideoFormat::Any, 0, 0, 0, props);
  1120. UpdateFPS(device, VideoFormat::Any, 0, 0, 0, props);
  1121. return true;
  1122. }
  1123. int resType = (int)obs_data_get_int(settings, RES_TYPE);
  1124. if (resType != ResType_Custom)
  1125. return true;
  1126. if (val == FPS_MATCHING)
  1127. val = GetOBSFPS();
  1128. VideoFormat format = (VideoFormat)obs_data_get_int(settings,
  1129. VIDEO_FORMAT);
  1130. bool video_format_matches = false;
  1131. long long best_interval = numeric_limits<long long>::max();
  1132. bool frameRateSupported = CapsMatch(device,
  1133. ResolutionMatcher(cx, cy),
  1134. VideoFormatMatcher(format, video_format_matches),
  1135. ClosestFrameRateSelector(val, best_interval),
  1136. FrameRateMatcher(val));
  1137. if (video_format_matches &&
  1138. !frameRateSupported &&
  1139. best_interval != val) {
  1140. long long listed_val = 0;
  1141. for (const FPSFormat &format : validFPSFormats) {
  1142. long long diff = llabs(format.interval - best_interval);
  1143. if (diff < DEVICE_INTERVAL_DIFF_LIMIT) {
  1144. listed_val = format.interval;
  1145. break;
  1146. }
  1147. }
  1148. if (listed_val != val)
  1149. obs_data_set_autoselect_int(settings, FRAME_INTERVAL,
  1150. listed_val);
  1151. } else {
  1152. obs_data_unset_autoselect_value(settings, FRAME_INTERVAL);
  1153. }
  1154. UpdateVideoFormats(device, format, cx, cy, val, props);
  1155. UpdateFPS(device, format, val, cx, cy, props);
  1156. UNUSED_PARAMETER(p);
  1157. return true;
  1158. }
  1159. static bool UpdateVideoFormats(VideoFormat format, obs_property_t *list)
  1160. {
  1161. size_t size = obs_property_list_item_count(list);
  1162. DStr name;
  1163. for (size_t i = 0; i < size; i++) {
  1164. if ((VideoFormat)obs_property_list_item_int(list, i) != format)
  1165. continue;
  1166. if (size == 1)
  1167. return false;
  1168. dstr_cat(name, obs_property_list_item_name(list, i));
  1169. break;
  1170. }
  1171. obs_property_list_clear(list);
  1172. if (!name->len)
  1173. name = GetVideoFormatName(format);
  1174. obs_property_list_add_int(list, name, (long long)format);
  1175. obs_property_list_item_disable(list, 0, true);
  1176. return true;
  1177. }
  1178. static bool VideoFormatChanged(obs_properties_t *props, obs_property_t *p,
  1179. obs_data_t *settings)
  1180. {
  1181. PropertiesData *data = (PropertiesData*)obs_properties_get_param(props);
  1182. const char *id = obs_data_get_string(settings, VIDEO_DEVICE_ID);
  1183. VideoDevice device;
  1184. VideoFormat curFormat =
  1185. (VideoFormat)obs_data_get_int(settings, VIDEO_FORMAT);
  1186. if (!data->GetDevice(device, id))
  1187. return UpdateVideoFormats(curFormat, p);
  1188. int cx, cy;
  1189. if (!DetermineResolution(cx, cy, settings, device)) {
  1190. UpdateVideoFormats(device, VideoFormat::Any, cx, cy, 0, props);
  1191. UpdateFPS(device, VideoFormat::Any, 0, 0, 0, props);
  1192. return true;
  1193. }
  1194. long long interval = obs_data_get_int(settings, FRAME_INTERVAL);
  1195. UpdateVideoFormats(device, curFormat, cx, cy, interval, props);
  1196. UpdateFPS(device, curFormat, interval, cx, cy, props);
  1197. return true;
  1198. }
  1199. static bool CustomAudioClicked(obs_properties_t *props, obs_property_t *p,
  1200. obs_data_t *settings)
  1201. {
  1202. bool useCustomAudio = obs_data_get_bool(settings, USE_CUSTOM_AUDIO);
  1203. p = obs_properties_get(props, AUDIO_DEVICE_ID);
  1204. obs_property_set_visible(p, useCustomAudio);
  1205. return true;
  1206. }
  1207. static obs_properties_t *GetDShowProperties(void *)
  1208. {
  1209. obs_properties_t *ppts = obs_properties_create();
  1210. PropertiesData *data = new PropertiesData;
  1211. obs_properties_set_param(ppts, data, PropertiesDataDestroy);
  1212. obs_property_t *p = obs_properties_add_list(ppts,
  1213. VIDEO_DEVICE_ID, TEXT_DEVICE,
  1214. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
  1215. obs_property_set_modified_callback(p, DeviceSelectionChanged);
  1216. Device::EnumVideoDevices(data->devices);
  1217. for (const VideoDevice &device : data->devices)
  1218. AddDevice(p, device);
  1219. obs_properties_add_button(ppts, "video_config", TEXT_CONFIG_VIDEO,
  1220. VideoConfigClicked);
  1221. obs_properties_add_button(ppts, "xbar_config", TEXT_CONFIG_XBAR,
  1222. CrossbarConfigClicked);
  1223. /* ------------------------------------- */
  1224. /* video settings */
  1225. p = obs_properties_add_list(ppts, RES_TYPE, TEXT_RES_FPS_TYPE,
  1226. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
  1227. obs_property_set_modified_callback(p, ResTypeChanged);
  1228. obs_property_list_add_int(p, TEXT_PREFERRED_RES, ResType_Preferred);
  1229. obs_property_list_add_int(p, TEXT_CUSTOM_RES, ResType_Custom);
  1230. p = obs_properties_add_list(ppts, RESOLUTION, TEXT_RESOLUTION,
  1231. OBS_COMBO_TYPE_EDITABLE, OBS_COMBO_FORMAT_STRING);
  1232. obs_property_set_modified_callback(p, DeviceResolutionChanged);
  1233. p = obs_properties_add_list(ppts, FRAME_INTERVAL, "FPS",
  1234. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
  1235. obs_property_set_modified_callback(p, DeviceIntervalChanged);
  1236. p = obs_properties_add_list(ppts, VIDEO_FORMAT, TEXT_VIDEO_FORMAT,
  1237. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
  1238. obs_property_set_modified_callback(p, VideoFormatChanged);
  1239. /* ------------------------------------- */
  1240. /* audio settings */
  1241. Device::EnumAudioDevices(data->audioDevices);
  1242. if (!data->audioDevices.size())
  1243. return ppts;
  1244. p = obs_properties_add_bool(ppts, USE_CUSTOM_AUDIO, TEXT_CUSTOM_AUDIO);
  1245. obs_property_set_modified_callback(p, CustomAudioClicked);
  1246. p = obs_properties_add_list(ppts, AUDIO_DEVICE_ID, TEXT_AUDIO_DEVICE,
  1247. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
  1248. for (const AudioDevice &device : data->audioDevices)
  1249. AddAudioDevice(p, device);
  1250. return ppts;
  1251. }
  1252. OBS_DECLARE_MODULE()
  1253. OBS_MODULE_USE_DEFAULT_LOCALE("win-dshow", "en-US")
  1254. void DShowModuleLogCallback(LogType type, const wchar_t *msg, void *param)
  1255. {
  1256. int obs_type = LOG_DEBUG;
  1257. switch (type) {
  1258. case LogType::Error: obs_type = LOG_ERROR; break;
  1259. case LogType::Warning: obs_type = LOG_WARNING; break;
  1260. case LogType::Info: obs_type = LOG_INFO; break;
  1261. case LogType::Debug: obs_type = LOG_DEBUG; break;
  1262. }
  1263. DStr dmsg;
  1264. dstr_from_wcs(dmsg, msg);
  1265. blog(obs_type, "DShow: %s", dmsg->array);
  1266. UNUSED_PARAMETER(param);
  1267. }
  1268. bool obs_module_load(void)
  1269. {
  1270. SetLogCallback(DShowModuleLogCallback, nullptr);
  1271. obs_source_info info = {};
  1272. info.id = "dshow_input";
  1273. info.type = OBS_SOURCE_TYPE_INPUT;
  1274. info.output_flags = OBS_SOURCE_VIDEO |
  1275. OBS_SOURCE_AUDIO |
  1276. OBS_SOURCE_ASYNC;
  1277. info.get_name = GetDShowInputName;
  1278. info.create = CreateDShowInput;
  1279. info.destroy = DestroyDShowInput;
  1280. info.update = UpdateDShowInput;
  1281. info.get_defaults = GetDShowDefaults;
  1282. info.get_properties = GetDShowProperties;
  1283. obs_register_source(&info);
  1284. return true;
  1285. }