decklink-device-instance.cpp 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. #include "decklink-device-instance.hpp"
  2. #include "audio-repack.hpp"
  3. #include <util/platform.h>
  4. #include <util/threading.h>
  5. #include <sstream>
  6. #define LOG(level, message, ...) blog(level, "%s: " message, \
  7. obs_source_get_name(this->decklink->GetSource()), ##__VA_ARGS__)
  8. #ifdef _WIN32
  9. #define IS_WIN 1
  10. #else
  11. #define IS_WIN 0
  12. #endif
  13. static inline enum video_format ConvertPixelFormat(BMDPixelFormat format)
  14. {
  15. switch (format) {
  16. case bmdFormat8BitBGRA: return VIDEO_FORMAT_BGRX;
  17. default:
  18. case bmdFormat8BitYUV:;
  19. }
  20. return VIDEO_FORMAT_UYVY;
  21. }
  22. static inline int ConvertChannelFormat(speaker_layout format)
  23. {
  24. switch (format) {
  25. case SPEAKERS_2POINT1:
  26. case SPEAKERS_QUAD:
  27. case SPEAKERS_4POINT1:
  28. case SPEAKERS_5POINT1:
  29. case SPEAKERS_5POINT1_SURROUND:
  30. case SPEAKERS_7POINT1:
  31. case SPEAKERS_7POINT1_SURROUND:
  32. return 8;
  33. default:
  34. case SPEAKERS_STEREO:
  35. return 2;
  36. }
  37. }
  38. static inline audio_repack_mode_t ConvertRepackFormat(speaker_layout format)
  39. {
  40. switch (format) {
  41. case SPEAKERS_QUAD:
  42. return repack_mode_8to4ch_swap23;
  43. case SPEAKERS_4POINT1:
  44. return repack_mode_8to5ch_swap23;
  45. case SPEAKERS_5POINT1:
  46. case SPEAKERS_5POINT1_SURROUND:
  47. return repack_mode_8to6ch_swap23;
  48. case SPEAKERS_7POINT1:
  49. case SPEAKERS_7POINT1_SURROUND:
  50. return repack_mode_8ch_swap23_swap46_swap57;
  51. default:
  52. assert(false && "No repack requested");
  53. return (audio_repack_mode_t)-1;
  54. }
  55. }
  56. DeckLinkDeviceInstance::DeckLinkDeviceInstance(DeckLink *decklink_,
  57. DeckLinkDevice *device_) :
  58. currentFrame(), currentPacket(), decklink(decklink_), device(device_)
  59. {
  60. currentPacket.samples_per_sec = 48000;
  61. currentPacket.speakers = SPEAKERS_STEREO;
  62. currentPacket.format = AUDIO_FORMAT_16BIT;
  63. }
  64. DeckLinkDeviceInstance::~DeckLinkDeviceInstance()
  65. {
  66. }
  67. void DeckLinkDeviceInstance::HandleAudioPacket(
  68. IDeckLinkAudioInputPacket *audioPacket,
  69. const uint64_t timestamp)
  70. {
  71. if (audioPacket == nullptr)
  72. return;
  73. void *bytes;
  74. if (audioPacket->GetBytes(&bytes) != S_OK) {
  75. LOG(LOG_WARNING, "Failed to get audio packet data");
  76. return;
  77. }
  78. const uint32_t frameCount = (uint32_t)audioPacket->GetSampleFrameCount();
  79. currentPacket.frames = frameCount;
  80. currentPacket.timestamp = timestamp;
  81. if (decklink && !decklink->buffering) {
  82. currentPacket.timestamp = os_gettime_ns();
  83. currentPacket.timestamp -=
  84. (uint64_t)frameCount * 1000000000ULL /
  85. (uint64_t)currentPacket.samples_per_sec;
  86. }
  87. int maxdevicechannel = device->GetMaxChannel();
  88. bool isWin = IS_WIN;
  89. if (channelFormat != SPEAKERS_UNKNOWN &&
  90. channelFormat != SPEAKERS_MONO &&
  91. channelFormat != SPEAKERS_STEREO &&
  92. channelFormat != SPEAKERS_2POINT1 &&
  93. maxdevicechannel >= 8 &&
  94. isWin) {
  95. if (audioRepacker->repack((uint8_t *)bytes, frameCount) < 0) {
  96. LOG(LOG_ERROR, "Failed to convert audio packet data");
  97. return;
  98. }
  99. currentPacket.data[0] = (*audioRepacker)->packet_buffer;
  100. } else {
  101. currentPacket.data[0] = (uint8_t *)bytes;
  102. }
  103. nextAudioTS = timestamp +
  104. ((uint64_t)frameCount * 1000000000ULL / 48000ULL) + 1;
  105. obs_source_output_audio(decklink->GetSource(), &currentPacket);
  106. }
  107. void DeckLinkDeviceInstance::HandleVideoFrame(
  108. IDeckLinkVideoInputFrame *videoFrame, const uint64_t timestamp)
  109. {
  110. if (videoFrame == nullptr)
  111. return;
  112. void *bytes;
  113. if (videoFrame->GetBytes(&bytes) != S_OK) {
  114. LOG(LOG_WARNING, "Failed to get video frame data");
  115. return;
  116. }
  117. currentFrame.data[0] = (uint8_t *)bytes;
  118. currentFrame.linesize[0] = (uint32_t)videoFrame->GetRowBytes();
  119. currentFrame.width = (uint32_t)videoFrame->GetWidth();
  120. currentFrame.height = (uint32_t)videoFrame->GetHeight();
  121. currentFrame.timestamp = timestamp;
  122. obs_source_output_video(decklink->GetSource(), &currentFrame);
  123. }
  124. void DeckLinkDeviceInstance::FinalizeStream()
  125. {
  126. input->SetCallback(nullptr);
  127. input->DisableVideoInput();
  128. if (channelFormat != SPEAKERS_UNKNOWN)
  129. input->DisableAudioInput();
  130. if (audioRepacker != nullptr)
  131. {
  132. delete audioRepacker;
  133. audioRepacker = nullptr;
  134. }
  135. mode = nullptr;
  136. }
  137. //#define LOG_SETUP_VIDEO_FORMAT 1
  138. void DeckLinkDeviceInstance::SetupVideoFormat(DeckLinkDeviceMode *mode_)
  139. {
  140. if (mode_ == nullptr)
  141. return;
  142. currentFrame.format = ConvertPixelFormat(pixelFormat);
  143. colorSpace = decklink->GetColorSpace();
  144. if (colorSpace == VIDEO_CS_DEFAULT) {
  145. const BMDDisplayModeFlags flags = mode_->GetDisplayModeFlags();
  146. if (flags & bmdDisplayModeColorspaceRec709)
  147. activeColorSpace = VIDEO_CS_709;
  148. else if (flags & bmdDisplayModeColorspaceRec601)
  149. activeColorSpace = VIDEO_CS_601;
  150. else
  151. activeColorSpace = VIDEO_CS_DEFAULT;
  152. } else {
  153. activeColorSpace = colorSpace;
  154. }
  155. colorRange = decklink->GetColorRange();
  156. currentFrame.full_range = colorRange == VIDEO_RANGE_FULL;
  157. video_format_get_parameters(activeColorSpace, colorRange,
  158. currentFrame.color_matrix, currentFrame.color_range_min,
  159. currentFrame.color_range_max);
  160. #ifdef LOG_SETUP_VIDEO_FORMAT
  161. LOG(LOG_INFO, "Setup video format: %s, %s, %s",
  162. pixelFormat == bmdFormat8BitYUV ? "YUV" : "RGB",
  163. activeColorSpace == VIDEO_CS_709 ? "BT.709" : "BT.601",
  164. colorRange == VIDEO_RANGE_FULL ? "full" : "limited");
  165. #endif
  166. }
  167. bool DeckLinkDeviceInstance::StartCapture(DeckLinkDeviceMode *mode_)
  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. BMDVideoInputFlags flags;
  177. bool isauto = mode_->GetName() == "Auto";
  178. if (isauto) {
  179. displayMode = bmdModeNTSC;
  180. pixelFormat = bmdFormat8BitYUV;
  181. flags = bmdVideoInputEnableFormatDetection;
  182. } else {
  183. displayMode = mode_->GetDisplayMode();
  184. pixelFormat = decklink->GetPixelFormat();
  185. flags = bmdVideoInputFlagDefault;
  186. }
  187. const HRESULT videoResult = input->EnableVideoInput(displayMode,
  188. pixelFormat, flags);
  189. if (videoResult != S_OK) {
  190. LOG(LOG_ERROR, "Failed to enable video input");
  191. return false;
  192. }
  193. SetupVideoFormat(mode_);
  194. channelFormat = decklink->GetChannelFormat();
  195. currentPacket.speakers = channelFormat;
  196. int maxdevicechannel = device->GetMaxChannel();
  197. bool isWin = IS_WIN;
  198. if (channelFormat != SPEAKERS_UNKNOWN) {
  199. const int channel = ConvertChannelFormat(channelFormat);
  200. const HRESULT audioResult = input->EnableAudioInput(
  201. bmdAudioSampleRate48kHz, bmdAudioSampleType16bitInteger,
  202. channel);
  203. if (audioResult != S_OK)
  204. LOG(LOG_WARNING, "Failed to enable audio input; continuing...");
  205. if (channelFormat != SPEAKERS_UNKNOWN &&
  206. channelFormat != SPEAKERS_MONO &&
  207. channelFormat != SPEAKERS_STEREO &&
  208. channelFormat != SPEAKERS_2POINT1 &&
  209. maxdevicechannel >= 8 &&
  210. isWin) {
  211. const audio_repack_mode_t repack_mode = ConvertRepackFormat
  212. (channelFormat);
  213. audioRepacker = new AudioRepacker(repack_mode);
  214. }
  215. }
  216. if (input->SetCallback(this) != S_OK) {
  217. LOG(LOG_ERROR, "Failed to set callback");
  218. FinalizeStream();
  219. return false;
  220. }
  221. if (input->StartStreams() != S_OK) {
  222. LOG(LOG_ERROR, "Failed to start streams");
  223. FinalizeStream();
  224. return false;
  225. }
  226. mode = mode_;
  227. return true;
  228. }
  229. bool DeckLinkDeviceInstance::StopCapture(void)
  230. {
  231. if (mode == nullptr || input == nullptr)
  232. return false;
  233. LOG(LOG_INFO, "Stopping capture of '%s'...",
  234. GetDevice()->GetDisplayName().c_str());
  235. input->StopStreams();
  236. FinalizeStream();
  237. return true;
  238. }
  239. #define TIME_BASE 1000000000
  240. HRESULT STDMETHODCALLTYPE DeckLinkDeviceInstance::VideoInputFrameArrived(
  241. IDeckLinkVideoInputFrame *videoFrame,
  242. IDeckLinkAudioInputPacket *audioPacket)
  243. {
  244. BMDTimeValue videoTS = 0;
  245. BMDTimeValue videoDur = 0;
  246. BMDTimeValue audioTS = 0;
  247. if (videoFrame) {
  248. videoFrame->GetStreamTime(&videoTS, &videoDur, TIME_BASE);
  249. lastVideoTS = (uint64_t)videoTS;
  250. }
  251. if (audioPacket) {
  252. BMDTimeValue newAudioTS = 0;
  253. int64_t diff;
  254. audioPacket->GetPacketTime(&newAudioTS, TIME_BASE);
  255. audioTS = newAudioTS + audioOffset;
  256. diff = (int64_t)audioTS - (int64_t)nextAudioTS;
  257. if (diff > 10000000LL) {
  258. audioOffset -= diff;
  259. audioTS = newAudioTS + audioOffset;
  260. } else if (diff < -1000000) {
  261. audioOffset = 0;
  262. audioTS = newAudioTS;
  263. }
  264. }
  265. if (videoFrame && videoTS >= 0)
  266. HandleVideoFrame(videoFrame, (uint64_t)videoTS);
  267. if (audioPacket && audioTS >= 0)
  268. HandleAudioPacket(audioPacket, (uint64_t)audioTS);
  269. return S_OK;
  270. }
  271. HRESULT STDMETHODCALLTYPE DeckLinkDeviceInstance::VideoInputFormatChanged(
  272. BMDVideoInputFormatChangedEvents events,
  273. IDeckLinkDisplayMode *newMode,
  274. BMDDetectedVideoInputFormatFlags detectedSignalFlags)
  275. {
  276. input->PauseStreams();
  277. mode->SetMode(newMode);
  278. if (events & bmdVideoInputDisplayModeChanged) {
  279. displayMode = mode->GetDisplayMode();
  280. }
  281. if (events & bmdVideoInputColorspaceChanged) {
  282. switch (detectedSignalFlags) {
  283. case bmdDetectedVideoInputRGB444:
  284. pixelFormat = bmdFormat8BitBGRA;
  285. break;
  286. default:
  287. case bmdDetectedVideoInputYCbCr422:
  288. pixelFormat = bmdFormat8BitYUV;
  289. break;
  290. }
  291. }
  292. const HRESULT videoResult = input->EnableVideoInput(displayMode,
  293. pixelFormat, bmdVideoInputEnableFormatDetection);
  294. if (videoResult != S_OK) {
  295. LOG(LOG_ERROR, "Failed to enable video input");
  296. input->StopStreams();
  297. FinalizeStream();
  298. return E_FAIL;
  299. }
  300. SetupVideoFormat(mode);
  301. input->FlushStreams();
  302. input->StartStreams();
  303. return S_OK;
  304. }
  305. ULONG STDMETHODCALLTYPE DeckLinkDeviceInstance::AddRef(void)
  306. {
  307. return os_atomic_inc_long(&refCount);
  308. }
  309. HRESULT STDMETHODCALLTYPE DeckLinkDeviceInstance::QueryInterface(REFIID iid,
  310. LPVOID *ppv)
  311. {
  312. HRESULT result = E_NOINTERFACE;
  313. *ppv = nullptr;
  314. CFUUIDBytes unknown = CFUUIDGetUUIDBytes(IUnknownUUID);
  315. if (memcmp(&iid, &unknown, sizeof(REFIID)) == 0) {
  316. *ppv = this;
  317. AddRef();
  318. result = S_OK;
  319. } else if (memcmp(&iid, &IID_IDeckLinkNotificationCallback,
  320. sizeof(REFIID)) == 0) {
  321. *ppv = (IDeckLinkNotificationCallback *)this;
  322. AddRef();
  323. result = S_OK;
  324. }
  325. return result;
  326. }
  327. ULONG STDMETHODCALLTYPE DeckLinkDeviceInstance::Release(void)
  328. {
  329. const long newRefCount = os_atomic_dec_long(&refCount);
  330. if (newRefCount == 0) {
  331. delete this;
  332. return 0;
  333. }
  334. return newRefCount;
  335. }