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.

468 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_configs(avctx, DIRECTION_OUT) < 0) {
  145. av_log(avctx, AV_LOG_ERROR, "Could not set output configuration\n");
  146. return -1;
  147. }
  148. if (ff_decklink_set_format(avctx, c->width, c->height,
  149. st->time_base.num, st->time_base.den, c->field_order)) {
  150. av_log(avctx, AV_LOG_ERROR, "Unsupported video size, framerate or field order!"
  151. " Check available formats with -list_formats 1.\n");
  152. return -1;
  153. }
  154. if (ctx->dlo->EnableVideoOutput(ctx->bmd_mode,
  155. bmdVideoOutputFlagDefault) != S_OK) {
  156. av_log(avctx, AV_LOG_ERROR, "Could not enable video output!\n");
  157. return -1;
  158. }
  159. /* Set callback. */
  160. ctx->output_callback = new decklink_output_callback();
  161. ctx->dlo->SetScheduledFrameCompletionCallback(ctx->output_callback);
  162. ctx->frames_preroll = st->time_base.den * ctx->preroll;
  163. if (st->time_base.den > 1000)
  164. ctx->frames_preroll /= 1000;
  165. /* Buffer twice as many frames as the preroll. */
  166. ctx->frames_buffer = ctx->frames_preroll * 2;
  167. ctx->frames_buffer = FFMIN(ctx->frames_buffer, 60);
  168. pthread_mutex_init(&ctx->mutex, NULL);
  169. pthread_cond_init(&ctx->cond, NULL);
  170. ctx->frames_buffer_available_spots = ctx->frames_buffer;
  171. /* The device expects the framerate to be fixed. */
  172. avpriv_set_pts_info(st, 64, st->time_base.num, st->time_base.den);
  173. ctx->video = 1;
  174. return 0;
  175. }
  176. static int decklink_setup_audio(AVFormatContext *avctx, AVStream *st)
  177. {
  178. struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
  179. struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
  180. AVCodecParameters *c = st->codecpar;
  181. if (ctx->audio) {
  182. av_log(avctx, AV_LOG_ERROR, "Only one audio stream is supported!\n");
  183. return -1;
  184. }
  185. if (c->sample_rate != 48000) {
  186. av_log(avctx, AV_LOG_ERROR, "Unsupported sample rate!"
  187. " Only 48kHz is supported.\n");
  188. return -1;
  189. }
  190. if (c->channels != 2 && c->channels != 8 && c->channels != 16) {
  191. av_log(avctx, AV_LOG_ERROR, "Unsupported number of channels!"
  192. " Only 2, 8 or 16 channels are supported.\n");
  193. return -1;
  194. }
  195. if (ctx->dlo->EnableAudioOutput(bmdAudioSampleRate48kHz,
  196. bmdAudioSampleType16bitInteger,
  197. c->channels,
  198. bmdAudioOutputStreamTimestamped) != S_OK) {
  199. av_log(avctx, AV_LOG_ERROR, "Could not enable audio output!\n");
  200. return -1;
  201. }
  202. if (ctx->dlo->BeginAudioPreroll() != S_OK) {
  203. av_log(avctx, AV_LOG_ERROR, "Could not begin audio preroll!\n");
  204. return -1;
  205. }
  206. /* The device expects the sample rate to be fixed. */
  207. avpriv_set_pts_info(st, 64, 1, c->sample_rate);
  208. ctx->channels = c->channels;
  209. ctx->audio = 1;
  210. return 0;
  211. }
  212. av_cold int ff_decklink_write_trailer(AVFormatContext *avctx)
  213. {
  214. struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
  215. struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
  216. if (ctx->playback_started) {
  217. BMDTimeValue actual;
  218. ctx->dlo->StopScheduledPlayback(ctx->last_pts * ctx->bmd_tb_num,
  219. &actual, ctx->bmd_tb_den);
  220. ctx->dlo->DisableVideoOutput();
  221. if (ctx->audio)
  222. ctx->dlo->DisableAudioOutput();
  223. }
  224. ff_decklink_cleanup(avctx);
  225. if (ctx->output_callback)
  226. delete ctx->output_callback;
  227. pthread_mutex_destroy(&ctx->mutex);
  228. pthread_cond_destroy(&ctx->cond);
  229. av_freep(&cctx->ctx);
  230. return 0;
  231. }
  232. static int decklink_write_video_packet(AVFormatContext *avctx, AVPacket *pkt)
  233. {
  234. struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
  235. struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
  236. AVStream *st = avctx->streams[pkt->stream_index];
  237. AVFrame *avframe = NULL, *tmp = (AVFrame *)pkt->data;
  238. AVPacket *avpacket = NULL;
  239. decklink_frame *frame;
  240. buffercount_type buffered;
  241. HRESULT hr;
  242. if (st->codecpar->codec_id == AV_CODEC_ID_WRAPPED_AVFRAME) {
  243. if (tmp->format != AV_PIX_FMT_UYVY422 ||
  244. tmp->width != ctx->bmd_width ||
  245. tmp->height != ctx->bmd_height) {
  246. av_log(avctx, AV_LOG_ERROR, "Got a frame with invalid pixel format or dimension.\n");
  247. return AVERROR(EINVAL);
  248. }
  249. avframe = av_frame_clone(tmp);
  250. if (!avframe) {
  251. av_log(avctx, AV_LOG_ERROR, "Could not clone video frame.\n");
  252. return AVERROR(EIO);
  253. }
  254. frame = new decklink_frame(ctx, avframe, st->codecpar->codec_id, avframe->height, avframe->width);
  255. } else {
  256. avpacket = av_packet_clone(pkt);
  257. if (!avpacket) {
  258. av_log(avctx, AV_LOG_ERROR, "Could not clone video frame.\n");
  259. return AVERROR(EIO);
  260. }
  261. frame = new decklink_frame(ctx, avpacket, st->codecpar->codec_id, ctx->bmd_height, ctx->bmd_width);
  262. }
  263. if (!frame) {
  264. av_log(avctx, AV_LOG_ERROR, "Could not create new frame.\n");
  265. av_frame_free(&avframe);
  266. av_packet_free(&avpacket);
  267. return AVERROR(EIO);
  268. }
  269. /* Always keep at most one second of frames buffered. */
  270. pthread_mutex_lock(&ctx->mutex);
  271. while (ctx->frames_buffer_available_spots == 0) {
  272. pthread_cond_wait(&ctx->cond, &ctx->mutex);
  273. }
  274. ctx->frames_buffer_available_spots--;
  275. pthread_mutex_unlock(&ctx->mutex);
  276. /* Schedule frame for playback. */
  277. hr = ctx->dlo->ScheduleVideoFrame((class IDeckLinkVideoFrame *) frame,
  278. pkt->pts * ctx->bmd_tb_num,
  279. ctx->bmd_tb_num, ctx->bmd_tb_den);
  280. /* Pass ownership to DeckLink, or release on failure */
  281. frame->Release();
  282. if (hr != S_OK) {
  283. av_log(avctx, AV_LOG_ERROR, "Could not schedule video frame."
  284. " error %08x.\n", (uint32_t) hr);
  285. return AVERROR(EIO);
  286. }
  287. ctx->dlo->GetBufferedVideoFrameCount(&buffered);
  288. av_log(avctx, AV_LOG_DEBUG, "Buffered video frames: %d.\n", (int) buffered);
  289. if (pkt->pts > 2 && buffered <= 2)
  290. av_log(avctx, AV_LOG_WARNING, "There are not enough buffered video frames."
  291. " Video may misbehave!\n");
  292. /* Preroll video frames. */
  293. if (!ctx->playback_started && pkt->pts > ctx->frames_preroll) {
  294. av_log(avctx, AV_LOG_DEBUG, "Ending audio preroll.\n");
  295. if (ctx->audio && ctx->dlo->EndAudioPreroll() != S_OK) {
  296. av_log(avctx, AV_LOG_ERROR, "Could not end audio preroll!\n");
  297. return AVERROR(EIO);
  298. }
  299. av_log(avctx, AV_LOG_DEBUG, "Starting scheduled playback.\n");
  300. if (ctx->dlo->StartScheduledPlayback(0, ctx->bmd_tb_den, 1.0) != S_OK) {
  301. av_log(avctx, AV_LOG_ERROR, "Could not start scheduled playback!\n");
  302. return AVERROR(EIO);
  303. }
  304. ctx->playback_started = 1;
  305. }
  306. return 0;
  307. }
  308. static int decklink_write_audio_packet(AVFormatContext *avctx, AVPacket *pkt)
  309. {
  310. struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
  311. struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
  312. int sample_count = pkt->size / (ctx->channels << 1);
  313. buffercount_type buffered;
  314. ctx->dlo->GetBufferedAudioSampleFrameCount(&buffered);
  315. if (pkt->pts > 1 && !buffered)
  316. av_log(avctx, AV_LOG_WARNING, "There's no buffered audio."
  317. " Audio will misbehave!\n");
  318. if (ctx->dlo->ScheduleAudioSamples(pkt->data, sample_count, pkt->pts,
  319. bmdAudioSampleRate48kHz, NULL) != S_OK) {
  320. av_log(avctx, AV_LOG_ERROR, "Could not schedule audio samples.\n");
  321. return AVERROR(EIO);
  322. }
  323. return 0;
  324. }
  325. extern "C" {
  326. av_cold int ff_decklink_write_header(AVFormatContext *avctx)
  327. {
  328. struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
  329. struct decklink_ctx *ctx;
  330. unsigned int n;
  331. int ret;
  332. ctx = (struct decklink_ctx *) av_mallocz(sizeof(struct decklink_ctx));
  333. if (!ctx)
  334. return AVERROR(ENOMEM);
  335. ctx->list_devices = cctx->list_devices;
  336. ctx->list_formats = cctx->list_formats;
  337. ctx->preroll = cctx->preroll;
  338. cctx->ctx = ctx;
  339. /* List available devices and exit. */
  340. if (ctx->list_devices) {
  341. ff_decklink_list_devices_legacy(avctx, 0, 1);
  342. return AVERROR_EXIT;
  343. }
  344. ret = ff_decklink_init_device(avctx, avctx->url);
  345. if (ret < 0)
  346. return ret;
  347. /* Get output device. */
  348. if (ctx->dl->QueryInterface(IID_IDeckLinkOutput, (void **) &ctx->dlo) != S_OK) {
  349. av_log(avctx, AV_LOG_ERROR, "Could not open output device from '%s'\n",
  350. avctx->url);
  351. ret = AVERROR(EIO);
  352. goto error;
  353. }
  354. /* List supported formats. */
  355. if (ctx->list_formats) {
  356. ff_decklink_list_formats(avctx);
  357. ret = AVERROR_EXIT;
  358. goto error;
  359. }
  360. /* Setup streams. */
  361. ret = AVERROR(EIO);
  362. for (n = 0; n < avctx->nb_streams; n++) {
  363. AVStream *st = avctx->streams[n];
  364. AVCodecParameters *c = st->codecpar;
  365. if (c->codec_type == AVMEDIA_TYPE_AUDIO) {
  366. if (decklink_setup_audio(avctx, st))
  367. goto error;
  368. } else if (c->codec_type == AVMEDIA_TYPE_VIDEO) {
  369. if (decklink_setup_video(avctx, st))
  370. goto error;
  371. } else {
  372. av_log(avctx, AV_LOG_ERROR, "Unsupported stream type.\n");
  373. goto error;
  374. }
  375. }
  376. return 0;
  377. error:
  378. ff_decklink_cleanup(avctx);
  379. return ret;
  380. }
  381. int ff_decklink_write_packet(AVFormatContext *avctx, AVPacket *pkt)
  382. {
  383. struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
  384. struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
  385. AVStream *st = avctx->streams[pkt->stream_index];
  386. ctx->last_pts = FFMAX(ctx->last_pts, pkt->pts);
  387. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
  388. return decklink_write_video_packet(avctx, pkt);
  389. else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
  390. return decklink_write_audio_packet(avctx, pkt);
  391. return AVERROR(EIO);
  392. }
  393. int ff_decklink_list_output_devices(AVFormatContext *avctx, struct AVDeviceInfoList *device_list)
  394. {
  395. return ff_decklink_list_devices(avctx, device_list, 0, 1);
  396. }
  397. } /* extern "C" */