decklink-device-instance.cpp 12.1 KB
Newer Older
C
Colin Edwards 已提交
1
#include "decklink-device-instance.hpp"
2
#include "audio-repack.hpp"
3

C
Colin Edwards 已提交
4 5 6
#include "DecklinkInput.hpp"
#include "DecklinkOutput.hpp"

7 8 9 10
#include <util/platform.h>
#include <util/threading.h>

#include <sstream>
C
Colin Edwards 已提交
11
#include <algorithm>
12

13 14 15 16 17 18 19 20 21 22 23 24
static inline enum video_format ConvertPixelFormat(BMDPixelFormat format)
{
	switch (format) {
	case bmdFormat8BitBGRA: return VIDEO_FORMAT_BGRX;

	default:
	case bmdFormat8BitYUV:;
	}

	return VIDEO_FORMAT_UYVY;
}

25 26 27
static inline int ConvertChannelFormat(speaker_layout format)
{
	switch (format) {
P
pkviet 已提交
28
	case SPEAKERS_2POINT1:
P
pkviet 已提交
29
	case SPEAKERS_4POINT0:
P
pkviet 已提交
30
	case SPEAKERS_4POINT1:
31 32 33 34 35 36 37 38 39 40 41 42 43
	case SPEAKERS_5POINT1:
	case SPEAKERS_7POINT1:
		return 8;

	default:
	case SPEAKERS_STEREO:
		return 2;
	}
}

static inline audio_repack_mode_t ConvertRepackFormat(speaker_layout format)
{
	switch (format) {
44
	case SPEAKERS_2POINT1:
45
		return repack_mode_8to3ch;
P
pkviet 已提交
46
	case SPEAKERS_4POINT0:
47
		return repack_mode_8to4ch;
P
pkviet 已提交
48
	case SPEAKERS_4POINT1:
49
		return repack_mode_8to5ch;
50
	case SPEAKERS_5POINT1:
51
		return repack_mode_8to6ch;
52 53 54 55 56 57 58
	case SPEAKERS_7POINT1:
	default:
		assert(false && "No repack requested");
		return (audio_repack_mode_t)-1;
	}
}

C
Colin Edwards 已提交
59
DeckLinkDeviceInstance::DeckLinkDeviceInstance(DecklinkBase *decklink_,
60 61 62 63 64 65 66 67
		DeckLinkDevice *device_) :
	currentFrame(), currentPacket(), decklink(decklink_), device(device_)
{
	currentPacket.samples_per_sec = 48000;
	currentPacket.speakers        = SPEAKERS_STEREO;
	currentPacket.format          = AUDIO_FORMAT_16BIT;
}

J
jp9000 已提交
68 69 70 71
DeckLinkDeviceInstance::~DeckLinkDeviceInstance()
{
}

72 73 74 75 76 77 78 79 80 81 82 83 84
void DeckLinkDeviceInstance::HandleAudioPacket(
		IDeckLinkAudioInputPacket *audioPacket,
		const uint64_t timestamp)
{
	if (audioPacket == nullptr)
		return;

	void *bytes;
	if (audioPacket->GetBytes(&bytes) != S_OK) {
		LOG(LOG_WARNING, "Failed to get audio packet data");
		return;
	}

85 86 87 88
	const uint32_t frameCount = (uint32_t)audioPacket->GetSampleFrameCount();
	currentPacket.frames      = frameCount;
	currentPacket.timestamp   = timestamp;

C
Colin Edwards 已提交
89
	if (decklink && !static_cast<DeckLinkInput*>(decklink)->buffering) {
90 91 92 93 94 95
		currentPacket.timestamp = os_gettime_ns();
		currentPacket.timestamp -=
			(uint64_t)frameCount * 1000000000ULL /
			(uint64_t)currentPacket.samples_per_sec;
	}

P
pkviet 已提交
96 97 98 99 100
	int maxdevicechannel = device->GetMaxChannel();

	if (channelFormat != SPEAKERS_UNKNOWN &&
	    channelFormat != SPEAKERS_MONO &&
	    channelFormat != SPEAKERS_STEREO &&
101 102
	    channelFormat != SPEAKERS_7POINT1 &&
	    maxdevicechannel >= 8) {
P
pkviet 已提交
103

104 105 106 107
		if (audioRepacker->repack((uint8_t *)bytes, frameCount) < 0) {
			LOG(LOG_ERROR, "Failed to convert audio packet data");
			return;
		}
P
pkviet 已提交
108
		currentPacket.data[0] = (*audioRepacker)->packet_buffer;
109
	} else {
P
pkviet 已提交
110
		currentPacket.data[0] = (uint8_t *)bytes;
111
	}
112

113 114 115
	nextAudioTS = timestamp +
		((uint64_t)frameCount * 1000000000ULL / 48000ULL) + 1;

C
Colin Edwards 已提交
116
	obs_source_output_audio(static_cast<DeckLinkInput*>(decklink)->GetSource(), &currentPacket);
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
}

void DeckLinkDeviceInstance::HandleVideoFrame(
		IDeckLinkVideoInputFrame *videoFrame, const uint64_t timestamp)
{
	if (videoFrame == nullptr)
		return;

	void *bytes;
	if (videoFrame->GetBytes(&bytes) != S_OK) {
		LOG(LOG_WARNING, "Failed to get video frame data");
		return;
	}

	currentFrame.data[0]     = (uint8_t *)bytes;
	currentFrame.linesize[0] = (uint32_t)videoFrame->GetRowBytes();
	currentFrame.width       = (uint32_t)videoFrame->GetWidth();
	currentFrame.height      = (uint32_t)videoFrame->GetHeight();
	currentFrame.timestamp   = timestamp;

C
Colin Edwards 已提交
137
	obs_source_output_video(static_cast<DeckLinkInput*>(decklink)->GetSource(), &currentFrame);
138 139
}

140 141 142
void DeckLinkDeviceInstance::FinalizeStream()
{
	input->SetCallback(nullptr);
143 144 145
	input->DisableVideoInput();
	if (channelFormat != SPEAKERS_UNKNOWN)
		input->DisableAudioInput();
146 147 148 149 150 151 152 153 154 155

	if (audioRepacker != nullptr)
	{
		delete audioRepacker;
		audioRepacker = nullptr;
	}

	mode = nullptr;
}

156 157 158 159 160 161 162 163 164
//#define LOG_SETUP_VIDEO_FORMAT 1

void DeckLinkDeviceInstance::SetupVideoFormat(DeckLinkDeviceMode *mode_)
{
	if (mode_ == nullptr)
		return;

	currentFrame.format = ConvertPixelFormat(pixelFormat);

C
Colin Edwards 已提交
165
	colorSpace = static_cast<DeckLinkInput*>(decklink)->GetColorSpace();
166 167 168 169 170 171 172 173 174 175 176 177
	if (colorSpace == VIDEO_CS_DEFAULT) {
		const BMDDisplayModeFlags flags = mode_->GetDisplayModeFlags();
		if (flags & bmdDisplayModeColorspaceRec709)
			activeColorSpace = VIDEO_CS_709;
		else if (flags & bmdDisplayModeColorspaceRec601)
			activeColorSpace = VIDEO_CS_601;
		else
			activeColorSpace = VIDEO_CS_DEFAULT;
	} else {
		activeColorSpace = colorSpace;
	}

C
Colin Edwards 已提交
178
	colorRange = static_cast<DeckLinkInput*>(decklink)->GetColorRange();
179 180 181 182 183 184 185 186 187 188 189 190 191 192
	currentFrame.full_range = colorRange == VIDEO_RANGE_FULL;

	video_format_get_parameters(activeColorSpace, colorRange,
			currentFrame.color_matrix, currentFrame.color_range_min,
			currentFrame.color_range_max);

#ifdef LOG_SETUP_VIDEO_FORMAT
	LOG(LOG_INFO, "Setup video format: %s, %s, %s",
			pixelFormat == bmdFormat8BitYUV ? "YUV" : "RGB",
			activeColorSpace == VIDEO_CS_709 ? "BT.709" : "BT.601",
			colorRange == VIDEO_RANGE_FULL ? "full" : "limited");
#endif
}

193 194 195 196 197 198 199 200 201 202 203 204
bool DeckLinkDeviceInstance::StartCapture(DeckLinkDeviceMode *mode_)
{
	if (mode != nullptr)
		return false;
	if (mode_ == nullptr)
		return false;

	LOG(LOG_INFO, "Starting capture...");

	if (!device->GetInput(&input))
		return false;

205
	BMDVideoInputFlags flags;
206

207 208 209 210 211 212 213
	bool isauto = mode_->GetName() == "Auto";
	if (isauto) {
		displayMode = bmdModeNTSC;
		pixelFormat = bmdFormat8BitYUV;
		flags = bmdVideoInputEnableFormatDetection;
	} else {
		displayMode = mode_->GetDisplayMode();
C
Colin Edwards 已提交
214
		pixelFormat = static_cast<DeckLinkInput*>(decklink)->GetPixelFormat();
215 216
		flags = bmdVideoInputFlagDefault;
	}
217

218
	const HRESULT videoResult = input->EnableVideoInput(displayMode,
219
			pixelFormat, flags);
220 221 222 223 224
	if (videoResult != S_OK) {
		LOG(LOG_ERROR, "Failed to enable video input");
		return false;
	}

225 226
	SetupVideoFormat(mode_);

C
Colin Edwards 已提交
227
	channelFormat = static_cast<DeckLinkInput*>(decklink)->GetChannelFormat();
228
	currentPacket.speakers = channelFormat;
229

P
pkviet 已提交
230 231
	int maxdevicechannel = device->GetMaxChannel();

232 233 234 235 236 237 238 239
	if (channelFormat != SPEAKERS_UNKNOWN) {
		const int channel = ConvertChannelFormat(channelFormat);
		const HRESULT audioResult = input->EnableAudioInput(
				bmdAudioSampleRate48kHz, bmdAudioSampleType16bitInteger,
				channel);
		if (audioResult != S_OK)
			LOG(LOG_WARNING, "Failed to enable audio input; continuing...");

P
pkviet 已提交
240 241 242
		if (channelFormat != SPEAKERS_UNKNOWN &&
		    channelFormat != SPEAKERS_MONO &&
		    channelFormat != SPEAKERS_STEREO &&
243 244
		    channelFormat != SPEAKERS_7POINT1 &&
		    maxdevicechannel >= 8) {
P
pkviet 已提交
245 246 247

			const audio_repack_mode_t repack_mode = ConvertRepackFormat
					(channelFormat);
248 249 250 251 252 253 254 255 256
			audioRepacker = new AudioRepacker(repack_mode);
		}
	}

	if (input->SetCallback(this) != S_OK) {
		LOG(LOG_ERROR, "Failed to set callback");
		FinalizeStream();
		return false;
	}
257 258 259

	if (input->StartStreams() != S_OK) {
		LOG(LOG_ERROR, "Failed to start streams");
260
		FinalizeStream();
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
		return false;
	}

	mode = mode_;

	return true;
}

bool DeckLinkDeviceInstance::StopCapture(void)
{
	if (mode == nullptr || input == nullptr)
		return false;

	LOG(LOG_INFO, "Stopping capture of '%s'...",
			GetDevice()->GetDisplayName().c_str());

	input->StopStreams();
278
	FinalizeStream();
279 280 281 282

	return true;
}

C
Colin Edwards 已提交
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
bool DeckLinkDeviceInstance::StartOutput(DeckLinkDeviceMode *mode_)
{
	if (mode != nullptr)
		return false;
	if (mode_ == nullptr)
		return false;

	LOG(LOG_INFO, "Starting output...");

	if (!device->GetOutput(&output))
		return false;

	const HRESULT videoResult = output->EnableVideoOutput(
			mode_->GetDisplayMode(),
			bmdVideoOutputFlagDefault);
	if (videoResult != S_OK) {
		LOG(LOG_ERROR, "Failed to enable video output");
		return false;
	}

	const HRESULT audioResult = output->EnableAudioOutput(
			bmdAudioSampleRate48kHz,
			bmdAudioSampleType16bitInteger,
			2,
			bmdAudioOutputStreamTimestamped);
	if (audioResult != S_OK) {
		LOG(LOG_ERROR, "Failed to enable audio output");
		return false;
	}

	mode = mode_;

C
Colin Edwards 已提交
315 316 317 318 319 320 321 322 323 324 325 326

	IDeckLinkKeyer *deckLinkKeyer = nullptr;
	if (device->GetKeyer(&deckLinkKeyer)) {
		int keyerMode = device->GetKeyerMode();
		if (keyerMode) {
			deckLinkKeyer->Enable(keyerMode == 1);
			deckLinkKeyer->SetLevel(255);
		} else {
			deckLinkKeyer->Disable();
		}
	}

C
Colin Edwards 已提交
327 328 329 330 331 332 333
	auto decklinkOutput = dynamic_cast<DeckLinkOutput*>(decklink);
	if (decklinkOutput == nullptr)
		return false;

	HRESULT result;
	result = output->CreateVideoFrame(decklinkOutput->GetWidth(),
			decklinkOutput->GetHeight(),
C
Colin Edwards 已提交
334 335
			decklinkOutput->GetWidth() * 4,
			bmdFormat8BitBGRA,
C
Colin Edwards 已提交
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
			bmdFrameFlagDefault,
			&decklinkOutputFrame);
	if (result != S_OK) {
		blog(LOG_ERROR ,"failed to make frame 0x%X", result);
		return false;
	}

	return true;
}

bool DeckLinkDeviceInstance::StopOutput()
{
	if (mode == nullptr || output == nullptr)
		return false;

	LOG(LOG_INFO, "Stopping output of '%s'...",
			GetDevice()->GetDisplayName().c_str());

	output->DisableVideoOutput();
	output->DisableAudioOutput();

	if (decklinkOutputFrame != nullptr) {
		decklinkOutputFrame->Release();
		decklinkOutputFrame = nullptr;
	}

	return true;
}

void DeckLinkDeviceInstance::DisplayVideoFrame(video_data *frame)
{
	auto decklinkOutput = dynamic_cast<DeckLinkOutput*>(decklink);
	if (decklinkOutput == nullptr)
		return;

	uint8_t *destData;
	decklinkOutputFrame->GetBytes((void**)&destData);

	uint8_t *outData = frame->data[0];

	std::copy(outData, outData + (decklinkOutput->GetWidth() *
C
Colin Edwards 已提交
377
			decklinkOutput->GetHeight() * 4), destData);
C
Colin Edwards 已提交
378 379 380 381 382 383 384 385 386 387 388 389

	output->DisplayVideoFrameSync(decklinkOutputFrame);
}

void DeckLinkDeviceInstance::WriteAudio(audio_data *frames)
{
	uint32_t sampleFramesWritten;
	output->WriteAudioSamplesSync(frames->data[0],
			frames->frames,
			&sampleFramesWritten);
}

390 391
#define TIME_BASE 1000000000

392 393 394 395
HRESULT STDMETHODCALLTYPE DeckLinkDeviceInstance::VideoInputFrameArrived(
		IDeckLinkVideoInputFrame *videoFrame,
		IDeckLinkAudioInputPacket *audioPacket)
{
396 397 398 399
	BMDTimeValue videoTS = 0;
	BMDTimeValue videoDur = 0;
	BMDTimeValue audioTS = 0;

400
	if (videoFrame) {
401
		videoFrame->GetStreamTime(&videoTS, &videoDur, TIME_BASE);
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
		lastVideoTS = (uint64_t)videoTS;
	}
	if (audioPacket) {
		BMDTimeValue newAudioTS = 0;
		int64_t diff;

		audioPacket->GetPacketTime(&newAudioTS, TIME_BASE);
		audioTS = newAudioTS + audioOffset;

		diff = (int64_t)audioTS - (int64_t)nextAudioTS;
		if (diff > 10000000LL) {
			audioOffset -= diff;
			audioTS = newAudioTS + audioOffset;

		} else if (diff < -1000000) {
			audioOffset = 0;
			audioTS = newAudioTS;
		}
	}
421

422
	if (videoFrame && videoTS >= 0)
423
		HandleVideoFrame(videoFrame, (uint64_t)videoTS);
424
	if (audioPacket && audioTS >= 0)
425
		HandleAudioPacket(audioPacket, (uint64_t)audioTS);
426 427 428 429 430 431 432 433 434

	return S_OK;
}

HRESULT STDMETHODCALLTYPE DeckLinkDeviceInstance::VideoInputFormatChanged(
		BMDVideoInputFormatChangedEvents events,
		IDeckLinkDisplayMode *newMode,
		BMDDetectedVideoInputFormatFlags detectedSignalFlags)
{
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
	input->PauseStreams();

	mode->SetMode(newMode);

	if (events & bmdVideoInputDisplayModeChanged) {
		displayMode = mode->GetDisplayMode();
	}

	if (events & bmdVideoInputColorspaceChanged) {
		switch (detectedSignalFlags) {
		case bmdDetectedVideoInputRGB444:
			pixelFormat = bmdFormat8BitBGRA;
			break;

		default:
		case bmdDetectedVideoInputYCbCr422:
			pixelFormat = bmdFormat8BitYUV;
			break;
		}
	}

	const HRESULT videoResult = input->EnableVideoInput(displayMode,
			pixelFormat, bmdVideoInputEnableFormatDetection);
	if (videoResult != S_OK) {
		LOG(LOG_ERROR, "Failed to enable video input");
		input->StopStreams();
		FinalizeStream();

		return E_FAIL;
	}

	SetupVideoFormat(mode);
467

468 469
	input->FlushStreams();
	input->StartStreams();
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

	return S_OK;
}

ULONG STDMETHODCALLTYPE DeckLinkDeviceInstance::AddRef(void)
{
	return os_atomic_inc_long(&refCount);
}

HRESULT STDMETHODCALLTYPE DeckLinkDeviceInstance::QueryInterface(REFIID iid,
		LPVOID *ppv)
{
	HRESULT result = E_NOINTERFACE;

	*ppv = nullptr;

	CFUUIDBytes unknown = CFUUIDGetUUIDBytes(IUnknownUUID);
	if (memcmp(&iid, &unknown, sizeof(REFIID)) == 0) {
		*ppv = this;
		AddRef();
		result = S_OK;
	} else if (memcmp(&iid, &IID_IDeckLinkNotificationCallback,
				sizeof(REFIID)) == 0) {
		*ppv = (IDeckLinkNotificationCallback *)this;
		AddRef();
		result = S_OK;
	}

	return result;
}

ULONG STDMETHODCALLTYPE DeckLinkDeviceInstance::Release(void)
{
	const long newRefCount = os_atomic_dec_long(&refCount);
	if (newRefCount == 0) {
		delete this;
		return 0;
	}

	return newRefCount;
}