window-basic-main.cpp 67 KB

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