decklink-device-instance.cpp 9.7 KB

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