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.

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