win-dshow.cpp 48 KB

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