window-basic-main.cpp 68 KB

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