win-dshow.cpp 55 KB

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