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.

464 lines
16KB

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