win-dshow.cpp 45 KB

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