window-basic-main.cpp 60 KB

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