decklink_enc.cpp 13 KB

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