win-dshow.cpp 46 KB

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