win-dshow.cpp 55 KB

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