win-dshow.cpp 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026
  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 *CreateDShowInput(obs_data_t *settings, obs_source_t *source)
  955. {
  956. DShowInput *dshow = nullptr;
  957. try {
  958. dshow = new DShowInput(source, settings);
  959. } catch (const char *error) {
  960. blog(LOG_ERROR, "Could not create device '%s': %s",
  961. obs_source_get_name(source), error);
  962. }
  963. return dshow;
  964. }
  965. static void DestroyDShowInput(void *data)
  966. {
  967. delete reinterpret_cast<DShowInput *>(data);
  968. }
  969. static void UpdateDShowInput(void *data, obs_data_t *settings)
  970. {
  971. DShowInput *input = reinterpret_cast<DShowInput *>(data);
  972. if (input->active)
  973. input->QueueActivate(settings);
  974. }
  975. static void GetDShowDefaults(obs_data_t *settings)
  976. {
  977. obs_data_set_default_int(settings, FRAME_INTERVAL, FPS_MATCHING);
  978. obs_data_set_default_int(settings, RES_TYPE, ResType_Preferred);
  979. obs_data_set_default_int(settings, VIDEO_FORMAT, (int)VideoFormat::Any);
  980. obs_data_set_default_bool(settings, "active", true);
  981. obs_data_set_default_string(settings, COLOR_SPACE, "default");
  982. obs_data_set_default_string(settings, COLOR_RANGE, "default");
  983. obs_data_set_default_int(settings, AUDIO_OUTPUT_MODE,
  984. (int)AudioMode::Capture);
  985. }
  986. struct Resolution {
  987. int cx, cy;
  988. inline Resolution(int cx, int cy) : cx(cx), cy(cy) {}
  989. };
  990. static void InsertResolution(vector<Resolution> &resolutions, int cx, int cy)
  991. {
  992. int bestCY = 0;
  993. size_t idx = 0;
  994. for (; idx < resolutions.size(); idx++) {
  995. const Resolution &res = resolutions[idx];
  996. if (res.cx > cx)
  997. break;
  998. if (res.cx == cx) {
  999. if (res.cy == cy)
  1000. return;
  1001. if (!bestCY)
  1002. bestCY = res.cy;
  1003. else if (res.cy > bestCY)
  1004. break;
  1005. }
  1006. }
  1007. resolutions.insert(resolutions.begin() + idx, Resolution(cx, cy));
  1008. }
  1009. static inline void AddCap(vector<Resolution> &resolutions, const VideoInfo &cap)
  1010. {
  1011. InsertResolution(resolutions, cap.minCX, cap.minCY);
  1012. InsertResolution(resolutions, cap.maxCX, cap.maxCY);
  1013. }
  1014. #define MAKE_DSHOW_FPS(fps) (10000000LL / (fps))
  1015. #define MAKE_DSHOW_FRACTIONAL_FPS(den, num) ((num)*10000000LL / (den))
  1016. static long long GetOBSFPS()
  1017. {
  1018. obs_video_info ovi;
  1019. if (!obs_get_video_info(&ovi))
  1020. return 0;
  1021. return MAKE_DSHOW_FRACTIONAL_FPS(ovi.fps_num, ovi.fps_den);
  1022. }
  1023. struct FPSFormat {
  1024. const char *text;
  1025. long long interval;
  1026. };
  1027. static const FPSFormat validFPSFormats[] = {
  1028. {"60", MAKE_DSHOW_FPS(60)},
  1029. {"59.94 NTSC", MAKE_DSHOW_FRACTIONAL_FPS(60000, 1001)},
  1030. {"50", MAKE_DSHOW_FPS(50)},
  1031. {"48 film", MAKE_DSHOW_FRACTIONAL_FPS(48000, 1001)},
  1032. {"40", MAKE_DSHOW_FPS(40)},
  1033. {"30", MAKE_DSHOW_FPS(30)},
  1034. {"29.97 NTSC", MAKE_DSHOW_FRACTIONAL_FPS(30000, 1001)},
  1035. {"25", MAKE_DSHOW_FPS(25)},
  1036. {"24 film", MAKE_DSHOW_FRACTIONAL_FPS(24000, 1001)},
  1037. {"20", MAKE_DSHOW_FPS(20)},
  1038. {"15", MAKE_DSHOW_FPS(15)},
  1039. {"10", MAKE_DSHOW_FPS(10)},
  1040. {"5", MAKE_DSHOW_FPS(5)},
  1041. {"4", MAKE_DSHOW_FPS(4)},
  1042. {"3", MAKE_DSHOW_FPS(3)},
  1043. {"2", MAKE_DSHOW_FPS(2)},
  1044. {"1", MAKE_DSHOW_FPS(1)},
  1045. };
  1046. static bool DeviceIntervalChanged(obs_properties_t *props, obs_property_t *p,
  1047. obs_data_t *settings);
  1048. static bool TryResolution(VideoDevice &dev, string res)
  1049. {
  1050. int cx, cy;
  1051. if (!ConvertRes(cx, cy, res.c_str()))
  1052. return false;
  1053. return ResolutionAvailable(dev, cx, cy);
  1054. }
  1055. static bool SetResolution(obs_properties_t *props, obs_data_t *settings,
  1056. string res, bool autoselect = false)
  1057. {
  1058. if (autoselect)
  1059. obs_data_set_autoselect_string(settings, RESOLUTION,
  1060. res.c_str());
  1061. else
  1062. obs_data_unset_autoselect_value(settings, RESOLUTION);
  1063. DeviceIntervalChanged(props, obs_properties_get(props, FRAME_INTERVAL),
  1064. settings);
  1065. if (!autoselect)
  1066. obs_data_set_string(settings, LAST_RESOLUTION, res.c_str());
  1067. return true;
  1068. }
  1069. static bool DeviceResolutionChanged(obs_properties_t *props, obs_property_t *p,
  1070. obs_data_t *settings)
  1071. {
  1072. UNUSED_PARAMETER(p);
  1073. PropertiesData *data =
  1074. (PropertiesData *)obs_properties_get_param(props);
  1075. const char *id;
  1076. VideoDevice device;
  1077. id = obs_data_get_string(settings, VIDEO_DEVICE_ID);
  1078. string res = obs_data_get_string(settings, RESOLUTION);
  1079. string last_res = obs_data_get_string(settings, LAST_RESOLUTION);
  1080. if (!data->GetDevice(device, id))
  1081. return false;
  1082. if (TryResolution(device, res))
  1083. return SetResolution(props, settings, res);
  1084. if (TryResolution(device, last_res))
  1085. return SetResolution(props, settings, last_res, true);
  1086. return false;
  1087. }
  1088. struct VideoFormatName {
  1089. VideoFormat format;
  1090. const char *name;
  1091. };
  1092. static const VideoFormatName videoFormatNames[] = {
  1093. /* autoselect format*/
  1094. {VideoFormat::Any, "VideoFormat.Any"},
  1095. /* raw formats */
  1096. {VideoFormat::ARGB, "ARGB"},
  1097. {VideoFormat::XRGB, "XRGB"},
  1098. /* planar YUV formats */
  1099. {VideoFormat::I420, "I420"},
  1100. {VideoFormat::NV12, "NV12"},
  1101. {VideoFormat::YV12, "YV12"},
  1102. {VideoFormat::Y800, "Y800"},
  1103. /* packed YUV formats */
  1104. {VideoFormat::YVYU, "YVYU"},
  1105. {VideoFormat::YUY2, "YUY2"},
  1106. {VideoFormat::UYVY, "UYVY"},
  1107. {VideoFormat::HDYC, "HDYC"},
  1108. /* encoded formats */
  1109. {VideoFormat::MJPEG, "MJPEG"},
  1110. {VideoFormat::H264, "H264"}};
  1111. static bool ResTypeChanged(obs_properties_t *props, obs_property_t *p,
  1112. obs_data_t *settings);
  1113. static size_t AddDevice(obs_property_t *device_list, const string &id)
  1114. {
  1115. DStr name, path;
  1116. if (!DecodeDeviceDStr(name, path, id.c_str()))
  1117. return numeric_limits<size_t>::max();
  1118. return obs_property_list_add_string(device_list, name, id.c_str());
  1119. }
  1120. static bool UpdateDeviceList(obs_property_t *list, const string &id)
  1121. {
  1122. size_t size = obs_property_list_item_count(list);
  1123. bool found = false;
  1124. bool disabled_unknown_found = false;
  1125. for (size_t i = 0; i < size; i++) {
  1126. if (obs_property_list_item_string(list, i) == id) {
  1127. found = true;
  1128. continue;
  1129. }
  1130. if (obs_property_list_item_disabled(list, i))
  1131. disabled_unknown_found = true;
  1132. }
  1133. if (!found && !disabled_unknown_found) {
  1134. size_t idx = AddDevice(list, id);
  1135. obs_property_list_item_disable(list, idx, true);
  1136. return true;
  1137. }
  1138. if (found && !disabled_unknown_found)
  1139. return false;
  1140. for (size_t i = 0; i < size;) {
  1141. if (obs_property_list_item_disabled(list, i)) {
  1142. obs_property_list_item_remove(list, i);
  1143. continue;
  1144. }
  1145. i += 1;
  1146. }
  1147. return true;
  1148. }
  1149. static bool DeviceSelectionChanged(obs_properties_t *props, obs_property_t *p,
  1150. obs_data_t *settings)
  1151. {
  1152. PropertiesData *data =
  1153. (PropertiesData *)obs_properties_get_param(props);
  1154. VideoDevice device;
  1155. string id = obs_data_get_string(settings, VIDEO_DEVICE_ID);
  1156. string old_id = obs_data_get_string(settings, LAST_VIDEO_DEV_ID);
  1157. bool device_list_updated = UpdateDeviceList(p, id);
  1158. if (!data->GetDevice(device, id.c_str()))
  1159. return !device_list_updated;
  1160. vector<Resolution> resolutions;
  1161. for (const VideoInfo &cap : device.caps)
  1162. AddCap(resolutions, cap);
  1163. p = obs_properties_get(props, RESOLUTION);
  1164. obs_property_list_clear(p);
  1165. for (size_t idx = resolutions.size(); idx > 0; idx--) {
  1166. const Resolution &res = resolutions[idx - 1];
  1167. string strRes;
  1168. strRes += to_string(res.cx);
  1169. strRes += "x";
  1170. strRes += to_string(res.cy);
  1171. obs_property_list_add_string(p, strRes.c_str(), strRes.c_str());
  1172. }
  1173. /* only refresh properties if device legitimately changed */
  1174. if (!id.size() || !old_id.size() || id != old_id) {
  1175. p = obs_properties_get(props, RES_TYPE);
  1176. ResTypeChanged(props, p, settings);
  1177. obs_data_set_string(settings, LAST_VIDEO_DEV_ID, id.c_str());
  1178. }
  1179. return true;
  1180. }
  1181. static bool VideoConfigClicked(obs_properties_t *props, obs_property_t *p,
  1182. void *data)
  1183. {
  1184. DShowInput *input = reinterpret_cast<DShowInput *>(data);
  1185. input->QueueAction(Action::ConfigVideo);
  1186. UNUSED_PARAMETER(props);
  1187. UNUSED_PARAMETER(p);
  1188. return false;
  1189. }
  1190. /*static bool AudioConfigClicked(obs_properties_t *props, obs_property_t *p,
  1191. void *data)
  1192. {
  1193. DShowInput *input = reinterpret_cast<DShowInput*>(data);
  1194. input->QueueAction(Action::ConfigAudio);
  1195. UNUSED_PARAMETER(props);
  1196. UNUSED_PARAMETER(p);
  1197. return false;
  1198. }*/
  1199. static bool CrossbarConfigClicked(obs_properties_t *props, obs_property_t *p,
  1200. void *data)
  1201. {
  1202. DShowInput *input = reinterpret_cast<DShowInput *>(data);
  1203. input->QueueAction(Action::ConfigCrossbar1);
  1204. UNUSED_PARAMETER(props);
  1205. UNUSED_PARAMETER(p);
  1206. return false;
  1207. }
  1208. /*static bool Crossbar2ConfigClicked(obs_properties_t *props, obs_property_t *p,
  1209. void *data)
  1210. {
  1211. DShowInput *input = reinterpret_cast<DShowInput*>(data);
  1212. input->QueueAction(Action::ConfigCrossbar2);
  1213. UNUSED_PARAMETER(props);
  1214. UNUSED_PARAMETER(p);
  1215. return false;
  1216. }*/
  1217. static bool AddDevice(obs_property_t *device_list, const VideoDevice &device)
  1218. {
  1219. DStr name, path, device_id;
  1220. dstr_from_wcs(name, device.name.c_str());
  1221. dstr_from_wcs(path, device.path.c_str());
  1222. encode_dstr(path);
  1223. dstr_copy_dstr(device_id, name);
  1224. encode_dstr(device_id);
  1225. dstr_cat(device_id, ":");
  1226. dstr_cat_dstr(device_id, path);
  1227. obs_property_list_add_string(device_list, name, device_id);
  1228. return true;
  1229. }
  1230. static bool AddAudioDevice(obs_property_t *device_list,
  1231. const AudioDevice &device)
  1232. {
  1233. DStr name, path, device_id;
  1234. dstr_from_wcs(name, device.name.c_str());
  1235. dstr_from_wcs(path, device.path.c_str());
  1236. encode_dstr(path);
  1237. dstr_copy_dstr(device_id, name);
  1238. encode_dstr(device_id);
  1239. dstr_cat(device_id, ":");
  1240. dstr_cat_dstr(device_id, path);
  1241. obs_property_list_add_string(device_list, name, device_id);
  1242. return true;
  1243. }
  1244. static void PropertiesDataDestroy(void *data)
  1245. {
  1246. delete reinterpret_cast<PropertiesData *>(data);
  1247. }
  1248. static bool ResTypeChanged(obs_properties_t *props, obs_property_t *p,
  1249. obs_data_t *settings)
  1250. {
  1251. int val = (int)obs_data_get_int(settings, RES_TYPE);
  1252. bool enabled = (val != ResType_Preferred);
  1253. p = obs_properties_get(props, RESOLUTION);
  1254. obs_property_set_enabled(p, enabled);
  1255. p = obs_properties_get(props, FRAME_INTERVAL);
  1256. obs_property_set_enabled(p, enabled);
  1257. p = obs_properties_get(props, VIDEO_FORMAT);
  1258. obs_property_set_enabled(p, enabled);
  1259. if (val == ResType_Custom) {
  1260. p = obs_properties_get(props, RESOLUTION);
  1261. DeviceResolutionChanged(props, p, settings);
  1262. } else {
  1263. obs_data_unset_autoselect_value(settings, FRAME_INTERVAL);
  1264. }
  1265. return true;
  1266. }
  1267. static DStr GetFPSName(long long interval)
  1268. {
  1269. DStr name;
  1270. if (interval == FPS_MATCHING) {
  1271. dstr_cat(name, TEXT_FPS_MATCHING);
  1272. return name;
  1273. }
  1274. if (interval == FPS_HIGHEST) {
  1275. dstr_cat(name, TEXT_FPS_HIGHEST);
  1276. return name;
  1277. }
  1278. for (const FPSFormat &format : validFPSFormats) {
  1279. if (format.interval != interval)
  1280. continue;
  1281. dstr_cat(name, format.text);
  1282. return name;
  1283. }
  1284. dstr_cat(name, to_string(10000000. / interval).c_str());
  1285. return name;
  1286. }
  1287. static void UpdateFPS(VideoDevice &device, VideoFormat format,
  1288. long long interval, int cx, int cy,
  1289. obs_properties_t *props)
  1290. {
  1291. obs_property_t *list = obs_properties_get(props, FRAME_INTERVAL);
  1292. obs_property_list_clear(list);
  1293. obs_property_list_add_int(list, TEXT_FPS_MATCHING, FPS_MATCHING);
  1294. obs_property_list_add_int(list, TEXT_FPS_HIGHEST, FPS_HIGHEST);
  1295. bool interval_added = interval == FPS_HIGHEST ||
  1296. interval == FPS_MATCHING;
  1297. for (const FPSFormat &fps_format : validFPSFormats) {
  1298. bool video_format_match = false;
  1299. long long format_interval = fps_format.interval;
  1300. bool available = CapsMatch(
  1301. device, ResolutionMatcher(cx, cy),
  1302. VideoFormatMatcher(format, video_format_match),
  1303. FrameRateMatcher(format_interval));
  1304. if (!available && interval != fps_format.interval)
  1305. continue;
  1306. if (interval == fps_format.interval)
  1307. interval_added = true;
  1308. size_t idx = obs_property_list_add_int(list, fps_format.text,
  1309. fps_format.interval);
  1310. obs_property_list_item_disable(list, idx, !available);
  1311. }
  1312. if (interval_added)
  1313. return;
  1314. size_t idx =
  1315. obs_property_list_add_int(list, GetFPSName(interval), interval);
  1316. obs_property_list_item_disable(list, idx, true);
  1317. }
  1318. static DStr GetVideoFormatName(VideoFormat format)
  1319. {
  1320. DStr name;
  1321. for (const VideoFormatName &format_ : videoFormatNames) {
  1322. if (format_.format == format) {
  1323. dstr_cat(name, obs_module_text(format_.name));
  1324. return name;
  1325. }
  1326. }
  1327. dstr_cat(name, TEXT_FORMAT_UNKNOWN);
  1328. dstr_replace(name, "%1", std::to_string((long long)format).c_str());
  1329. return name;
  1330. }
  1331. static void UpdateVideoFormats(VideoDevice &device, VideoFormat format_, int cx,
  1332. int cy, long long interval,
  1333. obs_properties_t *props)
  1334. {
  1335. set<VideoFormat> formats = {VideoFormat::Any};
  1336. auto format_gatherer =
  1337. [&formats](const VideoInfo &info) mutable -> bool {
  1338. formats.insert(info.format);
  1339. return false;
  1340. };
  1341. CapsMatch(device, ResolutionMatcher(cx, cy), FrameRateMatcher(interval),
  1342. format_gatherer);
  1343. obs_property_t *list = obs_properties_get(props, VIDEO_FORMAT);
  1344. obs_property_list_clear(list);
  1345. bool format_added = false;
  1346. for (const VideoFormatName &format : videoFormatNames) {
  1347. bool available = formats.find(format.format) != end(formats);
  1348. if (!available && format.format != format_)
  1349. continue;
  1350. if (format.format == format_)
  1351. format_added = true;
  1352. size_t idx = obs_property_list_add_int(
  1353. list, obs_module_text(format.name),
  1354. (long long)format.format);
  1355. obs_property_list_item_disable(list, idx, !available);
  1356. }
  1357. if (format_added)
  1358. return;
  1359. size_t idx = obs_property_list_add_int(
  1360. list, GetVideoFormatName(format_), (long long)format_);
  1361. obs_property_list_item_disable(list, idx, true);
  1362. }
  1363. static bool UpdateFPS(long long interval, obs_property_t *list)
  1364. {
  1365. size_t size = obs_property_list_item_count(list);
  1366. DStr name;
  1367. for (size_t i = 0; i < size; i++) {
  1368. if (obs_property_list_item_int(list, i) != interval)
  1369. continue;
  1370. obs_property_list_item_disable(list, i, true);
  1371. if (size == 1)
  1372. return false;
  1373. dstr_cat(name, obs_property_list_item_name(list, i));
  1374. break;
  1375. }
  1376. obs_property_list_clear(list);
  1377. if (!name->len)
  1378. name = GetFPSName(interval);
  1379. obs_property_list_add_int(list, name, interval);
  1380. obs_property_list_item_disable(list, 0, true);
  1381. return true;
  1382. }
  1383. static bool DeviceIntervalChanged(obs_properties_t *props, obs_property_t *p,
  1384. obs_data_t *settings)
  1385. {
  1386. long long val = obs_data_get_int(settings, FRAME_INTERVAL);
  1387. PropertiesData *data =
  1388. (PropertiesData *)obs_properties_get_param(props);
  1389. const char *id = obs_data_get_string(settings, VIDEO_DEVICE_ID);
  1390. VideoDevice device;
  1391. if (!data->GetDevice(device, id))
  1392. return UpdateFPS(val, p);
  1393. int cx = 0, cy = 0;
  1394. if (!DetermineResolution(cx, cy, settings, device)) {
  1395. UpdateVideoFormats(device, VideoFormat::Any, 0, 0, 0, props);
  1396. UpdateFPS(device, VideoFormat::Any, 0, 0, 0, props);
  1397. return true;
  1398. }
  1399. int resType = (int)obs_data_get_int(settings, RES_TYPE);
  1400. if (resType != ResType_Custom)
  1401. return true;
  1402. if (val == FPS_MATCHING)
  1403. val = GetOBSFPS();
  1404. VideoFormat format =
  1405. (VideoFormat)obs_data_get_int(settings, VIDEO_FORMAT);
  1406. bool video_format_matches = false;
  1407. long long best_interval = numeric_limits<long long>::max();
  1408. bool frameRateSupported =
  1409. CapsMatch(device, ResolutionMatcher(cx, cy),
  1410. VideoFormatMatcher(format, video_format_matches),
  1411. ClosestFrameRateSelector(val, best_interval),
  1412. FrameRateMatcher(val));
  1413. if (video_format_matches && !frameRateSupported &&
  1414. best_interval != val) {
  1415. long long listed_val = 0;
  1416. for (const FPSFormat &format : validFPSFormats) {
  1417. long long diff = llabs(format.interval - best_interval);
  1418. if (diff < DEVICE_INTERVAL_DIFF_LIMIT) {
  1419. listed_val = format.interval;
  1420. break;
  1421. }
  1422. }
  1423. if (listed_val != val) {
  1424. obs_data_set_autoselect_int(settings, FRAME_INTERVAL,
  1425. listed_val);
  1426. val = listed_val;
  1427. }
  1428. } else {
  1429. obs_data_unset_autoselect_value(settings, FRAME_INTERVAL);
  1430. }
  1431. UpdateVideoFormats(device, format, cx, cy, val, props);
  1432. UpdateFPS(device, format, val, cx, cy, props);
  1433. UNUSED_PARAMETER(p);
  1434. return true;
  1435. }
  1436. static bool UpdateVideoFormats(VideoFormat format, obs_property_t *list)
  1437. {
  1438. size_t size = obs_property_list_item_count(list);
  1439. DStr name;
  1440. for (size_t i = 0; i < size; i++) {
  1441. if ((VideoFormat)obs_property_list_item_int(list, i) != format)
  1442. continue;
  1443. if (size == 1)
  1444. return false;
  1445. dstr_cat(name, obs_property_list_item_name(list, i));
  1446. break;
  1447. }
  1448. obs_property_list_clear(list);
  1449. if (!name->len)
  1450. name = GetVideoFormatName(format);
  1451. obs_property_list_add_int(list, name, (long long)format);
  1452. obs_property_list_item_disable(list, 0, true);
  1453. return true;
  1454. }
  1455. static bool VideoFormatChanged(obs_properties_t *props, obs_property_t *p,
  1456. obs_data_t *settings)
  1457. {
  1458. PropertiesData *data =
  1459. (PropertiesData *)obs_properties_get_param(props);
  1460. const char *id = obs_data_get_string(settings, VIDEO_DEVICE_ID);
  1461. VideoDevice device;
  1462. VideoFormat curFormat =
  1463. (VideoFormat)obs_data_get_int(settings, VIDEO_FORMAT);
  1464. if (!data->GetDevice(device, id))
  1465. return UpdateVideoFormats(curFormat, p);
  1466. int cx, cy;
  1467. if (!DetermineResolution(cx, cy, settings, device)) {
  1468. UpdateVideoFormats(device, VideoFormat::Any, cx, cy, 0, props);
  1469. UpdateFPS(device, VideoFormat::Any, 0, 0, 0, props);
  1470. return true;
  1471. }
  1472. long long interval = obs_data_get_int(settings, FRAME_INTERVAL);
  1473. UpdateVideoFormats(device, curFormat, cx, cy, interval, props);
  1474. UpdateFPS(device, curFormat, interval, cx, cy, props);
  1475. return true;
  1476. }
  1477. static bool CustomAudioClicked(obs_properties_t *props, obs_property_t *p,
  1478. obs_data_t *settings)
  1479. {
  1480. bool useCustomAudio = obs_data_get_bool(settings, USE_CUSTOM_AUDIO);
  1481. p = obs_properties_get(props, AUDIO_DEVICE_ID);
  1482. obs_property_set_visible(p, useCustomAudio);
  1483. return true;
  1484. }
  1485. static bool ActivateClicked(obs_properties_t *, obs_property_t *p, void *data)
  1486. {
  1487. DShowInput *input = reinterpret_cast<DShowInput *>(data);
  1488. if (input->active) {
  1489. input->SetActive(false);
  1490. obs_property_set_description(p, TEXT_ACTIVATE);
  1491. } else {
  1492. input->SetActive(true);
  1493. obs_property_set_description(p, TEXT_DEACTIVATE);
  1494. }
  1495. return true;
  1496. }
  1497. static obs_properties_t *GetDShowProperties(void *obj)
  1498. {
  1499. DShowInput *input = reinterpret_cast<DShowInput *>(obj);
  1500. obs_properties_t *ppts = obs_properties_create();
  1501. PropertiesData *data = new PropertiesData;
  1502. data->input = input;
  1503. obs_properties_set_param(ppts, data, PropertiesDataDestroy);
  1504. obs_property_t *p = obs_properties_add_list(ppts, VIDEO_DEVICE_ID,
  1505. TEXT_DEVICE,
  1506. OBS_COMBO_TYPE_LIST,
  1507. OBS_COMBO_FORMAT_STRING);
  1508. obs_property_set_modified_callback(p, DeviceSelectionChanged);
  1509. Device::EnumVideoDevices(data->devices);
  1510. for (const VideoDevice &device : data->devices)
  1511. AddDevice(p, device);
  1512. const char *activateText = TEXT_ACTIVATE;
  1513. if (input) {
  1514. if (input->active)
  1515. activateText = TEXT_DEACTIVATE;
  1516. }
  1517. obs_properties_add_button(ppts, "activate", activateText,
  1518. ActivateClicked);
  1519. obs_properties_add_button(ppts, "video_config", TEXT_CONFIG_VIDEO,
  1520. VideoConfigClicked);
  1521. obs_properties_add_button(ppts, "xbar_config", TEXT_CONFIG_XBAR,
  1522. CrossbarConfigClicked);
  1523. obs_properties_add_bool(ppts, DEACTIVATE_WNS, TEXT_DWNS);
  1524. /* ------------------------------------- */
  1525. /* video settings */
  1526. p = obs_properties_add_list(ppts, RES_TYPE, TEXT_RES_FPS_TYPE,
  1527. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
  1528. obs_property_set_modified_callback(p, ResTypeChanged);
  1529. obs_property_list_add_int(p, TEXT_PREFERRED_RES, ResType_Preferred);
  1530. obs_property_list_add_int(p, TEXT_CUSTOM_RES, ResType_Custom);
  1531. p = obs_properties_add_list(ppts, RESOLUTION, TEXT_RESOLUTION,
  1532. OBS_COMBO_TYPE_EDITABLE,
  1533. OBS_COMBO_FORMAT_STRING);
  1534. obs_property_set_modified_callback(p, DeviceResolutionChanged);
  1535. p = obs_properties_add_list(ppts, FRAME_INTERVAL, "FPS",
  1536. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
  1537. obs_property_set_modified_callback(p, DeviceIntervalChanged);
  1538. p = obs_properties_add_list(ppts, VIDEO_FORMAT, TEXT_VIDEO_FORMAT,
  1539. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
  1540. obs_property_set_modified_callback(p, VideoFormatChanged);
  1541. p = obs_properties_add_list(ppts, COLOR_SPACE, TEXT_COLOR_SPACE,
  1542. OBS_COMBO_TYPE_LIST,
  1543. OBS_COMBO_FORMAT_STRING);
  1544. obs_property_list_add_string(p, TEXT_COLOR_DEFAULT, "default");
  1545. obs_property_list_add_string(p, "709", "709");
  1546. obs_property_list_add_string(p, "601", "601");
  1547. p = obs_properties_add_list(ppts, COLOR_RANGE, TEXT_COLOR_RANGE,
  1548. OBS_COMBO_TYPE_LIST,
  1549. OBS_COMBO_FORMAT_STRING);
  1550. obs_property_list_add_string(p, TEXT_RANGE_DEFAULT, "default");
  1551. obs_property_list_add_string(p, TEXT_RANGE_PARTIAL, "partial");
  1552. obs_property_list_add_string(p, TEXT_RANGE_FULL, "full");
  1553. p = obs_properties_add_list(ppts, BUFFERING_VAL, TEXT_BUFFERING,
  1554. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
  1555. obs_property_list_add_int(p, TEXT_BUFFERING_AUTO,
  1556. (int64_t)BufferingType::Auto);
  1557. obs_property_list_add_int(p, TEXT_BUFFERING_ON,
  1558. (int64_t)BufferingType::On);
  1559. obs_property_list_add_int(p, TEXT_BUFFERING_OFF,
  1560. (int64_t)BufferingType::Off);
  1561. obs_property_set_long_description(p,
  1562. obs_module_text("Buffering.ToolTip"));
  1563. obs_properties_add_bool(ppts, FLIP_IMAGE, TEXT_FLIP_IMAGE);
  1564. /* ------------------------------------- */
  1565. /* audio settings */
  1566. Device::EnumAudioDevices(data->audioDevices);
  1567. p = obs_properties_add_list(ppts, AUDIO_OUTPUT_MODE, TEXT_AUDIO_MODE,
  1568. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
  1569. obs_property_list_add_int(p, TEXT_MODE_CAPTURE,
  1570. (int64_t)AudioMode::Capture);
  1571. obs_property_list_add_int(p, TEXT_MODE_DSOUND,
  1572. (int64_t)AudioMode::DirectSound);
  1573. obs_property_list_add_int(p, TEXT_MODE_WAVEOUT,
  1574. (int64_t)AudioMode::WaveOut);
  1575. if (!data->audioDevices.size())
  1576. return ppts;
  1577. p = obs_properties_add_bool(ppts, USE_CUSTOM_AUDIO, TEXT_CUSTOM_AUDIO);
  1578. obs_property_set_modified_callback(p, CustomAudioClicked);
  1579. p = obs_properties_add_list(ppts, AUDIO_DEVICE_ID, TEXT_AUDIO_DEVICE,
  1580. OBS_COMBO_TYPE_LIST,
  1581. OBS_COMBO_FORMAT_STRING);
  1582. for (const AudioDevice &device : data->audioDevices)
  1583. AddAudioDevice(p, device);
  1584. return ppts;
  1585. }
  1586. void DShowModuleLogCallback(LogType type, const wchar_t *msg, void *param)
  1587. {
  1588. int obs_type = LOG_DEBUG;
  1589. switch (type) {
  1590. case LogType::Error:
  1591. obs_type = LOG_ERROR;
  1592. break;
  1593. case LogType::Warning:
  1594. obs_type = LOG_WARNING;
  1595. break;
  1596. case LogType::Info:
  1597. obs_type = LOG_INFO;
  1598. break;
  1599. case LogType::Debug:
  1600. obs_type = LOG_DEBUG;
  1601. break;
  1602. }
  1603. DStr dmsg;
  1604. dstr_from_wcs(dmsg, msg);
  1605. blog(obs_type, "DShow: %s", dmsg->array);
  1606. UNUSED_PARAMETER(param);
  1607. }
  1608. static void HideDShowInput(void *data)
  1609. {
  1610. DShowInput *input = reinterpret_cast<DShowInput *>(data);
  1611. if (input->deactivateWhenNotShowing && input->active)
  1612. input->QueueAction(Action::Deactivate);
  1613. }
  1614. static void ShowDShowInput(void *data)
  1615. {
  1616. DShowInput *input = reinterpret_cast<DShowInput *>(data);
  1617. if (input->deactivateWhenNotShowing && input->active)
  1618. input->QueueAction(Action::Activate);
  1619. }
  1620. void RegisterDShowSource()
  1621. {
  1622. SetLogCallback(DShowModuleLogCallback, nullptr);
  1623. obs_source_info info = {};
  1624. info.id = "dshow_input";
  1625. info.type = OBS_SOURCE_TYPE_INPUT;
  1626. info.output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_AUDIO |
  1627. OBS_SOURCE_ASYNC | OBS_SOURCE_DO_NOT_DUPLICATE;
  1628. info.show = ShowDShowInput;
  1629. info.hide = HideDShowInput;
  1630. info.get_name = GetDShowInputName;
  1631. info.create = CreateDShowInput;
  1632. info.destroy = DestroyDShowInput;
  1633. info.update = UpdateDShowInput;
  1634. info.get_defaults = GetDShowDefaults;
  1635. info.get_properties = GetDShowProperties;
  1636. info.icon_type = OBS_ICON_TYPE_CAMERA;
  1637. obs_register_source(&info);
  1638. }