window-basic-main.cpp 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142
  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 <obs.hpp>
  16. #include <QMessageBox>
  17. #include <QShowEvent>
  18. #include <QFileDialog>
  19. #include <QNetworkRequest>
  20. #include <QNetworkReply>
  21. #include <util/dstr.h>
  22. #include <util/util.hpp>
  23. #include <util/platform.h>
  24. #include <graphics/math-defs.h>
  25. #include "obs-app.hpp"
  26. #include "platform.hpp"
  27. #include "window-basic-settings.hpp"
  28. #include "window-namedialog.hpp"
  29. #include "window-basic-source-select.hpp"
  30. #include "window-basic-main.hpp"
  31. #include "window-basic-properties.hpp"
  32. #include "window-log-reply.hpp"
  33. #include "qt-wrappers.hpp"
  34. #include "display-helpers.hpp"
  35. #include "volume-control.hpp"
  36. #include "ui_OBSBasic.h"
  37. #include <fstream>
  38. #include <sstream>
  39. #include <QScreen>
  40. #include <QWindow>
  41. #define PREVIEW_EDGE_SIZE 10
  42. using namespace std;
  43. Q_DECLARE_METATYPE(OBSScene);
  44. Q_DECLARE_METATYPE(OBSSceneItem);
  45. Q_DECLARE_METATYPE(order_movement);
  46. OBSBasic::OBSBasic(QWidget *parent)
  47. : OBSMainWindow (parent),
  48. ui (new Ui::OBSBasic)
  49. {
  50. ui->setupUi(this);
  51. connect(windowHandle(), &QWindow::screenChanged, [this]() {
  52. struct obs_video_info ovi;
  53. if (obs_get_video_info(&ovi))
  54. ResizePreview(ovi.base_width, ovi.base_height);
  55. });
  56. stringstream name;
  57. name << "OBS " << App()->GetVersionString();
  58. blog(LOG_INFO, "%s", name.str().c_str());
  59. setWindowTitle(QT_UTF8(name.str().c_str()));
  60. connect(ui->scenes->itemDelegate(),
  61. SIGNAL(closeEditor(QWidget*,
  62. QAbstractItemDelegate::EndEditHint)),
  63. this,
  64. SLOT(SceneNameEdited(QWidget*,
  65. QAbstractItemDelegate::EndEditHint)));
  66. connect(ui->sources->itemDelegate(),
  67. SIGNAL(closeEditor(QWidget*,
  68. QAbstractItemDelegate::EndEditHint)),
  69. this,
  70. SLOT(SceneItemNameEdited(QWidget*,
  71. QAbstractItemDelegate::EndEditHint)));
  72. }
  73. static void SaveAudioDevice(const char *name, int channel, obs_data_t parent)
  74. {
  75. obs_source_t source = obs_get_output_source(channel);
  76. if (!source)
  77. return;
  78. obs_data_t data = obs_save_source(source);
  79. obs_data_setobj(parent, name, data);
  80. obs_data_release(data);
  81. obs_source_release(source);
  82. }
  83. static obs_data_t GenerateSaveData()
  84. {
  85. obs_data_t saveData = obs_data_create();
  86. obs_data_array_t sourcesArray = obs_save_sources();
  87. obs_source_t currentScene = obs_get_output_source(0);
  88. const char *sceneName = obs_source_getname(currentScene);
  89. SaveAudioDevice(DESKTOP_AUDIO_1, 1, saveData);
  90. SaveAudioDevice(DESKTOP_AUDIO_2, 2, saveData);
  91. SaveAudioDevice(AUX_AUDIO_1, 3, saveData);
  92. SaveAudioDevice(AUX_AUDIO_2, 4, saveData);
  93. SaveAudioDevice(AUX_AUDIO_3, 5, saveData);
  94. obs_data_setstring(saveData, "current_scene", sceneName);
  95. obs_data_setarray(saveData, "sources", sourcesArray);
  96. obs_data_array_release(sourcesArray);
  97. obs_source_release(currentScene);
  98. return saveData;
  99. }
  100. void OBSBasic::ClearVolumeControls()
  101. {
  102. VolControl *control;
  103. for (size_t i = 0; i < volumes.size(); i++) {
  104. control = volumes[i];
  105. delete control;
  106. }
  107. volumes.clear();
  108. }
  109. void OBSBasic::Save(const char *file)
  110. {
  111. obs_data_t saveData = GenerateSaveData();
  112. const char *jsonData = obs_data_getjson(saveData);
  113. /* TODO maybe a message box here? */
  114. if (!os_quick_write_utf8_file(file, jsonData, strlen(jsonData), false))
  115. blog(LOG_ERROR, "Could not save scene data to %s", file);
  116. obs_data_release(saveData);
  117. }
  118. static void LoadAudioDevice(const char *name, int channel, obs_data_t parent)
  119. {
  120. obs_data_t data = obs_data_getobj(parent, name);
  121. if (!data)
  122. return;
  123. obs_source_t source = obs_load_source(data);
  124. if (source) {
  125. obs_set_output_source(channel, source);
  126. obs_source_release(source);
  127. }
  128. obs_data_release(data);
  129. }
  130. void OBSBasic::CreateDefaultScene()
  131. {
  132. obs_scene_t scene = obs_scene_create(Str("Basic.Scene"));
  133. obs_source_t source = obs_scene_getsource(scene);
  134. obs_add_source(source);
  135. #ifdef __APPLE__
  136. source = obs_source_create(OBS_SOURCE_TYPE_INPUT, "display_capture",
  137. Str("Basic.DisplayCapture"), NULL);
  138. if (source) {
  139. obs_scene_add(scene, source);
  140. obs_add_source(source);
  141. obs_source_release(source);
  142. }
  143. #endif
  144. obs_set_output_source(0, obs_scene_getsource(scene));
  145. obs_scene_release(scene);
  146. }
  147. void OBSBasic::Load(const char *file)
  148. {
  149. if (!file) {
  150. blog(LOG_ERROR, "Could not find file %s", file);
  151. return;
  152. }
  153. BPtr<char> jsonData = os_quick_read_utf8_file(file);
  154. if (!jsonData) {
  155. CreateDefaultScene();
  156. return;
  157. }
  158. obs_data_t data = obs_data_create_from_json(jsonData);
  159. obs_data_array_t sources = obs_data_getarray(data, "sources");
  160. const char *sceneName = obs_data_getstring(data, "current_scene");
  161. obs_source_t curScene;
  162. LoadAudioDevice(DESKTOP_AUDIO_1, 1, data);
  163. LoadAudioDevice(DESKTOP_AUDIO_2, 2, data);
  164. LoadAudioDevice(AUX_AUDIO_1, 3, data);
  165. LoadAudioDevice(AUX_AUDIO_2, 4, data);
  166. LoadAudioDevice(AUX_AUDIO_3, 5, data);
  167. obs_load_sources(sources);
  168. curScene = obs_get_source_by_name(sceneName);
  169. obs_set_output_source(0, curScene);
  170. obs_source_release(curScene);
  171. obs_data_array_release(sources);
  172. obs_data_release(data);
  173. }
  174. static inline bool HasAudioDevices(const char *source_id)
  175. {
  176. const char *output_id = source_id;
  177. obs_properties_t props = obs_get_source_properties(
  178. OBS_SOURCE_TYPE_INPUT, output_id);
  179. size_t count = 0;
  180. if (!props)
  181. return false;
  182. obs_property_t devices = obs_properties_get(props, "device_id");
  183. if (devices)
  184. count = obs_property_list_item_count(devices);
  185. obs_properties_destroy(props);
  186. return count != 0;
  187. }
  188. static void OBSStartStreaming(void *data, calldata_t params)
  189. {
  190. UNUSED_PARAMETER(params);
  191. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  192. "StreamingStart");
  193. }
  194. static void OBSStopStreaming(void *data, calldata_t params)
  195. {
  196. int code = (int)calldata_int(params, "code");
  197. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  198. "StreamingStop", Q_ARG(int, code));
  199. }
  200. static void OBSStopRecording(void *data, calldata_t params)
  201. {
  202. UNUSED_PARAMETER(params);
  203. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  204. "RecordingStop");
  205. }
  206. #define SERVICE_PATH "obs-studio/basic/service.json"
  207. void OBSBasic::SaveService()
  208. {
  209. if (!service)
  210. return;
  211. BPtr<char> serviceJsonPath(os_get_config_path(SERVICE_PATH));
  212. if (!serviceJsonPath)
  213. return;
  214. obs_data_t data = obs_data_create();
  215. obs_data_t settings = obs_service_get_settings(service);
  216. obs_data_setstring(data, "type", obs_service_gettype(service));
  217. obs_data_setobj(data, "settings", settings);
  218. const char *json = obs_data_getjson(data);
  219. os_quick_write_utf8_file(serviceJsonPath, json, strlen(json), false);
  220. obs_data_release(settings);
  221. obs_data_release(data);
  222. }
  223. bool OBSBasic::LoadService()
  224. {
  225. const char *type;
  226. BPtr<char> serviceJsonPath(os_get_config_path(SERVICE_PATH));
  227. if (!serviceJsonPath)
  228. return false;
  229. BPtr<char> jsonText = os_quick_read_utf8_file(serviceJsonPath);
  230. if (!jsonText)
  231. return false;
  232. obs_data_t data = obs_data_create_from_json(jsonText);
  233. obs_data_set_default_string(data, "type", "rtmp_common");
  234. type = obs_data_getstring(data, "type");
  235. obs_data_t settings = obs_data_getobj(data, "settings");
  236. service = obs_service_create(type, "default", settings);
  237. obs_data_release(settings);
  238. obs_data_release(data);
  239. return !!service;
  240. }
  241. bool OBSBasic::InitOutputs()
  242. {
  243. fileOutput = obs_output_create("flv_output", "default", nullptr);
  244. if (!fileOutput)
  245. return false;
  246. streamOutput = obs_output_create("rtmp_output", "default", nullptr);
  247. if (!streamOutput)
  248. return false;
  249. signal_handler_connect(obs_output_signalhandler(streamOutput),
  250. "start", OBSStartStreaming, this);
  251. signal_handler_connect(obs_output_signalhandler(streamOutput),
  252. "stop", OBSStopStreaming, this);
  253. signal_handler_connect(obs_output_signalhandler(fileOutput),
  254. "stop", OBSStopRecording, this);
  255. return true;
  256. }
  257. bool OBSBasic::InitEncoders()
  258. {
  259. x264 = obs_video_encoder_create("obs_x264", "h264", nullptr);
  260. if (!x264)
  261. return false;
  262. aac = obs_audio_encoder_create("libfdk_aac", "aac", nullptr);
  263. if(!aac)
  264. aac = obs_audio_encoder_create("ffmpeg_aac", "aac", nullptr);
  265. if (!aac)
  266. return false;
  267. return true;
  268. }
  269. bool OBSBasic::InitService()
  270. {
  271. if (LoadService())
  272. return true;
  273. service = obs_service_create("rtmp_common", nullptr, nullptr);
  274. if (!service)
  275. return false;
  276. return true;
  277. }
  278. bool OBSBasic::InitBasicConfigDefaults()
  279. {
  280. bool hasDesktopAudio = HasAudioDevices(App()->OutputAudioSource());
  281. bool hasInputAudio = HasAudioDevices(App()->InputAudioSource());
  282. config_set_default_int(basicConfig, "Window", "PosX", -1);
  283. config_set_default_int(basicConfig, "Window", "PosY", -1);
  284. config_set_default_int(basicConfig, "Window", "SizeX", -1);
  285. config_set_default_int(basicConfig, "Window", "SizeY", -1);
  286. vector<MonitorInfo> monitors;
  287. GetMonitors(monitors);
  288. if (!monitors.size()) {
  289. OBSErrorBox(NULL, "There appears to be no monitors. Er, this "
  290. "technically shouldn't be possible.");
  291. return false;
  292. }
  293. uint32_t cx = monitors[0].cx;
  294. uint32_t cy = monitors[0].cy;
  295. /* TODO: temporary */
  296. config_set_default_string(basicConfig, "SimpleOutput", "FilePath",
  297. GetDefaultVideoSavePath().c_str());
  298. config_set_default_uint (basicConfig, "SimpleOutput", "VBitrate",
  299. 2500);
  300. config_set_default_uint (basicConfig, "SimpleOutput", "ABitrate", 128);
  301. config_set_default_bool (basicConfig, "SimpleOutput", "Reconnect",
  302. true);
  303. config_set_default_uint (basicConfig, "SimpleOutput", "RetryDelay", 2);
  304. config_set_default_uint (basicConfig, "SimpleOutput", "MaxRetries",
  305. 20);
  306. config_set_default_uint (basicConfig, "Video", "BaseCX", cx);
  307. config_set_default_uint (basicConfig, "Video", "BaseCY", cy);
  308. cx = cx * 10 / 15;
  309. cy = cy * 10 / 15;
  310. config_set_default_uint (basicConfig, "Video", "OutputCX", cx);
  311. config_set_default_uint (basicConfig, "Video", "OutputCY", cy);
  312. config_set_default_uint (basicConfig, "Video", "FPSType", 0);
  313. config_set_default_string(basicConfig, "Video", "FPSCommon", "30");
  314. config_set_default_uint (basicConfig, "Video", "FPSInt", 30);
  315. config_set_default_uint (basicConfig, "Video", "FPSNum", 30);
  316. config_set_default_uint (basicConfig, "Video", "FPSDen", 1);
  317. config_set_default_uint (basicConfig, "Audio", "SampleRate", 44100);
  318. config_set_default_string(basicConfig, "Audio", "ChannelSetup",
  319. "Stereo");
  320. config_set_default_uint (basicConfig, "Audio", "BufferingTime", 1000);
  321. config_set_default_string(basicConfig, "Audio", "DesktopDevice1",
  322. hasDesktopAudio ? "default" : "disabled");
  323. config_set_default_string(basicConfig, "Audio", "DesktopDevice2",
  324. "disabled");
  325. config_set_default_string(basicConfig, "Audio", "AuxDevice1",
  326. hasInputAudio ? "default" : "disabled");
  327. config_set_default_string(basicConfig, "Audio", "AuxDevice2",
  328. "disabled");
  329. config_set_default_string(basicConfig, "Audio", "AuxDevice3",
  330. "disabled");
  331. return true;
  332. }
  333. bool OBSBasic::InitBasicConfig()
  334. {
  335. BPtr<char> configPath(os_get_config_path("obs-studio/basic/basic.ini"));
  336. int code = basicConfig.Open(configPath, CONFIG_OPEN_ALWAYS);
  337. if (code != CONFIG_SUCCESS) {
  338. OBSErrorBox(NULL, "Failed to open basic.ini: %d", code);
  339. return false;
  340. }
  341. return InitBasicConfigDefaults();
  342. }
  343. void OBSBasic::InitOBSCallbacks()
  344. {
  345. signal_handler_connect(obs_signalhandler(), "source_add",
  346. OBSBasic::SourceAdded, this);
  347. signal_handler_connect(obs_signalhandler(), "source_remove",
  348. OBSBasic::SourceRemoved, this);
  349. signal_handler_connect(obs_signalhandler(), "channel_change",
  350. OBSBasic::ChannelChanged, this);
  351. signal_handler_connect(obs_signalhandler(), "source_activate",
  352. OBSBasic::SourceActivated, this);
  353. signal_handler_connect(obs_signalhandler(), "source_deactivate",
  354. OBSBasic::SourceDeactivated, this);
  355. signal_handler_connect(obs_signalhandler(), "source_rename",
  356. OBSBasic::SourceRenamed, this);
  357. }
  358. void OBSBasic::InitPrimitives()
  359. {
  360. gs_entercontext(obs_graphics());
  361. gs_renderstart(true);
  362. gs_vertex2f(0.0f, 0.0f);
  363. gs_vertex2f(0.0f, 1.0f);
  364. gs_vertex2f(1.0f, 1.0f);
  365. gs_vertex2f(1.0f, 0.0f);
  366. gs_vertex2f(0.0f, 0.0f);
  367. box = gs_rendersave();
  368. gs_renderstart(true);
  369. for (int i = 0; i <= 360; i += (360/20)) {
  370. float pos = RAD(float(i));
  371. gs_vertex2f(cosf(pos), sinf(pos));
  372. }
  373. circle = gs_rendersave();
  374. gs_leavecontext();
  375. }
  376. void OBSBasic::OBSInit()
  377. {
  378. BPtr<char> savePath(os_get_config_path("obs-studio/basic/scenes.json"));
  379. /* make sure it's fully displayed before doing any initialization */
  380. show();
  381. App()->processEvents();
  382. if (!obs_startup(App()->GetLocale()))
  383. throw "Failed to initialize libobs";
  384. if (!InitBasicConfig())
  385. throw "Failed to load basic.ini";
  386. if (!ResetVideo())
  387. throw "Failed to initialize video";
  388. if (!ResetAudio())
  389. throw "Failed to initialize audio";
  390. InitOBSCallbacks();
  391. /* TODO: this is a test, all modules will be searched for and loaded
  392. * automatically later */
  393. obs_load_module("image-source");
  394. obs_load_module("test-input");
  395. obs_load_module("obs-ffmpeg");
  396. obs_load_module("obs-libfdk");
  397. obs_load_module("obs-x264");
  398. obs_load_module("obs-outputs");
  399. obs_load_module("rtmp-services");
  400. #ifdef __APPLE__
  401. obs_load_module("mac-avcapture");
  402. obs_load_module("mac-capture");
  403. #elif _WIN32
  404. obs_load_module("win-wasapi");
  405. obs_load_module("win-capture");
  406. obs_load_module("win-dshow");
  407. #else
  408. obs_load_module("linux-xshm");
  409. obs_load_module("linux-xcomposite");
  410. obs_load_module("linux-pulseaudio");
  411. obs_load_module("linux-v4l2");
  412. #endif
  413. if (!InitOutputs())
  414. throw "Failed to initialize outputs";
  415. if (!InitEncoders())
  416. throw "Failed to initialize encoders";
  417. if (!InitService())
  418. throw "Failed to initialize service";
  419. InitPrimitives();
  420. Load(savePath);
  421. ResetAudioDevices();
  422. loaded = true;
  423. }
  424. OBSBasic::~OBSBasic()
  425. {
  426. BPtr<char> savePath(os_get_config_path("obs-studio/basic/scenes.json"));
  427. SaveService();
  428. Save(savePath);
  429. /* XXX: any obs data must be released before calling obs_shutdown.
  430. * currently, we can't automate this with C++ RAII because of the
  431. * delicate nature of obs_shutdown needing to be freed before the UI
  432. * can be freed, and we have no control over the destruction order of
  433. * the Qt UI stuff, so we have to manually clear any references to
  434. * libobs. */
  435. if (properties)
  436. delete properties;
  437. if (transformWindow)
  438. delete transformWindow;
  439. ClearVolumeControls();
  440. ui->sources->clear();
  441. ui->scenes->clear();
  442. gs_entercontext(obs_graphics());
  443. vertexbuffer_destroy(box);
  444. vertexbuffer_destroy(circle);
  445. gs_leavecontext();
  446. obs_shutdown();
  447. }
  448. OBSScene OBSBasic::GetCurrentScene()
  449. {
  450. QListWidgetItem *item = ui->scenes->currentItem();
  451. return item ? item->data(Qt::UserRole).value<OBSScene>() : nullptr;
  452. }
  453. OBSSceneItem OBSBasic::GetCurrentSceneItem()
  454. {
  455. QListWidgetItem *item = ui->sources->currentItem();
  456. return item ? item->data(Qt::UserRole).value<OBSSceneItem>() : nullptr;
  457. }
  458. void OBSBasic::UpdateSources(OBSScene scene)
  459. {
  460. ui->sources->clear();
  461. obs_scene_enum_items(scene,
  462. [] (obs_scene_t scene, obs_sceneitem_t item, void *p)
  463. {
  464. OBSBasic *window = static_cast<OBSBasic*>(p);
  465. window->InsertSceneItem(item);
  466. UNUSED_PARAMETER(scene);
  467. return true;
  468. }, this);
  469. }
  470. void OBSBasic::InsertSceneItem(obs_sceneitem_t item)
  471. {
  472. obs_source_t source = obs_sceneitem_getsource(item);
  473. const char *name = obs_source_getname(source);
  474. QListWidgetItem *listItem = new QListWidgetItem(QT_UTF8(name));
  475. listItem->setFlags(listItem->flags() | Qt::ItemIsEditable);
  476. listItem->setData(Qt::UserRole,
  477. QVariant::fromValue(OBSSceneItem(item)));
  478. ui->sources->insertItem(0, listItem);
  479. ui->sources->setCurrentRow(0);
  480. /* if the source was just created, open properties dialog */
  481. if (sourceSceneRefs[source] == 0 && loaded) {
  482. delete properties;
  483. properties = new OBSBasicProperties(this, source);
  484. properties->Init();
  485. }
  486. }
  487. /* Qt callbacks for invokeMethod */
  488. void OBSBasic::AddScene(OBSSource source)
  489. {
  490. const char *name = obs_source_getname(source);
  491. obs_scene_t scene = obs_scene_fromsource(source);
  492. QListWidgetItem *item = new QListWidgetItem(QT_UTF8(name));
  493. item->setFlags(item->flags() | Qt::ItemIsEditable);
  494. item->setData(Qt::UserRole, QVariant::fromValue(OBSScene(scene)));
  495. ui->scenes->addItem(item);
  496. signal_handler_t handler = obs_source_signalhandler(source);
  497. signal_handler_connect(handler, "item_add",
  498. OBSBasic::SceneItemAdded, this);
  499. signal_handler_connect(handler, "item_remove",
  500. OBSBasic::SceneItemRemoved, this);
  501. signal_handler_connect(handler, "item_move_up",
  502. OBSBasic::SceneItemMoveUp, this);
  503. signal_handler_connect(handler, "item_move_down",
  504. OBSBasic::SceneItemMoveDown, this);
  505. signal_handler_connect(handler, "item_move_top",
  506. OBSBasic::SceneItemMoveTop, this);
  507. signal_handler_connect(handler, "item_move_bottom",
  508. OBSBasic::SceneItemMoveBottom, this);
  509. }
  510. void OBSBasic::RemoveScene(OBSSource source)
  511. {
  512. const char *name = obs_source_getname(source);
  513. QListWidgetItem *sel = ui->scenes->currentItem();
  514. QList<QListWidgetItem*> items = ui->scenes->findItems(QT_UTF8(name),
  515. Qt::MatchExactly);
  516. if (sel != nullptr) {
  517. if (items.contains(sel))
  518. ui->sources->clear();
  519. delete sel;
  520. }
  521. }
  522. void OBSBasic::AddSceneItem(OBSSceneItem item)
  523. {
  524. obs_scene_t scene = obs_sceneitem_getscene(item);
  525. obs_source_t source = obs_sceneitem_getsource(item);
  526. if (GetCurrentScene() == scene)
  527. InsertSceneItem(item);
  528. sourceSceneRefs[source] = sourceSceneRefs[source] + 1;
  529. }
  530. void OBSBasic::RemoveSceneItem(OBSSceneItem item)
  531. {
  532. obs_scene_t scene = obs_sceneitem_getscene(item);
  533. if (GetCurrentScene() == scene) {
  534. for (int i = 0; i < ui->sources->count(); i++) {
  535. QListWidgetItem *listItem = ui->sources->item(i);
  536. QVariant userData = listItem->data(Qt::UserRole);
  537. if (userData.value<OBSSceneItem>() == item) {
  538. delete listItem;
  539. break;
  540. }
  541. }
  542. }
  543. obs_source_t source = obs_sceneitem_getsource(item);
  544. int scenes = sourceSceneRefs[source] - 1;
  545. sourceSceneRefs[source] = scenes;
  546. if (scenes == 0) {
  547. obs_source_remove(source);
  548. sourceSceneRefs.erase(source);
  549. }
  550. }
  551. void OBSBasic::UpdateSceneSelection(OBSSource source)
  552. {
  553. if (source) {
  554. obs_source_type type;
  555. obs_source_gettype(source, &type, NULL);
  556. obs_scene_t scene = obs_scene_fromsource(source);
  557. const char *name = obs_source_getname(source);
  558. if (!scene)
  559. return;
  560. QList<QListWidgetItem*> items =
  561. ui->scenes->findItems(QT_UTF8(name), Qt::MatchExactly);
  562. if (items.count()) {
  563. sceneChanging = true;
  564. ui->scenes->setCurrentItem(items.first());
  565. sceneChanging = false;
  566. UpdateSources(scene);
  567. }
  568. }
  569. }
  570. static void RenameListValues(QListWidget *listWidget, const QString &newName,
  571. const QString &prevName)
  572. {
  573. QList<QListWidgetItem*> items =
  574. listWidget->findItems(prevName, Qt::MatchExactly);
  575. for (int i = 0; i < items.count(); i++)
  576. items[i]->setText(newName);
  577. }
  578. void OBSBasic::RenameSources(QString newName, QString prevName)
  579. {
  580. RenameListValues(ui->scenes, newName, prevName);
  581. RenameListValues(ui->sources, newName, prevName);
  582. }
  583. void OBSBasic::MoveSceneItem(OBSSceneItem item, order_movement movement)
  584. {
  585. OBSScene scene = obs_sceneitem_getscene(item);
  586. if (scene != GetCurrentScene())
  587. return;
  588. int curRow = ui->sources->currentRow();
  589. if (curRow == -1)
  590. return;
  591. QListWidgetItem *listItem = ui->sources->takeItem(curRow);
  592. switch (movement) {
  593. case ORDER_MOVE_UP:
  594. if (curRow > 0)
  595. curRow--;
  596. break;
  597. case ORDER_MOVE_DOWN:
  598. if (curRow < ui->sources->count())
  599. curRow++;
  600. break;
  601. case ORDER_MOVE_TOP:
  602. curRow = 0;
  603. break;
  604. case ORDER_MOVE_BOTTOM:
  605. curRow = ui->sources->count();
  606. break;
  607. }
  608. ui->sources->insertItem(curRow, listItem);
  609. ui->sources->setCurrentRow(curRow);
  610. }
  611. void OBSBasic::ActivateAudioSource(OBSSource source)
  612. {
  613. VolControl *vol = new VolControl(source);
  614. volumes.push_back(vol);
  615. ui->volumeWidgets->layout()->addWidget(vol);
  616. }
  617. void OBSBasic::DeactivateAudioSource(OBSSource source)
  618. {
  619. for (size_t i = 0; i < volumes.size(); i++) {
  620. if (volumes[i]->GetSource() == source) {
  621. delete volumes[i];
  622. volumes.erase(volumes.begin() + i);
  623. break;
  624. }
  625. }
  626. }
  627. bool OBSBasic::QueryRemoveSource(obs_source_t source)
  628. {
  629. const char *name = obs_source_getname(source);
  630. QString text = QTStr("ConfirmRemove.Text");
  631. text.replace("$1", QT_UTF8(name));
  632. QMessageBox::StandardButton button;
  633. button = QMessageBox::question(this,
  634. QTStr("ConfirmRemove.Remove"), text);
  635. return button == QMessageBox::Yes;
  636. }
  637. void OBSBasic::RemoveSelectedScene()
  638. {
  639. OBSScene scene = GetCurrentScene();
  640. if (scene) {
  641. obs_source_t source = obs_scene_getsource(scene);
  642. if (QueryRemoveSource(source))
  643. obs_source_remove(source);
  644. }
  645. }
  646. void OBSBasic::RemoveSelectedSceneItem()
  647. {
  648. OBSSceneItem item = GetCurrentSceneItem();
  649. if (item) {
  650. obs_source_t source = obs_sceneitem_getsource(item);
  651. if (QueryRemoveSource(source))
  652. obs_sceneitem_remove(item);
  653. }
  654. }
  655. /* OBS Callbacks */
  656. void OBSBasic::SceneItemAdded(void *data, calldata_t params)
  657. {
  658. OBSBasic *window = static_cast<OBSBasic*>(data);
  659. obs_sceneitem_t item = (obs_sceneitem_t)calldata_ptr(params, "item");
  660. QMetaObject::invokeMethod(window, "AddSceneItem",
  661. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  662. }
  663. void OBSBasic::SceneItemRemoved(void *data, calldata_t params)
  664. {
  665. OBSBasic *window = static_cast<OBSBasic*>(data);
  666. obs_sceneitem_t item = (obs_sceneitem_t)calldata_ptr(params, "item");
  667. QMetaObject::invokeMethod(window, "RemoveSceneItem",
  668. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  669. }
  670. void OBSBasic::SourceAdded(void *data, calldata_t params)
  671. {
  672. OBSBasic *window = static_cast<OBSBasic*>(data);
  673. obs_source_t source = (obs_source_t)calldata_ptr(params, "source");
  674. if (obs_scene_fromsource(source) != NULL)
  675. QMetaObject::invokeMethod(window,
  676. "AddScene",
  677. Q_ARG(OBSSource, OBSSource(source)));
  678. else
  679. window->sourceSceneRefs[source] = 0;
  680. }
  681. void OBSBasic::SourceRemoved(void *data, calldata_t params)
  682. {
  683. obs_source_t source = (obs_source_t)calldata_ptr(params, "source");
  684. if (obs_scene_fromsource(source) != NULL)
  685. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  686. "RemoveScene",
  687. Q_ARG(OBSSource, OBSSource(source)));
  688. }
  689. void OBSBasic::SourceActivated(void *data, calldata_t params)
  690. {
  691. obs_source_t source = (obs_source_t)calldata_ptr(params, "source");
  692. uint32_t flags = obs_source_get_output_flags(source);
  693. if (flags & OBS_SOURCE_AUDIO)
  694. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  695. "ActivateAudioSource",
  696. Q_ARG(OBSSource, OBSSource(source)));
  697. }
  698. void OBSBasic::SourceDeactivated(void *data, calldata_t params)
  699. {
  700. obs_source_t source = (obs_source_t)calldata_ptr(params, "source");
  701. uint32_t flags = obs_source_get_output_flags(source);
  702. if (flags & OBS_SOURCE_AUDIO)
  703. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  704. "DeactivateAudioSource",
  705. Q_ARG(OBSSource, OBSSource(source)));
  706. }
  707. void OBSBasic::SourceRenamed(void *data, calldata_t params)
  708. {
  709. const char *newName = calldata_string(params, "new_name");
  710. const char *prevName = calldata_string(params, "prev_name");
  711. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  712. "RenameSources",
  713. Q_ARG(QString, QT_UTF8(newName)),
  714. Q_ARG(QString, QT_UTF8(prevName)));
  715. }
  716. void OBSBasic::ChannelChanged(void *data, calldata_t params)
  717. {
  718. obs_source_t source = (obs_source_t)calldata_ptr(params, "source");
  719. uint32_t channel = (uint32_t)calldata_int(params, "channel");
  720. if (channel == 0)
  721. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  722. "UpdateSceneSelection",
  723. Q_ARG(OBSSource, OBSSource(source)));
  724. }
  725. void OBSBasic::DrawBackdrop(float cx, float cy)
  726. {
  727. if (!box)
  728. return;
  729. effect_t solid = obs_get_solid_effect();
  730. eparam_t color = effect_getparambyname(solid, "color");
  731. technique_t tech = effect_gettechnique(solid, "Solid");
  732. vec4 colorVal;
  733. vec4_set(&colorVal, 0.0f, 0.0f, 0.0f, 1.0f);
  734. effect_setvec4(color, &colorVal);
  735. technique_begin(tech);
  736. technique_beginpass(tech, 0);
  737. gs_matrix_push();
  738. gs_matrix_identity();
  739. gs_matrix_scale3f(float(cx), float(cy), 1.0f);
  740. gs_load_vertexbuffer(box);
  741. gs_draw(GS_TRISTRIP, 0, 0);
  742. gs_matrix_pop();
  743. technique_endpass(tech);
  744. technique_end(tech);
  745. gs_load_vertexbuffer(nullptr);
  746. }
  747. void OBSBasic::RenderMain(void *data, uint32_t cx, uint32_t cy)
  748. {
  749. OBSBasic *window = static_cast<OBSBasic*>(data);
  750. obs_video_info ovi;
  751. obs_get_video_info(&ovi);
  752. window->previewCX = int(window->previewScale * float(ovi.base_width));
  753. window->previewCY = int(window->previewScale * float(ovi.base_height));
  754. gs_viewport_push();
  755. gs_projection_push();
  756. /* --------------------------------------- */
  757. gs_ortho(0.0f, float(ovi.base_width), 0.0f, float(ovi.base_height),
  758. -100.0f, 100.0f);
  759. gs_setviewport(window->previewX, window->previewY,
  760. window->previewCX, window->previewCY);
  761. window->DrawBackdrop(float(ovi.base_width), float(ovi.base_height));
  762. obs_render_main_view();
  763. gs_load_vertexbuffer(nullptr);
  764. /* --------------------------------------- */
  765. float right = float(window->ui->preview->width()) - window->previewX;
  766. float bottom = float(window->ui->preview->height()) - window->previewY;
  767. gs_ortho(-window->previewX, right,
  768. -window->previewY, bottom,
  769. -100.0f, 100.0f);
  770. gs_resetviewport();
  771. window->ui->preview->DrawSceneEditing();
  772. /* --------------------------------------- */
  773. gs_projection_pop();
  774. gs_viewport_pop();
  775. UNUSED_PARAMETER(cx);
  776. UNUSED_PARAMETER(cy);
  777. }
  778. void OBSBasic::SceneItemMoveUp(void *data, calldata_t params)
  779. {
  780. OBSSceneItem item = (obs_sceneitem_t)calldata_ptr(params, "item");
  781. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  782. "MoveSceneItem",
  783. Q_ARG(OBSSceneItem, OBSSceneItem(item)),
  784. Q_ARG(order_movement, ORDER_MOVE_UP));
  785. }
  786. void OBSBasic::SceneItemMoveDown(void *data, calldata_t params)
  787. {
  788. OBSSceneItem item = (obs_sceneitem_t)calldata_ptr(params, "item");
  789. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  790. "MoveSceneItem",
  791. Q_ARG(OBSSceneItem, OBSSceneItem(item)),
  792. Q_ARG(order_movement, ORDER_MOVE_DOWN));
  793. }
  794. void OBSBasic::SceneItemMoveTop(void *data, calldata_t params)
  795. {
  796. OBSSceneItem item = (obs_sceneitem_t)calldata_ptr(params, "item");
  797. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  798. "MoveSceneItem",
  799. Q_ARG(OBSSceneItem, OBSSceneItem(item)),
  800. Q_ARG(order_movement, ORDER_MOVE_TOP));
  801. }
  802. void OBSBasic::SceneItemMoveBottom(void *data, calldata_t params)
  803. {
  804. OBSSceneItem item = (obs_sceneitem_t)calldata_ptr(params, "item");
  805. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  806. "MoveSceneItem",
  807. Q_ARG(OBSSceneItem, OBSSceneItem(item)),
  808. Q_ARG(order_movement, ORDER_MOVE_BOTTOM));
  809. }
  810. /* Main class functions */
  811. obs_service_t OBSBasic::GetService()
  812. {
  813. if (!service)
  814. service = obs_service_create("rtmp_common", NULL, NULL);
  815. return service;
  816. }
  817. void OBSBasic::SetService(obs_service_t newService)
  818. {
  819. if (newService) {
  820. if (service)
  821. obs_service_destroy(service);
  822. service = newService;
  823. }
  824. }
  825. bool OBSBasic::ResetVideo()
  826. {
  827. struct obs_video_info ovi;
  828. GetConfigFPS(ovi.fps_num, ovi.fps_den);
  829. ovi.graphics_module = App()->GetRenderModule();
  830. ovi.base_width = (uint32_t)config_get_uint(basicConfig,
  831. "Video", "BaseCX");
  832. ovi.base_height = (uint32_t)config_get_uint(basicConfig,
  833. "Video", "BaseCY");
  834. ovi.output_width = (uint32_t)config_get_uint(basicConfig,
  835. "Video", "OutputCX");
  836. ovi.output_height = (uint32_t)config_get_uint(basicConfig,
  837. "Video", "OutputCY");
  838. ovi.output_format = VIDEO_FORMAT_NV12;
  839. ovi.adapter = 0;
  840. ovi.gpu_conversion = true;
  841. QTToGSWindow(ui->preview->winId(), ovi.window);
  842. //required to make opengl display stuff on osx(?)
  843. ResizePreview(ovi.base_width, ovi.base_height);
  844. QSize size = GetPixelSize(ui->preview);
  845. ovi.window_width = size.width();
  846. ovi.window_height = size.height();
  847. if (!obs_reset_video(&ovi))
  848. return false;
  849. obs_add_draw_callback(OBSBasic::RenderMain, this);
  850. return true;
  851. }
  852. bool OBSBasic::ResetAudio()
  853. {
  854. struct audio_output_info ai;
  855. ai.name = "Main Audio Track";
  856. ai.format = AUDIO_FORMAT_FLOAT;
  857. ai.samples_per_sec = config_get_uint(basicConfig, "Audio",
  858. "SampleRate");
  859. const char *channelSetupStr = config_get_string(basicConfig,
  860. "Audio", "ChannelSetup");
  861. if (strcmp(channelSetupStr, "Mono") == 0)
  862. ai.speakers = SPEAKERS_MONO;
  863. else
  864. ai.speakers = SPEAKERS_STEREO;
  865. ai.buffer_ms = config_get_uint(basicConfig, "Audio", "BufferingTime");
  866. return obs_reset_audio(&ai);
  867. }
  868. void OBSBasic::ResetAudioDevice(const char *sourceId, const char *deviceName,
  869. const char *deviceDesc, int channel)
  870. {
  871. const char *deviceId = config_get_string(basicConfig, "Audio",
  872. deviceName);
  873. obs_source_t source;
  874. obs_data_t settings;
  875. bool same = false;
  876. source = obs_get_output_source(channel);
  877. if (source) {
  878. settings = obs_source_getsettings(source);
  879. const char *curId = obs_data_getstring(settings, "device_id");
  880. same = (strcmp(curId, deviceId) == 0);
  881. obs_data_release(settings);
  882. obs_source_release(source);
  883. }
  884. if (!same)
  885. obs_set_output_source(channel, nullptr);
  886. if (!same && strcmp(deviceId, "disabled") != 0) {
  887. obs_data_t settings = obs_data_create();
  888. obs_data_setstring(settings, "device_id", deviceId);
  889. source = obs_source_create(OBS_SOURCE_TYPE_INPUT,
  890. sourceId, deviceDesc, settings);
  891. obs_data_release(settings);
  892. obs_set_output_source(channel, source);
  893. obs_source_release(source);
  894. }
  895. }
  896. void OBSBasic::ResetAudioDevices()
  897. {
  898. ResetAudioDevice(App()->OutputAudioSource(), "DesktopDevice1",
  899. Str("Basic.DesktopDevice1"), 1);
  900. ResetAudioDevice(App()->OutputAudioSource(), "DesktopDevice2",
  901. Str("Basic.DesktopDevice2"), 2);
  902. ResetAudioDevice(App()->InputAudioSource(), "AuxDevice1",
  903. Str("Basic.AuxDevice1"), 3);
  904. ResetAudioDevice(App()->InputAudioSource(), "AuxDevice2",
  905. Str("Basic.AuxDevice2"), 4);
  906. ResetAudioDevice(App()->InputAudioSource(), "AuxDevice3",
  907. Str("Basic.AuxDevice3"), 5);
  908. }
  909. void OBSBasic::ResizePreview(uint32_t cx, uint32_t cy)
  910. {
  911. QSize targetSize;
  912. /* resize preview panel to fix to the top section of the window */
  913. targetSize = GetPixelSize(ui->preview);
  914. GetScaleAndCenterPos(int(cx), int(cy),
  915. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  916. targetSize.height() - PREVIEW_EDGE_SIZE * 2,
  917. previewX, previewY, previewScale);
  918. previewX += float(PREVIEW_EDGE_SIZE);
  919. previewY += float(PREVIEW_EDGE_SIZE);
  920. if (isVisible()) {
  921. if (resizeTimer)
  922. killTimer(resizeTimer);
  923. resizeTimer = startTimer(100);
  924. }
  925. }
  926. void OBSBasic::closeEvent(QCloseEvent *event)
  927. {
  928. QWidget::closeEvent(event);
  929. if (!event->isAccepted())
  930. return;
  931. // remove draw callback in case our drawable surfaces go away before
  932. // the destructor gets called
  933. obs_remove_draw_callback(OBSBasic::RenderMain, this);
  934. }
  935. void OBSBasic::changeEvent(QEvent *event)
  936. {
  937. /* TODO */
  938. UNUSED_PARAMETER(event);
  939. }
  940. void OBSBasic::resizeEvent(QResizeEvent *event)
  941. {
  942. struct obs_video_info ovi;
  943. if (obs_get_video_info(&ovi))
  944. ResizePreview(ovi.base_width, ovi.base_height);
  945. UNUSED_PARAMETER(event);
  946. }
  947. void OBSBasic::timerEvent(QTimerEvent *event)
  948. {
  949. if (event->timerId() == resizeTimer) {
  950. killTimer(resizeTimer);
  951. resizeTimer = 0;
  952. QSize size = GetPixelSize(ui->preview);
  953. obs_resize(size.width(), size.height());
  954. }
  955. }
  956. void OBSBasic::on_action_New_triggered()
  957. {
  958. /* TODO */
  959. }
  960. void OBSBasic::on_action_Open_triggered()
  961. {
  962. /* TODO */
  963. }
  964. void OBSBasic::on_action_Save_triggered()
  965. {
  966. /* TODO */
  967. }
  968. void OBSBasic::on_action_Settings_triggered()
  969. {
  970. OBSBasicSettings settings(this);
  971. settings.exec();
  972. }
  973. void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current,
  974. QListWidgetItem *prev)
  975. {
  976. obs_source_t source = NULL;
  977. if (sceneChanging)
  978. return;
  979. if (current) {
  980. obs_scene_t scene;
  981. scene = current->data(Qt::UserRole).value<OBSScene>();
  982. source = obs_scene_getsource(scene);
  983. }
  984. /* TODO: allow transitions */
  985. obs_set_output_source(0, source);
  986. UNUSED_PARAMETER(prev);
  987. }
  988. void OBSBasic::EditSceneName()
  989. {
  990. ui->scenes->editItem(ui->scenes->currentItem());
  991. }
  992. void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos)
  993. {
  994. QListWidgetItem *item = ui->scenes->itemAt(pos);
  995. QMenu popup;
  996. popup.addAction(QTStr("Add"),
  997. this, SLOT(on_actionAddScene_triggered()));
  998. if (item)
  999. popup.addAction(QTStr("Remove"),
  1000. this, SLOT(RemoveSelectedScene()));
  1001. popup.exec(QCursor::pos());
  1002. }
  1003. void OBSBasic::on_actionAddScene_triggered()
  1004. {
  1005. string name;
  1006. QString format{QTStr("Basic.Main.DefaultSceneName.Text")};
  1007. int i = 1;
  1008. QString placeHolderText = format.arg(i);
  1009. obs_source_t source = nullptr;
  1010. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  1011. obs_source_release(source);
  1012. placeHolderText = format.arg(++i);
  1013. }
  1014. bool accepted = NameDialog::AskForName(this,
  1015. QTStr("Basic.Main.AddSceneDlg.Title"),
  1016. QTStr("Basic.Main.AddSceneDlg.Text"),
  1017. name,
  1018. placeHolderText);
  1019. if (accepted) {
  1020. if (name.empty()) {
  1021. QMessageBox::information(this,
  1022. QTStr("NoNameEntered"),
  1023. QTStr("NoNameEntered"));
  1024. on_actionAddScene_triggered();
  1025. return;
  1026. }
  1027. obs_source_t source = obs_get_source_by_name(name.c_str());
  1028. if (source) {
  1029. QMessageBox::information(this,
  1030. QTStr("NameExists.Title"),
  1031. QTStr("NameExists.Text"));
  1032. obs_source_release(source);
  1033. on_actionAddScene_triggered();
  1034. return;
  1035. }
  1036. obs_scene_t scene = obs_scene_create(name.c_str());
  1037. source = obs_scene_getsource(scene);
  1038. obs_add_source(source);
  1039. obs_scene_release(scene);
  1040. obs_set_output_source(0, source);
  1041. }
  1042. }
  1043. void OBSBasic::on_actionRemoveScene_triggered()
  1044. {
  1045. OBSScene scene = GetCurrentScene();
  1046. obs_source_t source = obs_scene_getsource(scene);
  1047. if (source && QueryRemoveSource(source))
  1048. obs_source_remove(source);
  1049. }
  1050. void OBSBasic::on_actionSceneProperties_triggered()
  1051. {
  1052. /* TODO */
  1053. }
  1054. void OBSBasic::on_actionSceneUp_triggered()
  1055. {
  1056. /* TODO */
  1057. }
  1058. void OBSBasic::on_actionSceneDown_triggered()
  1059. {
  1060. /* TODO */
  1061. }
  1062. void OBSBasic::on_sources_currentItemChanged(QListWidgetItem *current,
  1063. QListWidgetItem *prev)
  1064. {
  1065. auto select_one = [] (obs_scene_t scene, obs_sceneitem_t item,
  1066. void *param)
  1067. {
  1068. obs_sceneitem_t selectedItem =
  1069. *reinterpret_cast<OBSSceneItem*>(param);
  1070. obs_sceneitem_select(item, (selectedItem == item));
  1071. UNUSED_PARAMETER(scene);
  1072. return true;
  1073. };
  1074. if (!current)
  1075. return;
  1076. OBSSceneItem item = current->data(Qt::UserRole).value<OBSSceneItem>();
  1077. obs_source_t source = obs_sceneitem_getsource(item);
  1078. if ((obs_source_get_output_flags(source) & OBS_SOURCE_VIDEO) == 0)
  1079. return;
  1080. obs_scene_enum_items(GetCurrentScene(), select_one, &item);
  1081. UNUSED_PARAMETER(prev);
  1082. }
  1083. void OBSBasic::EditSceneItemName()
  1084. {
  1085. ui->sources->editItem(ui->sources->currentItem());
  1086. }
  1087. void OBSBasic::on_sources_customContextMenuRequested(const QPoint &pos)
  1088. {
  1089. QListWidgetItem *item = ui->sources->itemAt(pos);
  1090. QMenu popup;
  1091. QPointer<QMenu> addSourceMenu = CreateAddSourcePopupMenu();
  1092. if (addSourceMenu)
  1093. popup.addMenu(addSourceMenu);
  1094. if (item) {
  1095. if (addSourceMenu)
  1096. popup.addSeparator();
  1097. popup.addAction(QTStr("Rename"), this,
  1098. SLOT(EditSceneItemName()));
  1099. popup.addAction(QTStr("Remove"), this,
  1100. SLOT(on_actionRemoveSource_triggered()),
  1101. QKeySequence::Delete);
  1102. popup.addSeparator();
  1103. popup.addMenu(ui->orderMenu);
  1104. popup.addMenu(ui->transformMenu);
  1105. popup.addSeparator();
  1106. popup.addAction(QTStr("Properties"), this,
  1107. SLOT(on_actionSourceProperties_triggered()));
  1108. }
  1109. popup.exec(QCursor::pos());
  1110. }
  1111. void OBSBasic::AddSource(const char *id)
  1112. {
  1113. if (id && *id) {
  1114. OBSBasicSourceSelect sourceSelect(this, id);
  1115. sourceSelect.exec();
  1116. }
  1117. }
  1118. QMenu *OBSBasic::CreateAddSourcePopupMenu()
  1119. {
  1120. const char *type;
  1121. bool foundValues = false;
  1122. size_t idx = 0;
  1123. QMenu *popup = new QMenu(QTStr("Add"));
  1124. while (obs_enum_input_types(idx++, &type)) {
  1125. const char *name = obs_source_getdisplayname(
  1126. OBS_SOURCE_TYPE_INPUT, type);
  1127. if (strcmp(type, "scene") == 0)
  1128. continue;
  1129. QAction *popupItem = new QAction(QT_UTF8(name), this);
  1130. popupItem->setData(QT_UTF8(type));
  1131. connect(popupItem, SIGNAL(triggered(bool)),
  1132. this, SLOT(AddSourceFromAction()));
  1133. popup->addAction(popupItem);
  1134. foundValues = true;
  1135. }
  1136. if (!foundValues) {
  1137. delete popup;
  1138. popup = nullptr;
  1139. }
  1140. return popup;
  1141. }
  1142. void OBSBasic::AddSourceFromAction()
  1143. {
  1144. QAction *action = qobject_cast<QAction*>(sender());
  1145. if (!action)
  1146. return;
  1147. AddSource(QT_TO_UTF8(action->data().toString()));
  1148. }
  1149. void OBSBasic::AddSourcePopupMenu(const QPoint &pos)
  1150. {
  1151. if (!GetCurrentScene()) {
  1152. // Tell the user he needs a scene first (help beginners).
  1153. QMessageBox::information(this,
  1154. QTStr("Basic.Main.AddSourceHelp.Title"),
  1155. QTStr("Basic.Main.AddSourceHelp.Text"));
  1156. return;
  1157. }
  1158. QPointer<QMenu> popup = CreateAddSourcePopupMenu();
  1159. if (popup)
  1160. popup->exec(pos);
  1161. }
  1162. void OBSBasic::on_actionAddSource_triggered()
  1163. {
  1164. AddSourcePopupMenu(QCursor::pos());
  1165. }
  1166. void OBSBasic::on_actionRemoveSource_triggered()
  1167. {
  1168. OBSSceneItem item = GetCurrentSceneItem();
  1169. obs_source_t source = obs_sceneitem_getsource(item);
  1170. if (source && QueryRemoveSource(source))
  1171. obs_sceneitem_remove(item);
  1172. }
  1173. void OBSBasic::on_actionSourceProperties_triggered()
  1174. {
  1175. OBSSceneItem item = GetCurrentSceneItem();
  1176. OBSSource source = obs_sceneitem_getsource(item);
  1177. if (source) {
  1178. delete properties;
  1179. properties = new OBSBasicProperties(this, source);
  1180. properties->Init();
  1181. }
  1182. }
  1183. void OBSBasic::on_actionSourceUp_triggered()
  1184. {
  1185. OBSSceneItem item = GetCurrentSceneItem();
  1186. obs_sceneitem_setorder(item, ORDER_MOVE_UP);
  1187. }
  1188. void OBSBasic::on_actionSourceDown_triggered()
  1189. {
  1190. OBSSceneItem item = GetCurrentSceneItem();
  1191. obs_sceneitem_setorder(item, ORDER_MOVE_DOWN);
  1192. }
  1193. void OBSBasic::on_actionMoveUp_triggered()
  1194. {
  1195. OBSSceneItem item = GetCurrentSceneItem();
  1196. obs_sceneitem_setorder(item, ORDER_MOVE_UP);
  1197. }
  1198. void OBSBasic::on_actionMoveDown_triggered()
  1199. {
  1200. OBSSceneItem item = GetCurrentSceneItem();
  1201. obs_sceneitem_setorder(item, ORDER_MOVE_DOWN);
  1202. }
  1203. void OBSBasic::on_actionMoveToTop_triggered()
  1204. {
  1205. OBSSceneItem item = GetCurrentSceneItem();
  1206. obs_sceneitem_setorder(item, ORDER_MOVE_TOP);
  1207. }
  1208. void OBSBasic::on_actionMoveToBottom_triggered()
  1209. {
  1210. OBSSceneItem item = GetCurrentSceneItem();
  1211. obs_sceneitem_setorder(item, ORDER_MOVE_BOTTOM);
  1212. }
  1213. static char *ReadLogFile(const char *log)
  1214. {
  1215. BPtr<char> logDir(os_get_config_path("obs-studio/logs"));
  1216. string path = (char*)logDir;
  1217. path += "/";
  1218. path += log;
  1219. char *file = os_quick_read_utf8_file(path.c_str());
  1220. if (!file)
  1221. blog(LOG_WARNING, "Failed to read log file %s", path.c_str());
  1222. return file;
  1223. }
  1224. void OBSBasic::UploadLog(const char *file)
  1225. {
  1226. dstr fileString = {};
  1227. stringstream ss;
  1228. string jsonData;
  1229. dstr_move_array(&fileString, ReadLogFile(file));
  1230. if (!fileString.array)
  1231. return;
  1232. if (!*fileString.array) {
  1233. dstr_free(&fileString);
  1234. return;
  1235. }
  1236. ui->menuLogFiles->setEnabled(false);
  1237. dstr_replace(&fileString, "\\", "\\\\");
  1238. dstr_replace(&fileString, "\"", "\\\"");
  1239. dstr_replace(&fileString, "\n", "\\n");
  1240. dstr_replace(&fileString, "\r", "\\r");
  1241. dstr_replace(&fileString, "\t", "\\t");
  1242. dstr_replace(&fileString, "\t", "\\t");
  1243. dstr_replace(&fileString, "/", "\\/");
  1244. ss << "{ \"public\": false, \"description\": \"OBS " <<
  1245. App()->GetVersionString() << " log file uploaded at " <<
  1246. CurrentDateTimeString() << "\", \"files\": { \"" <<
  1247. file << "\": { \"content\": \"" <<
  1248. fileString.array << "\" } } }";
  1249. jsonData = std::move(ss.str());
  1250. logUploadPostData.setData(jsonData.c_str(), (int)jsonData.size());
  1251. QUrl url("https://api.github.com/gists");
  1252. logUploadReply = networkManager.post(QNetworkRequest(url),
  1253. &logUploadPostData);
  1254. connect(logUploadReply, SIGNAL(finished()),
  1255. this, SLOT(logUploadFinished()));
  1256. connect(logUploadReply, SIGNAL(readyRead()),
  1257. this, SLOT(logUploadRead()));
  1258. dstr_free(&fileString);
  1259. }
  1260. void OBSBasic::on_actionUploadCurrentLog_triggered()
  1261. {
  1262. UploadLog(App()->GetCurrentLog());
  1263. }
  1264. void OBSBasic::on_actionUploadLastLog_triggered()
  1265. {
  1266. UploadLog(App()->GetLastLog());
  1267. }
  1268. void OBSBasic::logUploadRead()
  1269. {
  1270. logUploadReturnData.push_back(logUploadReply->readAll());
  1271. }
  1272. void OBSBasic::logUploadFinished()
  1273. {
  1274. ui->menuLogFiles->setEnabled(true);
  1275. if (logUploadReply->error()) {
  1276. QMessageBox::information(this,
  1277. QTStr("LogReturnDialog.ErrorUploadingLog"),
  1278. logUploadReply->errorString());
  1279. return;
  1280. }
  1281. const char *jsonReply = logUploadReturnData.constData();
  1282. if (!jsonReply || !*jsonReply)
  1283. return;
  1284. obs_data_t returnData = obs_data_create_from_json(jsonReply);
  1285. QString logURL = obs_data_getstring(returnData, "html_url");
  1286. obs_data_release(returnData);
  1287. OBSLogReply logDialog(this, logURL);
  1288. logDialog.exec();
  1289. }
  1290. static void RenameListItem(QListWidget *listWidget, obs_source_t source,
  1291. const string &name)
  1292. {
  1293. const char *prevName = obs_source_getname(source);
  1294. obs_source_t foundSource = obs_get_source_by_name(name.c_str());
  1295. QListWidgetItem *listItem = listWidget->currentItem();
  1296. if (foundSource || name.compare(prevName) == 0 || name.empty()) {
  1297. listItem->setText(QT_UTF8(prevName));
  1298. obs_source_release(foundSource);
  1299. } else {
  1300. listItem->setText(QT_UTF8(name.c_str()));
  1301. obs_source_setname(source, name.c_str());
  1302. }
  1303. }
  1304. void OBSBasic::SceneNameEdited(QWidget *editor,
  1305. QAbstractItemDelegate::EndEditHint endHint)
  1306. {
  1307. OBSScene scene = GetCurrentScene();
  1308. QLineEdit *edit = qobject_cast<QLineEdit*>(editor);
  1309. string text = QT_TO_UTF8(edit->text().trimmed());
  1310. if (!scene)
  1311. return;
  1312. obs_source_t source = obs_scene_getsource(scene);
  1313. RenameListItem(ui->scenes, source, text);
  1314. UNUSED_PARAMETER(endHint);
  1315. }
  1316. void OBSBasic::SceneItemNameEdited(QWidget *editor,
  1317. QAbstractItemDelegate::EndEditHint endHint)
  1318. {
  1319. OBSSceneItem item = GetCurrentSceneItem();
  1320. QLineEdit *edit = qobject_cast<QLineEdit*>(editor);
  1321. string text = QT_TO_UTF8(edit->text().trimmed());
  1322. if (!item)
  1323. return;
  1324. obs_source_t source = obs_sceneitem_getsource(item);
  1325. RenameListItem(ui->sources, source, text);
  1326. UNUSED_PARAMETER(endHint);
  1327. }
  1328. void OBSBasic::StreamingStart()
  1329. {
  1330. ui->streamButton->setText("Stop Streaming");
  1331. ui->streamButton->setEnabled(true);
  1332. }
  1333. void OBSBasic::StreamingStop(int code)
  1334. {
  1335. const char *errorMessage;
  1336. switch (code) {
  1337. case OBS_OUTPUT_BAD_PATH:
  1338. errorMessage = Str("Output.ConnectFail.BadPath");
  1339. break;
  1340. case OBS_OUTPUT_CONNECT_FAILED:
  1341. errorMessage = Str("Output.ConnectFail.ConnectFailed");
  1342. break;
  1343. case OBS_OUTPUT_INVALID_STREAM:
  1344. errorMessage = Str("Output.ConnectFail.InvalidStream");
  1345. break;
  1346. default:
  1347. case OBS_OUTPUT_ERROR:
  1348. errorMessage = Str("Output.ConnectFail.Error");
  1349. break;
  1350. case OBS_OUTPUT_DISCONNECTED:
  1351. /* doesn't happen if output is set to reconnect. note that
  1352. * reconnects are handled in the output, not in the UI */
  1353. errorMessage = Str("Output.ConnectFail.Disconnected");
  1354. }
  1355. activeRefs--;
  1356. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  1357. ui->streamButton->setEnabled(true);
  1358. if (code != OBS_OUTPUT_SUCCESS)
  1359. QMessageBox::information(this,
  1360. QTStr("Output.ConnectFail.Title"),
  1361. QT_UTF8(errorMessage));
  1362. }
  1363. void OBSBasic::RecordingStop()
  1364. {
  1365. activeRefs--;
  1366. ui->recordButton->setText(QTStr("Basic.Main.StartRecording"));
  1367. }
  1368. void OBSBasic::SetupEncoders()
  1369. {
  1370. if (activeRefs == 0) {
  1371. obs_data_t x264Settings = obs_data_create();
  1372. obs_data_t aacSettings = obs_data_create();
  1373. int videoBitrate = config_get_uint(basicConfig, "SimpleOutput",
  1374. "VBitrate");
  1375. int audioBitrate = config_get_uint(basicConfig, "SimpleOutput",
  1376. "ABitrate");
  1377. obs_data_setint(x264Settings, "bitrate", videoBitrate);
  1378. obs_data_setbool(x264Settings, "cbr", true);
  1379. obs_data_setint(aacSettings, "bitrate", audioBitrate);
  1380. obs_encoder_update(x264, x264Settings);
  1381. obs_encoder_update(aac, aacSettings);
  1382. obs_data_release(x264Settings);
  1383. obs_data_release(aacSettings);
  1384. obs_encoder_set_video(x264, obs_video());
  1385. obs_encoder_set_audio(aac, obs_audio());
  1386. }
  1387. }
  1388. void OBSBasic::on_streamButton_clicked()
  1389. {
  1390. if (obs_output_active(streamOutput)) {
  1391. obs_output_stop(streamOutput);
  1392. } else {
  1393. SaveService();
  1394. SetupEncoders();
  1395. obs_output_set_video_encoder(streamOutput, x264);
  1396. obs_output_set_audio_encoder(streamOutput, aac);
  1397. obs_output_set_service(streamOutput, service);
  1398. bool reconnect = config_get_bool(basicConfig, "SimpleOutput",
  1399. "Reconnect");
  1400. int retryDelay = config_get_uint(basicConfig, "SimpleOutput",
  1401. "RetryDelay");
  1402. int maxRetries = config_get_uint(basicConfig, "SimpleOutput",
  1403. "MaxRetries");
  1404. if (!reconnect)
  1405. maxRetries = 0;
  1406. obs_output_set_reconnect_settings(streamOutput, maxRetries,
  1407. retryDelay);
  1408. if (obs_output_start(streamOutput)) {
  1409. activeRefs++;
  1410. ui->streamButton->setEnabled(false);
  1411. ui->streamButton->setText(
  1412. QTStr("Basic.Main.Connecting"));
  1413. }
  1414. }
  1415. }
  1416. void OBSBasic::on_recordButton_clicked()
  1417. {
  1418. if (obs_output_active(fileOutput)) {
  1419. obs_output_stop(fileOutput);
  1420. } else {
  1421. const char *path = config_get_string(basicConfig,
  1422. "SimpleOutput", "FilePath");
  1423. os_dir_t dir = path ? os_opendir(path) : nullptr;
  1424. if (!dir) {
  1425. QMessageBox::information(this,
  1426. QTStr("Output.BadPath.Title"),
  1427. QTStr("Output.BadPath.Text"));
  1428. return;
  1429. }
  1430. os_closedir(dir);
  1431. string strPath;
  1432. strPath += path;
  1433. char lastChar = strPath.back();
  1434. if (lastChar != '/' && lastChar != '\\')
  1435. strPath += "/";
  1436. strPath += GenerateTimeDateFilename("flv");
  1437. SetupEncoders();
  1438. obs_output_set_video_encoder(fileOutput, x264);
  1439. obs_output_set_audio_encoder(fileOutput, aac);
  1440. obs_data_t settings = obs_data_create();
  1441. obs_data_setstring(settings, "path", strPath.c_str());
  1442. obs_output_update(fileOutput, settings);
  1443. obs_data_release(settings);
  1444. if (obs_output_start(fileOutput)) {
  1445. activeRefs++;
  1446. ui->recordButton->setText(
  1447. QTStr("Basic.Main.StopRecording"));
  1448. }
  1449. }
  1450. }
  1451. void OBSBasic::on_settingsButton_clicked()
  1452. {
  1453. OBSBasicSettings settings(this);
  1454. settings.exec();
  1455. }
  1456. void OBSBasic::GetFPSCommon(uint32_t &num, uint32_t &den) const
  1457. {
  1458. const char *val = config_get_string(basicConfig, "Video", "FPSCommon");
  1459. if (strcmp(val, "10") == 0) {
  1460. num = 10;
  1461. den = 1;
  1462. } else if (strcmp(val, "20") == 0) {
  1463. num = 20;
  1464. den = 1;
  1465. } else if (strcmp(val, "25") == 0) {
  1466. num = 25;
  1467. den = 1;
  1468. } else if (strcmp(val, "29.97") == 0) {
  1469. num = 30000;
  1470. den = 1001;
  1471. } else if (strcmp(val, "48") == 0) {
  1472. num = 48;
  1473. den = 1;
  1474. } else if (strcmp(val, "59.94") == 0) {
  1475. num = 60000;
  1476. den = 1001;
  1477. } else if (strcmp(val, "60") == 0) {
  1478. num = 60;
  1479. den = 1;
  1480. } else {
  1481. num = 30;
  1482. den = 1;
  1483. }
  1484. }
  1485. void OBSBasic::GetFPSInteger(uint32_t &num, uint32_t &den) const
  1486. {
  1487. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSInt");
  1488. den = 1;
  1489. }
  1490. void OBSBasic::GetFPSFraction(uint32_t &num, uint32_t &den) const
  1491. {
  1492. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNum");
  1493. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSDen");
  1494. }
  1495. void OBSBasic::GetFPSNanoseconds(uint32_t &num, uint32_t &den) const
  1496. {
  1497. num = 1000000000;
  1498. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNS");
  1499. }
  1500. void OBSBasic::GetConfigFPS(uint32_t &num, uint32_t &den) const
  1501. {
  1502. uint32_t type = config_get_uint(basicConfig, "Video", "FPSType");
  1503. if (type == 1) //"Integer"
  1504. GetFPSInteger(num, den);
  1505. else if (type == 2) //"Fraction"
  1506. GetFPSFraction(num, den);
  1507. else if (false) //"Nanoseconds", currently not implemented
  1508. GetFPSNanoseconds(num, den);
  1509. else
  1510. GetFPSCommon(num, den);
  1511. }
  1512. config_t OBSBasic::Config() const
  1513. {
  1514. return basicConfig;
  1515. }
  1516. void OBSBasic::on_actionEditTransform_triggered()
  1517. {
  1518. delete transformWindow;
  1519. transformWindow = new OBSBasicTransform(this);
  1520. transformWindow->show();
  1521. }
  1522. void OBSBasic::on_actionResetTransform_triggered()
  1523. {
  1524. auto func = [] (obs_scene_t scene, obs_sceneitem_t item, void *param)
  1525. {
  1526. if (!obs_sceneitem_selected(item))
  1527. return true;
  1528. obs_sceneitem_info info;
  1529. vec2_set(&info.pos, 0.0f, 0.0f);
  1530. vec2_set(&info.scale, 1.0f, 1.0f);
  1531. info.rot = 0.0f;
  1532. info.alignment = OBS_ALIGN_TOP | OBS_ALIGN_LEFT;
  1533. info.bounds_type = OBS_BOUNDS_NONE;
  1534. info.bounds_alignment = OBS_ALIGN_CENTER;
  1535. vec2_set(&info.bounds, 0.0f, 0.0f);
  1536. obs_sceneitem_set_info(item, &info);
  1537. UNUSED_PARAMETER(scene);
  1538. UNUSED_PARAMETER(param);
  1539. return true;
  1540. };
  1541. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  1542. }
  1543. static void GetItemBox(obs_sceneitem_t item, vec3 &tl, vec3 &br)
  1544. {
  1545. matrix4 boxTransform;
  1546. obs_sceneitem_get_box_transform(item, &boxTransform);
  1547. vec3_set(&tl, M_INFINITE, M_INFINITE, 0.0f);
  1548. vec3_set(&br, -M_INFINITE, -M_INFINITE, 0.0f);
  1549. auto GetMinPos = [&] (float x, float y)
  1550. {
  1551. vec3 pos;
  1552. vec3_set(&pos, x, y, 0.0f);
  1553. vec3_transform(&pos, &pos, &boxTransform);
  1554. vec3_min(&tl, &tl, &pos);
  1555. vec3_max(&br, &br, &pos);
  1556. };
  1557. GetMinPos(0.0f, 0.0f);
  1558. GetMinPos(1.0f, 0.0f);
  1559. GetMinPos(0.0f, 1.0f);
  1560. GetMinPos(1.0f, 1.0f);
  1561. }
  1562. static vec3 GetItemTL(obs_sceneitem_t item)
  1563. {
  1564. vec3 tl, br;
  1565. GetItemBox(item, tl, br);
  1566. return tl;
  1567. }
  1568. static void SetItemTL(obs_sceneitem_t item, const vec3 &tl)
  1569. {
  1570. vec3 newTL;
  1571. vec2 pos;
  1572. obs_sceneitem_getpos(item, &pos);
  1573. newTL = GetItemTL(item);
  1574. pos.x += tl.x - newTL.x;
  1575. pos.y += tl.y - newTL.y;
  1576. obs_sceneitem_setpos(item, &pos);
  1577. }
  1578. static bool RotateSelectedSources(obs_scene_t scene, obs_sceneitem_t item,
  1579. void *param)
  1580. {
  1581. if (!obs_sceneitem_selected(item))
  1582. return true;
  1583. float rot = *reinterpret_cast<float*>(param);
  1584. vec3 tl = GetItemTL(item);
  1585. rot += obs_sceneitem_getrot(item);
  1586. if (rot >= 360.0f) rot -= 360.0f;
  1587. else if (rot <= -360.0f) rot += 360.0f;
  1588. obs_sceneitem_setrot(item, rot);
  1589. SetItemTL(item, tl);
  1590. UNUSED_PARAMETER(scene);
  1591. UNUSED_PARAMETER(param);
  1592. return true;
  1593. };
  1594. void OBSBasic::on_actionRotate90CW_triggered()
  1595. {
  1596. float f90CW = 90.0f;
  1597. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CW);
  1598. }
  1599. void OBSBasic::on_actionRotate90CCW_triggered()
  1600. {
  1601. float f90CCW = -90.0f;
  1602. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CCW);
  1603. }
  1604. void OBSBasic::on_actionRotate180_triggered()
  1605. {
  1606. float f180 = 180.0f;
  1607. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f180);
  1608. }
  1609. static bool MultiplySelectedItemScale(obs_scene_t scene, obs_sceneitem_t item,
  1610. void *param)
  1611. {
  1612. vec2 &mul = *reinterpret_cast<vec2*>(param);
  1613. if (!obs_sceneitem_selected(item))
  1614. return true;
  1615. vec3 tl = GetItemTL(item);
  1616. vec2 scale;
  1617. obs_sceneitem_getscale(item, &scale);
  1618. vec2_mul(&scale, &scale, &mul);
  1619. obs_sceneitem_setscale(item, &scale);
  1620. SetItemTL(item, tl);
  1621. UNUSED_PARAMETER(scene);
  1622. return true;
  1623. }
  1624. void OBSBasic::on_actionFlipHorizontal_triggered()
  1625. {
  1626. vec2 scale;
  1627. vec2_set(&scale, -1.0f, 1.0f);
  1628. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  1629. &scale);
  1630. }
  1631. void OBSBasic::on_actionFlipVertical_triggered()
  1632. {
  1633. vec2 scale;
  1634. vec2_set(&scale, 1.0f, -1.0f);
  1635. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  1636. &scale);
  1637. }
  1638. static bool CenterAlignSelectedItems(obs_scene_t scene, obs_sceneitem_t item,
  1639. void *param)
  1640. {
  1641. obs_bounds_type boundsType = *reinterpret_cast<obs_bounds_type*>(param);
  1642. if (!obs_sceneitem_selected(item))
  1643. return true;
  1644. obs_video_info ovi;
  1645. obs_get_video_info(&ovi);
  1646. obs_sceneitem_info itemInfo;
  1647. vec2_set(&itemInfo.pos, 0.0f, 0.0f);
  1648. vec2_set(&itemInfo.scale, 1.0f, 1.0f);
  1649. itemInfo.alignment = OBS_ALIGN_LEFT | OBS_ALIGN_TOP;
  1650. itemInfo.rot = 0.0f;
  1651. vec2_set(&itemInfo.bounds,
  1652. float(ovi.base_width), float(ovi.base_height));
  1653. itemInfo.bounds_type = boundsType;
  1654. itemInfo.bounds_alignment = OBS_ALIGN_CENTER;
  1655. obs_sceneitem_set_info(item, &itemInfo);
  1656. UNUSED_PARAMETER(scene);
  1657. return true;
  1658. }
  1659. void OBSBasic::on_actionFitToScreen_triggered()
  1660. {
  1661. obs_bounds_type boundsType = OBS_BOUNDS_SCALE_INNER;
  1662. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  1663. &boundsType);
  1664. }
  1665. void OBSBasic::on_actionStretchToScreen_triggered()
  1666. {
  1667. obs_bounds_type boundsType = OBS_BOUNDS_STRETCH;
  1668. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  1669. &boundsType);
  1670. }
  1671. void OBSBasic::on_actionCenterToScreen_triggered()
  1672. {
  1673. auto func = [] (obs_scene_t scene, obs_sceneitem_t item, void *param)
  1674. {
  1675. vec3 tl, br, itemCenter, screenCenter, offset;
  1676. obs_video_info ovi;
  1677. if (!obs_sceneitem_selected(item))
  1678. return true;
  1679. obs_get_video_info(&ovi);
  1680. vec3_set(&screenCenter, float(ovi.base_width),
  1681. float(ovi.base_height), 0.0f);
  1682. vec3_mulf(&screenCenter, &screenCenter, 0.5f);
  1683. GetItemBox(item, tl, br);
  1684. vec3_sub(&itemCenter, &br, &tl);
  1685. vec3_mulf(&itemCenter, &itemCenter, 0.5f);
  1686. vec3_add(&itemCenter, &itemCenter, &tl);
  1687. vec3_sub(&offset, &screenCenter, &itemCenter);
  1688. vec3_add(&tl, &tl, &offset);
  1689. SetItemTL(item, tl);
  1690. UNUSED_PARAMETER(scene);
  1691. UNUSED_PARAMETER(param);
  1692. return true;
  1693. };
  1694. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  1695. }