window-basic-main.cpp 61 KB

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