window-basic-main.cpp 66 KB

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