window-basic-main-outputs.cpp 57.7 KB
Newer Older
J
jp9000 已提交
1
#include <string>
2
#include <algorithm>
J
jp9000 已提交
3
#include <QMessageBox>
4
#include "qt-wrappers.hpp"
5
#include "audio-encoders.hpp"
J
jp9000 已提交
6 7 8 9 10
#include "window-basic-main.hpp"
#include "window-basic-main-outputs.hpp"

using namespace std;

11 12
extern bool EncoderAvailable(const char *encoder);

13 14
volatile bool streaming_active = false;
volatile bool recording_active = false;
J
jp9000 已提交
15
volatile bool recording_paused = false;
16
volatile bool replaybuf_active = false;
J
jp9000 已提交
17
volatile bool virtualcam_active = false;
18

19 20
#define RTMP_PROTOCOL "rtmp"

J
jp9000 已提交
21 22
static void OBSStreamStarting(void *data, calldata_t *params)
{
J
jp9000 已提交
23 24
	BasicOutputHandler *output = static_cast<BasicOutputHandler *>(data);
	obs_output_t *obj = (obs_output_t *)calldata_ptr(params, "output");
J
jp9000 已提交
25 26 27 28 29 30

	int sec = (int)obs_output_get_active_delay(obj);
	if (sec == 0)
		return;

	output->delayActive = true;
J
jp9000 已提交
31 32
	QMetaObject::invokeMethod(output->main, "StreamDelayStarting",
				  Q_ARG(int, sec));
J
jp9000 已提交
33 34 35 36
}

static void OBSStreamStopping(void *data, calldata_t *params)
{
J
jp9000 已提交
37 38
	BasicOutputHandler *output = static_cast<BasicOutputHandler *>(data);
	obs_output_t *obj = (obs_output_t *)calldata_ptr(params, "output");
J
jp9000 已提交
39 40 41

	int sec = (int)obs_output_get_active_delay(obj);
	if (sec == 0)
42 43
		QMetaObject::invokeMethod(output->main, "StreamStopping");
	else
J
jp9000 已提交
44 45
		QMetaObject::invokeMethod(output->main, "StreamDelayStopping",
					  Q_ARG(int, sec));
J
jp9000 已提交
46 47
}

J
jp9000 已提交
48 49
static void OBSStartStreaming(void *data, calldata_t *params)
{
J
jp9000 已提交
50
	BasicOutputHandler *output = static_cast<BasicOutputHandler *>(data);
51
	output->streamingActive = true;
52
	os_atomic_set_bool(&streaming_active, true);
J
jp9000 已提交
53 54 55 56 57 58 59
	QMetaObject::invokeMethod(output->main, "StreamingStart");

	UNUSED_PARAMETER(params);
}

static void OBSStopStreaming(void *data, calldata_t *params)
{
J
jp9000 已提交
60
	BasicOutputHandler *output = static_cast<BasicOutputHandler *>(data);
J
jp9000 已提交
61
	int code = (int)calldata_int(params, "code");
62 63 64
	const char *last_error = calldata_string(params, "last_error");

	QString arg_last_error = QString::fromUtf8(last_error);
J
jp9000 已提交
65

66
	output->streamingActive = false;
J
jp9000 已提交
67
	output->delayActive = false;
68
	os_atomic_set_bool(&streaming_active, false);
J
jp9000 已提交
69 70 71
	QMetaObject::invokeMethod(output->main, "StreamingStop",
				  Q_ARG(int, code),
				  Q_ARG(QString, arg_last_error));
J
jp9000 已提交
72 73 74 75
}

static void OBSStartRecording(void *data, calldata_t *params)
{
J
jp9000 已提交
76
	BasicOutputHandler *output = static_cast<BasicOutputHandler *>(data);
J
jp9000 已提交
77

78
	output->recordingActive = true;
79
	os_atomic_set_bool(&recording_active, true);
J
jp9000 已提交
80 81 82 83 84 85 86
	QMetaObject::invokeMethod(output->main, "RecordingStart");

	UNUSED_PARAMETER(params);
}

static void OBSStopRecording(void *data, calldata_t *params)
{
J
jp9000 已提交
87
	BasicOutputHandler *output = static_cast<BasicOutputHandler *>(data);
88
	int code = (int)calldata_int(params, "code");
89 90 91
	const char *last_error = calldata_string(params, "last_error");

	QString arg_last_error = QString::fromUtf8(last_error);
J
jp9000 已提交
92

93
	output->recordingActive = false;
94
	os_atomic_set_bool(&recording_active, false);
J
jp9000 已提交
95
	os_atomic_set_bool(&recording_paused, false);
J
jp9000 已提交
96 97 98
	QMetaObject::invokeMethod(output->main, "RecordingStop",
				  Q_ARG(int, code),
				  Q_ARG(QString, arg_last_error));
J
jp9000 已提交
99 100 101 102

	UNUSED_PARAMETER(params);
}

103 104
static void OBSRecordStopping(void *data, calldata_t *params)
{
J
jp9000 已提交
105
	BasicOutputHandler *output = static_cast<BasicOutputHandler *>(data);
106 107 108 109 110
	QMetaObject::invokeMethod(output->main, "RecordStopping");

	UNUSED_PARAMETER(params);
}

J
jp9000 已提交
111 112
static void OBSStartReplayBuffer(void *data, calldata_t *params)
{
J
jp9000 已提交
113
	BasicOutputHandler *output = static_cast<BasicOutputHandler *>(data);
J
jp9000 已提交
114 115

	output->replayBufferActive = true;
116
	os_atomic_set_bool(&replaybuf_active, true);
J
jp9000 已提交
117 118 119 120 121 122 123
	QMetaObject::invokeMethod(output->main, "ReplayBufferStart");

	UNUSED_PARAMETER(params);
}

static void OBSStopReplayBuffer(void *data, calldata_t *params)
{
J
jp9000 已提交
124
	BasicOutputHandler *output = static_cast<BasicOutputHandler *>(data);
J
jp9000 已提交
125 126 127
	int code = (int)calldata_int(params, "code");

	output->replayBufferActive = false;
128
	os_atomic_set_bool(&replaybuf_active, false);
J
jp9000 已提交
129 130
	QMetaObject::invokeMethod(output->main, "ReplayBufferStop",
				  Q_ARG(int, code));
J
jp9000 已提交
131 132 133 134 135 136

	UNUSED_PARAMETER(params);
}

static void OBSReplayBufferStopping(void *data, calldata_t *params)
{
J
jp9000 已提交
137
	BasicOutputHandler *output = static_cast<BasicOutputHandler *>(data);
J
jp9000 已提交
138 139 140 141 142
	QMetaObject::invokeMethod(output->main, "ReplayBufferStopping");

	UNUSED_PARAMETER(params);
}

143 144 145 146 147 148 149
static void OBSReplayBufferSaved(void *data, calldata_t *)
{
	BasicOutputHandler *output = static_cast<BasicOutputHandler *>(data);
	QMetaObject::invokeMethod(output->main, "ReplayBufferSaved",
				  Qt::QueuedConnection);
}

J
jp9000 已提交
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
static void OBSStartVirtualCam(void *data, calldata_t *params)
{
	BasicOutputHandler *output = static_cast<BasicOutputHandler *>(data);

	output->virtualCamActive = true;
	os_atomic_set_bool(&virtualcam_active, true);
	QMetaObject::invokeMethod(output->main, "OnVirtualCamStart");

	UNUSED_PARAMETER(params);
}

static void OBSStopVirtualCam(void *data, calldata_t *params)
{
	BasicOutputHandler *output = static_cast<BasicOutputHandler *>(data);
	int code = (int)calldata_int(params, "code");

	output->virtualCamActive = false;
	os_atomic_set_bool(&virtualcam_active, false);
	QMetaObject::invokeMethod(output->main, "OnVirtualCamStop",
				  Q_ARG(int, code));

	UNUSED_PARAMETER(params);
}

J
jp9000 已提交
174 175
/* ------------------------------------------------------------------------ */

176
static bool CreateAACEncoder(OBSEncoder &res, string &id, int bitrate,
J
jp9000 已提交
177
			     const char *name, size_t idx)
P
Palana 已提交
178
{
179 180 181 182 183
	const char *id_ = GetAACEncoderForBitrate(bitrate);
	if (!id_) {
		id.clear();
		res = nullptr;
		return false;
P
Palana 已提交
184 185
	}

186 187 188 189 190 191 192 193 194 195 196 197
	if (id == id_)
		return true;

	id = id_;
	res = obs_audio_encoder_create(id_, name, nullptr, idx, nullptr);

	if (res) {
		obs_encoder_release(res);
		return true;
	}

	return false;
P
Palana 已提交
198 199 200
}

/* ------------------------------------------------------------------------ */
J
jp9000 已提交
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222

inline BasicOutputHandler::BasicOutputHandler(OBSBasic *main_) : main(main_)
{
	if (main->vcamEnabled) {
		virtualCam = obs_output_create("virtualcam_output",
					       "virtualcam_output", nullptr,
					       nullptr);
		obs_output_release(virtualCam);

		signal_handler_t *signal =
			obs_output_get_signal_handler(virtualCam);
		startVirtualCam.Connect(signal, "start", OBSStartVirtualCam,
					this);
		stopVirtualCam.Connect(signal, "stop", OBSStopVirtualCam, this);
	}
}

bool BasicOutputHandler::StartVirtualCam()
{
	if (main->vcamEnabled) {
		obs_output_set_media(virtualCam, obs_get_video(),
				     obs_get_audio());
223 224 225
		if (!Active())
			SetupOutputs();

J
jp9000 已提交
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
		return obs_output_start(virtualCam);
	}
	return false;
}

void BasicOutputHandler::StopVirtualCam()
{
	if (main->vcamEnabled) {
		obs_output_stop(virtualCam);
	}
}

bool BasicOutputHandler::VirtualCamActive() const
{
	if (main->vcamEnabled) {
		return obs_output_active(virtualCam);
	}
	return false;
}

/* ------------------------------------------------------------------------ */
P
Palana 已提交
247

J
jp9000 已提交
248
struct SimpleOutput : BasicOutputHandler {
J
jp9000 已提交
249 250 251
	OBSEncoder aacStreaming;
	OBSEncoder h264Streaming;
	OBSEncoder aacRecording;
252
	OBSEncoder aacArchive;
J
jp9000 已提交
253
	OBSEncoder h264Recording;
J
jp9000 已提交
254

J
jp9000 已提交
255 256
	string aacRecEncID;
	string aacStreamEncID;
257
	string aacArchiveEncID;
258

J
jp9000 已提交
259 260 261 262 263 264
	string videoEncoder;
	string videoQuality;
	bool usingRecordingPreset = false;
	bool recordingConfigured = false;
	bool ffmpegOutput = false;
	bool lowCPUx264 = false;
265

J
jp9000 已提交
266 267
	SimpleOutput(OBSBasic *main_);

268 269
	int CalcCRF(int crf);

270
	void UpdateStreamingSettings_amd(obs_data_t *settings, int bitrate);
271
	void UpdateRecordingSettings_x264_crf(int crf);
272
	void UpdateRecordingSettings_qsv11(int crf);
273
	void UpdateRecordingSettings_nvenc(int cqp);
274
	void UpdateRecordingSettings_amd_cqp(int cqp);
275 276
	void UpdateRecordingSettings();
	void UpdateRecordingAudioSettings();
J
jp9000 已提交
277 278
	virtual void Update() override;

279
	void SetupOutputs() override;
280
	int GetAudioBitrate() const;
J
jp9000 已提交
281

282
	void LoadRecordingPreset_h264(const char *encoder);
283 284 285
	void LoadRecordingPreset_Lossless();
	void LoadRecordingPreset();

286 287
	void LoadStreamingPreset_h264(const char *encoder);

J
jp9000 已提交
288 289 290
	void UpdateRecording();
	bool ConfigureRecording(bool useReplayBuffer);

291 292
	void SetupVodTrack(obs_service_t *service);

293
	virtual bool SetupStreaming(obs_service_t *service) override;
J
jp9000 已提交
294 295
	virtual bool StartStreaming(obs_service_t *service) override;
	virtual bool StartRecording() override;
J
jp9000 已提交
296
	virtual bool StartReplayBuffer() override;
297 298
	virtual void StopStreaming(bool force) override;
	virtual void StopRecording(bool force) override;
J
jp9000 已提交
299
	virtual void StopReplayBuffer(bool force) override;
J
jp9000 已提交
300 301
	virtual bool StreamingActive() const override;
	virtual bool RecordingActive() const override;
J
jp9000 已提交
302
	virtual bool ReplayBufferActive() const override;
J
jp9000 已提交
303 304
};

305 306
void SimpleOutput::LoadRecordingPreset_Lossless()
{
J
jp9000 已提交
307 308
	fileOutput = obs_output_create("ffmpeg_output", "simple_ffmpeg_output",
				       nullptr, nullptr);
309 310 311 312 313 314
	if (!fileOutput)
		throw "Failed to create recording FFmpeg output "
		      "(simple output)";
	obs_output_release(fileOutput);

	obs_data_t *settings = obs_data_create();
315
	obs_data_set_string(settings, "format_name", "avi");
316
	obs_data_set_string(settings, "video_encoder", "utvideo");
J
jp9000 已提交
317
	obs_data_set_string(settings, "audio_encoder", "pcm_s16le");
318

319 320
	int aMixes = 1;
	obs_output_set_mixers(fileOutput, aMixes);
321 322 323 324
	obs_output_update(fileOutput, settings);
	obs_data_release(settings);
}

325
void SimpleOutput::LoadRecordingPreset_h264(const char *encoderId)
326
{
J
jp9000 已提交
327 328
	h264Recording = obs_video_encoder_create(
		encoderId, "simple_h264_recording", nullptr, nullptr);
329 330 331
	if (!h264Recording)
		throw "Failed to create h264 recording encoder (simple output)";
	obs_encoder_release(h264Recording);
332
}
333

334 335
void SimpleOutput::LoadStreamingPreset_h264(const char *encoderId)
{
J
jp9000 已提交
336 337
	h264Streaming = obs_video_encoder_create(
		encoderId, "simple_h264_stream", nullptr, nullptr);
338 339 340
	if (!h264Streaming)
		throw "Failed to create h264 streaming encoder (simple output)";
	obs_encoder_release(h264Streaming);
341 342 343 344
}

void SimpleOutput::LoadRecordingPreset()
{
J
jp9000 已提交
345 346 347 348
	const char *quality =
		config_get_string(main->Config(), "SimpleOutput", "RecQuality");
	const char *encoder =
		config_get_string(main->Config(), "SimpleOutput", "RecEncoder");
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366

	videoEncoder = encoder;
	videoQuality = quality;
	ffmpegOutput = false;

	if (strcmp(quality, "Stream") == 0) {
		h264Recording = h264Streaming;
		aacRecording = aacStreaming;
		usingRecordingPreset = false;
		return;

	} else if (strcmp(quality, "Lossless") == 0) {
		LoadRecordingPreset_Lossless();
		usingRecordingPreset = true;
		ffmpegOutput = true;
		return;

	} else {
367 368 369 370 371 372 373 374 375
		lowCPUx264 = false;

		if (strcmp(encoder, SIMPLE_ENCODER_X264) == 0) {
			LoadRecordingPreset_h264("obs_x264");
		} else if (strcmp(encoder, SIMPLE_ENCODER_X264_LOWCPU) == 0) {
			LoadRecordingPreset_h264("obs_x264");
			lowCPUx264 = true;
		} else if (strcmp(encoder, SIMPLE_ENCODER_QSV) == 0) {
			LoadRecordingPreset_h264("obs_qsv11");
376 377
		} else if (strcmp(encoder, SIMPLE_ENCODER_AMD) == 0) {
			LoadRecordingPreset_h264("amd_amf_h264");
J
jp9000 已提交
378
		} else if (strcmp(encoder, SIMPLE_ENCODER_NVENC) == 0) {
379
			const char *id = EncoderAvailable("jim_nvenc")
J
jp9000 已提交
380 381
						 ? "jim_nvenc"
						 : "ffmpeg_nvenc";
382
			LoadRecordingPreset_h264(id);
383
		}
384
		usingRecordingPreset = true;
385 386

		if (!CreateAACEncoder(aacRecording, aacRecEncID, 192,
J
jp9000 已提交
387
				      "simple_aac_recording", 0))
388 389
			throw "Failed to create aac recording encoder "
			      "(simple output)";
390 391 392
	}
}

393 394
#define SIMPLE_ARCHIVE_NAME "simple_archive_aac"

J
jp9000 已提交
395 396
SimpleOutput::SimpleOutput(OBSBasic *main_) : BasicOutputHandler(main_)
{
397
	const char *encoder = config_get_string(main->Config(), "SimpleOutput",
J
jp9000 已提交
398
						"StreamEncoder");
399 400

	if (strcmp(encoder, SIMPLE_ENCODER_QSV) == 0) {
401
		LoadStreamingPreset_h264("obs_qsv11");
402 403

	} else if (strcmp(encoder, SIMPLE_ENCODER_AMD) == 0) {
404
		LoadStreamingPreset_h264("amd_amf_h264");
405 406

	} else if (strcmp(encoder, SIMPLE_ENCODER_NVENC) == 0) {
J
jp9000 已提交
407 408
		const char *id = EncoderAvailable("jim_nvenc") ? "jim_nvenc"
							       : "ffmpeg_nvenc";
409 410 411
		LoadStreamingPreset_h264(id);

	} else {
412
		LoadStreamingPreset_h264("obs_x264");
413
	}
J
jp9000 已提交
414

415
	if (!CreateAACEncoder(aacStreaming, aacStreamEncID, GetAudioBitrate(),
J
jp9000 已提交
416
			      "simple_aac", 0))
417
		throw "Failed to create aac streaming encoder (simple output)";
418
	if (!CreateAACEncoder(aacArchive, aacArchiveEncID, GetAudioBitrate(),
419
			      SIMPLE_ARCHIVE_NAME, 1))
420
		throw "Failed to create aac arhive encoder (simple output)";
J
jp9000 已提交
421

422 423 424
	LoadRecordingPreset();

	if (!ffmpegOutput) {
J
jp9000 已提交
425
		bool useReplayBuffer = config_get_bool(main->Config(),
J
jp9000 已提交
426
						       "SimpleOutput", "RecRB");
J
jp9000 已提交
427
		if (useReplayBuffer) {
428
			obs_data_t *hotkey;
J
jp9000 已提交
429 430
			const char *str = config_get_string(
				main->Config(), "Hotkeys", "ReplayBuffer");
431 432 433 434 435
			if (str)
				hotkey = obs_data_create_from_json(str);
			else
				hotkey = nullptr;

J
jp9000 已提交
436
			replayBuffer = obs_output_create("replay_buffer",
J
jp9000 已提交
437 438
							 Str("ReplayBuffer"),
							 nullptr, hotkey);
439 440

			obs_data_release(hotkey);
J
jp9000 已提交
441 442 443 444 445 446 447 448 449
			if (!replayBuffer)
				throw "Failed to create replay buffer output "
				      "(simple output)";
			obs_output_release(replayBuffer);

			signal_handler_t *signal =
				obs_output_get_signal_handler(replayBuffer);

			startReplayBuffer.Connect(signal, "start",
J
jp9000 已提交
450
						  OBSStartReplayBuffer, this);
J
jp9000 已提交
451
			stopReplayBuffer.Connect(signal, "stop",
J
jp9000 已提交
452
						 OBSStopReplayBuffer, this);
J
jp9000 已提交
453
			replayBufferStopping.Connect(signal, "stopping",
J
jp9000 已提交
454 455
						     OBSReplayBufferStopping,
						     this);
456 457
			replayBufferSaved.Connect(signal, "saved",
						  OBSReplayBufferSaved, this);
458 459
		}

J
jp9000 已提交
460 461
		fileOutput = obs_output_create(
			"ffmpeg_muxer", "simple_file_output", nullptr, nullptr);
462 463 464 465 466 467
		if (!fileOutput)
			throw "Failed to create recording output "
			      "(simple output)";
		obs_output_release(fileOutput);
	}

468
	startRecording.Connect(obs_output_get_signal_handler(fileOutput),
J
jp9000 已提交
469 470 471
			       "start", OBSStartRecording, this);
	stopRecording.Connect(obs_output_get_signal_handler(fileOutput), "stop",
			      OBSStopRecording, this);
472
	recordStopping.Connect(obs_output_get_signal_handler(fileOutput),
J
jp9000 已提交
473
			       "stopping", OBSRecordStopping, this);
J
jp9000 已提交
474 475
}

476 477
int SimpleOutput::GetAudioBitrate() const
{
478
	int bitrate = (int)config_get_uint(main->Config(), "SimpleOutput",
J
jp9000 已提交
479
					   "ABitrate");
480 481

	return FindClosestAvailableAACBitrate(bitrate);
482 483
}

J
jp9000 已提交
484 485 486
void SimpleOutput::Update()
{
	obs_data_t *h264Settings = obs_data_create();
J
jp9000 已提交
487
	obs_data_t *aacSettings = obs_data_create();
J
jp9000 已提交
488

J
jp9000 已提交
489 490
	int videoBitrate =
		config_get_uint(main->Config(), "SimpleOutput", "VBitrate");
491
	int audioBitrate = GetAudioBitrate();
J
jp9000 已提交
492 493
	bool advanced =
		config_get_bool(main->Config(), "SimpleOutput", "UseAdvanced");
494 495
	bool enforceBitrate = !config_get_bool(main->Config(), "Stream1",
					       "IgnoreRecommended");
J
jp9000 已提交
496 497
	const char *custom = config_get_string(main->Config(), "SimpleOutput",
					       "x264Settings");
498
	const char *encoder = config_get_string(main->Config(), "SimpleOutput",
J
jp9000 已提交
499
						"StreamEncoder");
500 501 502
	const char *presetType;
	const char *preset;

503
	if (strcmp(encoder, SIMPLE_ENCODER_QSV) == 0) {
504
		presetType = "QSVPreset";
505 506 507 508 509 510

	} else if (strcmp(encoder, SIMPLE_ENCODER_AMD) == 0) {
		presetType = "AMDPreset";
		UpdateStreamingSettings_amd(h264Settings, videoBitrate);

	} else if (strcmp(encoder, SIMPLE_ENCODER_NVENC) == 0) {
J
jp9000 已提交
511
		presetType = "NVENCPreset";
512 513

	} else {
514
		presetType = "Preset";
515
	}
516 517

	preset = config_get_string(main->Config(), "SimpleOutput", presetType);
J
jp9000 已提交
518

519
	obs_data_set_string(h264Settings, "rate_control", "CBR");
J
jp9000 已提交
520 521 522 523 524 525 526
	obs_data_set_int(h264Settings, "bitrate", videoBitrate);

	if (advanced) {
		obs_data_set_string(h264Settings, "preset", preset);
		obs_data_set_string(h264Settings, "x264opts", custom);
	}

527
	obs_data_set_string(aacSettings, "rate_control", "CBR");
J
jp9000 已提交
528 529
	obs_data_set_int(aacSettings, "bitrate", audioBitrate);

J
jp9000 已提交
530 531
	obs_service_apply_encoder_settings(main->GetService(), h264Settings,
					   aacSettings);
532

533
	if (!enforceBitrate) {
534
		obs_data_set_int(h264Settings, "bitrate", videoBitrate);
535 536
		obs_data_set_int(aacSettings, "bitrate", audioBitrate);
	}
537

538 539 540 541
	video_t *video = obs_get_video();
	enum video_format format = video_output_get_format(video);

	if (format != VIDEO_FORMAT_NV12 && format != VIDEO_FORMAT_I420)
542
		obs_encoder_set_preferred_video_format(h264Streaming,
J
jp9000 已提交
543
						       VIDEO_FORMAT_NV12);
544

545
	obs_encoder_update(h264Streaming, h264Settings);
J
jp9000 已提交
546
	obs_encoder_update(aacStreaming, aacSettings);
547
	obs_encoder_update(aacArchive, aacSettings);
J
jp9000 已提交
548 549 550 551 552

	obs_data_release(h264Settings);
	obs_data_release(aacSettings);
}

553 554 555 556
void SimpleOutput::UpdateRecordingAudioSettings()
{
	obs_data_t *settings = obs_data_create();
	obs_data_set_int(settings, "bitrate", 192);
557
	obs_data_set_string(settings, "rate_control", "CBR");
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

	obs_encoder_update(aacRecording, settings);

	obs_data_release(settings);
}

#define CROSS_DIST_CUTOFF 2000.0

int SimpleOutput::CalcCRF(int crf)
{
	int cx = config_get_uint(main->Config(), "Video", "OutputCX");
	int cy = config_get_uint(main->Config(), "Video", "OutputCY");
	double fCX = double(cx);
	double fCY = double(cy);

	if (lowCPUx264)
		crf -= 2;

	double crossDist = sqrt(fCX * fCX + fCY * fCY);
	double crfResReduction =
		fmin(CROSS_DIST_CUTOFF, crossDist) / CROSS_DIST_CUTOFF;
	crfResReduction = (1.0 - crfResReduction) * 10.0;

	return crf - int(crfResReduction);
}

void SimpleOutput::UpdateRecordingSettings_x264_crf(int crf)
{
	obs_data_t *settings = obs_data_create();
	obs_data_set_int(settings, "crf", crf);
	obs_data_set_bool(settings, "use_bufsize", true);
589
	obs_data_set_string(settings, "rate_control", "CRF");
590 591
	obs_data_set_string(settings, "profile", "high");
	obs_data_set_string(settings, "preset",
J
jp9000 已提交
592
			    lowCPUx264 ? "ultrafast" : "veryfast");
593 594 595 596 597 598

	obs_encoder_update(h264Recording, settings);

	obs_data_release(settings);
}

599 600 601 602 603 604 605 606 607
static bool icq_available(obs_encoder_t *encoder)
{
	obs_properties_t *props = obs_encoder_properties(encoder);
	obs_property_t *p = obs_properties_get(props, "rate_control");
	bool icq_found = false;

	size_t num = obs_property_list_item_count(p);
	for (size_t i = 0; i < num; i++) {
		const char *val = obs_property_list_item_string(p, i);
608
		if (strcmp(val, "ICQ") == 0) {
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
			icq_found = true;
			break;
		}
	}

	obs_properties_destroy(props);
	return icq_found;
}

void SimpleOutput::UpdateRecordingSettings_qsv11(int crf)
{
	bool icq = icq_available(h264Recording);

	obs_data_t *settings = obs_data_create();
	obs_data_set_string(settings, "profile", "high");

	if (icq) {
626
		obs_data_set_string(settings, "rate_control", "ICQ");
627 628 629 630 631 632 633 634 635 636 637 638 639
		obs_data_set_int(settings, "icq_quality", crf);
	} else {
		obs_data_set_string(settings, "rate_control", "CQP");
		obs_data_set_int(settings, "qpi", crf);
		obs_data_set_int(settings, "qpp", crf);
		obs_data_set_int(settings, "qpb", crf);
	}

	obs_encoder_update(h264Recording, settings);

	obs_data_release(settings);
}

640
void SimpleOutput::UpdateRecordingSettings_nvenc(int cqp)
J
jp9000 已提交
641 642
{
	obs_data_t *settings = obs_data_create();
643
	obs_data_set_string(settings, "rate_control", "CQP");
J
jp9000 已提交
644 645
	obs_data_set_string(settings, "profile", "high");
	obs_data_set_string(settings, "preset", "hq");
646
	obs_data_set_int(settings, "cqp", cqp);
J
jp9000 已提交
647 648 649 650 651 652

	obs_encoder_update(h264Recording, settings);

	obs_data_release(settings);
}

653
void SimpleOutput::UpdateStreamingSettings_amd(obs_data_t *settings,
J
jp9000 已提交
654
					       int bitrate)
655
{
656
	// Static Properties
M
Michael Fabian Dirks 已提交
657 658
	obs_data_set_int(settings, "Usage", 0);
	obs_data_set_int(settings, "Profile", 100); // High
J
jp9000 已提交
659

660
	// Rate Control Properties
661
	obs_data_set_int(settings, "RateControlMethod", 3);
M
Michael Fabian Dirks 已提交
662 663 664 665
	obs_data_set_int(settings, "Bitrate.Target", bitrate);
	obs_data_set_int(settings, "FillerData", 1);
	obs_data_set_int(settings, "VBVBuffer", 1);
	obs_data_set_int(settings, "VBVBuffer.Size", bitrate);
J
jp9000 已提交
666

667
	// Picture Control Properties
M
Michael Fabian Dirks 已提交
668
	obs_data_set_double(settings, "KeyframeInterval", 2.0);
669
	obs_data_set_int(settings, "BFrame.Pattern", 0);
670 671 672 673 674 675
}

void SimpleOutput::UpdateRecordingSettings_amd_cqp(int cqp)
{
	obs_data_t *settings = obs_data_create();

676
	// Static Properties
M
Michael Fabian Dirks 已提交
677 678
	obs_data_set_int(settings, "Usage", 0);
	obs_data_set_int(settings, "Profile", 100); // High
679

680
	// Rate Control Properties
M
Michael Fabian Dirks 已提交
681 682 683 684 685 686
	obs_data_set_int(settings, "RateControlMethod", 0);
	obs_data_set_int(settings, "QP.IFrame", cqp);
	obs_data_set_int(settings, "QP.PFrame", cqp);
	obs_data_set_int(settings, "QP.BFrame", cqp);
	obs_data_set_int(settings, "VBVBuffer", 1);
	obs_data_set_int(settings, "VBVBuffer.Size", 100000);
687

688
	// Picture Control Properties
M
Michael Fabian Dirks 已提交
689
	obs_data_set_double(settings, "KeyframeInterval", 2.0);
690
	obs_data_set_int(settings, "BFrame.Pattern", 0);
691

692 693
	// Update and release
	obs_encoder_update(h264Recording, settings);
694 695 696
	obs_data_release(settings);
}

697 698
void SimpleOutput::UpdateRecordingSettings()
{
J
jp9000 已提交
699 700
	bool ultra_hq = (videoQuality == "HQ");
	int crf = CalcCRF(ultra_hq ? 16 : 23);
701

702
	if (astrcmp_n(videoEncoder.c_str(), "x264", 4) == 0) {
703 704 705 706
		UpdateRecordingSettings_x264_crf(crf);

	} else if (videoEncoder == SIMPLE_ENCODER_QSV) {
		UpdateRecordingSettings_qsv11(crf);
J
jp9000 已提交
707

708 709 710
	} else if (videoEncoder == SIMPLE_ENCODER_AMD) {
		UpdateRecordingSettings_amd_cqp(crf);

J
jp9000 已提交
711
	} else if (videoEncoder == SIMPLE_ENCODER_NVENC) {
712
		UpdateRecordingSettings_nvenc(crf);
713
	}
714
	UpdateRecordingAudioSettings();
715 716
}

J
jp9000 已提交
717 718 719
inline void SimpleOutput::SetupOutputs()
{
	SimpleOutput::Update();
720
	obs_encoder_set_video(h264Streaming, obs_get_video());
J
jp9000 已提交
721
	obs_encoder_set_audio(aacStreaming, obs_get_audio());
722
	obs_encoder_set_audio(aacArchive, obs_get_audio());
723 724 725 726

	if (usingRecordingPreset) {
		if (ffmpegOutput) {
			obs_output_set_media(fileOutput, obs_get_video(),
J
jp9000 已提交
727
					     obs_get_audio());
728 729
		} else {
			obs_encoder_set_video(h264Recording, obs_get_video());
J
jp9000 已提交
730
			obs_encoder_set_audio(aacRecording, obs_get_audio());
731 732
		}
	}
J
jp9000 已提交
733 734
}

735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
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)) {
		const char *codec = obs_get_encoder_codec(alt_enc_id);
		if (strcmp(type, codec) == 0) {
			return alt_enc_id;
		}
	}

	return nullptr;
}

750
bool SimpleOutput::SetupStreaming(obs_service_t *service)
J
jp9000 已提交
751
{
752
	if (!Active())
J
jp9000 已提交
753 754
		SetupOutputs();

J
jp9000 已提交
755 756 757 758
	Auth *auth = main->GetAuth();
	if (auth)
		auth->OnStreamConfig();

759 760 761
	/* --------------------- */

	const char *type = obs_service_get_output_type(service);
762
	if (!type) {
763
		type = "rtmp_output";
764 765 766
		const char *url = obs_service_get_url(service);
		if (url != NULL &&
		    strncmp(url, RTMP_PROTOCOL, strlen(RTMP_PROTOCOL)) != 0) {
P
pkv 已提交
767
			type = "ffmpeg_mpegts_muxer";
768 769
		}
	}
770 771 772

	/* XXX: this is messy and disgusting and should be refactored */
	if (outputType != type) {
773 774 775 776 777
		streamDelayStarting.Disconnect();
		streamStopping.Disconnect();
		startStreaming.Disconnect();
		stopStreaming.Disconnect();

J
jp9000 已提交
778 779
		streamOutput = obs_output_create(type, "simple_stream", nullptr,
						 nullptr);
J
jp9000 已提交
780
		if (!streamOutput) {
J
jp9000 已提交
781 782 783 784
			blog(LOG_WARNING,
			     "Creation of stream output type '%s' "
			     "failed!",
			     type);
785
			return false;
J
jp9000 已提交
786
		}
787 788 789
		obs_output_release(streamOutput);

		streamDelayStarting.Connect(
J
jp9000 已提交
790 791
			obs_output_get_signal_handler(streamOutput), "starting",
			OBSStreamStarting, this);
792
		streamStopping.Connect(
J
jp9000 已提交
793 794
			obs_output_get_signal_handler(streamOutput), "stopping",
			OBSStreamStopping, this);
795 796

		startStreaming.Connect(
J
jp9000 已提交
797 798
			obs_output_get_signal_handler(streamOutput), "start",
			OBSStartStreaming, this);
799
		stopStreaming.Connect(
J
jp9000 已提交
800 801
			obs_output_get_signal_handler(streamOutput), "stop",
			OBSStopStreaming, this);
802

J
jp9000 已提交
803 804
		bool isEncoded = obs_output_get_flags(streamOutput) &
				 OBS_OUTPUT_ENCODED;
805 806 807 808

		if (isEncoded) {
			const char *codec =
				obs_output_get_supported_audio_codecs(
J
jp9000 已提交
809
					streamOutput);
810 811
			if (!codec) {
				blog(LOG_WARNING, "Failed to load audio codec");
812
				return false;
813
			}
814

815
			if (strcmp(codec, "aac") != 0) {
J
jp9000 已提交
816 817
				const char *id =
					FindAudioEncoderFromCodec(codec);
818 819 820
				int audioBitrate = GetAudioBitrate();
				obs_data_t *settings = obs_data_create();
				obs_data_set_int(settings, "bitrate",
J
jp9000 已提交
821
						 audioBitrate);
822

J
jp9000 已提交
823 824 825
				aacStreaming = obs_audio_encoder_create(
					id, "alt_audio_enc", nullptr, 0,
					nullptr);
826 827 828 829 830 831
				obs_encoder_release(aacStreaming);
				if (!aacStreaming)
					return false;

				obs_encoder_update(aacStreaming, settings);
				obs_encoder_set_audio(aacStreaming,
J
jp9000 已提交
832
						      obs_get_audio());
833 834 835

				obs_data_release(settings);
			}
836 837
		}

838 839 840
		outputType = type;
	}

841 842
	obs_output_set_video_encoder(streamOutput, h264Streaming);
	obs_output_set_audio_encoder(streamOutput, aacStreaming, 0);
J
jp9000 已提交
843
	obs_output_set_service(streamOutput, service);
844 845
	return true;
}
J
jp9000 已提交
846

847 848
static inline bool ServiceSupportsVodTrack(const char *service);

849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
static void clear_archive_encoder(obs_output_t *output,
				  const char *expected_name)
{
	obs_encoder_t *last = obs_output_get_audio_encoder(output, 1);
	bool clear = false;

	/* ensures that we don't remove twitch's soundtrack encoder */
	if (last) {
		const char *name = obs_encoder_get_name(last);
		clear = name && strcmp(name, expected_name) == 0;
		obs_encoder_release(last);
	}

	if (clear)
		obs_output_set_audio_encoder(output, nullptr, 1);
}

866 867 868 869 870 871 872 873 874 875
void SimpleOutput::SetupVodTrack(obs_service_t *service)
{
	bool advanced =
		config_get_bool(main->Config(), "SimpleOutput", "UseAdvanced");
	bool enable = config_get_bool(main->Config(), "SimpleOutput",
				      "VodTrackEnabled");

	obs_data_t *settings = obs_service_get_settings(service);
	const char *name = obs_data_get_string(settings, "service");

876 877 878 879 880 881 882
	const char *id = obs_service_get_id(service);
	if (strcmp(id, "rtmp_custom") == 0)
		enable = false;
	else
		enable = advanced && enable && ServiceSupportsVodTrack(name);

	if (enable)
883
		obs_output_set_audio_encoder(streamOutput, aacArchive, 1);
884 885
	else
		clear_archive_encoder(streamOutput, SIMPLE_ARCHIVE_NAME);
886 887 888 889

	obs_data_release(settings);
}

890 891
bool SimpleOutput::StartStreaming(obs_service_t *service)
{
J
jp9000 已提交
892 893 894 895 896 897 898 899 900 901 902 903
	bool reconnect = config_get_bool(main->Config(), "Output", "Reconnect");
	int retryDelay =
		config_get_uint(main->Config(), "Output", "RetryDelay");
	int maxRetries =
		config_get_uint(main->Config(), "Output", "MaxRetries");
	bool useDelay =
		config_get_bool(main->Config(), "Output", "DelayEnable");
	int delaySec = config_get_int(main->Config(), "Output", "DelaySec");
	bool preserveDelay =
		config_get_bool(main->Config(), "Output", "DelayPreserve");
	const char *bindIP =
		config_get_string(main->Config(), "Output", "BindIP");
D
derrod 已提交
904
	bool enableNewSocketLoop = config_get_bool(main->Config(), "Output",
J
jp9000 已提交
905 906 907
						   "NewSocketLoopEnable");
	bool enableLowLatencyMode =
		config_get_bool(main->Config(), "Output", "LowLatencyEnable");
908 909
	bool enableDynBitrate =
		config_get_bool(main->Config(), "Output", "DynamicBitrate");
910 911 912

	obs_data_t *settings = obs_data_create();
	obs_data_set_string(settings, "bind_ip", bindIP);
D
derrod 已提交
913
	obs_data_set_bool(settings, "new_socket_loop_enabled",
J
jp9000 已提交
914
			  enableNewSocketLoop);
D
derrod 已提交
915
	obs_data_set_bool(settings, "low_latency_mode_enabled",
J
jp9000 已提交
916
			  enableLowLatencyMode);
917
	obs_data_set_bool(settings, "dyn_bitrate", enableDynBitrate);
918 919 920
	obs_output_update(streamOutput, settings);
	obs_data_release(settings);

J
jp9000 已提交
921 922 923
	if (!reconnect)
		maxRetries = 0;

J
jp9000 已提交
924
	obs_output_set_delay(streamOutput, useDelay ? delaySec : 0,
J
jp9000 已提交
925
			     preserveDelay ? OBS_OUTPUT_DELAY_PRESERVE : 0);
J
jp9000 已提交
926

J
jp9000 已提交
927
	obs_output_set_reconnect_settings(streamOutput, maxRetries, retryDelay);
J
jp9000 已提交
928

929 930
	SetupVodTrack(service);

J
jp9000 已提交
931 932 933 934
	if (obs_output_start(streamOutput)) {
		return true;
	}

J
jp9000 已提交
935
	const char *error = obs_output_get_last_error(streamOutput);
936 937 938 939 940
	bool hasLastError = error && *error;
	if (hasLastError)
		lastError = error;
	else
		lastError = string();
J
jp9000 已提交
941

942
	const char *type = obs_service_get_output_type(service);
943
	blog(LOG_WARNING, "Stream output type '%s' failed to start!%s%s", type,
J
jp9000 已提交
944
	     hasLastError ? "  Last Error: " : "", hasLastError ? error : "");
J
jp9000 已提交
945 946 947
	return false;
}

J
jp9000 已提交
948
void SimpleOutput::UpdateRecording()
J
jp9000 已提交
949
{
J
jp9000 已提交
950 951 952
	if (replayBufferActive || recordingActive)
		return;

953 954 955 956 957 958 959
	if (usingRecordingPreset) {
		if (!ffmpegOutput)
			UpdateRecordingSettings();
	} else if (!obs_output_active(streamOutput)) {
		Update();
	}

960
	if (!Active())
J
jp9000 已提交
961 962
		SetupOutputs();

J
jp9000 已提交
963 964 965 966 967 968 969 970 971 972 973 974 975 976
	if (!ffmpegOutput) {
		obs_output_set_video_encoder(fileOutput, h264Recording);
		obs_output_set_audio_encoder(fileOutput, aacRecording, 0);
	}
	if (replayBuffer) {
		obs_output_set_video_encoder(replayBuffer, h264Recording);
		obs_output_set_audio_encoder(replayBuffer, aacRecording, 0);
	}

	recordingConfigured = true;
}

bool SimpleOutput::ConfigureRecording(bool updateReplayBuffer)
{
J
jp9000 已提交
977 978 979 980
	const char *path =
		config_get_string(main->Config(), "SimpleOutput", "FilePath");
	const char *format =
		config_get_string(main->Config(), "SimpleOutput", "RecFormat");
981
	const char *mux = config_get_string(main->Config(), "SimpleOutput",
J
jp9000 已提交
982
					    "MuxerCustom");
983
	bool noSpace = config_get_bool(main->Config(), "SimpleOutput",
J
jp9000 已提交
984
				       "FileNameWithoutSpace");
985
	const char *filenameFormat = config_get_string(main->Config(), "Output",
J
jp9000 已提交
986 987 988
						       "FilenameFormatting");
	bool overwriteIfExists =
		config_get_bool(main->Config(), "Output", "OverwriteIfExists");
989
	const char *rbPrefix = config_get_string(main->Config(), "SimpleOutput",
J
jp9000 已提交
990
						 "RecRBPrefix");
991
	const char *rbSuffix = config_get_string(main->Config(), "SimpleOutput",
J
jp9000 已提交
992 993 994 995 996
						 "RecRBSuffix");
	int rbTime =
		config_get_int(main->Config(), "SimpleOutput", "RecRBTime");
	int rbSize =
		config_get_int(main->Config(), "SimpleOutput", "RecRBSize");
J
jp9000 已提交
997

998
	string f;
J
jp9000 已提交
999 1000 1001
	string strPath;

	obs_data_t *settings = obs_data_create();
J
jp9000 已提交
1002
	if (updateReplayBuffer) {
1003 1004 1005 1006
		f = GetFormatString(filenameFormat, rbPrefix, rbSuffix);
		strPath = GetOutputFilename(path, ffmpegOutput ? "avi" : format,
					    noSpace, overwriteIfExists,
					    f.c_str());
1007
		obs_data_set_string(settings, "directory", path);
1008
		obs_data_set_string(settings, "format", f.c_str());
1009
		obs_data_set_string(settings, "extension", format);
1010
		obs_data_set_bool(settings, "allow_spaces", !noSpace);
1011 1012
		obs_data_set_int(settings, "max_time_sec", rbTime);
		obs_data_set_int(settings, "max_size_mb",
J
jp9000 已提交
1013
				 usingRecordingPreset ? rbSize : 0);
1014
	} else {
1015
		f = GetFormatString(filenameFormat, nullptr, nullptr);
1016 1017 1018 1019
		strPath = GetRecordingFilename(path,
					       ffmpegOutput ? "avi" : format,
					       noSpace, overwriteIfExists,
					       f.c_str(), ffmpegOutput);
1020
		obs_data_set_string(settings, ffmpegOutput ? "url" : "path",
J
jp9000 已提交
1021
				    strPath.c_str());
1022
	}
J
jp9000 已提交
1023

1024
	obs_data_set_string(settings, "muxer_settings", mux);
J
jp9000 已提交
1025

J
jp9000 已提交
1026 1027 1028 1029
	if (updateReplayBuffer)
		obs_output_update(replayBuffer, settings);
	else
		obs_output_update(fileOutput, settings);
J
jp9000 已提交
1030 1031

	obs_data_release(settings);
J
jp9000 已提交
1032 1033
	return true;
}
J
jp9000 已提交
1034

J
jp9000 已提交
1035 1036 1037 1038 1039
bool SimpleOutput::StartRecording()
{
	UpdateRecording();
	if (!ConfigureRecording(false))
		return false;
J
jp9000 已提交
1040
	if (!obs_output_start(fileOutput)) {
1041 1042 1043 1044 1045 1046
		QString error_reason;
		const char *error = obs_output_get_last_error(fileOutput);
		if (error)
			error_reason = QT_UTF8(error);
		else
			error_reason = QTStr("Output.StartFailedGeneric");
1047
		QMessageBox::critical(main,
J
jp9000 已提交
1048 1049
				      QTStr("Output.StartRecordingFailed"),
				      error_reason);
J
jp9000 已提交
1050
		return false;
1051 1052
	}

J
jp9000 已提交
1053 1054
	return true;
}
J
jp9000 已提交
1055

J
jp9000 已提交
1056 1057 1058 1059 1060
bool SimpleOutput::StartReplayBuffer()
{
	UpdateRecording();
	if (!ConfigureRecording(true))
		return false;
1061
	if (!obs_output_start(replayBuffer)) {
J
jp9000 已提交
1062 1063
		QMessageBox::critical(main, QTStr("Output.StartReplayFailed"),
				      QTStr("Output.StartFailedGeneric"));
J
jp9000 已提交
1064
		return false;
1065 1066
	}

J
jp9000 已提交
1067
	return true;
J
jp9000 已提交
1068 1069
}

1070
void SimpleOutput::StopStreaming(bool force)
J
jp9000 已提交
1071
{
1072 1073 1074 1075
	if (force)
		obs_output_force_stop(streamOutput);
	else
		obs_output_stop(streamOutput);
J
jp9000 已提交
1076 1077
}

1078
void SimpleOutput::StopRecording(bool force)
J
jp9000 已提交
1079
{
1080 1081 1082 1083
	if (force)
		obs_output_force_stop(fileOutput);
	else
		obs_output_stop(fileOutput);
J
jp9000 已提交
1084 1085
}

J
jp9000 已提交
1086 1087 1088 1089 1090 1091 1092 1093
void SimpleOutput::StopReplayBuffer(bool force)
{
	if (force)
		obs_output_force_stop(replayBuffer);
	else
		obs_output_stop(replayBuffer);
}

J
jp9000 已提交
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
bool SimpleOutput::StreamingActive() const
{
	return obs_output_active(streamOutput);
}

bool SimpleOutput::RecordingActive() const
{
	return obs_output_active(fileOutput);
}

J
jp9000 已提交
1104 1105 1106 1107 1108
bool SimpleOutput::ReplayBufferActive() const
{
	return obs_output_active(replayBuffer);
}

J
jp9000 已提交
1109 1110
/* ------------------------------------------------------------------------ */

J
jp9000 已提交
1111
struct AdvancedOutput : BasicOutputHandler {
1112
	OBSEncoder streamAudioEnc;
1113
	OBSEncoder streamArchiveEnc;
J
jp9000 已提交
1114 1115 1116
	OBSEncoder aacTrack[MAX_AUDIO_MIXES];
	OBSEncoder h264Streaming;
	OBSEncoder h264Recording;
J
jp9000 已提交
1117

J
jp9000 已提交
1118 1119 1120 1121
	bool ffmpegOutput;
	bool ffmpegRecording;
	bool useStreamEncoder;
	bool usesBitrate = false;
J
jp9000 已提交
1122

J
jp9000 已提交
1123
	string aacEncoderID[MAX_AUDIO_MIXES];
1124

J
jp9000 已提交
1125 1126 1127 1128
	AdvancedOutput(OBSBasic *main_);

	inline void UpdateStreamSettings();
	inline void UpdateRecordingSettings();
1129
	inline void UpdateAudioSettings();
J
jp9000 已提交
1130 1131
	virtual void Update() override;

1132 1133
	inline void SetupVodTrack(obs_service_t *service);

J
jp9000 已提交
1134 1135 1136
	inline void SetupStreaming();
	inline void SetupRecording();
	inline void SetupFFmpeg();
1137
	void SetupOutputs() override;
1138
	int GetAudioBitrate(size_t i) const;
J
jp9000 已提交
1139

1140
	virtual bool SetupStreaming(obs_service_t *service) override;
J
jp9000 已提交
1141 1142
	virtual bool StartStreaming(obs_service_t *service) override;
	virtual bool StartRecording() override;
1143
	virtual bool StartReplayBuffer() override;
1144 1145
	virtual void StopStreaming(bool force) override;
	virtual void StopRecording(bool force) override;
1146
	virtual void StopReplayBuffer(bool force) override;
J
jp9000 已提交
1147 1148
	virtual bool StreamingActive() const override;
	virtual bool RecordingActive() const override;
1149
	virtual bool ReplayBufferActive() const override;
J
jp9000 已提交
1150 1151 1152 1153 1154
};

static OBSData GetDataFromJsonFile(const char *jsonFile)
{
	char fullPath[512];
1155
	obs_data_t *data = nullptr;
J
jp9000 已提交
1156

J
jp9000 已提交
1157
	int ret = GetProfilePath(fullPath, sizeof(fullPath), jsonFile);
J
jp9000 已提交
1158 1159 1160
	if (ret > 0) {
		BPtr<char> jsonData = os_quick_read_utf8_file(fullPath);
		if (!!jsonData) {
1161
			data = obs_data_create_from_json(jsonData);
J
jp9000 已提交
1162 1163 1164
		}
	}

1165 1166 1167 1168 1169 1170 1171 1172
	if (!data)
		data = obs_data_create();
	OBSData dataRet(data);
	obs_data_release(data);
	return dataRet;
}

static void ApplyEncoderDefaults(OBSData &settings,
J
jp9000 已提交
1173
				 const obs_encoder_t *encoder)
1174 1175 1176 1177 1178 1179 1180
{
	OBSData dataRet = obs_encoder_get_defaults(encoder);
	obs_data_release(dataRet);

	if (!!settings)
		obs_data_apply(dataRet, settings);
	settings = std::move(dataRet);
J
jp9000 已提交
1181 1182
}

1183 1184
#define ADV_ARCHIVE_NAME "adv_archive_aac"

J
jp9000 已提交
1185 1186
AdvancedOutput::AdvancedOutput(OBSBasic *main_) : BasicOutputHandler(main_)
{
J
jp9000 已提交
1187 1188 1189 1190 1191 1192
	const char *recType =
		config_get_string(main->Config(), "AdvOut", "RecType");
	const char *streamEncoder =
		config_get_string(main->Config(), "AdvOut", "Encoder");
	const char *recordEncoder =
		config_get_string(main->Config(), "AdvOut", "RecEncoder");
J
jp9000 已提交
1193

1194
	ffmpegOutput = astrcmpi(recType, "FFmpeg") == 0;
J
jp9000 已提交
1195 1196
	ffmpegRecording =
		ffmpegOutput &&
1197
		config_get_bool(main->Config(), "AdvOut", "FFOutputToFile");
J
jp9000 已提交
1198 1199
	useStreamEncoder = astrcmpi(recordEncoder, "none") == 0;

J
jp9000 已提交
1200 1201
	OBSData streamEncSettings = GetDataFromJsonFile("streamEncoder.json");
	OBSData recordEncSettings = GetDataFromJsonFile("recordEncoder.json");
J
jp9000 已提交
1202

1203
	const char *rate_control = obs_data_get_string(
J
jp9000 已提交
1204 1205
		useStreamEncoder ? streamEncSettings : recordEncSettings,
		"rate_control");
1206 1207 1208
	if (!rate_control)
		rate_control = "";
	usesBitrate = astrcmpi(rate_control, "CBR") == 0 ||
J
jp9000 已提交
1209 1210
		      astrcmpi(rate_control, "VBR") == 0 ||
		      astrcmpi(rate_control, "ABR") == 0;
1211

1212
	if (ffmpegOutput) {
J
jp9000 已提交
1213 1214
		fileOutput = obs_output_create(
			"ffmpeg_output", "adv_ffmpeg_output", nullptr, nullptr);
J
jp9000 已提交
1215 1216 1217
		if (!fileOutput)
			throw "Failed to create recording FFmpeg output "
			      "(advanced output)";
1218
		obs_output_release(fileOutput);
J
jp9000 已提交
1219
	} else {
J
jp9000 已提交
1220 1221
		bool useReplayBuffer =
			config_get_bool(main->Config(), "AdvOut", "RecRB");
1222
		if (useReplayBuffer) {
J
jp9000 已提交
1223 1224
			const char *str = config_get_string(
				main->Config(), "Hotkeys", "ReplayBuffer");
1225 1226
			obs_data_t *hotkey = obs_data_create_from_json(str);
			replayBuffer = obs_output_create("replay_buffer",
J
jp9000 已提交
1227 1228
							 Str("ReplayBuffer"),
							 nullptr, hotkey);
1229 1230 1231 1232

			obs_data_release(hotkey);
			if (!replayBuffer)
				throw "Failed to create replay buffer output "
J
jp9000 已提交
1233
				      "(simple output)";
1234 1235 1236
			obs_output_release(replayBuffer);

			signal_handler_t *signal =
J
jp9000 已提交
1237
				obs_output_get_signal_handler(replayBuffer);
1238 1239

			startReplayBuffer.Connect(signal, "start",
J
jp9000 已提交
1240
						  OBSStartReplayBuffer, this);
1241
			stopReplayBuffer.Connect(signal, "stop",
J
jp9000 已提交
1242
						 OBSStopReplayBuffer, this);
1243
			replayBufferStopping.Connect(signal, "stopping",
J
jp9000 已提交
1244 1245
						     OBSReplayBufferStopping,
						     this);
1246 1247
			replayBufferSaved.Connect(signal, "saved",
						  OBSReplayBufferSaved, this);
1248 1249
		}

J
jp9000 已提交
1250 1251
		fileOutput = obs_output_create(
			"ffmpeg_muxer", "adv_file_output", nullptr, nullptr);
J
jp9000 已提交
1252 1253 1254
		if (!fileOutput)
			throw "Failed to create recording output "
			      "(advanced output)";
1255
		obs_output_release(fileOutput);
J
jp9000 已提交
1256 1257

		if (!useStreamEncoder) {
J
jp9000 已提交
1258 1259 1260
			h264Recording = obs_video_encoder_create(
				recordEncoder, "recording_h264",
				recordEncSettings, nullptr);
J
jp9000 已提交
1261 1262 1263
			if (!h264Recording)
				throw "Failed to create recording h264 "
				      "encoder (advanced output)";
1264
			obs_encoder_release(h264Recording);
J
jp9000 已提交
1265 1266 1267
		}
	}

J
jp9000 已提交
1268 1269
	h264Streaming = obs_video_encoder_create(
		streamEncoder, "streaming_h264", streamEncSettings, nullptr);
J
jp9000 已提交
1270 1271 1272
	if (!h264Streaming)
		throw "Failed to create streaming h264 encoder "
		      "(advanced output)";
1273
	obs_encoder_release(h264Streaming);
J
jp9000 已提交
1274

J
jp9000 已提交
1275
	for (int i = 0; i < MAX_AUDIO_MIXES; i++) {
J
jp9000 已提交
1276 1277 1278
		char name[9];
		sprintf(name, "adv_aac%d", i);

1279
		if (!CreateAACEncoder(aacTrack[i], aacEncoderID[i],
J
jp9000 已提交
1280
				      GetAudioBitrate(i), name, i))
J
jp9000 已提交
1281 1282 1283 1284
			throw "Failed to create audio encoder "
			      "(advanced output)";
	}

1285 1286 1287
	std::string id;
	int streamTrack =
		config_get_int(main->Config(), "AdvOut", "TrackIndex") - 1;
1288
	if (!CreateAACEncoder(streamAudioEnc, id, GetAudioBitrate(streamTrack),
J
jp9000 已提交
1289
			      "adv_stream_aac", streamTrack))
1290 1291 1292
		throw "Failed to create streaming audio encoder "
		      "(advanced output)";

1293 1294 1295 1296
	id = "";
	int vodTrack =
		config_get_int(main->Config(), "AdvOut", "VodTrackIndex") - 1;
	if (!CreateAACEncoder(streamArchiveEnc, id, GetAudioBitrate(vodTrack),
1297
			      ADV_ARCHIVE_NAME, vodTrack))
1298 1299 1300
		throw "Failed to create archive audio encoder "
		      "(advanced output)";

1301
	startRecording.Connect(obs_output_get_signal_handler(fileOutput),
J
jp9000 已提交
1302 1303 1304
			       "start", OBSStartRecording, this);
	stopRecording.Connect(obs_output_get_signal_handler(fileOutput), "stop",
			      OBSStopRecording, this);
1305
	recordStopping.Connect(obs_output_get_signal_handler(fileOutput),
J
jp9000 已提交
1306
			       "stopping", OBSRecordStopping, this);
J
jp9000 已提交
1307 1308 1309 1310
}

void AdvancedOutput::UpdateStreamSettings()
{
1311
	bool applyServiceSettings = config_get_bool(main->Config(), "AdvOut",
J
jp9000 已提交
1312
						    "ApplyServiceSettings");
1313 1314
	bool enforceBitrate = !config_get_bool(main->Config(), "Stream1",
					       "IgnoreRecommended");
1315 1316 1317 1318
	bool dynBitrate =
		config_get_bool(main->Config(), "Output", "DynamicBitrate");
	const char *streamEncoder =
		config_get_string(main->Config(), "AdvOut", "Encoder");
1319

J
jp9000 已提交
1320
	OBSData settings = GetDataFromJsonFile("streamEncoder.json");
1321
	ApplyEncoderDefaults(settings, h264Streaming);
1322

1323 1324
	if (applyServiceSettings) {
		int bitrate = (int)obs_data_get_int(settings, "bitrate");
J
jp9000 已提交
1325 1326
		obs_service_apply_encoder_settings(main->GetService(), settings,
						   nullptr);
1327 1328 1329
		if (!enforceBitrate)
			obs_data_set_int(settings, "bitrate", bitrate);
	}
1330

1331 1332 1333
	if (dynBitrate && astrcmpi(streamEncoder, "jim_nvenc") == 0)
		obs_data_set_bool(settings, "lookahead", false);

1334 1335 1336 1337 1338
	video_t *video = obs_get_video();
	enum video_format format = video_output_get_format(video);

	if (format != VIDEO_FORMAT_NV12 && format != VIDEO_FORMAT_I420)
		obs_encoder_set_preferred_video_format(h264Streaming,
J
jp9000 已提交
1339
						       VIDEO_FORMAT_NV12);
1340

J
jp9000 已提交
1341 1342 1343 1344 1345
	obs_encoder_update(h264Streaming, settings);
}

inline void AdvancedOutput::UpdateRecordingSettings()
{
J
jp9000 已提交
1346
	OBSData settings = GetDataFromJsonFile("recordEncoder.json");
J
jp9000 已提交
1347 1348 1349 1350 1351 1352
	obs_encoder_update(h264Recording, settings);
}

void AdvancedOutput::Update()
{
	UpdateStreamSettings();
1353
	if (!useStreamEncoder && !ffmpegOutput)
J
jp9000 已提交
1354
		UpdateRecordingSettings();
1355
	UpdateAudioSettings();
J
jp9000 已提交
1356 1357
}

1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369
static inline bool ServiceSupportsVodTrack(const char *service)
{
	static const char *vodTrackServices[] = {"Twitch"};

	for (const char *vodTrackService : vodTrackServices) {
		if (astrcmpi(vodTrackService, service) == 0)
			return true;
	}

	return false;
}

J
jp9000 已提交
1370 1371
inline void AdvancedOutput::SetupStreaming()
{
J
jp9000 已提交
1372 1373 1374
	bool rescale = config_get_bool(main->Config(), "AdvOut", "Rescale");
	const char *rescaleRes =
		config_get_string(main->Config(), "AdvOut", "RescaleRes");
J
jp9000 已提交
1375 1376 1377
	unsigned int cx = 0;
	unsigned int cy = 0;

1378 1379 1380 1381 1382
	if (rescale && rescaleRes && *rescaleRes) {
		if (sscanf(rescaleRes, "%ux%u", &cx, &cy) != 2) {
			cx = 0;
			cy = 0;
		}
J
jp9000 已提交
1383 1384
	}

1385
	obs_output_set_audio_encoder(streamOutput, streamAudioEnc, 0);
J
jp9000 已提交
1386 1387
	obs_encoder_set_scaled_size(h264Streaming, cx, cy);
	obs_encoder_set_video(h264Streaming, obs_get_video());
1388 1389 1390 1391 1392 1393 1394 1395 1396

	const char *id = obs_service_get_id(main->GetService());
	if (strcmp(id, "rtmp_custom") == 0) {
		obs_data_t *settings = obs_data_create();
		obs_service_apply_encoder_settings(main->GetService(), settings,
						   nullptr);
		obs_encoder_update(h264Streaming, settings);
		obs_data_release(settings);
	}
J
jp9000 已提交
1397 1398 1399 1400
}

inline void AdvancedOutput::SetupRecording()
{
J
jp9000 已提交
1401 1402 1403 1404 1405 1406 1407
	const char *path =
		config_get_string(main->Config(), "AdvOut", "RecFilePath");
	const char *mux =
		config_get_string(main->Config(), "AdvOut", "RecMuxerCustom");
	bool rescale = config_get_bool(main->Config(), "AdvOut", "RecRescale");
	const char *rescaleRes =
		config_get_string(main->Config(), "AdvOut", "RecRescaleRes");
1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419
	int tracks;

	const char *recFormat =
		config_get_string(main->Config(), "AdvOut", "RecFormat");

	bool flv = strcmp(recFormat, "flv") == 0;

	if (flv)
		tracks = config_get_int(main->Config(), "AdvOut", "FLVTrack");
	else
		tracks = config_get_int(main->Config(), "AdvOut", "RecTracks");

J
jp9000 已提交
1420 1421 1422
	obs_data_t *settings = obs_data_create();
	unsigned int cx = 0;
	unsigned int cy = 0;
1423
	int idx = 0;
J
jp9000 已提交
1424

1425 1426 1427
	if (tracks == 0)
		tracks = config_get_int(main->Config(), "AdvOut", "TrackIndex");

J
jp9000 已提交
1428 1429
	if (useStreamEncoder) {
		obs_output_set_video_encoder(fileOutput, h264Streaming);
1430 1431
		if (replayBuffer)
			obs_output_set_video_encoder(replayBuffer,
J
jp9000 已提交
1432
						     h264Streaming);
J
jp9000 已提交
1433
	} else {
1434 1435 1436 1437 1438
		if (rescale && rescaleRes && *rescaleRes) {
			if (sscanf(rescaleRes, "%ux%u", &cx, &cy) != 2) {
				cx = 0;
				cy = 0;
			}
J
jp9000 已提交
1439 1440 1441 1442 1443
		}

		obs_encoder_set_scaled_size(h264Recording, cx, cy);
		obs_encoder_set_video(h264Recording, obs_get_video());
		obs_output_set_video_encoder(fileOutput, h264Recording);
1444 1445
		if (replayBuffer)
			obs_output_set_video_encoder(replayBuffer,
J
jp9000 已提交
1446
						     h264Recording);
J
jp9000 已提交
1447 1448
	}

1449 1450 1451 1452
	if (!flv) {
		for (int i = 0; i < MAX_AUDIO_MIXES; i++) {
			if ((tracks & (1 << i)) != 0) {
				obs_output_set_audio_encoder(fileOutput,
J
jp9000 已提交
1453
							     aacTrack[i], idx);
1454 1455 1456 1457 1458
				if (replayBuffer)
					obs_output_set_audio_encoder(
						replayBuffer, aacTrack[i], idx);
				idx++;
			}
1459
		}
1460 1461 1462 1463 1464 1465 1466
	} else if (flv && tracks != 0) {
		obs_output_set_audio_encoder(fileOutput, aacTrack[tracks - 1],
					     idx);

		if (replayBuffer)
			obs_output_set_audio_encoder(replayBuffer,
						     aacTrack[tracks - 1], idx);
J
jp9000 已提交
1467 1468 1469
	}

	obs_data_set_string(settings, "path", path);
1470
	obs_data_set_string(settings, "muxer_settings", mux);
J
jp9000 已提交
1471
	obs_output_update(fileOutput, settings);
1472 1473
	if (replayBuffer)
		obs_output_update(replayBuffer, settings);
J
jp9000 已提交
1474 1475 1476 1477 1478 1479
	obs_data_release(settings);
}

inline void AdvancedOutput::SetupFFmpeg()
{
	const char *url = config_get_string(main->Config(), "AdvOut", "FFURL");
J
jp9000 已提交
1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504
	int vBitrate = config_get_int(main->Config(), "AdvOut", "FFVBitrate");
	int gopSize = config_get_int(main->Config(), "AdvOut", "FFVGOPSize");
	bool rescale = config_get_bool(main->Config(), "AdvOut", "FFRescale");
	const char *rescaleRes =
		config_get_string(main->Config(), "AdvOut", "FFRescaleRes");
	const char *formatName =
		config_get_string(main->Config(), "AdvOut", "FFFormat");
	const char *mimeType =
		config_get_string(main->Config(), "AdvOut", "FFFormatMimeType");
	const char *muxCustom =
		config_get_string(main->Config(), "AdvOut", "FFMCustom");
	const char *vEncoder =
		config_get_string(main->Config(), "AdvOut", "FFVEncoder");
	int vEncoderId =
		config_get_int(main->Config(), "AdvOut", "FFVEncoderId");
	const char *vEncCustom =
		config_get_string(main->Config(), "AdvOut", "FFVCustom");
	int aBitrate = config_get_int(main->Config(), "AdvOut", "FFABitrate");
	int aMixes = config_get_int(main->Config(), "AdvOut", "FFAudioMixes");
	const char *aEncoder =
		config_get_string(main->Config(), "AdvOut", "FFAEncoder");
	int aEncoderId =
		config_get_int(main->Config(), "AdvOut", "FFAEncoderId");
	const char *aEncCustom =
		config_get_string(main->Config(), "AdvOut", "FFACustom");
J
jp9000 已提交
1505 1506 1507
	obs_data_t *settings = obs_data_create();

	obs_data_set_string(settings, "url", url);
1508 1509
	obs_data_set_string(settings, "format_name", formatName);
	obs_data_set_string(settings, "format_mime_type", mimeType);
1510
	obs_data_set_string(settings, "muxer_settings", muxCustom);
1511
	obs_data_set_int(settings, "gop_size", gopSize);
J
jp9000 已提交
1512 1513
	obs_data_set_int(settings, "video_bitrate", vBitrate);
	obs_data_set_string(settings, "video_encoder", vEncoder);
1514
	obs_data_set_int(settings, "video_encoder_id", vEncoderId);
J
jp9000 已提交
1515 1516 1517
	obs_data_set_string(settings, "video_settings", vEncCustom);
	obs_data_set_int(settings, "audio_bitrate", aBitrate);
	obs_data_set_string(settings, "audio_encoder", aEncoder);
1518
	obs_data_set_int(settings, "audio_encoder_id", aEncoderId);
J
jp9000 已提交
1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531
	obs_data_set_string(settings, "audio_settings", aEncCustom);

	if (rescale && rescaleRes && *rescaleRes) {
		int width;
		int height;
		int val = sscanf(rescaleRes, "%dx%d", &width, &height);

		if (val == 2 && width && height) {
			obs_data_set_int(settings, "scale_width", width);
			obs_data_set_int(settings, "scale_height", height);
		}
	}

P
pkviet 已提交
1532
	obs_output_set_mixers(fileOutput, aMixes);
J
jp9000 已提交
1533 1534 1535 1536 1537 1538 1539
	obs_output_set_media(fileOutput, obs_get_video(), obs_get_audio());
	obs_output_update(fileOutput, settings);

	obs_data_release(settings);
}

static inline void SetEncoderName(obs_encoder_t *encoder, const char *name,
J
jp9000 已提交
1540
				  const char *defaultName)
J
jp9000 已提交
1541 1542 1543 1544
{
	obs_encoder_set_name(encoder, (name && *name) ? name : defaultName);
}

1545
inline void AdvancedOutput::UpdateAudioSettings()
J
jp9000 已提交
1546
{
1547
	bool applyServiceSettings = config_get_bool(main->Config(), "AdvOut",
J
jp9000 已提交
1548
						    "ApplyServiceSettings");
1549 1550
	bool enforceBitrate = !config_get_bool(main->Config(), "Stream1",
					       "IgnoreRecommended");
J
jp9000 已提交
1551 1552
	int streamTrackIndex =
		config_get_int(main->Config(), "AdvOut", "TrackIndex");
1553 1554
	int vodTrackIndex =
		config_get_int(main->Config(), "AdvOut", "VodTrackIndex");
J
jp9000 已提交
1555
	obs_data_t *settings[MAX_AUDIO_MIXES];
J
jp9000 已提交
1556

J
jp9000 已提交
1557
	for (size_t i = 0; i < MAX_AUDIO_MIXES; i++) {
J
jp9000 已提交
1558
		settings[i] = obs_data_create();
1559 1560
		obs_data_set_int(settings[i], "bitrate", GetAudioBitrate(i));
	}
J
jp9000 已提交
1561

J
jp9000 已提交
1562 1563 1564 1565 1566
	for (size_t i = 0; i < MAX_AUDIO_MIXES; i++) {
		string cfg_name = "Track";
		cfg_name += to_string((int)i + 1);
		cfg_name += "Name";
		const char *name = config_get_string(main->Config(), "AdvOut",
J
jp9000 已提交
1567
						     cfg_name.c_str());
J
jp9000 已提交
1568 1569 1570 1571 1572

		string def_name = "Track";
		def_name += to_string((int)i + 1);
		SetEncoderName(aacTrack[i], name, def_name.c_str());
	}
J
jp9000 已提交
1573

J
jp9000 已提交
1574
	for (size_t i = 0; i < MAX_AUDIO_MIXES; i++) {
1575 1576
		int track = (int)(i + 1);

J
jp9000 已提交
1577
		obs_encoder_update(aacTrack[i], settings[i]);
1578

1579
		if (track == streamTrackIndex || track == vodTrackIndex) {
1580
			if (applyServiceSettings) {
1581 1582
				int bitrate = (int)obs_data_get_int(settings[i],
								    "bitrate");
1583 1584 1585
				obs_service_apply_encoder_settings(
					main->GetService(), nullptr,
					settings[i]);
1586 1587 1588 1589

				if (!enforceBitrate)
					obs_data_set_int(settings[i], "bitrate",
							 bitrate);
1590
			}
1591
		}
1592

1593
		if (track == streamTrackIndex)
1594
			obs_encoder_update(streamAudioEnc, settings[i]);
1595 1596
		if (track == vodTrackIndex)
			obs_encoder_update(streamArchiveEnc, settings[i]);
1597

J
jp9000 已提交
1598 1599 1600 1601 1602 1603 1604 1605 1606
		obs_data_release(settings[i]);
	}
}

void AdvancedOutput::SetupOutputs()
{
	obs_encoder_set_video(h264Streaming, obs_get_video());
	if (h264Recording)
		obs_encoder_set_video(h264Recording, obs_get_video());
J
jp9000 已提交
1607 1608
	for (size_t i = 0; i < MAX_AUDIO_MIXES; i++)
		obs_encoder_set_audio(aacTrack[i], obs_get_audio());
1609
	obs_encoder_set_audio(streamAudioEnc, obs_get_audio());
1610
	obs_encoder_set_audio(streamArchiveEnc, obs_get_audio());
J
jp9000 已提交
1611 1612 1613

	SetupStreaming();

1614
	if (ffmpegOutput)
J
jp9000 已提交
1615 1616 1617 1618 1619
		SetupFFmpeg();
	else
		SetupRecording();
}

1620 1621
int AdvancedOutput::GetAudioBitrate(size_t i) const
{
J
jp9000 已提交
1622
	static const char *names[] = {
J
jp9000 已提交
1623 1624
		"Track1Bitrate", "Track2Bitrate", "Track3Bitrate",
		"Track4Bitrate", "Track5Bitrate", "Track6Bitrate",
1625
	};
1626 1627
	int bitrate = (int)config_get_uint(main->Config(), "AdvOut", names[i]);
	return FindClosestAvailableAACBitrate(bitrate);
1628 1629
}

1630
inline void AdvancedOutput::SetupVodTrack(obs_service_t *service)
J
jp9000 已提交
1631
{
1632
	int streamTrack =
1633 1634 1635 1636 1637
		config_get_int(main->Config(), "AdvOut", "TrackIndex");
	bool vodTrackEnabled =
		config_get_bool(main->Config(), "AdvOut", "VodTrackEnabled");
	int vodTrackIndex =
		config_get_int(main->Config(), "AdvOut", "VodTrackIndex");
1638

1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660
	const char *id = obs_service_get_id(service);
	if (strcmp(id, "rtmp_custom") == 0) {
		vodTrackEnabled = false;
	} else {
		obs_data_t *settings = obs_service_get_settings(service);
		const char *service = obs_data_get_string(settings, "service");
		if (!ServiceSupportsVodTrack(service))
			vodTrackEnabled = false;
		obs_data_release(settings);
	}

	if (vodTrackEnabled && streamTrack != vodTrackIndex)
		obs_output_set_audio_encoder(streamOutput, streamArchiveEnc, 1);
	else
		clear_archive_encoder(streamOutput, ADV_ARCHIVE_NAME);
}

bool AdvancedOutput::SetupStreaming(obs_service_t *service)
{
	int streamTrack =
		config_get_int(main->Config(), "AdvOut", "TrackIndex");

1661
	if (!useStreamEncoder ||
1662
	    (!ffmpegOutput && !obs_output_active(fileOutput))) {
1663 1664 1665
		UpdateStreamSettings();
	}

1666 1667
	UpdateAudioSettings();

1668
	if (!Active())
J
jp9000 已提交
1669 1670
		SetupOutputs();

J
jp9000 已提交
1671 1672 1673 1674
	Auth *auth = main->GetAuth();
	if (auth)
		auth->OnStreamConfig();

1675 1676 1677
	/* --------------------- */

	const char *type = obs_service_get_output_type(service);
1678
	if (!type) {
1679
		type = "rtmp_output";
1680 1681 1682
		const char *url = obs_service_get_url(service);
		if (url != NULL &&
		    strncmp(url, RTMP_PROTOCOL, strlen(RTMP_PROTOCOL)) != 0) {
P
pkv 已提交
1683
			type = "ffmpeg_mpegts_muxer";
1684 1685
		}
	}
1686 1687 1688

	/* XXX: this is messy and disgusting and should be refactored */
	if (outputType != type) {
1689 1690 1691 1692 1693
		streamDelayStarting.Disconnect();
		streamStopping.Disconnect();
		startStreaming.Disconnect();
		stopStreaming.Disconnect();

J
jp9000 已提交
1694 1695
		streamOutput =
			obs_output_create(type, "adv_stream", nullptr, nullptr);
J
jp9000 已提交
1696
		if (!streamOutput) {
J
jp9000 已提交
1697 1698 1699 1700
			blog(LOG_WARNING,
			     "Creation of stream output type '%s' "
			     "failed!",
			     type);
1701
			return false;
J
jp9000 已提交
1702
		}
1703 1704 1705
		obs_output_release(streamOutput);

		streamDelayStarting.Connect(
J
jp9000 已提交
1706 1707
			obs_output_get_signal_handler(streamOutput), "starting",
			OBSStreamStarting, this);
1708
		streamStopping.Connect(
J
jp9000 已提交
1709 1710
			obs_output_get_signal_handler(streamOutput), "stopping",
			OBSStreamStopping, this);
1711 1712

		startStreaming.Connect(
J
jp9000 已提交
1713 1714
			obs_output_get_signal_handler(streamOutput), "start",
			OBSStartStreaming, this);
1715
		stopStreaming.Connect(
J
jp9000 已提交
1716 1717
			obs_output_get_signal_handler(streamOutput), "stop",
			OBSStopStreaming, this);
1718

J
jp9000 已提交
1719 1720
		bool isEncoded = obs_output_get_flags(streamOutput) &
				 OBS_OUTPUT_ENCODED;
1721

1722 1723 1724
		if (isEncoded) {
			const char *codec =
				obs_output_get_supported_audio_codecs(
J
jp9000 已提交
1725
					streamOutput);
1726 1727
			if (!codec) {
				blog(LOG_WARNING, "Failed to load audio codec");
1728
				return false;
1729
			}
1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740

			if (strcmp(codec, "aac") != 0) {
				OBSData settings = obs_encoder_get_settings(
					streamAudioEnc);
				obs_data_release(settings);

				const char *id =
					FindAudioEncoderFromCodec(codec);

				streamAudioEnc = obs_audio_encoder_create(
					id, "alt_audio_enc", nullptr,
1741
					streamTrack - 1, nullptr);
1742 1743 1744 1745 1746 1747 1748 1749 1750

				if (!streamAudioEnc)
					return false;

				obs_encoder_release(streamAudioEnc);
				obs_encoder_update(streamAudioEnc, settings);
				obs_encoder_set_audio(streamAudioEnc,
						      obs_get_audio());
			}
1751 1752
		}

1753 1754 1755 1756
		outputType = type;
	}

	obs_output_set_video_encoder(streamOutput, h264Streaming);
1757
	obs_output_set_audio_encoder(streamOutput, streamAudioEnc, 0);
1758

1759 1760
	return true;
}
1761

1762 1763
bool AdvancedOutput::StartStreaming(obs_service_t *service)
{
J
jp9000 已提交
1764 1765
	obs_output_set_service(streamOutput, service);

1766 1767 1768
	bool reconnect = config_get_bool(main->Config(), "Output", "Reconnect");
	int retryDelay = config_get_int(main->Config(), "Output", "RetryDelay");
	int maxRetries = config_get_int(main->Config(), "Output", "MaxRetries");
J
jp9000 已提交
1769 1770 1771 1772 1773 1774 1775
	bool useDelay =
		config_get_bool(main->Config(), "Output", "DelayEnable");
	int delaySec = config_get_int(main->Config(), "Output", "DelaySec");
	bool preserveDelay =
		config_get_bool(main->Config(), "Output", "DelayPreserve");
	const char *bindIP =
		config_get_string(main->Config(), "Output", "BindIP");
D
derrod 已提交
1776
	bool enableNewSocketLoop = config_get_bool(main->Config(), "Output",
J
jp9000 已提交
1777 1778 1779
						   "NewSocketLoopEnable");
	bool enableLowLatencyMode =
		config_get_bool(main->Config(), "Output", "LowLatencyEnable");
1780 1781
	bool enableDynBitrate =
		config_get_bool(main->Config(), "Output", "DynamicBitrate");
1782 1783 1784

	obs_data_t *settings = obs_data_create();
	obs_data_set_string(settings, "bind_ip", bindIP);
D
derrod 已提交
1785
	obs_data_set_bool(settings, "new_socket_loop_enabled",
J
jp9000 已提交
1786
			  enableNewSocketLoop);
D
derrod 已提交
1787
	obs_data_set_bool(settings, "low_latency_mode_enabled",
J
jp9000 已提交
1788
			  enableLowLatencyMode);
1789
	obs_data_set_bool(settings, "dyn_bitrate", enableDynBitrate);
1790 1791 1792
	obs_output_update(streamOutput, settings);
	obs_data_release(settings);

J
jp9000 已提交
1793 1794 1795
	if (!reconnect)
		maxRetries = 0;

J
jp9000 已提交
1796
	obs_output_set_delay(streamOutput, useDelay ? delaySec : 0,
J
jp9000 已提交
1797
			     preserveDelay ? OBS_OUTPUT_DELAY_PRESERVE : 0);
J
jp9000 已提交
1798

J
jp9000 已提交
1799
	obs_output_set_reconnect_settings(streamOutput, maxRetries, retryDelay);
J
jp9000 已提交
1800

1801 1802
	SetupVodTrack(service);

J
jp9000 已提交
1803 1804 1805 1806
	if (obs_output_start(streamOutput)) {
		return true;
	}

J
jp9000 已提交
1807
	const char *error = obs_output_get_last_error(streamOutput);
1808 1809 1810 1811 1812
	bool hasLastError = error && *error;
	if (hasLastError)
		lastError = error;
	else
		lastError = string();
J
jp9000 已提交
1813

1814
	const char *type = obs_service_get_output_type(service);
1815
	blog(LOG_WARNING, "Stream output type '%s' failed to start!%s%s", type,
J
jp9000 已提交
1816
	     hasLastError ? "  Last Error: " : "", hasLastError ? error : "");
J
jp9000 已提交
1817 1818 1819 1820 1821
	return false;
}

bool AdvancedOutput::StartRecording()
{
1822
	const char *path;
1823 1824
	const char *recFormat;
	const char *filenameFormat;
1825
	bool noSpace = false;
1826
	bool overwriteIfExists = false;
1827

1828
	if (!useStreamEncoder) {
1829
		if (!ffmpegOutput) {
1830 1831 1832 1833 1834 1835
			UpdateRecordingSettings();
		}
	} else if (!obs_output_active(streamOutput)) {
		UpdateStreamSettings();
	}

1836 1837
	UpdateAudioSettings();

1838
	if (!Active())
J
jp9000 已提交
1839 1840
		SetupOutputs();

1841 1842
	if (!ffmpegOutput || ffmpegRecording) {
		path = config_get_string(main->Config(), "AdvOut",
J
jp9000 已提交
1843 1844
					 ffmpegRecording ? "FFFilePath"
							 : "RecFilePath");
1845
		recFormat = config_get_string(main->Config(), "AdvOut",
J
jp9000 已提交
1846 1847
					      ffmpegRecording ? "FFExtension"
							      : "RecFormat");
1848
		filenameFormat = config_get_string(main->Config(), "Output",
J
jp9000 已提交
1849
						   "FilenameFormatting");
1850
		overwriteIfExists = config_get_bool(main->Config(), "Output",
J
jp9000 已提交
1851
						    "OverwriteIfExists");
1852
		noSpace = config_get_bool(main->Config(), "AdvOut",
J
jp9000 已提交
1853 1854 1855
					  ffmpegRecording
						  ? "FFFileNameWithoutSpace"
						  : "RecFileNameWithoutSpace");
J
jp9000 已提交
1856

1857 1858 1859 1860
		string strPath = GetRecordingFilename(path, recFormat, noSpace,
						      overwriteIfExists,
						      filenameFormat,
						      ffmpegRecording);
J
jp9000 已提交
1861 1862

		obs_data_t *settings = obs_data_create();
J
jp9000 已提交
1863 1864
		obs_data_set_string(settings, ffmpegRecording ? "url" : "path",
				    strPath.c_str());
J
jp9000 已提交
1865 1866 1867 1868 1869 1870

		obs_output_update(fileOutput, settings);

		obs_data_release(settings);
	}

1871
	if (!obs_output_start(fileOutput)) {
1872 1873 1874 1875 1876 1877
		QString error_reason;
		const char *error = obs_output_get_last_error(fileOutput);
		if (error)
			error_reason = QT_UTF8(error);
		else
			error_reason = QTStr("Output.StartFailedGeneric");
1878
		QMessageBox::critical(main,
J
jp9000 已提交
1879 1880
				      QTStr("Output.StartRecordingFailed"),
				      error_reason);
1881
		return false;
J
jp9000 已提交
1882 1883
	}

1884
	return true;
J
jp9000 已提交
1885 1886
}

1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907
bool AdvancedOutput::StartReplayBuffer()
{
	const char *path;
	const char *recFormat;
	const char *filenameFormat;
	bool noSpace = false;
	bool overwriteIfExists = false;
	const char *rbPrefix;
	const char *rbSuffix;
	int rbTime;
	int rbSize;

	if (!useStreamEncoder) {
		if (!ffmpegOutput)
			UpdateRecordingSettings();
	} else if (!obs_output_active(streamOutput)) {
		UpdateStreamSettings();
	}

	UpdateAudioSettings();

1908
	if (!Active())
1909 1910 1911 1912
		SetupOutputs();

	if (!ffmpegOutput || ffmpegRecording) {
		path = config_get_string(main->Config(), "AdvOut",
J
jp9000 已提交
1913 1914
					 ffmpegRecording ? "FFFilePath"
							 : "RecFilePath");
1915
		recFormat = config_get_string(main->Config(), "AdvOut",
J
jp9000 已提交
1916 1917
					      ffmpegRecording ? "FFExtension"
							      : "RecFormat");
1918
		filenameFormat = config_get_string(main->Config(), "Output",
J
jp9000 已提交
1919
						   "FilenameFormatting");
1920
		overwriteIfExists = config_get_bool(main->Config(), "Output",
J
jp9000 已提交
1921
						    "OverwriteIfExists");
1922
		noSpace = config_get_bool(main->Config(), "AdvOut",
J
jp9000 已提交
1923 1924 1925
					  ffmpegRecording
						  ? "FFFileNameWithoutSpace"
						  : "RecFileNameWithoutSpace");
1926
		rbPrefix = config_get_string(main->Config(), "SimpleOutput",
J
jp9000 已提交
1927
					     "RecRBPrefix");
1928
		rbSuffix = config_get_string(main->Config(), "SimpleOutput",
J
jp9000 已提交
1929 1930 1931
					     "RecRBSuffix");
		rbTime = config_get_int(main->Config(), "AdvOut", "RecRBTime");
		rbSize = config_get_int(main->Config(), "AdvOut", "RecRBSize");
1932

1933 1934 1935
		string f = GetFormatString(filenameFormat, rbPrefix, rbSuffix);
		string strPath = GetOutputFilename(
			path, recFormat, noSpace, overwriteIfExists, f.c_str());
1936 1937 1938 1939 1940 1941

		obs_data_t *settings = obs_data_create();

		obs_data_set_string(settings, "directory", path);
		obs_data_set_string(settings, "format", f.c_str());
		obs_data_set_string(settings, "extension", recFormat);
1942
		obs_data_set_bool(settings, "allow_spaces", !noSpace);
1943 1944
		obs_data_set_int(settings, "max_time_sec", rbTime);
		obs_data_set_int(settings, "max_size_mb",
J
jp9000 已提交
1945
				 usesBitrate ? 0 : rbSize);
1946 1947 1948 1949 1950 1951 1952

		obs_output_update(replayBuffer, settings);

		obs_data_release(settings);
	}

	if (!obs_output_start(replayBuffer)) {
1953 1954 1955 1956 1957 1958
		QString error_reason;
		const char *error = obs_output_get_last_error(replayBuffer);
		if (error)
			error_reason = QT_UTF8(error);
		else
			error_reason = QTStr("Output.StartFailedGeneric");
1959
		QMessageBox::critical(main,
J
jp9000 已提交
1960
				      QTStr("Output.StartRecordingFailed"),
1961
				      error_reason);
1962 1963 1964 1965 1966 1967
		return false;
	}

	return true;
}

1968
void AdvancedOutput::StopStreaming(bool force)
J
jp9000 已提交
1969
{
1970 1971 1972 1973
	if (force)
		obs_output_force_stop(streamOutput);
	else
		obs_output_stop(streamOutput);
J
jp9000 已提交
1974 1975
}

1976
void AdvancedOutput::StopRecording(bool force)
J
jp9000 已提交
1977
{
1978 1979 1980 1981
	if (force)
		obs_output_force_stop(fileOutput);
	else
		obs_output_stop(fileOutput);
J
jp9000 已提交
1982 1983
}

1984 1985 1986 1987 1988 1989 1990 1991
void AdvancedOutput::StopReplayBuffer(bool force)
{
	if (force)
		obs_output_force_stop(replayBuffer);
	else
		obs_output_stop(replayBuffer);
}

J
jp9000 已提交
1992 1993 1994 1995 1996 1997 1998 1999 2000 2001
bool AdvancedOutput::StreamingActive() const
{
	return obs_output_active(streamOutput);
}

bool AdvancedOutput::RecordingActive() const
{
	return obs_output_active(fileOutput);
}

2002 2003 2004 2005 2006
bool AdvancedOutput::ReplayBufferActive() const
{
	return obs_output_active(replayBuffer);
}

J
jp9000 已提交
2007 2008
/* ------------------------------------------------------------------------ */

2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027
bool BasicOutputHandler::SetupAutoRemux(const char *&ext)
{
	bool autoRemux = config_get_bool(main->Config(), "Video", "AutoRemux");
	if (autoRemux && strcmp(ext, "mp4") == 0)
		ext = "mkv";
	return autoRemux;
}

std::string
BasicOutputHandler::GetRecordingFilename(const char *path, const char *ext,
					 bool noSpace, bool overwrite,
					 const char *format, bool ffmpeg)
{
	bool remux = !ffmpeg && SetupAutoRemux(ext);
	string dst = GetOutputFilename(path, ext, noSpace, overwrite, format);
	lastRecordingPath = remux ? dst : "";
	return dst;
}

J
jp9000 已提交
2028 2029 2030 2031
BasicOutputHandler *CreateSimpleOutputHandler(OBSBasic *main)
{
	return new SimpleOutput(main);
}
J
jp9000 已提交
2032 2033 2034 2035 2036

BasicOutputHandler *CreateAdvancedOutputHandler(OBSBasic *main)
{
	return new AdvancedOutput(main);
}