window-basic-main.cpp 63 KB

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