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/internal.h"
36 #include "libavutil/imgutils.h"
40 #include "decklink_common.h"
41 #include "decklink_enc.h"
43 #include "libklvanc/vanc.h"
44 #include "libklvanc/vanc-lines.h"
45 #include "libklvanc/pixels.h"
48 /* DeckLink callback class declaration */
49 class decklink_frame : public IDeckLinkVideoFrame
52 decklink_frame(struct decklink_ctx *ctx, AVFrame *avframe, AVCodecID codec_id, int height, int width) :
53 _ctx(ctx), _avframe(avframe), _avpacket(NULL), _codec_id(codec_id), _ancillary(NULL), _height(height), _width(width), _refs(1) { }
54 decklink_frame(struct decklink_ctx *ctx, AVPacket *avpacket, AVCodecID codec_id, int height, int width) :
55 _ctx(ctx), _avframe(NULL), _avpacket(avpacket), _codec_id(codec_id), _ancillary(NULL), _height(height), _width(width), _refs(1) { }
56 virtual long STDMETHODCALLTYPE GetWidth (void) { return _width; }
57 virtual long STDMETHODCALLTYPE GetHeight (void) { return _height; }
58 virtual long STDMETHODCALLTYPE GetRowBytes (void)
60 if (_codec_id == AV_CODEC_ID_WRAPPED_AVFRAME)
61 return _avframe->linesize[0] < 0 ? -_avframe->linesize[0] : _avframe->linesize[0];
63 return ((GetWidth() + 47) / 48) * 128;
65 virtual BMDPixelFormat STDMETHODCALLTYPE GetPixelFormat(void)
67 if (_codec_id == AV_CODEC_ID_WRAPPED_AVFRAME)
68 return bmdFormat8BitYUV;
70 return bmdFormat10BitYUV;
72 virtual BMDFrameFlags STDMETHODCALLTYPE GetFlags (void)
74 if (_codec_id == AV_CODEC_ID_WRAPPED_AVFRAME)
75 return _avframe->linesize[0] < 0 ? bmdFrameFlagFlipVertical : bmdFrameFlagDefault;
77 return bmdFrameFlagDefault;
80 virtual HRESULT STDMETHODCALLTYPE GetBytes (void **buffer)
82 if (_codec_id == AV_CODEC_ID_WRAPPED_AVFRAME) {
83 if (_avframe->linesize[0] < 0)
84 *buffer = (void *)(_avframe->data[0] + _avframe->linesize[0] * (_avframe->height - 1));
86 *buffer = (void *)(_avframe->data[0]);
88 *buffer = (void *)(_avpacket->data);
93 virtual HRESULT STDMETHODCALLTYPE GetTimecode (BMDTimecodeFormat format, IDeckLinkTimecode **timecode) { return S_FALSE; }
94 virtual HRESULT STDMETHODCALLTYPE GetAncillaryData(IDeckLinkVideoFrameAncillary **ancillary)
96 *ancillary = _ancillary;
104 virtual HRESULT STDMETHODCALLTYPE SetAncillaryData(IDeckLinkVideoFrameAncillary *ancillary)
107 _ancillary->Release();
108 _ancillary = ancillary;
109 _ancillary->AddRef();
112 virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv) { return E_NOINTERFACE; }
113 virtual ULONG STDMETHODCALLTYPE AddRef(void) { return ++_refs; }
114 virtual ULONG STDMETHODCALLTYPE Release(void)
118 av_frame_free(&_avframe);
119 av_packet_free(&_avpacket);
121 _ancillary->Release();
127 struct decklink_ctx *_ctx;
131 IDeckLinkVideoFrameAncillary *_ancillary;
136 std::atomic<int> _refs;
139 class decklink_output_callback : public IDeckLinkVideoOutputCallback
142 virtual HRESULT STDMETHODCALLTYPE ScheduledFrameCompleted(IDeckLinkVideoFrame *_frame, BMDOutputFrameCompletionResult result)
144 decklink_frame *frame = static_cast<decklink_frame *>(_frame);
145 struct decklink_ctx *ctx = frame->_ctx;
148 av_frame_unref(frame->_avframe);
149 if (frame->_avpacket)
150 av_packet_unref(frame->_avpacket);
152 pthread_mutex_lock(&ctx->mutex);
153 ctx->frames_buffer_available_spots++;
154 pthread_cond_broadcast(&ctx->cond);
155 pthread_mutex_unlock(&ctx->mutex);
159 virtual HRESULT STDMETHODCALLTYPE ScheduledPlaybackHasStopped(void) { return S_OK; }
160 virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv) { return E_NOINTERFACE; }
161 virtual ULONG STDMETHODCALLTYPE AddRef(void) { return 1; }
162 virtual ULONG STDMETHODCALLTYPE Release(void) { return 1; }
165 static int decklink_setup_video(AVFormatContext *avctx, AVStream *st)
167 struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
168 struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
169 AVCodecParameters *c = st->codecpar;
172 av_log(avctx, AV_LOG_ERROR, "Only one video stream is supported!\n");
176 if (c->codec_id == AV_CODEC_ID_WRAPPED_AVFRAME) {
177 if (c->format != AV_PIX_FMT_UYVY422) {
178 av_log(avctx, AV_LOG_ERROR, "Unsupported pixel format!"
179 " Only AV_PIX_FMT_UYVY422 is supported.\n");
182 ctx->raw_format = bmdFormat8BitYUV;
183 } else if (c->codec_id != AV_CODEC_ID_V210) {
184 av_log(avctx, AV_LOG_ERROR, "Unsupported codec type!"
185 " Only V210 and wrapped frame with AV_PIX_FMT_UYVY422 are supported.\n");
188 ctx->raw_format = bmdFormat10BitYUV;
191 if (ff_decklink_set_configs(avctx, DIRECTION_OUT) < 0) {
192 av_log(avctx, AV_LOG_ERROR, "Could not set output configuration\n");
195 if (ff_decklink_set_format(avctx, c->width, c->height,
196 st->time_base.num, st->time_base.den, c->field_order)) {
197 av_log(avctx, AV_LOG_ERROR, "Unsupported video size, framerate or field order!"
198 " Check available formats with -list_formats 1.\n");
201 if (ctx->supports_vanc && ctx->dlo->EnableVideoOutput(ctx->bmd_mode, bmdVideoOutputVANC) != S_OK) {
202 av_log(avctx, AV_LOG_WARNING, "Could not enable video output with VANC! Trying without...\n");
203 ctx->supports_vanc = 0;
205 if (!ctx->supports_vanc && ctx->dlo->EnableVideoOutput(ctx->bmd_mode, bmdVideoOutputFlagDefault) != S_OK) {
206 av_log(avctx, AV_LOG_ERROR, "Could not enable video output!\n");
211 ctx->output_callback = new decklink_output_callback();
212 ctx->dlo->SetScheduledFrameCompletionCallback(ctx->output_callback);
214 ctx->frames_preroll = st->time_base.den * ctx->preroll;
215 if (st->time_base.den > 1000)
216 ctx->frames_preroll /= 1000;
218 /* Buffer twice as many frames as the preroll. */
219 ctx->frames_buffer = ctx->frames_preroll * 2;
220 ctx->frames_buffer = FFMIN(ctx->frames_buffer, 60);
221 pthread_mutex_init(&ctx->mutex, NULL);
222 pthread_cond_init(&ctx->cond, NULL);
223 ctx->frames_buffer_available_spots = ctx->frames_buffer;
225 av_log(avctx, AV_LOG_DEBUG, "output: %s, preroll: %d, frames buffer size: %d\n",
226 avctx->url, ctx->frames_preroll, ctx->frames_buffer);
228 /* The device expects the framerate to be fixed. */
229 avpriv_set_pts_info(st, 64, st->time_base.num, st->time_base.den);
236 static int decklink_setup_audio(AVFormatContext *avctx, AVStream *st)
238 struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
239 struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
240 AVCodecParameters *c = st->codecpar;
243 av_log(avctx, AV_LOG_ERROR, "Only one audio stream is supported!\n");
246 if (c->sample_rate != 48000) {
247 av_log(avctx, AV_LOG_ERROR, "Unsupported sample rate!"
248 " Only 48kHz is supported.\n");
251 if (c->channels != 2 && c->channels != 8 && c->channels != 16) {
252 av_log(avctx, AV_LOG_ERROR, "Unsupported number of channels!"
253 " Only 2, 8 or 16 channels are supported.\n");
256 if (ctx->dlo->EnableAudioOutput(bmdAudioSampleRate48kHz,
257 bmdAudioSampleType16bitInteger,
259 bmdAudioOutputStreamTimestamped) != S_OK) {
260 av_log(avctx, AV_LOG_ERROR, "Could not enable audio output!\n");
263 if (ctx->dlo->BeginAudioPreroll() != S_OK) {
264 av_log(avctx, AV_LOG_ERROR, "Could not begin audio preroll!\n");
268 /* The device expects the sample rate to be fixed. */
269 avpriv_set_pts_info(st, 64, 1, c->sample_rate);
270 ctx->channels = c->channels;
277 av_cold int ff_decklink_write_trailer(AVFormatContext *avctx)
279 struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
280 struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
282 if (ctx->playback_started) {
284 ctx->dlo->StopScheduledPlayback(ctx->last_pts * ctx->bmd_tb_num,
285 &actual, ctx->bmd_tb_den);
286 ctx->dlo->DisableVideoOutput();
288 ctx->dlo->DisableAudioOutput();
291 ff_decklink_cleanup(avctx);
293 if (ctx->output_callback)
294 delete ctx->output_callback;
296 pthread_mutex_destroy(&ctx->mutex);
297 pthread_cond_destroy(&ctx->cond);
300 klvanc_context_destroy(ctx->vanc_ctx);
303 av_freep(&cctx->ctx);
309 static void construct_cc(AVFormatContext *avctx, struct decklink_ctx *ctx,
310 AVPacket *pkt, struct klvanc_line_set_s *vanc_lines)
312 struct klvanc_packet_eia_708b_s *cdp;
319 const uint8_t *data = av_packet_get_side_data(pkt, AV_PKT_DATA_A53_CC, &size);
325 ret = klvanc_create_eia708_cdp(&cdp);
329 ret = klvanc_set_framerate_EIA_708B(cdp, ctx->bmd_tb_num, ctx->bmd_tb_den);
331 av_log(avctx, AV_LOG_ERROR, "Invalid framerate specified: %lld/%lld\n",
332 ctx->bmd_tb_num, ctx->bmd_tb_den);
333 klvanc_destroy_eia708_cdp(cdp);
337 if (cc_count > KLVANC_MAX_CC_COUNT) {
338 av_log(avctx, AV_LOG_ERROR, "Illegal cc_count received: %d\n", cc_count);
339 cc_count = KLVANC_MAX_CC_COUNT;
343 cdp->header.ccdata_present = 1;
344 cdp->header.caption_service_active = 1;
345 cdp->ccdata.cc_count = cc_count;
346 for (i = 0; i < cc_count; i++) {
347 if (data [3*i] & 0x04)
348 cdp->ccdata.cc[i].cc_valid = 1;
349 cdp->ccdata.cc[i].cc_type = data[3*i] & 0x03;
350 cdp->ccdata.cc[i].cc_data[0] = data[3*i+1];
351 cdp->ccdata.cc[i].cc_data[1] = data[3*i+2];
354 klvanc_finalize_EIA_708B(cdp, ctx->cdp_sequence_num++);
355 ret = klvanc_convert_EIA_708B_to_words(cdp, &cdp_words, &len);
356 klvanc_destroy_eia708_cdp(cdp);
358 av_log(avctx, AV_LOG_ERROR, "Failed converting 708 packet to words\n");
362 ret = klvanc_line_insert(ctx->vanc_ctx, vanc_lines, cdp_words, len, 11, 0);
365 av_log(avctx, AV_LOG_ERROR, "VANC line insertion failed\n");
370 static int decklink_construct_vanc(AVFormatContext *avctx, struct decklink_ctx *ctx,
371 AVPacket *pkt, decklink_frame *frame)
373 struct klvanc_line_set_s vanc_lines = { 0 };
376 if (!ctx->supports_vanc)
379 construct_cc(avctx, ctx, pkt, &vanc_lines);
381 IDeckLinkVideoFrameAncillary *vanc;
382 int result = ctx->dlo->CreateAncillaryData(bmdFormat10BitYUV, &vanc);
383 if (result != S_OK) {
384 av_log(avctx, AV_LOG_ERROR, "Failed to create vanc\n");
389 /* Now that we've got all the VANC lines in a nice orderly manner, generate the
390 final VANC sections for the Decklink output */
391 for (i = 0; i < vanc_lines.num_lines; i++) {
392 struct klvanc_line_s *line = vanc_lines.lines[i];
399 /* FIXME: include hack for certain Decklink cards which mis-represent
400 line numbers for pSF frames */
401 real_line = line->line_number;
403 result = vanc->GetBufferForVerticalBlankingLine(real_line, &buf);
404 if (result != S_OK) {
405 av_log(avctx, AV_LOG_ERROR, "Failed to get VANC line %d: %d", real_line, result);
409 /* Generate the full line taking into account all VANC packets on that line */
410 result = klvanc_generate_vanc_line_v210(ctx->vanc_ctx, line, (uint8_t *) buf,
413 av_log(avctx, AV_LOG_ERROR, "Failed to generate VANC line\n");
418 result = frame->SetAncillaryData(vanc);
420 if (result != S_OK) {
421 av_log(avctx, AV_LOG_ERROR, "Failed to set vanc: %d", result);
426 for (i = 0; i < vanc_lines.num_lines; i++)
427 klvanc_line_free(vanc_lines.lines[i]);
433 static int decklink_write_video_packet(AVFormatContext *avctx, AVPacket *pkt)
435 struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
436 struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
437 AVStream *st = avctx->streams[pkt->stream_index];
438 AVFrame *avframe = NULL, *tmp = (AVFrame *)pkt->data;
439 AVPacket *avpacket = NULL;
440 decklink_frame *frame;
444 if (st->codecpar->codec_id == AV_CODEC_ID_WRAPPED_AVFRAME) {
445 if (tmp->format != AV_PIX_FMT_UYVY422 ||
446 tmp->width != ctx->bmd_width ||
447 tmp->height != ctx->bmd_height) {
448 av_log(avctx, AV_LOG_ERROR, "Got a frame with invalid pixel format or dimension.\n");
449 return AVERROR(EINVAL);
452 avframe = av_frame_clone(tmp);
454 av_log(avctx, AV_LOG_ERROR, "Could not clone video frame.\n");
458 frame = new decklink_frame(ctx, avframe, st->codecpar->codec_id, avframe->height, avframe->width);
460 avpacket = av_packet_clone(pkt);
462 av_log(avctx, AV_LOG_ERROR, "Could not clone video frame.\n");
466 frame = new decklink_frame(ctx, avpacket, st->codecpar->codec_id, ctx->bmd_height, ctx->bmd_width);
469 if (decklink_construct_vanc(avctx, ctx, pkt, frame))
470 av_log(avctx, AV_LOG_ERROR, "Failed to construct VANC\n");
475 av_log(avctx, AV_LOG_ERROR, "Could not create new frame.\n");
476 av_frame_free(&avframe);
477 av_packet_free(&avpacket);
481 /* Always keep at most one second of frames buffered. */
482 pthread_mutex_lock(&ctx->mutex);
483 while (ctx->frames_buffer_available_spots == 0) {
484 pthread_cond_wait(&ctx->cond, &ctx->mutex);
486 ctx->frames_buffer_available_spots--;
487 pthread_mutex_unlock(&ctx->mutex);
489 /* Schedule frame for playback. */
490 hr = ctx->dlo->ScheduleVideoFrame((class IDeckLinkVideoFrame *) frame,
491 pkt->pts * ctx->bmd_tb_num,
492 ctx->bmd_tb_num, ctx->bmd_tb_den);
493 /* Pass ownership to DeckLink, or release on failure */
496 av_log(avctx, AV_LOG_ERROR, "Could not schedule video frame."
497 " error %08x.\n", (uint32_t) hr);
501 ctx->dlo->GetBufferedVideoFrameCount(&buffered);
502 av_log(avctx, AV_LOG_DEBUG, "Buffered video frames: %d.\n", (int) buffered);
503 if (pkt->pts > 2 && buffered <= 2)
504 av_log(avctx, AV_LOG_WARNING, "There are not enough buffered video frames."
505 " Video may misbehave!\n");
507 /* Preroll video frames. */
508 if (!ctx->playback_started && pkt->pts > ctx->frames_preroll) {
509 av_log(avctx, AV_LOG_DEBUG, "Ending audio preroll.\n");
510 if (ctx->audio && ctx->dlo->EndAudioPreroll() != S_OK) {
511 av_log(avctx, AV_LOG_ERROR, "Could not end audio preroll!\n");
514 av_log(avctx, AV_LOG_DEBUG, "Starting scheduled playback.\n");
515 if (ctx->dlo->StartScheduledPlayback(0, ctx->bmd_tb_den, 1.0) != S_OK) {
516 av_log(avctx, AV_LOG_ERROR, "Could not start scheduled playback!\n");
519 ctx->playback_started = 1;
525 static int decklink_write_audio_packet(AVFormatContext *avctx, AVPacket *pkt)
527 struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
528 struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
529 int sample_count = pkt->size / (ctx->channels << 1);
532 ctx->dlo->GetBufferedAudioSampleFrameCount(&buffered);
533 if (pkt->pts > 1 && !buffered)
534 av_log(avctx, AV_LOG_WARNING, "There's no buffered audio."
535 " Audio will misbehave!\n");
537 if (ctx->dlo->ScheduleAudioSamples(pkt->data, sample_count, pkt->pts,
538 bmdAudioSampleRate48kHz, NULL) != S_OK) {
539 av_log(avctx, AV_LOG_ERROR, "Could not schedule audio samples.\n");
548 av_cold int ff_decklink_write_header(AVFormatContext *avctx)
550 struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
551 struct decklink_ctx *ctx;
555 ctx = (struct decklink_ctx *) av_mallocz(sizeof(struct decklink_ctx));
557 return AVERROR(ENOMEM);
558 ctx->list_devices = cctx->list_devices;
559 ctx->list_formats = cctx->list_formats;
560 ctx->preroll = cctx->preroll;
561 ctx->duplex_mode = cctx->duplex_mode;
564 if (klvanc_context_create(&ctx->vanc_ctx) < 0) {
565 av_log(avctx, AV_LOG_ERROR, "Cannot create VANC library context\n");
566 return AVERROR(ENOMEM);
568 ctx->supports_vanc = 1;
571 /* List available devices and exit. */
572 if (ctx->list_devices) {
573 ff_decklink_list_devices_legacy(avctx, 0, 1);
577 ret = ff_decklink_init_device(avctx, avctx->url);
581 /* Get output device. */
582 if (ctx->dl->QueryInterface(IID_IDeckLinkOutput, (void **) &ctx->dlo) != S_OK) {
583 av_log(avctx, AV_LOG_ERROR, "Could not open output device from '%s'\n",
589 /* List supported formats. */
590 if (ctx->list_formats) {
591 ff_decklink_list_formats(avctx);
598 for (n = 0; n < avctx->nb_streams; n++) {
599 AVStream *st = avctx->streams[n];
600 AVCodecParameters *c = st->codecpar;
601 if (c->codec_type == AVMEDIA_TYPE_AUDIO) {
602 if (decklink_setup_audio(avctx, st))
604 } else if (c->codec_type == AVMEDIA_TYPE_VIDEO) {
605 if (decklink_setup_video(avctx, st))
608 av_log(avctx, AV_LOG_ERROR, "Unsupported stream type.\n");
616 ff_decklink_cleanup(avctx);
620 int ff_decklink_write_packet(AVFormatContext *avctx, AVPacket *pkt)
622 struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
623 struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
624 AVStream *st = avctx->streams[pkt->stream_index];
626 ctx->last_pts = FFMAX(ctx->last_pts, pkt->pts);
628 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
629 return decklink_write_video_packet(avctx, pkt);
630 else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
631 return decklink_write_audio_packet(avctx, pkt);
636 int ff_decklink_list_output_devices(AVFormatContext *avctx, struct AVDeviceInfoList *device_list)
638 return ff_decklink_list_devices(avctx, device_list, 0, 1);