window-basic-main.cpp 57 KB

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