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->supports_vanc && ctx->dlo->EnableVideoOutput(ctx->bmd_mode, bmdVideoOutputVANC) != S_OK) {
201 av_log(avctx, AV_LOG_WARNING, "Could not enable video output with VANC! Trying without...\n");
202 ctx->supports_vanc = 0;
204 if (!ctx->supports_vanc && ctx->dlo->EnableVideoOutput(ctx->bmd_mode, bmdVideoOutputFlagDefault) != S_OK) {
205 av_log(avctx, AV_LOG_ERROR, "Could not enable video output!\n");
210 ctx->output_callback = new decklink_output_callback();
211 ctx->dlo->SetScheduledFrameCompletionCallback(ctx->output_callback);
213 ctx->frames_preroll = st->time_base.den * ctx->preroll;
214 if (st->time_base.den > 1000)
215 ctx->frames_preroll /= 1000;
217 /* Buffer twice as many frames as the preroll. */
218 ctx->frames_buffer = ctx->frames_preroll * 2;
219 ctx->frames_buffer = FFMIN(ctx->frames_buffer, 60);
220 pthread_mutex_init(&ctx->mutex, NULL);
221 pthread_cond_init(&ctx->cond, NULL);
222 ctx->frames_buffer_available_spots = ctx->frames_buffer;
224 av_log(avctx, AV_LOG_DEBUG, "output: %s, preroll: %d, frames buffer size: %d\n",
225 avctx->url, ctx->frames_preroll, ctx->frames_buffer);
227 /* The device expects the framerate to be fixed. */
228 avpriv_set_pts_info(st, 64, st->time_base.num, st->time_base.den);
235 static int decklink_setup_audio(AVFormatContext *avctx, AVStream *st)
237 struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
238 struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
239 AVCodecParameters *c = st->codecpar;
242 av_log(avctx, AV_LOG_ERROR, "Only one audio stream is supported!\n");
245 if (c->sample_rate != 48000) {
246 av_log(avctx, AV_LOG_ERROR, "Unsupported sample rate!"
247 " Only 48kHz is supported.\n");
250 if (c->channels != 2 && c->channels != 8 && c->channels != 16) {
251 av_log(avctx, AV_LOG_ERROR, "Unsupported number of channels!"
252 " Only 2, 8 or 16 channels are supported.\n");
255 if (ctx->dlo->EnableAudioOutput(bmdAudioSampleRate48kHz,
256 bmdAudioSampleType16bitInteger,
258 bmdAudioOutputStreamTimestamped) != S_OK) {
259 av_log(avctx, AV_LOG_ERROR, "Could not enable audio output!\n");
262 if (ctx->dlo->BeginAudioPreroll() != S_OK) {
263 av_log(avctx, AV_LOG_ERROR, "Could not begin audio preroll!\n");
267 /* The device expects the sample rate to be fixed. */
268 avpriv_set_pts_info(st, 64, 1, c->sample_rate);
269 ctx->channels = c->channels;
276 av_cold int ff_decklink_write_trailer(AVFormatContext *avctx)
278 struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
279 struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
281 if (ctx->playback_started) {
283 ctx->dlo->StopScheduledPlayback(ctx->last_pts * ctx->bmd_tb_num,
284 &actual, ctx->bmd_tb_den);
285 ctx->dlo->DisableVideoOutput();
287 ctx->dlo->DisableAudioOutput();
290 ff_decklink_cleanup(avctx);
292 if (ctx->output_callback)
293 delete ctx->output_callback;
295 pthread_mutex_destroy(&ctx->mutex);
296 pthread_cond_destroy(&ctx->cond);
299 klvanc_context_destroy(ctx->vanc_ctx);
302 av_freep(&cctx->ctx);
308 static void construct_cc(AVFormatContext *avctx, struct decklink_ctx *ctx,
309 AVPacket *pkt, struct klvanc_line_set_s *vanc_lines)
311 struct klvanc_packet_eia_708b_s *cdp;
317 const uint8_t *data = av_packet_get_side_data(pkt, AV_PKT_DATA_A53_CC, &size);
323 ret = klvanc_create_eia708_cdp(&cdp);
327 ret = klvanc_set_framerate_EIA_708B(cdp, ctx->bmd_tb_num, ctx->bmd_tb_den);
329 av_log(avctx, AV_LOG_ERROR, "Invalid framerate specified: %lld/%lld\n",
330 ctx->bmd_tb_num, ctx->bmd_tb_den);
331 klvanc_destroy_eia708_cdp(cdp);
335 if (cc_count > KLVANC_MAX_CC_COUNT) {
336 av_log(avctx, AV_LOG_ERROR, "Illegal cc_count received: %d\n", cc_count);
337 cc_count = KLVANC_MAX_CC_COUNT;
341 cdp->header.ccdata_present = 1;
342 cdp->header.caption_service_active = 1;
343 cdp->ccdata.cc_count = cc_count;
344 for (i = 0; i < cc_count; i++) {
345 if (data [3*i] & 0x04)
346 cdp->ccdata.cc[i].cc_valid = 1;
347 cdp->ccdata.cc[i].cc_type = data[3*i] & 0x03;
348 cdp->ccdata.cc[i].cc_data[0] = data[3*i+1];
349 cdp->ccdata.cc[i].cc_data[1] = data[3*i+2];
352 klvanc_finalize_EIA_708B(cdp, ctx->cdp_sequence_num++);
353 ret = klvanc_convert_EIA_708B_to_words(cdp, &cdp_words, &len);
354 klvanc_destroy_eia708_cdp(cdp);
356 av_log(avctx, AV_LOG_ERROR, "Failed converting 708 packet to words\n");
360 ret = klvanc_line_insert(ctx->vanc_ctx, vanc_lines, cdp_words, len, 11, 0);
363 av_log(avctx, AV_LOG_ERROR, "VANC line insertion failed\n");
368 static int decklink_construct_vanc(AVFormatContext *avctx, struct decklink_ctx *ctx,
369 AVPacket *pkt, decklink_frame *frame)
371 struct klvanc_line_set_s vanc_lines = { 0 };
374 if (!ctx->supports_vanc)
377 construct_cc(avctx, ctx, pkt, &vanc_lines);
379 IDeckLinkVideoFrameAncillary *vanc;
380 int result = ctx->dlo->CreateAncillaryData(bmdFormat10BitYUV, &vanc);
381 if (result != S_OK) {
382 av_log(avctx, AV_LOG_ERROR, "Failed to create vanc\n");
387 /* Now that we've got all the VANC lines in a nice orderly manner, generate the
388 final VANC sections for the Decklink output */
389 for (i = 0; i < vanc_lines.num_lines; i++) {
390 struct klvanc_line_s *line = vanc_lines.lines[i];
397 /* FIXME: include hack for certain Decklink cards which mis-represent
398 line numbers for pSF frames */
399 real_line = line->line_number;
401 result = vanc->GetBufferForVerticalBlankingLine(real_line, &buf);
402 if (result != S_OK) {
403 av_log(avctx, AV_LOG_ERROR, "Failed to get VANC line %d: %d", real_line, result);
407 /* Generate the full line taking into account all VANC packets on that line */
408 result = klvanc_generate_vanc_line_v210(ctx->vanc_ctx, line, (uint8_t *) buf,
411 av_log(avctx, AV_LOG_ERROR, "Failed to generate VANC line\n");
416 result = frame->SetAncillaryData(vanc);
418 if (result != S_OK) {
419 av_log(avctx, AV_LOG_ERROR, "Failed to set vanc: %d", result);
424 for (i = 0; i < vanc_lines.num_lines; i++)
425 klvanc_line_free(vanc_lines.lines[i]);
431 static int decklink_write_video_packet(AVFormatContext *avctx, AVPacket *pkt)
433 struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
434 struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
435 AVStream *st = avctx->streams[pkt->stream_index];
436 AVFrame *avframe = NULL, *tmp = (AVFrame *)pkt->data;
437 AVPacket *avpacket = NULL;
438 decklink_frame *frame;
439 buffercount_type buffered;
442 if (st->codecpar->codec_id == AV_CODEC_ID_WRAPPED_AVFRAME) {
443 if (tmp->format != AV_PIX_FMT_UYVY422 ||
444 tmp->width != ctx->bmd_width ||
445 tmp->height != ctx->bmd_height) {
446 av_log(avctx, AV_LOG_ERROR, "Got a frame with invalid pixel format or dimension.\n");
447 return AVERROR(EINVAL);
450 avframe = av_frame_clone(tmp);
452 av_log(avctx, AV_LOG_ERROR, "Could not clone video frame.\n");
456 frame = new decklink_frame(ctx, avframe, st->codecpar->codec_id, avframe->height, avframe->width);
458 avpacket = av_packet_clone(pkt);
460 av_log(avctx, AV_LOG_ERROR, "Could not clone video frame.\n");
464 frame = new decklink_frame(ctx, avpacket, st->codecpar->codec_id, ctx->bmd_height, ctx->bmd_width);
467 if (decklink_construct_vanc(avctx, ctx, pkt, frame))
468 av_log(avctx, AV_LOG_ERROR, "Failed to construct VANC\n");
473 av_log(avctx, AV_LOG_ERROR, "Could not create new frame.\n");
474 av_frame_free(&avframe);
475 av_packet_free(&avpacket);
479 /* Always keep at most one second of frames buffered. */
480 pthread_mutex_lock(&ctx->mutex);
481 while (ctx->frames_buffer_available_spots == 0) {
482 pthread_cond_wait(&ctx->cond, &ctx->mutex);
484 ctx->frames_buffer_available_spots--;
485 pthread_mutex_unlock(&ctx->mutex);
487 /* Schedule frame for playback. */
488 hr = ctx->dlo->ScheduleVideoFrame((class IDeckLinkVideoFrame *) frame,
489 pkt->pts * ctx->bmd_tb_num,
490 ctx->bmd_tb_num, ctx->bmd_tb_den);
491 /* Pass ownership to DeckLink, or release on failure */
494 av_log(avctx, AV_LOG_ERROR, "Could not schedule video frame."
495 " error %08x.\n", (uint32_t) hr);
499 ctx->dlo->GetBufferedVideoFrameCount(&buffered);
500 av_log(avctx, AV_LOG_DEBUG, "Buffered video frames: %d.\n", (int) buffered);
501 if (pkt->pts > 2 && buffered <= 2)
502 av_log(avctx, AV_LOG_WARNING, "There are not enough buffered video frames."
503 " Video may misbehave!\n");
505 /* Preroll video frames. */
506 if (!ctx->playback_started && pkt->pts > ctx->frames_preroll) {
507 av_log(avctx, AV_LOG_DEBUG, "Ending audio preroll.\n");
508 if (ctx->audio && ctx->dlo->EndAudioPreroll() != S_OK) {
509 av_log(avctx, AV_LOG_ERROR, "Could not end audio preroll!\n");
512 av_log(avctx, AV_LOG_DEBUG, "Starting scheduled playback.\n");
513 if (ctx->dlo->StartScheduledPlayback(0, ctx->bmd_tb_den, 1.0) != S_OK) {
514 av_log(avctx, AV_LOG_ERROR, "Could not start scheduled playback!\n");
517 ctx->playback_started = 1;
523 static int decklink_write_audio_packet(AVFormatContext *avctx, AVPacket *pkt)
525 struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
526 struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
527 int sample_count = pkt->size / (ctx->channels << 1);
528 buffercount_type buffered;
530 ctx->dlo->GetBufferedAudioSampleFrameCount(&buffered);
531 if (pkt->pts > 1 && !buffered)
532 av_log(avctx, AV_LOG_WARNING, "There's no buffered audio."
533 " Audio will misbehave!\n");
535 if (ctx->dlo->ScheduleAudioSamples(pkt->data, sample_count, pkt->pts,
536 bmdAudioSampleRate48kHz, NULL) != S_OK) {
537 av_log(avctx, AV_LOG_ERROR, "Could not schedule audio samples.\n");
546 av_cold int ff_decklink_write_header(AVFormatContext *avctx)
548 struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
549 struct decklink_ctx *ctx;
553 ctx = (struct decklink_ctx *) av_mallocz(sizeof(struct decklink_ctx));
555 return AVERROR(ENOMEM);
556 ctx->list_devices = cctx->list_devices;
557 ctx->list_formats = cctx->list_formats;
558 ctx->preroll = cctx->preroll;
559 ctx->duplex_mode = cctx->duplex_mode;
562 if (klvanc_context_create(&ctx->vanc_ctx) < 0) {
563 av_log(avctx, AV_LOG_ERROR, "Cannot create VANC library context\n");
564 return AVERROR(ENOMEM);
566 ctx->supports_vanc = 1;
569 /* List available devices and exit. */
570 if (ctx->list_devices) {
571 av_log(avctx, AV_LOG_WARNING, "The -list_devices option is deprecated and will be removed. Please use ffmpeg -sinks decklink instead.\n");
572 ff_decklink_list_devices_legacy(avctx, 0, 1);
576 ret = ff_decklink_init_device(avctx, avctx->url);
580 /* Get output device. */
581 if (ctx->dl->QueryInterface(IID_IDeckLinkOutput, (void **) &ctx->dlo) != S_OK) {
582 av_log(avctx, AV_LOG_ERROR, "Could not open output device from '%s'\n",
588 /* List supported formats. */
589 if (ctx->list_formats) {
590 ff_decklink_list_formats(avctx);
597 for (n = 0; n < avctx->nb_streams; n++) {
598 AVStream *st = avctx->streams[n];
599 AVCodecParameters *c = st->codecpar;
600 if (c->codec_type == AVMEDIA_TYPE_AUDIO) {
601 if (decklink_setup_audio(avctx, st))
603 } else if (c->codec_type == AVMEDIA_TYPE_VIDEO) {
604 if (decklink_setup_video(avctx, st))
607 av_log(avctx, AV_LOG_ERROR, "Unsupported stream type.\n");
615 ff_decklink_cleanup(avctx);
619 int ff_decklink_write_packet(AVFormatContext *avctx, AVPacket *pkt)
621 struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
622 struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
623 AVStream *st = avctx->streams[pkt->stream_index];
625 ctx->last_pts = FFMAX(ctx->last_pts, pkt->pts);
627 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
628 return decklink_write_video_packet(avctx, pkt);
629 else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
630 return decklink_write_audio_packet(avctx, pkt);
635 int ff_decklink_list_output_devices(AVFormatContext *avctx, struct AVDeviceInfoList *device_list)
637 return ff_decklink_list_devices(avctx, device_list, 0, 1);