decklink-device-instance.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. #include "decklink-device-instance.hpp"
  2. #include "audio-repack.hpp"
  3. #include "DecklinkInput.hpp"
  4. #include "DecklinkOutput.hpp"
  5. #include <util/platform.h>
  6. #include <util/threading.h>
  7. #include <sstream>
  8. #include <algorithm>
  9. static inline enum video_format ConvertPixelFormat(BMDPixelFormat format)
  10. {
  11. switch (format) {
  12. case bmdFormat8BitBGRA:
  13. return VIDEO_FORMAT_BGRX;
  14. default:
  15. case bmdFormat8BitYUV:;
  16. }
  17. return VIDEO_FORMAT_UYVY;
  18. }
  19. static inline int ConvertChannelFormat(speaker_layout format)
  20. {
  21. switch (format) {
  22. case SPEAKERS_2POINT1:
  23. case SPEAKERS_4POINT0:
  24. case SPEAKERS_4POINT1:
  25. case SPEAKERS_5POINT1:
  26. case SPEAKERS_7POINT1:
  27. return 8;
  28. default:
  29. case SPEAKERS_STEREO:
  30. return 2;
  31. }
  32. }
  33. static inline audio_repack_mode_t ConvertRepackFormat(speaker_layout format,
  34. bool swap)
  35. {
  36. switch (format) {
  37. case SPEAKERS_2POINT1:
  38. return repack_mode_8to3ch;
  39. case SPEAKERS_4POINT0:
  40. return repack_mode_8to4ch;
  41. case SPEAKERS_4POINT1:
  42. return swap ? repack_mode_8to5ch_swap : repack_mode_8to5ch;
  43. case SPEAKERS_5POINT1:
  44. return swap ? repack_mode_8to6ch_swap : repack_mode_8to6ch;
  45. case SPEAKERS_7POINT1:
  46. return swap ? repack_mode_8ch_swap : repack_mode_8ch;
  47. default:
  48. assert(false && "No repack requested");
  49. return (audio_repack_mode_t)-1;
  50. }
  51. }
  52. DeckLinkDeviceInstance::DeckLinkDeviceInstance(DecklinkBase *decklink_,
  53. DeckLinkDevice *device_)
  54. : currentFrame(), currentPacket(), decklink(decklink_), device(device_)
  55. {
  56. currentPacket.samples_per_sec = 48000;
  57. currentPacket.speakers = SPEAKERS_STEREO;
  58. currentPacket.format = AUDIO_FORMAT_16BIT;
  59. }
  60. DeckLinkDeviceInstance::~DeckLinkDeviceInstance() {}
  61. void DeckLinkDeviceInstance::HandleAudioPacket(
  62. IDeckLinkAudioInputPacket *audioPacket, const uint64_t timestamp)
  63. {
  64. if (audioPacket == nullptr)
  65. return;
  66. void *bytes;
  67. if (audioPacket->GetBytes(&bytes) != S_OK) {
  68. LOG(LOG_WARNING, "Failed to get audio packet data");
  69. return;
  70. }
  71. const uint32_t frameCount =
  72. (uint32_t)audioPacket->GetSampleFrameCount();
  73. currentPacket.frames = frameCount;
  74. currentPacket.timestamp = timestamp;
  75. if (decklink && !static_cast<DeckLinkInput *>(decklink)->buffering) {
  76. currentPacket.timestamp = os_gettime_ns();
  77. currentPacket.timestamp -=
  78. (uint64_t)frameCount * 1000000000ULL /
  79. (uint64_t)currentPacket.samples_per_sec;
  80. }
  81. int maxdevicechannel = device->GetMaxChannel();
  82. if (channelFormat != SPEAKERS_UNKNOWN &&
  83. channelFormat != SPEAKERS_MONO &&
  84. channelFormat != SPEAKERS_STEREO &&
  85. (channelFormat != SPEAKERS_7POINT1 ||
  86. static_cast<DeckLinkInput *>(decklink)->swap) &&
  87. maxdevicechannel >= 8) {
  88. if (audioRepacker->repack((uint8_t *)bytes, frameCount) < 0) {
  89. LOG(LOG_ERROR, "Failed to convert audio packet data");
  90. return;
  91. }
  92. currentPacket.data[0] = (*audioRepacker)->packet_buffer;
  93. } else {
  94. currentPacket.data[0] = (uint8_t *)bytes;
  95. }
  96. nextAudioTS = timestamp +
  97. ((uint64_t)frameCount * 1000000000ULL / 48000ULL) + 1;
  98. obs_source_output_audio(
  99. static_cast<DeckLinkInput *>(decklink)->GetSource(),
  100. &currentPacket);
  101. }
  102. void DeckLinkDeviceInstance::HandleVideoFrame(
  103. IDeckLinkVideoInputFrame *videoFrame, const uint64_t timestamp)
  104. {
  105. if (videoFrame == nullptr)
  106. return;
  107. void *bytes;
  108. if (videoFrame->GetBytes(&bytes) != S_OK) {
  109. LOG(LOG_WARNING, "Failed to get video frame data");
  110. return;
  111. }
  112. currentFrame.data[0] = (uint8_t *)bytes;
  113. currentFrame.linesize[0] = (uint32_t)videoFrame->GetRowBytes();
  114. currentFrame.width = (uint32_t)videoFrame->GetWidth();
  115. currentFrame.height = (uint32_t)videoFrame->GetHeight();
  116. currentFrame.timestamp = timestamp;
  117. obs_source_output_video2(
  118. static_cast<DeckLinkInput *>(decklink)->GetSource(),
  119. &currentFrame);
  120. }
  121. void DeckLinkDeviceInstance::FinalizeStream()
  122. {
  123. input->SetCallback(nullptr);
  124. input->DisableVideoInput();
  125. if (channelFormat != SPEAKERS_UNKNOWN)
  126. input->DisableAudioInput();
  127. if (audioRepacker != nullptr) {
  128. delete audioRepacker;
  129. audioRepacker = nullptr;
  130. }
  131. mode = nullptr;
  132. }
  133. //#define LOG_SETUP_VIDEO_FORMAT 1
  134. void DeckLinkDeviceInstance::SetupVideoFormat(DeckLinkDeviceMode *mode_)
  135. {
  136. if (mode_ == nullptr)
  137. return;
  138. currentFrame.format = ConvertPixelFormat(pixelFormat);
  139. colorSpace = static_cast<DeckLinkInput *>(decklink)->GetColorSpace();
  140. if (colorSpace == VIDEO_CS_DEFAULT) {
  141. const BMDDisplayModeFlags flags = mode_->GetDisplayModeFlags();
  142. if (flags & bmdDisplayModeColorspaceRec709)
  143. activeColorSpace = VIDEO_CS_709;
  144. else if (flags & bmdDisplayModeColorspaceRec601)
  145. activeColorSpace = VIDEO_CS_601;
  146. else
  147. activeColorSpace = VIDEO_CS_DEFAULT;
  148. } else {
  149. activeColorSpace = colorSpace;
  150. }
  151. colorRange = static_cast<DeckLinkInput *>(decklink)->GetColorRange();
  152. currentFrame.range = colorRange;
  153. video_format_get_parameters(activeColorSpace, colorRange,
  154. currentFrame.color_matrix,
  155. currentFrame.color_range_min,
  156. currentFrame.color_range_max);
  157. #ifdef LOG_SETUP_VIDEO_FORMAT
  158. LOG(LOG_INFO, "Setup video format: %s, %s, %s",
  159. pixelFormat == bmdFormat8BitYUV ? "YUV" : "RGB",
  160. activeColorSpace == VIDEO_CS_709 ? "BT.709" : "BT.601",
  161. colorRange == VIDEO_RANGE_FULL ? "full" : "limited");
  162. #endif
  163. }
  164. bool DeckLinkDeviceInstance::StartCapture(DeckLinkDeviceMode *mode_,
  165. BMDVideoConnection bmdVideoConnection,
  166. BMDAudioConnection bmdAudioConnection)
  167. {
  168. if (mode != nullptr)
  169. return false;
  170. if (mode_ == nullptr)
  171. return false;
  172. LOG(LOG_INFO, "Starting capture...");
  173. if (!device->GetInput(&input))
  174. return false;
  175. IDeckLinkConfiguration *deckLinkConfiguration = NULL;
  176. HRESULT result = input->QueryInterface(IID_IDeckLinkConfiguration,
  177. (void **)&deckLinkConfiguration);
  178. if (result != S_OK) {
  179. LOG(LOG_ERROR,
  180. "Could not obtain the IDeckLinkConfiguration interface: %08x\n",
  181. result);
  182. } else {
  183. if (bmdVideoConnection > 0) {
  184. result = deckLinkConfiguration->SetInt(
  185. bmdDeckLinkConfigVideoInputConnection,
  186. bmdVideoConnection);
  187. if (result != S_OK) {
  188. LOG(LOG_ERROR,
  189. "Couldn't set input video port to %d\n\n",
  190. bmdVideoConnection);
  191. }
  192. }
  193. if (bmdAudioConnection > 0) {
  194. result = deckLinkConfiguration->SetInt(
  195. bmdDeckLinkConfigAudioInputConnection,
  196. bmdAudioConnection);
  197. if (result != S_OK) {
  198. LOG(LOG_ERROR,
  199. "Couldn't set input audio port to %d\n\n",
  200. bmdVideoConnection);
  201. }
  202. }
  203. }
  204. videoConnection = bmdVideoConnection;
  205. audioConnection = bmdAudioConnection;
  206. BMDVideoInputFlags flags;
  207. bool isauto = mode_->GetName() == "Auto";
  208. if (isauto) {
  209. displayMode = bmdModeNTSC;
  210. pixelFormat = bmdFormat8BitYUV;
  211. flags = bmdVideoInputEnableFormatDetection;
  212. } else {
  213. displayMode = mode_->GetDisplayMode();
  214. pixelFormat =
  215. static_cast<DeckLinkInput *>(decklink)->GetPixelFormat();
  216. flags = bmdVideoInputFlagDefault;
  217. }
  218. const HRESULT videoResult =
  219. input->EnableVideoInput(displayMode, pixelFormat, flags);
  220. if (videoResult != S_OK) {
  221. LOG(LOG_ERROR, "Failed to enable video input");
  222. return false;
  223. }
  224. SetupVideoFormat(mode_);
  225. channelFormat =
  226. static_cast<DeckLinkInput *>(decklink)->GetChannelFormat();
  227. currentPacket.speakers = channelFormat;
  228. swap = static_cast<DeckLinkInput *>(decklink)->swap;
  229. int maxdevicechannel = device->GetMaxChannel();
  230. if (channelFormat != SPEAKERS_UNKNOWN) {
  231. const int channel = ConvertChannelFormat(channelFormat);
  232. const HRESULT audioResult = input->EnableAudioInput(
  233. bmdAudioSampleRate48kHz, bmdAudioSampleType16bitInteger,
  234. channel);
  235. if (audioResult != S_OK)
  236. LOG(LOG_WARNING,
  237. "Failed to enable audio input; continuing...");
  238. if (channelFormat != SPEAKERS_UNKNOWN &&
  239. channelFormat != SPEAKERS_MONO &&
  240. channelFormat != SPEAKERS_STEREO &&
  241. (channelFormat != SPEAKERS_7POINT1 || swap) &&
  242. maxdevicechannel >= 8) {
  243. const audio_repack_mode_t repack_mode =
  244. ConvertRepackFormat(channelFormat, swap);
  245. audioRepacker = new AudioRepacker(repack_mode);
  246. }
  247. }
  248. if (input->SetCallback(this) != S_OK) {
  249. LOG(LOG_ERROR, "Failed to set callback");
  250. FinalizeStream();
  251. return false;
  252. }
  253. if (input->StartStreams() != S_OK) {
  254. LOG(LOG_ERROR, "Failed to start streams");
  255. FinalizeStream();
  256. return false;
  257. }
  258. mode = mode_;
  259. return true;
  260. }
  261. bool DeckLinkDeviceInstance::StopCapture(void)
  262. {
  263. if (mode == nullptr || input == nullptr)
  264. return false;
  265. LOG(LOG_INFO, "Stopping capture of '%s'...",
  266. GetDevice()->GetDisplayName().c_str());
  267. input->StopStreams();
  268. FinalizeStream();
  269. return true;
  270. }
  271. bool DeckLinkDeviceInstance::StartOutput(DeckLinkDeviceMode *mode_)
  272. {
  273. if (mode != nullptr)
  274. return false;
  275. if (mode_ == nullptr)
  276. return false;
  277. LOG(LOG_INFO, "Starting output...");
  278. if (!device->GetOutput(&output))
  279. return false;
  280. const HRESULT videoResult = output->EnableVideoOutput(
  281. mode_->GetDisplayMode(), bmdVideoOutputFlagDefault);
  282. if (videoResult != S_OK) {
  283. LOG(LOG_ERROR, "Failed to enable video output");
  284. return false;
  285. }
  286. const HRESULT audioResult = output->EnableAudioOutput(
  287. bmdAudioSampleRate48kHz, bmdAudioSampleType16bitInteger, 2,
  288. bmdAudioOutputStreamTimestamped);
  289. if (audioResult != S_OK) {
  290. LOG(LOG_ERROR, "Failed to enable audio output");
  291. return false;
  292. }
  293. mode = mode_;
  294. int keyerMode = device->GetKeyerMode();
  295. IDeckLinkKeyer *deckLinkKeyer = nullptr;
  296. if (device->GetKeyer(&deckLinkKeyer)) {
  297. if (keyerMode) {
  298. deckLinkKeyer->Enable(keyerMode == 1);
  299. deckLinkKeyer->SetLevel(255);
  300. } else {
  301. deckLinkKeyer->Disable();
  302. }
  303. }
  304. auto decklinkOutput = dynamic_cast<DeckLinkOutput *>(decklink);
  305. if (decklinkOutput == nullptr)
  306. return false;
  307. int rowBytes = decklinkOutput->GetWidth() * 2;
  308. if (decklinkOutput->keyerMode != 0) {
  309. rowBytes = decklinkOutput->GetWidth() * 4;
  310. }
  311. BMDPixelFormat pixelFormat = bmdFormat8BitYUV;
  312. if (keyerMode != 0) {
  313. pixelFormat = bmdFormat8BitBGRA;
  314. }
  315. HRESULT result;
  316. result = output->CreateVideoFrame(decklinkOutput->GetWidth(),
  317. decklinkOutput->GetHeight(), rowBytes,
  318. pixelFormat, bmdFrameFlagDefault,
  319. &decklinkOutputFrame);
  320. if (result != S_OK) {
  321. blog(LOG_ERROR, "failed to make frame 0x%X", result);
  322. return false;
  323. }
  324. return true;
  325. }
  326. bool DeckLinkDeviceInstance::StopOutput()
  327. {
  328. if (mode == nullptr || output == nullptr)
  329. return false;
  330. LOG(LOG_INFO, "Stopping output of '%s'...",
  331. GetDevice()->GetDisplayName().c_str());
  332. output->DisableVideoOutput();
  333. output->DisableAudioOutput();
  334. if (decklinkOutputFrame != nullptr) {
  335. decklinkOutputFrame->Release();
  336. decklinkOutputFrame = nullptr;
  337. }
  338. return true;
  339. }
  340. void DeckLinkDeviceInstance::DisplayVideoFrame(video_data *frame)
  341. {
  342. auto decklinkOutput = dynamic_cast<DeckLinkOutput *>(decklink);
  343. if (decklinkOutput == nullptr)
  344. return;
  345. uint8_t *destData;
  346. decklinkOutputFrame->GetBytes((void **)&destData);
  347. uint8_t *outData = frame->data[0];
  348. int rowBytes = decklinkOutput->GetWidth() * 2;
  349. if (device->GetKeyerMode()) {
  350. rowBytes = decklinkOutput->GetWidth() * 4;
  351. }
  352. std::copy(outData, outData + (decklinkOutput->GetHeight() * rowBytes),
  353. destData);
  354. output->DisplayVideoFrameSync(decklinkOutputFrame);
  355. }
  356. void DeckLinkDeviceInstance::WriteAudio(audio_data *frames)
  357. {
  358. uint32_t sampleFramesWritten;
  359. output->WriteAudioSamplesSync(frames->data[0], frames->frames,
  360. &sampleFramesWritten);
  361. }
  362. #define TIME_BASE 1000000000
  363. HRESULT STDMETHODCALLTYPE DeckLinkDeviceInstance::VideoInputFrameArrived(
  364. IDeckLinkVideoInputFrame *videoFrame,
  365. IDeckLinkAudioInputPacket *audioPacket)
  366. {
  367. BMDTimeValue videoTS = 0;
  368. BMDTimeValue videoDur = 0;
  369. BMDTimeValue audioTS = 0;
  370. if (videoFrame) {
  371. videoFrame->GetStreamTime(&videoTS, &videoDur, TIME_BASE);
  372. lastVideoTS = (uint64_t)videoTS;
  373. }
  374. if (audioPacket) {
  375. BMDTimeValue newAudioTS = 0;
  376. int64_t diff;
  377. audioPacket->GetPacketTime(&newAudioTS, TIME_BASE);
  378. audioTS = newAudioTS + audioOffset;
  379. diff = (int64_t)audioTS - (int64_t)nextAudioTS;
  380. if (diff > 10000000LL) {
  381. audioOffset -= diff;
  382. audioTS = newAudioTS + audioOffset;
  383. } else if (diff < -1000000) {
  384. audioOffset = 0;
  385. audioTS = newAudioTS;
  386. }
  387. }
  388. if (videoFrame && videoTS >= 0)
  389. HandleVideoFrame(videoFrame, (uint64_t)videoTS);
  390. if (audioPacket && audioTS >= 0)
  391. HandleAudioPacket(audioPacket, (uint64_t)audioTS);
  392. return S_OK;
  393. }
  394. HRESULT STDMETHODCALLTYPE DeckLinkDeviceInstance::VideoInputFormatChanged(
  395. BMDVideoInputFormatChangedEvents events, IDeckLinkDisplayMode *newMode,
  396. BMDDetectedVideoInputFormatFlags detectedSignalFlags)
  397. {
  398. input->PauseStreams();
  399. mode->SetMode(newMode);
  400. if (events & bmdVideoInputDisplayModeChanged) {
  401. displayMode = mode->GetDisplayMode();
  402. }
  403. if (events & bmdVideoInputColorspaceChanged) {
  404. switch (detectedSignalFlags) {
  405. case bmdDetectedVideoInputRGB444:
  406. pixelFormat = bmdFormat8BitBGRA;
  407. break;
  408. default:
  409. case bmdDetectedVideoInputYCbCr422:
  410. pixelFormat = bmdFormat8BitYUV;
  411. break;
  412. }
  413. }
  414. const HRESULT videoResult = input->EnableVideoInput(
  415. displayMode, pixelFormat, bmdVideoInputEnableFormatDetection);
  416. if (videoResult != S_OK) {
  417. LOG(LOG_ERROR, "Failed to enable video input");
  418. input->StopStreams();
  419. FinalizeStream();
  420. return E_FAIL;
  421. }
  422. SetupVideoFormat(mode);
  423. input->FlushStreams();
  424. input->StartStreams();
  425. return S_OK;
  426. }
  427. ULONG STDMETHODCALLTYPE DeckLinkDeviceInstance::AddRef(void)
  428. {
  429. return os_atomic_inc_long(&refCount);
  430. }
  431. HRESULT STDMETHODCALLTYPE DeckLinkDeviceInstance::QueryInterface(REFIID iid,
  432. LPVOID *ppv)
  433. {
  434. HRESULT result = E_NOINTERFACE;
  435. *ppv = nullptr;
  436. CFUUIDBytes unknown = CFUUIDGetUUIDBytes(IUnknownUUID);
  437. if (memcmp(&iid, &unknown, sizeof(REFIID)) == 0) {
  438. *ppv = this;
  439. AddRef();
  440. result = S_OK;
  441. } else if (memcmp(&iid, &IID_IDeckLinkNotificationCallback,
  442. sizeof(REFIID)) == 0) {
  443. *ppv = (IDeckLinkNotificationCallback *)this;
  444. AddRef();
  445. result = S_OK;
  446. }
  447. return result;
  448. }
  449. ULONG STDMETHODCALLTYPE DeckLinkDeviceInstance::Release(void)
  450. {
  451. const long newRefCount = os_atomic_dec_long(&refCount);
  452. if (newRefCount == 0) {
  453. delete this;
  454. return 0;
  455. }
  456. return newRefCount;
  457. }