win-dshow.cpp 55 KB

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