win-dshow.cpp 53 KB

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