window-basic-main.cpp 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808
  1. /******************************************************************************
  2. Copyright (C) 2013-2014 by Hugh Bailey <[email protected]>
  3. Zachary Lund <[email protected]>
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. ******************************************************************************/
  15. #include <obs.hpp>
  16. #include <QMessageBox>
  17. #include <QShowEvent>
  18. #include <QFileDialog>
  19. #include <QNetworkRequest>
  20. #include <QNetworkReply>
  21. #include <util/dstr.h>
  22. #include <util/util.hpp>
  23. #include <util/platform.h>
  24. #include <graphics/math-defs.h>
  25. #include "obs-app.hpp"
  26. #include "platform.hpp"
  27. #include "window-basic-settings.hpp"
  28. #include "window-namedialog.hpp"
  29. #include "window-basic-source-select.hpp"
  30. #include "window-basic-main.hpp"
  31. #include "window-basic-properties.hpp"
  32. #include "window-log-reply.hpp"
  33. #include "qt-wrappers.hpp"
  34. #include "display-helpers.hpp"
  35. #include "volume-control.hpp"
  36. #include "ui_OBSBasic.h"
  37. #include <fstream>
  38. #include <sstream>
  39. #include <QScreen>
  40. #include <QWindow>
  41. using namespace std;
  42. Q_DECLARE_METATYPE(OBSScene);
  43. Q_DECLARE_METATYPE(OBSSceneItem);
  44. Q_DECLARE_METATYPE(order_movement);
  45. OBSBasic::OBSBasic(QWidget *parent)
  46. : OBSMainWindow (parent),
  47. ui (new Ui::OBSBasic)
  48. {
  49. ui->setupUi(this);
  50. connect(windowHandle(), &QWindow::screenChanged, [this]() {
  51. struct obs_video_info ovi;
  52. if (obs_get_video_info(&ovi))
  53. ResizePreview(ovi.base_width, ovi.base_height);
  54. });
  55. stringstream name;
  56. name << "OBS " << App()->GetVersionString();
  57. blog(LOG_INFO, "%s", name.str().c_str());
  58. setWindowTitle(QT_UTF8(name.str().c_str()));
  59. }
  60. static void SaveAudioDevice(const char *name, int channel, obs_data_t parent)
  61. {
  62. obs_source_t source = obs_get_output_source(channel);
  63. if (!source)
  64. return;
  65. obs_data_t data = obs_save_source(source);
  66. obs_data_setobj(parent, name, data);
  67. obs_data_release(data);
  68. obs_source_release(source);
  69. }
  70. static obs_data_t GenerateSaveData()
  71. {
  72. obs_data_t saveData = obs_data_create();
  73. obs_data_array_t sourcesArray = obs_save_sources();
  74. obs_source_t currentScene = obs_get_output_source(0);
  75. const char *sceneName = obs_source_getname(currentScene);
  76. SaveAudioDevice(DESKTOP_AUDIO_1, 1, saveData);
  77. SaveAudioDevice(DESKTOP_AUDIO_2, 2, saveData);
  78. SaveAudioDevice(AUX_AUDIO_1, 3, saveData);
  79. SaveAudioDevice(AUX_AUDIO_2, 4, saveData);
  80. SaveAudioDevice(AUX_AUDIO_3, 5, saveData);
  81. obs_data_setstring(saveData, "current_scene", sceneName);
  82. obs_data_setarray(saveData, "sources", sourcesArray);
  83. obs_data_array_release(sourcesArray);
  84. obs_source_release(currentScene);
  85. return saveData;
  86. }
  87. void OBSBasic::ClearVolumeControls()
  88. {
  89. VolControl *control;
  90. for (size_t i = 0; i < volumes.size(); i++) {
  91. control = volumes[i];
  92. delete control;
  93. }
  94. volumes.clear();
  95. }
  96. void OBSBasic::Save(const char *file)
  97. {
  98. obs_data_t saveData = GenerateSaveData();
  99. const char *jsonData = obs_data_getjson(saveData);
  100. /* TODO maybe a message box here? */
  101. if (!os_quick_write_utf8_file(file, jsonData, strlen(jsonData), false))
  102. blog(LOG_ERROR, "Could not save scene data to %s", file);
  103. obs_data_release(saveData);
  104. }
  105. static void LoadAudioDevice(const char *name, int channel, obs_data_t parent)
  106. {
  107. obs_data_t data = obs_data_getobj(parent, name);
  108. if (!data)
  109. return;
  110. obs_source_t source = obs_load_source(data);
  111. if (source) {
  112. obs_set_output_source(channel, source);
  113. obs_source_release(source);
  114. }
  115. obs_data_release(data);
  116. }
  117. void OBSBasic::CreateDefaultScene()
  118. {
  119. obs_scene_t scene = obs_scene_create(Str("Basic.Scene"));
  120. obs_source_t source = obs_scene_getsource(scene);
  121. obs_add_source(source);
  122. #ifdef __APPLE__
  123. source = obs_source_create(OBS_SOURCE_TYPE_INPUT, "display_capture",
  124. Str("Basic.DisplayCapture"), NULL);
  125. if (source) {
  126. obs_scene_add(scene, source);
  127. obs_add_source(source);
  128. obs_source_release(source);
  129. }
  130. #endif
  131. obs_set_output_source(0, obs_scene_getsource(scene));
  132. obs_scene_release(scene);
  133. }
  134. void OBSBasic::Load(const char *file)
  135. {
  136. if (!file) {
  137. blog(LOG_ERROR, "Could not find file %s", file);
  138. return;
  139. }
  140. BPtr<char> jsonData = os_quick_read_utf8_file(file);
  141. if (!jsonData) {
  142. CreateDefaultScene();
  143. return;
  144. }
  145. obs_data_t data = obs_data_create_from_json(jsonData);
  146. obs_data_array_t sources = obs_data_getarray(data, "sources");
  147. const char *sceneName = obs_data_getstring(data, "current_scene");
  148. obs_source_t curScene;
  149. LoadAudioDevice(DESKTOP_AUDIO_1, 1, data);
  150. LoadAudioDevice(DESKTOP_AUDIO_2, 2, data);
  151. LoadAudioDevice(AUX_AUDIO_1, 3, data);
  152. LoadAudioDevice(AUX_AUDIO_2, 4, data);
  153. LoadAudioDevice(AUX_AUDIO_3, 5, data);
  154. obs_load_sources(sources);
  155. curScene = obs_get_source_by_name(sceneName);
  156. obs_set_output_source(0, curScene);
  157. obs_source_release(curScene);
  158. obs_data_array_release(sources);
  159. obs_data_release(data);
  160. }
  161. static inline bool HasAudioDevices(const char *source_id)
  162. {
  163. const char *output_id = source_id;
  164. obs_properties_t props = obs_get_source_properties(
  165. OBS_SOURCE_TYPE_INPUT, output_id, App()->GetLocale());
  166. size_t count = 0;
  167. if (!props)
  168. return false;
  169. obs_property_t devices = obs_properties_get(props, "device_id");
  170. if (devices)
  171. count = obs_property_list_item_count(devices);
  172. obs_properties_destroy(props);
  173. return count != 0;
  174. }
  175. static void OBSStartStreaming(void *data, calldata_t params)
  176. {
  177. UNUSED_PARAMETER(params);
  178. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  179. "StreamingStart");
  180. }
  181. static void OBSStopStreaming(void *data, calldata_t params)
  182. {
  183. int code = (int)calldata_int(params, "code");
  184. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  185. "StreamingStop", Q_ARG(int, code));
  186. }
  187. static void OBSStopRecording(void *data, calldata_t params)
  188. {
  189. UNUSED_PARAMETER(params);
  190. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  191. "RecordingStop");
  192. }
  193. #define SERVICE_PATH "obs-studio/basic/service.json"
  194. void OBSBasic::SaveService()
  195. {
  196. if (!service)
  197. return;
  198. BPtr<char> serviceJsonPath(os_get_config_path(SERVICE_PATH));
  199. if (!serviceJsonPath)
  200. return;
  201. obs_data_t data = obs_data_create();
  202. obs_data_t settings = obs_service_get_settings(service);
  203. obs_data_setstring(data, "type", obs_service_gettype(service));
  204. obs_data_setobj(data, "settings", settings);
  205. const char *json = obs_data_getjson(data);
  206. os_quick_write_utf8_file(serviceJsonPath, json, strlen(json), false);
  207. obs_data_release(settings);
  208. obs_data_release(data);
  209. }
  210. bool OBSBasic::LoadService()
  211. {
  212. const char *type;
  213. BPtr<char> serviceJsonPath(os_get_config_path(SERVICE_PATH));
  214. if (!serviceJsonPath)
  215. return false;
  216. BPtr<char> jsonText = os_quick_read_utf8_file(serviceJsonPath);
  217. if (!jsonText)
  218. return false;
  219. obs_data_t data = obs_data_create_from_json(jsonText);
  220. obs_data_set_default_string(data, "type", "rtmp_common");
  221. type = obs_data_getstring(data, "type");
  222. obs_data_t settings = obs_data_getobj(data, "settings");
  223. service = obs_service_create(type, "default", settings);
  224. obs_data_release(settings);
  225. obs_data_release(data);
  226. return !!service;
  227. }
  228. bool OBSBasic::InitOutputs()
  229. {
  230. fileOutput = obs_output_create("flv_output", "default", nullptr);
  231. if (!fileOutput)
  232. return false;
  233. streamOutput = obs_output_create("rtmp_output", "default", nullptr);
  234. if (!streamOutput)
  235. return false;
  236. signal_handler_connect(obs_output_signalhandler(streamOutput),
  237. "start", OBSStartStreaming, this);
  238. signal_handler_connect(obs_output_signalhandler(streamOutput),
  239. "stop", OBSStopStreaming, this);
  240. signal_handler_connect(obs_output_signalhandler(fileOutput),
  241. "stop", OBSStopRecording, this);
  242. return true;
  243. }
  244. bool OBSBasic::InitEncoders()
  245. {
  246. x264 = obs_video_encoder_create("obs_x264", "h264", nullptr);
  247. if (!x264)
  248. return false;
  249. aac = obs_audio_encoder_create("libfdk_aac", "aac", nullptr);
  250. if(!aac)
  251. aac = obs_audio_encoder_create("ffmpeg_aac", "aac", nullptr);
  252. if (!aac)
  253. return false;
  254. return true;
  255. }
  256. bool OBSBasic::InitService()
  257. {
  258. if (LoadService())
  259. return true;
  260. service = obs_service_create("rtmp_common", nullptr, nullptr);
  261. if (!service)
  262. return false;
  263. return true;
  264. }
  265. bool OBSBasic::InitBasicConfigDefaults()
  266. {
  267. bool hasDesktopAudio = HasAudioDevices(App()->OutputAudioSource());
  268. bool hasInputAudio = HasAudioDevices(App()->InputAudioSource());
  269. config_set_default_int(basicConfig, "Window", "PosX", -1);
  270. config_set_default_int(basicConfig, "Window", "PosY", -1);
  271. config_set_default_int(basicConfig, "Window", "SizeX", -1);
  272. config_set_default_int(basicConfig, "Window", "SizeY", -1);
  273. vector<MonitorInfo> monitors;
  274. GetMonitors(monitors);
  275. if (!monitors.size()) {
  276. OBSErrorBox(NULL, "There appears to be no monitors. Er, this "
  277. "technically shouldn't be possible.");
  278. return false;
  279. }
  280. uint32_t cx = monitors[0].cx;
  281. uint32_t cy = monitors[0].cy;
  282. /* TODO: temporary */
  283. config_set_default_string(basicConfig, "SimpleOutput", "FilePath",
  284. GetDefaultVideoSavePath().c_str());
  285. config_set_default_uint (basicConfig, "SimpleOutput", "VBitrate",
  286. 2500);
  287. config_set_default_uint (basicConfig, "SimpleOutput", "ABitrate", 128);
  288. config_set_default_uint (basicConfig, "Video", "BaseCX", cx);
  289. config_set_default_uint (basicConfig, "Video", "BaseCY", cy);
  290. cx = cx * 10 / 15;
  291. cy = cy * 10 / 15;
  292. config_set_default_uint (basicConfig, "Video", "OutputCX", cx);
  293. config_set_default_uint (basicConfig, "Video", "OutputCY", cy);
  294. config_set_default_uint (basicConfig, "Video", "FPSType", 0);
  295. config_set_default_string(basicConfig, "Video", "FPSCommon", "30");
  296. config_set_default_uint (basicConfig, "Video", "FPSInt", 30);
  297. config_set_default_uint (basicConfig, "Video", "FPSNum", 30);
  298. config_set_default_uint (basicConfig, "Video", "FPSDen", 1);
  299. config_set_default_uint (basicConfig, "Audio", "SampleRate", 44100);
  300. config_set_default_string(basicConfig, "Audio", "ChannelSetup",
  301. "Stereo");
  302. config_set_default_uint (basicConfig, "Audio", "BufferingTime", 1000);
  303. config_set_default_string(basicConfig, "Audio", "DesktopDevice1",
  304. hasDesktopAudio ? "default" : "disabled");
  305. config_set_default_string(basicConfig, "Audio", "DesktopDevice2",
  306. "disabled");
  307. config_set_default_string(basicConfig, "Audio", "AuxDevice1",
  308. hasInputAudio ? "default" : "disabled");
  309. config_set_default_string(basicConfig, "Audio", "AuxDevice2",
  310. "disabled");
  311. config_set_default_string(basicConfig, "Audio", "AuxDevice3",
  312. "disabled");
  313. return true;
  314. }
  315. bool OBSBasic::InitBasicConfig()
  316. {
  317. BPtr<char> configPath(os_get_config_path("obs-studio/basic/basic.ini"));
  318. int code = basicConfig.Open(configPath, CONFIG_OPEN_ALWAYS);
  319. if (code != CONFIG_SUCCESS) {
  320. OBSErrorBox(NULL, "Failed to open basic.ini: %d", code);
  321. return false;
  322. }
  323. return InitBasicConfigDefaults();
  324. }
  325. void OBSBasic::InitOBSCallbacks()
  326. {
  327. signal_handler_connect(obs_signalhandler(), "source_add",
  328. OBSBasic::SourceAdded, this);
  329. signal_handler_connect(obs_signalhandler(), "source_remove",
  330. OBSBasic::SourceRemoved, this);
  331. signal_handler_connect(obs_signalhandler(), "channel_change",
  332. OBSBasic::ChannelChanged, this);
  333. signal_handler_connect(obs_signalhandler(), "source_activate",
  334. OBSBasic::SourceActivated, this);
  335. signal_handler_connect(obs_signalhandler(), "source_deactivate",
  336. OBSBasic::SourceDeactivated, this);
  337. }
  338. void OBSBasic::InitPrimitives()
  339. {
  340. gs_entercontext(obs_graphics());
  341. gs_renderstart(true);
  342. gs_vertex2f(0.0f, 0.0f);
  343. gs_vertex2f(0.0f, 1.0f);
  344. gs_vertex2f(1.0f, 1.0f);
  345. gs_vertex2f(1.0f, 0.0f);
  346. gs_vertex2f(0.0f, 0.0f);
  347. box = gs_rendersave();
  348. gs_renderstart(true);
  349. for (int i = 0; i <= 360; i += (360/20)) {
  350. float pos = RAD(float(i));
  351. gs_vertex2f(cosf(pos), sinf(pos));
  352. }
  353. circle = gs_rendersave();
  354. gs_leavecontext();
  355. }
  356. void OBSBasic::OBSInit()
  357. {
  358. BPtr<char> savePath(os_get_config_path("obs-studio/basic/scenes.json"));
  359. /* make sure it's fully displayed before doing any initialization */
  360. show();
  361. App()->processEvents();
  362. if (!obs_startup())
  363. throw "Failed to initialize libobs";
  364. if (!InitBasicConfig())
  365. throw "Failed to load basic.ini";
  366. if (!ResetVideo())
  367. throw "Failed to initialize video";
  368. if (!ResetAudio())
  369. throw "Failed to initialize audio";
  370. InitOBSCallbacks();
  371. /* TODO: this is a test, all modules will be searched for and loaded
  372. * automatically later */
  373. obs_load_module("test-input");
  374. obs_load_module("obs-ffmpeg");
  375. obs_load_module("obs-libfdk");
  376. obs_load_module("obs-x264");
  377. obs_load_module("obs-outputs");
  378. obs_load_module("rtmp-services");
  379. #ifdef __APPLE__
  380. obs_load_module("mac-avcapture");
  381. obs_load_module("mac-capture");
  382. #elif _WIN32
  383. obs_load_module("win-wasapi");
  384. obs_load_module("win-capture");
  385. obs_load_module("win-dshow");
  386. #else
  387. obs_load_module("linux-xshm");
  388. obs_load_module("linux-xcomposite");
  389. obs_load_module("linux-pulseaudio");
  390. #endif
  391. if (!InitOutputs())
  392. throw "Failed to initialize outputs";
  393. if (!InitEncoders())
  394. throw "Failed to initialize encoders";
  395. if (!InitService())
  396. throw "Failed to initialize service";
  397. InitPrimitives();
  398. Load(savePath);
  399. ResetAudioDevices();
  400. }
  401. OBSBasic::~OBSBasic()
  402. {
  403. BPtr<char> savePath(os_get_config_path("obs-studio/basic/scenes.json"));
  404. SaveService();
  405. Save(savePath);
  406. /* XXX: any obs data must be released before calling obs_shutdown.
  407. * currently, we can't automate this with C++ RAII because of the
  408. * delicate nature of obs_shutdown needing to be freed before the UI
  409. * can be freed, and we have no control over the destruction order of
  410. * the Qt UI stuff, so we have to manually clear any references to
  411. * libobs. */
  412. if (properties)
  413. delete properties;
  414. if (transformWindow)
  415. delete transformWindow;
  416. ClearVolumeControls();
  417. ui->sources->clear();
  418. ui->scenes->clear();
  419. gs_entercontext(obs_graphics());
  420. vertexbuffer_destroy(box);
  421. vertexbuffer_destroy(circle);
  422. gs_leavecontext();
  423. obs_shutdown();
  424. }
  425. OBSScene OBSBasic::GetCurrentScene()
  426. {
  427. QListWidgetItem *item = ui->scenes->currentItem();
  428. return item ? item->data(Qt::UserRole).value<OBSScene>() : nullptr;
  429. }
  430. OBSSceneItem OBSBasic::GetCurrentSceneItem()
  431. {
  432. QListWidgetItem *item = ui->sources->currentItem();
  433. return item ? item->data(Qt::UserRole).value<OBSSceneItem>() : nullptr;
  434. }
  435. void OBSBasic::UpdateSources(OBSScene scene)
  436. {
  437. ui->sources->clear();
  438. obs_scene_enum_items(scene,
  439. [] (obs_scene_t scene, obs_sceneitem_t item, void *p)
  440. {
  441. OBSBasic *window = static_cast<OBSBasic*>(p);
  442. window->InsertSceneItem(item);
  443. UNUSED_PARAMETER(scene);
  444. return true;
  445. }, this);
  446. }
  447. void OBSBasic::InsertSceneItem(obs_sceneitem_t item)
  448. {
  449. obs_source_t source = obs_sceneitem_getsource(item);
  450. const char *name = obs_source_getname(source);
  451. QListWidgetItem *listItem = new QListWidgetItem(QT_UTF8(name));
  452. listItem->setData(Qt::UserRole,
  453. QVariant::fromValue(OBSSceneItem(item)));
  454. ui->sources->insertItem(0, listItem);
  455. }
  456. /* Qt callbacks for invokeMethod */
  457. void OBSBasic::AddScene(OBSSource source)
  458. {
  459. const char *name = obs_source_getname(source);
  460. obs_scene_t scene = obs_scene_fromsource(source);
  461. QListWidgetItem *item = new QListWidgetItem(QT_UTF8(name));
  462. item->setData(Qt::UserRole, QVariant::fromValue(OBSScene(scene)));
  463. ui->scenes->addItem(item);
  464. signal_handler_t handler = obs_source_signalhandler(source);
  465. signal_handler_connect(handler, "item_add",
  466. OBSBasic::SceneItemAdded, this);
  467. signal_handler_connect(handler, "item_remove",
  468. OBSBasic::SceneItemRemoved, this);
  469. signal_handler_connect(handler, "item_move_up",
  470. OBSBasic::SceneItemMoveUp, this);
  471. signal_handler_connect(handler, "item_move_down",
  472. OBSBasic::SceneItemMoveDown, this);
  473. signal_handler_connect(handler, "item_move_top",
  474. OBSBasic::SceneItemMoveTop, this);
  475. signal_handler_connect(handler, "item_move_bottom",
  476. OBSBasic::SceneItemMoveBottom, this);
  477. }
  478. void OBSBasic::RemoveScene(OBSSource source)
  479. {
  480. const char *name = obs_source_getname(source);
  481. QListWidgetItem *sel = ui->scenes->currentItem();
  482. QList<QListWidgetItem*> items = ui->scenes->findItems(QT_UTF8(name),
  483. Qt::MatchExactly);
  484. if (sel != nullptr) {
  485. if (items.contains(sel))
  486. ui->sources->clear();
  487. delete sel;
  488. }
  489. }
  490. void OBSBasic::AddSceneItem(OBSSceneItem item)
  491. {
  492. obs_scene_t scene = obs_sceneitem_getscene(item);
  493. obs_source_t source = obs_sceneitem_getsource(item);
  494. if (GetCurrentScene() == scene)
  495. InsertSceneItem(item);
  496. sourceSceneRefs[source] = sourceSceneRefs[source] + 1;
  497. }
  498. void OBSBasic::RemoveSceneItem(OBSSceneItem item)
  499. {
  500. obs_scene_t scene = obs_sceneitem_getscene(item);
  501. if (GetCurrentScene() == scene) {
  502. for (int i = 0; i < ui->sources->count(); i++) {
  503. QListWidgetItem *listItem = ui->sources->item(i);
  504. QVariant userData = listItem->data(Qt::UserRole);
  505. if (userData.value<OBSSceneItem>() == item) {
  506. delete listItem;
  507. break;
  508. }
  509. }
  510. }
  511. obs_source_t source = obs_sceneitem_getsource(item);
  512. int scenes = sourceSceneRefs[source] - 1;
  513. sourceSceneRefs[source] = scenes;
  514. if (scenes == 0) {
  515. obs_source_remove(source);
  516. sourceSceneRefs.erase(source);
  517. }
  518. }
  519. void OBSBasic::UpdateSceneSelection(OBSSource source)
  520. {
  521. if (source) {
  522. obs_source_type type;
  523. obs_source_gettype(source, &type, NULL);
  524. obs_scene_t scene = obs_scene_fromsource(source);
  525. const char *name = obs_source_getname(source);
  526. if (!scene)
  527. return;
  528. QList<QListWidgetItem*> items =
  529. ui->scenes->findItems(QT_UTF8(name), Qt::MatchExactly);
  530. if (items.count()) {
  531. sceneChanging = true;
  532. ui->scenes->setCurrentItem(items.first());
  533. sceneChanging = false;
  534. UpdateSources(scene);
  535. }
  536. }
  537. }
  538. void OBSBasic::MoveSceneItem(OBSSceneItem item, order_movement movement)
  539. {
  540. OBSScene scene = obs_sceneitem_getscene(item);
  541. if (scene != GetCurrentScene())
  542. return;
  543. int curRow = ui->sources->currentRow();
  544. if (curRow == -1)
  545. return;
  546. QListWidgetItem *listItem = ui->sources->takeItem(curRow);
  547. switch (movement) {
  548. case ORDER_MOVE_UP:
  549. if (curRow > 0)
  550. curRow--;
  551. break;
  552. case ORDER_MOVE_DOWN:
  553. if (curRow < ui->sources->count())
  554. curRow++;
  555. break;
  556. case ORDER_MOVE_TOP:
  557. curRow = 0;
  558. break;
  559. case ORDER_MOVE_BOTTOM:
  560. curRow = ui->sources->count();
  561. break;
  562. }
  563. ui->sources->insertItem(curRow, listItem);
  564. ui->sources->setCurrentRow(curRow);
  565. }
  566. void OBSBasic::ActivateAudioSource(OBSSource source)
  567. {
  568. VolControl *vol = new VolControl(source);
  569. volumes.push_back(vol);
  570. ui->volumeWidgets->layout()->addWidget(vol);
  571. }
  572. void OBSBasic::DeactivateAudioSource(OBSSource source)
  573. {
  574. for (size_t i = 0; i < volumes.size(); i++) {
  575. if (volumes[i]->GetSource() == source) {
  576. delete volumes[i];
  577. volumes.erase(volumes.begin() + i);
  578. break;
  579. }
  580. }
  581. }
  582. /* OBS Callbacks */
  583. void OBSBasic::SceneItemAdded(void *data, calldata_t params)
  584. {
  585. OBSBasic *window = static_cast<OBSBasic*>(data);
  586. obs_sceneitem_t item = (obs_sceneitem_t)calldata_ptr(params, "item");
  587. QMetaObject::invokeMethod(window, "AddSceneItem",
  588. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  589. }
  590. void OBSBasic::SceneItemRemoved(void *data, calldata_t params)
  591. {
  592. OBSBasic *window = static_cast<OBSBasic*>(data);
  593. obs_sceneitem_t item = (obs_sceneitem_t)calldata_ptr(params, "item");
  594. QMetaObject::invokeMethod(window, "RemoveSceneItem",
  595. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  596. }
  597. void OBSBasic::SourceAdded(void *data, calldata_t params)
  598. {
  599. OBSBasic *window = static_cast<OBSBasic*>(data);
  600. obs_source_t source = (obs_source_t)calldata_ptr(params, "source");
  601. if (obs_scene_fromsource(source) != NULL)
  602. QMetaObject::invokeMethod(window,
  603. "AddScene",
  604. Q_ARG(OBSSource, OBSSource(source)));
  605. else
  606. window->sourceSceneRefs[source] = 0;
  607. }
  608. void OBSBasic::SourceRemoved(void *data, calldata_t params)
  609. {
  610. obs_source_t source = (obs_source_t)calldata_ptr(params, "source");
  611. if (obs_scene_fromsource(source) != NULL)
  612. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  613. "RemoveScene",
  614. Q_ARG(OBSSource, OBSSource(source)));
  615. }
  616. void OBSBasic::SourceActivated(void *data, calldata_t params)
  617. {
  618. obs_source_t source = (obs_source_t)calldata_ptr(params, "source");
  619. uint32_t flags = obs_source_get_output_flags(source);
  620. if (flags & OBS_SOURCE_AUDIO)
  621. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  622. "ActivateAudioSource",
  623. Q_ARG(OBSSource, OBSSource(source)));
  624. }
  625. void OBSBasic::SourceDeactivated(void *data, calldata_t params)
  626. {
  627. obs_source_t source = (obs_source_t)calldata_ptr(params, "source");
  628. uint32_t flags = obs_source_get_output_flags(source);
  629. if (flags & OBS_SOURCE_AUDIO)
  630. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  631. "DeactivateAudioSource",
  632. Q_ARG(OBSSource, OBSSource(source)));
  633. }
  634. void OBSBasic::ChannelChanged(void *data, calldata_t params)
  635. {
  636. obs_source_t source = (obs_source_t)calldata_ptr(params, "source");
  637. uint32_t channel = (uint32_t)calldata_int(params, "channel");
  638. if (channel == 0)
  639. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  640. "UpdateSceneSelection",
  641. Q_ARG(OBSSource, OBSSource(source)));
  642. }
  643. void OBSBasic::RenderMain(void *data, uint32_t cx, uint32_t cy)
  644. {
  645. OBSBasic *window = static_cast<OBSBasic*>(data);
  646. obs_video_info ovi;
  647. obs_get_video_info(&ovi);
  648. window->previewCX = int(window->previewScale * float(ovi.base_width));
  649. window->previewCY = int(window->previewScale * float(ovi.base_height));
  650. gs_viewport_push();
  651. gs_projection_push();
  652. gs_ortho(0.0f, float(ovi.base_width), 0.0f, float(ovi.base_height),
  653. -100.0f, 100.0f);
  654. gs_setviewport(window->previewX, window->previewY,
  655. window->previewCX, window->previewCY);
  656. obs_render_main_view();
  657. gs_ortho(0.0f, float(window->previewCX), 0.0f, float(window->previewCY),
  658. -100.0f, 100.0f);
  659. window->ui->preview->DrawSceneEditing();
  660. gs_projection_pop();
  661. gs_viewport_pop();
  662. UNUSED_PARAMETER(cx);
  663. UNUSED_PARAMETER(cy);
  664. }
  665. void OBSBasic::SceneItemMoveUp(void *data, calldata_t params)
  666. {
  667. OBSSceneItem item = (obs_sceneitem_t)calldata_ptr(params, "item");
  668. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  669. "MoveSceneItem",
  670. Q_ARG(OBSSceneItem, OBSSceneItem(item)),
  671. Q_ARG(order_movement, ORDER_MOVE_UP));
  672. }
  673. void OBSBasic::SceneItemMoveDown(void *data, calldata_t params)
  674. {
  675. OBSSceneItem item = (obs_sceneitem_t)calldata_ptr(params, "item");
  676. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  677. "MoveSceneItem",
  678. Q_ARG(OBSSceneItem, OBSSceneItem(item)),
  679. Q_ARG(order_movement, ORDER_MOVE_DOWN));
  680. }
  681. void OBSBasic::SceneItemMoveTop(void *data, calldata_t params)
  682. {
  683. OBSSceneItem item = (obs_sceneitem_t)calldata_ptr(params, "item");
  684. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  685. "MoveSceneItem",
  686. Q_ARG(OBSSceneItem, OBSSceneItem(item)),
  687. Q_ARG(order_movement, ORDER_MOVE_TOP));
  688. }
  689. void OBSBasic::SceneItemMoveBottom(void *data, calldata_t params)
  690. {
  691. OBSSceneItem item = (obs_sceneitem_t)calldata_ptr(params, "item");
  692. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  693. "MoveSceneItem",
  694. Q_ARG(OBSSceneItem, OBSSceneItem(item)),
  695. Q_ARG(order_movement, ORDER_MOVE_BOTTOM));
  696. }
  697. /* Main class functions */
  698. obs_service_t OBSBasic::GetService()
  699. {
  700. if (!service)
  701. service = obs_service_create("rtmp_common", NULL, NULL);
  702. return service;
  703. }
  704. void OBSBasic::SetService(obs_service_t newService)
  705. {
  706. if (newService) {
  707. if (service)
  708. obs_service_destroy(service);
  709. service = newService;
  710. }
  711. }
  712. bool OBSBasic::ResetVideo()
  713. {
  714. struct obs_video_info ovi;
  715. GetConfigFPS(ovi.fps_num, ovi.fps_den);
  716. ovi.graphics_module = App()->GetRenderModule();
  717. ovi.base_width = (uint32_t)config_get_uint(basicConfig,
  718. "Video", "BaseCX");
  719. ovi.base_height = (uint32_t)config_get_uint(basicConfig,
  720. "Video", "BaseCY");
  721. ovi.output_width = (uint32_t)config_get_uint(basicConfig,
  722. "Video", "OutputCX");
  723. ovi.output_height = (uint32_t)config_get_uint(basicConfig,
  724. "Video", "OutputCY");
  725. ovi.output_format = VIDEO_FORMAT_NV12;
  726. ovi.adapter = 0;
  727. ovi.gpu_conversion = true;
  728. QTToGSWindow(ui->preview->winId(), ovi.window);
  729. //required to make opengl display stuff on osx(?)
  730. ResizePreview(ovi.base_width, ovi.base_height);
  731. QSize size = GetPixelSize(ui->preview);
  732. ovi.window_width = size.width();
  733. ovi.window_height = size.height();
  734. if (!obs_reset_video(&ovi))
  735. return false;
  736. obs_add_draw_callback(OBSBasic::RenderMain, this);
  737. return true;
  738. }
  739. bool OBSBasic::ResetAudio()
  740. {
  741. struct audio_output_info ai;
  742. ai.name = "Main Audio Track";
  743. ai.format = AUDIO_FORMAT_FLOAT;
  744. ai.samples_per_sec = config_get_uint(basicConfig, "Audio",
  745. "SampleRate");
  746. const char *channelSetupStr = config_get_string(basicConfig,
  747. "Audio", "ChannelSetup");
  748. if (strcmp(channelSetupStr, "Mono") == 0)
  749. ai.speakers = SPEAKERS_MONO;
  750. else
  751. ai.speakers = SPEAKERS_STEREO;
  752. ai.buffer_ms = config_get_uint(basicConfig, "Audio", "BufferingTime");
  753. return obs_reset_audio(&ai);
  754. }
  755. void OBSBasic::ResetAudioDevice(const char *sourceId, const char *deviceName,
  756. const char *deviceDesc, int channel)
  757. {
  758. const char *deviceId = config_get_string(basicConfig, "Audio",
  759. deviceName);
  760. obs_source_t source;
  761. obs_data_t settings;
  762. bool same = false;
  763. source = obs_get_output_source(channel);
  764. if (source) {
  765. settings = obs_source_getsettings(source);
  766. const char *curId = obs_data_getstring(settings, "device_id");
  767. same = (strcmp(curId, deviceId) == 0);
  768. obs_data_release(settings);
  769. obs_source_release(source);
  770. }
  771. if (!same)
  772. obs_set_output_source(channel, nullptr);
  773. if (!same && strcmp(deviceId, "disabled") != 0) {
  774. obs_data_t settings = obs_data_create();
  775. obs_data_setstring(settings, "device_id", deviceId);
  776. source = obs_source_create(OBS_SOURCE_TYPE_INPUT,
  777. sourceId, deviceDesc, settings);
  778. obs_data_release(settings);
  779. obs_set_output_source(channel, source);
  780. obs_source_release(source);
  781. }
  782. }
  783. void OBSBasic::ResetAudioDevices()
  784. {
  785. ResetAudioDevice(App()->OutputAudioSource(), "DesktopDevice1",
  786. Str("Basic.DesktopDevice1"), 1);
  787. ResetAudioDevice(App()->OutputAudioSource(), "DesktopDevice2",
  788. Str("Basic.DesktopDevice2"), 2);
  789. ResetAudioDevice(App()->InputAudioSource(), "AuxDevice1",
  790. Str("Basic.AuxDevice1"), 3);
  791. ResetAudioDevice(App()->InputAudioSource(), "AuxDevice2",
  792. Str("Basic.AuxDevice2"), 4);
  793. ResetAudioDevice(App()->InputAudioSource(), "AuxDevice3",
  794. Str("Basic.AuxDevice3"), 5);
  795. }
  796. void OBSBasic::ResizePreview(uint32_t cx, uint32_t cy)
  797. {
  798. QSize targetSize;
  799. /* resize preview panel to fix to the top section of the window */
  800. targetSize = GetPixelSize(ui->preview);
  801. GetScaleAndCenterPos(int(cx), int(cy),
  802. targetSize.width(), targetSize.height(),
  803. previewX, previewY, previewScale);
  804. if (isVisible()) {
  805. if (resizeTimer)
  806. killTimer(resizeTimer);
  807. resizeTimer = startTimer(100);
  808. }
  809. }
  810. void OBSBasic::closeEvent(QCloseEvent *event)
  811. {
  812. QWidget::closeEvent(event);
  813. if (!event->isAccepted())
  814. return;
  815. // remove draw callback in case our drawable surfaces go away before
  816. // the destructor gets called
  817. obs_remove_draw_callback(OBSBasic::RenderMain, this);
  818. }
  819. void OBSBasic::changeEvent(QEvent *event)
  820. {
  821. /* TODO */
  822. UNUSED_PARAMETER(event);
  823. }
  824. void OBSBasic::resizeEvent(QResizeEvent *event)
  825. {
  826. struct obs_video_info ovi;
  827. if (obs_get_video_info(&ovi))
  828. ResizePreview(ovi.base_width, ovi.base_height);
  829. UNUSED_PARAMETER(event);
  830. }
  831. void OBSBasic::timerEvent(QTimerEvent *event)
  832. {
  833. if (event->timerId() == resizeTimer) {
  834. killTimer(resizeTimer);
  835. resizeTimer = 0;
  836. QSize size = GetPixelSize(ui->preview);
  837. obs_resize(size.width(), size.height());
  838. }
  839. }
  840. void OBSBasic::on_action_New_triggered()
  841. {
  842. /* TODO */
  843. }
  844. void OBSBasic::on_action_Open_triggered()
  845. {
  846. /* TODO */
  847. }
  848. void OBSBasic::on_action_Save_triggered()
  849. {
  850. /* TODO */
  851. }
  852. void OBSBasic::on_action_Settings_triggered()
  853. {
  854. OBSBasicSettings settings(this);
  855. settings.exec();
  856. }
  857. void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current,
  858. QListWidgetItem *prev)
  859. {
  860. obs_source_t source = NULL;
  861. if (sceneChanging)
  862. return;
  863. if (current) {
  864. obs_scene_t scene;
  865. scene = current->data(Qt::UserRole).value<OBSScene>();
  866. source = obs_scene_getsource(scene);
  867. }
  868. /* TODO: allow transitions */
  869. obs_set_output_source(0, source);
  870. UNUSED_PARAMETER(prev);
  871. }
  872. void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos)
  873. {
  874. /* TODO */
  875. UNUSED_PARAMETER(pos);
  876. }
  877. void OBSBasic::on_actionAddScene_triggered()
  878. {
  879. string name;
  880. QString format{QTStr("Basic.Main.DefaultSceneName.Text")};
  881. int i = 1;
  882. QString placeHolderText = format.arg(i);
  883. obs_source_t source = nullptr;
  884. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  885. obs_source_release(source);
  886. placeHolderText = format.arg(++i);
  887. }
  888. bool accepted = NameDialog::AskForName(this,
  889. QTStr("Basic.Main.AddSceneDlg.Title"),
  890. QTStr("Basic.Main.AddSceneDlg.Text"),
  891. name,
  892. placeHolderText);
  893. if (accepted) {
  894. if (name.empty()) {
  895. QMessageBox::information(this,
  896. QTStr("NoNameEntered"),
  897. QTStr("NoNameEntered"));
  898. on_actionAddScene_triggered();
  899. return;
  900. }
  901. obs_source_t source = obs_get_source_by_name(name.c_str());
  902. if (source) {
  903. QMessageBox::information(this,
  904. QTStr("NameExists.Title"),
  905. QTStr("NameExists.Text"));
  906. obs_source_release(source);
  907. on_actionAddScene_triggered();
  908. return;
  909. }
  910. obs_scene_t scene = obs_scene_create(name.c_str());
  911. source = obs_scene_getsource(scene);
  912. obs_add_source(source);
  913. obs_scene_release(scene);
  914. obs_set_output_source(0, source);
  915. }
  916. }
  917. void OBSBasic::on_actionRemoveScene_triggered()
  918. {
  919. QListWidgetItem *item = ui->scenes->currentItem();
  920. if (!item)
  921. return;
  922. QVariant userData = item->data(Qt::UserRole);
  923. obs_scene_t scene = userData.value<OBSScene>();
  924. obs_source_t source = obs_scene_getsource(scene);
  925. obs_source_remove(source);
  926. }
  927. void OBSBasic::on_actionSceneProperties_triggered()
  928. {
  929. /* TODO */
  930. }
  931. void OBSBasic::on_actionSceneUp_triggered()
  932. {
  933. /* TODO */
  934. }
  935. void OBSBasic::on_actionSceneDown_triggered()
  936. {
  937. /* TODO */
  938. }
  939. void OBSBasic::on_sources_currentItemChanged(QListWidgetItem *current,
  940. QListWidgetItem *prev)
  941. {
  942. auto select_one = [] (obs_scene_t scene, obs_sceneitem_t item,
  943. void *param)
  944. {
  945. obs_sceneitem_t selectedItem =
  946. *reinterpret_cast<OBSSceneItem*>(param);
  947. obs_sceneitem_select(item, (selectedItem == item));
  948. UNUSED_PARAMETER(scene);
  949. return true;
  950. };
  951. if (!current)
  952. return;
  953. OBSSceneItem item = current->data(Qt::UserRole).value<OBSSceneItem>();
  954. obs_scene_enum_items(GetCurrentScene(), select_one, &item);
  955. UNUSED_PARAMETER(prev);
  956. }
  957. void OBSBasic::on_sources_customContextMenuRequested(const QPoint &pos)
  958. {
  959. /* TODO */
  960. UNUSED_PARAMETER(pos);
  961. }
  962. void OBSBasic::AddSource(const char *id)
  963. {
  964. OBSBasicSourceSelect sourceSelect(this, id);
  965. sourceSelect.exec();
  966. }
  967. void OBSBasic::AddSourcePopupMenu(const QPoint &pos)
  968. {
  969. const char *type;
  970. bool foundValues = false;
  971. size_t idx = 0;
  972. if (!GetCurrentScene()) {
  973. // Tell the user he needs a scene first (help beginners).
  974. QMessageBox::information(this,
  975. QTStr("Basic.Main.AddSourceHelp.Title"),
  976. QTStr("Basic.Main.AddSourceHelp.Text"));
  977. return;
  978. }
  979. QMenu popup;
  980. while (obs_enum_input_types(idx++, &type)) {
  981. const char *name = obs_source_getdisplayname(
  982. OBS_SOURCE_TYPE_INPUT,
  983. type, App()->GetLocale());
  984. if (strcmp(type, "scene") == 0)
  985. continue;
  986. QAction *popupItem = new QAction(QT_UTF8(name), this);
  987. popupItem->setData(QT_UTF8(type));
  988. popup.addAction(popupItem);
  989. foundValues = true;
  990. }
  991. if (foundValues) {
  992. QAction *ret = popup.exec(pos);
  993. if (ret)
  994. AddSource(ret->data().toString().toUtf8());
  995. }
  996. }
  997. void OBSBasic::on_actionAddSource_triggered()
  998. {
  999. AddSourcePopupMenu(QCursor::pos());
  1000. }
  1001. void OBSBasic::on_actionRemoveSource_triggered()
  1002. {
  1003. OBSSceneItem item = GetCurrentSceneItem();
  1004. if (item)
  1005. obs_sceneitem_remove(item);
  1006. }
  1007. void OBSBasic::on_actionSourceProperties_triggered()
  1008. {
  1009. OBSSceneItem item = GetCurrentSceneItem();
  1010. OBSSource source = obs_sceneitem_getsource(item);
  1011. if (source) {
  1012. delete properties;
  1013. properties = new OBSBasicProperties(this, source);
  1014. properties->Init();
  1015. }
  1016. }
  1017. void OBSBasic::on_actionSourceUp_triggered()
  1018. {
  1019. OBSSceneItem item = GetCurrentSceneItem();
  1020. obs_sceneitem_setorder(item, ORDER_MOVE_UP);
  1021. }
  1022. void OBSBasic::on_actionSourceDown_triggered()
  1023. {
  1024. OBSSceneItem item = GetCurrentSceneItem();
  1025. obs_sceneitem_setorder(item, ORDER_MOVE_DOWN);
  1026. }
  1027. static char *ReadLogFile(const char *log)
  1028. {
  1029. BPtr<char> logDir(os_get_config_path("obs-studio/logs"));
  1030. string path = (char*)logDir;
  1031. path += "/";
  1032. path += log;
  1033. char *file = os_quick_read_utf8_file(path.c_str());
  1034. if (!file)
  1035. blog(LOG_WARNING, "Failed to read log file %s", path.c_str());
  1036. return file;
  1037. }
  1038. void OBSBasic::UploadLog(const char *file)
  1039. {
  1040. dstr fileString = {};
  1041. stringstream ss;
  1042. string jsonData;
  1043. dstr_move_array(&fileString, ReadLogFile(file));
  1044. if (!fileString.array)
  1045. return;
  1046. if (!*fileString.array) {
  1047. dstr_free(&fileString);
  1048. return;
  1049. }
  1050. ui->menuLogFiles->setEnabled(false);
  1051. dstr_replace(&fileString, "\\", "\\\\");
  1052. dstr_replace(&fileString, "\"", "\\\"");
  1053. dstr_replace(&fileString, "\n", "\\n");
  1054. dstr_replace(&fileString, "\r", "\\r");
  1055. dstr_replace(&fileString, "\t", "\\t");
  1056. dstr_replace(&fileString, "\t", "\\t");
  1057. dstr_replace(&fileString, "/", "\\/");
  1058. ss << "{ \"public\": false, \"description\": \"OBS " <<
  1059. App()->GetVersionString() << " log file uploaded at " <<
  1060. CurrentDateTimeString() << "\", \"files\": { \"" <<
  1061. file << "\": { \"content\": \"" <<
  1062. fileString.array << "\" } } }";
  1063. jsonData = std::move(ss.str());
  1064. logUploadPostData.setData(jsonData.c_str(), (int)jsonData.size());
  1065. QUrl url("https://api.github.com/gists");
  1066. logUploadReply = networkManager.post(QNetworkRequest(url),
  1067. &logUploadPostData);
  1068. connect(logUploadReply, SIGNAL(finished()),
  1069. this, SLOT(logUploadFinished()));
  1070. connect(logUploadReply, SIGNAL(readyRead()),
  1071. this, SLOT(logUploadRead()));
  1072. dstr_free(&fileString);
  1073. }
  1074. void OBSBasic::on_actionUploadCurrentLog_triggered()
  1075. {
  1076. UploadLog(App()->GetCurrentLog());
  1077. }
  1078. void OBSBasic::on_actionUploadLastLog_triggered()
  1079. {
  1080. UploadLog(App()->GetLastLog());
  1081. }
  1082. void OBSBasic::logUploadRead()
  1083. {
  1084. logUploadReturnData.push_back(logUploadReply->readAll());
  1085. }
  1086. void OBSBasic::logUploadFinished()
  1087. {
  1088. ui->menuLogFiles->setEnabled(true);
  1089. if (logUploadReply->error()) {
  1090. QMessageBox::information(this,
  1091. QTStr("LogReturnDialog.ErrorUploadingLog"),
  1092. logUploadReply->errorString());
  1093. return;
  1094. }
  1095. const char *jsonReply = logUploadReturnData.constData();
  1096. if (!jsonReply || !*jsonReply)
  1097. return;
  1098. obs_data_t returnData = obs_data_create_from_json(jsonReply);
  1099. QString logURL = obs_data_getstring(returnData, "html_url");
  1100. obs_data_release(returnData);
  1101. OBSLogReply logDialog(this, logURL);
  1102. logDialog.exec();
  1103. }
  1104. void OBSBasic::StreamingStart()
  1105. {
  1106. ui->streamButton->setText("Stop Streaming");
  1107. ui->streamButton->setEnabled(true);
  1108. }
  1109. void OBSBasic::StreamingStop(int code)
  1110. {
  1111. const char *errorMessage;
  1112. switch (code) {
  1113. case OBS_OUTPUT_BAD_PATH:
  1114. errorMessage = Str("Output.ConnectFail.BadPath");
  1115. break;
  1116. case OBS_OUTPUT_CONNECT_FAILED:
  1117. errorMessage = Str("Output.ConnectFail.ConnectFailed");
  1118. break;
  1119. case OBS_OUTPUT_INVALID_STREAM:
  1120. errorMessage = Str("Output.ConnectFail.InvalidStream");
  1121. break;
  1122. case OBS_OUTPUT_ERROR:
  1123. errorMessage = Str("Output.ConnectFail.Error");
  1124. break;
  1125. case OBS_OUTPUT_DISCONNECTED:
  1126. /* doesn't happen if output is set to reconnect. note that
  1127. * reconnects are handled in the output, not in the UI */
  1128. errorMessage = Str("Output.ConnectFail.Disconnected");
  1129. }
  1130. activeRefs--;
  1131. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  1132. ui->streamButton->setEnabled(true);
  1133. if (code != OBS_OUTPUT_SUCCESS)
  1134. QMessageBox::information(this,
  1135. QTStr("Output.ConnectFail.Title"),
  1136. QT_UTF8(errorMessage));
  1137. }
  1138. void OBSBasic::RecordingStop()
  1139. {
  1140. activeRefs--;
  1141. ui->recordButton->setText(QTStr("Basic.Main.StartRecording"));
  1142. }
  1143. void OBSBasic::SetupEncoders()
  1144. {
  1145. if (activeRefs == 0) {
  1146. obs_data_t x264Settings = obs_data_create();
  1147. obs_data_t aacSettings = obs_data_create();
  1148. int videoBitrate = config_get_uint(basicConfig, "SimpleOutput",
  1149. "VBitrate");
  1150. int audioBitrate = config_get_uint(basicConfig, "SimpleOutput",
  1151. "ABitrate");
  1152. obs_data_setint(x264Settings, "bitrate", videoBitrate);
  1153. obs_data_setbool(x264Settings, "cbr", true);
  1154. obs_data_setint(aacSettings, "bitrate", audioBitrate);
  1155. obs_encoder_update(x264, x264Settings);
  1156. obs_encoder_update(aac, aacSettings);
  1157. obs_data_release(x264Settings);
  1158. obs_data_release(aacSettings);
  1159. obs_encoder_set_video(x264, obs_video());
  1160. obs_encoder_set_audio(aac, obs_audio());
  1161. }
  1162. }
  1163. void OBSBasic::on_streamButton_clicked()
  1164. {
  1165. if (obs_output_active(streamOutput)) {
  1166. obs_output_stop(streamOutput);
  1167. } else {
  1168. SaveService();
  1169. SetupEncoders();
  1170. obs_output_set_video_encoder(streamOutput, x264);
  1171. obs_output_set_audio_encoder(streamOutput, aac);
  1172. obs_output_set_service(streamOutput, service);
  1173. if (obs_output_start(streamOutput)) {
  1174. activeRefs++;
  1175. ui->streamButton->setEnabled(false);
  1176. ui->streamButton->setText(
  1177. QTStr("Basic.Main.Connecting"));
  1178. }
  1179. }
  1180. }
  1181. void OBSBasic::on_recordButton_clicked()
  1182. {
  1183. if (obs_output_active(fileOutput)) {
  1184. obs_output_stop(fileOutput);
  1185. } else {
  1186. const char *path = config_get_string(basicConfig,
  1187. "SimpleOutput", "FilePath");
  1188. os_dir_t dir = path ? os_opendir(path) : nullptr;
  1189. if (!dir) {
  1190. QMessageBox::information(this,
  1191. QTStr("Output.BadPath.Title"),
  1192. QTStr("Output.BadPath.Text"));
  1193. return;
  1194. }
  1195. os_closedir(dir);
  1196. string strPath;
  1197. strPath += path;
  1198. char lastChar = strPath.back();
  1199. if (lastChar != '/' && lastChar != '\\')
  1200. strPath += "/";
  1201. strPath += GenerateTimeDateFilename("flv");
  1202. SetupEncoders();
  1203. obs_output_set_video_encoder(fileOutput, x264);
  1204. obs_output_set_audio_encoder(fileOutput, aac);
  1205. obs_data_t settings = obs_data_create();
  1206. obs_data_setstring(settings, "path", strPath.c_str());
  1207. obs_output_update(fileOutput, settings);
  1208. obs_data_release(settings);
  1209. if (obs_output_start(fileOutput)) {
  1210. activeRefs++;
  1211. ui->recordButton->setText(
  1212. QTStr("Basic.Main.StopRecording"));
  1213. }
  1214. }
  1215. }
  1216. void OBSBasic::on_settingsButton_clicked()
  1217. {
  1218. OBSBasicSettings settings(this);
  1219. settings.exec();
  1220. }
  1221. void OBSBasic::GetFPSCommon(uint32_t &num, uint32_t &den) const
  1222. {
  1223. const char *val = config_get_string(basicConfig, "Video", "FPSCommon");
  1224. if (strcmp(val, "10") == 0) {
  1225. num = 10;
  1226. den = 1;
  1227. } else if (strcmp(val, "20") == 0) {
  1228. num = 20;
  1229. den = 1;
  1230. } else if (strcmp(val, "25") == 0) {
  1231. num = 25;
  1232. den = 1;
  1233. } else if (strcmp(val, "29.97") == 0) {
  1234. num = 30000;
  1235. den = 1001;
  1236. } else if (strcmp(val, "48") == 0) {
  1237. num = 48;
  1238. den = 1;
  1239. } else if (strcmp(val, "59.94") == 0) {
  1240. num = 60000;
  1241. den = 1001;
  1242. } else if (strcmp(val, "60") == 0) {
  1243. num = 60;
  1244. den = 1;
  1245. } else {
  1246. num = 30;
  1247. den = 1;
  1248. }
  1249. }
  1250. void OBSBasic::GetFPSInteger(uint32_t &num, uint32_t &den) const
  1251. {
  1252. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSInt");
  1253. den = 1;
  1254. }
  1255. void OBSBasic::GetFPSFraction(uint32_t &num, uint32_t &den) const
  1256. {
  1257. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNum");
  1258. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSDen");
  1259. }
  1260. void OBSBasic::GetFPSNanoseconds(uint32_t &num, uint32_t &den) const
  1261. {
  1262. num = 1000000000;
  1263. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNS");
  1264. }
  1265. void OBSBasic::GetConfigFPS(uint32_t &num, uint32_t &den) const
  1266. {
  1267. uint32_t type = config_get_uint(basicConfig, "Video", "FPSType");
  1268. if (type == 1) //"Integer"
  1269. GetFPSInteger(num, den);
  1270. else if (type == 2) //"Fraction"
  1271. GetFPSFraction(num, den);
  1272. else if (false) //"Nanoseconds", currently not implemented
  1273. GetFPSNanoseconds(num, den);
  1274. else
  1275. GetFPSCommon(num, den);
  1276. }
  1277. config_t OBSBasic::Config() const
  1278. {
  1279. return basicConfig;
  1280. }
  1281. void OBSBasic::on_actionEditTransform_triggered()
  1282. {
  1283. delete transformWindow;
  1284. transformWindow = new OBSBasicTransform(this);
  1285. transformWindow->show();
  1286. }
  1287. void OBSBasic::on_actionResetTransform_triggered()
  1288. {
  1289. auto func = [] (obs_scene_t scene, obs_sceneitem_t item, void *param)
  1290. {
  1291. if (!obs_sceneitem_selected(item))
  1292. return true;
  1293. obs_sceneitem_info info;
  1294. vec2_set(&info.pos, 0.0f, 0.0f);
  1295. vec2_set(&info.scale, 1.0f, 1.0f);
  1296. info.rot = 0.0f;
  1297. info.alignment = OBS_ALIGN_TOP | OBS_ALIGN_LEFT;
  1298. info.bounds_type = OBS_BOUNDS_NONE;
  1299. info.bounds_alignment = OBS_ALIGN_CENTER;
  1300. vec2_set(&info.bounds, 0.0f, 0.0f);
  1301. obs_sceneitem_set_info(item, &info);
  1302. UNUSED_PARAMETER(scene);
  1303. UNUSED_PARAMETER(param);
  1304. return true;
  1305. };
  1306. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  1307. }
  1308. static vec3 GetItemTL(obs_sceneitem_t item)
  1309. {
  1310. matrix4 boxTransform;
  1311. obs_sceneitem_get_box_transform(item, &boxTransform);
  1312. vec3 tl;
  1313. vec3_set(&tl, M_INFINITE, M_INFINITE, 0.0f);
  1314. auto GetMinPos = [&] (vec3 &val, float x, float y)
  1315. {
  1316. vec3 pos;
  1317. vec3_set(&pos, x, y, 0.0f);
  1318. vec3_transform(&pos, &pos, &boxTransform);
  1319. vec3_min(&val, &val, &pos);
  1320. };
  1321. GetMinPos(tl, 0.0f, 0.0f);
  1322. GetMinPos(tl, 1.0f, 0.0f);
  1323. GetMinPos(tl, 0.0f, 1.0f);
  1324. GetMinPos(tl, 1.0f, 1.0f);
  1325. return tl;
  1326. }
  1327. static void SetItemTL(obs_sceneitem_t item, const vec3 &tl)
  1328. {
  1329. vec3 newTL;
  1330. vec2 pos;
  1331. obs_sceneitem_getpos(item, &pos);
  1332. newTL = GetItemTL(item);
  1333. pos.x += tl.x - newTL.x;
  1334. pos.y += tl.y - newTL.y;
  1335. obs_sceneitem_setpos(item, &pos);
  1336. }
  1337. static bool RotateSelectedSources(obs_scene_t scene, obs_sceneitem_t item,
  1338. void *param)
  1339. {
  1340. if (!obs_sceneitem_selected(item))
  1341. return true;
  1342. float rot = *reinterpret_cast<float*>(param);
  1343. vec3 tl = GetItemTL(item);
  1344. rot += obs_sceneitem_getrot(item);
  1345. if (rot >= 360.0f) rot -= 360.0f;
  1346. else if (rot <= -360.0f) rot += 360.0f;
  1347. obs_sceneitem_setrot(item, rot);
  1348. SetItemTL(item, tl);
  1349. UNUSED_PARAMETER(scene);
  1350. UNUSED_PARAMETER(param);
  1351. return true;
  1352. };
  1353. void OBSBasic::on_actionRotate90CW_triggered()
  1354. {
  1355. float f90CW = 90.0f;
  1356. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CW);
  1357. }
  1358. void OBSBasic::on_actionRotate90CCW_triggered()
  1359. {
  1360. float f90CCW = -90.0f;
  1361. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CCW);
  1362. }
  1363. void OBSBasic::on_actionRotate180_triggered()
  1364. {
  1365. float f180 = 180.0f;
  1366. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f180);
  1367. }
  1368. static bool MultiplySelectedItemScale(obs_scene_t scene, obs_sceneitem_t item,
  1369. void *param)
  1370. {
  1371. vec2 &mul = *reinterpret_cast<vec2*>(param);
  1372. if (!obs_sceneitem_selected(item))
  1373. return true;
  1374. vec3 tl = GetItemTL(item);
  1375. vec2 scale;
  1376. obs_sceneitem_getscale(item, &scale);
  1377. vec2_mul(&scale, &scale, &mul);
  1378. obs_sceneitem_setscale(item, &scale);
  1379. SetItemTL(item, tl);
  1380. return true;
  1381. }
  1382. void OBSBasic::on_actionFlipHorizontal_triggered()
  1383. {
  1384. vec2 scale = {-1.0f, 1.0f};
  1385. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  1386. &scale);
  1387. }
  1388. void OBSBasic::on_actionFlipVertical_triggered()
  1389. {
  1390. vec2 scale = {1.0f, -1.0f};
  1391. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  1392. &scale);
  1393. }
  1394. static bool CenterAlignSelectedItems(obs_scene_t scene, obs_sceneitem_t item,
  1395. void *param)
  1396. {
  1397. obs_bounds_type boundsType = *reinterpret_cast<obs_bounds_type*>(param);
  1398. if (!obs_sceneitem_selected(item))
  1399. return true;
  1400. obs_video_info ovi;
  1401. obs_get_video_info(&ovi);
  1402. obs_sceneitem_info itemInfo;
  1403. vec2_set(&itemInfo.pos, 0.0f, 0.0f);
  1404. vec2_set(&itemInfo.scale, 1.0f, 1.0f);
  1405. itemInfo.alignment = OBS_ALIGN_LEFT | OBS_ALIGN_TOP;
  1406. itemInfo.rot = 0.0f;
  1407. vec2_set(&itemInfo.bounds,
  1408. float(ovi.base_width), float(ovi.base_height));
  1409. itemInfo.bounds_type = boundsType;
  1410. itemInfo.bounds_alignment = OBS_ALIGN_CENTER;
  1411. obs_sceneitem_set_info(item, &itemInfo);
  1412. UNUSED_PARAMETER(scene);
  1413. return true;
  1414. }
  1415. void OBSBasic::on_actionFitToScreen_triggered()
  1416. {
  1417. obs_bounds_type boundsType = OBS_BOUNDS_SCALE_INNER;
  1418. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  1419. &boundsType);
  1420. }
  1421. void OBSBasic::on_actionStretchToScreen_triggered()
  1422. {
  1423. obs_bounds_type boundsType = OBS_BOUNDS_STRETCH;
  1424. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  1425. &boundsType);
  1426. }
  1427. void OBSBasic::on_actionCenterToScreen_triggered()
  1428. {
  1429. obs_bounds_type boundsType = OBS_BOUNDS_MAX_ONLY;
  1430. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  1431. &boundsType);
  1432. }