decklink-device-instance.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  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 <iomanip>
  10. #include <algorithm>
  11. #include "OBSVideoFrame.h"
  12. #include <caption/caption.h>
  13. #include <util/bitstream.h>
  14. template<typename T> RenderDelegate<T>::RenderDelegate(T *pOwner)
  15. {
  16. m_pOwner = pOwner;
  17. }
  18. template<typename T> RenderDelegate<T>::~RenderDelegate() {}
  19. template<typename T>
  20. HRESULT RenderDelegate<T>::QueryInterface(REFIID, LPVOID *ppv)
  21. {
  22. *ppv = NULL;
  23. return E_NOINTERFACE;
  24. }
  25. template<typename T> ULONG RenderDelegate<T>::AddRef()
  26. {
  27. return ++m_refCount;
  28. }
  29. template<typename T> ULONG RenderDelegate<T>::Release()
  30. {
  31. const ULONG newRefValue = --m_refCount;
  32. if (newRefValue == 0) {
  33. delete this;
  34. return 0;
  35. }
  36. return newRefValue;
  37. }
  38. template<typename T>
  39. HRESULT
  40. RenderDelegate<T>::ScheduledFrameCompleted(IDeckLinkVideoFrame *completedFrame,
  41. BMDOutputFrameCompletionResult)
  42. {
  43. m_pOwner->ScheduleVideoFrame(completedFrame);
  44. return S_OK;
  45. }
  46. template<typename T> HRESULT RenderDelegate<T>::ScheduledPlaybackHasStopped()
  47. {
  48. return S_OK;
  49. }
  50. static inline enum video_format ConvertPixelFormat(BMDPixelFormat format)
  51. {
  52. switch (format) {
  53. case bmdFormat8BitBGRA:
  54. return VIDEO_FORMAT_BGRX;
  55. case bmdFormat10BitRGBXLE:
  56. return VIDEO_FORMAT_R10L;
  57. case bmdFormat10BitYUV:
  58. return VIDEO_FORMAT_V210;
  59. default:
  60. case bmdFormat8BitYUV:
  61. return VIDEO_FORMAT_UYVY;
  62. }
  63. }
  64. static inline int ConvertChannelFormat(speaker_layout format)
  65. {
  66. switch (format) {
  67. case SPEAKERS_2POINT1:
  68. case SPEAKERS_4POINT0:
  69. case SPEAKERS_4POINT1:
  70. case SPEAKERS_5POINT1:
  71. case SPEAKERS_7POINT1:
  72. return 8;
  73. default:
  74. case SPEAKERS_STEREO:
  75. return 2;
  76. }
  77. }
  78. static inline audio_repack_mode_t ConvertRepackFormat(speaker_layout format,
  79. bool swap)
  80. {
  81. switch (format) {
  82. case SPEAKERS_2POINT1:
  83. return repack_mode_8to3ch;
  84. case SPEAKERS_4POINT0:
  85. return repack_mode_8to4ch;
  86. case SPEAKERS_4POINT1:
  87. return swap ? repack_mode_8to5ch_swap : repack_mode_8to5ch;
  88. case SPEAKERS_5POINT1:
  89. return swap ? repack_mode_8to6ch_swap : repack_mode_8to6ch;
  90. case SPEAKERS_7POINT1:
  91. return swap ? repack_mode_8ch_swap : repack_mode_8ch;
  92. default:
  93. assert(false && "No repack requested");
  94. return (audio_repack_mode_t)-1;
  95. }
  96. }
  97. DeckLinkDeviceInstance::DeckLinkDeviceInstance(DecklinkBase *decklink_,
  98. DeckLinkDevice *device_)
  99. : currentFrame(),
  100. currentPacket(),
  101. currentCaptions(),
  102. decklink(decklink_),
  103. device(device_)
  104. {
  105. currentPacket.samples_per_sec = 48000;
  106. currentPacket.speakers = SPEAKERS_STEREO;
  107. currentPacket.format = AUDIO_FORMAT_16BIT;
  108. }
  109. DeckLinkDeviceInstance::~DeckLinkDeviceInstance()
  110. {
  111. if (convertFrame) {
  112. delete convertFrame;
  113. }
  114. }
  115. void DeckLinkDeviceInstance::HandleAudioPacket(
  116. IDeckLinkAudioInputPacket *audioPacket, const uint64_t timestamp)
  117. {
  118. if (audioPacket == nullptr)
  119. return;
  120. void *bytes;
  121. if (audioPacket->GetBytes(&bytes) != S_OK) {
  122. LOG(LOG_WARNING, "Failed to get audio packet data");
  123. return;
  124. }
  125. const uint32_t frameCount =
  126. (uint32_t)audioPacket->GetSampleFrameCount();
  127. currentPacket.frames = frameCount;
  128. currentPacket.timestamp = timestamp;
  129. if (decklink && !static_cast<DeckLinkInput *>(decklink)->buffering) {
  130. currentPacket.timestamp = os_gettime_ns();
  131. currentPacket.timestamp -=
  132. util_mul_div64(frameCount, 1000000000ULL,
  133. currentPacket.samples_per_sec);
  134. }
  135. int maxdevicechannel = device->GetMaxChannel();
  136. if (channelFormat != SPEAKERS_UNKNOWN &&
  137. channelFormat != SPEAKERS_MONO &&
  138. channelFormat != SPEAKERS_STEREO &&
  139. (channelFormat != SPEAKERS_7POINT1 ||
  140. static_cast<DeckLinkInput *>(decklink)->swap) &&
  141. maxdevicechannel >= 8) {
  142. if (audioRepacker->repack((uint8_t *)bytes, frameCount) < 0) {
  143. LOG(LOG_ERROR, "Failed to convert audio packet data");
  144. return;
  145. }
  146. currentPacket.data[0] = (*audioRepacker)->packet_buffer;
  147. } else {
  148. currentPacket.data[0] = (uint8_t *)bytes;
  149. }
  150. nextAudioTS = timestamp +
  151. util_mul_div64(frameCount, 1000000000ULL, 48000ULL) + 1;
  152. obs_source_output_audio(
  153. static_cast<DeckLinkInput *>(decklink)->GetSource(),
  154. &currentPacket);
  155. }
  156. void DeckLinkDeviceInstance::HandleVideoFrame(
  157. IDeckLinkVideoInputFrame *videoFrame, const uint64_t timestamp)
  158. {
  159. if (videoFrame == nullptr)
  160. return;
  161. ComPtr<IDeckLinkVideoFrameAncillaryPackets> packets;
  162. if (videoFrame->QueryInterface(IID_IDeckLinkVideoFrameAncillaryPackets,
  163. (void **)&packets) == S_OK) {
  164. ComPtr<IDeckLinkAncillaryPacketIterator> iterator;
  165. packets->GetPacketIterator(&iterator);
  166. ComPtr<IDeckLinkAncillaryPacket> packet;
  167. iterator->Next(&packet);
  168. if (packet) {
  169. auto did = packet->GetDID();
  170. auto sdid = packet->GetSDID();
  171. // Caption data
  172. if (did == 0x61 && sdid == 0x01) {
  173. this->HandleCaptionPacket(packet, timestamp);
  174. }
  175. }
  176. }
  177. ComPtr<IDeckLinkVideoFrame> frame;
  178. if (videoFrame->GetPixelFormat() != convertFrame->GetPixelFormat()) {
  179. ComPtr<IDeckLinkVideoConversion> frameConverter;
  180. frameConverter.Set(CreateVideoConversionInstance());
  181. frameConverter->ConvertFrame(videoFrame, convertFrame);
  182. frame = convertFrame;
  183. } else {
  184. frame = videoFrame;
  185. }
  186. void *bytes;
  187. if (frame->GetBytes(&bytes) != S_OK) {
  188. LOG(LOG_WARNING, "Failed to get video frame data");
  189. return;
  190. }
  191. currentFrame.data[0] = (uint8_t *)bytes;
  192. currentFrame.linesize[0] = (uint32_t)frame->GetRowBytes();
  193. currentFrame.width = (uint32_t)frame->GetWidth();
  194. currentFrame.height = (uint32_t)frame->GetHeight();
  195. currentFrame.timestamp = timestamp;
  196. if (currentFrame.width == 0 || currentFrame.height == 0)
  197. return;
  198. enum video_trc trc = VIDEO_TRC_DEFAULT;
  199. if (frame->GetFlags() & bmdFrameContainsHDRMetadata) {
  200. ComPtr<IDeckLinkVideoFrameMetadataExtensions> metadata;
  201. if (SUCCEEDED(videoFrame->QueryInterface(
  202. IID_IDeckLinkVideoFrameMetadataExtensions,
  203. (void **)&metadata))) {
  204. int64_t range;
  205. if (SUCCEEDED(metadata->GetInt(
  206. bmdDeckLinkFrameMetadataHDRElectroOpticalTransferFunc,
  207. &range))) {
  208. switch (range) {
  209. case 2:
  210. trc = VIDEO_TRC_PQ;
  211. break;
  212. case 3:
  213. trc = VIDEO_TRC_HLG;
  214. break;
  215. default:
  216. trc = VIDEO_TRC_DEFAULT;
  217. break;
  218. }
  219. }
  220. }
  221. }
  222. currentFrame.trc = trc;
  223. obs_source_output_video2(
  224. static_cast<DeckLinkInput *>(decklink)->GetSource(),
  225. &currentFrame);
  226. }
  227. void DeckLinkDeviceInstance::HandleCaptionPacket(
  228. IDeckLinkAncillaryPacket *packet, const uint64_t timestamp)
  229. {
  230. const void *data;
  231. uint32_t size;
  232. packet->GetBytes(bmdAncillaryPacketFormatUInt8, &data, &size);
  233. auto anc = (uint8_t *)data;
  234. struct bitstream_reader reader;
  235. bitstream_reader_init(&reader, anc, size);
  236. // header1
  237. bitstream_reader_r8(&reader);
  238. // header2
  239. bitstream_reader_r8(&reader);
  240. // length
  241. bitstream_reader_r8(&reader);
  242. // frameRate
  243. bitstream_reader_read_bits(&reader, 4);
  244. //reserved
  245. bitstream_reader_read_bits(&reader, 4);
  246. auto cdp_timecode_added = bitstream_reader_read_bits(&reader, 1);
  247. // cdp_data_block_added
  248. bitstream_reader_read_bits(&reader, 1);
  249. // cdp_service_info_added
  250. bitstream_reader_read_bits(&reader, 1);
  251. // cdp_service_info_start
  252. bitstream_reader_read_bits(&reader, 1);
  253. // cdp_service_info_changed
  254. bitstream_reader_read_bits(&reader, 1);
  255. // cdp_service_info_end
  256. bitstream_reader_read_bits(&reader, 1);
  257. auto cdp_contains_captions = bitstream_reader_read_bits(&reader, 1);
  258. //reserved
  259. bitstream_reader_read_bits(&reader, 1);
  260. // cdp_counter
  261. bitstream_reader_r8(&reader);
  262. // cdp_counter2
  263. bitstream_reader_r8(&reader);
  264. if (cdp_timecode_added) {
  265. // timecodeSectionID
  266. bitstream_reader_r8(&reader);
  267. //reserved
  268. bitstream_reader_read_bits(&reader, 2);
  269. bitstream_reader_read_bits(&reader, 2);
  270. bitstream_reader_read_bits(&reader, 4);
  271. // reserved
  272. bitstream_reader_read_bits(&reader, 1);
  273. bitstream_reader_read_bits(&reader, 3);
  274. bitstream_reader_read_bits(&reader, 4);
  275. bitstream_reader_read_bits(&reader, 1);
  276. bitstream_reader_read_bits(&reader, 3);
  277. bitstream_reader_read_bits(&reader, 4);
  278. bitstream_reader_read_bits(&reader, 1);
  279. bitstream_reader_read_bits(&reader, 1);
  280. bitstream_reader_read_bits(&reader, 3);
  281. bitstream_reader_read_bits(&reader, 4);
  282. }
  283. if (cdp_contains_captions) {
  284. // cdp_data_section
  285. bitstream_reader_r8(&reader);
  286. //process_em_data_flag
  287. bitstream_reader_read_bits(&reader, 1);
  288. // process_cc_data_flag
  289. bitstream_reader_read_bits(&reader, 1);
  290. //additional_data_flag
  291. bitstream_reader_read_bits(&reader, 1);
  292. auto cc_count = bitstream_reader_read_bits(&reader, 5);
  293. auto *outData =
  294. (uint8_t *)bzalloc(sizeof(uint8_t) * cc_count * 3);
  295. memcpy(outData, anc + reader.pos, cc_count * 3);
  296. currentCaptions.data = outData;
  297. currentCaptions.timestamp = timestamp;
  298. currentCaptions.packets = cc_count;
  299. obs_source_output_cea708(
  300. static_cast<DeckLinkInput *>(decklink)->GetSource(),
  301. &currentCaptions);
  302. bfree(outData);
  303. }
  304. }
  305. void DeckLinkDeviceInstance::FinalizeStream()
  306. {
  307. input->SetCallback(nullptr);
  308. input->DisableVideoInput();
  309. if (channelFormat != SPEAKERS_UNKNOWN)
  310. input->DisableAudioInput();
  311. if (audioRepacker != nullptr) {
  312. delete audioRepacker;
  313. audioRepacker = nullptr;
  314. }
  315. mode = nullptr;
  316. }
  317. //#define LOG_SETUP_VIDEO_FORMAT 1
  318. void DeckLinkDeviceInstance::SetupVideoFormat(DeckLinkDeviceMode *mode_)
  319. {
  320. if (mode_ == nullptr)
  321. return;
  322. const enum video_format format = ConvertPixelFormat(pixelFormat);
  323. currentFrame.format = format;
  324. colorSpace = static_cast<DeckLinkInput *>(decklink)->GetColorSpace();
  325. if (colorSpace == VIDEO_CS_DEFAULT) {
  326. const BMDDisplayModeFlags flags = mode_->GetDisplayModeFlags();
  327. /* 2020 wasn't set when testing but maybe it will be someday */
  328. if (flags & bmdDisplayModeColorspaceRec2020)
  329. activeColorSpace = VIDEO_CS_2100_PQ;
  330. else if (flags & bmdDisplayModeColorspaceRec709)
  331. activeColorSpace = VIDEO_CS_709;
  332. else if (flags & bmdDisplayModeColorspaceRec601)
  333. activeColorSpace = VIDEO_CS_601;
  334. else
  335. activeColorSpace = VIDEO_CS_DEFAULT;
  336. } else {
  337. activeColorSpace = colorSpace;
  338. }
  339. colorRange = static_cast<DeckLinkInput *>(decklink)->GetColorRange();
  340. currentFrame.range = colorRange;
  341. video_format_get_parameters_for_format(
  342. activeColorSpace, colorRange, format, currentFrame.color_matrix,
  343. currentFrame.color_range_min, currentFrame.color_range_max);
  344. delete convertFrame;
  345. BMDPixelFormat convertFormat;
  346. switch (pixelFormat) {
  347. case bmdFormat10BitYUV:
  348. case bmdFormat8BitBGRA:
  349. case bmdFormat10BitRGBXLE:
  350. convertFormat = pixelFormat;
  351. break;
  352. default:
  353. convertFormat = bmdFormat8BitYUV;
  354. break;
  355. }
  356. convertFrame = new OBSVideoFrame(mode_->GetWidth(), mode_->GetHeight(),
  357. convertFormat);
  358. #ifdef LOG_SETUP_VIDEO_FORMAT
  359. LOG(LOG_INFO, "Setup video format: %s, %s, %s",
  360. pixelFormat == bmdFormat8BitYUV ? "YUV" : "RGB",
  361. activeColorSpace == VIDEO_CS_601 ? "BT.601" : "BT.709",
  362. colorRange == VIDEO_RANGE_FULL ? "full" : "limited");
  363. #endif
  364. }
  365. bool DeckLinkDeviceInstance::StartCapture(DeckLinkDeviceMode *mode_,
  366. bool allow10Bit_,
  367. BMDVideoConnection bmdVideoConnection,
  368. BMDAudioConnection bmdAudioConnection)
  369. {
  370. if (mode != nullptr)
  371. return false;
  372. if (mode_ == nullptr)
  373. return false;
  374. LOG(LOG_INFO, "Starting capture...");
  375. if (!device->GetInput(&input))
  376. return false;
  377. HRESULT result = input->QueryInterface(IID_IDeckLinkConfiguration,
  378. (void **)&deckLinkConfiguration);
  379. if (result != S_OK) {
  380. LOG(LOG_ERROR,
  381. "Could not obtain the IDeckLinkConfiguration interface: %08x\n",
  382. result);
  383. } else {
  384. if (bmdVideoConnection > 0) {
  385. result = deckLinkConfiguration->SetInt(
  386. bmdDeckLinkConfigVideoInputConnection,
  387. bmdVideoConnection);
  388. if (result != S_OK) {
  389. LOG(LOG_ERROR,
  390. "Couldn't set input video port to %d\n\n",
  391. bmdVideoConnection);
  392. }
  393. }
  394. if (bmdAudioConnection > 0) {
  395. result = deckLinkConfiguration->SetInt(
  396. bmdDeckLinkConfigAudioInputConnection,
  397. bmdAudioConnection);
  398. if (result != S_OK) {
  399. LOG(LOG_ERROR,
  400. "Couldn't set input audio port to %d\n\n",
  401. bmdVideoConnection);
  402. }
  403. }
  404. }
  405. videoConnection = bmdVideoConnection;
  406. audioConnection = bmdAudioConnection;
  407. BMDVideoInputFlags flags;
  408. bool isauto = mode_->GetName() == "Auto";
  409. if (isauto) {
  410. displayMode = bmdModeNTSC;
  411. if (allow10Bit_) {
  412. pixelFormat = bmdFormat10BitYUV;
  413. } else {
  414. pixelFormat = bmdFormat8BitYUV;
  415. }
  416. flags = bmdVideoInputEnableFormatDetection;
  417. } else {
  418. displayMode = mode_->GetDisplayMode();
  419. pixelFormat =
  420. static_cast<DeckLinkInput *>(decklink)->GetPixelFormat();
  421. flags = bmdVideoInputFlagDefault;
  422. }
  423. allow10Bit = allow10Bit_;
  424. const HRESULT videoResult =
  425. input->EnableVideoInput(displayMode, pixelFormat, flags);
  426. if (videoResult != S_OK) {
  427. LOG(LOG_ERROR, "Failed to enable video input");
  428. return false;
  429. }
  430. SetupVideoFormat(mode_);
  431. channelFormat =
  432. static_cast<DeckLinkInput *>(decklink)->GetChannelFormat();
  433. currentPacket.speakers = channelFormat;
  434. swap = static_cast<DeckLinkInput *>(decklink)->swap;
  435. int maxdevicechannel = device->GetMaxChannel();
  436. if (channelFormat != SPEAKERS_UNKNOWN) {
  437. const int channel = ConvertChannelFormat(channelFormat);
  438. const HRESULT audioResult = input->EnableAudioInput(
  439. bmdAudioSampleRate48kHz, bmdAudioSampleType16bitInteger,
  440. channel);
  441. if (audioResult != S_OK)
  442. LOG(LOG_WARNING,
  443. "Failed to enable audio input; continuing...");
  444. if (channelFormat != SPEAKERS_UNKNOWN &&
  445. channelFormat != SPEAKERS_MONO &&
  446. channelFormat != SPEAKERS_STEREO &&
  447. (channelFormat != SPEAKERS_7POINT1 || swap) &&
  448. maxdevicechannel >= 8) {
  449. const audio_repack_mode_t repack_mode =
  450. ConvertRepackFormat(channelFormat, swap);
  451. audioRepacker = new AudioRepacker(repack_mode);
  452. }
  453. }
  454. if (input->SetCallback(this) != S_OK) {
  455. LOG(LOG_ERROR, "Failed to set callback");
  456. FinalizeStream();
  457. return false;
  458. }
  459. if (input->StartStreams() != S_OK) {
  460. LOG(LOG_ERROR, "Failed to start streams");
  461. FinalizeStream();
  462. return false;
  463. }
  464. mode = mode_;
  465. return true;
  466. }
  467. bool DeckLinkDeviceInstance::StopCapture(void)
  468. {
  469. if (mode == nullptr || input == nullptr)
  470. return false;
  471. LOG(LOG_INFO, "Stopping capture of '%s'...",
  472. GetDevice()->GetDisplayName().c_str());
  473. input->StopStreams();
  474. FinalizeStream();
  475. return true;
  476. }
  477. bool DeckLinkDeviceInstance::StartOutput(DeckLinkDeviceMode *mode_)
  478. {
  479. if (mode != nullptr)
  480. return false;
  481. if (mode_ == nullptr)
  482. return false;
  483. auto decklinkOutput = dynamic_cast<DeckLinkOutput *>(decklink);
  484. if (decklinkOutput == nullptr)
  485. return false;
  486. LOG(LOG_INFO, "Starting output...");
  487. ComPtr<IDeckLinkOutput> output_;
  488. if (!device->GetOutput(&output_))
  489. return false;
  490. const HRESULT videoResult = output_->EnableVideoOutput(
  491. mode_->GetDisplayMode(), bmdVideoOutputFlagDefault);
  492. if (videoResult != S_OK) {
  493. LOG(LOG_ERROR, "Failed to enable video output");
  494. return false;
  495. }
  496. const HRESULT audioResult = output_->EnableAudioOutput(
  497. bmdAudioSampleRate48kHz, bmdAudioSampleType16bitInteger, 2,
  498. bmdAudioOutputStreamTimestamped);
  499. if (audioResult != S_OK) {
  500. LOG(LOG_ERROR, "Failed to enable audio output");
  501. return false;
  502. }
  503. if (!mode_->GetFrameRate(&frameDuration, &frameTimescale)) {
  504. LOG(LOG_ERROR, "Failed to get frame rate");
  505. return false;
  506. }
  507. ComPtr<IDeckLinkKeyer> deckLinkKeyer;
  508. if (device->GetKeyer(&deckLinkKeyer)) {
  509. const int keyerMode = device->GetKeyerMode();
  510. if (keyerMode) {
  511. deckLinkKeyer->Enable(keyerMode == 1);
  512. deckLinkKeyer->SetLevel(255);
  513. } else {
  514. deckLinkKeyer->Disable();
  515. }
  516. }
  517. frameQueueDecklinkToObs.reset();
  518. frameQueueObsToDecklink.reset();
  519. const int rowSize = decklinkOutput->GetWidth() * 4;
  520. const int frameSize = rowSize * decklinkOutput->GetHeight();
  521. for (std::vector<uint8_t> &blob : frameBlobs) {
  522. blob.assign(frameSize, 0);
  523. frameQueueDecklinkToObs.push(blob.data());
  524. }
  525. activeBlob = nullptr;
  526. struct obs_video_info ovi;
  527. const enum video_colorspace colorspace =
  528. obs_get_video_info(&ovi) ? ovi.colorspace : VIDEO_CS_DEFAULT;
  529. const bool source_hdr = (colorspace == VIDEO_CS_2100_PQ) ||
  530. (colorspace == VIDEO_CS_2100_HLG);
  531. const bool enable_hdr =
  532. source_hdr &&
  533. (obs_output_get_video_conversion(decklinkOutput->GetOutput())
  534. ->colorspace == VIDEO_CS_2100_PQ);
  535. BMDPixelFormat pixelFormat = enable_hdr ? bmdFormat10BitRGBXLE
  536. : bmdFormat8BitBGRA;
  537. const int64_t minimumPrerollFrames =
  538. std::max(device->GetMinimumPrerollFrames(), INT64_C(3));
  539. for (int64_t i = 0; i < minimumPrerollFrames; ++i) {
  540. ComPtr<IDeckLinkMutableVideoFrame> decklinkOutputFrame;
  541. HRESULT result = output_->CreateVideoFrame(
  542. decklinkOutput->GetWidth(), decklinkOutput->GetHeight(),
  543. rowSize, pixelFormat, bmdFrameFlagDefault,
  544. &decklinkOutputFrame);
  545. if (result != S_OK) {
  546. blog(LOG_ERROR, "failed to create video frame 0x%X",
  547. result);
  548. return false;
  549. }
  550. IDeckLinkVideoFrame *theFrame = decklinkOutputFrame.Get();
  551. ComPtr<HDRVideoFrame> decklinkOutputHDRFrame;
  552. if (enable_hdr) {
  553. *decklinkOutputHDRFrame.Assign() =
  554. new HDRVideoFrame(decklinkOutputFrame);
  555. theFrame = decklinkOutputHDRFrame.Get();
  556. }
  557. result = output_->ScheduleVideoFrame(theFrame,
  558. i * frameDuration,
  559. frameDuration,
  560. frameTimescale);
  561. if (result != S_OK) {
  562. blog(LOG_ERROR,
  563. "failed to schedule video frame for preroll 0x%X",
  564. result);
  565. return false;
  566. }
  567. }
  568. totalFramesScheduled = minimumPrerollFrames;
  569. *renderDelegate.Assign() =
  570. new RenderDelegate<DeckLinkDeviceInstance>(this);
  571. output_->SetScheduledFrameCompletionCallback(renderDelegate);
  572. output_->StartScheduledPlayback(0, 100, 1.0);
  573. mode = mode_;
  574. output = std::move(output_);
  575. return true;
  576. }
  577. bool DeckLinkDeviceInstance::StopOutput()
  578. {
  579. if (mode == nullptr || output == nullptr)
  580. return false;
  581. LOG(LOG_INFO, "Stopping output of '%s'...",
  582. GetDevice()->GetDisplayName().c_str());
  583. output->SetScheduledFrameCompletionCallback(NULL);
  584. output->DisableVideoOutput();
  585. output->DisableAudioOutput();
  586. output.Clear();
  587. renderDelegate.Clear();
  588. frameQueueDecklinkToObs.reset();
  589. frameQueueObsToDecklink.reset();
  590. return true;
  591. }
  592. void DeckLinkDeviceInstance::UpdateVideoFrame(video_data *frame)
  593. {
  594. auto decklinkOutput = dynamic_cast<DeckLinkOutput *>(decklink);
  595. if (decklinkOutput == nullptr)
  596. return;
  597. uint8_t *const blob = frameQueueDecklinkToObs.pop();
  598. if (blob) {
  599. memcpy(blob, frame->data[0],
  600. frame->linesize[0] * decklinkOutput->GetHeight());
  601. frameQueueObsToDecklink.push(blob);
  602. }
  603. }
  604. void DeckLinkDeviceInstance::ScheduleVideoFrame(IDeckLinkVideoFrame *frame)
  605. {
  606. void *bytes;
  607. if (SUCCEEDED(frame->GetBytes(&bytes))) {
  608. uint8_t *blob = frameQueueObsToDecklink.pop();
  609. if (blob) {
  610. if (activeBlob)
  611. frameQueueDecklinkToObs.push(activeBlob);
  612. activeBlob = blob;
  613. } else {
  614. blob = activeBlob;
  615. }
  616. const int frameSize = frame->GetRowBytes() * frame->GetHeight();
  617. if (blob)
  618. memcpy(bytes, blob, frameSize);
  619. else
  620. memset(bytes, 0, frameSize);
  621. output->ScheduleVideoFrame(frame,
  622. totalFramesScheduled * frameDuration,
  623. frameDuration, frameTimescale);
  624. ++totalFramesScheduled;
  625. }
  626. }
  627. void DeckLinkDeviceInstance::WriteAudio(audio_data *frames)
  628. {
  629. uint32_t sampleFramesWritten;
  630. output->WriteAudioSamplesSync(frames->data[0], frames->frames,
  631. &sampleFramesWritten);
  632. }
  633. #define TIME_BASE 1000000000
  634. HRESULT STDMETHODCALLTYPE DeckLinkDeviceInstance::VideoInputFrameArrived(
  635. IDeckLinkVideoInputFrame *videoFrame,
  636. IDeckLinkAudioInputPacket *audioPacket)
  637. {
  638. BMDTimeValue videoTS = 0;
  639. BMDTimeValue videoDur = 0;
  640. BMDTimeValue audioTS = 0;
  641. if (videoFrame) {
  642. videoFrame->GetStreamTime(&videoTS, &videoDur, TIME_BASE);
  643. lastVideoTS = (uint64_t)videoTS;
  644. }
  645. if (audioPacket) {
  646. BMDTimeValue newAudioTS = 0;
  647. int64_t diff;
  648. audioPacket->GetPacketTime(&newAudioTS, TIME_BASE);
  649. audioTS = newAudioTS + audioOffset;
  650. diff = (int64_t)audioTS - (int64_t)nextAudioTS;
  651. if (diff > 10000000LL) {
  652. audioOffset -= diff;
  653. audioTS = newAudioTS + audioOffset;
  654. } else if (diff < -1000000) {
  655. audioOffset = 0;
  656. audioTS = newAudioTS;
  657. }
  658. }
  659. if (videoFrame && videoTS >= 0)
  660. HandleVideoFrame(videoFrame, (uint64_t)videoTS);
  661. if (audioPacket && audioTS >= 0)
  662. HandleAudioPacket(audioPacket, (uint64_t)audioTS);
  663. return S_OK;
  664. }
  665. HRESULT STDMETHODCALLTYPE DeckLinkDeviceInstance::VideoInputFormatChanged(
  666. BMDVideoInputFormatChangedEvents events, IDeckLinkDisplayMode *newMode,
  667. BMDDetectedVideoInputFormatFlags detectedSignalFlags)
  668. {
  669. bool formatChanged = false;
  670. if (events & bmdVideoInputColorspaceChanged) {
  671. constexpr BMDDetectedVideoInputFormatFlags highBitFlags =
  672. (bmdDetectedVideoInput12BitDepth |
  673. bmdDetectedVideoInput10BitDepth);
  674. if (detectedSignalFlags & bmdDetectedVideoInputRGB444) {
  675. const BMDPixelFormat nextFormat =
  676. ((detectedSignalFlags & highBitFlags) &&
  677. allow10Bit)
  678. ? bmdFormat10BitRGBXLE
  679. : bmdFormat8BitBGRA;
  680. formatChanged = pixelFormat != nextFormat;
  681. pixelFormat = nextFormat;
  682. }
  683. if (detectedSignalFlags & bmdDetectedVideoInputYCbCr422) {
  684. const BMDPixelFormat nextFormat =
  685. ((detectedSignalFlags & highBitFlags) &&
  686. allow10Bit)
  687. ? bmdFormat10BitYUV
  688. : bmdFormat8BitYUV;
  689. formatChanged = pixelFormat != nextFormat;
  690. pixelFormat = nextFormat;
  691. }
  692. }
  693. if (formatChanged || (events & bmdVideoInputDisplayModeChanged)) {
  694. input->PauseStreams();
  695. mode->SetMode(newMode);
  696. displayMode = mode->GetDisplayMode();
  697. const HRESULT videoResult = input->EnableVideoInput(
  698. displayMode, pixelFormat,
  699. bmdVideoInputEnableFormatDetection);
  700. if (videoResult != S_OK) {
  701. LOG(LOG_ERROR, "Failed to enable video input");
  702. input->StopStreams();
  703. FinalizeStream();
  704. return E_FAIL;
  705. }
  706. SetupVideoFormat(mode);
  707. input->FlushStreams();
  708. input->StartStreams();
  709. }
  710. return S_OK;
  711. }
  712. ULONG STDMETHODCALLTYPE DeckLinkDeviceInstance::AddRef(void)
  713. {
  714. return os_atomic_inc_long(&refCount);
  715. }
  716. HRESULT STDMETHODCALLTYPE DeckLinkDeviceInstance::QueryInterface(REFIID iid,
  717. LPVOID *ppv)
  718. {
  719. HRESULT result = E_NOINTERFACE;
  720. *ppv = nullptr;
  721. CFUUIDBytes unknown = CFUUIDGetUUIDBytes(IUnknownUUID);
  722. if (memcmp(&iid, &unknown, sizeof(REFIID)) == 0) {
  723. *ppv = this;
  724. AddRef();
  725. result = S_OK;
  726. } else if (memcmp(&iid, &IID_IDeckLinkNotificationCallback,
  727. sizeof(REFIID)) == 0) {
  728. *ppv = (IDeckLinkNotificationCallback *)this;
  729. AddRef();
  730. result = S_OK;
  731. }
  732. return result;
  733. }
  734. ULONG STDMETHODCALLTYPE DeckLinkDeviceInstance::Release(void)
  735. {
  736. const long newRefCount = os_atomic_dec_long(&refCount);
  737. if (newRefCount == 0) {
  738. delete this;
  739. return 0;
  740. }
  741. return newRefCount;
  742. }