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 bool 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. if (!Activate(settings)) {
  242. obs_source_output_video(source,
  243. nullptr);
  244. }
  245. obs_data_release(settings);
  246. break;
  247. }
  248. case Action::Deactivate:
  249. Deactivate();
  250. break;
  251. case Action::Shutdown:
  252. device.ShutdownGraph();
  253. return;
  254. case Action::ConfigVideo:
  255. device.OpenDialog(nullptr, DialogType::ConfigVideo);
  256. break;
  257. case Action::ConfigAudio:
  258. device.OpenDialog(nullptr, DialogType::ConfigAudio);
  259. break;
  260. case Action::ConfigCrossbar1:
  261. device.OpenDialog(nullptr, DialogType::ConfigCrossbar);
  262. break;
  263. case Action::ConfigCrossbar2:
  264. device.OpenDialog(nullptr, DialogType::ConfigCrossbar2);
  265. break;
  266. case Action::None:;
  267. }
  268. }
  269. }
  270. #define FPS_HIGHEST 0LL
  271. #define FPS_MATCHING -1LL
  272. template <typename T, typename U, typename V>
  273. static bool between(T &&lower, U &&value, V &&upper)
  274. {
  275. return value >= lower && value <= upper;
  276. }
  277. static bool ResolutionAvailable(const VideoInfo &cap, int cx, int cy)
  278. {
  279. return between(cap.minCX, cx, cap.maxCX) &&
  280. between(cap.minCY, cy, cap.maxCY);
  281. }
  282. #define DEVICE_INTERVAL_DIFF_LIMIT 20
  283. static bool FrameRateAvailable(const VideoInfo &cap, long long interval)
  284. {
  285. return interval == FPS_HIGHEST || interval == FPS_MATCHING ||
  286. between(cap.minInterval - DEVICE_INTERVAL_DIFF_LIMIT,
  287. interval,
  288. cap.maxInterval + DEVICE_INTERVAL_DIFF_LIMIT);
  289. }
  290. static long long FrameRateInterval(const VideoInfo &cap,
  291. long long desired_interval)
  292. {
  293. return desired_interval < cap.minInterval ?
  294. cap.minInterval :
  295. min(desired_interval, cap.maxInterval);
  296. }
  297. static inline video_format ConvertVideoFormat(VideoFormat format)
  298. {
  299. switch (format) {
  300. case VideoFormat::ARGB: return VIDEO_FORMAT_BGRA;
  301. case VideoFormat::XRGB: return VIDEO_FORMAT_BGRX;
  302. case VideoFormat::I420: return VIDEO_FORMAT_I420;
  303. case VideoFormat::YV12: return VIDEO_FORMAT_I420;
  304. case VideoFormat::NV12: return VIDEO_FORMAT_NV12;
  305. case VideoFormat::YVYU: return VIDEO_FORMAT_YVYU;
  306. case VideoFormat::YUY2: return VIDEO_FORMAT_YUY2;
  307. case VideoFormat::UYVY: return VIDEO_FORMAT_UYVY;
  308. case VideoFormat::HDYC: return VIDEO_FORMAT_UYVY;
  309. case VideoFormat::MJPEG: return VIDEO_FORMAT_YUY2;
  310. default: return VIDEO_FORMAT_NONE;
  311. }
  312. }
  313. static inline audio_format ConvertAudioFormat(AudioFormat format)
  314. {
  315. switch (format) {
  316. case AudioFormat::Wave16bit: return AUDIO_FORMAT_16BIT;
  317. case AudioFormat::WaveFloat: return AUDIO_FORMAT_FLOAT;
  318. default: return AUDIO_FORMAT_UNKNOWN;
  319. }
  320. }
  321. //#define LOG_ENCODED_VIDEO_TS 1
  322. //#define LOG_ENCODED_AUDIO_TS 1
  323. void DShowInput::OnEncodedVideoData(enum AVCodecID id,
  324. unsigned char *data, size_t size, long long ts)
  325. {
  326. if (!ffmpeg_decode_valid(video_decoder)) {
  327. if (ffmpeg_decode_init(video_decoder, id) < 0) {
  328. blog(LOG_WARNING, "Could not initialize video decoder");
  329. return;
  330. }
  331. }
  332. bool got_output;
  333. int len = ffmpeg_decode_video(video_decoder, data, size, &ts,
  334. &frame, &got_output);
  335. if (len < 0) {
  336. blog(LOG_WARNING, "Error decoding video");
  337. return;
  338. }
  339. if (got_output) {
  340. frame.timestamp = (uint64_t)ts * 100;
  341. #if LOG_ENCODED_VIDEO_TS
  342. blog(LOG_DEBUG, "video ts: %llu", frame.timestamp);
  343. #endif
  344. obs_source_output_video(source, &frame);
  345. }
  346. }
  347. void DShowInput::OnVideoData(const VideoConfig &config,
  348. unsigned char *data, size_t size,
  349. long long startTime, long long endTime)
  350. {
  351. if (videoConfig.format == VideoFormat::H264) {
  352. OnEncodedVideoData(AV_CODEC_ID_H264, data, size, startTime);
  353. return;
  354. }
  355. const int cx = config.cx;
  356. const int cy = config.cy;
  357. frame.timestamp = (uint64_t)startTime * 100;
  358. frame.width = config.cx;
  359. frame.height = config.cy;
  360. frame.format = ConvertVideoFormat(config.format);
  361. frame.full_range = false;
  362. frame.flip = (config.format == VideoFormat::XRGB ||
  363. config.format == VideoFormat::ARGB);
  364. if (videoConfig.format == VideoFormat::XRGB ||
  365. videoConfig.format == VideoFormat::ARGB) {
  366. frame.data[0] = data;
  367. frame.linesize[0] = cx * 4;
  368. } else if (videoConfig.format == VideoFormat::YVYU ||
  369. videoConfig.format == VideoFormat::YUY2 ||
  370. videoConfig.format == VideoFormat::HDYC ||
  371. videoConfig.format == VideoFormat::UYVY) {
  372. frame.data[0] = data;
  373. frame.linesize[0] = cx * 2;
  374. } else if (videoConfig.format == VideoFormat::I420) {
  375. frame.data[0] = data;
  376. frame.data[1] = frame.data[0] + (cx * cy);
  377. frame.data[2] = frame.data[1] + (cx * cy / 4);
  378. frame.linesize[0] = cx;
  379. frame.linesize[1] = cx / 2;
  380. frame.linesize[2] = cx / 2;
  381. } else if (videoConfig.format == VideoFormat::YV12) {
  382. frame.data[0] = data;
  383. frame.data[2] = frame.data[0] + (cx * cy);
  384. frame.data[1] = frame.data[2] + (cx * cy / 4);
  385. frame.linesize[0] = cx;
  386. frame.linesize[1] = cx / 2;
  387. frame.linesize[2] = cx / 2;
  388. } else if (videoConfig.format == VideoFormat::NV12) {
  389. frame.data[0] = data;
  390. frame.data[1] = frame.data[0] + (cx * cy);
  391. frame.linesize[0] = cx;
  392. frame.linesize[1] = cx;
  393. } else {
  394. /* TODO: other formats */
  395. return;
  396. }
  397. obs_source_output_video(source, &frame);
  398. UNUSED_PARAMETER(endTime); /* it's the enndd tiimmes! */
  399. UNUSED_PARAMETER(size);
  400. }
  401. void DShowInput::OnEncodedAudioData(enum AVCodecID id,
  402. unsigned char *data, size_t size, long long ts)
  403. {
  404. if (!ffmpeg_decode_valid(audio_decoder)) {
  405. if (ffmpeg_decode_init(audio_decoder, id) < 0) {
  406. blog(LOG_WARNING, "Could not initialize audio decoder");
  407. return;
  408. }
  409. }
  410. bool got_output;
  411. int len = ffmpeg_decode_audio(audio_decoder, data, size,
  412. &audio, &got_output);
  413. if (len < 0) {
  414. blog(LOG_WARNING, "Error decoding audio");
  415. return;
  416. }
  417. if (got_output) {
  418. audio.timestamp = (uint64_t)ts * 100;
  419. #if LOG_ENCODED_AUDIO_TS
  420. blog(LOG_DEBUG, "audio ts: %llu", audio.timestamp);
  421. #endif
  422. obs_source_output_audio(source, &audio);
  423. }
  424. }
  425. void DShowInput::OnAudioData(const AudioConfig &config,
  426. unsigned char *data, size_t size,
  427. long long startTime, long long endTime)
  428. {
  429. size_t block_size;
  430. if (config.format == AudioFormat::AAC) {
  431. OnEncodedAudioData(AV_CODEC_ID_AAC, data, size, startTime);
  432. return;
  433. } else if (config.format == AudioFormat::AC3) {
  434. OnEncodedAudioData(AV_CODEC_ID_AC3, data, size, startTime);
  435. return;
  436. } else if (config.format == AudioFormat::MPGA) {
  437. OnEncodedAudioData(AV_CODEC_ID_MP2, data, size, startTime);
  438. return;
  439. }
  440. audio.speakers = (enum speaker_layout)config.channels;
  441. audio.format = ConvertAudioFormat(config.format);
  442. audio.samples_per_sec = (uint32_t)config.sampleRate;
  443. audio.data[0] = data;
  444. block_size = get_audio_bytes_per_channel(audio.format) *
  445. get_audio_channels(audio.speakers);
  446. audio.frames = (uint32_t)(size / block_size);
  447. audio.timestamp = (uint64_t)startTime * 100;
  448. if (audio.format != AUDIO_FORMAT_UNKNOWN)
  449. obs_source_output_audio(source, &audio);
  450. UNUSED_PARAMETER(endTime);
  451. }
  452. struct PropertiesData {
  453. DShowInput *input;
  454. vector<VideoDevice> devices;
  455. vector<AudioDevice> audioDevices;
  456. bool GetDevice(VideoDevice &device, const char *encoded_id) const
  457. {
  458. DeviceId deviceId;
  459. DecodeDeviceId(deviceId, encoded_id);
  460. for (const VideoDevice &curDevice : devices) {
  461. if (deviceId.name == curDevice.name &&
  462. deviceId.path == curDevice.path) {
  463. device = curDevice;
  464. return true;
  465. }
  466. }
  467. return false;
  468. }
  469. };
  470. static inline bool ConvertRes(int &cx, int &cy, const char *res)
  471. {
  472. return sscanf(res, "%dx%d", &cx, &cy) == 2;
  473. }
  474. static inline bool FormatMatches(VideoFormat left, VideoFormat right)
  475. {
  476. return left == VideoFormat::Any || right == VideoFormat::Any ||
  477. left == right;
  478. }
  479. static inline bool ResolutionValid(string res, int &cx, int &cy)
  480. {
  481. if (!res.size())
  482. return false;
  483. return ConvertRes(cx, cy, res.c_str());
  484. }
  485. static inline bool CapsMatch(const VideoInfo&)
  486. {
  487. return true;
  488. }
  489. template <typename ... F>
  490. static bool CapsMatch(const VideoDevice &dev, F ... fs);
  491. template <typename F, typename ... Fs>
  492. static inline bool CapsMatch(const VideoInfo &info, F&& f, Fs ... fs)
  493. {
  494. return f(info) && CapsMatch(info, fs ...);
  495. }
  496. template <typename ... F>
  497. static bool CapsMatch(const VideoDevice &dev, F ... fs)
  498. {
  499. auto matcher = [&](const VideoInfo &info)
  500. {
  501. return CapsMatch(info, fs ...);
  502. };
  503. return any_of(begin(dev.caps), end(dev.caps), matcher);
  504. }
  505. static inline bool MatcherMatchVideoFormat(VideoFormat format,
  506. bool &did_match, const VideoInfo &info)
  507. {
  508. bool match = FormatMatches(format, info.format);
  509. did_match = did_match || match;
  510. return match;
  511. }
  512. static inline bool MatcherClosestFrameRateSelector(long long interval,
  513. long long &best_match, const VideoInfo &info)
  514. {
  515. long long current = FrameRateInterval(info, interval);
  516. if (llabs(interval - best_match) > llabs(interval - current))
  517. best_match = current;
  518. return true;
  519. }
  520. #if 0
  521. auto ResolutionMatcher = [](int cx, int cy)
  522. {
  523. return [cx, cy](const VideoInfo &info)
  524. {
  525. return ResolutionAvailable(info, cx, cy);
  526. };
  527. };
  528. auto FrameRateMatcher = [](long long interval)
  529. {
  530. return [interval](const VideoInfo &info)
  531. {
  532. return FrameRateAvailable(info, interval);
  533. };
  534. };
  535. auto VideoFormatMatcher = [](VideoFormat format, bool &did_match)
  536. {
  537. return [format, &did_match](const VideoInfo &info)
  538. {
  539. return MatcherMatchVideoFormat(format, did_match, info);
  540. };
  541. };
  542. auto ClosestFrameRateSelector = [](long long interval, long long &best_match)
  543. {
  544. return [interval, &best_match](const VideoInfo &info) mutable -> bool
  545. {
  546. MatcherClosestFrameRateSelector(interval, best_match, info);
  547. };
  548. }
  549. #else
  550. #define ResolutionMatcher(cx, cy) \
  551. [cx, cy](const VideoInfo &info) -> bool \
  552. { return ResolutionAvailable(info, cx, cy); }
  553. #define FrameRateMatcher(interval) \
  554. [interval](const VideoInfo &info) -> bool \
  555. { return FrameRateAvailable(info, interval); }
  556. #define VideoFormatMatcher(format, did_match) \
  557. [format, &did_match](const VideoInfo &info) mutable -> bool \
  558. { return MatcherMatchVideoFormat(format, did_match, info); }
  559. #define ClosestFrameRateSelector(interval, best_match) \
  560. [interval, &best_match](const VideoInfo &info) mutable -> bool \
  561. { return MatcherClosestFrameRateSelector(interval, best_match, info); }
  562. #endif
  563. static bool ResolutionAvailable(const VideoDevice &dev, int cx, int cy)
  564. {
  565. return CapsMatch(dev, ResolutionMatcher(cx, cy));
  566. }
  567. static bool DetermineResolution(int &cx, int &cy, obs_data_t *settings,
  568. VideoDevice dev)
  569. {
  570. const char *res = obs_data_get_autoselect_string(settings, RESOLUTION);
  571. if (obs_data_has_autoselect_value(settings, RESOLUTION) &&
  572. ConvertRes(cx, cy, res) &&
  573. ResolutionAvailable(dev, cx, cy))
  574. return true;
  575. res = obs_data_get_string(settings, RESOLUTION);
  576. if (ConvertRes(cx, cy, res) && ResolutionAvailable(dev, cx, cy))
  577. return true;
  578. res = obs_data_get_string(settings, LAST_RESOLUTION);
  579. if (ConvertRes(cx, cy, res) && ResolutionAvailable(dev, cx, cy))
  580. return true;
  581. return false;
  582. }
  583. static long long GetOBSFPS();
  584. static inline bool IsEncoded(const VideoConfig &config)
  585. {
  586. return config.format >= VideoFormat::MJPEG ||
  587. wstrstri(config.name.c_str(), L"elgato") != NULL ||
  588. wstrstri(config.name.c_str(), L"stream engine") != NULL;
  589. }
  590. inline void DShowInput::SetupBuffering(obs_data_t *settings)
  591. {
  592. BufferingType bufType;
  593. uint32_t flags = obs_source_get_flags(source);
  594. bool useBuffering;
  595. bufType = (BufferingType)obs_data_get_int(settings, BUFFERING_VAL);
  596. if (bufType == BufferingType::Auto)
  597. useBuffering = IsEncoded(videoConfig);
  598. else
  599. useBuffering = bufType == BufferingType::On;
  600. if (useBuffering)
  601. flags &= ~OBS_SOURCE_FLAG_UNBUFFERED;
  602. else
  603. flags |= OBS_SOURCE_FLAG_UNBUFFERED;
  604. obs_source_set_flags(source, flags);
  605. }
  606. bool DShowInput::UpdateVideoConfig(obs_data_t *settings)
  607. {
  608. string video_device_id = obs_data_get_string(settings, VIDEO_DEVICE_ID);
  609. DeviceId id;
  610. if (!DecodeDeviceId(id, video_device_id.c_str()))
  611. return false;
  612. PropertiesData data;
  613. Device::EnumVideoDevices(data.devices);
  614. VideoDevice dev;
  615. if (!data.GetDevice(dev, video_device_id.c_str()))
  616. return false;
  617. int resType = (int)obs_data_get_int(settings, RES_TYPE);
  618. int cx = 0, cy = 0;
  619. long long interval = 0;
  620. VideoFormat format = VideoFormat::Any;
  621. if (resType == ResType_Custom) {
  622. bool has_autosel_val;
  623. string resolution = obs_data_get_string(settings, RESOLUTION);
  624. if (!ResolutionValid(resolution, cx, cy))
  625. return false;
  626. has_autosel_val = obs_data_has_autoselect_value(settings,
  627. FRAME_INTERVAL);
  628. interval = has_autosel_val ?
  629. obs_data_get_autoselect_int(settings, FRAME_INTERVAL) :
  630. obs_data_get_int(settings, FRAME_INTERVAL);
  631. if (interval == FPS_MATCHING)
  632. interval = GetOBSFPS();
  633. format = (VideoFormat)obs_data_get_int(settings, VIDEO_FORMAT);
  634. long long best_interval = numeric_limits<long long>::max();
  635. bool video_format_match = false;
  636. if (!CapsMatch(dev,
  637. ResolutionMatcher(cx, cy),
  638. VideoFormatMatcher(format, video_format_match),
  639. ClosestFrameRateSelector(interval, best_interval),
  640. FrameRateMatcher(interval)) && !video_format_match)
  641. return false;
  642. interval = best_interval;
  643. blog(LOG_INFO, "%s: Using interval %lld",
  644. obs_source_get_name(source), interval);
  645. }
  646. videoConfig.name = id.name.c_str();
  647. videoConfig.path = id.path.c_str();
  648. videoConfig.useDefaultConfig = resType == ResType_Preferred;
  649. videoConfig.cx = cx;
  650. videoConfig.cy = cy;
  651. videoConfig.frameInterval = interval;
  652. videoConfig.internalFormat = format;
  653. deviceHasAudio = dev.audioAttached;
  654. videoConfig.callback = std::bind(&DShowInput::OnVideoData, this,
  655. placeholders::_1, placeholders::_2,
  656. placeholders::_3, placeholders::_4,
  657. placeholders::_5);
  658. if (videoConfig.internalFormat != VideoFormat::MJPEG)
  659. videoConfig.format = videoConfig.internalFormat;
  660. if (!device.SetVideoConfig(&videoConfig))
  661. return false;
  662. if (videoConfig.internalFormat == VideoFormat::MJPEG) {
  663. videoConfig.format = VideoFormat::XRGB;
  664. if (!device.SetVideoConfig(&videoConfig))
  665. return false;
  666. }
  667. SetupBuffering(settings);
  668. return true;
  669. }
  670. bool DShowInput::UpdateAudioConfig(obs_data_t *settings)
  671. {
  672. string audio_device_id = obs_data_get_string(settings, AUDIO_DEVICE_ID);
  673. bool useCustomAudio = obs_data_get_bool(settings, USE_CUSTOM_AUDIO);
  674. if (useCustomAudio) {
  675. DeviceId id;
  676. if (!DecodeDeviceId(id, audio_device_id.c_str()))
  677. return false;
  678. audioConfig.name = id.name.c_str();
  679. audioConfig.path = id.path.c_str();
  680. } else if (!deviceHasAudio) {
  681. return true;
  682. }
  683. audioConfig.useVideoDevice = !useCustomAudio;
  684. audioConfig.callback = std::bind(&DShowInput::OnAudioData, this,
  685. placeholders::_1, placeholders::_2,
  686. placeholders::_3, placeholders::_4,
  687. placeholders::_5);
  688. return device.SetAudioConfig(&audioConfig);
  689. }
  690. void DShowInput::SetActive(bool active_)
  691. {
  692. obs_data_t *settings = obs_source_get_settings(source);
  693. QueueAction(active_ ? Action::Activate : Action::Deactivate);
  694. obs_data_set_bool(settings, "active", active_);
  695. active = active_;
  696. obs_data_release(settings);
  697. }
  698. inline enum video_colorspace DShowInput::GetColorSpace(
  699. obs_data_t *settings) const
  700. {
  701. const char *space = obs_data_get_string(settings, COLOR_SPACE);
  702. if (astrcmpi(space, "709") == 0)
  703. return VIDEO_CS_709;
  704. else if (astrcmpi(space, "601") == 0)
  705. return VIDEO_CS_601;
  706. else
  707. return (videoConfig.format == VideoFormat::HDYC) ?
  708. VIDEO_CS_709 : VIDEO_CS_601;
  709. }
  710. inline enum video_range_type DShowInput::GetColorRange(
  711. obs_data_t *settings) const
  712. {
  713. const char *range = obs_data_get_string(settings, COLOR_RANGE);
  714. return astrcmpi(range, "full") == 0 ?
  715. VIDEO_RANGE_FULL : VIDEO_RANGE_PARTIAL;
  716. }
  717. inline bool DShowInput::Activate(obs_data_t *settings)
  718. {
  719. if (!device.ResetGraph())
  720. return false;
  721. if (!UpdateVideoConfig(settings)) {
  722. blog(LOG_WARNING, "%s: Video configuration failed",
  723. obs_source_get_name(source));
  724. return false;
  725. }
  726. if (!UpdateAudioConfig(settings))
  727. blog(LOG_WARNING, "%s: Audio configuration failed, ignoring "
  728. "audio", obs_source_get_name(source));
  729. if (!device.ConnectFilters())
  730. return false;
  731. if (device.Start() != Result::Success)
  732. return false;
  733. enum video_colorspace cs = GetColorSpace(settings);
  734. bool success = video_format_get_parameters(
  735. cs, GetColorRange(settings),
  736. frame.color_matrix,
  737. frame.color_range_min,
  738. frame.color_range_max);
  739. if (!success) {
  740. blog(LOG_ERROR, "Failed to get video format parameters for " \
  741. "video format %u", cs);
  742. }
  743. return true;
  744. }
  745. inline void DShowInput::Deactivate()
  746. {
  747. device.ResetGraph();
  748. obs_source_output_video(source, nullptr);
  749. }
  750. /* ------------------------------------------------------------------------- */
  751. static const char *GetDShowInputName(void)
  752. {
  753. return TEXT_INPUT_NAME;
  754. }
  755. static void *CreateDShowInput(obs_data_t *settings, obs_source_t *source)
  756. {
  757. DShowInput *dshow = nullptr;
  758. try {
  759. dshow = new DShowInput(source, settings);
  760. } catch (const char *error) {
  761. blog(LOG_ERROR, "Could not create device '%s': %s",
  762. obs_source_get_name(source), error);
  763. }
  764. return dshow;
  765. }
  766. static void DestroyDShowInput(void *data)
  767. {
  768. delete reinterpret_cast<DShowInput*>(data);
  769. }
  770. static void UpdateDShowInput(void *data, obs_data_t *settings)
  771. {
  772. DShowInput *input = reinterpret_cast<DShowInput*>(data);
  773. if (input->active)
  774. input->QueueAction(Action::Activate);
  775. UNUSED_PARAMETER(settings);
  776. }
  777. static void GetDShowDefaults(obs_data_t *settings)
  778. {
  779. obs_data_set_default_int(settings, FRAME_INTERVAL, FPS_MATCHING);
  780. obs_data_set_default_int(settings, RES_TYPE, ResType_Preferred);
  781. obs_data_set_default_int(settings, VIDEO_FORMAT, (int)VideoFormat::Any);
  782. obs_data_set_default_bool(settings, "active", true);
  783. obs_data_set_default_string(settings, COLOR_SPACE, "default");
  784. obs_data_set_default_string(settings, COLOR_RANGE, "partial");
  785. }
  786. struct Resolution {
  787. int cx, cy;
  788. inline Resolution(int cx, int cy) : cx(cx), cy(cy) {}
  789. };
  790. static void InsertResolution(vector<Resolution> &resolutions, int cx, int cy)
  791. {
  792. int bestCY = 0;
  793. size_t idx = 0;
  794. for (; idx < resolutions.size(); idx++) {
  795. const Resolution &res = resolutions[idx];
  796. if (res.cx > cx)
  797. break;
  798. if (res.cx == cx) {
  799. if (res.cy == cy)
  800. return;
  801. if (!bestCY)
  802. bestCY = res.cy;
  803. else if (res.cy > bestCY)
  804. break;
  805. }
  806. }
  807. resolutions.insert(resolutions.begin() + idx, Resolution(cx, cy));
  808. }
  809. static inline void AddCap(vector<Resolution> &resolutions, const VideoInfo &cap)
  810. {
  811. InsertResolution(resolutions, cap.minCX, cap.minCY);
  812. InsertResolution(resolutions, cap.maxCX, cap.maxCY);
  813. }
  814. #define MAKE_DSHOW_FPS(fps) (10000000LL/(fps))
  815. #define MAKE_DSHOW_FRACTIONAL_FPS(den, num) ((num)*10000000LL/(den))
  816. static long long GetOBSFPS()
  817. {
  818. obs_video_info ovi;
  819. if (!obs_get_video_info(&ovi))
  820. return 0;
  821. return MAKE_DSHOW_FRACTIONAL_FPS(ovi.fps_num, ovi.fps_den);
  822. }
  823. struct FPSFormat {
  824. const char *text;
  825. long long interval;
  826. };
  827. static const FPSFormat validFPSFormats[] = {
  828. {"60", MAKE_DSHOW_FPS(60)},
  829. {"59.94 NTSC", MAKE_DSHOW_FRACTIONAL_FPS(60000, 1001)},
  830. {"50", MAKE_DSHOW_FPS(50)},
  831. {"48 film", MAKE_DSHOW_FRACTIONAL_FPS(48000, 1001)},
  832. {"40", MAKE_DSHOW_FPS(40)},
  833. {"30", MAKE_DSHOW_FPS(30)},
  834. {"29.97 NTSC", MAKE_DSHOW_FRACTIONAL_FPS(30000, 1001)},
  835. {"25", MAKE_DSHOW_FPS(25)},
  836. {"24 film", MAKE_DSHOW_FRACTIONAL_FPS(24000, 1001)},
  837. {"20", MAKE_DSHOW_FPS(20)},
  838. {"15", MAKE_DSHOW_FPS(15)},
  839. {"10", MAKE_DSHOW_FPS(10)},
  840. {"5", MAKE_DSHOW_FPS(5)},
  841. {"4", MAKE_DSHOW_FPS(4)},
  842. {"3", MAKE_DSHOW_FPS(3)},
  843. {"2", MAKE_DSHOW_FPS(2)},
  844. {"1", MAKE_DSHOW_FPS(1)},
  845. };
  846. static bool DeviceIntervalChanged(obs_properties_t *props, obs_property_t *p,
  847. obs_data_t *settings);
  848. static bool TryResolution(VideoDevice &dev, string res)
  849. {
  850. int cx, cy;
  851. if (!ConvertRes(cx, cy, res.c_str()))
  852. return false;
  853. return ResolutionAvailable(dev, cx, cy);
  854. }
  855. static bool SetResolution(obs_properties_t *props, obs_data_t *settings,
  856. string res, bool autoselect=false)
  857. {
  858. if (autoselect)
  859. obs_data_set_autoselect_string(settings, RESOLUTION,
  860. res.c_str());
  861. else
  862. obs_data_unset_autoselect_value(settings, RESOLUTION);
  863. DeviceIntervalChanged(props, obs_properties_get(props, FRAME_INTERVAL),
  864. settings);
  865. if (!autoselect)
  866. obs_data_set_string(settings, LAST_RESOLUTION, res.c_str());
  867. return true;
  868. }
  869. static bool DeviceResolutionChanged(obs_properties_t *props, obs_property_t *p,
  870. obs_data_t *settings)
  871. {
  872. UNUSED_PARAMETER(p);
  873. PropertiesData *data = (PropertiesData*)obs_properties_get_param(props);
  874. const char *id;
  875. VideoDevice device;
  876. id = obs_data_get_string(settings, VIDEO_DEVICE_ID);
  877. string res = obs_data_get_string(settings, RESOLUTION);
  878. string last_res = obs_data_get_string(settings, LAST_RESOLUTION);
  879. if (!data->GetDevice(device, id))
  880. return false;
  881. if (TryResolution(device, res))
  882. return SetResolution(props, settings, res);
  883. if (TryResolution(device, last_res))
  884. return SetResolution(props, settings, last_res, true);
  885. return false;
  886. }
  887. struct VideoFormatName {
  888. VideoFormat format;
  889. const char *name;
  890. };
  891. static const VideoFormatName videoFormatNames[] = {
  892. /* autoselect format*/
  893. {VideoFormat::Any, "VideoFormat.Any"},
  894. /* raw formats */
  895. {VideoFormat::ARGB, "ARGB"},
  896. {VideoFormat::XRGB, "XRGB"},
  897. /* planar YUV formats */
  898. {VideoFormat::I420, "I420"},
  899. {VideoFormat::NV12, "NV12"},
  900. {VideoFormat::YV12, "YV12"},
  901. /* packed YUV formats */
  902. {VideoFormat::YVYU, "YVYU"},
  903. {VideoFormat::YUY2, "YUY2"},
  904. {VideoFormat::UYVY, "UYVY"},
  905. {VideoFormat::HDYC, "HDYC"},
  906. /* encoded formats */
  907. {VideoFormat::MJPEG, "MJPEG"},
  908. {VideoFormat::H264, "H264"}
  909. };
  910. static bool ResTypeChanged(obs_properties_t *props, obs_property_t *p,
  911. obs_data_t *settings);
  912. static size_t AddDevice(obs_property_t *device_list, const string &id)
  913. {
  914. DStr name, path;
  915. if (!DecodeDeviceDStr(name, path, id.c_str()))
  916. return numeric_limits<size_t>::max();
  917. return obs_property_list_add_string(device_list, name, id.c_str());
  918. }
  919. static bool UpdateDeviceList(obs_property_t *list, const string &id)
  920. {
  921. size_t size = obs_property_list_item_count(list);
  922. bool found = false;
  923. bool disabled_unknown_found = false;
  924. for (size_t i = 0; i < size; i++) {
  925. if (obs_property_list_item_string(list, i) == id) {
  926. found = true;
  927. continue;
  928. }
  929. if (obs_property_list_item_disabled(list, i))
  930. disabled_unknown_found = true;
  931. }
  932. if (!found && !disabled_unknown_found) {
  933. size_t idx = AddDevice(list, id);
  934. obs_property_list_item_disable(list, idx, true);
  935. return true;
  936. }
  937. if (found && !disabled_unknown_found)
  938. return false;
  939. for (size_t i = 0; i < size;) {
  940. if (obs_property_list_item_disabled(list, i)) {
  941. obs_property_list_item_remove(list, i);
  942. continue;
  943. }
  944. i += 1;
  945. }
  946. return true;
  947. }
  948. static bool DeviceSelectionChanged(obs_properties_t *props, obs_property_t *p,
  949. obs_data_t *settings)
  950. {
  951. PropertiesData *data = (PropertiesData*)obs_properties_get_param(props);
  952. VideoDevice device;
  953. string id = obs_data_get_string(settings, VIDEO_DEVICE_ID);
  954. string old_id = obs_data_get_string(settings, LAST_VIDEO_DEV_ID);
  955. bool device_list_updated = UpdateDeviceList(p, id);
  956. if (!data->GetDevice(device, id.c_str()))
  957. return !device_list_updated;
  958. vector<Resolution> resolutions;
  959. for (const VideoInfo &cap : device.caps)
  960. AddCap(resolutions, cap);
  961. p = obs_properties_get(props, RESOLUTION);
  962. obs_property_list_clear(p);
  963. for (size_t idx = resolutions.size(); idx > 0; idx--) {
  964. const Resolution &res = resolutions[idx-1];
  965. string strRes;
  966. strRes += to_string(res.cx);
  967. strRes += "x";
  968. strRes += to_string(res.cy);
  969. obs_property_list_add_string(p, strRes.c_str(), strRes.c_str());
  970. }
  971. /* only refresh properties if device legitimately changed */
  972. if (!id.size() || !old_id.size() || id != old_id) {
  973. p = obs_properties_get(props, RES_TYPE);
  974. ResTypeChanged(props, p, settings);
  975. obs_data_set_string(settings, LAST_VIDEO_DEV_ID, id.c_str());
  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. }