window-basic-main.cpp 69 KB

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