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
22 #include <DeckLinkAPI.h>
24 #include <DeckLinkAPI_i.c>
25 typedef unsigned long buffercount_type
;
27 #include <DeckLinkAPIDispatch.cpp>
28 typedef uint32_t buffercount_type
;
32 #include <semaphore.h>
35 #include "libavformat/avformat.h"
36 #include "libavformat/internal.h"
37 #include "libavutil/imgutils.h"
40 #include "decklink_enc.h"
42 class decklink_callback
;
45 /* DeckLink SDK interfaces */
48 decklink_callback
*callback
;
50 /* DeckLink mode information */
51 IDeckLinkDisplayModeIterator
*itermode
;
52 BMDTimeValue bmd_tb_den
;
53 BMDTimeValue bmd_tb_num
;
54 BMDDisplayMode bmd_mode
;
79 /* DeckLink callback class declaration */
80 class decklink_frame
: public IDeckLinkVideoFrame
83 decklink_frame(struct decklink_ctx
*ctx
, AVFrame
*avframe
, long width
,
84 long height
, void *buffer
) :
85 _ctx(ctx
), _avframe(avframe
), _width(width
),
86 _height(height
), _buffer(buffer
), _refs(0) { }
88 virtual long STDMETHODCALLTYPE
GetWidth (void) { return _width
; }
89 virtual long STDMETHODCALLTYPE
GetHeight (void) { return _height
; }
90 virtual long STDMETHODCALLTYPE
GetRowBytes (void) { return _width
<<1; }
91 virtual BMDPixelFormat STDMETHODCALLTYPE
GetPixelFormat(void) { return bmdFormat8BitYUV
; }
92 virtual BMDFrameFlags STDMETHODCALLTYPE
GetFlags (void) { return bmdVideoOutputFlagDefault
; }
93 virtual HRESULT STDMETHODCALLTYPE
GetBytes (void **buffer
) { *buffer
= _buffer
; return S_OK
; }
95 virtual HRESULT STDMETHODCALLTYPE
GetTimecode (BMDTimecodeFormat format
, IDeckLinkTimecode
**timecode
) { return S_FALSE
; }
96 virtual HRESULT STDMETHODCALLTYPE
GetAncillaryData(IDeckLinkVideoFrameAncillary
**ancillary
) { return S_FALSE
; }
98 virtual HRESULT STDMETHODCALLTYPE
QueryInterface(REFIID iid
, LPVOID
*ppv
) { return E_NOINTERFACE
; }
99 virtual ULONG STDMETHODCALLTYPE
AddRef(void) { return ++_refs
; }
100 virtual ULONG STDMETHODCALLTYPE
Release(void) { if (!--_refs
) delete this; return _refs
; }
102 struct decklink_ctx
*_ctx
;
112 class decklink_callback
: public IDeckLinkVideoOutputCallback
115 virtual HRESULT STDMETHODCALLTYPE
ScheduledFrameCompleted(IDeckLinkVideoFrame
*_frame
, BMDOutputFrameCompletionResult result
)
117 decklink_frame
*frame
= static_cast<decklink_frame
*>(_frame
);
118 struct decklink_ctx
*ctx
= frame
->_ctx
;
119 AVFrame
*avframe
= frame
->_avframe
;
121 av_frame_free(&avframe
);
123 sem_post(&ctx
->semaphore
);
127 virtual HRESULT STDMETHODCALLTYPE
ScheduledPlaybackHasStopped(void) { return S_OK
; }
128 virtual HRESULT STDMETHODCALLTYPE
QueryInterface(REFIID iid
, LPVOID
*ppv
) { return E_NOINTERFACE
; }
129 virtual ULONG STDMETHODCALLTYPE
AddRef(void) { return 1; }
130 virtual ULONG STDMETHODCALLTYPE
Release(void) { return 1; }
134 static IDeckLinkIterator
*CreateDeckLinkIteratorInstance(void)
136 IDeckLinkIterator
*iter
;
138 if (CoInitialize(NULL
) != S_OK
) {
139 av_log(NULL
, AV_LOG_ERROR
, "COM initialization failed.\n");
143 if (CoCreateInstance(CLSID_CDeckLinkIterator
, NULL
, CLSCTX_ALL
,
144 IID_IDeckLinkIterator
, (void**) &iter
) != S_OK
) {
145 av_log(NULL
, AV_LOG_ERROR
, "DeckLink drivers not installed.\n");
153 /* free() is needed for a string returned by the DeckLink SDL. */
157 static char *dup_wchar_to_utf8(wchar_t *w
)
160 int l
= WideCharToMultiByte(CP_UTF8
, 0, w
, -1, 0, 0, 0, 0);
161 s
= (char *) av_malloc(l
);
163 WideCharToMultiByte(CP_UTF8
, 0, w
, -1, s
, l
, 0, 0);
166 #define DECKLINK_STR OLECHAR *
167 #define DECKLINK_STRDUP dup_wchar_to_utf8
169 #define DECKLINK_STR const char *
170 #define DECKLINK_STRDUP av_strdup
173 static HRESULT
IDeckLink_GetDisplayName(IDeckLink
*This
, const char **displayName
)
175 DECKLINK_STR tmpDisplayName
;
176 HRESULT hr
= This
->GetDisplayName(&tmpDisplayName
);
179 *displayName
= DECKLINK_STRDUP(tmpDisplayName
);
180 free((void *) tmpDisplayName
);
184 static int decklink_set_format(struct decklink_ctx
*ctx
,
185 int width
, int height
,
186 int tb_num
, int tb_den
)
188 BMDDisplayModeSupport support
;
189 IDeckLinkDisplayMode
*mode
;
195 ctx
->bmd_mode
= bmdModeUnknown
;
196 while ((ctx
->bmd_mode
== bmdModeUnknown
) && ctx
->itermode
->Next(&mode
) == S_OK
) {
197 BMDTimeValue bmd_tb_num
, bmd_tb_den
;
198 int bmd_width
= mode
->GetWidth();
199 int bmd_height
= mode
->GetHeight();
201 mode
->GetFrameRate(&bmd_tb_num
, &bmd_tb_den
);
203 if (bmd_width
== width
&& bmd_height
== height
&&
204 bmd_tb_num
== tb_num
&& bmd_tb_den
== tb_den
) {
205 ctx
->bmd_mode
= mode
->GetDisplayMode();
206 ctx
->bmd_width
= bmd_width
;
207 ctx
->bmd_height
= bmd_height
;
208 ctx
->bmd_tb_den
= bmd_tb_den
;
209 ctx
->bmd_tb_num
= bmd_tb_num
;
214 if (ctx
->bmd_mode
== bmdModeUnknown
)
216 if (ctx
->dlo
->DoesSupportVideoMode(ctx
->bmd_mode
, bmdFormat8BitYUV
,
217 bmdVideoOutputFlagDefault
,
218 &support
, NULL
) != S_OK
)
220 if (support
== bmdDisplayModeSupported
)
226 static int decklink_setup_video(AVFormatContext
*avctx
, AVStream
*st
)
228 struct decklink_cctx
*cctx
= (struct decklink_cctx
*) avctx
->priv_data
;
229 struct decklink_ctx
*ctx
= (struct decklink_ctx
*) cctx
->ctx
;
230 AVCodecContext
*c
= st
->codec
;
233 av_log(avctx
, AV_LOG_ERROR
, "Only one video stream is supported!\n");
237 if (c
->pix_fmt
!= AV_PIX_FMT_UYVY422
) {
238 av_log(avctx
, AV_LOG_ERROR
, "Unsupported pixel format!"
239 " Only AV_PIX_FMT_UYVY422 is supported.\n");
242 if (decklink_set_format(ctx
, c
->width
, c
->height
,
243 c
->time_base
.num
, c
->time_base
.den
)) {
244 av_log(avctx
, AV_LOG_ERROR
, "Unsupported video size or framerate!"
245 " Check available formats with -list_formats 1.\n");
248 if (ctx
->dlo
->EnableVideoOutput(ctx
->bmd_mode
,
249 bmdVideoOutputFlagDefault
) != S_OK
) {
250 av_log(avctx
, AV_LOG_ERROR
, "Could not enable video output!\n");
255 ctx
->callback
= new decklink_callback();
256 ctx
->dlo
->SetScheduledFrameCompletionCallback(ctx
->callback
);
258 /* Start video semaphore. */
259 ctx
->frames_preroll
= c
->time_base
.den
* ctx
->preroll
;
260 if (c
->time_base
.den
> 1000)
261 ctx
->frames_preroll
/= 1000;
263 /* Buffer twice as many frames as the preroll. */
264 ctx
->frames_buffer
= ctx
->frames_preroll
* 2;
265 ctx
->frames_buffer
= FFMIN(ctx
->frames_buffer
, 60);
266 sem_init(&ctx
->semaphore
, 0, ctx
->frames_buffer
);
268 /* The device expects the framerate to be fixed. */
269 avpriv_set_pts_info(st
, 64, c
->time_base
.num
, c
->time_base
.den
);
276 static int decklink_setup_audio(AVFormatContext
*avctx
, AVStream
*st
)
278 struct decklink_cctx
*cctx
= (struct decklink_cctx
*) avctx
->priv_data
;
279 struct decklink_ctx
*ctx
= (struct decklink_ctx
*) cctx
->ctx
;
280 AVCodecContext
*c
= st
->codec
;
283 av_log(avctx
, AV_LOG_ERROR
, "Only one audio stream is supported!\n");
286 if (c
->sample_rate
!= 48000) {
287 av_log(avctx
, AV_LOG_ERROR
, "Unsupported sample rate!"
288 " Only 48kHz is supported.\n");
291 if (c
->channels
!= 2 && c
->channels
!= 8) {
292 av_log(avctx
, AV_LOG_ERROR
, "Unsupported number of channels!"
293 " Only stereo and 7.1 are supported.\n");
296 if (ctx
->dlo
->EnableAudioOutput(bmdAudioSampleRate48kHz
,
297 bmdAudioSampleType16bitInteger
,
299 bmdAudioOutputStreamTimestamped
) != S_OK
) {
300 av_log(avctx
, AV_LOG_ERROR
, "Could not enable audio output!\n");
303 if (ctx
->dlo
->BeginAudioPreroll() != S_OK
) {
304 av_log(avctx
, AV_LOG_ERROR
, "Could not begin audio preroll!\n");
308 /* The device expects the sample rate to be fixed. */
309 avpriv_set_pts_info(st
, 64, 1, c
->sample_rate
);
310 ctx
->channels
= c
->channels
;
317 av_cold
int ff_decklink_write_trailer(AVFormatContext
*avctx
)
319 struct decklink_cctx
*cctx
= (struct decklink_cctx
*) avctx
->priv_data
;
320 struct decklink_ctx
*ctx
= (struct decklink_ctx
*) cctx
->ctx
;
322 if (ctx
->playback_started
) {
324 ctx
->dlo
->StopScheduledPlayback(ctx
->last_pts
* ctx
->bmd_tb_num
,
325 &actual
, ctx
->bmd_tb_den
);
326 ctx
->dlo
->DisableVideoOutput();
328 ctx
->dlo
->DisableAudioOutput();
337 delete ctx
->callback
;
339 sem_destroy(&ctx
->semaphore
);
341 av_freep(&cctx
->ctx
);
346 static int decklink_write_video_packet(AVFormatContext
*avctx
, AVPacket
*pkt
)
348 struct decklink_cctx
*cctx
= (struct decklink_cctx
*) avctx
->priv_data
;
349 struct decklink_ctx
*ctx
= (struct decklink_ctx
*) cctx
->ctx
;
350 AVPicture
*avpicture
= (AVPicture
*) pkt
->data
;
351 AVFrame
*avframe
, *tmp
;
352 decklink_frame
*frame
;
353 buffercount_type buffered
;
356 /* HACK while av_uncoded_frame() isn't implemented */
359 tmp
= av_frame_alloc();
361 return AVERROR(ENOMEM
);
362 tmp
->format
= AV_PIX_FMT_UYVY422
;
363 tmp
->width
= ctx
->bmd_width
;
364 tmp
->height
= ctx
->bmd_height
;
365 ret
= av_frame_get_buffer(tmp
, 32);
370 av_image_copy(tmp
->data
, tmp
->linesize
, (const uint8_t **) avpicture
->data
,
371 avpicture
->linesize
, (AVPixelFormat
) tmp
->format
, tmp
->width
,
373 avframe
= av_frame_clone(tmp
);
376 av_log(avctx
, AV_LOG_ERROR
, "Could not clone video frame.\n");
381 frame
= new decklink_frame(ctx
, avframe
, ctx
->bmd_width
, ctx
->bmd_height
,
382 (void *) avframe
->data
[0]);
384 av_log(avctx
, AV_LOG_ERROR
, "Could not create new frame.\n");
388 /* Always keep at most one second of frames buffered. */
389 sem_wait(&ctx
->semaphore
);
391 /* Schedule frame for playback. */
392 hr
= ctx
->dlo
->ScheduleVideoFrame((struct IDeckLinkVideoFrame
*) frame
,
393 pkt
->pts
* ctx
->bmd_tb_num
,
394 ctx
->bmd_tb_num
, ctx
->bmd_tb_den
);
396 av_log(avctx
, AV_LOG_ERROR
, "Could not schedule video frame."
397 " error %08x.\n", (uint32_t) hr
);
402 ctx
->dlo
->GetBufferedVideoFrameCount(&buffered
);
403 av_log(avctx
, AV_LOG_DEBUG
, "Buffered video frames: %d.\n", (int) buffered
);
404 if (pkt
->pts
> 2 && buffered
<= 2)
405 av_log(avctx
, AV_LOG_WARNING
, "There are not enough buffered video frames."
406 " Video may misbehave!\n");
408 /* Preroll video frames. */
409 if (!ctx
->playback_started
&& pkt
->pts
> ctx
->frames_preroll
) {
410 av_log(avctx
, AV_LOG_DEBUG
, "Ending audio preroll.\n");
411 if (ctx
->audio
&& ctx
->dlo
->EndAudioPreroll() != S_OK
) {
412 av_log(avctx
, AV_LOG_ERROR
, "Could not end audio preroll!\n");
415 av_log(avctx
, AV_LOG_DEBUG
, "Starting scheduled playback.\n");
416 if (ctx
->dlo
->StartScheduledPlayback(0, ctx
->bmd_tb_den
, 1.0) != S_OK
) {
417 av_log(avctx
, AV_LOG_ERROR
, "Could not start scheduled playback!\n");
420 ctx
->playback_started
= 1;
426 static int decklink_write_audio_packet(AVFormatContext
*avctx
, AVPacket
*pkt
)
428 struct decklink_cctx
*cctx
= (struct decklink_cctx
*) avctx
->priv_data
;
429 struct decklink_ctx
*ctx
= (struct decklink_ctx
*) cctx
->ctx
;
430 int sample_count
= pkt
->size
/ (ctx
->channels
<< 1);
431 buffercount_type buffered
;
433 ctx
->dlo
->GetBufferedAudioSampleFrameCount(&buffered
);
434 if (pkt
->pts
> 1 && !buffered
)
435 av_log(avctx
, AV_LOG_WARNING
, "There's no buffered audio."
436 " Audio will misbehave!\n");
438 if (ctx
->dlo
->ScheduleAudioSamples(pkt
->data
, sample_count
, pkt
->pts
,
439 bmdAudioSampleRate48kHz
, NULL
) != S_OK
) {
440 av_log(avctx
, AV_LOG_ERROR
, "Could not schedule audio samples.\n");
449 av_cold
int ff_decklink_write_header(AVFormatContext
*avctx
)
451 struct decklink_cctx
*cctx
= (struct decklink_cctx
*) avctx
->priv_data
;
452 struct decklink_ctx
*ctx
;
453 IDeckLinkIterator
*iter
;
454 IDeckLink
*dl
= NULL
;
457 ctx
= (struct decklink_ctx
*) av_mallocz(sizeof(struct decklink_ctx
));
459 return AVERROR(ENOMEM
);
460 ctx
->list_devices
= cctx
->list_devices
;
461 ctx
->list_formats
= cctx
->list_formats
;
462 ctx
->preroll
= cctx
->preroll
;
465 iter
= CreateDeckLinkIteratorInstance();
467 av_log(avctx
, AV_LOG_ERROR
, "Could not create DeckLink iterator\n");
471 /* List available devices. */
472 if (ctx
->list_devices
) {
473 av_log(avctx
, AV_LOG_INFO
, "Blackmagic DeckLink devices:\n");
474 while (iter
->Next(&dl
) == S_OK
) {
475 const char *displayName
;
476 IDeckLink_GetDisplayName(dl
, &displayName
);
477 av_log(avctx
, AV_LOG_INFO
, "\t'%s'\n", displayName
);
478 av_free((void *) displayName
);
486 while (iter
->Next(&dl
) == S_OK
) {
487 const char *displayName
;
488 IDeckLink_GetDisplayName(dl
, &displayName
);
489 if (!strcmp(avctx
->filename
, displayName
)) {
490 av_free((void *) displayName
);
494 av_free((void *) displayName
);
499 av_log(avctx
, AV_LOG_ERROR
, "Could not open '%s'\n", avctx
->filename
);
503 /* Get output device. */
504 if (ctx
->dl
->QueryInterface(IID_IDeckLinkOutput
, (void **) &ctx
->dlo
) != S_OK
) {
505 av_log(avctx
, AV_LOG_ERROR
, "Could not open output device from '%s'\n",
511 if (ctx
->dlo
->GetDisplayModeIterator(&ctx
->itermode
) != S_OK
) {
512 av_log(avctx
, AV_LOG_ERROR
, "Could not get Display Mode Iterator\n");
517 /* List supported formats. */
518 if (ctx
->list_formats
) {
519 IDeckLinkDisplayMode
*mode
;
521 av_log(avctx
, AV_LOG_INFO
, "Supported formats for '%s':\n",
523 while (ctx
->itermode
->Next(&mode
) == S_OK
) {
524 BMDTimeValue tb_num
, tb_den
;
525 mode
->GetFrameRate(&tb_num
, &tb_den
);
526 av_log(avctx
, AV_LOG_INFO
, "\t%ldx%ld at %d/%d fps",
527 mode
->GetWidth(), mode
->GetHeight(),
528 (int) tb_den
, (int) tb_num
);
529 switch (mode
->GetFieldDominance()) {
530 case bmdLowerFieldFirst
:
531 av_log(avctx
, AV_LOG_INFO
, " (interlaced, lower field first)"); break;
532 case bmdUpperFieldFirst
:
533 av_log(avctx
, AV_LOG_INFO
, " (interlaced, upper field first)"); break;
535 av_log(avctx
, AV_LOG_INFO
, "\n");
539 ctx
->itermode
->Release();
546 for (n
= 0; n
< avctx
->nb_streams
; n
++) {
547 AVStream
*st
= avctx
->streams
[n
];
548 AVCodecContext
*c
= st
->codec
;
549 if (c
->codec_type
== AVMEDIA_TYPE_AUDIO
) {
550 if (decklink_setup_audio(avctx
, st
))
552 } else if (c
->codec_type
== AVMEDIA_TYPE_VIDEO
) {
553 if (decklink_setup_video(avctx
, st
))
556 av_log(avctx
, AV_LOG_ERROR
, "Unsupported stream type.\n");
560 ctx
->itermode
->Release();
572 int ff_decklink_write_packet(AVFormatContext
*avctx
, AVPacket
*pkt
)
574 struct decklink_cctx
*cctx
= (struct decklink_cctx
*) avctx
->priv_data
;
575 struct decklink_ctx
*ctx
= (struct decklink_ctx
*) cctx
->ctx
;
576 AVStream
*st
= avctx
->streams
[pkt
->stream_index
];
578 ctx
->last_pts
= FFMAX(ctx
->last_pts
, pkt
->pts
);
580 if (st
->codec
->codec_type
== AVMEDIA_TYPE_VIDEO
)
581 return decklink_write_video_packet(avctx
, pkt
);
582 else if (st
->codec
->codec_type
== AVMEDIA_TYPE_AUDIO
)
583 return decklink_write_audio_packet(avctx
, pkt
);