-
Notifications
You must be signed in to change notification settings - Fork 113
Expand file tree
/
Copy pathnodeobs_service.cpp
More file actions
2880 lines (2394 loc) · 90.3 KB
/
Copy pathnodeobs_service.cpp
File metadata and controls
2880 lines (2394 loc) · 90.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/******************************************************************************
Copyright (C) 2016-2019 by Streamlabs (General Workings Inc)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#include "nodeobs_service.h"
#ifdef WIN32
#include <ShlObj.h>
#include <windows.h>
#include <filesystem>
#endif
#include "error.hpp"
#include "shared.hpp"
#include "utility.hpp"
#ifdef __APPLE__
#include <sys/types.h>
#include <sys/stat.h>
#endif
obs_output_t* streamingOutput = nullptr;
obs_output_t* recordingOutput = nullptr;
obs_output_t* replayBufferOutput = nullptr;
obs_output_t* virtualWebcamOutput = nullptr;
obs_encoder_t* audioSimpleStreamingEncoder = nullptr;
obs_encoder_t* audioSimpleRecordingEncoder = nullptr;
obs_encoder_t* audioAdvancedStreamingEncoder = nullptr;
obs_encoder_t* videoStreamingEncoder = nullptr;
obs_encoder_t* videoRecordingEncoder = nullptr;
obs_service_t* service = nullptr;
obs_encoder_t* streamArchiveEncVod = nullptr;
obs_encoder_t* aacTracks[MAX_AUDIO_MIXES];
std::string aacEncodersID[MAX_AUDIO_MIXES];
std::string aacSimpleRecEncID;
std::string aacStreamEncID;
std::string videoEncoder;
std::string videoQuality;
bool usingRecordingPreset = true;
bool recordingConfigured = false;
bool ffmpegOutput = false;
bool lowCPUx264 = false;
bool isStreaming = false;
bool isRecording = false;
bool isReplayBufferActive = false;
bool rpUsesRec = false;
bool rpUsesStream = false;
std::mutex signalMutex;
std::queue<SignalInfo> outputSignal;
std::thread releaseWorker;
static constexpr int kSoundtrackArchiveEncoderIdx = 1;
static constexpr int kSoundtrackArchiveTrackIdx = 5;
static obs_encoder_t *streamArchiveEncST = nullptr;
static bool twitchSoundtrackEnabled = false;
OBS_service::OBS_service() {}
OBS_service::~OBS_service() {}
void OBS_service::Register(ipc::server& srv)
{
std::shared_ptr<ipc::collection> cls = std::make_shared<ipc::collection>("NodeOBS_Service");
cls->register_function(std::make_shared<ipc::function>(
"OBS_service_resetAudioContext", std::vector<ipc::type>{}, OBS_service_resetAudioContext));
cls->register_function(std::make_shared<ipc::function>(
"OBS_service_resetVideoContext", std::vector<ipc::type>{}, OBS_service_resetVideoContext));
cls->register_function(std::make_shared<ipc::function>(
"OBS_service_startStreaming", std::vector<ipc::type>{}, OBS_service_startStreaming));
cls->register_function(std::make_shared<ipc::function>(
"OBS_service_startRecording", std::vector<ipc::type>{}, OBS_service_startRecording));
cls->register_function(std::make_shared<ipc::function>(
"OBS_service_startReplayBuffer", std::vector<ipc::type>{}, OBS_service_startReplayBuffer));
cls->register_function(std::make_shared<ipc::function>(
"OBS_service_stopStreaming", std::vector<ipc::type>{ipc::type::Int32}, OBS_service_stopStreaming));
cls->register_function(std::make_shared<ipc::function>(
"OBS_service_stopRecording", std::vector<ipc::type>{}, OBS_service_stopRecording));
cls->register_function(std::make_shared<ipc::function>(
"OBS_service_stopReplayBuffer", std::vector<ipc::type>{ipc::type::Int32}, OBS_service_stopReplayBuffer));
cls->register_function(std::make_shared<ipc::function>(
"OBS_service_canPauseRecording", std::vector<ipc::type>{}, OBS_service_canPauseRecording));
cls->register_function(std::make_shared<ipc::function>(
"OBS_service_pauseRecording", std::vector<ipc::type>{ipc::type::Int32}, OBS_service_pauseRecording));
cls->register_function(std::make_shared<ipc::function>(
"OBS_service_isPausedRecording", std::vector<ipc::type>{}, OBS_service_isPausedRecording));
cls->register_function(std::make_shared<ipc::function>(
"OBS_service_connectOutputSignals", std::vector<ipc::type>{}, OBS_service_connectOutputSignals));
cls->register_function(std::make_shared<ipc::function>("Query", std::vector<ipc::type>{}, Query));
cls->register_function(std::make_shared<ipc::function>(
"OBS_service_processReplayBufferHotkey", std::vector<ipc::type>{}, OBS_service_processReplayBufferHotkey));
cls->register_function(std::make_shared<ipc::function>(
"OBS_service_getLastReplay", std::vector<ipc::type>{}, OBS_service_getLastReplay));
cls->register_function(std::make_shared<ipc::function>(
"OBS_service_getLastRecording", std::vector<ipc::type>{}, OBS_service_getLastRecording));
cls->register_function(std::make_shared<ipc::function>(
"OBS_service_createVirtualWebcam", std::vector<ipc::type>{ipc::type::String}, OBS_service_createVirtualWebcam));
cls->register_function(std::make_shared<ipc::function>(
"OBS_service_removeVirtualWebcam", std::vector<ipc::type>{}, OBS_service_removeVirtualWebcam));
cls->register_function(std::make_shared<ipc::function>(
"OBS_service_startVirtualWebcam", std::vector<ipc::type>{}, OBS_service_startVirtualWebcam));
cls->register_function(std::make_shared<ipc::function>(
"OBS_service_stopVirtualWebcan", std::vector<ipc::type>{}, OBS_service_stopVirtualWebcan));
srv.register_collection(cls);
}
void OBS_service::OBS_service_resetAudioContext(
void* data,
const int64_t id,
const std::vector<ipc::value>& args,
std::vector<ipc::value>& rval)
{
if (!resetAudioContext(true)) {
PRETTY_ERROR_RETURN(ErrorCode::Error, "Failed OBS_service_resetAudioContext.");
} else {
rval.push_back(ipc::value((uint64_t)ErrorCode::Ok));
}
AUTO_DEBUG;
}
void OBS_service::OBS_service_resetVideoContext(
void* data,
const int64_t id,
const std::vector<ipc::value>& args,
std::vector<ipc::value>& rval)
{
int result = resetVideoContext(true);
if (result == OBS_VIDEO_SUCCESS) {
rval.push_back(ipc::value((uint64_t)ErrorCode::Ok));
} else {
rval.push_back(ipc::value((uint64_t)ErrorCode::Error));
rval.push_back(ipc::value(result));
}
AUTO_DEBUG;
}
void OBS_service::OBS_service_startStreaming(
void* data,
const int64_t id,
const std::vector<ipc::value>& args,
std::vector<ipc::value>& rval)
{
if (isStreamingOutputActive()) {
rval.push_back(ipc::value((uint64_t)ErrorCode::Ok));
AUTO_DEBUG;
return;
}
if (!startStreaming()) {
PRETTY_ERROR_RETURN(ErrorCode::Error, "Failed to start streaming!");
} else {
rval.push_back(ipc::value((uint64_t)ErrorCode::Ok));
}
AUTO_DEBUG;
}
void OBS_service::OBS_service_startRecording(
void* data,
const int64_t id,
const std::vector<ipc::value>& args,
std::vector<ipc::value>& rval)
{
if (isRecordingOutputActive()) {
rval.push_back(ipc::value((uint64_t)ErrorCode::Ok));
AUTO_DEBUG;
return;
}
if (!startRecording()) {
PRETTY_ERROR_RETURN(ErrorCode::Error, "Failed to start recording!");
} else {
rval.push_back(ipc::value((uint64_t)ErrorCode::Ok));
}
AUTO_DEBUG;
}
void OBS_service::OBS_service_startReplayBuffer(
void* data,
const int64_t id,
const std::vector<ipc::value>& args,
std::vector<ipc::value>& rval)
{
if (isReplayBufferOutputActive()) {
rval.push_back(ipc::value((uint64_t)ErrorCode::Ok));
AUTO_DEBUG;
return;
}
if (!startReplayBuffer()) {
PRETTY_ERROR_RETURN(ErrorCode::Error, "Failed to start the replay buffer!");
} else {
rval.push_back(ipc::value((uint64_t)ErrorCode::Ok));
}
AUTO_DEBUG;
}
void OBS_service::OBS_service_stopStreaming(
void* data,
const int64_t id,
const std::vector<ipc::value>& args,
std::vector<ipc::value>& rval)
{
stopStreaming((bool)args[0].value_union.i32);
rval.push_back(ipc::value((uint64_t)ErrorCode::Ok));
AUTO_DEBUG;
}
void OBS_service::OBS_service_stopRecording(
void* data,
const int64_t id,
const std::vector<ipc::value>& args,
std::vector<ipc::value>& rval)
{
stopRecording();
rval.push_back(ipc::value((uint64_t)ErrorCode::Ok));
AUTO_DEBUG;
}
void OBS_service::OBS_service_stopReplayBuffer(
void* data,
const int64_t id,
const std::vector<ipc::value>& args,
std::vector<ipc::value>& rval)
{
stopReplayBuffer((bool)args[0].value_union.i32);
rpUsesRec = false;
rpUsesStream = false;
rval.push_back(ipc::value((uint64_t)ErrorCode::Ok));
AUTO_DEBUG;
}
void OBS_service::OBS_service_canPauseRecording(
void* data,
const int64_t id,
const std::vector<ipc::value>& args,
std::vector<ipc::value>& rval)
{
bool result = canPauseRecording();
rval.push_back(ipc::value((uint64_t)ErrorCode::Ok));
rval.push_back(ipc::value(result));
AUTO_DEBUG;
}
void OBS_service::OBS_service_pauseRecording(
void* data,
const int64_t id,
const std::vector<ipc::value>& args,
std::vector<ipc::value>& rval)
{
bool result = pauseRecording((bool)args[0].value_union.i32);
rval.push_back(ipc::value((uint64_t)ErrorCode::Ok));
rval.push_back(ipc::value(result));
AUTO_DEBUG;
}
void OBS_service::OBS_service_isPausedRecording(
void* data,
const int64_t id,
const std::vector<ipc::value>& args,
std::vector<ipc::value>& rval)
{
bool result = isPausedRecording();
rval.push_back(ipc::value((uint64_t)ErrorCode::Ok));
rval.push_back(ipc::value(result));
AUTO_DEBUG;
}
bool OBS_service::resetAudioContext(bool reload)
{
struct obs_audio_info ai;
if (reload)
ConfigManager::getInstance().reloadConfig();
ai.samples_per_sec = config_get_uint(ConfigManager::getInstance().getBasic(), "Audio", "SampleRate");
const char* channelSetupStr = config_get_string(ConfigManager::getInstance().getBasic(), "Audio", "ChannelSetup");
if (strcmp(channelSetupStr, "Mono") == 0)
ai.speakers = SPEAKERS_MONO;
else if (strcmp(channelSetupStr, "2.1") == 0)
ai.speakers = SPEAKERS_2POINT1;
else if (strcmp(channelSetupStr, "4.0") == 0)
ai.speakers = SPEAKERS_4POINT0;
else if (strcmp(channelSetupStr, "4.1") == 0)
ai.speakers = SPEAKERS_4POINT1;
else if (strcmp(channelSetupStr, "5.1") == 0)
ai.speakers = SPEAKERS_5POINT1;
else if (strcmp(channelSetupStr, "7.1") == 0)
ai.speakers = SPEAKERS_7POINT1;
else
ai.speakers = SPEAKERS_STEREO;
return obs_reset_audio(&ai);
}
static uint64_t basicConfigGetUInt(const char *section, const char *name, bool defaultConf)
{
return (defaultConf) ?
config_get_default_uint(ConfigManager::getInstance().getBasic(), section, name) :
config_get_uint(ConfigManager::getInstance().getBasic(), section, name);
}
static const char *basicConfigGetString(const char *section, const char *name, bool defaultConf)
{
return (defaultConf) ?
config_get_default_string(ConfigManager::getInstance().getBasic(), section, name) :
config_get_string(ConfigManager::getInstance().getBasic(), section, name);
}
static inline enum video_format GetVideoFormatFromName(const char* name)
{
if (name != NULL) {
if (astrcmpi(name, "I420") == 0)
return VIDEO_FORMAT_I420;
else if (astrcmpi(name, "NV12") == 0)
return VIDEO_FORMAT_NV12;
else if (astrcmpi(name, "I444") == 0)
return VIDEO_FORMAT_I444;
#if 0 //currently unsupported
else if (astrcmpi(name, "YVYU") == 0)
return VIDEO_FORMAT_YVYU;
else if (astrcmpi(name, "YUY2") == 0)
return VIDEO_FORMAT_YUY2;
else if (astrcmpi(name, "UYVY") == 0)
return VIDEO_FORMAT_UYVY;
#endif
else
return VIDEO_FORMAT_RGBA;
} else {
return VIDEO_FORMAT_I420;
}
}
static inline enum obs_scale_type GetScaleType(const char* scaleTypeStr)
{
if (scaleTypeStr != NULL) {
if (astrcmpi(scaleTypeStr, "bilinear") == 0)
return OBS_SCALE_BILINEAR;
else if (astrcmpi(scaleTypeStr, "lanczos") == 0)
return OBS_SCALE_LANCZOS;
else
return OBS_SCALE_BICUBIC;
} else {
return OBS_SCALE_BICUBIC;
}
}
static inline const char* GetRenderModule(config_t* config)
{
const char* renderer = config_get_string(config, "Video", "Renderer");
const char* DL_D3D11 = "libobs-d3d11.dll";
const char* DL_OPENGL;
#ifdef _WIN32
DL_OPENGL = "libobs-opengl.dll";
#else
DL_OPENGL = "libobs-opengl.so";
#endif
if (renderer != NULL) {
return (astrcmpi(renderer, "Direct3D 11") == 0) ? DL_D3D11 : DL_OPENGL;
} else {
return DL_D3D11;
}
}
void GetFPSInteger(bool defaultConf, uint32_t& num, uint32_t& den)
{
num = (uint32_t)basicConfigGetUInt("Video", "FPSInt", defaultConf);
if (num <= 0)
num = 1;
den = 1;
}
void GetFPSFraction(bool defaultConf, uint32_t& num, uint32_t& den)
{
num = (uint32_t)basicConfigGetUInt("Video", "FPSNum", defaultConf);
if (num <= 0)
num = 1;
den = (uint32_t)basicConfigGetUInt("Video", "FPSDen", defaultConf);
if (den <= 0)
den = 1;
if ((num / den) <= 0) {
num = 1;
den = 1;
}
}
void GetFPSNanoseconds(bool defaultConf, uint32_t& num, uint32_t& den)
{
num = 1000000000;
den = (uint32_t)basicConfigGetUInt("Video", "FPSNS", defaultConf);
}
void GetFPSCommon(bool defaultConf, uint32_t& num, uint32_t& den)
{
const char* val = basicConfigGetString("Video", "FPSCommon", defaultConf);
if (val != NULL) {
if (strcmp(val, "10") == 0) {
num = 10;
den = 1;
} else if (strcmp(val, "20") == 0) {
num = 20;
den = 1;
} else if (strcmp(val, "24 NTSC") == 0) {
num = 24000;
den = 1001;
} else if (strcmp(val, "25") == 0) {
num = 25;
den = 1;
} else if (strcmp(val, "29.97") == 0) {
num = 30000;
den = 1001;
} else if (strcmp(val, "48") == 0) {
num = 48;
den = 1;
} else if (strcmp(val, "59.94") == 0) {
num = 60000;
den = 1001;
} else if (strcmp(val, "60") == 0) {
num = 60;
den = 1;
} else {
num = 30;
den = 1;
}
} else {
num = 30;
den = 1;
if (!defaultConf) {
config_set_uint(ConfigManager::getInstance().getBasic(), "Video", "FPSType", 0);
config_set_string(ConfigManager::getInstance().getBasic(), "Video", "FPSCommon", "30");
config_save_safe(ConfigManager::getInstance().getBasic(), "tmp", nullptr);
}
}
}
void GetConfigFPS(bool defaultConf, uint32_t& num, uint32_t& den)
{
uint64_t type = basicConfigGetUInt("Video", "FPSType", defaultConf);
if (type == 1) //"Integer"
GetFPSInteger(defaultConf, num, den);
else if (type == 2) //"Fraction"
GetFPSFraction(defaultConf, num, den);
else if (false) //"Nanoseconds", currently not implemented
GetFPSNanoseconds(defaultConf, num, den);
else
GetFPSCommon(defaultConf, num, den);
}
/* some nice default output resolution vals */
static const double vals[] = {1.0, 1.25, (1.0 / 0.75), 1.5, (1.0 / 0.6), 1.75, 2.0, 2.25, 2.5, 2.75, 3.0};
static const size_t numVals = sizeof(vals) / sizeof(double);
int OBS_service::resetVideoContext(bool reload, bool retryWithDefaultConf)
{
obs_video_info ovi = prepareOBSVideoInfo(reload, false);
config_save_safe(ConfigManager::getInstance().getBasic(), "tmp", nullptr);
blog(LOG_INFO, "About to reset the video context with the user configuration");
int errorcode = doResetVideoContext(ovi);
// OBS_VIDEO_NOT_SUPPORTED: any of the following functions fails:
// gl_init_extensions,
// CreateDXGIFactory1,
// DXGIFactory1::EnumAdapters1,
// D3D11CreateDevice,
// etc.
// OBS_VIDEO_INVALID_PARAM: A parameter is invalid.
// OBS_VIDEO_CURRENTLY_ACTIVE: Video is currently active.
// OBS_VIDEO_MODULE_NOT_FOUND: Could not load a dynamic library (ovi.graphics_module):
// libobs-d3d11.dll,
// libobs-opengl.
// OBS_VIDEO_FAIL: Generic failure.
if (retryWithDefaultConf && (errorcode == OBS_VIDEO_FAIL || errorcode == OBS_VIDEO_INVALID_PARAM)) {
blog(LOG_ERROR, "The video context reset with the user configuration failed: %d", errorcode);
ovi = prepareOBSVideoInfo(false, true);
blog(LOG_INFO, "About to reset the video context with the default configuration");
errorcode = doResetVideoContext(ovi);
if (errorcode == OBS_VIDEO_SUCCESS) {
keepFallbackVideoConfig(ovi);
} else {
blog(LOG_ERROR, "The video context reset with the default configuration failed: %d", errorcode);
}
}
return errorcode;
}
int OBS_service::doResetVideoContext(const obs_video_info& ovi)
{
try {
// obs_reset_video may change some parameters. For example,
// ovi->output_width &= 0xFFFFFFFC;
// ovi->output_height &= 0xFFFFFFFE;
// So just make a temporary copy and then forget about it.
obs_video_info tmp = ovi;
return obs_reset_video(&tmp);
} catch (const char* error) {
blog(LOG_ERROR, error);
return OBS_VIDEO_FAIL;
}
}
obs_video_info OBS_service::prepareOBSVideoInfo(bool reload, bool defaultConf)
{
obs_video_info ovi = {};
#ifdef _WIN32
ovi.graphics_module = "libobs-d3d11.dll";
#else
ovi.graphics_module = "libobs-opengl";
#endif
if (reload)
ConfigManager::getInstance().reloadConfig();
ovi.base_width = (uint32_t)basicConfigGetUInt("Video", "BaseCX", defaultConf);
ovi.base_height = (uint32_t)basicConfigGetUInt("Video", "BaseCY", defaultConf);
// Do we really need it?
#if 0
const char* outputMode = config_get_string(ConfigManager::getInstance().getBasic(), "Output", "Mode");
if (outputMode == NULL) {
outputMode = "Simple";
}
#endif
ovi.output_width = (uint32_t)basicConfigGetUInt("Video", "OutputCX", defaultConf);
ovi.output_height = (uint32_t)basicConfigGetUInt("Video", "OutputCY", defaultConf);
std::vector<std::pair<uint32_t, uint32_t>> resolutions = OBS_API::availableResolutions();
uint32_t limit_cx = 1920;
uint32_t limit_cy = 1080;
if (ovi.base_width == 0 || ovi.base_height == 0) {
for (int i = 0; i < resolutions.size(); i++) {
uint32_t nbPixels = resolutions.at(i).first * resolutions.at(i).second;
if (int(ovi.base_width * ovi.base_height) < nbPixels &&
nbPixels <= limit_cx * limit_cy) {
ovi.base_width = resolutions.at(i).first;
ovi.base_height = resolutions.at(i).second;
}
}
if (ovi.base_width == 0 || ovi.base_height == 0) {
ovi.base_width = 1920;
ovi.base_height = 1080;
}
}
if (!defaultConf) {
config_set_uint(ConfigManager::getInstance().getBasic(), "Video", "BaseCX", ovi.base_width);
config_set_uint(ConfigManager::getInstance().getBasic(), "Video", "BaseCY", ovi.base_height);
}
if (ovi.output_width == 0 || ovi.output_height == 0) {
if (ovi.base_width > 1280 && ovi.base_height > 720) {
int idx = 0;
do {
double use_val = 1.0;
if (idx < numVals) {
use_val = vals[idx];
} else {
use_val = vals[numVals - 1] + double(numVals - idx + 1) / 2.0;
}
ovi.output_width = uint32_t(double(ovi.base_width) / use_val);
ovi.output_height = uint32_t(double(ovi.base_height) / use_val);
idx++;
} while (ovi.output_width > 1280 && ovi.output_height > 720);
} else {
ovi.output_width = ovi.base_width;
ovi.output_height = ovi.base_height;
}
ovi.output_width = 1280;
ovi.output_height = 720;
if (!defaultConf) {
config_set_uint(ConfigManager::getInstance().getBasic(), "Video", "OutputCX", ovi.output_width);
config_set_uint(ConfigManager::getInstance().getBasic(), "Video", "OutputCY", ovi.output_height);
}
}
GetConfigFPS(defaultConf, ovi.fps_num, ovi.fps_den);
const char* colorFormat = basicConfigGetString("Video", "ColorFormat", defaultConf);
const char* colorSpace = basicConfigGetString("Video", "ColorSpace", defaultConf);
const char* colorRange = basicConfigGetString("Video", "ColorRange", defaultConf);
ovi.output_format = GetVideoFormatFromName(colorFormat);
ovi.adapter = 0;
ovi.gpu_conversion = true;
ovi.colorspace = astrcmpi(colorSpace, "601") == 0 ? VIDEO_CS_601 : VIDEO_CS_709;
ovi.range = astrcmpi(colorRange, "Full") == 0 ? VIDEO_RANGE_FULL : VIDEO_RANGE_PARTIAL;
const char* scaleTypeStr = basicConfigGetString("Video", "ScaleType", defaultConf);
ovi.scale_type = GetScaleType(scaleTypeStr);
blog(LOG_DEBUG, "Prepared obs_video_info:");
blog(LOG_DEBUG, " base_width: %u", ovi.base_width);
blog(LOG_DEBUG, " base_height: %u", ovi.base_height);
blog(LOG_DEBUG, " output_width: %u", ovi.output_width);
blog(LOG_DEBUG, " output_height: %u", ovi.output_height);
blog(LOG_DEBUG, " fps_num: %u", ovi.fps_num);
blog(LOG_DEBUG, " fps_den: %u", ovi.fps_den);
blog(LOG_DEBUG, " output_format: %u", static_cast<uint32_t>(ovi.output_format));
blog(LOG_DEBUG, " colorspace: %u", static_cast<uint32_t>(ovi.colorspace));
blog(LOG_DEBUG, " range: %u", static_cast<uint32_t>(ovi.range));
blog(LOG_DEBUG, " scale_type: %u", static_cast<uint32_t>(ovi.scale_type));
return ovi;
}
static void copyDefaultUIntToUserBasicConfig(const char* section, const char* name)
{
config_set_uint(ConfigManager::getInstance().getBasic(), section, name,
config_get_default_uint(ConfigManager::getInstance().getBasic(), section, name));
}
static void copyDefaultStringToUserBasicConfig(const char* section, const char* name)
{
config_set_string(ConfigManager::getInstance().getBasic(), section, name,
config_get_default_string(ConfigManager::getInstance().getBasic(), section, name));
}
void OBS_service::keepFallbackVideoConfig(const obs_video_info& ovi)
{
blog(LOG_DEBUG, "Saving the fallback/default video configuration to basic.ini");
// Overall, we only copy and save parameters
// which were used for the successful obs_reset_video call.
// Some values come from config_get_default_uint/config_get_default_string.
// The other values come from |ovi| because the default configuration
// does not have some of the actual values.
config_set_uint(ConfigManager::getInstance().getBasic(), "Video", "BaseCX", ovi.base_width);
config_set_uint(ConfigManager::getInstance().getBasic(), "Video", "BaseCY", ovi.base_height);
config_set_uint(ConfigManager::getInstance().getBasic(), "Video", "OutputCX", ovi.output_width);
config_set_uint(ConfigManager::getInstance().getBasic(), "Video", "OutputCY", ovi.output_height);
// Currently, there is no "FPSNS" in the default configuration,
// So we do not copy it here.
copyDefaultUIntToUserBasicConfig("Video", "FPSType");
copyDefaultUIntToUserBasicConfig("Video", "FPSCommon");
copyDefaultUIntToUserBasicConfig("Video", "FPSInt");
copyDefaultUIntToUserBasicConfig("Video", "FPSNum");
copyDefaultUIntToUserBasicConfig("Video", "FPSDen");
copyDefaultStringToUserBasicConfig("Video", "ColorFormat");
copyDefaultStringToUserBasicConfig("Video", "ColorSpace");
copyDefaultStringToUserBasicConfig("Video", "ColorRange");
copyDefaultStringToUserBasicConfig("Video", "ScaleType");
config_save_safe(ConfigManager::getInstance().getBasic(), "tmp", nullptr);
}
const char* FindAudioEncoderFromCodec(const char* type)
{
const char* alt_enc_id = nullptr;
size_t i = 0;
while (obs_enum_encoder_types(i++, &alt_enc_id)) {
if (alt_enc_id == nullptr)
continue;
const char* codec = obs_get_encoder_codec(alt_enc_id);
if (strcmp(type, codec) == 0) {
return alt_enc_id;
}
}
return nullptr;
}
bool OBS_service::createAudioEncoder(
obs_encoder_t** audioEncoder,
std::string& id,
int bitrate,
const char* name,
size_t idx)
{
const char* id_ = GetAACEncoderForBitrate(bitrate);
if (!id_) {
id.clear();
*audioEncoder = nullptr;
return false;
}
if (id == id_)
return true;
id = id_;
*audioEncoder = obs_audio_encoder_create(id_, name, nullptr, idx, nullptr);
if (*audioEncoder) {
return true;
}
return false;
}
bool OBS_service::createVideoStreamingEncoder()
{
const char* encoder = config_get_string(ConfigManager::getInstance().getBasic(), "SimpleOutput", "StreamEncoder");
if (encoder == NULL || !EncoderAvailable(encoder)) {
encoder = "obs_x264";
}
if (videoStreamingEncoder != NULL) {
obs_encoder_release(videoStreamingEncoder);
}
videoStreamingEncoder = obs_video_encoder_create(encoder, "streaming_h264", nullptr, nullptr);
if (videoStreamingEncoder == nullptr) {
return false;
}
updateVideoStreamingEncoder(true);
return true;
}
void OBS_service::createSimpleAudioStreamingEncoder()
{
std::string id;
if (audioSimpleStreamingEncoder) {
obs_encoder_release(audioSimpleStreamingEncoder);
audioSimpleStreamingEncoder = nullptr;
}
if (!createAudioEncoder(&audioSimpleStreamingEncoder, id, GetSimpleAudioBitrate(), "acc", 0)) {
throw "Failed to create audio simple recording encoder";
}
}
static inline bool valid_string(const char* str)
{
while (str && *str) {
if (*(str++) != ' ')
return true;
}
return false;
}
static void replace_text(struct dstr* str, size_t pos, size_t len, const char* new_text)
{
struct dstr front = {0};
struct dstr back = {0};
dstr_left(&front, str, pos);
dstr_right(&back, str, pos + len);
dstr_copy_dstr(str, &front);
dstr_cat(str, new_text);
dstr_cat_dstr(str, &back);
dstr_free(&front);
dstr_free(&back);
}
static void erase_ch(struct dstr* str, size_t pos)
{
struct dstr new_str = {0};
dstr_left(&new_str, str, pos);
dstr_cat(&new_str, str->array + pos + 1);
dstr_free(str);
*str = new_str;
}
char* os_generate_formatted_filename(const char* extension, bool space, const char* format)
{
time_t now = time(0);
struct tm* cur_time;
cur_time = localtime(&now);
const size_t spec_count = 23;
static const char* spec[][2] = {
{"%CCYY", "%Y"}, {"%YY", "%y"}, {"%MM", "%m"}, {"%DD", "%d"}, {"%hh", "%H"},
{"%mm", "%M"}, {"%ss", "%S"}, {"%%", "%%"},
{"%a", ""}, {"%A", ""}, {"%b", ""}, {"%B", ""}, {"%d", ""},
{"%H", ""}, {"%I", ""}, {"%m", ""}, {"%M", ""}, {"%p", ""},
{"%S", ""}, {"%y", ""}, {"%Y", ""}, {"%z", ""}, {"%Z", ""},
};
char convert[128] = {0};
struct dstr sf;
struct dstr c = {0};
size_t pos = 0;
dstr_init_copy(&sf, format);
while (pos < sf.len) {
for (size_t i = 0; i < spec_count && !convert[0]; i++) {
size_t len = strlen(spec[i][0]);
const char* cmp = sf.array + pos;
if (astrcmp_n(cmp, spec[i][0], len) == 0) {
if (strlen(spec[i][1]))
strftime(convert, sizeof(convert), spec[i][1], cur_time);
else
strftime(convert, sizeof(convert), spec[i][0], cur_time);
dstr_copy(&c, convert);
if (c.len && valid_string(c.array))
replace_text(&sf, pos, len, convert);
}
}
if (convert[0]) {
pos += strlen(convert);
convert[0] = 0;
} else if (!convert[0] && sf.array[pos] == '%') {
erase_ch(&sf, pos);
} else {
pos++;
}
}
if (!space)
dstr_replace(&sf, " ", "_");
dstr_cat_ch(&sf, '.');
dstr_cat(&sf, extension);
dstr_free(&c);
if (sf.len > 255)
dstr_mid(&sf, &sf, 0, 255);
return sf.array;
}
std::string GenerateSpecifiedFilename(const char* extension, bool noSpace, const char* format)
{
char* filename = os_generate_formatted_filename(extension, !noSpace, format);
if (filename == nullptr) {
throw "Invalid filename";
}
std::string result(filename);
bfree(filename);
return result;
}
static void FindBestFilename(std::string& strPath, bool noSpace)
{
int num = 2;
if (!os_file_exists(strPath.c_str()))
return;
const char* ext = strrchr(strPath.c_str(), '.');
if (!ext)
return;
int extStart = int(ext - strPath.c_str());
for (;;) {
std::string testPath = strPath;
std::string numStr;
numStr = noSpace ? "_" : " (";
numStr += std::to_string(num++);
if (!noSpace)
numStr += ")";
testPath.insert(extStart, numStr);
if (!os_file_exists(testPath.c_str())) {
strPath = testPath;
break;
}
}
}
static void remove_reserved_file_characters(std::string& s)
{
replace(s.begin(), s.end(), '/', '_');
replace(s.begin(), s.end(), '\\', '_');
replace(s.begin(), s.end(), '*', '_');
replace(s.begin(), s.end(), '?', '_');
replace(s.begin(), s.end(), '"', '_');
replace(s.begin(), s.end(), '|', '_');
replace(s.begin(), s.end(), ':', '_');
replace(s.begin(), s.end(), '>', '_');
replace(s.begin(), s.end(), '<', '_');
}
bool OBS_service::createVideoRecordingEncoder()
{
if (videoRecordingEncoder != NULL) {
obs_encoder_release(videoRecordingEncoder);
}
videoRecordingEncoder = obs_video_encoder_create("obs_x264", "simple_h264_recording", nullptr, nullptr);
if (videoRecordingEncoder == nullptr) {
return false;
}
return true;
}
bool OBS_service::createService()
{
const char* type = nullptr;
obs_data_t* data = nullptr;
obs_data_t* settings = nullptr;
obs_data_t* hotkey_data = nullptr;
struct stat buffer;
auto CreateNewService = [&]() {
service = obs_service_create("rtmp_common", "default_service", nullptr, nullptr);
if (service == nullptr) {
return false;
}
data = obs_data_create();
settings = obs_service_get_settings(service);
obs_data_set_string(settings, "streamType", "rtmp_common");
obs_data_set_string(settings, "service", "Twitch");
obs_data_set_bool(settings, "show_all", 0);
obs_data_set_string(settings, "server", "auto");
obs_data_set_string(settings, "key", "");
obs_data_set_string(data, "type", obs_service_get_type(service));
obs_data_set_obj(data, "settings", settings);
};
bool fileExist = (os_stat(ConfigManager::getInstance().getService().c_str(), &buffer) == 0);
if (!fileExist) {
CreateNewService();
} else {
// Verify if the service.json was corrupted
data = obs_data_create_from_json_file_safe(ConfigManager::getInstance().getService().c_str(), "bak");
if (data == nullptr) {
blog(LOG_WARNING, "Failed to create data from service json, using default properties!");
CreateNewService();
} else {
obs_data_set_default_string(data, "type", "rtmp_common");
type = obs_data_get_string(data, "type");
settings = obs_data_get_obj(data, "settings");
hotkey_data = obs_data_get_obj(data, "hotkeys");
// If the type is invalid it could cause a crash since internally obs uses strcmp (nullptr = undef behavior)
if (type == nullptr || strlen(type) == 0) {
obs_data_release(data);
obs_data_release(hotkey_data);
obs_data_release(settings);
blog(LOG_WARNING, "Failed to retrieve a valid service type from the data, using default properties!");
CreateNewService();
// Create the service normally since the service.json info looks valid
} else {
service = obs_service_create(type, "default_service", settings, hotkey_data);
if (service == nullptr) {
obs_data_release(data);
obs_data_release(hotkey_data);
obs_data_release(settings);
blog( LOG_ERROR, "Failed to create service using service info from a file!");
return false;
}
obs_data_release(hotkey_data);
}