win-dshow.cpp 56 KB

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