win-dshow.cpp 53 KB

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