window-basic-main.cpp 58 KB

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