win-dshow.cpp 48 KB

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