2 * Blackmagic DeckLink output
3 * Copyright (c) 2013-2014 Luca Barbato, Deti Fliegl
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>
25 #include <semaphore.h>
28 #include "libavformat/avformat.h"
29 #include "libavformat/internal.h"
30 #include "libavutil/imgutils.h"
33 #include "decklink_common.h"
34 #include "decklink_dec.h"
36 static void avpacket_queue_init(AVFormatContext *avctx, AVPacketQueue *q)
38 memset(q, 0, sizeof(AVPacketQueue));
39 pthread_mutex_init(&q->mutex, NULL);
40 pthread_cond_init(&q->cond, NULL);
44 static void avpacket_queue_flush(AVPacketQueue *q)
46 AVPacketList *pkt, *pkt1;
48 pthread_mutex_lock(&q->mutex);
49 for (pkt = q->first_pkt; pkt != NULL; pkt = pkt1) {
51 av_free_packet(&pkt->pkt);
58 pthread_mutex_unlock(&q->mutex);
61 static void avpacket_queue_end(AVPacketQueue *q)
63 avpacket_queue_flush(q);
64 pthread_mutex_destroy(&q->mutex);
65 pthread_cond_destroy(&q->cond);
68 static unsigned long long avpacket_queue_size(AVPacketQueue *q)
70 unsigned long long size;
71 pthread_mutex_lock(&q->mutex);
73 pthread_mutex_unlock(&q->mutex);
77 static int avpacket_queue_put(AVPacketQueue *q, AVPacket *pkt)
81 // Drop Packet if queue size is > 1GB
82 if (avpacket_queue_size(q) > 1024 * 1024 * 1024 ) {
83 av_log(q->avctx, AV_LOG_WARNING, "Decklink input buffer overrun!\n");
86 /* duplicate the packet */
87 if (av_dup_packet(pkt) < 0) {
91 pkt1 = (AVPacketList *)av_malloc(sizeof(AVPacketList));
98 pthread_mutex_lock(&q->mutex);
103 q->last_pkt->next = pkt1;
108 q->size += pkt1->pkt.size + sizeof(*pkt1);
110 pthread_cond_signal(&q->cond);
112 pthread_mutex_unlock(&q->mutex);
116 static int avpacket_queue_get(AVPacketQueue *q, AVPacket *pkt, int block)
121 pthread_mutex_lock(&q->mutex);
126 q->first_pkt = pkt1->next;
131 q->size -= pkt1->pkt.size + sizeof(*pkt1);
140 pthread_cond_wait(&q->cond, &q->mutex);
143 pthread_mutex_unlock(&q->mutex);
147 class decklink_input_callback : public IDeckLinkInputCallback
150 decklink_input_callback(AVFormatContext *_avctx);
151 ~decklink_input_callback();
153 virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv) { return E_NOINTERFACE; }
154 virtual ULONG STDMETHODCALLTYPE AddRef(void);
155 virtual ULONG STDMETHODCALLTYPE Release(void);
156 virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents, IDeckLinkDisplayMode*, BMDDetectedVideoInputFormatFlags);
157 virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame*, IDeckLinkAudioInputPacket*);
161 pthread_mutex_t m_mutex;
162 AVFormatContext *avctx;
165 int64_t initial_video_pts;
166 int64_t initial_audio_pts;
169 decklink_input_callback::decklink_input_callback(AVFormatContext *_avctx) : m_refCount(0)
172 decklink_cctx *cctx = (struct decklink_cctx *) avctx->priv_data;
173 ctx = (struct decklink_ctx *) cctx->ctx;
174 initial_audio_pts = initial_video_pts = AV_NOPTS_VALUE;
175 pthread_mutex_init(&m_mutex, NULL);
178 decklink_input_callback::~decklink_input_callback()
180 pthread_mutex_destroy(&m_mutex);
183 ULONG decklink_input_callback::AddRef(void)
185 pthread_mutex_lock(&m_mutex);
187 pthread_mutex_unlock(&m_mutex);
189 return (ULONG)m_refCount;
192 ULONG decklink_input_callback::Release(void)
194 pthread_mutex_lock(&m_mutex);
196 pthread_mutex_unlock(&m_mutex);
198 if (m_refCount == 0) {
203 return (ULONG)m_refCount;
206 HRESULT decklink_input_callback::VideoInputFrameArrived(
207 IDeckLinkVideoInputFrame *videoFrame, IDeckLinkAudioInputPacket *audioFrame)
210 void *audioFrameBytes;
211 BMDTimeValue frameTime;
212 BMDTimeValue frameDuration;
216 // Handle Video Frame
220 av_init_packet(&pkt);
221 c = ctx->video_st->codec;
222 if (ctx->frameCount % 25 == 0) {
223 unsigned long long qsize = avpacket_queue_size(&ctx->queue);
224 av_log(avctx, AV_LOG_DEBUG,
225 "Frame received (#%lu) - Valid (%liB) - QSize %fMB\n",
227 videoFrame->GetRowBytes() * videoFrame->GetHeight(),
228 (double)qsize / 1024 / 1024);
231 videoFrame->GetBytes(&frameBytes);
232 videoFrame->GetStreamTime(&frameTime, &frameDuration,
233 ctx->video_st->time_base.den);
235 if (videoFrame->GetFlags() & bmdFrameHasNoInputSource) {
236 if (videoFrame->GetPixelFormat() == bmdFormat8BitYUV) {
238 0xEA80EA80, 0xD292D210, 0xA910A9A5, 0x90229035,
239 0x6ADD6ACA, 0x51EF515A, 0x286D28EF, 0x10801080 };
240 int width = videoFrame->GetWidth();
241 int height = videoFrame->GetHeight();
242 unsigned *p = (unsigned *)frameBytes;
244 for (int y = 0; y < height; y++) {
245 for (int x = 0; x < width; x += 2)
246 *p++ = bars[(x * 8) / width];
251 av_log(avctx, AV_LOG_WARNING, "Frame received (#%lu) - No input signal detected "
252 "- Frames dropped %u\n", ctx->frameCount, ++ctx->dropped);
257 av_log(avctx, AV_LOG_WARNING, "Frame received (#%lu) - Input returned "
258 "- Frames dropped %u\n", ctx->frameCount, ++ctx->dropped);
263 pkt.pts = frameTime / ctx->video_st->time_base.num;
265 if (initial_video_pts == AV_NOPTS_VALUE) {
266 initial_video_pts = pkt.pts;
269 pkt.pts -= initial_video_pts;
272 pkt.duration = frameDuration;
273 //To be made sure it still applies
274 pkt.flags |= AV_PKT_FLAG_KEY;
275 pkt.stream_index = ctx->video_st->index;
276 pkt.data = (uint8_t *)frameBytes;
277 pkt.size = videoFrame->GetRowBytes() *
278 videoFrame->GetHeight();
279 //fprintf(stderr,"Video Frame size %d ts %d\n", pkt.size, pkt.pts);
281 if (avpacket_queue_put(&ctx->queue, &pkt) < 0) {
286 // Handle Audio Frame
290 BMDTimeValue audio_pts;
291 av_init_packet(&pkt);
293 c = ctx->audio_st->codec;
295 pkt.size = audioFrame->GetSampleFrameCount() * ctx->audio_st->codec->channels * (16 / 8);
296 audioFrame->GetBytes(&audioFrameBytes);
297 audioFrame->GetPacketTime(&audio_pts, ctx->audio_st->time_base.den);
298 pkt.pts = audio_pts / ctx->audio_st->time_base.num;
300 if (initial_audio_pts == AV_NOPTS_VALUE) {
301 initial_audio_pts = pkt.pts;
304 pkt.pts -= initial_audio_pts;
307 //fprintf(stderr,"Audio Frame size %d ts %d\n", pkt.size, pkt.pts);
308 pkt.flags |= AV_PKT_FLAG_KEY;
309 pkt.stream_index = ctx->audio_st->index;
310 pkt.data = (uint8_t *)audioFrameBytes;
313 if (avpacket_queue_put(&ctx->queue, &pkt) < 0) {
321 HRESULT decklink_input_callback::VideoInputFormatChanged(
322 BMDVideoInputFormatChangedEvents events, IDeckLinkDisplayMode *mode,
323 BMDDetectedVideoInputFormatFlags)
328 static HRESULT decklink_start_input(AVFormatContext *avctx)
330 struct decklink_cctx *cctx = (struct decklink_cctx *) avctx->priv_data;
331 struct decklink_ctx *ctx = (struct decklink_ctx *) cctx->ctx;
333 ctx->input_callback = new decklink_input_callback(avctx);
334 ctx->dli->SetCallback(ctx->input_callback);
335 return ctx->dli->StartStreams();
340 av_cold int ff_decklink_read_close(AVFormatContext *avctx)
342 struct decklink_cctx *cctx = (struct decklink_cctx *) avctx->priv_data;
343 struct decklink_ctx *ctx = (struct decklink_ctx *) cctx->ctx;
345 if (ctx->capture_started) {
346 ctx->dli->StopStreams();
347 ctx->dli->DisableVideoInput();
348 ctx->dli->DisableAudioInput();
356 avpacket_queue_end(&ctx->queue);
358 av_freep(&cctx->ctx);
363 av_cold int ff_decklink_read_header(AVFormatContext *avctx)
365 struct decklink_cctx *cctx = (struct decklink_cctx *) avctx->priv_data;
366 struct decklink_ctx *ctx;
367 IDeckLinkDisplayModeIterator *itermode;
368 IDeckLinkIterator *iter;
369 IDeckLink *dl = NULL;
376 ctx = (struct decklink_ctx *) av_mallocz(sizeof(struct decklink_ctx));
378 return AVERROR(ENOMEM);
379 ctx->list_devices = cctx->list_devices;
380 ctx->list_formats = cctx->list_formats;
381 ctx->preroll = cctx->preroll;
384 iter = CreateDeckLinkIteratorInstance();
386 av_log(avctx, AV_LOG_ERROR, "Could not create DeckLink iterator\n");
390 /* List available devices. */
391 if (ctx->list_devices) {
392 ff_decklink_list_devices(avctx);
396 strcpy (fname, avctx->filename);
397 tmp=strchr (fname, '@');
399 mode_num = atoi (tmp+1);
404 while (iter->Next(&dl) == S_OK) {
405 const char *displayName;
406 ff_decklink_get_display_name(dl, &displayName);
407 if (!strcmp(fname, displayName)) {
408 av_free((void *) displayName);
412 av_free((void *) displayName);
417 av_log(avctx, AV_LOG_ERROR, "Could not open '%s'\n", fname);
421 /* Get input device. */
422 if (ctx->dl->QueryInterface(IID_IDeckLinkInput, (void **) &ctx->dli) != S_OK) {
423 av_log(avctx, AV_LOG_ERROR, "Could not open output device from '%s'\n",
429 /* List supported formats. */
430 if (ctx->list_formats) {
431 ff_decklink_list_formats(avctx, DIRECTION_IN);
437 if (ctx->dli->GetDisplayModeIterator(&itermode) != S_OK) {
438 av_log(avctx, AV_LOG_ERROR, "Could not get Display Mode Iterator\n");
444 if (ff_decklink_set_format(avctx, DIRECTION_IN, mode_num) < 0) {
445 av_log(avctx, AV_LOG_ERROR, "Could not set mode %d for %s\n", mode_num, fname);
453 st = avformat_new_stream(avctx, NULL);
455 av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
458 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
459 st->codec->codec_id = AV_CODEC_ID_PCM_S16LE;
460 st->codec->sample_rate = bmdAudioSampleRate48kHz;
461 st->codec->channels = 2;
462 avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
465 st = avformat_new_stream(avctx, NULL);
467 av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
470 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
471 st->codec->width = ctx->bmd_width;
472 st->codec->height = ctx->bmd_height;
474 st->codec->time_base.den = ctx->bmd_tb_den;
475 st->codec->time_base.num = ctx->bmd_tb_num;
476 st->codec->bit_rate = avpicture_get_size(st->codec->pix_fmt, ctx->bmd_width, ctx->bmd_height) * 1/av_q2d(st->codec->time_base) * 8;
479 st->codec->codec_id = AV_CODEC_ID_V210;
480 st->codec->codec_tag = MKTAG('V', '2', '1', '0');
482 st->codec->codec_id = AV_CODEC_ID_RAWVIDEO;
483 st->codec->pix_fmt = AV_PIX_FMT_UYVY422;
484 st->codec->codec_tag = MKTAG('U', 'Y', 'V', 'Y');
487 avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
491 result = ctx->dli->EnableAudioInput(bmdAudioSampleRate48kHz, bmdAudioSampleType16bitInteger, 2);
493 if (result != S_OK) {
494 av_log(avctx, AV_LOG_ERROR, "Cannot enable audio input\n");
498 result = ctx->dli->EnableVideoInput(ctx->bmd_mode,
499 cctx->v210 ? bmdFormat10BitYUV : bmdFormat8BitYUV,
500 bmdVideoInputFlagDefault);
502 if (result != S_OK) {
503 av_log(avctx, AV_LOG_ERROR, "Cannot enable video input\n");
507 avpacket_queue_init (avctx, &ctx->queue);
509 if (decklink_start_input (avctx) != S_OK) {
510 av_log(avctx, AV_LOG_ERROR, "Cannot start input stream\n");
524 int ff_decklink_read_packet(AVFormatContext *avctx, AVPacket *pkt)
526 struct decklink_cctx *cctx = (struct decklink_cctx *) avctx->priv_data;
527 struct decklink_ctx *ctx = (struct decklink_ctx *) cctx->ctx;
528 AVFrame *frame = ctx->video_st->codec->coded_frame;
530 avpacket_queue_get(&ctx->queue, pkt, 1);
531 if (frame && (ctx->bmd_field_dominance == bmdUpperFieldFirst || ctx->bmd_field_dominance == bmdLowerFieldFirst)) {
532 frame->interlaced_frame = 1;
533 if (ctx->bmd_field_dominance == bmdUpperFieldFirst) {
534 frame->top_field_first = 1;