window-basic-main.cpp 61 KB

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