window-basic-main.cpp 60 KB

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