window-basic-main.cpp 53 KB

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