decklink-device-instance.cpp 14 KB

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