decklink_enc.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. /*
  2. * Blackmagic DeckLink output
  3. * Copyright (c) 2013-2014 Ramiro Polla
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include <atomic>
  22. using std::atomic;
  23. /* Include internal.h first to avoid conflict between winsock.h (used by
  24. * DeckLink headers) and winsock2.h (used by libavformat) in MSVC++ builds */
  25. extern "C" {
  26. #include "libavformat/internal.h"
  27. }
  28. #include <DeckLinkAPI.h>
  29. extern "C" {
  30. #include "libavformat/avformat.h"
  31. #include "libavutil/imgutils.h"
  32. #include "avdevice.h"
  33. }
  34. #include "decklink_common.h"
  35. #include "decklink_enc.h"
  36. /* DeckLink callback class declaration */
  37. class decklink_frame : public IDeckLinkVideoFrame
  38. {
  39. public:
  40. decklink_frame(struct decklink_ctx *ctx, AVFrame *avframe) :
  41. _ctx(ctx), _avframe(avframe), _refs(1) { }
  42. virtual long STDMETHODCALLTYPE GetWidth (void) { return _avframe->width; }
  43. virtual long STDMETHODCALLTYPE GetHeight (void) { return _avframe->height; }
  44. virtual long STDMETHODCALLTYPE GetRowBytes (void) { return _avframe->linesize[0] < 0 ? -_avframe->linesize[0] : _avframe->linesize[0]; }
  45. virtual BMDPixelFormat STDMETHODCALLTYPE GetPixelFormat(void) { return bmdFormat8BitYUV; }
  46. virtual BMDFrameFlags STDMETHODCALLTYPE GetFlags (void) { return _avframe->linesize[0] < 0 ? bmdFrameFlagFlipVertical : bmdFrameFlagDefault; }
  47. virtual HRESULT STDMETHODCALLTYPE GetBytes (void **buffer)
  48. {
  49. if (_avframe->linesize[0] < 0)
  50. *buffer = (void *)(_avframe->data[0] + _avframe->linesize[0] * (_avframe->height - 1));
  51. else
  52. *buffer = (void *)(_avframe->data[0]);
  53. return S_OK;
  54. }
  55. virtual HRESULT STDMETHODCALLTYPE GetTimecode (BMDTimecodeFormat format, IDeckLinkTimecode **timecode) { return S_FALSE; }
  56. virtual HRESULT STDMETHODCALLTYPE GetAncillaryData(IDeckLinkVideoFrameAncillary **ancillary) { return S_FALSE; }
  57. virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv) { return E_NOINTERFACE; }
  58. virtual ULONG STDMETHODCALLTYPE AddRef(void) { return ++_refs; }
  59. virtual ULONG STDMETHODCALLTYPE Release(void)
  60. {
  61. int ret = --_refs;
  62. if (!ret) {
  63. av_frame_free(&_avframe);
  64. delete this;
  65. }
  66. return ret;
  67. }
  68. struct decklink_ctx *_ctx;
  69. AVFrame *_avframe;
  70. private:
  71. std::atomic<int> _refs;
  72. };
  73. class decklink_output_callback : public IDeckLinkVideoOutputCallback
  74. {
  75. public:
  76. virtual HRESULT STDMETHODCALLTYPE ScheduledFrameCompleted(IDeckLinkVideoFrame *_frame, BMDOutputFrameCompletionResult result)
  77. {
  78. decklink_frame *frame = static_cast<decklink_frame *>(_frame);
  79. struct decklink_ctx *ctx = frame->_ctx;
  80. AVFrame *avframe = frame->_avframe;
  81. av_frame_unref(avframe);
  82. pthread_mutex_lock(&ctx->mutex);
  83. ctx->frames_buffer_available_spots++;
  84. pthread_cond_broadcast(&ctx->cond);
  85. pthread_mutex_unlock(&ctx->mutex);
  86. return S_OK;
  87. }
  88. virtual HRESULT STDMETHODCALLTYPE ScheduledPlaybackHasStopped(void) { return S_OK; }
  89. virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv) { return E_NOINTERFACE; }
  90. virtual ULONG STDMETHODCALLTYPE AddRef(void) { return 1; }
  91. virtual ULONG STDMETHODCALLTYPE Release(void) { return 1; }
  92. };
  93. static int decklink_setup_video(AVFormatContext *avctx, AVStream *st)
  94. {
  95. struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
  96. struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
  97. AVCodecParameters *c = st->codecpar;
  98. if (ctx->video) {
  99. av_log(avctx, AV_LOG_ERROR, "Only one video stream is supported!\n");
  100. return -1;
  101. }
  102. if (c->format != AV_PIX_FMT_UYVY422) {
  103. av_log(avctx, AV_LOG_ERROR, "Unsupported pixel format!"
  104. " Only AV_PIX_FMT_UYVY422 is supported.\n");
  105. return -1;
  106. }
  107. if (ff_decklink_set_format(avctx, c->width, c->height,
  108. st->time_base.num, st->time_base.den, c->field_order)) {
  109. av_log(avctx, AV_LOG_ERROR, "Unsupported video size, framerate or field order!"
  110. " Check available formats with -list_formats 1.\n");
  111. return -1;
  112. }
  113. if (ctx->dlo->EnableVideoOutput(ctx->bmd_mode,
  114. bmdVideoOutputFlagDefault) != S_OK) {
  115. av_log(avctx, AV_LOG_ERROR, "Could not enable video output!\n");
  116. return -1;
  117. }
  118. /* Set callback. */
  119. ctx->output_callback = new decklink_output_callback();
  120. ctx->dlo->SetScheduledFrameCompletionCallback(ctx->output_callback);
  121. ctx->frames_preroll = st->time_base.den * ctx->preroll;
  122. if (st->time_base.den > 1000)
  123. ctx->frames_preroll /= 1000;
  124. /* Buffer twice as many frames as the preroll. */
  125. ctx->frames_buffer = ctx->frames_preroll * 2;
  126. ctx->frames_buffer = FFMIN(ctx->frames_buffer, 60);
  127. pthread_mutex_init(&ctx->mutex, NULL);
  128. pthread_cond_init(&ctx->cond, NULL);
  129. ctx->frames_buffer_available_spots = ctx->frames_buffer;
  130. /* The device expects the framerate to be fixed. */
  131. avpriv_set_pts_info(st, 64, st->time_base.num, st->time_base.den);
  132. ctx->video = 1;
  133. return 0;
  134. }
  135. static int decklink_setup_audio(AVFormatContext *avctx, AVStream *st)
  136. {
  137. struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
  138. struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
  139. AVCodecParameters *c = st->codecpar;
  140. if (ctx->audio) {
  141. av_log(avctx, AV_LOG_ERROR, "Only one audio stream is supported!\n");
  142. return -1;
  143. }
  144. if (c->sample_rate != 48000) {
  145. av_log(avctx, AV_LOG_ERROR, "Unsupported sample rate!"
  146. " Only 48kHz is supported.\n");
  147. return -1;
  148. }
  149. if (c->channels != 2 && c->channels != 8 && c->channels != 16) {
  150. av_log(avctx, AV_LOG_ERROR, "Unsupported number of channels!"
  151. " Only 2, 8 or 16 channels are supported.\n");
  152. return -1;
  153. }
  154. if (ctx->dlo->EnableAudioOutput(bmdAudioSampleRate48kHz,
  155. bmdAudioSampleType16bitInteger,
  156. c->channels,
  157. bmdAudioOutputStreamTimestamped) != S_OK) {
  158. av_log(avctx, AV_LOG_ERROR, "Could not enable audio output!\n");
  159. return -1;
  160. }
  161. if (ctx->dlo->BeginAudioPreroll() != S_OK) {
  162. av_log(avctx, AV_LOG_ERROR, "Could not begin audio preroll!\n");
  163. return -1;
  164. }
  165. /* The device expects the sample rate to be fixed. */
  166. avpriv_set_pts_info(st, 64, 1, c->sample_rate);
  167. ctx->channels = c->channels;
  168. ctx->audio = 1;
  169. return 0;
  170. }
  171. av_cold int ff_decklink_write_trailer(AVFormatContext *avctx)
  172. {
  173. struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
  174. struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
  175. if (ctx->playback_started) {
  176. BMDTimeValue actual;
  177. ctx->dlo->StopScheduledPlayback(ctx->last_pts * ctx->bmd_tb_num,
  178. &actual, ctx->bmd_tb_den);
  179. ctx->dlo->DisableVideoOutput();
  180. if (ctx->audio)
  181. ctx->dlo->DisableAudioOutput();
  182. }
  183. ff_decklink_cleanup(avctx);
  184. if (ctx->output_callback)
  185. delete ctx->output_callback;
  186. pthread_mutex_destroy(&ctx->mutex);
  187. pthread_cond_destroy(&ctx->cond);
  188. av_freep(&cctx->ctx);
  189. return 0;
  190. }
  191. static int decklink_write_video_packet(AVFormatContext *avctx, AVPacket *pkt)
  192. {
  193. struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
  194. struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
  195. AVFrame *avframe, *tmp = (AVFrame *)pkt->data;
  196. decklink_frame *frame;
  197. buffercount_type buffered;
  198. HRESULT hr;
  199. if (tmp->format != AV_PIX_FMT_UYVY422 ||
  200. tmp->width != ctx->bmd_width ||
  201. tmp->height != ctx->bmd_height) {
  202. av_log(avctx, AV_LOG_ERROR, "Got a frame with invalid pixel format or dimension.\n");
  203. return AVERROR(EINVAL);
  204. }
  205. avframe = av_frame_clone(tmp);
  206. if (!avframe) {
  207. av_log(avctx, AV_LOG_ERROR, "Could not clone video frame.\n");
  208. return AVERROR(EIO);
  209. }
  210. frame = new decklink_frame(ctx, avframe);
  211. if (!frame) {
  212. av_log(avctx, AV_LOG_ERROR, "Could not create new frame.\n");
  213. av_frame_free(&avframe);
  214. return AVERROR(EIO);
  215. }
  216. /* Always keep at most one second of frames buffered. */
  217. pthread_mutex_lock(&ctx->mutex);
  218. while (ctx->frames_buffer_available_spots == 0) {
  219. pthread_cond_wait(&ctx->cond, &ctx->mutex);
  220. }
  221. ctx->frames_buffer_available_spots--;
  222. pthread_mutex_unlock(&ctx->mutex);
  223. /* Schedule frame for playback. */
  224. hr = ctx->dlo->ScheduleVideoFrame((struct IDeckLinkVideoFrame *) frame,
  225. pkt->pts * ctx->bmd_tb_num,
  226. ctx->bmd_tb_num, ctx->bmd_tb_den);
  227. /* Pass ownership to DeckLink, or release on failure */
  228. frame->Release();
  229. if (hr != S_OK) {
  230. av_log(avctx, AV_LOG_ERROR, "Could not schedule video frame."
  231. " error %08x.\n", (uint32_t) hr);
  232. return AVERROR(EIO);
  233. }
  234. ctx->dlo->GetBufferedVideoFrameCount(&buffered);
  235. av_log(avctx, AV_LOG_DEBUG, "Buffered video frames: %d.\n", (int) buffered);
  236. if (pkt->pts > 2 && buffered <= 2)
  237. av_log(avctx, AV_LOG_WARNING, "There are not enough buffered video frames."
  238. " Video may misbehave!\n");
  239. /* Preroll video frames. */
  240. if (!ctx->playback_started && pkt->pts > ctx->frames_preroll) {
  241. av_log(avctx, AV_LOG_DEBUG, "Ending audio preroll.\n");
  242. if (ctx->audio && ctx->dlo->EndAudioPreroll() != S_OK) {
  243. av_log(avctx, AV_LOG_ERROR, "Could not end audio preroll!\n");
  244. return AVERROR(EIO);
  245. }
  246. av_log(avctx, AV_LOG_DEBUG, "Starting scheduled playback.\n");
  247. if (ctx->dlo->StartScheduledPlayback(0, ctx->bmd_tb_den, 1.0) != S_OK) {
  248. av_log(avctx, AV_LOG_ERROR, "Could not start scheduled playback!\n");
  249. return AVERROR(EIO);
  250. }
  251. ctx->playback_started = 1;
  252. }
  253. return 0;
  254. }
  255. static int decklink_write_audio_packet(AVFormatContext *avctx, AVPacket *pkt)
  256. {
  257. struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
  258. struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
  259. int sample_count = pkt->size / (ctx->channels << 1);
  260. buffercount_type buffered;
  261. ctx->dlo->GetBufferedAudioSampleFrameCount(&buffered);
  262. if (pkt->pts > 1 && !buffered)
  263. av_log(avctx, AV_LOG_WARNING, "There's no buffered audio."
  264. " Audio will misbehave!\n");
  265. if (ctx->dlo->ScheduleAudioSamples(pkt->data, sample_count, pkt->pts,
  266. bmdAudioSampleRate48kHz, NULL) != S_OK) {
  267. av_log(avctx, AV_LOG_ERROR, "Could not schedule audio samples.\n");
  268. return AVERROR(EIO);
  269. }
  270. return 0;
  271. }
  272. extern "C" {
  273. av_cold int ff_decklink_write_header(AVFormatContext *avctx)
  274. {
  275. struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
  276. struct decklink_ctx *ctx;
  277. unsigned int n;
  278. int ret;
  279. ctx = (struct decklink_ctx *) av_mallocz(sizeof(struct decklink_ctx));
  280. if (!ctx)
  281. return AVERROR(ENOMEM);
  282. ctx->list_devices = cctx->list_devices;
  283. ctx->list_formats = cctx->list_formats;
  284. ctx->preroll = cctx->preroll;
  285. cctx->ctx = ctx;
  286. /* List available devices and exit. */
  287. if (ctx->list_devices) {
  288. ff_decklink_list_devices_legacy(avctx, 0, 1);
  289. return AVERROR_EXIT;
  290. }
  291. ret = ff_decklink_init_device(avctx, avctx->filename);
  292. if (ret < 0)
  293. return ret;
  294. /* Get output device. */
  295. if (ctx->dl->QueryInterface(IID_IDeckLinkOutput, (void **) &ctx->dlo) != S_OK) {
  296. av_log(avctx, AV_LOG_ERROR, "Could not open output device from '%s'\n",
  297. avctx->filename);
  298. ret = AVERROR(EIO);
  299. goto error;
  300. }
  301. /* List supported formats. */
  302. if (ctx->list_formats) {
  303. ff_decklink_list_formats(avctx);
  304. ret = AVERROR_EXIT;
  305. goto error;
  306. }
  307. /* Setup streams. */
  308. ret = AVERROR(EIO);
  309. for (n = 0; n < avctx->nb_streams; n++) {
  310. AVStream *st = avctx->streams[n];
  311. AVCodecParameters *c = st->codecpar;
  312. if (c->codec_type == AVMEDIA_TYPE_AUDIO) {
  313. if (decklink_setup_audio(avctx, st))
  314. goto error;
  315. } else if (c->codec_type == AVMEDIA_TYPE_VIDEO) {
  316. if (decklink_setup_video(avctx, st))
  317. goto error;
  318. } else {
  319. av_log(avctx, AV_LOG_ERROR, "Unsupported stream type.\n");
  320. goto error;
  321. }
  322. }
  323. return 0;
  324. error:
  325. ff_decklink_cleanup(avctx);
  326. return ret;
  327. }
  328. int ff_decklink_write_packet(AVFormatContext *avctx, AVPacket *pkt)
  329. {
  330. struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
  331. struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
  332. AVStream *st = avctx->streams[pkt->stream_index];
  333. ctx->last_pts = FFMAX(ctx->last_pts, pkt->pts);
  334. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
  335. return decklink_write_video_packet(avctx, pkt);
  336. else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
  337. return decklink_write_audio_packet(avctx, pkt);
  338. return AVERROR(EIO);
  339. }
  340. int ff_decklink_list_output_devices(AVFormatContext *avctx, struct AVDeviceInfoList *device_list)
  341. {
  342. return ff_decklink_list_devices(avctx, device_list, 0, 1);
  343. }
  344. } /* extern "C" */