window-basic-main.cpp 69 KB

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