2 * Blackmagic DeckLink input
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 internal.h first to avoid conflict between winsock.h (used by
23 * DeckLink headers) and winsock2.h (used by libavformat) in MSVC++ builds */
25 #include "libavformat/internal.h"
28 #include <DeckLinkAPI.h>
32 #include "libavformat/avformat.h"
33 #include "libavutil/avutil.h"
34 #include "libavutil/common.h"
35 #include "libavutil/imgutils.h"
36 #include "libavutil/time.h"
37 #include "libavutil/mathematics.h"
43 #include "decklink_common.h"
44 #include "decklink_dec.h"
47 static uint8_t calc_parity_and_line_offset(int line)
49 uint8_t ret = (line < 313) << 5;
50 if (line >= 7 && line <= 22)
52 if (line >= 320 && line <= 335)
57 int teletext_data_unit_from_vbi_data(int line, uint8_t *src, uint8_t *tgt)
59 vbi_bit_slicer slicer;
61 vbi_bit_slicer_init(&slicer, 720, 13500000, 6937500, 6937500, 0x00aaaae4, 0xffff, 18, 6, 42 * 8, VBI_MODULATION_NRZ_MSB, VBI_PIXFMT_UYVY);
63 if (vbi_bit_slice(&slicer, src, tgt + 4) == FALSE)
66 tgt[0] = 0x02; // data_unit_id
67 tgt[1] = 0x2c; // data_unit_length
68 tgt[2] = calc_parity_and_line_offset(line); // field_parity, line_offset
69 tgt[3] = 0xe4; // framing code
75 static void avpacket_queue_init(AVFormatContext *avctx, AVPacketQueue *q)
77 memset(q, 0, sizeof(AVPacketQueue));
78 pthread_mutex_init(&q->mutex, NULL);
79 pthread_cond_init(&q->cond, NULL);
83 static void avpacket_queue_flush(AVPacketQueue *q)
85 AVPacketList *pkt, *pkt1;
87 pthread_mutex_lock(&q->mutex);
88 for (pkt = q->first_pkt; pkt != NULL; pkt = pkt1) {
90 av_packet_unref(&pkt->pkt);
97 pthread_mutex_unlock(&q->mutex);
100 static void avpacket_queue_end(AVPacketQueue *q)
102 avpacket_queue_flush(q);
103 pthread_mutex_destroy(&q->mutex);
104 pthread_cond_destroy(&q->cond);
107 static unsigned long long avpacket_queue_size(AVPacketQueue *q)
109 unsigned long long size;
110 pthread_mutex_lock(&q->mutex);
112 pthread_mutex_unlock(&q->mutex);
116 static int avpacket_queue_put(AVPacketQueue *q, AVPacket *pkt)
120 // Drop Packet if queue size is > 1GB
121 if (avpacket_queue_size(q) > 1024 * 1024 * 1024 ) {
122 av_log(q->avctx, AV_LOG_WARNING, "Decklink input buffer overrun!\n");
125 /* duplicate the packet */
126 if (av_dup_packet(pkt) < 0) {
130 pkt1 = (AVPacketList *)av_malloc(sizeof(AVPacketList));
137 pthread_mutex_lock(&q->mutex);
142 q->last_pkt->next = pkt1;
147 q->size += pkt1->pkt.size + sizeof(*pkt1);
149 pthread_cond_signal(&q->cond);
151 pthread_mutex_unlock(&q->mutex);
155 static int avpacket_queue_get(AVPacketQueue *q, AVPacket *pkt, int block)
160 pthread_mutex_lock(&q->mutex);
165 q->first_pkt = pkt1->next;
170 q->size -= pkt1->pkt.size + sizeof(*pkt1);
179 pthread_cond_wait(&q->cond, &q->mutex);
182 pthread_mutex_unlock(&q->mutex);
186 class decklink_input_callback : public IDeckLinkInputCallback
189 decklink_input_callback(AVFormatContext *_avctx);
190 ~decklink_input_callback();
192 virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv) { return E_NOINTERFACE; }
193 virtual ULONG STDMETHODCALLTYPE AddRef(void);
194 virtual ULONG STDMETHODCALLTYPE Release(void);
195 virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents, IDeckLinkDisplayMode*, BMDDetectedVideoInputFormatFlags);
196 virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame*, IDeckLinkAudioInputPacket*);
200 pthread_mutex_t m_mutex;
201 AVFormatContext *avctx;
204 int64_t initial_video_pts;
205 int64_t initial_audio_pts;
208 decklink_input_callback::decklink_input_callback(AVFormatContext *_avctx) : m_refCount(0)
211 decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
212 ctx = (struct decklink_ctx *)cctx->ctx;
214 initial_audio_pts = initial_video_pts = AV_NOPTS_VALUE;
215 pthread_mutex_init(&m_mutex, NULL);
218 decklink_input_callback::~decklink_input_callback()
220 pthread_mutex_destroy(&m_mutex);
223 ULONG decklink_input_callback::AddRef(void)
225 pthread_mutex_lock(&m_mutex);
227 pthread_mutex_unlock(&m_mutex);
229 return (ULONG)m_refCount;
232 ULONG decklink_input_callback::Release(void)
234 pthread_mutex_lock(&m_mutex);
236 pthread_mutex_unlock(&m_mutex);
238 if (m_refCount == 0) {
243 return (ULONG)m_refCount;
246 static int64_t get_pkt_pts(IDeckLinkVideoInputFrame *videoFrame,
247 IDeckLinkAudioInputPacket *audioFrame,
249 DecklinkPtsSource pts_src,
250 AVRational time_base, int64_t *initial_pts)
252 int64_t pts = AV_NOPTS_VALUE;
253 BMDTimeValue bmd_pts;
254 BMDTimeValue bmd_duration;
255 HRESULT res = E_INVALIDARG;
259 res = audioFrame->GetPacketTime(&bmd_pts, time_base.den);
263 res = videoFrame->GetStreamTime(&bmd_pts, &bmd_duration, time_base.den);
265 case PTS_SRC_REFERENCE:
267 res = videoFrame->GetHardwareReferenceTimestamp(time_base.den, &bmd_pts, &bmd_duration);
269 case PTS_SRC_WALLCLOCK:
271 /* MSVC does not support compound literals like AV_TIME_BASE_Q
272 * in C++ code (compiler error C4576) */
275 timebase.den = AV_TIME_BASE;
276 pts = av_rescale_q(wallclock, timebase, time_base);
281 pts = bmd_pts / time_base.num;
283 if (pts != AV_NOPTS_VALUE && *initial_pts == AV_NOPTS_VALUE)
285 if (*initial_pts != AV_NOPTS_VALUE)
291 HRESULT decklink_input_callback::VideoInputFrameArrived(
292 IDeckLinkVideoInputFrame *videoFrame, IDeckLinkAudioInputPacket *audioFrame)
295 void *audioFrameBytes;
296 BMDTimeValue frameTime;
297 BMDTimeValue frameDuration;
298 int64_t wallclock = 0;
301 if (ctx->audio_pts_source == PTS_SRC_WALLCLOCK || ctx->video_pts_source == PTS_SRC_WALLCLOCK)
302 wallclock = av_gettime_relative();
304 // Handle Video Frame
307 av_init_packet(&pkt);
308 if (ctx->frameCount % 25 == 0) {
309 unsigned long long qsize = avpacket_queue_size(&ctx->queue);
310 av_log(avctx, AV_LOG_DEBUG,
311 "Frame received (#%lu) - Valid (%liB) - QSize %fMB\n",
313 videoFrame->GetRowBytes() * videoFrame->GetHeight(),
314 (double)qsize / 1024 / 1024);
317 videoFrame->GetBytes(&frameBytes);
318 videoFrame->GetStreamTime(&frameTime, &frameDuration,
319 ctx->video_st->time_base.den);
321 if (videoFrame->GetFlags() & bmdFrameHasNoInputSource) {
322 if (ctx->draw_bars && videoFrame->GetPixelFormat() == bmdFormat8BitYUV) {
324 0xEA80EA80, 0xD292D210, 0xA910A9A5, 0x90229035,
325 0x6ADD6ACA, 0x51EF515A, 0x286D28EF, 0x10801080 };
326 int width = videoFrame->GetWidth();
327 int height = videoFrame->GetHeight();
328 unsigned *p = (unsigned *)frameBytes;
330 for (int y = 0; y < height; y++) {
331 for (int x = 0; x < width; x += 2)
332 *p++ = bars[(x * 8) / width];
337 av_log(avctx, AV_LOG_WARNING, "Frame received (#%lu) - No input signal detected "
338 "- Frames dropped %u\n", ctx->frameCount, ++ctx->dropped);
343 av_log(avctx, AV_LOG_WARNING, "Frame received (#%lu) - Input returned "
344 "- Frames dropped %u\n", ctx->frameCount, ++ctx->dropped);
349 pkt.pts = get_pkt_pts(videoFrame, audioFrame, wallclock, ctx->video_pts_source, ctx->video_st->time_base, &initial_video_pts);
352 pkt.duration = frameDuration;
353 //To be made sure it still applies
354 pkt.flags |= AV_PKT_FLAG_KEY;
355 pkt.stream_index = ctx->video_st->index;
356 pkt.data = (uint8_t *)frameBytes;
357 pkt.size = videoFrame->GetRowBytes() *
358 videoFrame->GetHeight();
359 //fprintf(stderr,"Video Frame size %d ts %d\n", pkt.size, pkt.pts);
362 if (!no_video && ctx->teletext_lines && videoFrame->GetPixelFormat() == bmdFormat8BitYUV && videoFrame->GetWidth() == 720) {
363 IDeckLinkVideoFrameAncillary *vanc;
365 uint8_t txt_buf0[1611]; // max 35 * 46 bytes decoded teletext lines + 1 byte data_identifier
366 uint8_t *txt_buf = txt_buf0;
368 if (videoFrame->GetAncillaryData(&vanc) == S_OK) {
370 int64_t line_mask = 1;
371 txt_buf[0] = 0x10; // data_identifier - EBU_data
373 for (i = 6; i < 336; i++, line_mask <<= 1) {
375 if ((ctx->teletext_lines & line_mask) && vanc->GetBufferForVerticalBlankingLine(i, (void**)&buf) == S_OK) {
376 if (teletext_data_unit_from_vbi_data(i, buf, txt_buf) >= 0)
383 if (txt_buf - txt_buf0 > 1) {
384 int stuffing_units = (4 - ((45 + txt_buf - txt_buf0) / 46) % 4) % 4;
385 while (stuffing_units--) {
386 memset(txt_buf, 0xff, 46);
387 txt_buf[1] = 0x2c; // data_unit_length
390 av_init_packet(&txt_pkt);
391 txt_pkt.pts = pkt.pts;
392 txt_pkt.dts = pkt.dts;
393 txt_pkt.stream_index = ctx->teletext_st->index;
394 txt_pkt.data = txt_buf0;
395 txt_pkt.size = txt_buf - txt_buf0;
396 if (avpacket_queue_put(&ctx->queue, &txt_pkt) < 0) {
404 if (avpacket_queue_put(&ctx->queue, &pkt) < 0) {
409 // Handle Audio Frame
412 BMDTimeValue audio_pts;
413 av_init_packet(&pkt);
416 pkt.size = audioFrame->GetSampleFrameCount() * ctx->audio_st->codecpar->channels * (16 / 8);
417 audioFrame->GetBytes(&audioFrameBytes);
418 audioFrame->GetPacketTime(&audio_pts, ctx->audio_st->time_base.den);
419 pkt.pts = get_pkt_pts(videoFrame, audioFrame, wallclock, ctx->audio_pts_source, ctx->audio_st->time_base, &initial_audio_pts);
422 //fprintf(stderr,"Audio Frame size %d ts %d\n", pkt.size, pkt.pts);
423 pkt.flags |= AV_PKT_FLAG_KEY;
424 pkt.stream_index = ctx->audio_st->index;
425 pkt.data = (uint8_t *)audioFrameBytes;
427 if (avpacket_queue_put(&ctx->queue, &pkt) < 0) {
435 HRESULT decklink_input_callback::VideoInputFormatChanged(
436 BMDVideoInputFormatChangedEvents events, IDeckLinkDisplayMode *mode,
437 BMDDetectedVideoInputFormatFlags)
442 static HRESULT decklink_start_input(AVFormatContext *avctx)
444 struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
445 struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
447 ctx->input_callback = new decklink_input_callback(avctx);
448 ctx->dli->SetCallback(ctx->input_callback);
449 return ctx->dli->StartStreams();
454 av_cold int ff_decklink_read_close(AVFormatContext *avctx)
456 struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
457 struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
459 if (ctx->capture_started) {
460 ctx->dli->StopStreams();
461 ctx->dli->DisableVideoInput();
462 ctx->dli->DisableAudioInput();
465 ff_decklink_cleanup(avctx);
466 avpacket_queue_end(&ctx->queue);
468 av_freep(&cctx->ctx);
473 av_cold int ff_decklink_read_header(AVFormatContext *avctx)
475 struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
476 struct decklink_ctx *ctx;
484 ctx = (struct decklink_ctx *) av_mallocz(sizeof(struct decklink_ctx));
486 return AVERROR(ENOMEM);
487 ctx->list_devices = cctx->list_devices;
488 ctx->list_formats = cctx->list_formats;
489 ctx->teletext_lines = cctx->teletext_lines;
490 ctx->preroll = cctx->preroll;
491 ctx->duplex_mode = cctx->duplex_mode;
492 if (cctx->video_input > 0 && (unsigned int)cctx->video_input < FF_ARRAY_ELEMS(decklink_video_connection_map))
493 ctx->video_input = decklink_video_connection_map[cctx->video_input];
494 if (cctx->audio_input > 0 && (unsigned int)cctx->audio_input < FF_ARRAY_ELEMS(decklink_audio_connection_map))
495 ctx->audio_input = decklink_audio_connection_map[cctx->audio_input];
496 ctx->audio_pts_source = cctx->audio_pts_source;
497 ctx->video_pts_source = cctx->video_pts_source;
498 ctx->draw_bars = cctx->draw_bars;
502 if (ctx->teletext_lines) {
503 av_log(avctx, AV_LOG_ERROR, "Libzvbi support is needed for capturing teletext, please recompile FFmpeg.\n");
504 return AVERROR(ENOSYS);
508 /* Check audio channel option for valid values: 2, 8 or 16 */
509 switch (cctx->audio_channels) {
515 av_log(avctx, AV_LOG_ERROR, "Value of channels option must be one of 2, 8 or 16\n");
516 return AVERROR(EINVAL);
519 /* List available devices. */
520 if (ctx->list_devices) {
521 ff_decklink_list_devices(avctx);
525 strcpy (fname, avctx->filename);
526 tmp=strchr (fname, '@');
528 av_log(avctx, AV_LOG_WARNING, "The @mode syntax is deprecated and will be removed. Please use the -format_code option.\n");
529 mode_num = atoi (tmp+1);
533 ret = ff_decklink_init_device(avctx, fname);
537 /* Get input device. */
538 if (ctx->dl->QueryInterface(IID_IDeckLinkInput, (void **) &ctx->dli) != S_OK) {
539 av_log(avctx, AV_LOG_ERROR, "Could not open input device from '%s'\n",
545 /* List supported formats. */
546 if (ctx->list_formats) {
547 ff_decklink_list_formats(avctx, DIRECTION_IN);
552 if (mode_num > 0 || cctx->format_code) {
553 if (ff_decklink_set_format(avctx, DIRECTION_IN, mode_num) < 0) {
554 av_log(avctx, AV_LOG_ERROR, "Could not set mode number %d or format code %s for %s\n",
555 mode_num, (cctx->format_code) ? cctx->format_code : "(unset)", fname);
562 st = avformat_new_stream(avctx, NULL);
564 av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
565 ret = AVERROR(ENOMEM);
568 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
569 st->codecpar->codec_id = AV_CODEC_ID_PCM_S16LE;
570 st->codecpar->sample_rate = bmdAudioSampleRate48kHz;
571 st->codecpar->channels = cctx->audio_channels;
572 avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
575 st = avformat_new_stream(avctx, NULL);
577 av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
578 ret = AVERROR(ENOMEM);
581 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
582 st->codecpar->width = ctx->bmd_width;
583 st->codecpar->height = ctx->bmd_height;
585 st->time_base.den = ctx->bmd_tb_den;
586 st->time_base.num = ctx->bmd_tb_num;
587 av_stream_set_r_frame_rate(st, av_make_q(st->time_base.den, st->time_base.num));
590 st->codecpar->codec_id = AV_CODEC_ID_V210;
591 st->codecpar->codec_tag = MKTAG('V', '2', '1', '0');
592 st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 64, st->time_base.den, st->time_base.num * 3);
594 st->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
595 st->codecpar->format = AV_PIX_FMT_UYVY422;
596 st->codecpar->codec_tag = MKTAG('U', 'Y', 'V', 'Y');
597 st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 16, st->time_base.den, st->time_base.num);
600 avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
604 if (ctx->teletext_lines) {
605 st = avformat_new_stream(avctx, NULL);
607 av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
608 ret = AVERROR(ENOMEM);
611 st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
612 st->time_base.den = ctx->bmd_tb_den;
613 st->time_base.num = ctx->bmd_tb_num;
614 st->codecpar->codec_id = AV_CODEC_ID_DVB_TELETEXT;
615 avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
616 ctx->teletext_st = st;
619 av_log(avctx, AV_LOG_VERBOSE, "Using %d input audio channels\n", ctx->audio_st->codecpar->channels);
620 result = ctx->dli->EnableAudioInput(bmdAudioSampleRate48kHz, bmdAudioSampleType16bitInteger, ctx->audio_st->codecpar->channels);
622 if (result != S_OK) {
623 av_log(avctx, AV_LOG_ERROR, "Cannot enable audio input\n");
628 result = ctx->dli->EnableVideoInput(ctx->bmd_mode,
629 cctx->v210 ? bmdFormat10BitYUV : bmdFormat8BitYUV,
630 bmdVideoInputFlagDefault);
632 if (result != S_OK) {
633 av_log(avctx, AV_LOG_ERROR, "Cannot enable video input\n");
638 avpacket_queue_init (avctx, &ctx->queue);
640 if (decklink_start_input (avctx) != S_OK) {
641 av_log(avctx, AV_LOG_ERROR, "Cannot start input stream\n");
649 ff_decklink_cleanup(avctx);
653 int ff_decklink_read_packet(AVFormatContext *avctx, AVPacket *pkt)
655 struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
656 struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
657 AVFrame *frame = ctx->video_st->codec->coded_frame;
659 avpacket_queue_get(&ctx->queue, pkt, 1);
660 if (frame && (ctx->bmd_field_dominance == bmdUpperFieldFirst || ctx->bmd_field_dominance == bmdLowerFieldFirst)) {
661 frame->interlaced_frame = 1;
662 if (ctx->bmd_field_dominance == bmdUpperFieldFirst) {
663 frame->top_field_first = 1;