win-dshow.cpp 41 KB

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