win-dshow.cpp 45 KB

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