decklink-device-instance.cpp 14 KB

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