win-dshow.cpp 55 KB

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