decklink-device-instance.cpp 12 KB

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