win-dshow.cpp 53 KB

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