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.

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