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.

390 lines
13KB

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