1
0

window-basic-main.cpp 65 KB

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