decklink-device-instance.cpp 21 KB

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