window-basic-main.cpp 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339
  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 <time.h>
  16. #include <obs.hpp>
  17. #include <QMessageBox>
  18. #include <QShowEvent>
  19. #include <QFileDialog>
  20. #include <QNetworkRequest>
  21. #include <QNetworkReply>
  22. #include <util/dstr.h>
  23. #include <util/util.hpp>
  24. #include <util/platform.h>
  25. #include <graphics/math-defs.h>
  26. #include "obs-app.hpp"
  27. #include "platform.hpp"
  28. #include "window-basic-settings.hpp"
  29. #include "window-namedialog.hpp"
  30. #include "window-basic-source-select.hpp"
  31. #include "window-basic-main.hpp"
  32. #include "window-basic-properties.hpp"
  33. #include "window-log-reply.hpp"
  34. #include "qt-wrappers.hpp"
  35. #include "display-helpers.hpp"
  36. #include "volume-control.hpp"
  37. #include "ui_OBSBasic.h"
  38. #include <fstream>
  39. #include <sstream>
  40. #include <QScreen>
  41. #include <QWindow>
  42. #define PREVIEW_EDGE_SIZE 10
  43. using namespace std;
  44. Q_DECLARE_METATYPE(OBSScene);
  45. Q_DECLARE_METATYPE(OBSSceneItem);
  46. Q_DECLARE_METATYPE(obs_order_movement);
  47. static void AddExtraModulePaths()
  48. {
  49. BPtr<char> base_module_dir = os_get_config_path("plugins/%module%");
  50. if (!base_module_dir)
  51. return;
  52. string path = (char*)base_module_dir;
  53. obs_add_module_path((path + "/bin").c_str(), (path + "/data").c_str());
  54. }
  55. OBSBasic::OBSBasic(QWidget *parent)
  56. : OBSMainWindow (parent),
  57. ui (new Ui::OBSBasic)
  58. {
  59. ui->setupUi(this);
  60. connect(windowHandle(), &QWindow::screenChanged, [this]() {
  61. struct obs_video_info ovi;
  62. if (obs_get_video_info(&ovi))
  63. ResizePreview(ovi.base_width, ovi.base_height);
  64. });
  65. stringstream name;
  66. name << "OBS " << App()->GetVersionString();
  67. blog(LOG_INFO, "%s", name.str().c_str());
  68. setWindowTitle(QT_UTF8(name.str().c_str()));
  69. connect(ui->scenes->itemDelegate(),
  70. SIGNAL(closeEditor(QWidget*,
  71. QAbstractItemDelegate::EndEditHint)),
  72. this,
  73. SLOT(SceneNameEdited(QWidget*,
  74. QAbstractItemDelegate::EndEditHint)));
  75. connect(ui->sources->itemDelegate(),
  76. SIGNAL(closeEditor(QWidget*,
  77. QAbstractItemDelegate::EndEditHint)),
  78. this,
  79. SLOT(SceneItemNameEdited(QWidget*,
  80. QAbstractItemDelegate::EndEditHint)));
  81. cpuUsageInfo = os_cpu_usage_info_start();
  82. cpuUsageTimer = new QTimer(this);
  83. connect(cpuUsageTimer, SIGNAL(timeout()),
  84. ui->statusbar, SLOT(UpdateCPUUsage()));
  85. cpuUsageTimer->start(3000);
  86. #ifdef __APPLE__
  87. QList<QKeySequence> keys;
  88. keys.append(QKeySequence::Delete);
  89. keys.append(QKeySequence(Qt::Key_Backspace));
  90. ui->actionRemoveSource->setShortcuts(keys);
  91. ui->action_Settings->setMenuRole(QAction::PreferencesRole);
  92. ui->actionE_xit->setMenuRole(QAction::QuitRole);
  93. #endif
  94. }
  95. static void SaveAudioDevice(const char *name, int channel, obs_data_t parent)
  96. {
  97. obs_source_t source = obs_get_output_source(channel);
  98. if (!source)
  99. return;
  100. obs_data_t data = obs_save_source(source);
  101. obs_data_setobj(parent, name, data);
  102. obs_data_release(data);
  103. obs_source_release(source);
  104. }
  105. static obs_data_t GenerateSaveData()
  106. {
  107. obs_data_t saveData = obs_data_create();
  108. obs_data_array_t sourcesArray = obs_save_sources();
  109. obs_source_t currentScene = obs_get_output_source(0);
  110. const char *sceneName = obs_source_getname(currentScene);
  111. SaveAudioDevice(DESKTOP_AUDIO_1, 1, saveData);
  112. SaveAudioDevice(DESKTOP_AUDIO_2, 2, saveData);
  113. SaveAudioDevice(AUX_AUDIO_1, 3, saveData);
  114. SaveAudioDevice(AUX_AUDIO_2, 4, saveData);
  115. SaveAudioDevice(AUX_AUDIO_3, 5, saveData);
  116. obs_data_setstring(saveData, "current_scene", sceneName);
  117. obs_data_setarray(saveData, "sources", sourcesArray);
  118. obs_data_array_release(sourcesArray);
  119. obs_source_release(currentScene);
  120. return saveData;
  121. }
  122. void OBSBasic::ClearVolumeControls()
  123. {
  124. VolControl *control;
  125. for (size_t i = 0; i < volumes.size(); i++) {
  126. control = volumes[i];
  127. delete control;
  128. }
  129. volumes.clear();
  130. }
  131. void OBSBasic::Save(const char *file)
  132. {
  133. obs_data_t saveData = GenerateSaveData();
  134. const char *jsonData = obs_data_getjson(saveData);
  135. /* TODO maybe a message box here? */
  136. if (!os_quick_write_utf8_file(file, jsonData, strlen(jsonData), false))
  137. blog(LOG_ERROR, "Could not save scene data to %s", file);
  138. obs_data_release(saveData);
  139. }
  140. static void LoadAudioDevice(const char *name, int channel, obs_data_t parent)
  141. {
  142. obs_data_t data = obs_data_getobj(parent, name);
  143. if (!data)
  144. return;
  145. obs_source_t source = obs_load_source(data);
  146. if (source) {
  147. obs_set_output_source(channel, source);
  148. obs_source_release(source);
  149. }
  150. obs_data_release(data);
  151. }
  152. void OBSBasic::CreateDefaultScene()
  153. {
  154. obs_scene_t scene = obs_scene_create(Str("Basic.Scene"));
  155. obs_source_t source = obs_scene_getsource(scene);
  156. obs_add_source(source);
  157. #ifdef __APPLE__
  158. source = obs_source_create(OBS_SOURCE_TYPE_INPUT, "display_capture",
  159. Str("Basic.DisplayCapture"), NULL);
  160. if (source) {
  161. obs_scene_add(scene, source);
  162. obs_add_source(source);
  163. obs_source_release(source);
  164. }
  165. #endif
  166. obs_set_output_source(0, obs_scene_getsource(scene));
  167. obs_scene_release(scene);
  168. }
  169. void OBSBasic::Load(const char *file)
  170. {
  171. if (!file) {
  172. blog(LOG_ERROR, "Could not find file %s", file);
  173. return;
  174. }
  175. BPtr<char> jsonData = os_quick_read_utf8_file(file);
  176. if (!jsonData) {
  177. CreateDefaultScene();
  178. return;
  179. }
  180. obs_data_t data = obs_data_create_from_json(jsonData);
  181. obs_data_array_t sources = obs_data_getarray(data, "sources");
  182. const char *sceneName = obs_data_getstring(data, "current_scene");
  183. obs_source_t curScene;
  184. LoadAudioDevice(DESKTOP_AUDIO_1, 1, data);
  185. LoadAudioDevice(DESKTOP_AUDIO_2, 2, data);
  186. LoadAudioDevice(AUX_AUDIO_1, 3, data);
  187. LoadAudioDevice(AUX_AUDIO_2, 4, data);
  188. LoadAudioDevice(AUX_AUDIO_3, 5, data);
  189. obs_load_sources(sources);
  190. curScene = obs_get_source_by_name(sceneName);
  191. obs_set_output_source(0, curScene);
  192. obs_source_release(curScene);
  193. obs_data_array_release(sources);
  194. obs_data_release(data);
  195. }
  196. static inline bool HasAudioDevices(const char *source_id)
  197. {
  198. const char *output_id = source_id;
  199. obs_properties_t props = obs_get_source_properties(
  200. OBS_SOURCE_TYPE_INPUT, output_id);
  201. size_t count = 0;
  202. if (!props)
  203. return false;
  204. obs_property_t devices = obs_properties_get(props, "device_id");
  205. if (devices)
  206. count = obs_property_list_item_count(devices);
  207. obs_properties_destroy(props);
  208. return count != 0;
  209. }
  210. static void OBSStartStreaming(void *data, calldata_t params)
  211. {
  212. UNUSED_PARAMETER(params);
  213. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  214. "StreamingStart");
  215. }
  216. static void OBSStopStreaming(void *data, calldata_t params)
  217. {
  218. int code = (int)calldata_int(params, "code");
  219. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  220. "StreamingStop", Q_ARG(int, code));
  221. }
  222. static void OBSStopRecording(void *data, calldata_t params)
  223. {
  224. UNUSED_PARAMETER(params);
  225. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  226. "RecordingStop");
  227. }
  228. #define SERVICE_PATH "obs-studio/basic/service.json"
  229. void OBSBasic::SaveService()
  230. {
  231. if (!service)
  232. return;
  233. BPtr<char> serviceJsonPath(os_get_config_path(SERVICE_PATH));
  234. if (!serviceJsonPath)
  235. return;
  236. obs_data_t data = obs_data_create();
  237. obs_data_t settings = obs_service_get_settings(service);
  238. obs_data_setstring(data, "type", obs_service_gettype(service));
  239. obs_data_setobj(data, "settings", settings);
  240. const char *json = obs_data_getjson(data);
  241. os_quick_write_utf8_file(serviceJsonPath, json, strlen(json), false);
  242. obs_data_release(settings);
  243. obs_data_release(data);
  244. }
  245. bool OBSBasic::LoadService()
  246. {
  247. const char *type;
  248. BPtr<char> serviceJsonPath(os_get_config_path(SERVICE_PATH));
  249. if (!serviceJsonPath)
  250. return false;
  251. BPtr<char> jsonText = os_quick_read_utf8_file(serviceJsonPath);
  252. if (!jsonText)
  253. return false;
  254. obs_data_t data = obs_data_create_from_json(jsonText);
  255. obs_data_set_default_string(data, "type", "rtmp_common");
  256. type = obs_data_getstring(data, "type");
  257. obs_data_t settings = obs_data_getobj(data, "settings");
  258. service = obs_service_create(type, "default_service", settings);
  259. obs_data_release(settings);
  260. obs_data_release(data);
  261. return !!service;
  262. }
  263. bool OBSBasic::InitOutputs()
  264. {
  265. fileOutput = obs_output_create("flv_output", "default_file_output",
  266. nullptr);
  267. if (!fileOutput)
  268. return false;
  269. streamOutput = obs_output_create("rtmp_output", "default_stream",
  270. nullptr);
  271. if (!streamOutput)
  272. return false;
  273. signal_handler_connect(obs_output_signalhandler(streamOutput),
  274. "start", OBSStartStreaming, this);
  275. signal_handler_connect(obs_output_signalhandler(streamOutput),
  276. "stop", OBSStopStreaming, this);
  277. signal_handler_connect(obs_output_signalhandler(fileOutput),
  278. "stop", OBSStopRecording, this);
  279. return true;
  280. }
  281. bool OBSBasic::InitEncoders()
  282. {
  283. x264 = obs_video_encoder_create("obs_x264", "default_h264", nullptr);
  284. if (!x264)
  285. return false;
  286. aac = obs_audio_encoder_create("libfdk_aac", "default_aac", nullptr);
  287. if (!aac)
  288. aac = obs_audio_encoder_create("ffmpeg_aac", "default_aac",
  289. nullptr);
  290. if (!aac)
  291. return false;
  292. return true;
  293. }
  294. bool OBSBasic::InitService()
  295. {
  296. if (LoadService())
  297. return true;
  298. service = obs_service_create("rtmp_common", "default_service", nullptr);
  299. if (!service)
  300. return false;
  301. return true;
  302. }
  303. bool OBSBasic::InitBasicConfigDefaults()
  304. {
  305. bool hasDesktopAudio = HasAudioDevices(App()->OutputAudioSource());
  306. bool hasInputAudio = HasAudioDevices(App()->InputAudioSource());
  307. config_set_default_int(basicConfig, "Window", "PosX", -1);
  308. config_set_default_int(basicConfig, "Window", "PosY", -1);
  309. config_set_default_int(basicConfig, "Window", "SizeX", -1);
  310. config_set_default_int(basicConfig, "Window", "SizeY", -1);
  311. vector<MonitorInfo> monitors;
  312. GetMonitors(monitors);
  313. if (!monitors.size()) {
  314. OBSErrorBox(NULL, "There appears to be no monitors. Er, this "
  315. "technically shouldn't be possible.");
  316. return false;
  317. }
  318. uint32_t cx = monitors[0].cx;
  319. uint32_t cy = monitors[0].cy;
  320. /* TODO: temporary */
  321. config_set_default_string(basicConfig, "SimpleOutput", "FilePath",
  322. GetDefaultVideoSavePath().c_str());
  323. config_set_default_uint (basicConfig, "SimpleOutput", "VBitrate",
  324. 2500);
  325. config_set_default_uint (basicConfig, "SimpleOutput", "ABitrate", 128);
  326. config_set_default_bool (basicConfig, "SimpleOutput", "Reconnect",
  327. true);
  328. config_set_default_uint (basicConfig, "SimpleOutput", "RetryDelay", 2);
  329. config_set_default_uint (basicConfig, "SimpleOutput", "MaxRetries",
  330. 20);
  331. config_set_default_uint (basicConfig, "Video", "BaseCX", cx);
  332. config_set_default_uint (basicConfig, "Video", "BaseCY", cy);
  333. cx = cx * 10 / 15;
  334. cy = cy * 10 / 15;
  335. config_set_default_uint (basicConfig, "Video", "OutputCX", cx);
  336. config_set_default_uint (basicConfig, "Video", "OutputCY", cy);
  337. config_set_default_uint (basicConfig, "Video", "FPSType", 0);
  338. config_set_default_string(basicConfig, "Video", "FPSCommon", "30");
  339. config_set_default_uint (basicConfig, "Video", "FPSInt", 30);
  340. config_set_default_uint (basicConfig, "Video", "FPSNum", 30);
  341. config_set_default_uint (basicConfig, "Video", "FPSDen", 1);
  342. config_set_default_uint (basicConfig, "Audio", "SampleRate", 44100);
  343. config_set_default_string(basicConfig, "Audio", "ChannelSetup",
  344. "Stereo");
  345. config_set_default_uint (basicConfig, "Audio", "BufferingTime", 1000);
  346. config_set_default_string(basicConfig, "Audio", "DesktopDevice1",
  347. hasDesktopAudio ? "default" : "disabled");
  348. config_set_default_string(basicConfig, "Audio", "DesktopDevice2",
  349. "disabled");
  350. config_set_default_string(basicConfig, "Audio", "AuxDevice1",
  351. hasInputAudio ? "default" : "disabled");
  352. config_set_default_string(basicConfig, "Audio", "AuxDevice2",
  353. "disabled");
  354. config_set_default_string(basicConfig, "Audio", "AuxDevice3",
  355. "disabled");
  356. return true;
  357. }
  358. bool OBSBasic::InitBasicConfig()
  359. {
  360. BPtr<char> configPath(os_get_config_path("obs-studio/basic/basic.ini"));
  361. int code = basicConfig.Open(configPath, CONFIG_OPEN_ALWAYS);
  362. if (code != CONFIG_SUCCESS) {
  363. OBSErrorBox(NULL, "Failed to open basic.ini: %d", code);
  364. return false;
  365. }
  366. return InitBasicConfigDefaults();
  367. }
  368. void OBSBasic::InitOBSCallbacks()
  369. {
  370. signal_handler_connect(obs_signalhandler(), "source_add",
  371. OBSBasic::SourceAdded, this);
  372. signal_handler_connect(obs_signalhandler(), "source_remove",
  373. OBSBasic::SourceRemoved, this);
  374. signal_handler_connect(obs_signalhandler(), "channel_change",
  375. OBSBasic::ChannelChanged, this);
  376. signal_handler_connect(obs_signalhandler(), "source_activate",
  377. OBSBasic::SourceActivated, this);
  378. signal_handler_connect(obs_signalhandler(), "source_deactivate",
  379. OBSBasic::SourceDeactivated, this);
  380. signal_handler_connect(obs_signalhandler(), "source_rename",
  381. OBSBasic::SourceRenamed, this);
  382. }
  383. void OBSBasic::InitPrimitives()
  384. {
  385. gs_entercontext(obs_graphics());
  386. gs_renderstart(true);
  387. gs_vertex2f(0.0f, 0.0f);
  388. gs_vertex2f(0.0f, 1.0f);
  389. gs_vertex2f(1.0f, 1.0f);
  390. gs_vertex2f(1.0f, 0.0f);
  391. gs_vertex2f(0.0f, 0.0f);
  392. box = gs_rendersave();
  393. gs_renderstart(true);
  394. for (int i = 0; i <= 360; i += (360/20)) {
  395. float pos = RAD(float(i));
  396. gs_vertex2f(cosf(pos), sinf(pos));
  397. }
  398. circle = gs_rendersave();
  399. gs_leavecontext();
  400. }
  401. void OBSBasic::OBSInit()
  402. {
  403. BPtr<char> savePath(os_get_config_path("obs-studio/basic/scenes.json"));
  404. /* make sure it's fully displayed before doing any initialization */
  405. show();
  406. App()->processEvents();
  407. if (!obs_startup(App()->GetLocale()))
  408. throw "Failed to initialize libobs";
  409. if (!InitBasicConfig())
  410. throw "Failed to load basic.ini";
  411. if (!ResetAudio())
  412. throw "Failed to initialize audio";
  413. int ret = ResetVideo();
  414. switch (ret) {
  415. case OBS_VIDEO_MODULE_NOT_FOUND:
  416. throw "Failed to initialize video: Graphics module not found";
  417. case OBS_VIDEO_NOT_SUPPORTED:
  418. throw "Failed to initialize video: Your graphics adapter "
  419. "is either too old or does not have the required "
  420. "capabilities required for this program";
  421. case OBS_VIDEO_INVALID_PARAM:
  422. throw "Failed to initialize video: Invalid parameters";
  423. default:
  424. if (ret != OBS_VIDEO_SUCCESS)
  425. throw "Failed to initialize video: Unspecified error";
  426. }
  427. InitOBSCallbacks();
  428. AddExtraModulePaths();
  429. obs_load_all_modules();
  430. if (!InitOutputs())
  431. throw "Failed to initialize outputs";
  432. if (!InitEncoders())
  433. throw "Failed to initialize encoders";
  434. if (!InitService())
  435. throw "Failed to initialize service";
  436. InitPrimitives();
  437. Load(savePath);
  438. ResetAudioDevices();
  439. TimedCheckForUpdates();
  440. loaded = true;
  441. }
  442. OBSBasic::~OBSBasic()
  443. {
  444. BPtr<char> savePath(os_get_config_path("obs-studio/basic/scenes.json"));
  445. SaveService();
  446. Save(savePath);
  447. /* XXX: any obs data must be released before calling obs_shutdown.
  448. * currently, we can't automate this with C++ RAII because of the
  449. * delicate nature of obs_shutdown needing to be freed before the UI
  450. * can be freed, and we have no control over the destruction order of
  451. * the Qt UI stuff, so we have to manually clear any references to
  452. * libobs. */
  453. delete cpuUsageTimer;
  454. os_cpu_usage_info_destroy(cpuUsageInfo);
  455. if (properties)
  456. delete properties;
  457. if (transformWindow)
  458. delete transformWindow;
  459. ClearVolumeControls();
  460. ui->sources->clear();
  461. ui->scenes->clear();
  462. gs_entercontext(obs_graphics());
  463. vertexbuffer_destroy(box);
  464. vertexbuffer_destroy(circle);
  465. gs_leavecontext();
  466. obs_shutdown();
  467. config_set_int(App()->GlobalConfig(), "General", "LastVersion",
  468. LIBOBS_API_VER);
  469. config_save(App()->GlobalConfig());
  470. }
  471. OBSScene OBSBasic::GetCurrentScene()
  472. {
  473. QListWidgetItem *item = ui->scenes->currentItem();
  474. return item ? item->data(Qt::UserRole).value<OBSScene>() : nullptr;
  475. }
  476. OBSSceneItem OBSBasic::GetCurrentSceneItem()
  477. {
  478. QListWidgetItem *item = ui->sources->currentItem();
  479. return item ? item->data(Qt::UserRole).value<OBSSceneItem>() : nullptr;
  480. }
  481. void OBSBasic::UpdateSources(OBSScene scene)
  482. {
  483. ui->sources->clear();
  484. obs_scene_enum_items(scene,
  485. [] (obs_scene_t scene, obs_sceneitem_t item, void *p)
  486. {
  487. OBSBasic *window = static_cast<OBSBasic*>(p);
  488. window->InsertSceneItem(item);
  489. UNUSED_PARAMETER(scene);
  490. return true;
  491. }, this);
  492. }
  493. void OBSBasic::InsertSceneItem(obs_sceneitem_t item)
  494. {
  495. obs_source_t source = obs_sceneitem_getsource(item);
  496. const char *name = obs_source_getname(source);
  497. QListWidgetItem *listItem = new QListWidgetItem(QT_UTF8(name));
  498. listItem->setFlags(listItem->flags() | Qt::ItemIsEditable);
  499. listItem->setData(Qt::UserRole,
  500. QVariant::fromValue(OBSSceneItem(item)));
  501. ui->sources->insertItem(0, listItem);
  502. ui->sources->setCurrentRow(0);
  503. /* if the source was just created, open properties dialog */
  504. if (sourceSceneRefs[source] == 0 && loaded)
  505. CreatePropertiesWindow(source);
  506. }
  507. void OBSBasic::CreatePropertiesWindow(obs_source_t source)
  508. {
  509. if (properties)
  510. properties->close();
  511. properties = new OBSBasicProperties(this, source);
  512. properties->Init();
  513. properties->setAttribute(Qt::WA_DeleteOnClose, true);
  514. }
  515. /* Qt callbacks for invokeMethod */
  516. void OBSBasic::AddScene(OBSSource source)
  517. {
  518. const char *name = obs_source_getname(source);
  519. obs_scene_t scene = obs_scene_fromsource(source);
  520. QListWidgetItem *item = new QListWidgetItem(QT_UTF8(name));
  521. item->setFlags(item->flags() | Qt::ItemIsEditable);
  522. item->setData(Qt::UserRole, QVariant::fromValue(OBSScene(scene)));
  523. ui->scenes->addItem(item);
  524. signal_handler_t handler = obs_source_signalhandler(source);
  525. signal_handler_connect(handler, "item_add",
  526. OBSBasic::SceneItemAdded, this);
  527. signal_handler_connect(handler, "item_remove",
  528. OBSBasic::SceneItemRemoved, this);
  529. signal_handler_connect(handler, "item_move_up",
  530. OBSBasic::SceneItemMoveUp, this);
  531. signal_handler_connect(handler, "item_move_down",
  532. OBSBasic::SceneItemMoveDown, this);
  533. signal_handler_connect(handler, "item_move_top",
  534. OBSBasic::SceneItemMoveTop, this);
  535. signal_handler_connect(handler, "item_move_bottom",
  536. OBSBasic::SceneItemMoveBottom, this);
  537. }
  538. void OBSBasic::RemoveScene(OBSSource source)
  539. {
  540. const char *name = obs_source_getname(source);
  541. QListWidgetItem *sel = ui->scenes->currentItem();
  542. QList<QListWidgetItem*> items = ui->scenes->findItems(QT_UTF8(name),
  543. Qt::MatchExactly);
  544. if (sel != nullptr) {
  545. if (items.contains(sel))
  546. ui->sources->clear();
  547. delete sel;
  548. }
  549. }
  550. void OBSBasic::AddSceneItem(OBSSceneItem item)
  551. {
  552. obs_scene_t scene = obs_sceneitem_getscene(item);
  553. obs_source_t source = obs_sceneitem_getsource(item);
  554. if (GetCurrentScene() == scene)
  555. InsertSceneItem(item);
  556. sourceSceneRefs[source] = sourceSceneRefs[source] + 1;
  557. }
  558. void OBSBasic::RemoveSceneItem(OBSSceneItem item)
  559. {
  560. obs_scene_t scene = obs_sceneitem_getscene(item);
  561. if (GetCurrentScene() == scene) {
  562. for (int i = 0; i < ui->sources->count(); i++) {
  563. QListWidgetItem *listItem = ui->sources->item(i);
  564. QVariant userData = listItem->data(Qt::UserRole);
  565. if (userData.value<OBSSceneItem>() == item) {
  566. delete listItem;
  567. break;
  568. }
  569. }
  570. }
  571. obs_source_t source = obs_sceneitem_getsource(item);
  572. int scenes = sourceSceneRefs[source] - 1;
  573. sourceSceneRefs[source] = scenes;
  574. if (scenes == 0) {
  575. obs_source_remove(source);
  576. sourceSceneRefs.erase(source);
  577. }
  578. }
  579. void OBSBasic::UpdateSceneSelection(OBSSource source)
  580. {
  581. if (source) {
  582. obs_source_type type;
  583. obs_source_gettype(source, &type, NULL);
  584. obs_scene_t scene = obs_scene_fromsource(source);
  585. const char *name = obs_source_getname(source);
  586. if (!scene)
  587. return;
  588. QList<QListWidgetItem*> items =
  589. ui->scenes->findItems(QT_UTF8(name), Qt::MatchExactly);
  590. if (items.count()) {
  591. sceneChanging = true;
  592. ui->scenes->setCurrentItem(items.first());
  593. sceneChanging = false;
  594. UpdateSources(scene);
  595. }
  596. }
  597. }
  598. static void RenameListValues(QListWidget *listWidget, const QString &newName,
  599. const QString &prevName)
  600. {
  601. QList<QListWidgetItem*> items =
  602. listWidget->findItems(prevName, Qt::MatchExactly);
  603. for (int i = 0; i < items.count(); i++)
  604. items[i]->setText(newName);
  605. }
  606. void OBSBasic::RenameSources(QString newName, QString prevName)
  607. {
  608. RenameListValues(ui->scenes, newName, prevName);
  609. RenameListValues(ui->sources, newName, prevName);
  610. for (size_t i = 0; i < volumes.size(); i++) {
  611. if (volumes[i]->GetName().compare(prevName) == 0)
  612. volumes[i]->SetName(newName);
  613. }
  614. }
  615. void OBSBasic::MoveSceneItem(OBSSceneItem item, obs_order_movement movement)
  616. {
  617. OBSScene scene = obs_sceneitem_getscene(item);
  618. if (scene != GetCurrentScene())
  619. return;
  620. int curRow = ui->sources->currentRow();
  621. if (curRow == -1)
  622. return;
  623. QListWidgetItem *listItem = ui->sources->takeItem(curRow);
  624. switch (movement) {
  625. case OBS_ORDER_MOVE_UP:
  626. if (curRow > 0)
  627. curRow--;
  628. break;
  629. case OBS_ORDER_MOVE_DOWN:
  630. if (curRow < ui->sources->count())
  631. curRow++;
  632. break;
  633. case OBS_ORDER_MOVE_TOP:
  634. curRow = 0;
  635. break;
  636. case OBS_ORDER_MOVE_BOTTOM:
  637. curRow = ui->sources->count();
  638. break;
  639. }
  640. ui->sources->insertItem(curRow, listItem);
  641. ui->sources->setCurrentRow(curRow);
  642. }
  643. void OBSBasic::ActivateAudioSource(OBSSource source)
  644. {
  645. VolControl *vol = new VolControl(source);
  646. volumes.push_back(vol);
  647. ui->volumeWidgets->layout()->addWidget(vol);
  648. }
  649. void OBSBasic::DeactivateAudioSource(OBSSource source)
  650. {
  651. for (size_t i = 0; i < volumes.size(); i++) {
  652. if (volumes[i]->GetSource() == source) {
  653. delete volumes[i];
  654. volumes.erase(volumes.begin() + i);
  655. break;
  656. }
  657. }
  658. }
  659. bool OBSBasic::QueryRemoveSource(obs_source_t source)
  660. {
  661. const char *name = obs_source_getname(source);
  662. QString text = QTStr("ConfirmRemove.Text");
  663. text.replace("$1", QT_UTF8(name));
  664. QMessageBox::StandardButton button;
  665. button = QMessageBox::question(this,
  666. QTStr("ConfirmRemove.Remove"), text);
  667. return button == QMessageBox::Yes;
  668. }
  669. #define UPDATE_CHECK_INTERVAL (60*60*24*4) /* 4 days */
  670. void OBSBasic::TimedCheckForUpdates()
  671. {
  672. long long lastUpdate = config_get_int(App()->GlobalConfig(), "General",
  673. "LastUpdateCheck");
  674. uint32_t lastVersion = config_get_int(App()->GlobalConfig(), "General",
  675. "LastVersion");
  676. if (lastVersion < LIBOBS_API_VER) {
  677. lastUpdate = 0;
  678. config_set_int(App()->GlobalConfig(), "General",
  679. "LastUpdateCheck", 0);
  680. }
  681. long long t = (long long)time(nullptr);
  682. long long secs = t - lastUpdate;
  683. if (secs > UPDATE_CHECK_INTERVAL)
  684. CheckForUpdates();
  685. }
  686. void OBSBasic::CheckForUpdates()
  687. {
  688. ui->actionCheckForUpdates->setEnabled(false);
  689. string versionString("obs-basic ");
  690. versionString += App()->GetVersionString();
  691. QNetworkRequest request;
  692. request.setUrl(QUrl("https://obsproject.com/obs2_update/basic.json"));
  693. request.setRawHeader("User-Agent", versionString.c_str());
  694. updateReply = networkManager.get(request);
  695. connect(updateReply, SIGNAL(finished()),
  696. this, SLOT(updateFileFinished()));
  697. connect(updateReply, SIGNAL(readyRead()),
  698. this, SLOT(updateFileRead()));
  699. }
  700. void OBSBasic::updateFileRead()
  701. {
  702. updateReturnData.push_back(updateReply->readAll());
  703. }
  704. #ifdef __APPLE__
  705. #define VERSION_ENTRY "mac"
  706. #elif _WIN32
  707. #define VERSION_ENTRY "windows"
  708. #else
  709. #define VERSION_ENTRY "other"
  710. #endif
  711. void OBSBasic::updateFileFinished()
  712. {
  713. ui->actionCheckForUpdates->setEnabled(true);
  714. if (updateReply->error()) {
  715. blog(LOG_WARNING, "Update check failed: %s",
  716. QT_TO_UTF8(updateReply->errorString()));
  717. return;
  718. }
  719. const char *jsonReply = updateReturnData.constData();
  720. if (!jsonReply || !*jsonReply)
  721. return;
  722. obs_data_t returnData = obs_data_create_from_json(jsonReply);
  723. obs_data_t versionData = obs_data_getobj(returnData, VERSION_ENTRY);
  724. const char *description = obs_data_getstring(returnData, "description");
  725. const char *download = obs_data_getstring(versionData, "download");
  726. if (returnData && versionData && description && download) {
  727. long major = obs_data_getint(versionData, "major");
  728. long minor = obs_data_getint(versionData, "minor");
  729. long patch = obs_data_getint(versionData, "patch");
  730. long version = MAKE_SEMANTIC_VERSION(major, minor, patch);
  731. blog(LOG_INFO, "Update check: latest version is: %ld.%ld.%ld",
  732. major, minor, patch);
  733. if (version > LIBOBS_API_VER) {
  734. QString str = QTStr("UpdateAvailable.Text");
  735. QMessageBox messageBox(this);
  736. str = str.arg(QString::number(major),
  737. QString::number(minor),
  738. QString::number(patch),
  739. download);
  740. messageBox.setWindowTitle(QTStr("UpdateAvailable"));
  741. messageBox.setTextFormat(Qt::RichText);
  742. messageBox.setText(str);
  743. messageBox.setInformativeText(QT_UTF8(description));
  744. messageBox.exec();
  745. long long t = (long long)time(nullptr);
  746. config_set_int(App()->GlobalConfig(), "General",
  747. "LastUpdateCheck", t);
  748. config_save(App()->GlobalConfig());
  749. }
  750. } else {
  751. blog(LOG_WARNING, "Bad JSON file received from server");
  752. }
  753. obs_data_release(versionData);
  754. obs_data_release(returnData);
  755. }
  756. void OBSBasic::RemoveSelectedScene()
  757. {
  758. OBSScene scene = GetCurrentScene();
  759. if (scene) {
  760. obs_source_t source = obs_scene_getsource(scene);
  761. if (QueryRemoveSource(source))
  762. obs_source_remove(source);
  763. }
  764. }
  765. void OBSBasic::RemoveSelectedSceneItem()
  766. {
  767. OBSSceneItem item = GetCurrentSceneItem();
  768. if (item) {
  769. obs_source_t source = obs_sceneitem_getsource(item);
  770. if (QueryRemoveSource(source))
  771. obs_sceneitem_remove(item);
  772. }
  773. }
  774. /* OBS Callbacks */
  775. void OBSBasic::SceneItemAdded(void *data, calldata_t params)
  776. {
  777. OBSBasic *window = static_cast<OBSBasic*>(data);
  778. obs_sceneitem_t item = (obs_sceneitem_t)calldata_ptr(params, "item");
  779. QMetaObject::invokeMethod(window, "AddSceneItem",
  780. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  781. }
  782. void OBSBasic::SceneItemRemoved(void *data, calldata_t params)
  783. {
  784. OBSBasic *window = static_cast<OBSBasic*>(data);
  785. obs_sceneitem_t item = (obs_sceneitem_t)calldata_ptr(params, "item");
  786. QMetaObject::invokeMethod(window, "RemoveSceneItem",
  787. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  788. }
  789. void OBSBasic::SourceAdded(void *data, calldata_t params)
  790. {
  791. OBSBasic *window = static_cast<OBSBasic*>(data);
  792. obs_source_t source = (obs_source_t)calldata_ptr(params, "source");
  793. if (obs_scene_fromsource(source) != NULL)
  794. QMetaObject::invokeMethod(window,
  795. "AddScene",
  796. Q_ARG(OBSSource, OBSSource(source)));
  797. }
  798. void OBSBasic::SourceRemoved(void *data, calldata_t params)
  799. {
  800. obs_source_t source = (obs_source_t)calldata_ptr(params, "source");
  801. if (obs_scene_fromsource(source) != NULL)
  802. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  803. "RemoveScene",
  804. Q_ARG(OBSSource, OBSSource(source)));
  805. }
  806. void OBSBasic::SourceActivated(void *data, calldata_t params)
  807. {
  808. obs_source_t source = (obs_source_t)calldata_ptr(params, "source");
  809. uint32_t flags = obs_source_get_output_flags(source);
  810. if (flags & OBS_SOURCE_AUDIO)
  811. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  812. "ActivateAudioSource",
  813. Q_ARG(OBSSource, OBSSource(source)));
  814. }
  815. void OBSBasic::SourceDeactivated(void *data, calldata_t params)
  816. {
  817. obs_source_t source = (obs_source_t)calldata_ptr(params, "source");
  818. uint32_t flags = obs_source_get_output_flags(source);
  819. if (flags & OBS_SOURCE_AUDIO)
  820. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  821. "DeactivateAudioSource",
  822. Q_ARG(OBSSource, OBSSource(source)));
  823. }
  824. void OBSBasic::SourceRenamed(void *data, calldata_t params)
  825. {
  826. const char *newName = calldata_string(params, "new_name");
  827. const char *prevName = calldata_string(params, "prev_name");
  828. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  829. "RenameSources",
  830. Q_ARG(QString, QT_UTF8(newName)),
  831. Q_ARG(QString, QT_UTF8(prevName)));
  832. }
  833. void OBSBasic::ChannelChanged(void *data, calldata_t params)
  834. {
  835. obs_source_t source = (obs_source_t)calldata_ptr(params, "source");
  836. uint32_t channel = (uint32_t)calldata_int(params, "channel");
  837. if (channel == 0)
  838. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  839. "UpdateSceneSelection",
  840. Q_ARG(OBSSource, OBSSource(source)));
  841. }
  842. void OBSBasic::DrawBackdrop(float cx, float cy)
  843. {
  844. if (!box)
  845. return;
  846. effect_t solid = obs_get_solid_effect();
  847. eparam_t color = effect_getparambyname(solid, "color");
  848. technique_t tech = effect_gettechnique(solid, "Solid");
  849. vec4 colorVal;
  850. vec4_set(&colorVal, 0.0f, 0.0f, 0.0f, 1.0f);
  851. effect_setvec4(color, &colorVal);
  852. technique_begin(tech);
  853. technique_beginpass(tech, 0);
  854. gs_matrix_push();
  855. gs_matrix_identity();
  856. gs_matrix_scale3f(float(cx), float(cy), 1.0f);
  857. gs_load_vertexbuffer(box);
  858. gs_draw(GS_TRISTRIP, 0, 0);
  859. gs_matrix_pop();
  860. technique_endpass(tech);
  861. technique_end(tech);
  862. gs_load_vertexbuffer(nullptr);
  863. }
  864. void OBSBasic::RenderMain(void *data, uint32_t cx, uint32_t cy)
  865. {
  866. OBSBasic *window = static_cast<OBSBasic*>(data);
  867. obs_video_info ovi;
  868. obs_get_video_info(&ovi);
  869. window->previewCX = int(window->previewScale * float(ovi.base_width));
  870. window->previewCY = int(window->previewScale * float(ovi.base_height));
  871. gs_viewport_push();
  872. gs_projection_push();
  873. /* --------------------------------------- */
  874. gs_ortho(0.0f, float(ovi.base_width), 0.0f, float(ovi.base_height),
  875. -100.0f, 100.0f);
  876. gs_setviewport(window->previewX, window->previewY,
  877. window->previewCX, window->previewCY);
  878. window->DrawBackdrop(float(ovi.base_width), float(ovi.base_height));
  879. obs_render_main_view();
  880. gs_load_vertexbuffer(nullptr);
  881. /* --------------------------------------- */
  882. QSize previewSize = GetPixelSize(window->ui->preview);
  883. float right = float(previewSize.width()) - window->previewX;
  884. float bottom = float(previewSize.height()) - window->previewY;
  885. gs_ortho(-window->previewX, right,
  886. -window->previewY, bottom,
  887. -100.0f, 100.0f);
  888. gs_resetviewport();
  889. window->ui->preview->DrawSceneEditing();
  890. /* --------------------------------------- */
  891. gs_projection_pop();
  892. gs_viewport_pop();
  893. UNUSED_PARAMETER(cx);
  894. UNUSED_PARAMETER(cy);
  895. }
  896. void OBSBasic::SceneItemMoveUp(void *data, calldata_t params)
  897. {
  898. OBSSceneItem item = (obs_sceneitem_t)calldata_ptr(params, "item");
  899. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  900. "MoveSceneItem",
  901. Q_ARG(OBSSceneItem, OBSSceneItem(item)),
  902. Q_ARG(obs_order_movement, OBS_ORDER_MOVE_UP));
  903. }
  904. void OBSBasic::SceneItemMoveDown(void *data, calldata_t params)
  905. {
  906. OBSSceneItem item = (obs_sceneitem_t)calldata_ptr(params, "item");
  907. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  908. "MoveSceneItem",
  909. Q_ARG(OBSSceneItem, OBSSceneItem(item)),
  910. Q_ARG(obs_order_movement, OBS_ORDER_MOVE_DOWN));
  911. }
  912. void OBSBasic::SceneItemMoveTop(void *data, calldata_t params)
  913. {
  914. OBSSceneItem item = (obs_sceneitem_t)calldata_ptr(params, "item");
  915. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  916. "MoveSceneItem",
  917. Q_ARG(OBSSceneItem, OBSSceneItem(item)),
  918. Q_ARG(obs_order_movement, OBS_ORDER_MOVE_TOP));
  919. }
  920. void OBSBasic::SceneItemMoveBottom(void *data, calldata_t params)
  921. {
  922. OBSSceneItem item = (obs_sceneitem_t)calldata_ptr(params, "item");
  923. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  924. "MoveSceneItem",
  925. Q_ARG(OBSSceneItem, OBSSceneItem(item)),
  926. Q_ARG(obs_order_movement, OBS_ORDER_MOVE_BOTTOM));
  927. }
  928. /* Main class functions */
  929. obs_service_t OBSBasic::GetService()
  930. {
  931. if (!service)
  932. service = obs_service_create("rtmp_common", NULL, NULL);
  933. return service;
  934. }
  935. void OBSBasic::SetService(obs_service_t newService)
  936. {
  937. if (newService) {
  938. if (service)
  939. obs_service_destroy(service);
  940. service = newService;
  941. }
  942. }
  943. #ifdef _WIN32
  944. #define IS_WIN32 1
  945. #else
  946. #define IS_WIN32 0
  947. #endif
  948. static inline int AttemptToResetVideo(struct obs_video_info *ovi)
  949. {
  950. int ret = obs_reset_video(ovi);
  951. if (ret == OBS_VIDEO_INVALID_PARAM) {
  952. struct obs_video_info new_params = *ovi;
  953. if (new_params.window_width == 0)
  954. new_params.window_width = 512;
  955. if (new_params.window_height == 0)
  956. new_params.window_height = 512;
  957. new_params.output_width = new_params.window_width;
  958. new_params.output_height = new_params.window_height;
  959. new_params.base_width = new_params.window_width;
  960. new_params.base_height = new_params.window_height;
  961. ret = obs_reset_video(&new_params);
  962. }
  963. return ret;
  964. }
  965. int OBSBasic::ResetVideo()
  966. {
  967. struct obs_video_info ovi;
  968. int ret;
  969. GetConfigFPS(ovi.fps_num, ovi.fps_den);
  970. ovi.graphics_module = App()->GetRenderModule();
  971. ovi.base_width = (uint32_t)config_get_uint(basicConfig,
  972. "Video", "BaseCX");
  973. ovi.base_height = (uint32_t)config_get_uint(basicConfig,
  974. "Video", "BaseCY");
  975. ovi.output_width = (uint32_t)config_get_uint(basicConfig,
  976. "Video", "OutputCX");
  977. ovi.output_height = (uint32_t)config_get_uint(basicConfig,
  978. "Video", "OutputCY");
  979. ovi.output_format = VIDEO_FORMAT_NV12;
  980. ovi.adapter = 0;
  981. ovi.gpu_conversion = true;
  982. QTToGSWindow(ui->preview->winId(), ovi.window);
  983. //required to make opengl display stuff on osx(?)
  984. ResizePreview(ovi.base_width, ovi.base_height);
  985. QSize size = GetPixelSize(ui->preview);
  986. ovi.window_width = size.width();
  987. ovi.window_height = size.height();
  988. ret = AttemptToResetVideo(&ovi);
  989. if (IS_WIN32 && ret != OBS_VIDEO_SUCCESS) {
  990. /* Try OpenGL if DirectX fails on windows */
  991. if (astrcmpi(ovi.graphics_module, "libobs-opengl") != 0) {
  992. ovi.graphics_module = "libobs-opengl";
  993. ret = AttemptToResetVideo(&ovi);
  994. }
  995. }
  996. if (ret == OBS_VIDEO_SUCCESS)
  997. obs_add_draw_callback(OBSBasic::RenderMain, this);
  998. return ret;
  999. }
  1000. bool OBSBasic::ResetAudio()
  1001. {
  1002. struct audio_output_info ai;
  1003. ai.name = "Main Audio Track";
  1004. ai.format = AUDIO_FORMAT_FLOAT;
  1005. ai.samples_per_sec = config_get_uint(basicConfig, "Audio",
  1006. "SampleRate");
  1007. const char *channelSetupStr = config_get_string(basicConfig,
  1008. "Audio", "ChannelSetup");
  1009. if (strcmp(channelSetupStr, "Mono") == 0)
  1010. ai.speakers = SPEAKERS_MONO;
  1011. else
  1012. ai.speakers = SPEAKERS_STEREO;
  1013. ai.buffer_ms = config_get_uint(basicConfig, "Audio", "BufferingTime");
  1014. return obs_reset_audio(&ai);
  1015. }
  1016. void OBSBasic::ResetAudioDevice(const char *sourceId, const char *deviceName,
  1017. const char *deviceDesc, int channel)
  1018. {
  1019. const char *deviceId = config_get_string(basicConfig, "Audio",
  1020. deviceName);
  1021. obs_source_t source;
  1022. obs_data_t settings;
  1023. bool same = false;
  1024. source = obs_get_output_source(channel);
  1025. if (source) {
  1026. settings = obs_source_getsettings(source);
  1027. const char *curId = obs_data_getstring(settings, "device_id");
  1028. same = (strcmp(curId, deviceId) == 0);
  1029. obs_data_release(settings);
  1030. obs_source_release(source);
  1031. }
  1032. if (!same)
  1033. obs_set_output_source(channel, nullptr);
  1034. if (!same && strcmp(deviceId, "disabled") != 0) {
  1035. obs_data_t settings = obs_data_create();
  1036. obs_data_setstring(settings, "device_id", deviceId);
  1037. source = obs_source_create(OBS_SOURCE_TYPE_INPUT,
  1038. sourceId, deviceDesc, settings);
  1039. obs_data_release(settings);
  1040. obs_set_output_source(channel, source);
  1041. obs_source_release(source);
  1042. }
  1043. }
  1044. void OBSBasic::ResetAudioDevices()
  1045. {
  1046. ResetAudioDevice(App()->OutputAudioSource(), "DesktopDevice1",
  1047. Str("Basic.DesktopDevice1"), 1);
  1048. ResetAudioDevice(App()->OutputAudioSource(), "DesktopDevice2",
  1049. Str("Basic.DesktopDevice2"), 2);
  1050. ResetAudioDevice(App()->InputAudioSource(), "AuxDevice1",
  1051. Str("Basic.AuxDevice1"), 3);
  1052. ResetAudioDevice(App()->InputAudioSource(), "AuxDevice2",
  1053. Str("Basic.AuxDevice2"), 4);
  1054. ResetAudioDevice(App()->InputAudioSource(), "AuxDevice3",
  1055. Str("Basic.AuxDevice3"), 5);
  1056. }
  1057. void OBSBasic::ResizePreview(uint32_t cx, uint32_t cy)
  1058. {
  1059. QSize targetSize;
  1060. /* resize preview panel to fix to the top section of the window */
  1061. targetSize = GetPixelSize(ui->preview);
  1062. GetScaleAndCenterPos(int(cx), int(cy),
  1063. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  1064. targetSize.height() - PREVIEW_EDGE_SIZE * 2,
  1065. previewX, previewY, previewScale);
  1066. previewX += float(PREVIEW_EDGE_SIZE);
  1067. previewY += float(PREVIEW_EDGE_SIZE);
  1068. if (isVisible()) {
  1069. if (resizeTimer)
  1070. killTimer(resizeTimer);
  1071. resizeTimer = startTimer(100);
  1072. }
  1073. }
  1074. void OBSBasic::closeEvent(QCloseEvent *event)
  1075. {
  1076. QWidget::closeEvent(event);
  1077. if (!event->isAccepted())
  1078. return;
  1079. // remove draw callback in case our drawable surfaces go away before
  1080. // the destructor gets called
  1081. obs_remove_draw_callback(OBSBasic::RenderMain, this);
  1082. }
  1083. void OBSBasic::changeEvent(QEvent *event)
  1084. {
  1085. /* TODO */
  1086. UNUSED_PARAMETER(event);
  1087. }
  1088. void OBSBasic::resizeEvent(QResizeEvent *event)
  1089. {
  1090. struct obs_video_info ovi;
  1091. if (obs_get_video_info(&ovi))
  1092. ResizePreview(ovi.base_width, ovi.base_height);
  1093. UNUSED_PARAMETER(event);
  1094. }
  1095. void OBSBasic::timerEvent(QTimerEvent *event)
  1096. {
  1097. if (event->timerId() == resizeTimer) {
  1098. killTimer(resizeTimer);
  1099. resizeTimer = 0;
  1100. QSize size = GetPixelSize(ui->preview);
  1101. obs_resize(size.width(), size.height());
  1102. }
  1103. }
  1104. void OBSBasic::on_action_New_triggered()
  1105. {
  1106. /* TODO */
  1107. }
  1108. void OBSBasic::on_action_Open_triggered()
  1109. {
  1110. /* TODO */
  1111. }
  1112. void OBSBasic::on_action_Save_triggered()
  1113. {
  1114. /* TODO */
  1115. }
  1116. void OBSBasic::on_action_Settings_triggered()
  1117. {
  1118. OBSBasicSettings settings(this);
  1119. settings.exec();
  1120. }
  1121. void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current,
  1122. QListWidgetItem *prev)
  1123. {
  1124. obs_source_t source = NULL;
  1125. if (sceneChanging)
  1126. return;
  1127. if (current) {
  1128. obs_scene_t scene;
  1129. scene = current->data(Qt::UserRole).value<OBSScene>();
  1130. source = obs_scene_getsource(scene);
  1131. }
  1132. /* TODO: allow transitions */
  1133. obs_set_output_source(0, source);
  1134. UNUSED_PARAMETER(prev);
  1135. }
  1136. void OBSBasic::EditSceneName()
  1137. {
  1138. ui->scenes->editItem(ui->scenes->currentItem());
  1139. }
  1140. void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos)
  1141. {
  1142. QListWidgetItem *item = ui->scenes->itemAt(pos);
  1143. QMenu popup;
  1144. popup.addAction(QTStr("Add"),
  1145. this, SLOT(on_actionAddScene_triggered()));
  1146. if (item)
  1147. popup.addAction(QTStr("Remove"),
  1148. this, SLOT(RemoveSelectedScene()));
  1149. popup.exec(QCursor::pos());
  1150. }
  1151. void OBSBasic::on_actionAddScene_triggered()
  1152. {
  1153. string name;
  1154. QString format{QTStr("Basic.Main.DefaultSceneName.Text")};
  1155. int i = 1;
  1156. QString placeHolderText = format.arg(i);
  1157. obs_source_t source = nullptr;
  1158. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  1159. obs_source_release(source);
  1160. placeHolderText = format.arg(++i);
  1161. }
  1162. bool accepted = NameDialog::AskForName(this,
  1163. QTStr("Basic.Main.AddSceneDlg.Title"),
  1164. QTStr("Basic.Main.AddSceneDlg.Text"),
  1165. name,
  1166. placeHolderText);
  1167. if (accepted) {
  1168. if (name.empty()) {
  1169. QMessageBox::information(this,
  1170. QTStr("NoNameEntered"),
  1171. QTStr("NoNameEntered"));
  1172. on_actionAddScene_triggered();
  1173. return;
  1174. }
  1175. obs_source_t source = obs_get_source_by_name(name.c_str());
  1176. if (source) {
  1177. QMessageBox::information(this,
  1178. QTStr("NameExists.Title"),
  1179. QTStr("NameExists.Text"));
  1180. obs_source_release(source);
  1181. on_actionAddScene_triggered();
  1182. return;
  1183. }
  1184. obs_scene_t scene = obs_scene_create(name.c_str());
  1185. source = obs_scene_getsource(scene);
  1186. obs_add_source(source);
  1187. obs_scene_release(scene);
  1188. obs_set_output_source(0, source);
  1189. }
  1190. }
  1191. void OBSBasic::on_actionRemoveScene_triggered()
  1192. {
  1193. OBSScene scene = GetCurrentScene();
  1194. obs_source_t source = obs_scene_getsource(scene);
  1195. if (source && QueryRemoveSource(source))
  1196. obs_source_remove(source);
  1197. }
  1198. void OBSBasic::on_actionSceneProperties_triggered()
  1199. {
  1200. /* TODO */
  1201. }
  1202. void OBSBasic::on_actionSceneUp_triggered()
  1203. {
  1204. /* TODO */
  1205. }
  1206. void OBSBasic::on_actionSceneDown_triggered()
  1207. {
  1208. /* TODO */
  1209. }
  1210. void OBSBasic::on_sources_currentItemChanged(QListWidgetItem *current,
  1211. QListWidgetItem *prev)
  1212. {
  1213. auto select_one = [] (obs_scene_t scene, obs_sceneitem_t item,
  1214. void *param)
  1215. {
  1216. obs_sceneitem_t selectedItem =
  1217. *reinterpret_cast<OBSSceneItem*>(param);
  1218. obs_sceneitem_select(item, (selectedItem == item));
  1219. UNUSED_PARAMETER(scene);
  1220. return true;
  1221. };
  1222. if (!current)
  1223. return;
  1224. OBSSceneItem item = current->data(Qt::UserRole).value<OBSSceneItem>();
  1225. obs_source_t source = obs_sceneitem_getsource(item);
  1226. if ((obs_source_get_output_flags(source) & OBS_SOURCE_VIDEO) == 0)
  1227. return;
  1228. obs_scene_enum_items(GetCurrentScene(), select_one, &item);
  1229. UNUSED_PARAMETER(prev);
  1230. }
  1231. void OBSBasic::EditSceneItemName()
  1232. {
  1233. ui->sources->editItem(ui->sources->currentItem());
  1234. }
  1235. void OBSBasic::on_sources_customContextMenuRequested(const QPoint &pos)
  1236. {
  1237. QListWidgetItem *item = ui->sources->itemAt(pos);
  1238. QMenu popup;
  1239. QPointer<QMenu> addSourceMenu = CreateAddSourcePopupMenu();
  1240. if (addSourceMenu)
  1241. popup.addMenu(addSourceMenu);
  1242. if (item) {
  1243. if (addSourceMenu)
  1244. popup.addSeparator();
  1245. popup.addAction(QTStr("Rename"), this,
  1246. SLOT(EditSceneItemName()));
  1247. popup.addAction(QTStr("Remove"), this,
  1248. SLOT(on_actionRemoveSource_triggered()),
  1249. QKeySequence::Delete);
  1250. popup.addSeparator();
  1251. popup.addMenu(ui->orderMenu);
  1252. popup.addMenu(ui->transformMenu);
  1253. popup.addSeparator();
  1254. popup.addAction(QTStr("Properties"), this,
  1255. SLOT(on_actionSourceProperties_triggered()));
  1256. }
  1257. popup.exec(QCursor::pos());
  1258. }
  1259. void OBSBasic::AddSource(const char *id)
  1260. {
  1261. if (id && *id) {
  1262. OBSBasicSourceSelect sourceSelect(this, id);
  1263. sourceSelect.exec();
  1264. }
  1265. }
  1266. QMenu *OBSBasic::CreateAddSourcePopupMenu()
  1267. {
  1268. const char *type;
  1269. bool foundValues = false;
  1270. size_t idx = 0;
  1271. QMenu *popup = new QMenu(QTStr("Add"));
  1272. while (obs_enum_input_types(idx++, &type)) {
  1273. const char *name = obs_source_getdisplayname(
  1274. OBS_SOURCE_TYPE_INPUT, type);
  1275. if (strcmp(type, "scene") == 0)
  1276. continue;
  1277. QAction *popupItem = new QAction(QT_UTF8(name), this);
  1278. popupItem->setData(QT_UTF8(type));
  1279. connect(popupItem, SIGNAL(triggered(bool)),
  1280. this, SLOT(AddSourceFromAction()));
  1281. popup->addAction(popupItem);
  1282. foundValues = true;
  1283. }
  1284. if (!foundValues) {
  1285. delete popup;
  1286. popup = nullptr;
  1287. }
  1288. return popup;
  1289. }
  1290. void OBSBasic::AddSourceFromAction()
  1291. {
  1292. QAction *action = qobject_cast<QAction*>(sender());
  1293. if (!action)
  1294. return;
  1295. AddSource(QT_TO_UTF8(action->data().toString()));
  1296. }
  1297. void OBSBasic::AddSourcePopupMenu(const QPoint &pos)
  1298. {
  1299. if (!GetCurrentScene()) {
  1300. // Tell the user he needs a scene first (help beginners).
  1301. QMessageBox::information(this,
  1302. QTStr("Basic.Main.AddSourceHelp.Title"),
  1303. QTStr("Basic.Main.AddSourceHelp.Text"));
  1304. return;
  1305. }
  1306. QPointer<QMenu> popup = CreateAddSourcePopupMenu();
  1307. if (popup)
  1308. popup->exec(pos);
  1309. }
  1310. void OBSBasic::on_actionAddSource_triggered()
  1311. {
  1312. AddSourcePopupMenu(QCursor::pos());
  1313. }
  1314. void OBSBasic::on_actionRemoveSource_triggered()
  1315. {
  1316. OBSSceneItem item = GetCurrentSceneItem();
  1317. obs_source_t source = obs_sceneitem_getsource(item);
  1318. if (source && QueryRemoveSource(source))
  1319. obs_sceneitem_remove(item);
  1320. }
  1321. void OBSBasic::on_actionSourceProperties_triggered()
  1322. {
  1323. OBSSceneItem item = GetCurrentSceneItem();
  1324. OBSSource source = obs_sceneitem_getsource(item);
  1325. if (source)
  1326. CreatePropertiesWindow(source);
  1327. }
  1328. void OBSBasic::on_actionSourceUp_triggered()
  1329. {
  1330. OBSSceneItem item = GetCurrentSceneItem();
  1331. obs_sceneitem_setorder(item, OBS_ORDER_MOVE_UP);
  1332. }
  1333. void OBSBasic::on_actionSourceDown_triggered()
  1334. {
  1335. OBSSceneItem item = GetCurrentSceneItem();
  1336. obs_sceneitem_setorder(item, OBS_ORDER_MOVE_DOWN);
  1337. }
  1338. void OBSBasic::on_actionMoveUp_triggered()
  1339. {
  1340. OBSSceneItem item = GetCurrentSceneItem();
  1341. obs_sceneitem_setorder(item, OBS_ORDER_MOVE_UP);
  1342. }
  1343. void OBSBasic::on_actionMoveDown_triggered()
  1344. {
  1345. OBSSceneItem item = GetCurrentSceneItem();
  1346. obs_sceneitem_setorder(item, OBS_ORDER_MOVE_DOWN);
  1347. }
  1348. void OBSBasic::on_actionMoveToTop_triggered()
  1349. {
  1350. OBSSceneItem item = GetCurrentSceneItem();
  1351. obs_sceneitem_setorder(item, OBS_ORDER_MOVE_TOP);
  1352. }
  1353. void OBSBasic::on_actionMoveToBottom_triggered()
  1354. {
  1355. OBSSceneItem item = GetCurrentSceneItem();
  1356. obs_sceneitem_setorder(item, OBS_ORDER_MOVE_BOTTOM);
  1357. }
  1358. static char *ReadLogFile(const char *log)
  1359. {
  1360. BPtr<char> logDir(os_get_config_path("obs-studio/logs"));
  1361. string path = (char*)logDir;
  1362. path += "/";
  1363. path += log;
  1364. char *file = os_quick_read_utf8_file(path.c_str());
  1365. if (!file)
  1366. blog(LOG_WARNING, "Failed to read log file %s", path.c_str());
  1367. return file;
  1368. }
  1369. void OBSBasic::UploadLog(const char *file)
  1370. {
  1371. dstr fileString = {};
  1372. stringstream ss;
  1373. string jsonData;
  1374. dstr_move_array(&fileString, ReadLogFile(file));
  1375. if (!fileString.array)
  1376. return;
  1377. if (!*fileString.array) {
  1378. dstr_free(&fileString);
  1379. return;
  1380. }
  1381. ui->menuLogFiles->setEnabled(false);
  1382. dstr_replace(&fileString, "\\", "\\\\");
  1383. dstr_replace(&fileString, "\"", "\\\"");
  1384. dstr_replace(&fileString, "\n", "\\n");
  1385. dstr_replace(&fileString, "\r", "\\r");
  1386. dstr_replace(&fileString, "\t", "\\t");
  1387. dstr_replace(&fileString, "\t", "\\t");
  1388. dstr_replace(&fileString, "/", "\\/");
  1389. ss << "{ \"public\": false, \"description\": \"OBS " <<
  1390. App()->GetVersionString() << " log file uploaded at " <<
  1391. CurrentDateTimeString() << "\", \"files\": { \"" <<
  1392. file << "\": { \"content\": \"" <<
  1393. fileString.array << "\" } } }";
  1394. jsonData = std::move(ss.str());
  1395. logUploadPostData.setData(jsonData.c_str(), (int)jsonData.size());
  1396. QUrl url("https://api.github.com/gists");
  1397. logUploadReply = networkManager.post(QNetworkRequest(url),
  1398. &logUploadPostData);
  1399. connect(logUploadReply, SIGNAL(finished()),
  1400. this, SLOT(logUploadFinished()));
  1401. connect(logUploadReply, SIGNAL(readyRead()),
  1402. this, SLOT(logUploadRead()));
  1403. dstr_free(&fileString);
  1404. }
  1405. void OBSBasic::on_actionUploadCurrentLog_triggered()
  1406. {
  1407. UploadLog(App()->GetCurrentLog());
  1408. }
  1409. void OBSBasic::on_actionUploadLastLog_triggered()
  1410. {
  1411. UploadLog(App()->GetLastLog());
  1412. }
  1413. void OBSBasic::on_actionCheckForUpdates_triggered()
  1414. {
  1415. CheckForUpdates();
  1416. }
  1417. void OBSBasic::logUploadRead()
  1418. {
  1419. logUploadReturnData.push_back(logUploadReply->readAll());
  1420. }
  1421. void OBSBasic::logUploadFinished()
  1422. {
  1423. ui->menuLogFiles->setEnabled(true);
  1424. if (logUploadReply->error()) {
  1425. QMessageBox::information(this,
  1426. QTStr("LogReturnDialog.ErrorUploadingLog"),
  1427. logUploadReply->errorString());
  1428. return;
  1429. }
  1430. const char *jsonReply = logUploadReturnData.constData();
  1431. if (!jsonReply || !*jsonReply)
  1432. return;
  1433. obs_data_t returnData = obs_data_create_from_json(jsonReply);
  1434. QString logURL = obs_data_getstring(returnData, "html_url");
  1435. obs_data_release(returnData);
  1436. OBSLogReply logDialog(this, logURL);
  1437. logDialog.exec();
  1438. }
  1439. static void RenameListItem(QListWidget *listWidget, obs_source_t source,
  1440. const string &name)
  1441. {
  1442. const char *prevName = obs_source_getname(source);
  1443. obs_source_t foundSource = obs_get_source_by_name(name.c_str());
  1444. QListWidgetItem *listItem = listWidget->currentItem();
  1445. if (foundSource || name.compare(prevName) == 0 || name.empty()) {
  1446. listItem->setText(QT_UTF8(prevName));
  1447. obs_source_release(foundSource);
  1448. } else {
  1449. listItem->setText(QT_UTF8(name.c_str()));
  1450. obs_source_setname(source, name.c_str());
  1451. }
  1452. }
  1453. void OBSBasic::SceneNameEdited(QWidget *editor,
  1454. QAbstractItemDelegate::EndEditHint endHint)
  1455. {
  1456. OBSScene scene = GetCurrentScene();
  1457. QLineEdit *edit = qobject_cast<QLineEdit*>(editor);
  1458. string text = QT_TO_UTF8(edit->text().trimmed());
  1459. if (!scene)
  1460. return;
  1461. obs_source_t source = obs_scene_getsource(scene);
  1462. RenameListItem(ui->scenes, source, text);
  1463. UNUSED_PARAMETER(endHint);
  1464. }
  1465. void OBSBasic::SceneItemNameEdited(QWidget *editor,
  1466. QAbstractItemDelegate::EndEditHint endHint)
  1467. {
  1468. OBSSceneItem item = GetCurrentSceneItem();
  1469. QLineEdit *edit = qobject_cast<QLineEdit*>(editor);
  1470. string text = QT_TO_UTF8(edit->text().trimmed());
  1471. if (!item)
  1472. return;
  1473. obs_source_t source = obs_sceneitem_getsource(item);
  1474. RenameListItem(ui->sources, source, text);
  1475. UNUSED_PARAMETER(endHint);
  1476. }
  1477. void OBSBasic::StreamingStart()
  1478. {
  1479. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  1480. ui->streamButton->setEnabled(true);
  1481. ui->statusbar->StreamStarted(streamOutput);
  1482. }
  1483. void OBSBasic::StreamingStop(int code)
  1484. {
  1485. const char *errorMessage;
  1486. switch (code) {
  1487. case OBS_OUTPUT_BAD_PATH:
  1488. errorMessage = Str("Output.ConnectFail.BadPath");
  1489. break;
  1490. case OBS_OUTPUT_CONNECT_FAILED:
  1491. errorMessage = Str("Output.ConnectFail.ConnectFailed");
  1492. break;
  1493. case OBS_OUTPUT_INVALID_STREAM:
  1494. errorMessage = Str("Output.ConnectFail.InvalidStream");
  1495. break;
  1496. default:
  1497. case OBS_OUTPUT_ERROR:
  1498. errorMessage = Str("Output.ConnectFail.Error");
  1499. break;
  1500. case OBS_OUTPUT_DISCONNECTED:
  1501. /* doesn't happen if output is set to reconnect. note that
  1502. * reconnects are handled in the output, not in the UI */
  1503. errorMessage = Str("Output.ConnectFail.Disconnected");
  1504. }
  1505. activeRefs--;
  1506. ui->statusbar->StreamStopped();
  1507. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  1508. ui->streamButton->setEnabled(true);
  1509. if (code != OBS_OUTPUT_SUCCESS)
  1510. QMessageBox::information(this,
  1511. QTStr("Output.ConnectFail.Title"),
  1512. QT_UTF8(errorMessage));
  1513. }
  1514. void OBSBasic::RecordingStop()
  1515. {
  1516. activeRefs--;
  1517. ui->recordButton->setText(QTStr("Basic.Main.StartRecording"));
  1518. }
  1519. void OBSBasic::SetupEncoders()
  1520. {
  1521. if (activeRefs == 0) {
  1522. obs_data_t x264Settings = obs_data_create();
  1523. obs_data_t aacSettings = obs_data_create();
  1524. int videoBitrate = config_get_uint(basicConfig, "SimpleOutput",
  1525. "VBitrate");
  1526. int audioBitrate = config_get_uint(basicConfig, "SimpleOutput",
  1527. "ABitrate");
  1528. obs_data_setint(x264Settings, "bitrate", videoBitrate);
  1529. obs_data_setint(x264Settings, "buffer_size", videoBitrate);
  1530. obs_data_setbool(x264Settings, "cbr", true);
  1531. obs_data_setint(aacSettings, "bitrate", audioBitrate);
  1532. obs_encoder_update(x264, x264Settings);
  1533. obs_encoder_update(aac, aacSettings);
  1534. obs_data_release(x264Settings);
  1535. obs_data_release(aacSettings);
  1536. obs_encoder_set_video(x264, obs_video());
  1537. obs_encoder_set_audio(aac, obs_audio());
  1538. }
  1539. }
  1540. void OBSBasic::on_streamButton_clicked()
  1541. {
  1542. if (obs_output_active(streamOutput)) {
  1543. obs_output_stop(streamOutput);
  1544. } else {
  1545. SaveService();
  1546. SetupEncoders();
  1547. obs_output_set_video_encoder(streamOutput, x264);
  1548. obs_output_set_audio_encoder(streamOutput, aac);
  1549. obs_output_set_service(streamOutput, service);
  1550. bool reconnect = config_get_bool(basicConfig, "SimpleOutput",
  1551. "Reconnect");
  1552. int retryDelay = config_get_uint(basicConfig, "SimpleOutput",
  1553. "RetryDelay");
  1554. int maxRetries = config_get_uint(basicConfig, "SimpleOutput",
  1555. "MaxRetries");
  1556. if (!reconnect)
  1557. maxRetries = 0;
  1558. obs_output_set_reconnect_settings(streamOutput, maxRetries,
  1559. retryDelay);
  1560. if (obs_output_start(streamOutput)) {
  1561. activeRefs++;
  1562. ui->streamButton->setEnabled(false);
  1563. ui->streamButton->setText(
  1564. QTStr("Basic.Main.Connecting"));
  1565. }
  1566. }
  1567. }
  1568. void OBSBasic::on_recordButton_clicked()
  1569. {
  1570. if (obs_output_active(fileOutput)) {
  1571. obs_output_stop(fileOutput);
  1572. } else {
  1573. const char *path = config_get_string(basicConfig,
  1574. "SimpleOutput", "FilePath");
  1575. os_dir_t dir = path ? os_opendir(path) : nullptr;
  1576. if (!dir) {
  1577. QMessageBox::information(this,
  1578. QTStr("Output.BadPath.Title"),
  1579. QTStr("Output.BadPath.Text"));
  1580. return;
  1581. }
  1582. os_closedir(dir);
  1583. string strPath;
  1584. strPath += path;
  1585. char lastChar = strPath.back();
  1586. if (lastChar != '/' && lastChar != '\\')
  1587. strPath += "/";
  1588. strPath += GenerateTimeDateFilename("flv");
  1589. SetupEncoders();
  1590. obs_output_set_video_encoder(fileOutput, x264);
  1591. obs_output_set_audio_encoder(fileOutput, aac);
  1592. obs_data_t settings = obs_data_create();
  1593. obs_data_setstring(settings, "path", strPath.c_str());
  1594. obs_output_update(fileOutput, settings);
  1595. obs_data_release(settings);
  1596. if (obs_output_start(fileOutput)) {
  1597. activeRefs++;
  1598. ui->recordButton->setText(
  1599. QTStr("Basic.Main.StopRecording"));
  1600. }
  1601. }
  1602. }
  1603. void OBSBasic::on_settingsButton_clicked()
  1604. {
  1605. OBSBasicSettings settings(this);
  1606. settings.exec();
  1607. }
  1608. void OBSBasic::GetFPSCommon(uint32_t &num, uint32_t &den) const
  1609. {
  1610. const char *val = config_get_string(basicConfig, "Video", "FPSCommon");
  1611. if (strcmp(val, "10") == 0) {
  1612. num = 10;
  1613. den = 1;
  1614. } else if (strcmp(val, "20") == 0) {
  1615. num = 20;
  1616. den = 1;
  1617. } else if (strcmp(val, "25") == 0) {
  1618. num = 25;
  1619. den = 1;
  1620. } else if (strcmp(val, "29.97") == 0) {
  1621. num = 30000;
  1622. den = 1001;
  1623. } else if (strcmp(val, "48") == 0) {
  1624. num = 48;
  1625. den = 1;
  1626. } else if (strcmp(val, "59.94") == 0) {
  1627. num = 60000;
  1628. den = 1001;
  1629. } else if (strcmp(val, "60") == 0) {
  1630. num = 60;
  1631. den = 1;
  1632. } else {
  1633. num = 30;
  1634. den = 1;
  1635. }
  1636. }
  1637. void OBSBasic::GetFPSInteger(uint32_t &num, uint32_t &den) const
  1638. {
  1639. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSInt");
  1640. den = 1;
  1641. }
  1642. void OBSBasic::GetFPSFraction(uint32_t &num, uint32_t &den) const
  1643. {
  1644. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNum");
  1645. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSDen");
  1646. }
  1647. void OBSBasic::GetFPSNanoseconds(uint32_t &num, uint32_t &den) const
  1648. {
  1649. num = 1000000000;
  1650. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNS");
  1651. }
  1652. void OBSBasic::GetConfigFPS(uint32_t &num, uint32_t &den) const
  1653. {
  1654. uint32_t type = config_get_uint(basicConfig, "Video", "FPSType");
  1655. if (type == 1) //"Integer"
  1656. GetFPSInteger(num, den);
  1657. else if (type == 2) //"Fraction"
  1658. GetFPSFraction(num, den);
  1659. else if (false) //"Nanoseconds", currently not implemented
  1660. GetFPSNanoseconds(num, den);
  1661. else
  1662. GetFPSCommon(num, den);
  1663. }
  1664. config_t OBSBasic::Config() const
  1665. {
  1666. return basicConfig;
  1667. }
  1668. void OBSBasic::on_actionEditTransform_triggered()
  1669. {
  1670. if (transformWindow)
  1671. transformWindow->close();
  1672. transformWindow = new OBSBasicTransform(this);
  1673. transformWindow->show();
  1674. transformWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  1675. }
  1676. void OBSBasic::on_actionResetTransform_triggered()
  1677. {
  1678. auto func = [] (obs_scene_t scene, obs_sceneitem_t item, void *param)
  1679. {
  1680. if (!obs_sceneitem_selected(item))
  1681. return true;
  1682. obs_transform_info info;
  1683. vec2_set(&info.pos, 0.0f, 0.0f);
  1684. vec2_set(&info.scale, 1.0f, 1.0f);
  1685. info.rot = 0.0f;
  1686. info.alignment = OBS_ALIGN_TOP | OBS_ALIGN_LEFT;
  1687. info.bounds_type = OBS_BOUNDS_NONE;
  1688. info.bounds_alignment = OBS_ALIGN_CENTER;
  1689. vec2_set(&info.bounds, 0.0f, 0.0f);
  1690. obs_sceneitem_set_info(item, &info);
  1691. UNUSED_PARAMETER(scene);
  1692. UNUSED_PARAMETER(param);
  1693. return true;
  1694. };
  1695. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  1696. }
  1697. static void GetItemBox(obs_sceneitem_t item, vec3 &tl, vec3 &br)
  1698. {
  1699. matrix4 boxTransform;
  1700. obs_sceneitem_get_box_transform(item, &boxTransform);
  1701. vec3_set(&tl, M_INFINITE, M_INFINITE, 0.0f);
  1702. vec3_set(&br, -M_INFINITE, -M_INFINITE, 0.0f);
  1703. auto GetMinPos = [&] (float x, float y)
  1704. {
  1705. vec3 pos;
  1706. vec3_set(&pos, x, y, 0.0f);
  1707. vec3_transform(&pos, &pos, &boxTransform);
  1708. vec3_min(&tl, &tl, &pos);
  1709. vec3_max(&br, &br, &pos);
  1710. };
  1711. GetMinPos(0.0f, 0.0f);
  1712. GetMinPos(1.0f, 0.0f);
  1713. GetMinPos(0.0f, 1.0f);
  1714. GetMinPos(1.0f, 1.0f);
  1715. }
  1716. static vec3 GetItemTL(obs_sceneitem_t item)
  1717. {
  1718. vec3 tl, br;
  1719. GetItemBox(item, tl, br);
  1720. return tl;
  1721. }
  1722. static void SetItemTL(obs_sceneitem_t item, const vec3 &tl)
  1723. {
  1724. vec3 newTL;
  1725. vec2 pos;
  1726. obs_sceneitem_getpos(item, &pos);
  1727. newTL = GetItemTL(item);
  1728. pos.x += tl.x - newTL.x;
  1729. pos.y += tl.y - newTL.y;
  1730. obs_sceneitem_setpos(item, &pos);
  1731. }
  1732. static bool RotateSelectedSources(obs_scene_t scene, obs_sceneitem_t item,
  1733. void *param)
  1734. {
  1735. if (!obs_sceneitem_selected(item))
  1736. return true;
  1737. float rot = *reinterpret_cast<float*>(param);
  1738. vec3 tl = GetItemTL(item);
  1739. rot += obs_sceneitem_getrot(item);
  1740. if (rot >= 360.0f) rot -= 360.0f;
  1741. else if (rot <= -360.0f) rot += 360.0f;
  1742. obs_sceneitem_setrot(item, rot);
  1743. SetItemTL(item, tl);
  1744. UNUSED_PARAMETER(scene);
  1745. UNUSED_PARAMETER(param);
  1746. return true;
  1747. };
  1748. void OBSBasic::on_actionRotate90CW_triggered()
  1749. {
  1750. float f90CW = 90.0f;
  1751. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CW);
  1752. }
  1753. void OBSBasic::on_actionRotate90CCW_triggered()
  1754. {
  1755. float f90CCW = -90.0f;
  1756. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CCW);
  1757. }
  1758. void OBSBasic::on_actionRotate180_triggered()
  1759. {
  1760. float f180 = 180.0f;
  1761. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f180);
  1762. }
  1763. static bool MultiplySelectedItemScale(obs_scene_t scene, obs_sceneitem_t item,
  1764. void *param)
  1765. {
  1766. vec2 &mul = *reinterpret_cast<vec2*>(param);
  1767. if (!obs_sceneitem_selected(item))
  1768. return true;
  1769. vec3 tl = GetItemTL(item);
  1770. vec2 scale;
  1771. obs_sceneitem_getscale(item, &scale);
  1772. vec2_mul(&scale, &scale, &mul);
  1773. obs_sceneitem_setscale(item, &scale);
  1774. SetItemTL(item, tl);
  1775. UNUSED_PARAMETER(scene);
  1776. return true;
  1777. }
  1778. void OBSBasic::on_actionFlipHorizontal_triggered()
  1779. {
  1780. vec2 scale;
  1781. vec2_set(&scale, -1.0f, 1.0f);
  1782. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  1783. &scale);
  1784. }
  1785. void OBSBasic::on_actionFlipVertical_triggered()
  1786. {
  1787. vec2 scale;
  1788. vec2_set(&scale, 1.0f, -1.0f);
  1789. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  1790. &scale);
  1791. }
  1792. static bool CenterAlignSelectedItems(obs_scene_t scene, obs_sceneitem_t item,
  1793. void *param)
  1794. {
  1795. obs_bounds_type boundsType = *reinterpret_cast<obs_bounds_type*>(param);
  1796. if (!obs_sceneitem_selected(item))
  1797. return true;
  1798. obs_video_info ovi;
  1799. obs_get_video_info(&ovi);
  1800. obs_transform_info itemInfo;
  1801. vec2_set(&itemInfo.pos, 0.0f, 0.0f);
  1802. vec2_set(&itemInfo.scale, 1.0f, 1.0f);
  1803. itemInfo.alignment = OBS_ALIGN_LEFT | OBS_ALIGN_TOP;
  1804. itemInfo.rot = 0.0f;
  1805. vec2_set(&itemInfo.bounds,
  1806. float(ovi.base_width), float(ovi.base_height));
  1807. itemInfo.bounds_type = boundsType;
  1808. itemInfo.bounds_alignment = OBS_ALIGN_CENTER;
  1809. obs_sceneitem_set_info(item, &itemInfo);
  1810. UNUSED_PARAMETER(scene);
  1811. return true;
  1812. }
  1813. void OBSBasic::on_actionFitToScreen_triggered()
  1814. {
  1815. obs_bounds_type boundsType = OBS_BOUNDS_SCALE_INNER;
  1816. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  1817. &boundsType);
  1818. }
  1819. void OBSBasic::on_actionStretchToScreen_triggered()
  1820. {
  1821. obs_bounds_type boundsType = OBS_BOUNDS_STRETCH;
  1822. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  1823. &boundsType);
  1824. }
  1825. void OBSBasic::on_actionCenterToScreen_triggered()
  1826. {
  1827. auto func = [] (obs_scene_t scene, obs_sceneitem_t item, void *param)
  1828. {
  1829. vec3 tl, br, itemCenter, screenCenter, offset;
  1830. obs_video_info ovi;
  1831. if (!obs_sceneitem_selected(item))
  1832. return true;
  1833. obs_get_video_info(&ovi);
  1834. vec3_set(&screenCenter, float(ovi.base_width),
  1835. float(ovi.base_height), 0.0f);
  1836. vec3_mulf(&screenCenter, &screenCenter, 0.5f);
  1837. GetItemBox(item, tl, br);
  1838. vec3_sub(&itemCenter, &br, &tl);
  1839. vec3_mulf(&itemCenter, &itemCenter, 0.5f);
  1840. vec3_add(&itemCenter, &itemCenter, &tl);
  1841. vec3_sub(&offset, &screenCenter, &itemCenter);
  1842. vec3_add(&tl, &tl, &offset);
  1843. SetItemTL(item, tl);
  1844. UNUSED_PARAMETER(scene);
  1845. UNUSED_PARAMETER(param);
  1846. return true;
  1847. };
  1848. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  1849. }