window-basic-main.cpp 61 KB

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