win-dshow.cpp 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043
  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. /* YUV DIBS are always top-down */
  466. if (config.format == VideoFormat::XRGB ||
  467. config.format == VideoFormat::ARGB) {
  468. /* RGB DIBs are bottom-up by default */
  469. if (!config.cy_flip)
  470. frame.flip = !frame.flip;
  471. }
  472. if (videoConfig.format == VideoFormat::XRGB ||
  473. videoConfig.format == VideoFormat::ARGB) {
  474. frame.data[0] = data;
  475. frame.linesize[0] = cx * 4;
  476. } else if (videoConfig.format == VideoFormat::YVYU ||
  477. videoConfig.format == VideoFormat::YUY2 ||
  478. videoConfig.format == VideoFormat::HDYC ||
  479. videoConfig.format == VideoFormat::UYVY) {
  480. frame.data[0] = data;
  481. frame.linesize[0] = cx * 2;
  482. } else if (videoConfig.format == VideoFormat::I420) {
  483. frame.data[0] = data;
  484. frame.data[1] = frame.data[0] + (cx * cy_abs);
  485. frame.data[2] = frame.data[1] + (cx * cy_abs / 4);
  486. frame.linesize[0] = cx;
  487. frame.linesize[1] = cx / 2;
  488. frame.linesize[2] = cx / 2;
  489. } else if (videoConfig.format == VideoFormat::YV12) {
  490. frame.data[0] = data;
  491. frame.data[2] = frame.data[0] + (cx * cy_abs);
  492. frame.data[1] = frame.data[2] + (cx * cy_abs / 4);
  493. frame.linesize[0] = cx;
  494. frame.linesize[1] = cx / 2;
  495. frame.linesize[2] = cx / 2;
  496. } else if (videoConfig.format == VideoFormat::NV12) {
  497. frame.data[0] = data;
  498. frame.data[1] = frame.data[0] + (cx * cy_abs);
  499. frame.linesize[0] = cx;
  500. frame.linesize[1] = cx;
  501. } else if (videoConfig.format == VideoFormat::Y800) {
  502. frame.data[0] = data;
  503. frame.linesize[0] = cx;
  504. } else {
  505. /* TODO: other formats */
  506. return;
  507. }
  508. obs_source_output_video2(source, &frame);
  509. UNUSED_PARAMETER(endTime); /* it's the enndd tiimmes! */
  510. UNUSED_PARAMETER(size);
  511. }
  512. void DShowInput::OnEncodedAudioData(enum AVCodecID id, unsigned char *data,
  513. size_t size, long long ts)
  514. {
  515. if (!ffmpeg_decode_valid(audio_decoder)) {
  516. if (ffmpeg_decode_init(audio_decoder, id, false) < 0) {
  517. blog(LOG_WARNING, "Could not initialize audio decoder");
  518. return;
  519. }
  520. }
  521. bool got_output = false;
  522. do {
  523. bool success = ffmpeg_decode_audio(audio_decoder, data, size,
  524. &audio, &got_output);
  525. if (!success) {
  526. blog(LOG_WARNING, "Error decoding audio");
  527. return;
  528. }
  529. if (got_output) {
  530. audio.timestamp = (uint64_t)ts * 100;
  531. #if LOG_ENCODED_AUDIO_TS
  532. blog(LOG_DEBUG, "audio ts: %llu", audio.timestamp);
  533. #endif
  534. obs_source_output_audio(source, &audio);
  535. } else {
  536. break;
  537. }
  538. ts += int64_t(audio_decoder->frame->nb_samples) * 10000000LL /
  539. int64_t(audio_decoder->frame->sample_rate);
  540. size = 0;
  541. data = nullptr;
  542. } while (got_output);
  543. }
  544. void DShowInput::OnAudioData(const AudioConfig &config, unsigned char *data,
  545. size_t size, long long startTime,
  546. long long endTime)
  547. {
  548. size_t block_size;
  549. if (config.format == AudioFormat::AAC) {
  550. OnEncodedAudioData(AV_CODEC_ID_AAC, data, size, startTime);
  551. return;
  552. } else if (config.format == AudioFormat::AC3) {
  553. OnEncodedAudioData(AV_CODEC_ID_AC3, data, size, startTime);
  554. return;
  555. } else if (config.format == AudioFormat::MPGA) {
  556. OnEncodedAudioData(AV_CODEC_ID_MP2, data, size, startTime);
  557. return;
  558. }
  559. audio.speakers = convert_speaker_layout((uint8_t)config.channels);
  560. audio.format = ConvertAudioFormat(config.format);
  561. audio.samples_per_sec = (uint32_t)config.sampleRate;
  562. audio.data[0] = data;
  563. block_size = get_audio_bytes_per_channel(audio.format) *
  564. get_audio_channels(audio.speakers);
  565. audio.frames = (uint32_t)(size / block_size);
  566. audio.timestamp = (uint64_t)startTime * 100;
  567. if (audio.format != AUDIO_FORMAT_UNKNOWN)
  568. obs_source_output_audio(source, &audio);
  569. UNUSED_PARAMETER(endTime);
  570. }
  571. struct PropertiesData {
  572. DShowInput *input;
  573. vector<VideoDevice> devices;
  574. vector<AudioDevice> audioDevices;
  575. bool GetDevice(VideoDevice &device, const char *encoded_id) const
  576. {
  577. DeviceId deviceId;
  578. DecodeDeviceId(deviceId, encoded_id);
  579. for (const VideoDevice &curDevice : devices) {
  580. if (deviceId.name == curDevice.name &&
  581. deviceId.path == curDevice.path) {
  582. device = curDevice;
  583. return true;
  584. }
  585. }
  586. return false;
  587. }
  588. };
  589. static inline bool ConvertRes(int &cx, int &cy, const char *res)
  590. {
  591. return sscanf(res, "%dx%d", &cx, &cy) == 2;
  592. }
  593. static inline bool FormatMatches(VideoFormat left, VideoFormat right)
  594. {
  595. return left == VideoFormat::Any || right == VideoFormat::Any ||
  596. left == right;
  597. }
  598. static inline bool ResolutionValid(string res, int &cx, int &cy)
  599. {
  600. if (!res.size())
  601. return false;
  602. return ConvertRes(cx, cy, res.c_str());
  603. }
  604. static inline bool CapsMatch(const VideoInfo &)
  605. {
  606. return true;
  607. }
  608. template<typename... F> static bool CapsMatch(const VideoDevice &dev, F... fs);
  609. template<typename F, typename... Fs>
  610. static inline bool CapsMatch(const VideoInfo &info, F &&f, Fs... fs)
  611. {
  612. return f(info) && CapsMatch(info, fs...);
  613. }
  614. template<typename... F> static bool CapsMatch(const VideoDevice &dev, F... fs)
  615. {
  616. // no early exit, trigger all side effects.
  617. bool match = false;
  618. for (const VideoInfo &info : dev.caps)
  619. if (CapsMatch(info, fs...))
  620. match = true;
  621. return match;
  622. }
  623. static inline bool MatcherMatchVideoFormat(VideoFormat format, bool &did_match,
  624. const VideoInfo &info)
  625. {
  626. bool match = FormatMatches(format, info.format);
  627. did_match = did_match || match;
  628. return match;
  629. }
  630. static inline bool MatcherClosestFrameRateSelector(long long interval,
  631. long long &best_match,
  632. const VideoInfo &info)
  633. {
  634. long long current = FrameRateInterval(info, interval);
  635. if (llabs(interval - best_match) > llabs(interval - current))
  636. best_match = current;
  637. return true;
  638. }
  639. #if 0
  640. auto ResolutionMatcher = [](int cx, int cy)
  641. {
  642. return [cx, cy](const VideoInfo &info)
  643. {
  644. return ResolutionAvailable(info, cx, cy);
  645. };
  646. };
  647. auto FrameRateMatcher = [](long long interval)
  648. {
  649. return [interval](const VideoInfo &info)
  650. {
  651. return FrameRateAvailable(info, interval);
  652. };
  653. };
  654. auto VideoFormatMatcher = [](VideoFormat format, bool &did_match)
  655. {
  656. return [format, &did_match](const VideoInfo &info)
  657. {
  658. return MatcherMatchVideoFormat(format, did_match, info);
  659. };
  660. };
  661. auto ClosestFrameRateSelector = [](long long interval, long long &best_match)
  662. {
  663. return [interval, &best_match](const VideoInfo &info) mutable -> bool
  664. {
  665. MatcherClosestFrameRateSelector(interval, best_match, info);
  666. };
  667. }
  668. #else
  669. #define ResolutionMatcher(cx, cy) \
  670. [cx, cy](const VideoInfo &info) -> bool { \
  671. return ResolutionAvailable(info, cx, cy); \
  672. }
  673. #define FrameRateMatcher(interval) \
  674. [interval](const VideoInfo &info) -> bool { \
  675. return FrameRateAvailable(info, interval); \
  676. }
  677. #define VideoFormatMatcher(format, did_match) \
  678. [format, &did_match](const VideoInfo &info) mutable -> bool { \
  679. return MatcherMatchVideoFormat(format, did_match, info); \
  680. }
  681. #define ClosestFrameRateSelector(interval, best_match) \
  682. [interval, &best_match](const VideoInfo &info) mutable -> bool { \
  683. return MatcherClosestFrameRateSelector(interval, best_match, \
  684. info); \
  685. }
  686. #endif
  687. static bool ResolutionAvailable(const VideoDevice &dev, int cx, int cy)
  688. {
  689. return CapsMatch(dev, ResolutionMatcher(cx, cy));
  690. }
  691. static bool DetermineResolution(int &cx, int &cy, obs_data_t *settings,
  692. VideoDevice dev)
  693. {
  694. const char *res = obs_data_get_autoselect_string(settings, RESOLUTION);
  695. if (obs_data_has_autoselect_value(settings, RESOLUTION) &&
  696. ConvertRes(cx, cy, res) && ResolutionAvailable(dev, cx, cy))
  697. return true;
  698. res = obs_data_get_string(settings, RESOLUTION);
  699. if (ConvertRes(cx, cy, res) && ResolutionAvailable(dev, cx, cy))
  700. return true;
  701. res = obs_data_get_string(settings, LAST_RESOLUTION);
  702. if (ConvertRes(cx, cy, res) && ResolutionAvailable(dev, cx, cy))
  703. return true;
  704. return false;
  705. }
  706. static long long GetOBSFPS();
  707. static inline bool IsDelayedDevice(const VideoConfig &config)
  708. {
  709. return config.format > VideoFormat::MJPEG ||
  710. wstrstri(config.name.c_str(), L"elgato") != NULL ||
  711. wstrstri(config.name.c_str(), L"stream engine") != NULL;
  712. }
  713. static inline bool IsDecoupled(const VideoConfig &config)
  714. {
  715. return wstrstri(config.name.c_str(), L"GV-USB2") != NULL;
  716. }
  717. inline void DShowInput::SetupBuffering(obs_data_t *settings)
  718. {
  719. BufferingType bufType;
  720. bool useBuffering;
  721. bufType = (BufferingType)obs_data_get_int(settings, BUFFERING_VAL);
  722. if (bufType == BufferingType::Auto)
  723. useBuffering = IsDelayedDevice(videoConfig);
  724. else
  725. useBuffering = bufType == BufferingType::On;
  726. obs_source_set_async_unbuffered(source, !useBuffering);
  727. obs_source_set_async_decoupled(source, IsDecoupled(videoConfig));
  728. }
  729. static DStr GetVideoFormatName(VideoFormat format);
  730. bool DShowInput::UpdateVideoConfig(obs_data_t *settings)
  731. {
  732. string video_device_id = obs_data_get_string(settings, VIDEO_DEVICE_ID);
  733. deactivateWhenNotShowing = obs_data_get_bool(settings, DEACTIVATE_WNS);
  734. flip = obs_data_get_bool(settings, FLIP_IMAGE);
  735. autorotation = obs_data_get_bool(settings, AUTOROTATION);
  736. DeviceId id;
  737. if (!DecodeDeviceId(id, video_device_id.c_str())) {
  738. blog(LOG_WARNING, "%s: DecodeDeviceId failed",
  739. obs_source_get_name(source));
  740. return false;
  741. }
  742. PropertiesData data;
  743. Device::EnumVideoDevices(data.devices);
  744. VideoDevice dev;
  745. if (!data.GetDevice(dev, video_device_id.c_str())) {
  746. blog(LOG_WARNING, "%s: data.GetDevice failed",
  747. obs_source_get_name(source));
  748. return false;
  749. }
  750. int resType = (int)obs_data_get_int(settings, RES_TYPE);
  751. int cx = 0, cy = 0;
  752. long long interval = 0;
  753. VideoFormat format = VideoFormat::Any;
  754. if (resType == ResType_Custom) {
  755. bool has_autosel_val;
  756. string resolution = obs_data_get_string(settings, RESOLUTION);
  757. if (!ResolutionValid(resolution, cx, cy)) {
  758. blog(LOG_WARNING, "%s: ResolutionValid failed",
  759. obs_source_get_name(source));
  760. return false;
  761. }
  762. has_autosel_val =
  763. obs_data_has_autoselect_value(settings, FRAME_INTERVAL);
  764. interval = has_autosel_val
  765. ? obs_data_get_autoselect_int(settings,
  766. FRAME_INTERVAL)
  767. : obs_data_get_int(settings, FRAME_INTERVAL);
  768. if (interval == FPS_MATCHING)
  769. interval = GetOBSFPS();
  770. format = (VideoFormat)obs_data_get_int(settings, VIDEO_FORMAT);
  771. long long best_interval = numeric_limits<long long>::max();
  772. bool video_format_match = false;
  773. bool caps_match = CapsMatch(
  774. dev, ResolutionMatcher(cx, cy),
  775. VideoFormatMatcher(format, video_format_match),
  776. ClosestFrameRateSelector(interval, best_interval),
  777. FrameRateMatcher(interval));
  778. if (!caps_match && !video_format_match) {
  779. blog(LOG_WARNING, "%s: Video format match failed",
  780. obs_source_get_name(source));
  781. return false;
  782. }
  783. interval = best_interval;
  784. }
  785. videoConfig.name = id.name.c_str();
  786. videoConfig.path = id.path.c_str();
  787. videoConfig.useDefaultConfig = resType == ResType_Preferred;
  788. videoConfig.cx = cx;
  789. videoConfig.cy_abs = abs(cy);
  790. videoConfig.cy_flip = cy < 0;
  791. videoConfig.frameInterval = interval;
  792. videoConfig.internalFormat = format;
  793. deviceHasAudio = dev.audioAttached;
  794. deviceHasSeparateAudioFilter = dev.separateAudioFilter;
  795. videoConfig.callback = std::bind(&DShowInput::OnVideoData, this,
  796. placeholders::_1, placeholders::_2,
  797. placeholders::_3, placeholders::_4,
  798. placeholders::_5, placeholders::_6);
  799. videoConfig.format = videoConfig.internalFormat;
  800. if (!device.SetVideoConfig(&videoConfig)) {
  801. blog(LOG_WARNING, "%s: device.SetVideoConfig failed",
  802. obs_source_get_name(source));
  803. return false;
  804. }
  805. DStr formatName = GetVideoFormatName(videoConfig.internalFormat);
  806. double fps = 0.0;
  807. if (videoConfig.frameInterval)
  808. fps = 10000000.0 / double(videoConfig.frameInterval);
  809. BPtr<char> name_utf8;
  810. BPtr<char> path_utf8;
  811. os_wcs_to_utf8_ptr(videoConfig.name.c_str(), videoConfig.name.size(),
  812. &name_utf8);
  813. os_wcs_to_utf8_ptr(videoConfig.path.c_str(), videoConfig.path.size(),
  814. &path_utf8);
  815. blog(LOG_INFO, "---------------------------------");
  816. blog(LOG_INFO,
  817. "[DShow Device: '%s'] settings updated: \n"
  818. "\tvideo device: %s\n"
  819. "\tvideo path: %s\n"
  820. "\tresolution: %dx%d\n"
  821. "\tflip: %d\n"
  822. "\tfps: %0.2f (interval: %lld)\n"
  823. "\tformat: %s",
  824. obs_source_get_name(source), (const char *)name_utf8,
  825. (const char *)path_utf8, videoConfig.cx, videoConfig.cy_abs,
  826. (int)videoConfig.cy_flip, fps, videoConfig.frameInterval,
  827. formatName->array);
  828. SetupBuffering(settings);
  829. return true;
  830. }
  831. bool DShowInput::UpdateAudioConfig(obs_data_t *settings)
  832. {
  833. string audio_device_id = obs_data_get_string(settings, AUDIO_DEVICE_ID);
  834. bool useCustomAudio = obs_data_get_bool(settings, USE_CUSTOM_AUDIO);
  835. if (useCustomAudio) {
  836. DeviceId id;
  837. if (!DecodeDeviceId(id, audio_device_id.c_str()))
  838. return false;
  839. audioConfig.name = id.name.c_str();
  840. audioConfig.path = id.path.c_str();
  841. } else if (!deviceHasAudio) {
  842. return true;
  843. }
  844. audioConfig.useVideoDevice = !useCustomAudio &&
  845. !deviceHasSeparateAudioFilter;
  846. audioConfig.useSeparateAudioFilter = deviceHasSeparateAudioFilter;
  847. audioConfig.callback = std::bind(&DShowInput::OnAudioData, this,
  848. placeholders::_1, placeholders::_2,
  849. placeholders::_3, placeholders::_4,
  850. placeholders::_5);
  851. audioConfig.mode =
  852. (AudioMode)obs_data_get_int(settings, AUDIO_OUTPUT_MODE);
  853. bool success = device.SetAudioConfig(&audioConfig);
  854. if (!success)
  855. return false;
  856. BPtr<char> name_utf8;
  857. os_wcs_to_utf8_ptr(audioConfig.name.c_str(), audioConfig.name.size(),
  858. &name_utf8);
  859. blog(LOG_INFO, "\tusing video device audio: %s",
  860. audioConfig.useVideoDevice ? "yes" : "no");
  861. if (!audioConfig.useVideoDevice) {
  862. if (audioConfig.useSeparateAudioFilter)
  863. blog(LOG_INFO, "\tseparate audio filter");
  864. else
  865. blog(LOG_INFO, "\taudio device: %s",
  866. (const char *)name_utf8);
  867. }
  868. const char *mode = "";
  869. switch (audioConfig.mode) {
  870. case AudioMode::Capture:
  871. mode = "Capture";
  872. break;
  873. case AudioMode::DirectSound:
  874. mode = "DirectSound";
  875. break;
  876. case AudioMode::WaveOut:
  877. mode = "WaveOut";
  878. break;
  879. }
  880. blog(LOG_INFO,
  881. "\tsample rate: %d\n"
  882. "\tchannels: %d\n"
  883. "\taudio type: %s",
  884. audioConfig.sampleRate, audioConfig.channels, mode);
  885. return true;
  886. }
  887. void DShowInput::SetActive(bool active_)
  888. {
  889. obs_data_t *settings = obs_source_get_settings(source);
  890. QueueAction(active_ ? Action::Activate : Action::Deactivate);
  891. obs_data_set_bool(settings, "active", active_);
  892. active = active_;
  893. obs_data_release(settings);
  894. }
  895. inline enum video_colorspace
  896. DShowInput::GetColorSpace(obs_data_t *settings) const
  897. {
  898. const char *space = obs_data_get_string(settings, COLOR_SPACE);
  899. if (astrcmpi(space, "709") == 0)
  900. return VIDEO_CS_709;
  901. if (astrcmpi(space, "601") == 0)
  902. return VIDEO_CS_601;
  903. return VIDEO_CS_DEFAULT;
  904. }
  905. inline enum video_range_type
  906. DShowInput::GetColorRange(obs_data_t *settings) const
  907. {
  908. const char *range = obs_data_get_string(settings, COLOR_RANGE);
  909. if (astrcmpi(range, "full") == 0)
  910. return VIDEO_RANGE_FULL;
  911. if (astrcmpi(range, "partial") == 0)
  912. return VIDEO_RANGE_PARTIAL;
  913. return VIDEO_RANGE_DEFAULT;
  914. }
  915. inline bool DShowInput::Activate(obs_data_t *settings)
  916. {
  917. if (!device.ResetGraph())
  918. return false;
  919. if (!UpdateVideoConfig(settings)) {
  920. blog(LOG_WARNING, "%s: Video configuration failed",
  921. obs_source_get_name(source));
  922. return false;
  923. }
  924. if (!UpdateAudioConfig(settings))
  925. blog(LOG_WARNING,
  926. "%s: Audio configuration failed, ignoring "
  927. "audio",
  928. obs_source_get_name(source));
  929. if (!device.ConnectFilters())
  930. return false;
  931. if (device.Start() != Result::Success)
  932. return false;
  933. enum video_colorspace cs = GetColorSpace(settings);
  934. range = GetColorRange(settings);
  935. frame.range = range;
  936. bool success = video_format_get_parameters(cs, range,
  937. frame.color_matrix,
  938. frame.color_range_min,
  939. frame.color_range_max);
  940. if (!success) {
  941. blog(LOG_ERROR,
  942. "Failed to get video format parameters for "
  943. "video format %u",
  944. cs);
  945. }
  946. return true;
  947. }
  948. inline void DShowInput::Deactivate()
  949. {
  950. device.ResetGraph();
  951. obs_source_output_video2(source, nullptr);
  952. }
  953. /* ------------------------------------------------------------------------- */
  954. static const char *GetDShowInputName(void *)
  955. {
  956. return TEXT_INPUT_NAME;
  957. }
  958. static void proc_activate(void *data, calldata_t *cd)
  959. {
  960. bool activate = calldata_bool(cd, "active");
  961. DShowInput *input = reinterpret_cast<DShowInput *>(data);
  962. input->SetActive(activate);
  963. }
  964. static void *CreateDShowInput(obs_data_t *settings, obs_source_t *source)
  965. {
  966. DShowInput *dshow = nullptr;
  967. try {
  968. dshow = new DShowInput(source, settings);
  969. proc_handler_t *ph = obs_source_get_proc_handler(source);
  970. proc_handler_add(ph, "void activate(bool active)",
  971. proc_activate, dshow);
  972. } catch (const char *error) {
  973. blog(LOG_ERROR, "Could not create device '%s': %s",
  974. obs_source_get_name(source), error);
  975. }
  976. return dshow;
  977. }
  978. static void DestroyDShowInput(void *data)
  979. {
  980. delete reinterpret_cast<DShowInput *>(data);
  981. }
  982. static void UpdateDShowInput(void *data, obs_data_t *settings)
  983. {
  984. DShowInput *input = reinterpret_cast<DShowInput *>(data);
  985. if (input->active)
  986. input->QueueActivate(settings);
  987. }
  988. static void GetDShowDefaults(obs_data_t *settings)
  989. {
  990. obs_data_set_default_int(settings, FRAME_INTERVAL, FPS_MATCHING);
  991. obs_data_set_default_int(settings, RES_TYPE, ResType_Preferred);
  992. obs_data_set_default_int(settings, VIDEO_FORMAT, (int)VideoFormat::Any);
  993. obs_data_set_default_bool(settings, "active", true);
  994. obs_data_set_default_string(settings, COLOR_SPACE, "default");
  995. obs_data_set_default_string(settings, COLOR_RANGE, "default");
  996. obs_data_set_default_int(settings, AUDIO_OUTPUT_MODE,
  997. (int)AudioMode::Capture);
  998. obs_data_set_default_bool(settings, AUTOROTATION, true);
  999. }
  1000. struct Resolution {
  1001. int cx, cy;
  1002. inline Resolution(int cx, int cy) : cx(cx), cy(cy) {}
  1003. };
  1004. static void InsertResolution(vector<Resolution> &resolutions, int cx, int cy)
  1005. {
  1006. int bestCY = 0;
  1007. size_t idx = 0;
  1008. for (; idx < resolutions.size(); idx++) {
  1009. const Resolution &res = resolutions[idx];
  1010. if (res.cx > cx)
  1011. break;
  1012. if (res.cx == cx) {
  1013. if (res.cy == cy)
  1014. return;
  1015. if (!bestCY)
  1016. bestCY = res.cy;
  1017. else if (res.cy > bestCY)
  1018. break;
  1019. }
  1020. }
  1021. resolutions.insert(resolutions.begin() + idx, Resolution(cx, cy));
  1022. }
  1023. static inline void AddCap(vector<Resolution> &resolutions, const VideoInfo &cap)
  1024. {
  1025. InsertResolution(resolutions, cap.minCX, cap.minCY);
  1026. InsertResolution(resolutions, cap.maxCX, cap.maxCY);
  1027. }
  1028. #define MAKE_DSHOW_FPS(fps) (10000000LL / (fps))
  1029. #define MAKE_DSHOW_FRACTIONAL_FPS(den, num) ((num)*10000000LL / (den))
  1030. static long long GetOBSFPS()
  1031. {
  1032. obs_video_info ovi;
  1033. if (!obs_get_video_info(&ovi))
  1034. return 0;
  1035. return MAKE_DSHOW_FRACTIONAL_FPS(ovi.fps_num, ovi.fps_den);
  1036. }
  1037. struct FPSFormat {
  1038. const char *text;
  1039. long long interval;
  1040. };
  1041. static const FPSFormat validFPSFormats[] = {
  1042. {"60", MAKE_DSHOW_FPS(60)},
  1043. {"59.94 NTSC", MAKE_DSHOW_FRACTIONAL_FPS(60000, 1001)},
  1044. {"50", MAKE_DSHOW_FPS(50)},
  1045. {"48 film", MAKE_DSHOW_FRACTIONAL_FPS(48000, 1001)},
  1046. {"40", MAKE_DSHOW_FPS(40)},
  1047. {"30", MAKE_DSHOW_FPS(30)},
  1048. {"29.97 NTSC", MAKE_DSHOW_FRACTIONAL_FPS(30000, 1001)},
  1049. {"25", MAKE_DSHOW_FPS(25)},
  1050. {"24 film", MAKE_DSHOW_FRACTIONAL_FPS(24000, 1001)},
  1051. {"20", MAKE_DSHOW_FPS(20)},
  1052. {"15", MAKE_DSHOW_FPS(15)},
  1053. {"10", MAKE_DSHOW_FPS(10)},
  1054. {"5", MAKE_DSHOW_FPS(5)},
  1055. {"4", MAKE_DSHOW_FPS(4)},
  1056. {"3", MAKE_DSHOW_FPS(3)},
  1057. {"2", MAKE_DSHOW_FPS(2)},
  1058. {"1", MAKE_DSHOW_FPS(1)},
  1059. };
  1060. static bool DeviceIntervalChanged(obs_properties_t *props, obs_property_t *p,
  1061. obs_data_t *settings);
  1062. static bool TryResolution(VideoDevice &dev, string res)
  1063. {
  1064. int cx, cy;
  1065. if (!ConvertRes(cx, cy, res.c_str()))
  1066. return false;
  1067. return ResolutionAvailable(dev, cx, cy);
  1068. }
  1069. static bool SetResolution(obs_properties_t *props, obs_data_t *settings,
  1070. string res, bool autoselect = false)
  1071. {
  1072. if (autoselect)
  1073. obs_data_set_autoselect_string(settings, RESOLUTION,
  1074. res.c_str());
  1075. else
  1076. obs_data_unset_autoselect_value(settings, RESOLUTION);
  1077. DeviceIntervalChanged(props, obs_properties_get(props, FRAME_INTERVAL),
  1078. settings);
  1079. if (!autoselect)
  1080. obs_data_set_string(settings, LAST_RESOLUTION, res.c_str());
  1081. return true;
  1082. }
  1083. static bool DeviceResolutionChanged(obs_properties_t *props, obs_property_t *p,
  1084. obs_data_t *settings)
  1085. {
  1086. UNUSED_PARAMETER(p);
  1087. PropertiesData *data =
  1088. (PropertiesData *)obs_properties_get_param(props);
  1089. const char *id;
  1090. VideoDevice device;
  1091. id = obs_data_get_string(settings, VIDEO_DEVICE_ID);
  1092. string res = obs_data_get_string(settings, RESOLUTION);
  1093. string last_res = obs_data_get_string(settings, LAST_RESOLUTION);
  1094. if (!data->GetDevice(device, id))
  1095. return false;
  1096. if (TryResolution(device, res))
  1097. return SetResolution(props, settings, res);
  1098. if (TryResolution(device, last_res))
  1099. return SetResolution(props, settings, last_res, true);
  1100. return false;
  1101. }
  1102. struct VideoFormatName {
  1103. VideoFormat format;
  1104. const char *name;
  1105. };
  1106. static const VideoFormatName videoFormatNames[] = {
  1107. /* autoselect format*/
  1108. {VideoFormat::Any, "VideoFormat.Any"},
  1109. /* raw formats */
  1110. {VideoFormat::ARGB, "ARGB"},
  1111. {VideoFormat::XRGB, "XRGB"},
  1112. /* planar YUV formats */
  1113. {VideoFormat::I420, "I420"},
  1114. {VideoFormat::NV12, "NV12"},
  1115. {VideoFormat::YV12, "YV12"},
  1116. {VideoFormat::Y800, "Y800"},
  1117. /* packed YUV formats */
  1118. {VideoFormat::YVYU, "YVYU"},
  1119. {VideoFormat::YUY2, "YUY2"},
  1120. {VideoFormat::UYVY, "UYVY"},
  1121. {VideoFormat::HDYC, "HDYC"},
  1122. /* encoded formats */
  1123. {VideoFormat::MJPEG, "MJPEG"},
  1124. {VideoFormat::H264, "H264"}};
  1125. static bool ResTypeChanged(obs_properties_t *props, obs_property_t *p,
  1126. obs_data_t *settings);
  1127. static size_t AddDevice(obs_property_t *device_list, const string &id)
  1128. {
  1129. DStr name, path;
  1130. if (!DecodeDeviceDStr(name, path, id.c_str()))
  1131. return numeric_limits<size_t>::max();
  1132. return obs_property_list_add_string(device_list, name, id.c_str());
  1133. }
  1134. static bool UpdateDeviceList(obs_property_t *list, const string &id)
  1135. {
  1136. size_t size = obs_property_list_item_count(list);
  1137. bool found = false;
  1138. bool disabled_unknown_found = false;
  1139. for (size_t i = 0; i < size; i++) {
  1140. if (obs_property_list_item_string(list, i) == id) {
  1141. found = true;
  1142. continue;
  1143. }
  1144. if (obs_property_list_item_disabled(list, i))
  1145. disabled_unknown_found = true;
  1146. }
  1147. if (!found && !disabled_unknown_found) {
  1148. size_t idx = AddDevice(list, id);
  1149. obs_property_list_item_disable(list, idx, true);
  1150. return true;
  1151. }
  1152. if (found && !disabled_unknown_found)
  1153. return false;
  1154. for (size_t i = 0; i < size;) {
  1155. if (obs_property_list_item_disabled(list, i)) {
  1156. obs_property_list_item_remove(list, i);
  1157. continue;
  1158. }
  1159. i += 1;
  1160. }
  1161. return true;
  1162. }
  1163. static bool DeviceSelectionChanged(obs_properties_t *props, obs_property_t *p,
  1164. obs_data_t *settings)
  1165. {
  1166. PropertiesData *data =
  1167. (PropertiesData *)obs_properties_get_param(props);
  1168. VideoDevice device;
  1169. string id = obs_data_get_string(settings, VIDEO_DEVICE_ID);
  1170. string old_id = obs_data_get_string(settings, LAST_VIDEO_DEV_ID);
  1171. bool device_list_updated = UpdateDeviceList(p, id);
  1172. if (!data->GetDevice(device, id.c_str()))
  1173. return !device_list_updated;
  1174. vector<Resolution> resolutions;
  1175. for (const VideoInfo &cap : device.caps)
  1176. AddCap(resolutions, cap);
  1177. p = obs_properties_get(props, RESOLUTION);
  1178. obs_property_list_clear(p);
  1179. for (size_t idx = resolutions.size(); idx > 0; idx--) {
  1180. const Resolution &res = resolutions[idx - 1];
  1181. string strRes;
  1182. strRes += to_string(res.cx);
  1183. strRes += "x";
  1184. strRes += to_string(res.cy);
  1185. obs_property_list_add_string(p, strRes.c_str(), strRes.c_str());
  1186. }
  1187. /* only refresh properties if device legitimately changed */
  1188. if (!id.size() || !old_id.size() || id != old_id) {
  1189. p = obs_properties_get(props, RES_TYPE);
  1190. ResTypeChanged(props, p, settings);
  1191. obs_data_set_string(settings, LAST_VIDEO_DEV_ID, id.c_str());
  1192. }
  1193. return true;
  1194. }
  1195. static bool VideoConfigClicked(obs_properties_t *props, obs_property_t *p,
  1196. void *data)
  1197. {
  1198. DShowInput *input = reinterpret_cast<DShowInput *>(data);
  1199. input->QueueAction(Action::ConfigVideo);
  1200. UNUSED_PARAMETER(props);
  1201. UNUSED_PARAMETER(p);
  1202. return false;
  1203. }
  1204. /*static bool AudioConfigClicked(obs_properties_t *props, obs_property_t *p,
  1205. void *data)
  1206. {
  1207. DShowInput *input = reinterpret_cast<DShowInput*>(data);
  1208. input->QueueAction(Action::ConfigAudio);
  1209. UNUSED_PARAMETER(props);
  1210. UNUSED_PARAMETER(p);
  1211. return false;
  1212. }*/
  1213. static bool CrossbarConfigClicked(obs_properties_t *props, obs_property_t *p,
  1214. void *data)
  1215. {
  1216. DShowInput *input = reinterpret_cast<DShowInput *>(data);
  1217. input->QueueAction(Action::ConfigCrossbar1);
  1218. UNUSED_PARAMETER(props);
  1219. UNUSED_PARAMETER(p);
  1220. return false;
  1221. }
  1222. /*static bool Crossbar2ConfigClicked(obs_properties_t *props, obs_property_t *p,
  1223. void *data)
  1224. {
  1225. DShowInput *input = reinterpret_cast<DShowInput*>(data);
  1226. input->QueueAction(Action::ConfigCrossbar2);
  1227. UNUSED_PARAMETER(props);
  1228. UNUSED_PARAMETER(p);
  1229. return false;
  1230. }*/
  1231. static bool AddDevice(obs_property_t *device_list, const VideoDevice &device)
  1232. {
  1233. DStr name, path, device_id;
  1234. dstr_from_wcs(name, device.name.c_str());
  1235. dstr_from_wcs(path, device.path.c_str());
  1236. encode_dstr(path);
  1237. dstr_copy_dstr(device_id, name);
  1238. encode_dstr(device_id);
  1239. dstr_cat(device_id, ":");
  1240. dstr_cat_dstr(device_id, path);
  1241. obs_property_list_add_string(device_list, name, device_id);
  1242. return true;
  1243. }
  1244. static bool AddAudioDevice(obs_property_t *device_list,
  1245. const AudioDevice &device)
  1246. {
  1247. DStr name, path, device_id;
  1248. dstr_from_wcs(name, device.name.c_str());
  1249. dstr_from_wcs(path, device.path.c_str());
  1250. encode_dstr(path);
  1251. dstr_copy_dstr(device_id, name);
  1252. encode_dstr(device_id);
  1253. dstr_cat(device_id, ":");
  1254. dstr_cat_dstr(device_id, path);
  1255. obs_property_list_add_string(device_list, name, device_id);
  1256. return true;
  1257. }
  1258. static void PropertiesDataDestroy(void *data)
  1259. {
  1260. delete reinterpret_cast<PropertiesData *>(data);
  1261. }
  1262. static bool ResTypeChanged(obs_properties_t *props, obs_property_t *p,
  1263. obs_data_t *settings)
  1264. {
  1265. int val = (int)obs_data_get_int(settings, RES_TYPE);
  1266. bool enabled = (val != ResType_Preferred);
  1267. p = obs_properties_get(props, RESOLUTION);
  1268. obs_property_set_enabled(p, enabled);
  1269. p = obs_properties_get(props, FRAME_INTERVAL);
  1270. obs_property_set_enabled(p, enabled);
  1271. p = obs_properties_get(props, VIDEO_FORMAT);
  1272. obs_property_set_enabled(p, enabled);
  1273. if (val == ResType_Custom) {
  1274. p = obs_properties_get(props, RESOLUTION);
  1275. DeviceResolutionChanged(props, p, settings);
  1276. } else {
  1277. obs_data_unset_autoselect_value(settings, FRAME_INTERVAL);
  1278. }
  1279. return true;
  1280. }
  1281. static DStr GetFPSName(long long interval)
  1282. {
  1283. DStr name;
  1284. if (interval == FPS_MATCHING) {
  1285. dstr_cat(name, TEXT_FPS_MATCHING);
  1286. return name;
  1287. }
  1288. if (interval == FPS_HIGHEST) {
  1289. dstr_cat(name, TEXT_FPS_HIGHEST);
  1290. return name;
  1291. }
  1292. for (const FPSFormat &format : validFPSFormats) {
  1293. if (format.interval != interval)
  1294. continue;
  1295. dstr_cat(name, format.text);
  1296. return name;
  1297. }
  1298. dstr_cat(name, to_string(10000000. / interval).c_str());
  1299. return name;
  1300. }
  1301. static void UpdateFPS(VideoDevice &device, VideoFormat format,
  1302. long long interval, int cx, int cy,
  1303. obs_properties_t *props)
  1304. {
  1305. obs_property_t *list = obs_properties_get(props, FRAME_INTERVAL);
  1306. obs_property_list_clear(list);
  1307. obs_property_list_add_int(list, TEXT_FPS_MATCHING, FPS_MATCHING);
  1308. obs_property_list_add_int(list, TEXT_FPS_HIGHEST, FPS_HIGHEST);
  1309. bool interval_added = interval == FPS_HIGHEST ||
  1310. interval == FPS_MATCHING;
  1311. for (const FPSFormat &fps_format : validFPSFormats) {
  1312. bool video_format_match = false;
  1313. long long format_interval = fps_format.interval;
  1314. bool available = CapsMatch(
  1315. device, ResolutionMatcher(cx, cy),
  1316. VideoFormatMatcher(format, video_format_match),
  1317. FrameRateMatcher(format_interval));
  1318. if (!available && interval != fps_format.interval)
  1319. continue;
  1320. if (interval == fps_format.interval)
  1321. interval_added = true;
  1322. size_t idx = obs_property_list_add_int(list, fps_format.text,
  1323. fps_format.interval);
  1324. obs_property_list_item_disable(list, idx, !available);
  1325. }
  1326. if (interval_added)
  1327. return;
  1328. size_t idx =
  1329. obs_property_list_add_int(list, GetFPSName(interval), interval);
  1330. obs_property_list_item_disable(list, idx, true);
  1331. }
  1332. static DStr GetVideoFormatName(VideoFormat format)
  1333. {
  1334. DStr name;
  1335. for (const VideoFormatName &format_ : videoFormatNames) {
  1336. if (format_.format == format) {
  1337. dstr_cat(name, obs_module_text(format_.name));
  1338. return name;
  1339. }
  1340. }
  1341. dstr_cat(name, TEXT_FORMAT_UNKNOWN);
  1342. dstr_replace(name, "%1", std::to_string((long long)format).c_str());
  1343. return name;
  1344. }
  1345. static void UpdateVideoFormats(VideoDevice &device, VideoFormat format_, int cx,
  1346. int cy, long long interval,
  1347. obs_properties_t *props)
  1348. {
  1349. set<VideoFormat> formats = {VideoFormat::Any};
  1350. auto format_gatherer =
  1351. [&formats](const VideoInfo &info) mutable -> bool {
  1352. formats.insert(info.format);
  1353. return false;
  1354. };
  1355. CapsMatch(device, ResolutionMatcher(cx, cy), FrameRateMatcher(interval),
  1356. format_gatherer);
  1357. obs_property_t *list = obs_properties_get(props, VIDEO_FORMAT);
  1358. obs_property_list_clear(list);
  1359. bool format_added = false;
  1360. for (const VideoFormatName &format : videoFormatNames) {
  1361. bool available = formats.find(format.format) != end(formats);
  1362. if (!available && format.format != format_)
  1363. continue;
  1364. if (format.format == format_)
  1365. format_added = true;
  1366. size_t idx = obs_property_list_add_int(
  1367. list, obs_module_text(format.name),
  1368. (long long)format.format);
  1369. obs_property_list_item_disable(list, idx, !available);
  1370. }
  1371. if (format_added)
  1372. return;
  1373. size_t idx = obs_property_list_add_int(
  1374. list, GetVideoFormatName(format_), (long long)format_);
  1375. obs_property_list_item_disable(list, idx, true);
  1376. }
  1377. static bool UpdateFPS(long long interval, obs_property_t *list)
  1378. {
  1379. size_t size = obs_property_list_item_count(list);
  1380. DStr name;
  1381. for (size_t i = 0; i < size; i++) {
  1382. if (obs_property_list_item_int(list, i) != interval)
  1383. continue;
  1384. obs_property_list_item_disable(list, i, true);
  1385. if (size == 1)
  1386. return false;
  1387. dstr_cat(name, obs_property_list_item_name(list, i));
  1388. break;
  1389. }
  1390. obs_property_list_clear(list);
  1391. if (!name->len)
  1392. name = GetFPSName(interval);
  1393. obs_property_list_add_int(list, name, interval);
  1394. obs_property_list_item_disable(list, 0, true);
  1395. return true;
  1396. }
  1397. static bool DeviceIntervalChanged(obs_properties_t *props, obs_property_t *p,
  1398. obs_data_t *settings)
  1399. {
  1400. long long val = obs_data_get_int(settings, FRAME_INTERVAL);
  1401. PropertiesData *data =
  1402. (PropertiesData *)obs_properties_get_param(props);
  1403. const char *id = obs_data_get_string(settings, VIDEO_DEVICE_ID);
  1404. VideoDevice device;
  1405. if (!data->GetDevice(device, id))
  1406. return UpdateFPS(val, p);
  1407. int cx = 0, cy = 0;
  1408. if (!DetermineResolution(cx, cy, settings, device)) {
  1409. UpdateVideoFormats(device, VideoFormat::Any, 0, 0, 0, props);
  1410. UpdateFPS(device, VideoFormat::Any, 0, 0, 0, props);
  1411. return true;
  1412. }
  1413. int resType = (int)obs_data_get_int(settings, RES_TYPE);
  1414. if (resType != ResType_Custom)
  1415. return true;
  1416. if (val == FPS_MATCHING)
  1417. val = GetOBSFPS();
  1418. VideoFormat format =
  1419. (VideoFormat)obs_data_get_int(settings, VIDEO_FORMAT);
  1420. bool video_format_matches = false;
  1421. long long best_interval = numeric_limits<long long>::max();
  1422. bool frameRateSupported =
  1423. CapsMatch(device, ResolutionMatcher(cx, cy),
  1424. VideoFormatMatcher(format, video_format_matches),
  1425. ClosestFrameRateSelector(val, best_interval),
  1426. FrameRateMatcher(val));
  1427. if (video_format_matches && !frameRateSupported &&
  1428. best_interval != val) {
  1429. long long listed_val = 0;
  1430. for (const FPSFormat &format : validFPSFormats) {
  1431. long long diff = llabs(format.interval - best_interval);
  1432. if (diff < DEVICE_INTERVAL_DIFF_LIMIT) {
  1433. listed_val = format.interval;
  1434. break;
  1435. }
  1436. }
  1437. if (listed_val != val) {
  1438. obs_data_set_autoselect_int(settings, FRAME_INTERVAL,
  1439. listed_val);
  1440. val = listed_val;
  1441. }
  1442. } else {
  1443. obs_data_unset_autoselect_value(settings, FRAME_INTERVAL);
  1444. }
  1445. UpdateVideoFormats(device, format, cx, cy, val, props);
  1446. UpdateFPS(device, format, val, cx, cy, props);
  1447. UNUSED_PARAMETER(p);
  1448. return true;
  1449. }
  1450. static bool UpdateVideoFormats(VideoFormat format, obs_property_t *list)
  1451. {
  1452. size_t size = obs_property_list_item_count(list);
  1453. DStr name;
  1454. for (size_t i = 0; i < size; i++) {
  1455. if ((VideoFormat)obs_property_list_item_int(list, i) != format)
  1456. continue;
  1457. if (size == 1)
  1458. return false;
  1459. dstr_cat(name, obs_property_list_item_name(list, i));
  1460. break;
  1461. }
  1462. obs_property_list_clear(list);
  1463. if (!name->len)
  1464. name = GetVideoFormatName(format);
  1465. obs_property_list_add_int(list, name, (long long)format);
  1466. obs_property_list_item_disable(list, 0, true);
  1467. return true;
  1468. }
  1469. static bool VideoFormatChanged(obs_properties_t *props, obs_property_t *p,
  1470. obs_data_t *settings)
  1471. {
  1472. PropertiesData *data =
  1473. (PropertiesData *)obs_properties_get_param(props);
  1474. const char *id = obs_data_get_string(settings, VIDEO_DEVICE_ID);
  1475. VideoDevice device;
  1476. VideoFormat curFormat =
  1477. (VideoFormat)obs_data_get_int(settings, VIDEO_FORMAT);
  1478. if (!data->GetDevice(device, id))
  1479. return UpdateVideoFormats(curFormat, p);
  1480. int cx, cy;
  1481. if (!DetermineResolution(cx, cy, settings, device)) {
  1482. UpdateVideoFormats(device, VideoFormat::Any, cx, cy, 0, props);
  1483. UpdateFPS(device, VideoFormat::Any, 0, 0, 0, props);
  1484. return true;
  1485. }
  1486. long long interval = obs_data_get_int(settings, FRAME_INTERVAL);
  1487. UpdateVideoFormats(device, curFormat, cx, cy, interval, props);
  1488. UpdateFPS(device, curFormat, interval, cx, cy, props);
  1489. return true;
  1490. }
  1491. static bool CustomAudioClicked(obs_properties_t *props, obs_property_t *p,
  1492. obs_data_t *settings)
  1493. {
  1494. bool useCustomAudio = obs_data_get_bool(settings, USE_CUSTOM_AUDIO);
  1495. p = obs_properties_get(props, AUDIO_DEVICE_ID);
  1496. obs_property_set_visible(p, useCustomAudio);
  1497. return true;
  1498. }
  1499. static bool ActivateClicked(obs_properties_t *, obs_property_t *p, void *data)
  1500. {
  1501. DShowInput *input = reinterpret_cast<DShowInput *>(data);
  1502. if (input->active) {
  1503. input->SetActive(false);
  1504. obs_property_set_description(p, TEXT_ACTIVATE);
  1505. } else {
  1506. input->SetActive(true);
  1507. obs_property_set_description(p, TEXT_DEACTIVATE);
  1508. }
  1509. return true;
  1510. }
  1511. static obs_properties_t *GetDShowProperties(void *obj)
  1512. {
  1513. DShowInput *input = reinterpret_cast<DShowInput *>(obj);
  1514. obs_properties_t *ppts = obs_properties_create();
  1515. PropertiesData *data = new PropertiesData;
  1516. data->input = input;
  1517. obs_properties_set_param(ppts, data, PropertiesDataDestroy);
  1518. obs_property_t *p = obs_properties_add_list(ppts, VIDEO_DEVICE_ID,
  1519. TEXT_DEVICE,
  1520. OBS_COMBO_TYPE_LIST,
  1521. OBS_COMBO_FORMAT_STRING);
  1522. obs_property_set_modified_callback(p, DeviceSelectionChanged);
  1523. Device::EnumVideoDevices(data->devices);
  1524. for (const VideoDevice &device : data->devices)
  1525. AddDevice(p, device);
  1526. const char *activateText = TEXT_ACTIVATE;
  1527. if (input) {
  1528. if (input->active)
  1529. activateText = TEXT_DEACTIVATE;
  1530. }
  1531. obs_properties_add_button(ppts, "activate", activateText,
  1532. ActivateClicked);
  1533. obs_properties_add_button(ppts, "video_config", TEXT_CONFIG_VIDEO,
  1534. VideoConfigClicked);
  1535. obs_properties_add_button(ppts, "xbar_config", TEXT_CONFIG_XBAR,
  1536. CrossbarConfigClicked);
  1537. obs_properties_add_bool(ppts, DEACTIVATE_WNS, TEXT_DWNS);
  1538. /* ------------------------------------- */
  1539. /* video settings */
  1540. p = obs_properties_add_list(ppts, RES_TYPE, TEXT_RES_FPS_TYPE,
  1541. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
  1542. obs_property_set_modified_callback(p, ResTypeChanged);
  1543. obs_property_list_add_int(p, TEXT_PREFERRED_RES, ResType_Preferred);
  1544. obs_property_list_add_int(p, TEXT_CUSTOM_RES, ResType_Custom);
  1545. p = obs_properties_add_list(ppts, RESOLUTION, TEXT_RESOLUTION,
  1546. OBS_COMBO_TYPE_EDITABLE,
  1547. OBS_COMBO_FORMAT_STRING);
  1548. obs_property_set_modified_callback(p, DeviceResolutionChanged);
  1549. p = obs_properties_add_list(ppts, FRAME_INTERVAL, "FPS",
  1550. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
  1551. obs_property_set_modified_callback(p, DeviceIntervalChanged);
  1552. p = obs_properties_add_list(ppts, VIDEO_FORMAT, TEXT_VIDEO_FORMAT,
  1553. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
  1554. obs_property_set_modified_callback(p, VideoFormatChanged);
  1555. p = obs_properties_add_list(ppts, COLOR_SPACE, TEXT_COLOR_SPACE,
  1556. OBS_COMBO_TYPE_LIST,
  1557. OBS_COMBO_FORMAT_STRING);
  1558. obs_property_list_add_string(p, TEXT_COLOR_DEFAULT, "default");
  1559. obs_property_list_add_string(p, "709", "709");
  1560. obs_property_list_add_string(p, "601", "601");
  1561. p = obs_properties_add_list(ppts, COLOR_RANGE, TEXT_COLOR_RANGE,
  1562. OBS_COMBO_TYPE_LIST,
  1563. OBS_COMBO_FORMAT_STRING);
  1564. obs_property_list_add_string(p, TEXT_RANGE_DEFAULT, "default");
  1565. obs_property_list_add_string(p, TEXT_RANGE_PARTIAL, "partial");
  1566. obs_property_list_add_string(p, TEXT_RANGE_FULL, "full");
  1567. p = obs_properties_add_list(ppts, BUFFERING_VAL, TEXT_BUFFERING,
  1568. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
  1569. obs_property_list_add_int(p, TEXT_BUFFERING_AUTO,
  1570. (int64_t)BufferingType::Auto);
  1571. obs_property_list_add_int(p, TEXT_BUFFERING_ON,
  1572. (int64_t)BufferingType::On);
  1573. obs_property_list_add_int(p, TEXT_BUFFERING_OFF,
  1574. (int64_t)BufferingType::Off);
  1575. obs_property_set_long_description(p,
  1576. obs_module_text("Buffering.ToolTip"));
  1577. obs_properties_add_bool(ppts, FLIP_IMAGE, TEXT_FLIP_IMAGE);
  1578. obs_properties_add_bool(ppts, AUTOROTATION, TEXT_AUTOROTATION);
  1579. /* ------------------------------------- */
  1580. /* audio settings */
  1581. Device::EnumAudioDevices(data->audioDevices);
  1582. p = obs_properties_add_list(ppts, AUDIO_OUTPUT_MODE, TEXT_AUDIO_MODE,
  1583. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
  1584. obs_property_list_add_int(p, TEXT_MODE_CAPTURE,
  1585. (int64_t)AudioMode::Capture);
  1586. obs_property_list_add_int(p, TEXT_MODE_DSOUND,
  1587. (int64_t)AudioMode::DirectSound);
  1588. obs_property_list_add_int(p, TEXT_MODE_WAVEOUT,
  1589. (int64_t)AudioMode::WaveOut);
  1590. if (!data->audioDevices.size())
  1591. return ppts;
  1592. p = obs_properties_add_bool(ppts, USE_CUSTOM_AUDIO, TEXT_CUSTOM_AUDIO);
  1593. obs_property_set_modified_callback(p, CustomAudioClicked);
  1594. p = obs_properties_add_list(ppts, AUDIO_DEVICE_ID, TEXT_AUDIO_DEVICE,
  1595. OBS_COMBO_TYPE_LIST,
  1596. OBS_COMBO_FORMAT_STRING);
  1597. for (const AudioDevice &device : data->audioDevices)
  1598. AddAudioDevice(p, device);
  1599. return ppts;
  1600. }
  1601. void DShowModuleLogCallback(LogType type, const wchar_t *msg, void *param)
  1602. {
  1603. int obs_type = LOG_DEBUG;
  1604. switch (type) {
  1605. case LogType::Error:
  1606. obs_type = LOG_ERROR;
  1607. break;
  1608. case LogType::Warning:
  1609. obs_type = LOG_WARNING;
  1610. break;
  1611. case LogType::Info:
  1612. obs_type = LOG_INFO;
  1613. break;
  1614. case LogType::Debug:
  1615. obs_type = LOG_DEBUG;
  1616. break;
  1617. }
  1618. DStr dmsg;
  1619. dstr_from_wcs(dmsg, msg);
  1620. blog(obs_type, "DShow: %s", dmsg->array);
  1621. UNUSED_PARAMETER(param);
  1622. }
  1623. static void HideDShowInput(void *data)
  1624. {
  1625. DShowInput *input = reinterpret_cast<DShowInput *>(data);
  1626. if (input->deactivateWhenNotShowing && input->active)
  1627. input->QueueAction(Action::Deactivate);
  1628. }
  1629. static void ShowDShowInput(void *data)
  1630. {
  1631. DShowInput *input = reinterpret_cast<DShowInput *>(data);
  1632. if (input->deactivateWhenNotShowing && input->active)
  1633. input->QueueAction(Action::Activate);
  1634. }
  1635. void RegisterDShowSource()
  1636. {
  1637. SetLogCallback(DShowModuleLogCallback, nullptr);
  1638. obs_source_info info = {};
  1639. info.id = "dshow_input";
  1640. info.type = OBS_SOURCE_TYPE_INPUT;
  1641. info.output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_AUDIO |
  1642. OBS_SOURCE_ASYNC | OBS_SOURCE_DO_NOT_DUPLICATE;
  1643. info.show = ShowDShowInput;
  1644. info.hide = HideDShowInput;
  1645. info.get_name = GetDShowInputName;
  1646. info.create = CreateDShowInput;
  1647. info.destroy = DestroyDShowInput;
  1648. info.update = UpdateDShowInput;
  1649. info.get_defaults = GetDShowDefaults;
  1650. info.get_properties = GetDShowProperties;
  1651. info.icon_type = OBS_ICON_TYPE_CAMERA;
  1652. obs_register_source(&info);
  1653. }