win-dshow.cpp 53 KB

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