window-basic-main.cpp 53 KB

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