window-basic-main.cpp 59 KB

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