You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

404 lines
14KB

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