window-basic-main.cpp 67 KB

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