window-basic-main.cpp 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336
  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_get_name(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_get_source(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_get_source(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_get_signal_handler(streamOutput),
  274. "start", OBSStartStreaming, this);
  275. signal_handler_connect(obs_output_get_signal_handler(streamOutput),
  276. "stop", OBSStopStreaming, this);
  277. signal_handler_connect(obs_output_get_signal_handler(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_get_signal_handler(), "source_add",
  371. OBSBasic::SourceAdded, this);
  372. signal_handler_connect(obs_get_signal_handler(), "source_remove",
  373. OBSBasic::SourceRemoved, this);
  374. signal_handler_connect(obs_get_signal_handler(), "channel_change",
  375. OBSBasic::ChannelChanged, this);
  376. signal_handler_connect(obs_get_signal_handler(), "source_activate",
  377. OBSBasic::SourceActivated, this);
  378. signal_handler_connect(obs_get_signal_handler(), "source_deactivate",
  379. OBSBasic::SourceDeactivated, this);
  380. signal_handler_connect(obs_get_signal_handler(), "source_rename",
  381. OBSBasic::SourceRenamed, this);
  382. }
  383. void OBSBasic::InitPrimitives()
  384. {
  385. obs_enter_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. obs_leave_graphics();
  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. obs_enter_graphics();
  463. vertexbuffer_destroy(box);
  464. vertexbuffer_destroy(circle);
  465. obs_leave_graphics();
  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_get_source(item);
  496. const char *name = obs_source_get_name(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_get_name(source);
  519. obs_scene_t scene = obs_scene_from_source(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_get_signal_handler(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_get_name(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_get_scene(item);
  553. obs_source_t source = obs_sceneitem_get_source(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_get_scene(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_get_source(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_scene_t scene = obs_scene_from_source(source);
  583. const char *name = obs_source_get_name(source);
  584. if (!scene)
  585. return;
  586. QList<QListWidgetItem*> items =
  587. ui->scenes->findItems(QT_UTF8(name), Qt::MatchExactly);
  588. if (items.count()) {
  589. sceneChanging = true;
  590. ui->scenes->setCurrentItem(items.first());
  591. sceneChanging = false;
  592. UpdateSources(scene);
  593. }
  594. }
  595. }
  596. static void RenameListValues(QListWidget *listWidget, const QString &newName,
  597. const QString &prevName)
  598. {
  599. QList<QListWidgetItem*> items =
  600. listWidget->findItems(prevName, Qt::MatchExactly);
  601. for (int i = 0; i < items.count(); i++)
  602. items[i]->setText(newName);
  603. }
  604. void OBSBasic::RenameSources(QString newName, QString prevName)
  605. {
  606. RenameListValues(ui->scenes, newName, prevName);
  607. RenameListValues(ui->sources, newName, prevName);
  608. for (size_t i = 0; i < volumes.size(); i++) {
  609. if (volumes[i]->GetName().compare(prevName) == 0)
  610. volumes[i]->SetName(newName);
  611. }
  612. }
  613. void OBSBasic::MoveSceneItem(OBSSceneItem item, obs_order_movement movement)
  614. {
  615. OBSScene scene = obs_sceneitem_get_scene(item);
  616. if (scene != GetCurrentScene())
  617. return;
  618. int curRow = ui->sources->currentRow();
  619. if (curRow == -1)
  620. return;
  621. QListWidgetItem *listItem = ui->sources->takeItem(curRow);
  622. switch (movement) {
  623. case OBS_ORDER_MOVE_UP:
  624. if (curRow > 0)
  625. curRow--;
  626. break;
  627. case OBS_ORDER_MOVE_DOWN:
  628. if (curRow < ui->sources->count())
  629. curRow++;
  630. break;
  631. case OBS_ORDER_MOVE_TOP:
  632. curRow = 0;
  633. break;
  634. case OBS_ORDER_MOVE_BOTTOM:
  635. curRow = ui->sources->count();
  636. break;
  637. }
  638. ui->sources->insertItem(curRow, listItem);
  639. ui->sources->setCurrentRow(curRow);
  640. }
  641. void OBSBasic::ActivateAudioSource(OBSSource source)
  642. {
  643. VolControl *vol = new VolControl(source);
  644. volumes.push_back(vol);
  645. ui->volumeWidgets->layout()->addWidget(vol);
  646. }
  647. void OBSBasic::DeactivateAudioSource(OBSSource source)
  648. {
  649. for (size_t i = 0; i < volumes.size(); i++) {
  650. if (volumes[i]->GetSource() == source) {
  651. delete volumes[i];
  652. volumes.erase(volumes.begin() + i);
  653. break;
  654. }
  655. }
  656. }
  657. bool OBSBasic::QueryRemoveSource(obs_source_t source)
  658. {
  659. const char *name = obs_source_get_name(source);
  660. QString text = QTStr("ConfirmRemove.Text");
  661. text.replace("$1", QT_UTF8(name));
  662. QMessageBox::StandardButton button;
  663. button = QMessageBox::question(this,
  664. QTStr("ConfirmRemove.Remove"), text);
  665. return button == QMessageBox::Yes;
  666. }
  667. #define UPDATE_CHECK_INTERVAL (60*60*24*4) /* 4 days */
  668. void OBSBasic::TimedCheckForUpdates()
  669. {
  670. long long lastUpdate = config_get_int(App()->GlobalConfig(), "General",
  671. "LastUpdateCheck");
  672. uint32_t lastVersion = config_get_int(App()->GlobalConfig(), "General",
  673. "LastVersion");
  674. if (lastVersion < LIBOBS_API_VER) {
  675. lastUpdate = 0;
  676. config_set_int(App()->GlobalConfig(), "General",
  677. "LastUpdateCheck", 0);
  678. }
  679. long long t = (long long)time(nullptr);
  680. long long secs = t - lastUpdate;
  681. if (secs > UPDATE_CHECK_INTERVAL)
  682. CheckForUpdates();
  683. }
  684. void OBSBasic::CheckForUpdates()
  685. {
  686. ui->actionCheckForUpdates->setEnabled(false);
  687. string versionString("obs-basic ");
  688. versionString += App()->GetVersionString();
  689. QNetworkRequest request;
  690. request.setUrl(QUrl("https://obsproject.com/obs2_update/basic.json"));
  691. request.setRawHeader("User-Agent", versionString.c_str());
  692. updateReply = networkManager.get(request);
  693. connect(updateReply, SIGNAL(finished()),
  694. this, SLOT(updateFileFinished()));
  695. connect(updateReply, SIGNAL(readyRead()),
  696. this, SLOT(updateFileRead()));
  697. }
  698. void OBSBasic::updateFileRead()
  699. {
  700. updateReturnData.push_back(updateReply->readAll());
  701. }
  702. #ifdef __APPLE__
  703. #define VERSION_ENTRY "mac"
  704. #elif _WIN32
  705. #define VERSION_ENTRY "windows"
  706. #else
  707. #define VERSION_ENTRY "other"
  708. #endif
  709. void OBSBasic::updateFileFinished()
  710. {
  711. ui->actionCheckForUpdates->setEnabled(true);
  712. if (updateReply->error()) {
  713. blog(LOG_WARNING, "Update check failed: %s",
  714. QT_TO_UTF8(updateReply->errorString()));
  715. return;
  716. }
  717. const char *jsonReply = updateReturnData.constData();
  718. if (!jsonReply || !*jsonReply)
  719. return;
  720. obs_data_t returnData = obs_data_create_from_json(jsonReply);
  721. obs_data_t versionData = obs_data_getobj(returnData, VERSION_ENTRY);
  722. const char *description = obs_data_getstring(returnData, "description");
  723. const char *download = obs_data_getstring(versionData, "download");
  724. if (returnData && versionData && description && download) {
  725. long major = obs_data_getint(versionData, "major");
  726. long minor = obs_data_getint(versionData, "minor");
  727. long patch = obs_data_getint(versionData, "patch");
  728. long version = MAKE_SEMANTIC_VERSION(major, minor, patch);
  729. blog(LOG_INFO, "Update check: latest version is: %ld.%ld.%ld",
  730. major, minor, patch);
  731. if (version > LIBOBS_API_VER) {
  732. QString str = QTStr("UpdateAvailable.Text");
  733. QMessageBox messageBox(this);
  734. str = str.arg(QString::number(major),
  735. QString::number(minor),
  736. QString::number(patch),
  737. download);
  738. messageBox.setWindowTitle(QTStr("UpdateAvailable"));
  739. messageBox.setTextFormat(Qt::RichText);
  740. messageBox.setText(str);
  741. messageBox.setInformativeText(QT_UTF8(description));
  742. messageBox.exec();
  743. long long t = (long long)time(nullptr);
  744. config_set_int(App()->GlobalConfig(), "General",
  745. "LastUpdateCheck", t);
  746. config_save(App()->GlobalConfig());
  747. }
  748. } else {
  749. blog(LOG_WARNING, "Bad JSON file received from server");
  750. }
  751. obs_data_release(versionData);
  752. obs_data_release(returnData);
  753. }
  754. void OBSBasic::RemoveSelectedScene()
  755. {
  756. OBSScene scene = GetCurrentScene();
  757. if (scene) {
  758. obs_source_t source = obs_scene_get_source(scene);
  759. if (QueryRemoveSource(source))
  760. obs_source_remove(source);
  761. }
  762. }
  763. void OBSBasic::RemoveSelectedSceneItem()
  764. {
  765. OBSSceneItem item = GetCurrentSceneItem();
  766. if (item) {
  767. obs_source_t source = obs_sceneitem_get_source(item);
  768. if (QueryRemoveSource(source))
  769. obs_sceneitem_remove(item);
  770. }
  771. }
  772. /* OBS Callbacks */
  773. void OBSBasic::SceneItemAdded(void *data, calldata_t params)
  774. {
  775. OBSBasic *window = static_cast<OBSBasic*>(data);
  776. obs_sceneitem_t item = (obs_sceneitem_t)calldata_ptr(params, "item");
  777. QMetaObject::invokeMethod(window, "AddSceneItem",
  778. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  779. }
  780. void OBSBasic::SceneItemRemoved(void *data, calldata_t params)
  781. {
  782. OBSBasic *window = static_cast<OBSBasic*>(data);
  783. obs_sceneitem_t item = (obs_sceneitem_t)calldata_ptr(params, "item");
  784. QMetaObject::invokeMethod(window, "RemoveSceneItem",
  785. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  786. }
  787. void OBSBasic::SourceAdded(void *data, calldata_t params)
  788. {
  789. OBSBasic *window = static_cast<OBSBasic*>(data);
  790. obs_source_t source = (obs_source_t)calldata_ptr(params, "source");
  791. if (obs_scene_from_source(source) != NULL)
  792. QMetaObject::invokeMethod(window,
  793. "AddScene",
  794. Q_ARG(OBSSource, OBSSource(source)));
  795. }
  796. void OBSBasic::SourceRemoved(void *data, calldata_t params)
  797. {
  798. obs_source_t source = (obs_source_t)calldata_ptr(params, "source");
  799. if (obs_scene_from_source(source) != NULL)
  800. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  801. "RemoveScene",
  802. Q_ARG(OBSSource, OBSSource(source)));
  803. }
  804. void OBSBasic::SourceActivated(void *data, calldata_t params)
  805. {
  806. obs_source_t source = (obs_source_t)calldata_ptr(params, "source");
  807. uint32_t flags = obs_source_get_output_flags(source);
  808. if (flags & OBS_SOURCE_AUDIO)
  809. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  810. "ActivateAudioSource",
  811. Q_ARG(OBSSource, OBSSource(source)));
  812. }
  813. void OBSBasic::SourceDeactivated(void *data, calldata_t params)
  814. {
  815. obs_source_t source = (obs_source_t)calldata_ptr(params, "source");
  816. uint32_t flags = obs_source_get_output_flags(source);
  817. if (flags & OBS_SOURCE_AUDIO)
  818. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  819. "DeactivateAudioSource",
  820. Q_ARG(OBSSource, OBSSource(source)));
  821. }
  822. void OBSBasic::SourceRenamed(void *data, calldata_t params)
  823. {
  824. const char *newName = calldata_string(params, "new_name");
  825. const char *prevName = calldata_string(params, "prev_name");
  826. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  827. "RenameSources",
  828. Q_ARG(QString, QT_UTF8(newName)),
  829. Q_ARG(QString, QT_UTF8(prevName)));
  830. }
  831. void OBSBasic::ChannelChanged(void *data, calldata_t params)
  832. {
  833. obs_source_t source = (obs_source_t)calldata_ptr(params, "source");
  834. uint32_t channel = (uint32_t)calldata_int(params, "channel");
  835. if (channel == 0)
  836. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  837. "UpdateSceneSelection",
  838. Q_ARG(OBSSource, OBSSource(source)));
  839. }
  840. void OBSBasic::DrawBackdrop(float cx, float cy)
  841. {
  842. if (!box)
  843. return;
  844. effect_t solid = obs_get_solid_effect();
  845. eparam_t color = effect_getparambyname(solid, "color");
  846. technique_t tech = effect_gettechnique(solid, "Solid");
  847. vec4 colorVal;
  848. vec4_set(&colorVal, 0.0f, 0.0f, 0.0f, 1.0f);
  849. effect_setvec4(color, &colorVal);
  850. technique_begin(tech);
  851. technique_beginpass(tech, 0);
  852. gs_matrix_push();
  853. gs_matrix_identity();
  854. gs_matrix_scale3f(float(cx), float(cy), 1.0f);
  855. gs_load_vertexbuffer(box);
  856. gs_draw(GS_TRISTRIP, 0, 0);
  857. gs_matrix_pop();
  858. technique_endpass(tech);
  859. technique_end(tech);
  860. gs_load_vertexbuffer(nullptr);
  861. }
  862. void OBSBasic::RenderMain(void *data, uint32_t cx, uint32_t cy)
  863. {
  864. OBSBasic *window = static_cast<OBSBasic*>(data);
  865. obs_video_info ovi;
  866. obs_get_video_info(&ovi);
  867. window->previewCX = int(window->previewScale * float(ovi.base_width));
  868. window->previewCY = int(window->previewScale * float(ovi.base_height));
  869. gs_viewport_push();
  870. gs_projection_push();
  871. /* --------------------------------------- */
  872. gs_ortho(0.0f, float(ovi.base_width), 0.0f, float(ovi.base_height),
  873. -100.0f, 100.0f);
  874. gs_setviewport(window->previewX, window->previewY,
  875. window->previewCX, window->previewCY);
  876. window->DrawBackdrop(float(ovi.base_width), float(ovi.base_height));
  877. obs_render_main_view();
  878. gs_load_vertexbuffer(nullptr);
  879. /* --------------------------------------- */
  880. QSize previewSize = GetPixelSize(window->ui->preview);
  881. float right = float(previewSize.width()) - window->previewX;
  882. float bottom = float(previewSize.height()) - window->previewY;
  883. gs_ortho(-window->previewX, right,
  884. -window->previewY, bottom,
  885. -100.0f, 100.0f);
  886. gs_resetviewport();
  887. window->ui->preview->DrawSceneEditing();
  888. /* --------------------------------------- */
  889. gs_projection_pop();
  890. gs_viewport_pop();
  891. UNUSED_PARAMETER(cx);
  892. UNUSED_PARAMETER(cy);
  893. }
  894. void OBSBasic::SceneItemMoveUp(void *data, calldata_t params)
  895. {
  896. OBSSceneItem item = (obs_sceneitem_t)calldata_ptr(params, "item");
  897. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  898. "MoveSceneItem",
  899. Q_ARG(OBSSceneItem, OBSSceneItem(item)),
  900. Q_ARG(obs_order_movement, OBS_ORDER_MOVE_UP));
  901. }
  902. void OBSBasic::SceneItemMoveDown(void *data, calldata_t params)
  903. {
  904. OBSSceneItem item = (obs_sceneitem_t)calldata_ptr(params, "item");
  905. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  906. "MoveSceneItem",
  907. Q_ARG(OBSSceneItem, OBSSceneItem(item)),
  908. Q_ARG(obs_order_movement, OBS_ORDER_MOVE_DOWN));
  909. }
  910. void OBSBasic::SceneItemMoveTop(void *data, calldata_t params)
  911. {
  912. OBSSceneItem item = (obs_sceneitem_t)calldata_ptr(params, "item");
  913. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  914. "MoveSceneItem",
  915. Q_ARG(OBSSceneItem, OBSSceneItem(item)),
  916. Q_ARG(obs_order_movement, OBS_ORDER_MOVE_TOP));
  917. }
  918. void OBSBasic::SceneItemMoveBottom(void *data, calldata_t params)
  919. {
  920. OBSSceneItem item = (obs_sceneitem_t)calldata_ptr(params, "item");
  921. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  922. "MoveSceneItem",
  923. Q_ARG(OBSSceneItem, OBSSceneItem(item)),
  924. Q_ARG(obs_order_movement, OBS_ORDER_MOVE_BOTTOM));
  925. }
  926. /* Main class functions */
  927. obs_service_t OBSBasic::GetService()
  928. {
  929. if (!service)
  930. service = obs_service_create("rtmp_common", NULL, NULL);
  931. return service;
  932. }
  933. void OBSBasic::SetService(obs_service_t newService)
  934. {
  935. if (newService) {
  936. if (service)
  937. obs_service_destroy(service);
  938. service = newService;
  939. }
  940. }
  941. #ifdef _WIN32
  942. #define IS_WIN32 1
  943. #else
  944. #define IS_WIN32 0
  945. #endif
  946. static inline int AttemptToResetVideo(struct obs_video_info *ovi)
  947. {
  948. int ret = obs_reset_video(ovi);
  949. if (ret == OBS_VIDEO_INVALID_PARAM) {
  950. struct obs_video_info new_params = *ovi;
  951. if (new_params.window_width == 0)
  952. new_params.window_width = 512;
  953. if (new_params.window_height == 0)
  954. new_params.window_height = 512;
  955. new_params.output_width = new_params.window_width;
  956. new_params.output_height = new_params.window_height;
  957. new_params.base_width = new_params.window_width;
  958. new_params.base_height = new_params.window_height;
  959. ret = obs_reset_video(&new_params);
  960. }
  961. return ret;
  962. }
  963. int OBSBasic::ResetVideo()
  964. {
  965. struct obs_video_info ovi;
  966. int ret;
  967. GetConfigFPS(ovi.fps_num, ovi.fps_den);
  968. ovi.graphics_module = App()->GetRenderModule();
  969. ovi.base_width = (uint32_t)config_get_uint(basicConfig,
  970. "Video", "BaseCX");
  971. ovi.base_height = (uint32_t)config_get_uint(basicConfig,
  972. "Video", "BaseCY");
  973. ovi.output_width = (uint32_t)config_get_uint(basicConfig,
  974. "Video", "OutputCX");
  975. ovi.output_height = (uint32_t)config_get_uint(basicConfig,
  976. "Video", "OutputCY");
  977. ovi.output_format = VIDEO_FORMAT_NV12;
  978. ovi.adapter = 0;
  979. ovi.gpu_conversion = true;
  980. QTToGSWindow(ui->preview->winId(), ovi.window);
  981. //required to make opengl display stuff on osx(?)
  982. ResizePreview(ovi.base_width, ovi.base_height);
  983. QSize size = GetPixelSize(ui->preview);
  984. ovi.window_width = size.width();
  985. ovi.window_height = size.height();
  986. ret = AttemptToResetVideo(&ovi);
  987. if (IS_WIN32 && ret != OBS_VIDEO_SUCCESS) {
  988. /* Try OpenGL if DirectX fails on windows */
  989. if (astrcmpi(ovi.graphics_module, "libobs-opengl") != 0) {
  990. ovi.graphics_module = "libobs-opengl";
  991. ret = AttemptToResetVideo(&ovi);
  992. }
  993. }
  994. if (ret == OBS_VIDEO_SUCCESS)
  995. obs_add_draw_callback(OBSBasic::RenderMain, this);
  996. return ret;
  997. }
  998. bool OBSBasic::ResetAudio()
  999. {
  1000. struct audio_output_info ai;
  1001. ai.name = "Main Audio Track";
  1002. ai.format = AUDIO_FORMAT_FLOAT;
  1003. ai.samples_per_sec = config_get_uint(basicConfig, "Audio",
  1004. "SampleRate");
  1005. const char *channelSetupStr = config_get_string(basicConfig,
  1006. "Audio", "ChannelSetup");
  1007. if (strcmp(channelSetupStr, "Mono") == 0)
  1008. ai.speakers = SPEAKERS_MONO;
  1009. else
  1010. ai.speakers = SPEAKERS_STEREO;
  1011. ai.buffer_ms = config_get_uint(basicConfig, "Audio", "BufferingTime");
  1012. return obs_reset_audio(&ai);
  1013. }
  1014. void OBSBasic::ResetAudioDevice(const char *sourceId, const char *deviceName,
  1015. const char *deviceDesc, int channel)
  1016. {
  1017. const char *deviceId = config_get_string(basicConfig, "Audio",
  1018. deviceName);
  1019. obs_source_t source;
  1020. obs_data_t settings;
  1021. bool same = false;
  1022. source = obs_get_output_source(channel);
  1023. if (source) {
  1024. settings = obs_source_get_settings(source);
  1025. const char *curId = obs_data_getstring(settings, "device_id");
  1026. same = (strcmp(curId, deviceId) == 0);
  1027. obs_data_release(settings);
  1028. obs_source_release(source);
  1029. }
  1030. if (!same)
  1031. obs_set_output_source(channel, nullptr);
  1032. if (!same && strcmp(deviceId, "disabled") != 0) {
  1033. obs_data_t settings = obs_data_create();
  1034. obs_data_setstring(settings, "device_id", deviceId);
  1035. source = obs_source_create(OBS_SOURCE_TYPE_INPUT,
  1036. sourceId, deviceDesc, settings);
  1037. obs_data_release(settings);
  1038. obs_set_output_source(channel, source);
  1039. obs_source_release(source);
  1040. }
  1041. }
  1042. void OBSBasic::ResetAudioDevices()
  1043. {
  1044. ResetAudioDevice(App()->OutputAudioSource(), "DesktopDevice1",
  1045. Str("Basic.DesktopDevice1"), 1);
  1046. ResetAudioDevice(App()->OutputAudioSource(), "DesktopDevice2",
  1047. Str("Basic.DesktopDevice2"), 2);
  1048. ResetAudioDevice(App()->InputAudioSource(), "AuxDevice1",
  1049. Str("Basic.AuxDevice1"), 3);
  1050. ResetAudioDevice(App()->InputAudioSource(), "AuxDevice2",
  1051. Str("Basic.AuxDevice2"), 4);
  1052. ResetAudioDevice(App()->InputAudioSource(), "AuxDevice3",
  1053. Str("Basic.AuxDevice3"), 5);
  1054. }
  1055. void OBSBasic::ResizePreview(uint32_t cx, uint32_t cy)
  1056. {
  1057. QSize targetSize;
  1058. /* resize preview panel to fix to the top section of the window */
  1059. targetSize = GetPixelSize(ui->preview);
  1060. GetScaleAndCenterPos(int(cx), int(cy),
  1061. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  1062. targetSize.height() - PREVIEW_EDGE_SIZE * 2,
  1063. previewX, previewY, previewScale);
  1064. previewX += float(PREVIEW_EDGE_SIZE);
  1065. previewY += float(PREVIEW_EDGE_SIZE);
  1066. if (isVisible()) {
  1067. if (resizeTimer)
  1068. killTimer(resizeTimer);
  1069. resizeTimer = startTimer(100);
  1070. }
  1071. }
  1072. void OBSBasic::closeEvent(QCloseEvent *event)
  1073. {
  1074. QWidget::closeEvent(event);
  1075. if (!event->isAccepted())
  1076. return;
  1077. // remove draw callback in case our drawable surfaces go away before
  1078. // the destructor gets called
  1079. obs_remove_draw_callback(OBSBasic::RenderMain, this);
  1080. }
  1081. void OBSBasic::changeEvent(QEvent *event)
  1082. {
  1083. /* TODO */
  1084. UNUSED_PARAMETER(event);
  1085. }
  1086. void OBSBasic::resizeEvent(QResizeEvent *event)
  1087. {
  1088. struct obs_video_info ovi;
  1089. if (obs_get_video_info(&ovi))
  1090. ResizePreview(ovi.base_width, ovi.base_height);
  1091. UNUSED_PARAMETER(event);
  1092. }
  1093. void OBSBasic::timerEvent(QTimerEvent *event)
  1094. {
  1095. if (event->timerId() == resizeTimer) {
  1096. killTimer(resizeTimer);
  1097. resizeTimer = 0;
  1098. QSize size = GetPixelSize(ui->preview);
  1099. obs_resize(size.width(), size.height());
  1100. }
  1101. }
  1102. void OBSBasic::on_action_New_triggered()
  1103. {
  1104. /* TODO */
  1105. }
  1106. void OBSBasic::on_action_Open_triggered()
  1107. {
  1108. /* TODO */
  1109. }
  1110. void OBSBasic::on_action_Save_triggered()
  1111. {
  1112. /* TODO */
  1113. }
  1114. void OBSBasic::on_action_Settings_triggered()
  1115. {
  1116. OBSBasicSettings settings(this);
  1117. settings.exec();
  1118. }
  1119. void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current,
  1120. QListWidgetItem *prev)
  1121. {
  1122. obs_source_t source = NULL;
  1123. if (sceneChanging)
  1124. return;
  1125. if (current) {
  1126. obs_scene_t scene;
  1127. scene = current->data(Qt::UserRole).value<OBSScene>();
  1128. source = obs_scene_get_source(scene);
  1129. }
  1130. /* TODO: allow transitions */
  1131. obs_set_output_source(0, source);
  1132. UNUSED_PARAMETER(prev);
  1133. }
  1134. void OBSBasic::EditSceneName()
  1135. {
  1136. ui->scenes->editItem(ui->scenes->currentItem());
  1137. }
  1138. void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos)
  1139. {
  1140. QListWidgetItem *item = ui->scenes->itemAt(pos);
  1141. QMenu popup;
  1142. popup.addAction(QTStr("Add"),
  1143. this, SLOT(on_actionAddScene_triggered()));
  1144. if (item)
  1145. popup.addAction(QTStr("Remove"),
  1146. this, SLOT(RemoveSelectedScene()));
  1147. popup.exec(QCursor::pos());
  1148. }
  1149. void OBSBasic::on_actionAddScene_triggered()
  1150. {
  1151. string name;
  1152. QString format{QTStr("Basic.Main.DefaultSceneName.Text")};
  1153. int i = 1;
  1154. QString placeHolderText = format.arg(i);
  1155. obs_source_t source = nullptr;
  1156. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  1157. obs_source_release(source);
  1158. placeHolderText = format.arg(++i);
  1159. }
  1160. bool accepted = NameDialog::AskForName(this,
  1161. QTStr("Basic.Main.AddSceneDlg.Title"),
  1162. QTStr("Basic.Main.AddSceneDlg.Text"),
  1163. name,
  1164. placeHolderText);
  1165. if (accepted) {
  1166. if (name.empty()) {
  1167. QMessageBox::information(this,
  1168. QTStr("NoNameEntered"),
  1169. QTStr("NoNameEntered"));
  1170. on_actionAddScene_triggered();
  1171. return;
  1172. }
  1173. obs_source_t source = obs_get_source_by_name(name.c_str());
  1174. if (source) {
  1175. QMessageBox::information(this,
  1176. QTStr("NameExists.Title"),
  1177. QTStr("NameExists.Text"));
  1178. obs_source_release(source);
  1179. on_actionAddScene_triggered();
  1180. return;
  1181. }
  1182. obs_scene_t scene = obs_scene_create(name.c_str());
  1183. source = obs_scene_get_source(scene);
  1184. obs_add_source(source);
  1185. obs_scene_release(scene);
  1186. obs_set_output_source(0, source);
  1187. }
  1188. }
  1189. void OBSBasic::on_actionRemoveScene_triggered()
  1190. {
  1191. OBSScene scene = GetCurrentScene();
  1192. obs_source_t source = obs_scene_get_source(scene);
  1193. if (source && QueryRemoveSource(source))
  1194. obs_source_remove(source);
  1195. }
  1196. void OBSBasic::on_actionSceneProperties_triggered()
  1197. {
  1198. /* TODO */
  1199. }
  1200. void OBSBasic::on_actionSceneUp_triggered()
  1201. {
  1202. /* TODO */
  1203. }
  1204. void OBSBasic::on_actionSceneDown_triggered()
  1205. {
  1206. /* TODO */
  1207. }
  1208. void OBSBasic::on_sources_currentItemChanged(QListWidgetItem *current,
  1209. QListWidgetItem *prev)
  1210. {
  1211. auto select_one = [] (obs_scene_t scene, obs_sceneitem_t item,
  1212. void *param)
  1213. {
  1214. obs_sceneitem_t selectedItem =
  1215. *reinterpret_cast<OBSSceneItem*>(param);
  1216. obs_sceneitem_select(item, (selectedItem == item));
  1217. UNUSED_PARAMETER(scene);
  1218. return true;
  1219. };
  1220. if (!current)
  1221. return;
  1222. OBSSceneItem item = current->data(Qt::UserRole).value<OBSSceneItem>();
  1223. obs_source_t source = obs_sceneitem_get_source(item);
  1224. if ((obs_source_get_output_flags(source) & OBS_SOURCE_VIDEO) == 0)
  1225. return;
  1226. obs_scene_enum_items(GetCurrentScene(), select_one, &item);
  1227. UNUSED_PARAMETER(prev);
  1228. }
  1229. void OBSBasic::EditSceneItemName()
  1230. {
  1231. ui->sources->editItem(ui->sources->currentItem());
  1232. }
  1233. void OBSBasic::on_sources_customContextMenuRequested(const QPoint &pos)
  1234. {
  1235. QListWidgetItem *item = ui->sources->itemAt(pos);
  1236. QMenu popup;
  1237. QPointer<QMenu> addSourceMenu = CreateAddSourcePopupMenu();
  1238. if (addSourceMenu)
  1239. popup.addMenu(addSourceMenu);
  1240. if (item) {
  1241. if (addSourceMenu)
  1242. popup.addSeparator();
  1243. popup.addAction(QTStr("Rename"), this,
  1244. SLOT(EditSceneItemName()));
  1245. popup.addAction(QTStr("Remove"), this,
  1246. SLOT(on_actionRemoveSource_triggered()),
  1247. QKeySequence::Delete);
  1248. popup.addSeparator();
  1249. popup.addMenu(ui->orderMenu);
  1250. popup.addMenu(ui->transformMenu);
  1251. popup.addSeparator();
  1252. popup.addAction(QTStr("Properties"), this,
  1253. SLOT(on_actionSourceProperties_triggered()));
  1254. }
  1255. popup.exec(QCursor::pos());
  1256. }
  1257. void OBSBasic::AddSource(const char *id)
  1258. {
  1259. if (id && *id) {
  1260. OBSBasicSourceSelect sourceSelect(this, id);
  1261. sourceSelect.exec();
  1262. }
  1263. }
  1264. QMenu *OBSBasic::CreateAddSourcePopupMenu()
  1265. {
  1266. const char *type;
  1267. bool foundValues = false;
  1268. size_t idx = 0;
  1269. QMenu *popup = new QMenu(QTStr("Add"));
  1270. while (obs_enum_input_types(idx++, &type)) {
  1271. const char *name = obs_source_get_display_name(
  1272. OBS_SOURCE_TYPE_INPUT, type);
  1273. if (strcmp(type, "scene") == 0)
  1274. continue;
  1275. QAction *popupItem = new QAction(QT_UTF8(name), this);
  1276. popupItem->setData(QT_UTF8(type));
  1277. connect(popupItem, SIGNAL(triggered(bool)),
  1278. this, SLOT(AddSourceFromAction()));
  1279. popup->addAction(popupItem);
  1280. foundValues = true;
  1281. }
  1282. if (!foundValues) {
  1283. delete popup;
  1284. popup = nullptr;
  1285. }
  1286. return popup;
  1287. }
  1288. void OBSBasic::AddSourceFromAction()
  1289. {
  1290. QAction *action = qobject_cast<QAction*>(sender());
  1291. if (!action)
  1292. return;
  1293. AddSource(QT_TO_UTF8(action->data().toString()));
  1294. }
  1295. void OBSBasic::AddSourcePopupMenu(const QPoint &pos)
  1296. {
  1297. if (!GetCurrentScene()) {
  1298. // Tell the user he needs a scene first (help beginners).
  1299. QMessageBox::information(this,
  1300. QTStr("Basic.Main.AddSourceHelp.Title"),
  1301. QTStr("Basic.Main.AddSourceHelp.Text"));
  1302. return;
  1303. }
  1304. QPointer<QMenu> popup = CreateAddSourcePopupMenu();
  1305. if (popup)
  1306. popup->exec(pos);
  1307. }
  1308. void OBSBasic::on_actionAddSource_triggered()
  1309. {
  1310. AddSourcePopupMenu(QCursor::pos());
  1311. }
  1312. void OBSBasic::on_actionRemoveSource_triggered()
  1313. {
  1314. OBSSceneItem item = GetCurrentSceneItem();
  1315. obs_source_t source = obs_sceneitem_get_source(item);
  1316. if (source && QueryRemoveSource(source))
  1317. obs_sceneitem_remove(item);
  1318. }
  1319. void OBSBasic::on_actionSourceProperties_triggered()
  1320. {
  1321. OBSSceneItem item = GetCurrentSceneItem();
  1322. OBSSource source = obs_sceneitem_get_source(item);
  1323. if (source)
  1324. CreatePropertiesWindow(source);
  1325. }
  1326. void OBSBasic::on_actionSourceUp_triggered()
  1327. {
  1328. OBSSceneItem item = GetCurrentSceneItem();
  1329. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  1330. }
  1331. void OBSBasic::on_actionSourceDown_triggered()
  1332. {
  1333. OBSSceneItem item = GetCurrentSceneItem();
  1334. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  1335. }
  1336. void OBSBasic::on_actionMoveUp_triggered()
  1337. {
  1338. OBSSceneItem item = GetCurrentSceneItem();
  1339. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  1340. }
  1341. void OBSBasic::on_actionMoveDown_triggered()
  1342. {
  1343. OBSSceneItem item = GetCurrentSceneItem();
  1344. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  1345. }
  1346. void OBSBasic::on_actionMoveToTop_triggered()
  1347. {
  1348. OBSSceneItem item = GetCurrentSceneItem();
  1349. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_TOP);
  1350. }
  1351. void OBSBasic::on_actionMoveToBottom_triggered()
  1352. {
  1353. OBSSceneItem item = GetCurrentSceneItem();
  1354. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_BOTTOM);
  1355. }
  1356. static char *ReadLogFile(const char *log)
  1357. {
  1358. BPtr<char> logDir(os_get_config_path("obs-studio/logs"));
  1359. string path = (char*)logDir;
  1360. path += "/";
  1361. path += log;
  1362. char *file = os_quick_read_utf8_file(path.c_str());
  1363. if (!file)
  1364. blog(LOG_WARNING, "Failed to read log file %s", path.c_str());
  1365. return file;
  1366. }
  1367. void OBSBasic::UploadLog(const char *file)
  1368. {
  1369. dstr fileString = {};
  1370. stringstream ss;
  1371. string jsonData;
  1372. dstr_move_array(&fileString, ReadLogFile(file));
  1373. if (!fileString.array)
  1374. return;
  1375. if (!*fileString.array) {
  1376. dstr_free(&fileString);
  1377. return;
  1378. }
  1379. ui->menuLogFiles->setEnabled(false);
  1380. dstr_replace(&fileString, "\\", "\\\\");
  1381. dstr_replace(&fileString, "\"", "\\\"");
  1382. dstr_replace(&fileString, "\n", "\\n");
  1383. dstr_replace(&fileString, "\r", "\\r");
  1384. dstr_replace(&fileString, "\t", "\\t");
  1385. dstr_replace(&fileString, "\t", "\\t");
  1386. dstr_replace(&fileString, "/", "\\/");
  1387. ss << "{ \"public\": false, \"description\": \"OBS " <<
  1388. App()->GetVersionString() << " log file uploaded at " <<
  1389. CurrentDateTimeString() << "\", \"files\": { \"" <<
  1390. file << "\": { \"content\": \"" <<
  1391. fileString.array << "\" } } }";
  1392. jsonData = std::move(ss.str());
  1393. logUploadPostData.setData(jsonData.c_str(), (int)jsonData.size());
  1394. QUrl url("https://api.github.com/gists");
  1395. logUploadReply = networkManager.post(QNetworkRequest(url),
  1396. &logUploadPostData);
  1397. connect(logUploadReply, SIGNAL(finished()),
  1398. this, SLOT(logUploadFinished()));
  1399. connect(logUploadReply, SIGNAL(readyRead()),
  1400. this, SLOT(logUploadRead()));
  1401. dstr_free(&fileString);
  1402. }
  1403. void OBSBasic::on_actionUploadCurrentLog_triggered()
  1404. {
  1405. UploadLog(App()->GetCurrentLog());
  1406. }
  1407. void OBSBasic::on_actionUploadLastLog_triggered()
  1408. {
  1409. UploadLog(App()->GetLastLog());
  1410. }
  1411. void OBSBasic::on_actionCheckForUpdates_triggered()
  1412. {
  1413. CheckForUpdates();
  1414. }
  1415. void OBSBasic::logUploadRead()
  1416. {
  1417. logUploadReturnData.push_back(logUploadReply->readAll());
  1418. }
  1419. void OBSBasic::logUploadFinished()
  1420. {
  1421. ui->menuLogFiles->setEnabled(true);
  1422. if (logUploadReply->error()) {
  1423. QMessageBox::information(this,
  1424. QTStr("LogReturnDialog.ErrorUploadingLog"),
  1425. logUploadReply->errorString());
  1426. return;
  1427. }
  1428. const char *jsonReply = logUploadReturnData.constData();
  1429. if (!jsonReply || !*jsonReply)
  1430. return;
  1431. obs_data_t returnData = obs_data_create_from_json(jsonReply);
  1432. QString logURL = obs_data_getstring(returnData, "html_url");
  1433. obs_data_release(returnData);
  1434. OBSLogReply logDialog(this, logURL);
  1435. logDialog.exec();
  1436. }
  1437. static void RenameListItem(QListWidget *listWidget, obs_source_t source,
  1438. const string &name)
  1439. {
  1440. const char *prevName = obs_source_get_name(source);
  1441. obs_source_t foundSource = obs_get_source_by_name(name.c_str());
  1442. QListWidgetItem *listItem = listWidget->currentItem();
  1443. if (foundSource || name.compare(prevName) == 0 || name.empty()) {
  1444. listItem->setText(QT_UTF8(prevName));
  1445. obs_source_release(foundSource);
  1446. } else {
  1447. listItem->setText(QT_UTF8(name.c_str()));
  1448. obs_source_set_name(source, name.c_str());
  1449. }
  1450. }
  1451. void OBSBasic::SceneNameEdited(QWidget *editor,
  1452. QAbstractItemDelegate::EndEditHint endHint)
  1453. {
  1454. OBSScene scene = GetCurrentScene();
  1455. QLineEdit *edit = qobject_cast<QLineEdit*>(editor);
  1456. string text = QT_TO_UTF8(edit->text().trimmed());
  1457. if (!scene)
  1458. return;
  1459. obs_source_t source = obs_scene_get_source(scene);
  1460. RenameListItem(ui->scenes, source, text);
  1461. UNUSED_PARAMETER(endHint);
  1462. }
  1463. void OBSBasic::SceneItemNameEdited(QWidget *editor,
  1464. QAbstractItemDelegate::EndEditHint endHint)
  1465. {
  1466. OBSSceneItem item = GetCurrentSceneItem();
  1467. QLineEdit *edit = qobject_cast<QLineEdit*>(editor);
  1468. string text = QT_TO_UTF8(edit->text().trimmed());
  1469. if (!item)
  1470. return;
  1471. obs_source_t source = obs_sceneitem_get_source(item);
  1472. RenameListItem(ui->sources, source, text);
  1473. UNUSED_PARAMETER(endHint);
  1474. }
  1475. void OBSBasic::StreamingStart()
  1476. {
  1477. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  1478. ui->streamButton->setEnabled(true);
  1479. ui->statusbar->StreamStarted(streamOutput);
  1480. }
  1481. void OBSBasic::StreamingStop(int code)
  1482. {
  1483. const char *errorMessage;
  1484. switch (code) {
  1485. case OBS_OUTPUT_BAD_PATH:
  1486. errorMessage = Str("Output.ConnectFail.BadPath");
  1487. break;
  1488. case OBS_OUTPUT_CONNECT_FAILED:
  1489. errorMessage = Str("Output.ConnectFail.ConnectFailed");
  1490. break;
  1491. case OBS_OUTPUT_INVALID_STREAM:
  1492. errorMessage = Str("Output.ConnectFail.InvalidStream");
  1493. break;
  1494. default:
  1495. case OBS_OUTPUT_ERROR:
  1496. errorMessage = Str("Output.ConnectFail.Error");
  1497. break;
  1498. case OBS_OUTPUT_DISCONNECTED:
  1499. /* doesn't happen if output is set to reconnect. note that
  1500. * reconnects are handled in the output, not in the UI */
  1501. errorMessage = Str("Output.ConnectFail.Disconnected");
  1502. }
  1503. activeRefs--;
  1504. ui->statusbar->StreamStopped();
  1505. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  1506. ui->streamButton->setEnabled(true);
  1507. if (code != OBS_OUTPUT_SUCCESS)
  1508. QMessageBox::information(this,
  1509. QTStr("Output.ConnectFail.Title"),
  1510. QT_UTF8(errorMessage));
  1511. }
  1512. void OBSBasic::RecordingStop()
  1513. {
  1514. activeRefs--;
  1515. ui->recordButton->setText(QTStr("Basic.Main.StartRecording"));
  1516. }
  1517. void OBSBasic::SetupEncoders()
  1518. {
  1519. if (activeRefs == 0) {
  1520. obs_data_t x264Settings = obs_data_create();
  1521. obs_data_t aacSettings = obs_data_create();
  1522. int videoBitrate = config_get_uint(basicConfig, "SimpleOutput",
  1523. "VBitrate");
  1524. int audioBitrate = config_get_uint(basicConfig, "SimpleOutput",
  1525. "ABitrate");
  1526. obs_data_setint(x264Settings, "bitrate", videoBitrate);
  1527. obs_data_setint(x264Settings, "buffer_size", videoBitrate);
  1528. obs_data_setbool(x264Settings, "cbr", true);
  1529. obs_data_setint(aacSettings, "bitrate", audioBitrate);
  1530. obs_encoder_update(x264, x264Settings);
  1531. obs_encoder_update(aac, aacSettings);
  1532. obs_data_release(x264Settings);
  1533. obs_data_release(aacSettings);
  1534. obs_encoder_set_video(x264, obs_get_video());
  1535. obs_encoder_set_audio(aac, obs_get_audio());
  1536. }
  1537. }
  1538. void OBSBasic::on_streamButton_clicked()
  1539. {
  1540. if (obs_output_active(streamOutput)) {
  1541. obs_output_stop(streamOutput);
  1542. } else {
  1543. SaveService();
  1544. SetupEncoders();
  1545. obs_output_set_video_encoder(streamOutput, x264);
  1546. obs_output_set_audio_encoder(streamOutput, aac);
  1547. obs_output_set_service(streamOutput, service);
  1548. bool reconnect = config_get_bool(basicConfig, "SimpleOutput",
  1549. "Reconnect");
  1550. int retryDelay = config_get_uint(basicConfig, "SimpleOutput",
  1551. "RetryDelay");
  1552. int maxRetries = config_get_uint(basicConfig, "SimpleOutput",
  1553. "MaxRetries");
  1554. if (!reconnect)
  1555. maxRetries = 0;
  1556. obs_output_set_reconnect_settings(streamOutput, maxRetries,
  1557. retryDelay);
  1558. if (obs_output_start(streamOutput)) {
  1559. activeRefs++;
  1560. ui->streamButton->setEnabled(false);
  1561. ui->streamButton->setText(
  1562. QTStr("Basic.Main.Connecting"));
  1563. }
  1564. }
  1565. }
  1566. void OBSBasic::on_recordButton_clicked()
  1567. {
  1568. if (obs_output_active(fileOutput)) {
  1569. obs_output_stop(fileOutput);
  1570. } else {
  1571. const char *path = config_get_string(basicConfig,
  1572. "SimpleOutput", "FilePath");
  1573. os_dir_t dir = path ? os_opendir(path) : nullptr;
  1574. if (!dir) {
  1575. QMessageBox::information(this,
  1576. QTStr("Output.BadPath.Title"),
  1577. QTStr("Output.BadPath.Text"));
  1578. return;
  1579. }
  1580. os_closedir(dir);
  1581. string strPath;
  1582. strPath += path;
  1583. char lastChar = strPath.back();
  1584. if (lastChar != '/' && lastChar != '\\')
  1585. strPath += "/";
  1586. strPath += GenerateTimeDateFilename("flv");
  1587. SetupEncoders();
  1588. obs_output_set_video_encoder(fileOutput, x264);
  1589. obs_output_set_audio_encoder(fileOutput, aac);
  1590. obs_data_t settings = obs_data_create();
  1591. obs_data_setstring(settings, "path", strPath.c_str());
  1592. obs_output_update(fileOutput, settings);
  1593. obs_data_release(settings);
  1594. if (obs_output_start(fileOutput)) {
  1595. activeRefs++;
  1596. ui->recordButton->setText(
  1597. QTStr("Basic.Main.StopRecording"));
  1598. }
  1599. }
  1600. }
  1601. void OBSBasic::on_settingsButton_clicked()
  1602. {
  1603. OBSBasicSettings settings(this);
  1604. settings.exec();
  1605. }
  1606. void OBSBasic::GetFPSCommon(uint32_t &num, uint32_t &den) const
  1607. {
  1608. const char *val = config_get_string(basicConfig, "Video", "FPSCommon");
  1609. if (strcmp(val, "10") == 0) {
  1610. num = 10;
  1611. den = 1;
  1612. } else if (strcmp(val, "20") == 0) {
  1613. num = 20;
  1614. den = 1;
  1615. } else if (strcmp(val, "25") == 0) {
  1616. num = 25;
  1617. den = 1;
  1618. } else if (strcmp(val, "29.97") == 0) {
  1619. num = 30000;
  1620. den = 1001;
  1621. } else if (strcmp(val, "48") == 0) {
  1622. num = 48;
  1623. den = 1;
  1624. } else if (strcmp(val, "59.94") == 0) {
  1625. num = 60000;
  1626. den = 1001;
  1627. } else if (strcmp(val, "60") == 0) {
  1628. num = 60;
  1629. den = 1;
  1630. } else {
  1631. num = 30;
  1632. den = 1;
  1633. }
  1634. }
  1635. void OBSBasic::GetFPSInteger(uint32_t &num, uint32_t &den) const
  1636. {
  1637. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSInt");
  1638. den = 1;
  1639. }
  1640. void OBSBasic::GetFPSFraction(uint32_t &num, uint32_t &den) const
  1641. {
  1642. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNum");
  1643. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSDen");
  1644. }
  1645. void OBSBasic::GetFPSNanoseconds(uint32_t &num, uint32_t &den) const
  1646. {
  1647. num = 1000000000;
  1648. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNS");
  1649. }
  1650. void OBSBasic::GetConfigFPS(uint32_t &num, uint32_t &den) const
  1651. {
  1652. uint32_t type = config_get_uint(basicConfig, "Video", "FPSType");
  1653. if (type == 1) //"Integer"
  1654. GetFPSInteger(num, den);
  1655. else if (type == 2) //"Fraction"
  1656. GetFPSFraction(num, den);
  1657. else if (false) //"Nanoseconds", currently not implemented
  1658. GetFPSNanoseconds(num, den);
  1659. else
  1660. GetFPSCommon(num, den);
  1661. }
  1662. config_t OBSBasic::Config() const
  1663. {
  1664. return basicConfig;
  1665. }
  1666. void OBSBasic::on_actionEditTransform_triggered()
  1667. {
  1668. if (transformWindow)
  1669. transformWindow->close();
  1670. transformWindow = new OBSBasicTransform(this);
  1671. transformWindow->show();
  1672. transformWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  1673. }
  1674. void OBSBasic::on_actionResetTransform_triggered()
  1675. {
  1676. auto func = [] (obs_scene_t scene, obs_sceneitem_t item, void *param)
  1677. {
  1678. if (!obs_sceneitem_selected(item))
  1679. return true;
  1680. obs_transform_info info;
  1681. vec2_set(&info.pos, 0.0f, 0.0f);
  1682. vec2_set(&info.scale, 1.0f, 1.0f);
  1683. info.rot = 0.0f;
  1684. info.alignment = OBS_ALIGN_TOP | OBS_ALIGN_LEFT;
  1685. info.bounds_type = OBS_BOUNDS_NONE;
  1686. info.bounds_alignment = OBS_ALIGN_CENTER;
  1687. vec2_set(&info.bounds, 0.0f, 0.0f);
  1688. obs_sceneitem_set_info(item, &info);
  1689. UNUSED_PARAMETER(scene);
  1690. UNUSED_PARAMETER(param);
  1691. return true;
  1692. };
  1693. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  1694. }
  1695. static void GetItemBox(obs_sceneitem_t item, vec3 &tl, vec3 &br)
  1696. {
  1697. matrix4 boxTransform;
  1698. obs_sceneitem_get_box_transform(item, &boxTransform);
  1699. vec3_set(&tl, M_INFINITE, M_INFINITE, 0.0f);
  1700. vec3_set(&br, -M_INFINITE, -M_INFINITE, 0.0f);
  1701. auto GetMinPos = [&] (float x, float y)
  1702. {
  1703. vec3 pos;
  1704. vec3_set(&pos, x, y, 0.0f);
  1705. vec3_transform(&pos, &pos, &boxTransform);
  1706. vec3_min(&tl, &tl, &pos);
  1707. vec3_max(&br, &br, &pos);
  1708. };
  1709. GetMinPos(0.0f, 0.0f);
  1710. GetMinPos(1.0f, 0.0f);
  1711. GetMinPos(0.0f, 1.0f);
  1712. GetMinPos(1.0f, 1.0f);
  1713. }
  1714. static vec3 GetItemTL(obs_sceneitem_t item)
  1715. {
  1716. vec3 tl, br;
  1717. GetItemBox(item, tl, br);
  1718. return tl;
  1719. }
  1720. static void SetItemTL(obs_sceneitem_t item, const vec3 &tl)
  1721. {
  1722. vec3 newTL;
  1723. vec2 pos;
  1724. obs_sceneitem_get_pos(item, &pos);
  1725. newTL = GetItemTL(item);
  1726. pos.x += tl.x - newTL.x;
  1727. pos.y += tl.y - newTL.y;
  1728. obs_sceneitem_set_pos(item, &pos);
  1729. }
  1730. static bool RotateSelectedSources(obs_scene_t scene, obs_sceneitem_t item,
  1731. void *param)
  1732. {
  1733. if (!obs_sceneitem_selected(item))
  1734. return true;
  1735. float rot = *reinterpret_cast<float*>(param);
  1736. vec3 tl = GetItemTL(item);
  1737. rot += obs_sceneitem_get_rot(item);
  1738. if (rot >= 360.0f) rot -= 360.0f;
  1739. else if (rot <= -360.0f) rot += 360.0f;
  1740. obs_sceneitem_set_rot(item, rot);
  1741. SetItemTL(item, tl);
  1742. UNUSED_PARAMETER(scene);
  1743. UNUSED_PARAMETER(param);
  1744. return true;
  1745. };
  1746. void OBSBasic::on_actionRotate90CW_triggered()
  1747. {
  1748. float f90CW = 90.0f;
  1749. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CW);
  1750. }
  1751. void OBSBasic::on_actionRotate90CCW_triggered()
  1752. {
  1753. float f90CCW = -90.0f;
  1754. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CCW);
  1755. }
  1756. void OBSBasic::on_actionRotate180_triggered()
  1757. {
  1758. float f180 = 180.0f;
  1759. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f180);
  1760. }
  1761. static bool MultiplySelectedItemScale(obs_scene_t scene, obs_sceneitem_t item,
  1762. void *param)
  1763. {
  1764. vec2 &mul = *reinterpret_cast<vec2*>(param);
  1765. if (!obs_sceneitem_selected(item))
  1766. return true;
  1767. vec3 tl = GetItemTL(item);
  1768. vec2 scale;
  1769. obs_sceneitem_get_scale(item, &scale);
  1770. vec2_mul(&scale, &scale, &mul);
  1771. obs_sceneitem_set_scale(item, &scale);
  1772. SetItemTL(item, tl);
  1773. UNUSED_PARAMETER(scene);
  1774. return true;
  1775. }
  1776. void OBSBasic::on_actionFlipHorizontal_triggered()
  1777. {
  1778. vec2 scale;
  1779. vec2_set(&scale, -1.0f, 1.0f);
  1780. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  1781. &scale);
  1782. }
  1783. void OBSBasic::on_actionFlipVertical_triggered()
  1784. {
  1785. vec2 scale;
  1786. vec2_set(&scale, 1.0f, -1.0f);
  1787. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  1788. &scale);
  1789. }
  1790. static bool CenterAlignSelectedItems(obs_scene_t scene, obs_sceneitem_t item,
  1791. void *param)
  1792. {
  1793. obs_bounds_type boundsType = *reinterpret_cast<obs_bounds_type*>(param);
  1794. if (!obs_sceneitem_selected(item))
  1795. return true;
  1796. obs_video_info ovi;
  1797. obs_get_video_info(&ovi);
  1798. obs_transform_info itemInfo;
  1799. vec2_set(&itemInfo.pos, 0.0f, 0.0f);
  1800. vec2_set(&itemInfo.scale, 1.0f, 1.0f);
  1801. itemInfo.alignment = OBS_ALIGN_LEFT | OBS_ALIGN_TOP;
  1802. itemInfo.rot = 0.0f;
  1803. vec2_set(&itemInfo.bounds,
  1804. float(ovi.base_width), float(ovi.base_height));
  1805. itemInfo.bounds_type = boundsType;
  1806. itemInfo.bounds_alignment = OBS_ALIGN_CENTER;
  1807. obs_sceneitem_set_info(item, &itemInfo);
  1808. UNUSED_PARAMETER(scene);
  1809. return true;
  1810. }
  1811. void OBSBasic::on_actionFitToScreen_triggered()
  1812. {
  1813. obs_bounds_type boundsType = OBS_BOUNDS_SCALE_INNER;
  1814. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  1815. &boundsType);
  1816. }
  1817. void OBSBasic::on_actionStretchToScreen_triggered()
  1818. {
  1819. obs_bounds_type boundsType = OBS_BOUNDS_STRETCH;
  1820. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  1821. &boundsType);
  1822. }
  1823. void OBSBasic::on_actionCenterToScreen_triggered()
  1824. {
  1825. auto func = [] (obs_scene_t scene, obs_sceneitem_t item, void *param)
  1826. {
  1827. vec3 tl, br, itemCenter, screenCenter, offset;
  1828. obs_video_info ovi;
  1829. if (!obs_sceneitem_selected(item))
  1830. return true;
  1831. obs_get_video_info(&ovi);
  1832. vec3_set(&screenCenter, float(ovi.base_width),
  1833. float(ovi.base_height), 0.0f);
  1834. vec3_mulf(&screenCenter, &screenCenter, 0.5f);
  1835. GetItemBox(item, tl, br);
  1836. vec3_sub(&itemCenter, &br, &tl);
  1837. vec3_mulf(&itemCenter, &itemCenter, 0.5f);
  1838. vec3_add(&itemCenter, &itemCenter, &tl);
  1839. vec3_sub(&offset, &screenCenter, &itemCenter);
  1840. vec3_add(&tl, &tl, &offset);
  1841. SetItemTL(item, tl);
  1842. UNUSED_PARAMETER(scene);
  1843. UNUSED_PARAMETER(param);
  1844. return true;
  1845. };
  1846. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  1847. }