win-dshow.cpp 58 KB

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