2 * Blackmagic DeckLink output
3 * Copyright (c) 2013-2014 Ramiro Polla
5 * This file is part of FFmpeg.
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.
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.
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
25 /* Include internal.h first to avoid conflict between winsock.h (used by
26 * DeckLink headers) and winsock2.h (used by libavformat) in MSVC++ builds */
28 #include "libavformat/internal.h"
31 #include <DeckLinkAPI.h>
34 #include "libavformat/avformat.h"
35 #include "libavutil/imgutils.h"
39 #include "decklink_common.h"
40 #include "decklink_enc.h"
42 #include "libklvanc/vanc.h"
43 #include "libklvanc/vanc-lines.h"
44 #include "libklvanc/pixels.h"
47 /* DeckLink callback class declaration */
48 class decklink_frame : public IDeckLinkVideoFrame
51 decklink_frame(struct decklink_ctx *ctx, AVFrame *avframe, AVCodecID codec_id, int height, int width) :
52 _ctx(ctx), _avframe(avframe), _avpacket(NULL), _codec_id(codec_id), _ancillary(NULL), _height(height), _width(width), _refs(1) { }
53 decklink_frame(struct decklink_ctx *ctx, AVPacket *avpacket, AVCodecID codec_id, int height, int width) :
54 _ctx(ctx), _avframe(NULL), _avpacket(avpacket), _codec_id(codec_id), _ancillary(NULL), _height(height), _width(width), _refs(1) { }
55 virtual long STDMETHODCALLTYPE GetWidth (void) { return _width; }
56 virtual long STDMETHODCALLTYPE GetHeight (void) { return _height; }
57 virtual long STDMETHODCALLTYPE GetRowBytes (void)
59 if (_codec_id == AV_CODEC_ID_WRAPPED_AVFRAME)
60 return _avframe->linesize[0] < 0 ? -_avframe->linesize[0] : _avframe->linesize[0];
62 return ((GetWidth() + 47) / 48) * 128;
64 virtual BMDPixelFormat STDMETHODCALLTYPE GetPixelFormat(void)
66 if (_codec_id == AV_CODEC_ID_WRAPPED_AVFRAME)
67 return bmdFormat8BitYUV;
69 return bmdFormat10BitYUV;
71 virtual BMDFrameFlags STDMETHODCALLTYPE GetFlags (void)
73 if (_codec_id == AV_CODEC_ID_WRAPPED_AVFRAME)
74 return _avframe->linesize[0] < 0 ? bmdFrameFlagFlipVertical : bmdFrameFlagDefault;
76 return bmdFrameFlagDefault;
79 virtual HRESULT STDMETHODCALLTYPE GetBytes (void **buffer)
81 if (_codec_id == AV_CODEC_ID_WRAPPED_AVFRAME) {
82 if (_avframe->linesize[0] < 0)
83 *buffer = (void *)(_avframe->data[0] + _avframe->linesize[0] * (_avframe->height - 1));
85 *buffer = (void *)(_avframe->data[0]);
87 *buffer = (void *)(_avpacket->data);
92 virtual HRESULT STDMETHODCALLTYPE GetTimecode (BMDTimecodeFormat format, IDeckLinkTimecode **timecode) { return S_FALSE; }
93 virtual HRESULT STDMETHODCALLTYPE GetAncillaryData(IDeckLinkVideoFrameAncillary **ancillary)
95 *ancillary = _ancillary;
103 virtual HRESULT STDMETHODCALLTYPE SetAncillaryData(IDeckLinkVideoFrameAncillary *ancillary)
106 _ancillary->Release();
107 _ancillary = ancillary;
108 _ancillary->AddRef();
111 virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv) { return E_NOINTERFACE; }
112 virtual ULONG STDMETHODCALLTYPE AddRef(void) { return ++_refs; }
113 virtual ULONG STDMETHODCALLTYPE Release(void)
117 av_frame_free(&_avframe);
118 av_packet_free(&_avpacket);
120 _ancillary->Release();
126 struct decklink_ctx *_ctx;
130 IDeckLinkVideoFrameAncillary *_ancillary;
135 std::atomic<int> _refs;
138 class decklink_output_callback : public IDeckLinkVideoOutputCallback
141 virtual HRESULT STDMETHODCALLTYPE ScheduledFrameCompleted(IDeckLinkVideoFrame *_frame, BMDOutputFrameCompletionResult result)
143 decklink_frame *frame = static_cast<decklink_frame *>(_frame);
144 struct decklink_ctx *ctx = frame->_ctx;
147 av_frame_unref(frame->_avframe);
148 if (frame->_avpacket)
149 av_packet_unref(frame->_avpacket);
151 pthread_mutex_lock(&ctx->mutex);
152 ctx->frames_buffer_available_spots++;
153 pthread_cond_broadcast(&ctx->cond);
154 pthread_mutex_unlock(&ctx->mutex);
158 virtual HRESULT STDMETHODCALLTYPE ScheduledPlaybackHasStopped(void) { return S_OK; }
159 virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv) { return E_NOINTERFACE; }
160 virtual ULONG STDMETHODCALLTYPE AddRef(void) { return 1; }
161 virtual ULONG STDMETHODCALLTYPE Release(void) { return 1; }
164 static int decklink_setup_video(AVFormatContext *avctx, AVStream *st)
166 struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
167 struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
168 AVCodecParameters *c = st->codecpar;
171 av_log(avctx, AV_LOG_ERROR, "Only one video stream is supported!\n");
175 if (c->codec_id == AV_CODEC_ID_WRAPPED_AVFRAME) {
176 if (c->format != AV_PIX_FMT_UYVY422) {
177 av_log(avctx, AV_LOG_ERROR, "Unsupported pixel format!"
178 " Only AV_PIX_FMT_UYVY422 is supported.\n");
181 ctx->raw_format = bmdFormat8BitYUV;
182 } else if (c->codec_id != AV_CODEC_ID_V210) {
183 av_log(avctx, AV_LOG_ERROR, "Unsupported codec type!"
184 " Only V210 and wrapped frame with AV_PIX_FMT_UYVY422 are supported.\n");
187 ctx->raw_format = bmdFormat10BitYUV;
190 if (ff_decklink_set_configs(avctx, DIRECTION_OUT) < 0) {
191 av_log(avctx, AV_LOG_ERROR, "Could not set output configuration\n");
194 if (ff_decklink_set_format(avctx, c->width, c->height,
195 st->time_base.num, st->time_base.den, c->field_order)) {
196 av_log(avctx, AV_LOG_ERROR, "Unsupported video size, framerate or field order!"
197 " Check available formats with -list_formats 1.\n");
200 if (ctx->dlo->EnableVideoOutput(ctx->bmd_mode,
201 ctx->supports_vanc ? bmdVideoOutputVANC : bmdVideoOutputFlagDefault) != S_OK) {
202 av_log(avctx, AV_LOG_ERROR, "Could not enable video output!\n");
207 ctx->output_callback = new decklink_output_callback();
208 ctx->dlo->SetScheduledFrameCompletionCallback(ctx->output_callback);
210 ctx->frames_preroll = st->time_base.den * ctx->preroll;
211 if (st->time_base.den > 1000)
212 ctx->frames_preroll /= 1000;
214 /* Buffer twice as many frames as the preroll. */
215 ctx->frames_buffer = ctx->frames_preroll * 2;
216 ctx->frames_buffer = FFMIN(ctx->frames_buffer, 60);
217 pthread_mutex_init(&ctx->mutex, NULL);
218 pthread_cond_init(&ctx->cond, NULL);
219 ctx->frames_buffer_available_spots = ctx->frames_buffer;
221 av_log(avctx, AV_LOG_DEBUG, "output: %s, preroll: %d, frames buffer size: %d\n",
222 avctx->url, ctx->frames_preroll, ctx->frames_buffer);
224 /* The device expects the framerate to be fixed. */
225 avpriv_set_pts_info(st, 64, st->time_base.num, st->time_base.den);
232 static int decklink_setup_audio(AVFormatContext *avctx, AVStream *st)
234 struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
235 struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
236 AVCodecParameters *c = st->codecpar;
239 av_log(avctx, AV_LOG_ERROR, "Only one audio stream is supported!\n");
242 if (c->sample_rate != 48000) {
243 av_log(avctx, AV_LOG_ERROR, "Unsupported sample rate!"
244 " Only 48kHz is supported.\n");
247 if (c->channels != 2 && c->channels != 8 && c->channels != 16) {
248 av_log(avctx, AV_LOG_ERROR, "Unsupported number of channels!"
249 " Only 2, 8 or 16 channels are supported.\n");
252 if (ctx->dlo->EnableAudioOutput(bmdAudioSampleRate48kHz,
253 bmdAudioSampleType16bitInteger,
255 bmdAudioOutputStreamTimestamped) != S_OK) {
256 av_log(avctx, AV_LOG_ERROR, "Could not enable audio output!\n");
259 if (ctx->dlo->BeginAudioPreroll() != S_OK) {
260 av_log(avctx, AV_LOG_ERROR, "Could not begin audio preroll!\n");
264 /* The device expects the sample rate to be fixed. */
265 avpriv_set_pts_info(st, 64, 1, c->sample_rate);
266 ctx->channels = c->channels;
273 av_cold int ff_decklink_write_trailer(AVFormatContext *avctx)
275 struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
276 struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
278 if (ctx->playback_started) {
280 ctx->dlo->StopScheduledPlayback(ctx->last_pts * ctx->bmd_tb_num,
281 &actual, ctx->bmd_tb_den);
282 ctx->dlo->DisableVideoOutput();
284 ctx->dlo->DisableAudioOutput();
287 ff_decklink_cleanup(avctx);
289 if (ctx->output_callback)
290 delete ctx->output_callback;
292 pthread_mutex_destroy(&ctx->mutex);
293 pthread_cond_destroy(&ctx->cond);
296 klvanc_context_destroy(ctx->vanc_ctx);
299 av_freep(&cctx->ctx);
305 static void construct_cc(AVFormatContext *avctx, struct decklink_ctx *ctx,
306 AVPacket *pkt, struct klvanc_line_set_s *vanc_lines)
308 struct klvanc_packet_eia_708b_s *cdp;
314 const uint8_t *data = av_packet_get_side_data(pkt, AV_PKT_DATA_A53_CC, &size);
320 ret = klvanc_create_eia708_cdp(&cdp);
324 ret = klvanc_set_framerate_EIA_708B(cdp, ctx->bmd_tb_num, ctx->bmd_tb_den);
326 av_log(avctx, AV_LOG_ERROR, "Invalid framerate specified: %lld/%lld\n",
327 ctx->bmd_tb_num, ctx->bmd_tb_den);
328 klvanc_destroy_eia708_cdp(cdp);
332 if (cc_count > KLVANC_MAX_CC_COUNT) {
333 av_log(avctx, AV_LOG_ERROR, "Illegal cc_count received: %d\n", cc_count);
334 cc_count = KLVANC_MAX_CC_COUNT;
338 cdp->header.ccdata_present = 1;
339 cdp->header.caption_service_active = 1;
340 cdp->ccdata.cc_count = cc_count;
341 for (i = 0; i < cc_count; i++) {
342 if (data [3*i] & 0x04)
343 cdp->ccdata.cc[i].cc_valid = 1;
344 cdp->ccdata.cc[i].cc_type = data[3*i] & 0x03;
345 cdp->ccdata.cc[i].cc_data[0] = data[3*i+1];
346 cdp->ccdata.cc[i].cc_data[1] = data[3*i+2];
349 klvanc_finalize_EIA_708B(cdp, ctx->cdp_sequence_num++);
350 ret = klvanc_convert_EIA_708B_to_words(cdp, &cdp_words, &len);
351 klvanc_destroy_eia708_cdp(cdp);
353 av_log(avctx, AV_LOG_ERROR, "Failed converting 708 packet to words\n");
357 ret = klvanc_line_insert(ctx->vanc_ctx, vanc_lines, cdp_words, len, 11, 0);
360 av_log(avctx, AV_LOG_ERROR, "VANC line insertion failed\n");
365 static int decklink_construct_vanc(AVFormatContext *avctx, struct decklink_ctx *ctx,
366 AVPacket *pkt, decklink_frame *frame)
368 struct klvanc_line_set_s vanc_lines = { 0 };
371 if (!ctx->supports_vanc)
374 construct_cc(avctx, ctx, pkt, &vanc_lines);
376 IDeckLinkVideoFrameAncillary *vanc;
377 int result = ctx->dlo->CreateAncillaryData(bmdFormat10BitYUV, &vanc);
378 if (result != S_OK) {
379 av_log(avctx, AV_LOG_ERROR, "Failed to create vanc\n");
384 /* Now that we've got all the VANC lines in a nice orderly manner, generate the
385 final VANC sections for the Decklink output */
386 for (i = 0; i < vanc_lines.num_lines; i++) {
387 struct klvanc_line_s *line = vanc_lines.lines[i];
394 /* FIXME: include hack for certain Decklink cards which mis-represent
395 line numbers for pSF frames */
396 real_line = line->line_number;
398 result = vanc->GetBufferForVerticalBlankingLine(real_line, &buf);
399 if (result != S_OK) {
400 av_log(avctx, AV_LOG_ERROR, "Failed to get VANC line %d: %d", real_line, result);
404 /* Generate the full line taking into account all VANC packets on that line */
405 result = klvanc_generate_vanc_line_v210(ctx->vanc_ctx, line, (uint8_t *) buf,
408 av_log(avctx, AV_LOG_ERROR, "Failed to generate VANC line\n");
413 result = frame->SetAncillaryData(vanc);
415 if (result != S_OK) {
416 av_log(avctx, AV_LOG_ERROR, "Failed to set vanc: %d", result);
421 for (i = 0; i < vanc_lines.num_lines; i++)
422 klvanc_line_free(vanc_lines.lines[i]);
428 static int decklink_write_video_packet(AVFormatContext *avctx, AVPacket *pkt)
430 struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
431 struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
432 AVStream *st = avctx->streams[pkt->stream_index];
433 AVFrame *avframe = NULL, *tmp = (AVFrame *)pkt->data;
434 AVPacket *avpacket = NULL;
435 decklink_frame *frame;
436 buffercount_type buffered;
439 if (st->codecpar->codec_id == AV_CODEC_ID_WRAPPED_AVFRAME) {
440 if (tmp->format != AV_PIX_FMT_UYVY422 ||
441 tmp->width != ctx->bmd_width ||
442 tmp->height != ctx->bmd_height) {
443 av_log(avctx, AV_LOG_ERROR, "Got a frame with invalid pixel format or dimension.\n");
444 return AVERROR(EINVAL);
447 avframe = av_frame_clone(tmp);
449 av_log(avctx, AV_LOG_ERROR, "Could not clone video frame.\n");
453 frame = new decklink_frame(ctx, avframe, st->codecpar->codec_id, avframe->height, avframe->width);
455 avpacket = av_packet_clone(pkt);
457 av_log(avctx, AV_LOG_ERROR, "Could not clone video frame.\n");
461 frame = new decklink_frame(ctx, avpacket, st->codecpar->codec_id, ctx->bmd_height, ctx->bmd_width);
464 if (decklink_construct_vanc(avctx, ctx, pkt, frame))
465 av_log(avctx, AV_LOG_ERROR, "Failed to construct VANC\n");
470 av_log(avctx, AV_LOG_ERROR, "Could not create new frame.\n");
471 av_frame_free(&avframe);
472 av_packet_free(&avpacket);
476 /* Always keep at most one second of frames buffered. */
477 pthread_mutex_lock(&ctx->mutex);
478 while (ctx->frames_buffer_available_spots == 0) {
479 pthread_cond_wait(&ctx->cond, &ctx->mutex);
481 ctx->frames_buffer_available_spots--;
482 pthread_mutex_unlock(&ctx->mutex);
484 /* Schedule frame for playback. */
485 hr = ctx->dlo->ScheduleVideoFrame((class IDeckLinkVideoFrame *) frame,
486 pkt->pts * ctx->bmd_tb_num,
487 ctx->bmd_tb_num, ctx->bmd_tb_den);
488 /* Pass ownership to DeckLink, or release on failure */
491 av_log(avctx, AV_LOG_ERROR, "Could not schedule video frame."
492 " error %08x.\n", (uint32_t) hr);
496 ctx->dlo->GetBufferedVideoFrameCount(&buffered);
497 av_log(avctx, AV_LOG_DEBUG, "Buffered video frames: %d.\n", (int) buffered);
498 if (pkt->pts > 2 && buffered <= 2)
499 av_log(avctx, AV_LOG_WARNING, "There are not enough buffered video frames."
500 " Video may misbehave!\n");
502 /* Preroll video frames. */
503 if (!ctx->playback_started && pkt->pts > ctx->frames_preroll) {
504 av_log(avctx, AV_LOG_DEBUG, "Ending audio preroll.\n");
505 if (ctx->audio && ctx->dlo->EndAudioPreroll() != S_OK) {
506 av_log(avctx, AV_LOG_ERROR, "Could not end audio preroll!\n");
509 av_log(avctx, AV_LOG_DEBUG, "Starting scheduled playback.\n");
510 if (ctx->dlo->StartScheduledPlayback(0, ctx->bmd_tb_den, 1.0) != S_OK) {
511 av_log(avctx, AV_LOG_ERROR, "Could not start scheduled playback!\n");
514 ctx->playback_started = 1;
520 static int decklink_write_audio_packet(AVFormatContext *avctx, AVPacket *pkt)
522 struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
523 struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
524 int sample_count = pkt->size / (ctx->channels << 1);
525 buffercount_type buffered;
527 ctx->dlo->GetBufferedAudioSampleFrameCount(&buffered);
528 if (pkt->pts > 1 && !buffered)
529 av_log(avctx, AV_LOG_WARNING, "There's no buffered audio."
530 " Audio will misbehave!\n");
532 if (ctx->dlo->ScheduleAudioSamples(pkt->data, sample_count, pkt->pts,
533 bmdAudioSampleRate48kHz, NULL) != S_OK) {
534 av_log(avctx, AV_LOG_ERROR, "Could not schedule audio samples.\n");
543 av_cold int ff_decklink_write_header(AVFormatContext *avctx)
545 struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
546 struct decklink_ctx *ctx;
550 ctx = (struct decklink_ctx *) av_mallocz(sizeof(struct decklink_ctx));
552 return AVERROR(ENOMEM);
553 ctx->list_devices = cctx->list_devices;
554 ctx->list_formats = cctx->list_formats;
555 ctx->preroll = cctx->preroll;
556 ctx->duplex_mode = cctx->duplex_mode;
559 if (klvanc_context_create(&ctx->vanc_ctx) < 0) {
560 av_log(avctx, AV_LOG_ERROR, "Cannot create VANC library context\n");
561 return AVERROR(ENOMEM);
563 ctx->supports_vanc = 1;
566 /* List available devices and exit. */
567 if (ctx->list_devices) {
568 ff_decklink_list_devices_legacy(avctx, 0, 1);
572 ret = ff_decklink_init_device(avctx, avctx->url);
576 /* Get output device. */
577 if (ctx->dl->QueryInterface(IID_IDeckLinkOutput, (void **) &ctx->dlo) != S_OK) {
578 av_log(avctx, AV_LOG_ERROR, "Could not open output device from '%s'\n",
584 /* List supported formats. */
585 if (ctx->list_formats) {
586 ff_decklink_list_formats(avctx);
593 for (n = 0; n < avctx->nb_streams; n++) {
594 AVStream *st = avctx->streams[n];
595 AVCodecParameters *c = st->codecpar;
596 if (c->codec_type == AVMEDIA_TYPE_AUDIO) {
597 if (decklink_setup_audio(avctx, st))
599 } else if (c->codec_type == AVMEDIA_TYPE_VIDEO) {
600 if (decklink_setup_video(avctx, st))
603 av_log(avctx, AV_LOG_ERROR, "Unsupported stream type.\n");
611 ff_decklink_cleanup(avctx);
615 int ff_decklink_write_packet(AVFormatContext *avctx, AVPacket *pkt)
617 struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
618 struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
619 AVStream *st = avctx->streams[pkt->stream_index];
621 ctx->last_pts = FFMAX(ctx->last_pts, pkt->pts);
623 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
624 return decklink_write_video_packet(avctx, pkt);
625 else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
626 return decklink_write_audio_packet(avctx, pkt);
631 int ff_decklink_list_output_devices(AVFormatContext *avctx, struct AVDeviceInfoList *device_list)
633 return ff_decklink_list_devices(avctx, device_list, 0, 1);