decklink-device-instance.cpp 9.5 KB

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