win-dshow.cpp 54 KB

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