window-basic-main.cpp 56 KB

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