win-dshow.cpp 54 KB

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