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_2POINT1:
  40. return repack_mode_8to3ch_swap23;
  41. case SPEAKERS_4POINT0:
  42. return repack_mode_8to4ch_swap23;
  43. case SPEAKERS_4POINT1:
  44. return repack_mode_8to5ch_swap23;
  45. case SPEAKERS_5POINT1:
  46. return repack_mode_8to6ch_swap23;
  47. case SPEAKERS_7POINT1:
  48. return repack_mode_8ch_swap23_swap46_swap57;
  49. default:
  50. assert(false && "No repack requested");
  51. return (audio_repack_mode_t)-1;
  52. }
  53. }
  54. DeckLinkDeviceInstance::DeckLinkDeviceInstance(DeckLink *decklink_,
  55. DeckLinkDevice *device_) :
  56. currentFrame(), currentPacket(), decklink(decklink_), device(device_)
  57. {
  58. currentPacket.samples_per_sec = 48000;
  59. currentPacket.speakers = SPEAKERS_STEREO;
  60. currentPacket.format = AUDIO_FORMAT_16BIT;
  61. }
  62. DeckLinkDeviceInstance::~DeckLinkDeviceInstance()
  63. {
  64. }
  65. void DeckLinkDeviceInstance::HandleAudioPacket(
  66. IDeckLinkAudioInputPacket *audioPacket,
  67. const uint64_t timestamp)
  68. {
  69. if (audioPacket == nullptr)
  70. return;
  71. void *bytes;
  72. if (audioPacket->GetBytes(&bytes) != S_OK) {
  73. LOG(LOG_WARNING, "Failed to get audio packet data");
  74. return;
  75. }
  76. const uint32_t frameCount = (uint32_t)audioPacket->GetSampleFrameCount();
  77. currentPacket.frames = frameCount;
  78. currentPacket.timestamp = timestamp;
  79. if (decklink && !decklink->buffering) {
  80. currentPacket.timestamp = os_gettime_ns();
  81. currentPacket.timestamp -=
  82. (uint64_t)frameCount * 1000000000ULL /
  83. (uint64_t)currentPacket.samples_per_sec;
  84. }
  85. int maxdevicechannel = device->GetMaxChannel();
  86. bool isWin = IS_WIN;
  87. if (channelFormat != SPEAKERS_UNKNOWN &&
  88. channelFormat != SPEAKERS_MONO &&
  89. channelFormat != SPEAKERS_STEREO &&
  90. maxdevicechannel >= 8 &&
  91. isWin) {
  92. if (audioRepacker->repack((uint8_t *)bytes, frameCount) < 0) {
  93. LOG(LOG_ERROR, "Failed to convert audio packet data");
  94. return;
  95. }
  96. currentPacket.data[0] = (*audioRepacker)->packet_buffer;
  97. } else {
  98. currentPacket.data[0] = (uint8_t *)bytes;
  99. }
  100. nextAudioTS = timestamp +
  101. ((uint64_t)frameCount * 1000000000ULL / 48000ULL) + 1;
  102. obs_source_output_audio(decklink->GetSource(), &currentPacket);
  103. }
  104. void DeckLinkDeviceInstance::HandleVideoFrame(
  105. IDeckLinkVideoInputFrame *videoFrame, const uint64_t timestamp)
  106. {
  107. if (videoFrame == nullptr)
  108. return;
  109. void *bytes;
  110. if (videoFrame->GetBytes(&bytes) != S_OK) {
  111. LOG(LOG_WARNING, "Failed to get video frame data");
  112. return;
  113. }
  114. currentFrame.data[0] = (uint8_t *)bytes;
  115. currentFrame.linesize[0] = (uint32_t)videoFrame->GetRowBytes();
  116. currentFrame.width = (uint32_t)videoFrame->GetWidth();
  117. currentFrame.height = (uint32_t)videoFrame->GetHeight();
  118. currentFrame.timestamp = timestamp;
  119. obs_source_output_video(decklink->GetSource(), &currentFrame);
  120. }
  121. void DeckLinkDeviceInstance::FinalizeStream()
  122. {
  123. input->SetCallback(nullptr);
  124. input->DisableVideoInput();
  125. if (channelFormat != SPEAKERS_UNKNOWN)
  126. input->DisableAudioInput();
  127. if (audioRepacker != nullptr)
  128. {
  129. delete audioRepacker;
  130. audioRepacker = nullptr;
  131. }
  132. mode = nullptr;
  133. }
  134. //#define LOG_SETUP_VIDEO_FORMAT 1
  135. void DeckLinkDeviceInstance::SetupVideoFormat(DeckLinkDeviceMode *mode_)
  136. {
  137. if (mode_ == nullptr)
  138. return;
  139. currentFrame.format = ConvertPixelFormat(pixelFormat);
  140. colorSpace = decklink->GetColorSpace();
  141. if (colorSpace == VIDEO_CS_DEFAULT) {
  142. const BMDDisplayModeFlags flags = mode_->GetDisplayModeFlags();
  143. if (flags & bmdDisplayModeColorspaceRec709)
  144. activeColorSpace = VIDEO_CS_709;
  145. else if (flags & bmdDisplayModeColorspaceRec601)
  146. activeColorSpace = VIDEO_CS_601;
  147. else
  148. activeColorSpace = VIDEO_CS_DEFAULT;
  149. } else {
  150. activeColorSpace = colorSpace;
  151. }
  152. colorRange = decklink->GetColorRange();
  153. currentFrame.full_range = colorRange == VIDEO_RANGE_FULL;
  154. video_format_get_parameters(activeColorSpace, colorRange,
  155. currentFrame.color_matrix, currentFrame.color_range_min,
  156. currentFrame.color_range_max);
  157. #ifdef LOG_SETUP_VIDEO_FORMAT
  158. LOG(LOG_INFO, "Setup video format: %s, %s, %s",
  159. pixelFormat == bmdFormat8BitYUV ? "YUV" : "RGB",
  160. activeColorSpace == VIDEO_CS_709 ? "BT.709" : "BT.601",
  161. colorRange == VIDEO_RANGE_FULL ? "full" : "limited");
  162. #endif
  163. }
  164. bool DeckLinkDeviceInstance::StartCapture(DeckLinkDeviceMode *mode_)
  165. {
  166. if (mode != nullptr)
  167. return false;
  168. if (mode_ == nullptr)
  169. return false;
  170. LOG(LOG_INFO, "Starting capture...");
  171. if (!device->GetInput(&input))
  172. return false;
  173. BMDVideoInputFlags flags;
  174. bool isauto = mode_->GetName() == "Auto";
  175. if (isauto) {
  176. displayMode = bmdModeNTSC;
  177. pixelFormat = bmdFormat8BitYUV;
  178. flags = bmdVideoInputEnableFormatDetection;
  179. } else {
  180. displayMode = mode_->GetDisplayMode();
  181. pixelFormat = decklink->GetPixelFormat();
  182. flags = bmdVideoInputFlagDefault;
  183. }
  184. const HRESULT videoResult = input->EnableVideoInput(displayMode,
  185. pixelFormat, flags);
  186. if (videoResult != S_OK) {
  187. LOG(LOG_ERROR, "Failed to enable video input");
  188. return false;
  189. }
  190. SetupVideoFormat(mode_);
  191. channelFormat = decklink->GetChannelFormat();
  192. currentPacket.speakers = channelFormat;
  193. int maxdevicechannel = device->GetMaxChannel();
  194. bool isWin = IS_WIN;
  195. if (channelFormat != SPEAKERS_UNKNOWN) {
  196. const int channel = ConvertChannelFormat(channelFormat);
  197. const HRESULT audioResult = input->EnableAudioInput(
  198. bmdAudioSampleRate48kHz, bmdAudioSampleType16bitInteger,
  199. channel);
  200. if (audioResult != S_OK)
  201. LOG(LOG_WARNING, "Failed to enable audio input; continuing...");
  202. if (channelFormat != SPEAKERS_UNKNOWN &&
  203. channelFormat != SPEAKERS_MONO &&
  204. channelFormat != SPEAKERS_STEREO &&
  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. }