1
0

window-basic-main.cpp 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680
  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. QTimer *timer = new QTimer(this);
  524. connect(timer, SIGNAL(timeout()), this, SLOT(SaveProject()));
  525. timer->start(20000);
  526. }
  527. OBSBasic::~OBSBasic()
  528. {
  529. SaveProject();
  530. /* XXX: any obs data must be released before calling obs_shutdown.
  531. * currently, we can't automate this with C++ RAII because of the
  532. * delicate nature of obs_shutdown needing to be freed before the UI
  533. * can be freed, and we have no control over the destruction order of
  534. * the Qt UI stuff, so we have to manually clear any references to
  535. * libobs. */
  536. delete cpuUsageTimer;
  537. os_cpu_usage_info_destroy(cpuUsageInfo);
  538. outputHandler.reset();
  539. if (interaction)
  540. delete interaction;
  541. if (properties)
  542. delete properties;
  543. if (transformWindow)
  544. delete transformWindow;
  545. if (advAudioWindow)
  546. delete advAudioWindow;
  547. ClearVolumeControls();
  548. ui->sources->clear();
  549. ui->scenes->clear();
  550. obs_enter_graphics();
  551. gs_vertexbuffer_destroy(box);
  552. gs_vertexbuffer_destroy(circle);
  553. obs_leave_graphics();
  554. obs_shutdown();
  555. config_set_int(App()->GlobalConfig(), "General", "LastVersion",
  556. LIBOBS_API_VER);
  557. config_set_int(App()->GlobalConfig(), "MainWindow", "cx",
  558. this->width());
  559. config_set_int(App()->GlobalConfig(), "MainWindow", "cy",
  560. this->height());
  561. config_set_int(App()->GlobalConfig(), "MainWindow", "posx",
  562. this->pos().x());
  563. config_set_int(App()->GlobalConfig(), "MainWindow", "posy",
  564. this->pos().y());
  565. config_save(App()->GlobalConfig());
  566. }
  567. void OBSBasic::SaveProject()
  568. {
  569. char savePath[512];
  570. int ret = os_get_config_path(savePath, sizeof(savePath),
  571. "obs-studio/basic/scenes.json");
  572. if (ret <= 0)
  573. return;
  574. Save(savePath);
  575. }
  576. OBSScene OBSBasic::GetCurrentScene()
  577. {
  578. QListWidgetItem *item = ui->scenes->currentItem();
  579. return item ? item->data(Qt::UserRole).value<OBSScene>() : nullptr;
  580. }
  581. OBSSceneItem OBSBasic::GetSceneItem(QListWidgetItem *item)
  582. {
  583. return item ? item->data(Qt::UserRole).value<OBSSceneItem>() : nullptr;
  584. }
  585. OBSSceneItem OBSBasic::GetCurrentSceneItem()
  586. {
  587. return GetSceneItem(ui->sources->currentItem());
  588. }
  589. void OBSBasic::UpdateSources(OBSScene scene)
  590. {
  591. ui->sources->clear();
  592. obs_scene_enum_items(scene,
  593. [] (obs_scene_t *scene, obs_sceneitem_t *item, void *p)
  594. {
  595. OBSBasic *window = static_cast<OBSBasic*>(p);
  596. window->InsertSceneItem(item);
  597. UNUSED_PARAMETER(scene);
  598. return true;
  599. }, this);
  600. }
  601. void OBSBasic::InsertSceneItem(obs_sceneitem_t *item)
  602. {
  603. obs_source_t *source = obs_sceneitem_get_source(item);
  604. const char *name = obs_source_get_name(source);
  605. QListWidgetItem *listItem = new QListWidgetItem(QT_UTF8(name));
  606. listItem->setData(Qt::UserRole,
  607. QVariant::fromValue(OBSSceneItem(item)));
  608. ui->sources->insertItem(0, listItem);
  609. ui->sources->setCurrentRow(0);
  610. /* if the source was just created, open properties dialog */
  611. if (sourceSceneRefs[source] == 0 && loaded)
  612. CreatePropertiesWindow(source);
  613. }
  614. void OBSBasic::CreateInteractionWindow(obs_source_t *source)
  615. {
  616. if (interaction)
  617. interaction->close();
  618. interaction = new OBSBasicInteraction(this, source);
  619. interaction->Init();
  620. interaction->setAttribute(Qt::WA_DeleteOnClose, true);
  621. }
  622. void OBSBasic::CreatePropertiesWindow(obs_source_t *source)
  623. {
  624. if (properties)
  625. properties->close();
  626. properties = new OBSBasicProperties(this, source);
  627. properties->Init();
  628. properties->setAttribute(Qt::WA_DeleteOnClose, true);
  629. }
  630. /* Qt callbacks for invokeMethod */
  631. void OBSBasic::AddScene(OBSSource source)
  632. {
  633. const char *name = obs_source_get_name(source);
  634. obs_scene_t *scene = obs_scene_from_source(source);
  635. QListWidgetItem *item = new QListWidgetItem(QT_UTF8(name));
  636. item->setData(Qt::UserRole, QVariant::fromValue(OBSScene(scene)));
  637. ui->scenes->addItem(item);
  638. signal_handler_t *handler = obs_source_get_signal_handler(source);
  639. signal_handler_connect(handler, "item_add",
  640. OBSBasic::SceneItemAdded, this);
  641. signal_handler_connect(handler, "item_remove",
  642. OBSBasic::SceneItemRemoved, this);
  643. signal_handler_connect(handler, "item_select",
  644. OBSBasic::SceneItemSelected, this);
  645. signal_handler_connect(handler, "item_deselect",
  646. OBSBasic::SceneItemDeselected, this);
  647. signal_handler_connect(handler, "reorder",
  648. OBSBasic::SceneReordered, this);
  649. }
  650. void OBSBasic::RemoveScene(OBSSource source)
  651. {
  652. const char *name = obs_source_get_name(source);
  653. QListWidgetItem *sel = ui->scenes->currentItem();
  654. QList<QListWidgetItem*> items = ui->scenes->findItems(QT_UTF8(name),
  655. Qt::MatchExactly);
  656. if (sel != nullptr) {
  657. if (items.contains(sel))
  658. ui->sources->clear();
  659. delete sel;
  660. }
  661. }
  662. void OBSBasic::AddSceneItem(OBSSceneItem item)
  663. {
  664. obs_scene_t *scene = obs_sceneitem_get_scene(item);
  665. obs_source_t *source = obs_sceneitem_get_source(item);
  666. if (GetCurrentScene() == scene)
  667. InsertSceneItem(item);
  668. sourceSceneRefs[source] = sourceSceneRefs[source] + 1;
  669. }
  670. void OBSBasic::RemoveSceneItem(OBSSceneItem item)
  671. {
  672. obs_scene_t *scene = obs_sceneitem_get_scene(item);
  673. if (GetCurrentScene() == scene) {
  674. for (int i = 0; i < ui->sources->count(); i++) {
  675. QListWidgetItem *listItem = ui->sources->item(i);
  676. QVariant userData = listItem->data(Qt::UserRole);
  677. if (userData.value<OBSSceneItem>() == item) {
  678. delete listItem;
  679. break;
  680. }
  681. }
  682. }
  683. obs_source_t *source = obs_sceneitem_get_source(item);
  684. int scenes = sourceSceneRefs[source] - 1;
  685. sourceSceneRefs[source] = scenes;
  686. if (scenes == 0) {
  687. obs_source_remove(source);
  688. sourceSceneRefs.erase(source);
  689. }
  690. }
  691. void OBSBasic::UpdateSceneSelection(OBSSource source)
  692. {
  693. if (source) {
  694. obs_scene_t *scene = obs_scene_from_source(source);
  695. const char *name = obs_source_get_name(source);
  696. if (!scene)
  697. return;
  698. QList<QListWidgetItem*> items =
  699. ui->scenes->findItems(QT_UTF8(name), Qt::MatchExactly);
  700. if (items.count()) {
  701. sceneChanging = true;
  702. ui->scenes->setCurrentItem(items.first());
  703. sceneChanging = false;
  704. UpdateSources(scene);
  705. }
  706. }
  707. }
  708. static void RenameListValues(QListWidget *listWidget, const QString &newName,
  709. const QString &prevName)
  710. {
  711. QList<QListWidgetItem*> items =
  712. listWidget->findItems(prevName, Qt::MatchExactly);
  713. for (int i = 0; i < items.count(); i++)
  714. items[i]->setText(newName);
  715. }
  716. void OBSBasic::RenameSources(QString newName, QString prevName)
  717. {
  718. RenameListValues(ui->scenes, newName, prevName);
  719. RenameListValues(ui->sources, newName, prevName);
  720. for (size_t i = 0; i < volumes.size(); i++) {
  721. if (volumes[i]->GetName().compare(prevName) == 0)
  722. volumes[i]->SetName(newName);
  723. }
  724. }
  725. void OBSBasic::SelectSceneItem(OBSScene scene, OBSSceneItem item, bool select)
  726. {
  727. if (!select || scene != GetCurrentScene())
  728. return;
  729. for (int i = 0; i < ui->sources->count(); i++) {
  730. QListWidgetItem *witem = ui->sources->item(i);
  731. QVariant data = witem->data(Qt::UserRole);
  732. if (!data.canConvert<OBSSceneItem>())
  733. continue;
  734. if (item != data.value<OBSSceneItem>())
  735. continue;
  736. ui->sources->setCurrentItem(witem);
  737. break;
  738. }
  739. }
  740. void OBSBasic::MoveSceneItem(OBSSceneItem item, obs_order_movement movement)
  741. {
  742. OBSScene scene = obs_sceneitem_get_scene(item);
  743. if (scene != GetCurrentScene())
  744. return;
  745. int curRow = ui->sources->currentRow();
  746. if (curRow == -1)
  747. return;
  748. QListWidgetItem *listItem = ui->sources->takeItem(curRow);
  749. switch (movement) {
  750. case OBS_ORDER_MOVE_UP:
  751. if (curRow > 0)
  752. curRow--;
  753. break;
  754. case OBS_ORDER_MOVE_DOWN:
  755. if (curRow < ui->sources->count())
  756. curRow++;
  757. break;
  758. case OBS_ORDER_MOVE_TOP:
  759. curRow = 0;
  760. break;
  761. case OBS_ORDER_MOVE_BOTTOM:
  762. curRow = ui->sources->count();
  763. break;
  764. }
  765. ui->sources->insertItem(curRow, listItem);
  766. ui->sources->setCurrentRow(curRow);
  767. }
  768. void OBSBasic::ActivateAudioSource(OBSSource source)
  769. {
  770. VolControl *vol = new VolControl(source);
  771. volumes.push_back(vol);
  772. ui->volumeWidgets->layout()->addWidget(vol);
  773. }
  774. void OBSBasic::DeactivateAudioSource(OBSSource source)
  775. {
  776. for (size_t i = 0; i < volumes.size(); i++) {
  777. if (volumes[i]->GetSource() == source) {
  778. delete volumes[i];
  779. volumes.erase(volumes.begin() + i);
  780. break;
  781. }
  782. }
  783. }
  784. bool OBSBasic::QueryRemoveSource(obs_source_t *source)
  785. {
  786. const char *name = obs_source_get_name(source);
  787. QString text = QTStr("ConfirmRemove.Text");
  788. text.replace("$1", QT_UTF8(name));
  789. QMessageBox remove_source(this);
  790. remove_source.setText(text);
  791. QAbstractButton *Yes = remove_source.addButton(QTStr("Yes"),
  792. QMessageBox::YesRole);
  793. remove_source.addButton(QTStr("No"), QMessageBox::NoRole);
  794. remove_source.setIcon(QMessageBox::Question);
  795. remove_source.setWindowTitle(QTStr("ConfirmRemove.Title"));
  796. remove_source.exec();
  797. return Yes == remove_source.clickedButton();
  798. }
  799. #define UPDATE_CHECK_INTERVAL (60*60*24*4) /* 4 days */
  800. #ifdef UPDATE_SPARKLE
  801. void init_sparkle_updater(bool update_to_undeployed);
  802. void trigger_sparkle_update();
  803. #endif
  804. void OBSBasic::TimedCheckForUpdates()
  805. {
  806. #ifdef UPDATE_SPARKLE
  807. init_sparkle_updater(config_get_bool(App()->GlobalConfig(), "General",
  808. "UpdateToUndeployed"));
  809. #else
  810. long long lastUpdate = config_get_int(App()->GlobalConfig(), "General",
  811. "LastUpdateCheck");
  812. uint32_t lastVersion = config_get_int(App()->GlobalConfig(), "General",
  813. "LastVersion");
  814. if (lastVersion < LIBOBS_API_VER) {
  815. lastUpdate = 0;
  816. config_set_int(App()->GlobalConfig(), "General",
  817. "LastUpdateCheck", 0);
  818. }
  819. long long t = (long long)time(nullptr);
  820. long long secs = t - lastUpdate;
  821. if (secs > UPDATE_CHECK_INTERVAL)
  822. CheckForUpdates();
  823. #endif
  824. }
  825. void OBSBasic::CheckForUpdates()
  826. {
  827. #ifdef UPDATE_SPARKLE
  828. trigger_sparkle_update();
  829. #else
  830. ui->actionCheckForUpdates->setEnabled(false);
  831. string versionString("obs-basic ");
  832. versionString += App()->GetVersionString();
  833. QNetworkRequest request;
  834. request.setUrl(QUrl("https://obsproject.com/obs2_update/basic.json"));
  835. request.setRawHeader("User-Agent", versionString.c_str());
  836. QNetworkReply *reply = networkManager.get(request);
  837. connect(reply, SIGNAL(finished()),
  838. this, SLOT(updateFileFinished()));
  839. #endif
  840. }
  841. #ifdef __APPLE__
  842. #define VERSION_ENTRY "mac"
  843. #elif _WIN32
  844. #define VERSION_ENTRY "windows"
  845. #else
  846. #define VERSION_ENTRY "other"
  847. #endif
  848. void OBSBasic::updateFileFinished()
  849. {
  850. ui->actionCheckForUpdates->setEnabled(true);
  851. QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
  852. if (!reply || reply->error()) {
  853. blog(LOG_WARNING, "Update check failed: %s",
  854. QT_TO_UTF8(reply->errorString()));
  855. return;
  856. }
  857. QByteArray raw = reply->readAll();
  858. if (!raw.length())
  859. return;
  860. obs_data_t *returnData = obs_data_create_from_json(raw.constData());
  861. obs_data_t *versionData = obs_data_get_obj(returnData, VERSION_ENTRY);
  862. const char *description = obs_data_get_string(returnData,
  863. "description");
  864. const char *download = obs_data_get_string(versionData, "download");
  865. if (returnData && versionData && description && download) {
  866. long major = obs_data_get_int(versionData, "major");
  867. long minor = obs_data_get_int(versionData, "minor");
  868. long patch = obs_data_get_int(versionData, "patch");
  869. long version = MAKE_SEMANTIC_VERSION(major, minor, patch);
  870. blog(LOG_INFO, "Update check: latest version is: %ld.%ld.%ld",
  871. major, minor, patch);
  872. if (version > LIBOBS_API_VER) {
  873. QString str = QTStr("UpdateAvailable.Text");
  874. QMessageBox messageBox(this);
  875. str = str.arg(QString::number(major),
  876. QString::number(minor),
  877. QString::number(patch),
  878. download);
  879. messageBox.setWindowTitle(QTStr("UpdateAvailable"));
  880. messageBox.setTextFormat(Qt::RichText);
  881. messageBox.setText(str);
  882. messageBox.setInformativeText(QT_UTF8(description));
  883. messageBox.exec();
  884. long long t = (long long)time(nullptr);
  885. config_set_int(App()->GlobalConfig(), "General",
  886. "LastUpdateCheck", t);
  887. config_save(App()->GlobalConfig());
  888. }
  889. } else {
  890. blog(LOG_WARNING, "Bad JSON file received from server");
  891. }
  892. obs_data_release(versionData);
  893. obs_data_release(returnData);
  894. reply->deleteLater();
  895. }
  896. void OBSBasic::RemoveSelectedScene()
  897. {
  898. OBSScene scene = GetCurrentScene();
  899. if (scene) {
  900. obs_source_t *source = obs_scene_get_source(scene);
  901. if (QueryRemoveSource(source))
  902. obs_source_remove(source);
  903. }
  904. }
  905. void OBSBasic::RemoveSelectedSceneItem()
  906. {
  907. OBSSceneItem item = GetCurrentSceneItem();
  908. if (item) {
  909. obs_source_t *source = obs_sceneitem_get_source(item);
  910. if (QueryRemoveSource(source))
  911. obs_sceneitem_remove(item);
  912. }
  913. }
  914. struct ReorderInfo {
  915. int idx = 0;
  916. OBSBasic *window;
  917. inline ReorderInfo(OBSBasic *window_) : window(window_) {}
  918. };
  919. void OBSBasic::ReorderSceneItem(obs_sceneitem_t *item, size_t idx)
  920. {
  921. int count = ui->sources->count();
  922. int idx_inv = count - (int)idx - 1;
  923. for (int i = 0; i < count; i++) {
  924. QListWidgetItem *listItem = ui->sources->item(i);
  925. QVariant v = listItem->data(Qt::UserRole);
  926. OBSSceneItem sceneItem = v.value<OBSSceneItem>();
  927. if (sceneItem == item) {
  928. if ((int)idx_inv != i) {
  929. bool sel = (ui->sources->currentRow() == i);
  930. listItem = ui->sources->takeItem(i);
  931. if (listItem) {
  932. ui->sources->insertItem(idx_inv,
  933. listItem);
  934. if (sel)
  935. ui->sources->setCurrentRow(
  936. idx_inv);
  937. }
  938. }
  939. break;
  940. }
  941. }
  942. }
  943. void OBSBasic::ReorderSources(OBSScene scene)
  944. {
  945. ReorderInfo info(this);
  946. if (scene != GetCurrentScene())
  947. return;
  948. obs_scene_enum_items(scene,
  949. [] (obs_scene_t*, obs_sceneitem_t *item, void *p)
  950. {
  951. ReorderInfo *info =
  952. reinterpret_cast<ReorderInfo*>(p);
  953. info->window->ReorderSceneItem(item,
  954. info->idx++);
  955. return true;
  956. }, &info);
  957. }
  958. /* OBS Callbacks */
  959. void OBSBasic::SceneReordered(void *data, calldata_t *params)
  960. {
  961. OBSBasic *window = static_cast<OBSBasic*>(data);
  962. obs_scene_t *scene = (obs_scene_t*)calldata_ptr(params, "scene");
  963. QMetaObject::invokeMethod(window, "ReorderSources",
  964. Q_ARG(OBSScene, OBSScene(scene)));
  965. }
  966. void OBSBasic::SceneItemAdded(void *data, calldata_t *params)
  967. {
  968. OBSBasic *window = static_cast<OBSBasic*>(data);
  969. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  970. QMetaObject::invokeMethod(window, "AddSceneItem",
  971. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  972. }
  973. void OBSBasic::SceneItemRemoved(void *data, calldata_t *params)
  974. {
  975. OBSBasic *window = static_cast<OBSBasic*>(data);
  976. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  977. QMetaObject::invokeMethod(window, "RemoveSceneItem",
  978. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  979. }
  980. void OBSBasic::SceneItemSelected(void *data, calldata_t *params)
  981. {
  982. OBSBasic *window = static_cast<OBSBasic*>(data);
  983. obs_scene_t *scene = (obs_scene_t*)calldata_ptr(params, "scene");
  984. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  985. QMetaObject::invokeMethod(window, "SelectSceneItem",
  986. Q_ARG(OBSScene, scene), Q_ARG(OBSSceneItem, item),
  987. Q_ARG(bool, true));
  988. }
  989. void OBSBasic::SceneItemDeselected(void *data, calldata_t *params)
  990. {
  991. OBSBasic *window = static_cast<OBSBasic*>(data);
  992. obs_scene_t *scene = (obs_scene_t*)calldata_ptr(params, "scene");
  993. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  994. QMetaObject::invokeMethod(window, "SelectSceneItem",
  995. Q_ARG(OBSScene, scene), Q_ARG(OBSSceneItem, item),
  996. Q_ARG(bool, false));
  997. }
  998. void OBSBasic::SourceAdded(void *data, calldata_t *params)
  999. {
  1000. OBSBasic *window = static_cast<OBSBasic*>(data);
  1001. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  1002. if (obs_scene_from_source(source) != NULL)
  1003. QMetaObject::invokeMethod(window,
  1004. "AddScene",
  1005. Q_ARG(OBSSource, OBSSource(source)));
  1006. }
  1007. void OBSBasic::SourceRemoved(void *data, calldata_t *params)
  1008. {
  1009. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  1010. if (obs_scene_from_source(source) != NULL)
  1011. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  1012. "RemoveScene",
  1013. Q_ARG(OBSSource, OBSSource(source)));
  1014. }
  1015. void OBSBasic::SourceActivated(void *data, calldata_t *params)
  1016. {
  1017. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  1018. uint32_t flags = obs_source_get_output_flags(source);
  1019. if (flags & OBS_SOURCE_AUDIO)
  1020. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  1021. "ActivateAudioSource",
  1022. Q_ARG(OBSSource, OBSSource(source)));
  1023. }
  1024. void OBSBasic::SourceDeactivated(void *data, calldata_t *params)
  1025. {
  1026. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  1027. uint32_t flags = obs_source_get_output_flags(source);
  1028. if (flags & OBS_SOURCE_AUDIO)
  1029. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  1030. "DeactivateAudioSource",
  1031. Q_ARG(OBSSource, OBSSource(source)));
  1032. }
  1033. void OBSBasic::SourceRenamed(void *data, calldata_t *params)
  1034. {
  1035. const char *newName = calldata_string(params, "new_name");
  1036. const char *prevName = calldata_string(params, "prev_name");
  1037. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  1038. "RenameSources",
  1039. Q_ARG(QString, QT_UTF8(newName)),
  1040. Q_ARG(QString, QT_UTF8(prevName)));
  1041. }
  1042. void OBSBasic::ChannelChanged(void *data, calldata_t *params)
  1043. {
  1044. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  1045. uint32_t channel = (uint32_t)calldata_int(params, "channel");
  1046. if (channel == 0)
  1047. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  1048. "UpdateSceneSelection",
  1049. Q_ARG(OBSSource, OBSSource(source)));
  1050. }
  1051. void OBSBasic::DrawBackdrop(float cx, float cy)
  1052. {
  1053. if (!box)
  1054. return;
  1055. gs_effect_t *solid = obs_get_solid_effect();
  1056. gs_eparam_t *color = gs_effect_get_param_by_name(solid, "color");
  1057. gs_technique_t *tech = gs_effect_get_technique(solid, "Solid");
  1058. vec4 colorVal;
  1059. vec4_set(&colorVal, 0.0f, 0.0f, 0.0f, 1.0f);
  1060. gs_effect_set_vec4(color, &colorVal);
  1061. gs_technique_begin(tech);
  1062. gs_technique_begin_pass(tech, 0);
  1063. gs_matrix_push();
  1064. gs_matrix_identity();
  1065. gs_matrix_scale3f(float(cx), float(cy), 1.0f);
  1066. gs_load_vertexbuffer(box);
  1067. gs_draw(GS_TRISTRIP, 0, 0);
  1068. gs_matrix_pop();
  1069. gs_technique_end_pass(tech);
  1070. gs_technique_end(tech);
  1071. gs_load_vertexbuffer(nullptr);
  1072. }
  1073. void OBSBasic::RenderMain(void *data, uint32_t cx, uint32_t cy)
  1074. {
  1075. OBSBasic *window = static_cast<OBSBasic*>(data);
  1076. obs_video_info ovi;
  1077. obs_get_video_info(&ovi);
  1078. window->previewCX = int(window->previewScale * float(ovi.base_width));
  1079. window->previewCY = int(window->previewScale * float(ovi.base_height));
  1080. gs_viewport_push();
  1081. gs_projection_push();
  1082. /* --------------------------------------- */
  1083. gs_ortho(0.0f, float(ovi.base_width), 0.0f, float(ovi.base_height),
  1084. -100.0f, 100.0f);
  1085. gs_set_viewport(window->previewX, window->previewY,
  1086. window->previewCX, window->previewCY);
  1087. window->DrawBackdrop(float(ovi.base_width), float(ovi.base_height));
  1088. obs_render_main_view();
  1089. gs_load_vertexbuffer(nullptr);
  1090. /* --------------------------------------- */
  1091. QSize previewSize = GetPixelSize(window->ui->preview);
  1092. float right = float(previewSize.width()) - window->previewX;
  1093. float bottom = float(previewSize.height()) - window->previewY;
  1094. gs_ortho(-window->previewX, right,
  1095. -window->previewY, bottom,
  1096. -100.0f, 100.0f);
  1097. gs_reset_viewport();
  1098. window->ui->preview->DrawSceneEditing();
  1099. /* --------------------------------------- */
  1100. gs_projection_pop();
  1101. gs_viewport_pop();
  1102. UNUSED_PARAMETER(cx);
  1103. UNUSED_PARAMETER(cy);
  1104. }
  1105. /* Main class functions */
  1106. obs_service_t *OBSBasic::GetService()
  1107. {
  1108. if (!service)
  1109. service = obs_service_create("rtmp_common", NULL, NULL);
  1110. return service;
  1111. }
  1112. void OBSBasic::SetService(obs_service_t *newService)
  1113. {
  1114. if (newService) {
  1115. if (service)
  1116. obs_service_destroy(service);
  1117. service = newService;
  1118. }
  1119. }
  1120. bool OBSBasic::StreamingActive()
  1121. {
  1122. if (!outputHandler)
  1123. return false;
  1124. return outputHandler->StreamingActive();
  1125. }
  1126. #ifdef _WIN32
  1127. #define IS_WIN32 1
  1128. #else
  1129. #define IS_WIN32 0
  1130. #endif
  1131. static inline int AttemptToResetVideo(struct obs_video_info *ovi)
  1132. {
  1133. int ret = obs_reset_video(ovi);
  1134. if (ret == OBS_VIDEO_INVALID_PARAM) {
  1135. struct obs_video_info new_params = *ovi;
  1136. if (new_params.window_width == 0)
  1137. new_params.window_width = 512;
  1138. if (new_params.window_height == 0)
  1139. new_params.window_height = 512;
  1140. new_params.output_width = new_params.window_width;
  1141. new_params.output_height = new_params.window_height;
  1142. new_params.base_width = new_params.window_width;
  1143. new_params.base_height = new_params.window_height;
  1144. ret = obs_reset_video(&new_params);
  1145. }
  1146. return ret;
  1147. }
  1148. static inline enum obs_scale_type GetScaleType(ConfigFile &basicConfig)
  1149. {
  1150. const char *scaleTypeStr = config_get_string(basicConfig,
  1151. "Video", "ScaleType");
  1152. if (astrcmpi(scaleTypeStr, "bilinear") == 0)
  1153. return OBS_SCALE_BILINEAR;
  1154. else if (astrcmpi(scaleTypeStr, "lanczos") == 0)
  1155. return OBS_SCALE_LANCZOS;
  1156. else
  1157. return OBS_SCALE_BICUBIC;
  1158. }
  1159. static inline enum video_format GetVideoFormatFromName(const char *name)
  1160. {
  1161. if (astrcmpi(name, "I420") == 0)
  1162. return VIDEO_FORMAT_I420;
  1163. else if (astrcmpi(name, "NV12") == 0)
  1164. return VIDEO_FORMAT_NV12;
  1165. #if 0 //currently unsupported
  1166. else if (astrcmpi(name, "YVYU") == 0)
  1167. return VIDEO_FORMAT_YVYU;
  1168. else if (astrcmpi(name, "YUY2") == 0)
  1169. return VIDEO_FORMAT_YUY2;
  1170. else if (astrcmpi(name, "UYVY") == 0)
  1171. return VIDEO_FORMAT_UYVY;
  1172. #endif
  1173. else
  1174. return VIDEO_FORMAT_BGRA;
  1175. }
  1176. int OBSBasic::ResetVideo()
  1177. {
  1178. struct obs_video_info ovi;
  1179. int ret;
  1180. GetConfigFPS(ovi.fps_num, ovi.fps_den);
  1181. const char *colorFormat = config_get_string(basicConfig, "Video",
  1182. "ColorFormat");
  1183. const char *colorSpace = config_get_string(basicConfig, "Video",
  1184. "ColorSpace");
  1185. const char *colorRange = config_get_string(basicConfig, "Video",
  1186. "ColorRange");
  1187. ovi.graphics_module = App()->GetRenderModule();
  1188. ovi.base_width = (uint32_t)config_get_uint(basicConfig,
  1189. "Video", "BaseCX");
  1190. ovi.base_height = (uint32_t)config_get_uint(basicConfig,
  1191. "Video", "BaseCY");
  1192. ovi.output_width = (uint32_t)config_get_uint(basicConfig,
  1193. "Video", "OutputCX");
  1194. ovi.output_height = (uint32_t)config_get_uint(basicConfig,
  1195. "Video", "OutputCY");
  1196. ovi.output_format = GetVideoFormatFromName(colorFormat);
  1197. ovi.colorspace = astrcmpi(colorSpace, "601") == 0 ?
  1198. VIDEO_CS_601 : VIDEO_CS_709;
  1199. ovi.range = astrcmpi(colorRange, "Full") == 0 ?
  1200. VIDEO_RANGE_FULL : VIDEO_RANGE_PARTIAL;
  1201. ovi.adapter = 0;
  1202. ovi.gpu_conversion = true;
  1203. ovi.scale_type = GetScaleType(basicConfig);
  1204. QTToGSWindow(ui->preview->winId(), ovi.window);
  1205. //required to make opengl display stuff on osx(?)
  1206. ResizePreview(ovi.base_width, ovi.base_height);
  1207. QSize size = GetPixelSize(ui->preview);
  1208. ovi.window_width = size.width();
  1209. ovi.window_height = size.height();
  1210. ret = AttemptToResetVideo(&ovi);
  1211. if (IS_WIN32 && ret != OBS_VIDEO_SUCCESS) {
  1212. /* Try OpenGL if DirectX fails on windows */
  1213. if (astrcmpi(ovi.graphics_module, DL_OPENGL) != 0) {
  1214. blog(LOG_WARNING, "Failed to initialize obs video (%d) "
  1215. "with graphics_module='%s', retrying "
  1216. "with graphics_module='%s'",
  1217. ret, ovi.graphics_module,
  1218. DL_OPENGL);
  1219. ovi.graphics_module = DL_OPENGL;
  1220. ret = AttemptToResetVideo(&ovi);
  1221. }
  1222. }
  1223. if (ret == OBS_VIDEO_SUCCESS)
  1224. obs_add_draw_callback(OBSBasic::RenderMain, this);
  1225. return ret;
  1226. }
  1227. bool OBSBasic::ResetAudio()
  1228. {
  1229. struct obs_audio_info ai;
  1230. ai.samples_per_sec = config_get_uint(basicConfig, "Audio",
  1231. "SampleRate");
  1232. const char *channelSetupStr = config_get_string(basicConfig,
  1233. "Audio", "ChannelSetup");
  1234. if (strcmp(channelSetupStr, "Mono") == 0)
  1235. ai.speakers = SPEAKERS_MONO;
  1236. else
  1237. ai.speakers = SPEAKERS_STEREO;
  1238. ai.buffer_ms = config_get_uint(basicConfig, "Audio", "BufferingTime");
  1239. return obs_reset_audio(&ai);
  1240. }
  1241. void OBSBasic::ResetAudioDevice(const char *sourceId, const char *deviceName,
  1242. const char *deviceDesc, int channel)
  1243. {
  1244. const char *deviceId = config_get_string(basicConfig, "Audio",
  1245. deviceName);
  1246. obs_source_t *source;
  1247. obs_data_t *settings;
  1248. bool same = false;
  1249. source = obs_get_output_source(channel);
  1250. if (source) {
  1251. settings = obs_source_get_settings(source);
  1252. const char *curId = obs_data_get_string(settings, "device_id");
  1253. same = (strcmp(curId, deviceId) == 0);
  1254. obs_data_release(settings);
  1255. obs_source_release(source);
  1256. }
  1257. if (!same)
  1258. obs_set_output_source(channel, nullptr);
  1259. if (!same && strcmp(deviceId, "disabled") != 0) {
  1260. obs_data_t *settings = obs_data_create();
  1261. obs_data_set_string(settings, "device_id", deviceId);
  1262. source = obs_source_create(OBS_SOURCE_TYPE_INPUT,
  1263. sourceId, deviceDesc, settings);
  1264. obs_data_release(settings);
  1265. obs_set_output_source(channel, source);
  1266. obs_source_release(source);
  1267. }
  1268. }
  1269. void OBSBasic::ResetAudioDevices()
  1270. {
  1271. ResetAudioDevice(App()->OutputAudioSource(), "DesktopDevice1",
  1272. Str("Basic.DesktopDevice1"), 1);
  1273. ResetAudioDevice(App()->OutputAudioSource(), "DesktopDevice2",
  1274. Str("Basic.DesktopDevice2"), 2);
  1275. ResetAudioDevice(App()->InputAudioSource(), "AuxDevice1",
  1276. Str("Basic.AuxDevice1"), 3);
  1277. ResetAudioDevice(App()->InputAudioSource(), "AuxDevice2",
  1278. Str("Basic.AuxDevice2"), 4);
  1279. ResetAudioDevice(App()->InputAudioSource(), "AuxDevice3",
  1280. Str("Basic.AuxDevice3"), 5);
  1281. }
  1282. void OBSBasic::ResizePreview(uint32_t cx, uint32_t cy)
  1283. {
  1284. QSize targetSize;
  1285. /* resize preview panel to fix to the top section of the window */
  1286. targetSize = GetPixelSize(ui->preview);
  1287. GetScaleAndCenterPos(int(cx), int(cy),
  1288. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  1289. targetSize.height() - PREVIEW_EDGE_SIZE * 2,
  1290. previewX, previewY, previewScale);
  1291. previewX += float(PREVIEW_EDGE_SIZE);
  1292. previewY += float(PREVIEW_EDGE_SIZE);
  1293. if (isVisible()) {
  1294. if (resizeTimer)
  1295. killTimer(resizeTimer);
  1296. resizeTimer = startTimer(100);
  1297. }
  1298. }
  1299. void OBSBasic::closeEvent(QCloseEvent *event)
  1300. {
  1301. if (outputHandler && outputHandler->Active()) {
  1302. QMessageBox::StandardButton button = QMessageBox::question(
  1303. this, QTStr("ConfirmExit.Title"),
  1304. QTStr("ConfirmExit.Text"));
  1305. if (button == QMessageBox::No) {
  1306. event->ignore();
  1307. return;
  1308. }
  1309. }
  1310. QWidget::closeEvent(event);
  1311. if (!event->isAccepted())
  1312. return;
  1313. /* Check all child dialogs and ensure they run their proper closeEvent
  1314. * methods before exiting the application. Otherwise Qt doesn't send
  1315. * the proper QCloseEvent messages. */
  1316. QList<QDialog*> childDialogs = this->findChildren<QDialog *>();
  1317. if (!childDialogs.isEmpty()) {
  1318. for (int i = 0; i < childDialogs.size(); ++i) {
  1319. childDialogs.at(i)->close();
  1320. }
  1321. }
  1322. // remove draw callback in case our drawable surfaces go away before
  1323. // the destructor gets called
  1324. obs_remove_draw_callback(OBSBasic::RenderMain, this);
  1325. }
  1326. void OBSBasic::changeEvent(QEvent *event)
  1327. {
  1328. /* TODO */
  1329. UNUSED_PARAMETER(event);
  1330. }
  1331. void OBSBasic::resizeEvent(QResizeEvent *event)
  1332. {
  1333. struct obs_video_info ovi;
  1334. if (obs_get_video_info(&ovi))
  1335. ResizePreview(ovi.base_width, ovi.base_height);
  1336. UNUSED_PARAMETER(event);
  1337. }
  1338. void OBSBasic::timerEvent(QTimerEvent *event)
  1339. {
  1340. if (event->timerId() == resizeTimer) {
  1341. killTimer(resizeTimer);
  1342. resizeTimer = 0;
  1343. QSize size = GetPixelSize(ui->preview);
  1344. obs_resize(size.width(), size.height());
  1345. }
  1346. }
  1347. void OBSBasic::on_action_New_triggered()
  1348. {
  1349. /* TODO */
  1350. }
  1351. void OBSBasic::on_action_Open_triggered()
  1352. {
  1353. /* TODO */
  1354. }
  1355. void OBSBasic::on_action_Save_triggered()
  1356. {
  1357. /* TODO */
  1358. }
  1359. void OBSBasic::on_actionShow_Recordings_triggered()
  1360. {
  1361. const char *path = config_get_string(basicConfig,
  1362. "SimpleOutput", "FilePath");
  1363. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  1364. }
  1365. void OBSBasic::on_actionRemux_triggered()
  1366. {
  1367. const char *path = config_get_string(basicConfig,
  1368. "SimpleOutput", "FilePath");
  1369. OBSRemux remux(path, this);
  1370. remux.exec();
  1371. }
  1372. void OBSBasic::on_action_Settings_triggered()
  1373. {
  1374. OBSBasicSettings settings(this);
  1375. settings.exec();
  1376. }
  1377. void OBSBasic::on_actionAdvAudioProperties_triggered()
  1378. {
  1379. if (advAudioWindow != nullptr) {
  1380. advAudioWindow->raise();
  1381. return;
  1382. }
  1383. advAudioWindow = new OBSBasicAdvAudio(this);
  1384. advAudioWindow->show();
  1385. advAudioWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  1386. connect(advAudioWindow, SIGNAL(destroyed()),
  1387. this, SLOT(on_advAudioProps_destroyed()));
  1388. }
  1389. void OBSBasic::on_advAudioProps_clicked()
  1390. {
  1391. on_actionAdvAudioProperties_triggered();
  1392. }
  1393. void OBSBasic::on_advAudioProps_destroyed()
  1394. {
  1395. advAudioWindow = nullptr;
  1396. }
  1397. void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current,
  1398. QListWidgetItem *prev)
  1399. {
  1400. obs_source_t *source = NULL;
  1401. if (sceneChanging)
  1402. return;
  1403. if (current) {
  1404. obs_scene_t *scene;
  1405. scene = current->data(Qt::UserRole).value<OBSScene>();
  1406. source = obs_scene_get_source(scene);
  1407. }
  1408. /* TODO: allow transitions */
  1409. obs_set_output_source(0, source);
  1410. UNUSED_PARAMETER(prev);
  1411. }
  1412. void OBSBasic::EditSceneName()
  1413. {
  1414. QListWidgetItem *item = ui->scenes->currentItem();
  1415. Qt::ItemFlags flags = item->flags();
  1416. item->setFlags(flags | Qt::ItemIsEditable);
  1417. ui->scenes->editItem(item);
  1418. item->setFlags(flags);
  1419. }
  1420. void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos)
  1421. {
  1422. QListWidgetItem *item = ui->scenes->itemAt(pos);
  1423. QMenu popup(this);
  1424. popup.addAction(QTStr("Add"),
  1425. this, SLOT(on_actionAddScene_triggered()));
  1426. if (item) {
  1427. popup.addSeparator();
  1428. popup.addAction(QTStr("Rename"),
  1429. this, SLOT(EditSceneName()));
  1430. popup.addAction(QTStr("Remove"),
  1431. this, SLOT(RemoveSelectedScene()),
  1432. DeleteKeys.front());
  1433. }
  1434. popup.exec(QCursor::pos());
  1435. }
  1436. void OBSBasic::on_actionAddScene_triggered()
  1437. {
  1438. string name;
  1439. QString format{QTStr("Basic.Main.DefaultSceneName.Text")};
  1440. int i = 1;
  1441. QString placeHolderText = format.arg(i);
  1442. obs_source_t *source = nullptr;
  1443. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  1444. obs_source_release(source);
  1445. placeHolderText = format.arg(++i);
  1446. }
  1447. bool accepted = NameDialog::AskForName(this,
  1448. QTStr("Basic.Main.AddSceneDlg.Title"),
  1449. QTStr("Basic.Main.AddSceneDlg.Text"),
  1450. name,
  1451. placeHolderText);
  1452. if (accepted) {
  1453. if (name.empty()) {
  1454. QMessageBox::information(this,
  1455. QTStr("NoNameEntered.Title"),
  1456. QTStr("NoNameEntered.Text"));
  1457. on_actionAddScene_triggered();
  1458. return;
  1459. }
  1460. obs_source_t *source = obs_get_source_by_name(name.c_str());
  1461. if (source) {
  1462. QMessageBox::information(this,
  1463. QTStr("NameExists.Title"),
  1464. QTStr("NameExists.Text"));
  1465. obs_source_release(source);
  1466. on_actionAddScene_triggered();
  1467. return;
  1468. }
  1469. obs_scene_t *scene = obs_scene_create(name.c_str());
  1470. source = obs_scene_get_source(scene);
  1471. obs_add_source(source);
  1472. obs_scene_release(scene);
  1473. obs_set_output_source(0, source);
  1474. }
  1475. }
  1476. void OBSBasic::on_actionRemoveScene_triggered()
  1477. {
  1478. OBSScene scene = GetCurrentScene();
  1479. obs_source_t *source = obs_scene_get_source(scene);
  1480. if (source && QueryRemoveSource(source))
  1481. obs_source_remove(source);
  1482. }
  1483. void OBSBasic::on_actionSceneProperties_triggered()
  1484. {
  1485. /* TODO */
  1486. }
  1487. void OBSBasic::on_actionSceneUp_triggered()
  1488. {
  1489. /* TODO */
  1490. }
  1491. void OBSBasic::on_actionSceneDown_triggered()
  1492. {
  1493. /* TODO */
  1494. }
  1495. void OBSBasic::on_sources_currentItemChanged(QListWidgetItem *current,
  1496. QListWidgetItem *prev)
  1497. {
  1498. auto select_one = [] (obs_scene_t *scene, obs_sceneitem_t *item,
  1499. void *param)
  1500. {
  1501. obs_sceneitem_t *selectedItem =
  1502. *reinterpret_cast<OBSSceneItem*>(param);
  1503. obs_sceneitem_select(item, (selectedItem == item));
  1504. UNUSED_PARAMETER(scene);
  1505. return true;
  1506. };
  1507. if (!current)
  1508. return;
  1509. OBSSceneItem item = current->data(Qt::UserRole).value<OBSSceneItem>();
  1510. obs_source_t *source = obs_sceneitem_get_source(item);
  1511. if ((obs_source_get_output_flags(source) & OBS_SOURCE_VIDEO) == 0)
  1512. return;
  1513. obs_scene_enum_items(GetCurrentScene(), select_one, &item);
  1514. UNUSED_PARAMETER(prev);
  1515. }
  1516. void OBSBasic::EditSceneItemName()
  1517. {
  1518. QListWidgetItem *item = ui->sources->currentItem();
  1519. Qt::ItemFlags flags = item->flags();
  1520. item->setFlags(flags | Qt::ItemIsEditable);
  1521. ui->sources->editItem(item);
  1522. item->setFlags(flags);
  1523. }
  1524. void OBSBasic::on_sources_customContextMenuRequested(const QPoint &pos)
  1525. {
  1526. QListWidgetItem *item = ui->sources->itemAt(pos);
  1527. QMenu popup(this);
  1528. QPointer<QMenu> addSourceMenu = CreateAddSourcePopupMenu();
  1529. if (addSourceMenu)
  1530. popup.addMenu(addSourceMenu);
  1531. if (item) {
  1532. if (addSourceMenu)
  1533. popup.addSeparator();
  1534. OBSSceneItem sceneItem = GetSceneItem(item);
  1535. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  1536. QAction *action;
  1537. popup.addAction(QTStr("Rename"), this,
  1538. SLOT(EditSceneItemName()));
  1539. popup.addAction(QTStr("Remove"), this,
  1540. SLOT(on_actionRemoveSource_triggered()),
  1541. DeleteKeys.front());
  1542. popup.addSeparator();
  1543. popup.addMenu(ui->orderMenu);
  1544. popup.addMenu(ui->transformMenu);
  1545. popup.addSeparator();
  1546. action = popup.addAction(QTStr("Interact"), this,
  1547. SLOT(on_actionInteract_triggered()));
  1548. action->setEnabled(obs_source_get_output_flags(source) &
  1549. OBS_SOURCE_INTERACTION);
  1550. popup.addAction(QTStr("Properties"), this,
  1551. SLOT(on_actionSourceProperties_triggered()));
  1552. }
  1553. popup.exec(QCursor::pos());
  1554. }
  1555. void OBSBasic::on_sources_itemDoubleClicked(QListWidgetItem *witem)
  1556. {
  1557. if (!witem)
  1558. return;
  1559. OBSSceneItem item = GetSceneItem(witem);
  1560. OBSSource source = obs_sceneitem_get_source(item);
  1561. if (source)
  1562. CreatePropertiesWindow(source);
  1563. }
  1564. void OBSBasic::AddSource(const char *id)
  1565. {
  1566. if (id && *id) {
  1567. OBSBasicSourceSelect sourceSelect(this, id);
  1568. sourceSelect.exec();
  1569. }
  1570. }
  1571. QMenu *OBSBasic::CreateAddSourcePopupMenu()
  1572. {
  1573. const char *type;
  1574. bool foundValues = false;
  1575. size_t idx = 0;
  1576. QMenu *popup = new QMenu(QTStr("Add"), this);
  1577. while (obs_enum_input_types(idx++, &type)) {
  1578. const char *name = obs_source_get_display_name(
  1579. OBS_SOURCE_TYPE_INPUT, type);
  1580. if (strcmp(type, "scene") == 0)
  1581. continue;
  1582. QAction *popupItem = new QAction(QT_UTF8(name), this);
  1583. popupItem->setData(QT_UTF8(type));
  1584. connect(popupItem, SIGNAL(triggered(bool)),
  1585. this, SLOT(AddSourceFromAction()));
  1586. popup->addAction(popupItem);
  1587. foundValues = true;
  1588. }
  1589. if (!foundValues) {
  1590. delete popup;
  1591. popup = nullptr;
  1592. }
  1593. return popup;
  1594. }
  1595. void OBSBasic::AddSourceFromAction()
  1596. {
  1597. QAction *action = qobject_cast<QAction*>(sender());
  1598. if (!action)
  1599. return;
  1600. AddSource(QT_TO_UTF8(action->data().toString()));
  1601. }
  1602. void OBSBasic::AddSourcePopupMenu(const QPoint &pos)
  1603. {
  1604. if (!GetCurrentScene()) {
  1605. // Tell the user he needs a scene first (help beginners).
  1606. QMessageBox::information(this,
  1607. QTStr("Basic.Main.AddSourceHelp.Title"),
  1608. QTStr("Basic.Main.AddSourceHelp.Text"));
  1609. return;
  1610. }
  1611. QPointer<QMenu> popup = CreateAddSourcePopupMenu();
  1612. if (popup)
  1613. popup->exec(pos);
  1614. }
  1615. void OBSBasic::on_actionAddSource_triggered()
  1616. {
  1617. AddSourcePopupMenu(QCursor::pos());
  1618. }
  1619. void OBSBasic::on_actionRemoveSource_triggered()
  1620. {
  1621. OBSSceneItem item = GetCurrentSceneItem();
  1622. obs_source_t *source = obs_sceneitem_get_source(item);
  1623. if (source && QueryRemoveSource(source))
  1624. obs_sceneitem_remove(item);
  1625. }
  1626. void OBSBasic::on_actionInteract_triggered()
  1627. {
  1628. OBSSceneItem item = GetCurrentSceneItem();
  1629. OBSSource source = obs_sceneitem_get_source(item);
  1630. if (source)
  1631. CreateInteractionWindow(source);
  1632. }
  1633. void OBSBasic::on_actionSourceProperties_triggered()
  1634. {
  1635. OBSSceneItem item = GetCurrentSceneItem();
  1636. OBSSource source = obs_sceneitem_get_source(item);
  1637. if (source)
  1638. CreatePropertiesWindow(source);
  1639. }
  1640. void OBSBasic::on_actionSourceUp_triggered()
  1641. {
  1642. OBSSceneItem item = GetCurrentSceneItem();
  1643. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  1644. }
  1645. void OBSBasic::on_actionSourceDown_triggered()
  1646. {
  1647. OBSSceneItem item = GetCurrentSceneItem();
  1648. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  1649. }
  1650. void OBSBasic::on_actionMoveUp_triggered()
  1651. {
  1652. OBSSceneItem item = GetCurrentSceneItem();
  1653. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  1654. }
  1655. void OBSBasic::on_actionMoveDown_triggered()
  1656. {
  1657. OBSSceneItem item = GetCurrentSceneItem();
  1658. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  1659. }
  1660. void OBSBasic::on_actionMoveToTop_triggered()
  1661. {
  1662. OBSSceneItem item = GetCurrentSceneItem();
  1663. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_TOP);
  1664. }
  1665. void OBSBasic::on_actionMoveToBottom_triggered()
  1666. {
  1667. OBSSceneItem item = GetCurrentSceneItem();
  1668. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_BOTTOM);
  1669. }
  1670. static BPtr<char> ReadLogFile(const char *log)
  1671. {
  1672. char logDir[512];
  1673. if (os_get_config_path(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  1674. return nullptr;
  1675. string path = (char*)logDir;
  1676. path += "/";
  1677. path += log;
  1678. BPtr<char> file = os_quick_read_utf8_file(path.c_str());
  1679. if (!file)
  1680. blog(LOG_WARNING, "Failed to read log file %s", path.c_str());
  1681. return file;
  1682. }
  1683. void OBSBasic::UploadLog(const char *file)
  1684. {
  1685. BPtr<char> fileString{ReadLogFile(file)};
  1686. if (!fileString)
  1687. return;
  1688. if (!*fileString)
  1689. return;
  1690. ui->menuLogFiles->setEnabled(false);
  1691. auto data_deleter = [](obs_data_t *d) { obs_data_release(d); };
  1692. using data_t = unique_ptr<struct obs_data, decltype(data_deleter)>;
  1693. data_t content{obs_data_create(), data_deleter};
  1694. data_t files{obs_data_create(), data_deleter};
  1695. data_t request{obs_data_create(), data_deleter};
  1696. obs_data_set_string(content.get(), "content", fileString);
  1697. obs_data_set_obj(files.get(), file, content.get());
  1698. stringstream ss;
  1699. ss << "OBS " << App()->GetVersionString()
  1700. << " log file uploaded at " << CurrentDateTimeString();
  1701. obs_data_set_string(request.get(), "description", ss.str().c_str());
  1702. obs_data_set_bool(request.get(), "public", false);
  1703. obs_data_set_obj(request.get(), "files", files.get());
  1704. const char *json = obs_data_get_json(request.get());
  1705. if (!json) {
  1706. blog(LOG_ERROR, "Failed to get JSON data for log upload");
  1707. return;
  1708. }
  1709. QBuffer *postData = new QBuffer();
  1710. postData->setData(json, (int) strlen(json));
  1711. QNetworkRequest postReq(QUrl("https://api.github.com/gists"));
  1712. postReq.setHeader(QNetworkRequest::ContentTypeHeader,
  1713. "application/json");
  1714. QNetworkReply *reply = networkManager.post(postReq, postData);
  1715. /* set the reply as parent, so the buffer is deleted with the reply */
  1716. postData->setParent(reply);
  1717. connect(reply, SIGNAL(finished()),
  1718. this, SLOT(logUploadFinished()));
  1719. }
  1720. void OBSBasic::on_actionShowLogs_triggered()
  1721. {
  1722. char logDir[512];
  1723. if (os_get_config_path(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  1724. return;
  1725. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  1726. QDesktopServices::openUrl(url);
  1727. }
  1728. void OBSBasic::on_actionUploadCurrentLog_triggered()
  1729. {
  1730. UploadLog(App()->GetCurrentLog());
  1731. }
  1732. void OBSBasic::on_actionUploadLastLog_triggered()
  1733. {
  1734. UploadLog(App()->GetLastLog());
  1735. }
  1736. void OBSBasic::on_actionViewCurrentLog_triggered()
  1737. {
  1738. char logDir[512];
  1739. if (os_get_config_path(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  1740. return;
  1741. const char* log = App()->GetCurrentLog();
  1742. string path = (char*)logDir;
  1743. path += "/";
  1744. path += log;
  1745. QUrl url = QUrl::fromLocalFile(QT_UTF8(path.c_str()));
  1746. QDesktopServices::openUrl(url);
  1747. }
  1748. void OBSBasic::on_actionCheckForUpdates_triggered()
  1749. {
  1750. CheckForUpdates();
  1751. }
  1752. void OBSBasic::logUploadFinished()
  1753. {
  1754. ui->menuLogFiles->setEnabled(true);
  1755. QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
  1756. if (!reply || reply->error()) {
  1757. QMessageBox::information(this,
  1758. QTStr("LogReturnDialog.ErrorUploadingLog"),
  1759. reply->errorString());
  1760. return;
  1761. }
  1762. QByteArray raw = reply->readAll();
  1763. if (!raw.length())
  1764. return;
  1765. obs_data_t *returnData = obs_data_create_from_json(raw.constData());
  1766. QString logURL = obs_data_get_string(returnData, "html_url");
  1767. obs_data_release(returnData);
  1768. OBSLogReply logDialog(this, logURL);
  1769. logDialog.exec();
  1770. reply->deleteLater();
  1771. }
  1772. static void RenameListItem(OBSBasic *parent, QListWidget *listWidget,
  1773. obs_source_t *source, const string &name)
  1774. {
  1775. const char *prevName = obs_source_get_name(source);
  1776. if (name == prevName)
  1777. return;
  1778. obs_source_t *foundSource = obs_get_source_by_name(name.c_str());
  1779. QListWidgetItem *listItem = listWidget->currentItem();
  1780. if (foundSource || name.empty()) {
  1781. listItem->setText(QT_UTF8(prevName));
  1782. if (foundSource) {
  1783. QMessageBox::information(parent,
  1784. QTStr("NameExists.Title"),
  1785. QTStr("NameExists.Text"));
  1786. } else if (name.empty()) {
  1787. QMessageBox::information(parent,
  1788. QTStr("NoNameEntered.Title"),
  1789. QTStr("NoNameEntered.Text"));
  1790. }
  1791. obs_source_release(foundSource);
  1792. } else {
  1793. listItem->setText(QT_UTF8(name.c_str()));
  1794. obs_source_set_name(source, name.c_str());
  1795. }
  1796. }
  1797. void OBSBasic::SceneNameEdited(QWidget *editor,
  1798. QAbstractItemDelegate::EndEditHint endHint)
  1799. {
  1800. OBSScene scene = GetCurrentScene();
  1801. QLineEdit *edit = qobject_cast<QLineEdit*>(editor);
  1802. string text = QT_TO_UTF8(edit->text().trimmed());
  1803. if (!scene)
  1804. return;
  1805. obs_source_t *source = obs_scene_get_source(scene);
  1806. RenameListItem(this, ui->scenes, source, text);
  1807. UNUSED_PARAMETER(endHint);
  1808. }
  1809. void OBSBasic::SceneItemNameEdited(QWidget *editor,
  1810. QAbstractItemDelegate::EndEditHint endHint)
  1811. {
  1812. OBSSceneItem item = GetCurrentSceneItem();
  1813. QLineEdit *edit = qobject_cast<QLineEdit*>(editor);
  1814. string text = QT_TO_UTF8(edit->text().trimmed());
  1815. if (!item)
  1816. return;
  1817. obs_source_t *source = obs_sceneitem_get_source(item);
  1818. RenameListItem(this, ui->sources, source, text);
  1819. UNUSED_PARAMETER(endHint);
  1820. }
  1821. void OBSBasic::StreamingStart()
  1822. {
  1823. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  1824. ui->streamButton->setEnabled(true);
  1825. ui->statusbar->StreamStarted(outputHandler->streamOutput);
  1826. }
  1827. void OBSBasic::StreamingStop(int code)
  1828. {
  1829. const char *errorMessage;
  1830. switch (code) {
  1831. case OBS_OUTPUT_BAD_PATH:
  1832. errorMessage = Str("Output.ConnectFail.BadPath");
  1833. break;
  1834. case OBS_OUTPUT_CONNECT_FAILED:
  1835. errorMessage = Str("Output.ConnectFail.ConnectFailed");
  1836. break;
  1837. case OBS_OUTPUT_INVALID_STREAM:
  1838. errorMessage = Str("Output.ConnectFail.InvalidStream");
  1839. break;
  1840. default:
  1841. case OBS_OUTPUT_ERROR:
  1842. errorMessage = Str("Output.ConnectFail.Error");
  1843. break;
  1844. case OBS_OUTPUT_DISCONNECTED:
  1845. /* doesn't happen if output is set to reconnect. note that
  1846. * reconnects are handled in the output, not in the UI */
  1847. errorMessage = Str("Output.ConnectFail.Disconnected");
  1848. }
  1849. ui->statusbar->StreamStopped();
  1850. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  1851. ui->streamButton->setEnabled(true);
  1852. if (code != OBS_OUTPUT_SUCCESS)
  1853. QMessageBox::information(this,
  1854. QTStr("Output.ConnectFail.Title"),
  1855. QT_UTF8(errorMessage));
  1856. }
  1857. void OBSBasic::RecordingStart()
  1858. {
  1859. ui->statusbar->RecordingStarted(outputHandler->fileOutput);
  1860. }
  1861. void OBSBasic::RecordingStop()
  1862. {
  1863. ui->statusbar->RecordingStopped();
  1864. ui->recordButton->setText(QTStr("Basic.Main.StartRecording"));
  1865. }
  1866. void OBSBasic::on_streamButton_clicked()
  1867. {
  1868. SaveProject();
  1869. if (outputHandler->StreamingActive()) {
  1870. outputHandler->StopStreaming();
  1871. } else {
  1872. if (outputHandler->StartStreaming(service)) {
  1873. ui->streamButton->setEnabled(false);
  1874. ui->streamButton->setText(
  1875. QTStr("Basic.Main.Connecting"));
  1876. }
  1877. }
  1878. }
  1879. void OBSBasic::on_recordButton_clicked()
  1880. {
  1881. SaveProject();
  1882. if (outputHandler->RecordingActive()) {
  1883. outputHandler->StopRecording();
  1884. } else {
  1885. if (outputHandler->StartRecording()) {
  1886. ui->recordButton->setText(
  1887. QTStr("Basic.Main.StopRecording"));
  1888. }
  1889. }
  1890. }
  1891. void OBSBasic::on_settingsButton_clicked()
  1892. {
  1893. OBSBasicSettings settings(this);
  1894. settings.exec();
  1895. }
  1896. void OBSBasic::GetFPSCommon(uint32_t &num, uint32_t &den) const
  1897. {
  1898. const char *val = config_get_string(basicConfig, "Video", "FPSCommon");
  1899. if (strcmp(val, "10") == 0) {
  1900. num = 10;
  1901. den = 1;
  1902. } else if (strcmp(val, "20") == 0) {
  1903. num = 20;
  1904. den = 1;
  1905. } else if (strcmp(val, "25") == 0) {
  1906. num = 25;
  1907. den = 1;
  1908. } else if (strcmp(val, "29.97") == 0) {
  1909. num = 30000;
  1910. den = 1001;
  1911. } else if (strcmp(val, "48") == 0) {
  1912. num = 48;
  1913. den = 1;
  1914. } else if (strcmp(val, "59.94") == 0) {
  1915. num = 60000;
  1916. den = 1001;
  1917. } else if (strcmp(val, "60") == 0) {
  1918. num = 60;
  1919. den = 1;
  1920. } else {
  1921. num = 30;
  1922. den = 1;
  1923. }
  1924. }
  1925. void OBSBasic::GetFPSInteger(uint32_t &num, uint32_t &den) const
  1926. {
  1927. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSInt");
  1928. den = 1;
  1929. }
  1930. void OBSBasic::GetFPSFraction(uint32_t &num, uint32_t &den) const
  1931. {
  1932. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNum");
  1933. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSDen");
  1934. }
  1935. void OBSBasic::GetFPSNanoseconds(uint32_t &num, uint32_t &den) const
  1936. {
  1937. num = 1000000000;
  1938. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNS");
  1939. }
  1940. void OBSBasic::GetConfigFPS(uint32_t &num, uint32_t &den) const
  1941. {
  1942. uint32_t type = config_get_uint(basicConfig, "Video", "FPSType");
  1943. if (type == 1) //"Integer"
  1944. GetFPSInteger(num, den);
  1945. else if (type == 2) //"Fraction"
  1946. GetFPSFraction(num, den);
  1947. else if (false) //"Nanoseconds", currently not implemented
  1948. GetFPSNanoseconds(num, den);
  1949. else
  1950. GetFPSCommon(num, den);
  1951. }
  1952. config_t *OBSBasic::Config() const
  1953. {
  1954. return basicConfig;
  1955. }
  1956. void OBSBasic::on_actionEditTransform_triggered()
  1957. {
  1958. if (transformWindow)
  1959. transformWindow->close();
  1960. transformWindow = new OBSBasicTransform(this);
  1961. transformWindow->show();
  1962. transformWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  1963. }
  1964. void OBSBasic::on_actionResetTransform_triggered()
  1965. {
  1966. auto func = [] (obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  1967. {
  1968. if (!obs_sceneitem_selected(item))
  1969. return true;
  1970. obs_transform_info info;
  1971. vec2_set(&info.pos, 0.0f, 0.0f);
  1972. vec2_set(&info.scale, 1.0f, 1.0f);
  1973. info.rot = 0.0f;
  1974. info.alignment = OBS_ALIGN_TOP | OBS_ALIGN_LEFT;
  1975. info.bounds_type = OBS_BOUNDS_NONE;
  1976. info.bounds_alignment = OBS_ALIGN_CENTER;
  1977. vec2_set(&info.bounds, 0.0f, 0.0f);
  1978. obs_sceneitem_set_info(item, &info);
  1979. UNUSED_PARAMETER(scene);
  1980. UNUSED_PARAMETER(param);
  1981. return true;
  1982. };
  1983. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  1984. }
  1985. static void GetItemBox(obs_sceneitem_t *item, vec3 &tl, vec3 &br)
  1986. {
  1987. matrix4 boxTransform;
  1988. obs_sceneitem_get_box_transform(item, &boxTransform);
  1989. vec3_set(&tl, M_INFINITE, M_INFINITE, 0.0f);
  1990. vec3_set(&br, -M_INFINITE, -M_INFINITE, 0.0f);
  1991. auto GetMinPos = [&] (float x, float y)
  1992. {
  1993. vec3 pos;
  1994. vec3_set(&pos, x, y, 0.0f);
  1995. vec3_transform(&pos, &pos, &boxTransform);
  1996. vec3_min(&tl, &tl, &pos);
  1997. vec3_max(&br, &br, &pos);
  1998. };
  1999. GetMinPos(0.0f, 0.0f);
  2000. GetMinPos(1.0f, 0.0f);
  2001. GetMinPos(0.0f, 1.0f);
  2002. GetMinPos(1.0f, 1.0f);
  2003. }
  2004. static vec3 GetItemTL(obs_sceneitem_t *item)
  2005. {
  2006. vec3 tl, br;
  2007. GetItemBox(item, tl, br);
  2008. return tl;
  2009. }
  2010. static void SetItemTL(obs_sceneitem_t *item, const vec3 &tl)
  2011. {
  2012. vec3 newTL;
  2013. vec2 pos;
  2014. obs_sceneitem_get_pos(item, &pos);
  2015. newTL = GetItemTL(item);
  2016. pos.x += tl.x - newTL.x;
  2017. pos.y += tl.y - newTL.y;
  2018. obs_sceneitem_set_pos(item, &pos);
  2019. }
  2020. static bool RotateSelectedSources(obs_scene_t *scene, obs_sceneitem_t *item,
  2021. void *param)
  2022. {
  2023. if (!obs_sceneitem_selected(item))
  2024. return true;
  2025. float rot = *reinterpret_cast<float*>(param);
  2026. vec3 tl = GetItemTL(item);
  2027. rot += obs_sceneitem_get_rot(item);
  2028. if (rot >= 360.0f) rot -= 360.0f;
  2029. else if (rot <= -360.0f) rot += 360.0f;
  2030. obs_sceneitem_set_rot(item, rot);
  2031. SetItemTL(item, tl);
  2032. UNUSED_PARAMETER(scene);
  2033. UNUSED_PARAMETER(param);
  2034. return true;
  2035. };
  2036. void OBSBasic::on_actionRotate90CW_triggered()
  2037. {
  2038. float f90CW = 90.0f;
  2039. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CW);
  2040. }
  2041. void OBSBasic::on_actionRotate90CCW_triggered()
  2042. {
  2043. float f90CCW = -90.0f;
  2044. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CCW);
  2045. }
  2046. void OBSBasic::on_actionRotate180_triggered()
  2047. {
  2048. float f180 = 180.0f;
  2049. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f180);
  2050. }
  2051. static bool MultiplySelectedItemScale(obs_scene_t *scene, obs_sceneitem_t *item,
  2052. void *param)
  2053. {
  2054. vec2 &mul = *reinterpret_cast<vec2*>(param);
  2055. if (!obs_sceneitem_selected(item))
  2056. return true;
  2057. vec3 tl = GetItemTL(item);
  2058. vec2 scale;
  2059. obs_sceneitem_get_scale(item, &scale);
  2060. vec2_mul(&scale, &scale, &mul);
  2061. obs_sceneitem_set_scale(item, &scale);
  2062. SetItemTL(item, tl);
  2063. UNUSED_PARAMETER(scene);
  2064. return true;
  2065. }
  2066. void OBSBasic::on_actionFlipHorizontal_triggered()
  2067. {
  2068. vec2 scale;
  2069. vec2_set(&scale, -1.0f, 1.0f);
  2070. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  2071. &scale);
  2072. }
  2073. void OBSBasic::on_actionFlipVertical_triggered()
  2074. {
  2075. vec2 scale;
  2076. vec2_set(&scale, 1.0f, -1.0f);
  2077. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  2078. &scale);
  2079. }
  2080. static bool CenterAlignSelectedItems(obs_scene_t *scene, obs_sceneitem_t *item,
  2081. void *param)
  2082. {
  2083. obs_bounds_type boundsType = *reinterpret_cast<obs_bounds_type*>(param);
  2084. if (!obs_sceneitem_selected(item))
  2085. return true;
  2086. obs_video_info ovi;
  2087. obs_get_video_info(&ovi);
  2088. obs_transform_info itemInfo;
  2089. vec2_set(&itemInfo.pos, 0.0f, 0.0f);
  2090. vec2_set(&itemInfo.scale, 1.0f, 1.0f);
  2091. itemInfo.alignment = OBS_ALIGN_LEFT | OBS_ALIGN_TOP;
  2092. itemInfo.rot = 0.0f;
  2093. vec2_set(&itemInfo.bounds,
  2094. float(ovi.base_width), float(ovi.base_height));
  2095. itemInfo.bounds_type = boundsType;
  2096. itemInfo.bounds_alignment = OBS_ALIGN_CENTER;
  2097. obs_sceneitem_set_info(item, &itemInfo);
  2098. UNUSED_PARAMETER(scene);
  2099. return true;
  2100. }
  2101. void OBSBasic::on_actionFitToScreen_triggered()
  2102. {
  2103. obs_bounds_type boundsType = OBS_BOUNDS_SCALE_INNER;
  2104. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  2105. &boundsType);
  2106. }
  2107. void OBSBasic::on_actionStretchToScreen_triggered()
  2108. {
  2109. obs_bounds_type boundsType = OBS_BOUNDS_STRETCH;
  2110. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  2111. &boundsType);
  2112. }
  2113. void OBSBasic::on_actionCenterToScreen_triggered()
  2114. {
  2115. auto func = [] (obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  2116. {
  2117. vec3 tl, br, itemCenter, screenCenter, offset;
  2118. obs_video_info ovi;
  2119. if (!obs_sceneitem_selected(item))
  2120. return true;
  2121. obs_get_video_info(&ovi);
  2122. vec3_set(&screenCenter, float(ovi.base_width),
  2123. float(ovi.base_height), 0.0f);
  2124. vec3_mulf(&screenCenter, &screenCenter, 0.5f);
  2125. GetItemBox(item, tl, br);
  2126. vec3_sub(&itemCenter, &br, &tl);
  2127. vec3_mulf(&itemCenter, &itemCenter, 0.5f);
  2128. vec3_add(&itemCenter, &itemCenter, &tl);
  2129. vec3_sub(&offset, &screenCenter, &itemCenter);
  2130. vec3_add(&tl, &tl, &offset);
  2131. SetItemTL(item, tl);
  2132. UNUSED_PARAMETER(scene);
  2133. UNUSED_PARAMETER(param);
  2134. return true;
  2135. };
  2136. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  2137. }