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>
29 #include "libavformat/avformat.h"
30 #include "libavformat/internal.h"
31 #include "libavutil/imgutils.h"
37 #include "decklink_common.h"
38 #include "decklink_dec.h"
41 static uint8_t calc_parity_and_line_offset(int line)
43 uint8_t ret = (line < 313) << 5;
44 if (line >= 7 && line <= 22)
46 if (line >= 320 && line <= 335)
51 int teletext_data_unit_from_vbi_data(int line, uint8_t *src, uint8_t *tgt)
53 vbi_bit_slicer slicer;
55 vbi_bit_slicer_init(&slicer, 720, 13500000, 6937500, 6937500, 0x00aaaae4, 0xffff, 18, 6, 42 * 8, VBI_MODULATION_NRZ_MSB, VBI_PIXFMT_UYVY);
57 if (vbi_bit_slice(&slicer, src, tgt + 4) == FALSE)
60 tgt[0] = 0x02; // data_unit_id
61 tgt[1] = 0x2c; // data_unit_length
62 tgt[2] = calc_parity_and_line_offset(line); // field_parity, line_offset
63 tgt[3] = 0xe4; // framing code
69 static void avpacket_queue_init(AVFormatContext *avctx, AVPacketQueue *q)
71 memset(q, 0, sizeof(AVPacketQueue));
72 pthread_mutex_init(&q->mutex, NULL);
73 pthread_cond_init(&q->cond, NULL);
77 static void avpacket_queue_flush(AVPacketQueue *q)
79 AVPacketList *pkt, *pkt1;
81 pthread_mutex_lock(&q->mutex);
82 for (pkt = q->first_pkt; pkt != NULL; pkt = pkt1) {
84 av_packet_unref(&pkt->pkt);
91 pthread_mutex_unlock(&q->mutex);
94 static void avpacket_queue_end(AVPacketQueue *q)
96 avpacket_queue_flush(q);
97 pthread_mutex_destroy(&q->mutex);
98 pthread_cond_destroy(&q->cond);
101 static unsigned long long avpacket_queue_size(AVPacketQueue *q)
103 unsigned long long size;
104 pthread_mutex_lock(&q->mutex);
106 pthread_mutex_unlock(&q->mutex);
110 static int avpacket_queue_put(AVPacketQueue *q, AVPacket *pkt)
114 // Drop Packet if queue size is > 1GB
115 if (avpacket_queue_size(q) > 1024 * 1024 * 1024 ) {
116 av_log(q->avctx, AV_LOG_WARNING, "Decklink input buffer overrun!\n");
119 /* duplicate the packet */
120 if (av_dup_packet(pkt) < 0) {
124 pkt1 = (AVPacketList *)av_malloc(sizeof(AVPacketList));
131 pthread_mutex_lock(&q->mutex);
136 q->last_pkt->next = pkt1;
141 q->size += pkt1->pkt.size + sizeof(*pkt1);
143 pthread_cond_signal(&q->cond);
145 pthread_mutex_unlock(&q->mutex);
149 static int avpacket_queue_get(AVPacketQueue *q, AVPacket *pkt, int block)
154 pthread_mutex_lock(&q->mutex);
159 q->first_pkt = pkt1->next;
164 q->size -= pkt1->pkt.size + sizeof(*pkt1);
173 pthread_cond_wait(&q->cond, &q->mutex);
176 pthread_mutex_unlock(&q->mutex);
180 class decklink_input_callback : public IDeckLinkInputCallback
183 decklink_input_callback(AVFormatContext *_avctx);
184 ~decklink_input_callback();
186 virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv) { return E_NOINTERFACE; }
187 virtual ULONG STDMETHODCALLTYPE AddRef(void);
188 virtual ULONG STDMETHODCALLTYPE Release(void);
189 virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents, IDeckLinkDisplayMode*, BMDDetectedVideoInputFormatFlags);
190 virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame*, IDeckLinkAudioInputPacket*);
194 pthread_mutex_t m_mutex;
195 AVFormatContext *avctx;
198 int64_t initial_video_pts;
199 int64_t initial_audio_pts;
202 decklink_input_callback::decklink_input_callback(AVFormatContext *_avctx) : m_refCount(0)
205 decklink_cctx *cctx = (struct decklink_cctx *) avctx->priv_data;
206 ctx = (struct decklink_ctx *) cctx->ctx;
207 initial_audio_pts = initial_video_pts = AV_NOPTS_VALUE;
208 pthread_mutex_init(&m_mutex, NULL);
211 decklink_input_callback::~decklink_input_callback()
213 pthread_mutex_destroy(&m_mutex);
216 ULONG decklink_input_callback::AddRef(void)
218 pthread_mutex_lock(&m_mutex);
220 pthread_mutex_unlock(&m_mutex);
222 return (ULONG)m_refCount;
225 ULONG decklink_input_callback::Release(void)
227 pthread_mutex_lock(&m_mutex);
229 pthread_mutex_unlock(&m_mutex);
231 if (m_refCount == 0) {
236 return (ULONG)m_refCount;
239 HRESULT decklink_input_callback::VideoInputFrameArrived(
240 IDeckLinkVideoInputFrame *videoFrame, IDeckLinkAudioInputPacket *audioFrame)
243 void *audioFrameBytes;
244 BMDTimeValue frameTime;
245 BMDTimeValue frameDuration;
249 // Handle Video Frame
252 av_init_packet(&pkt);
253 if (ctx->frameCount % 25 == 0) {
254 unsigned long long qsize = avpacket_queue_size(&ctx->queue);
255 av_log(avctx, AV_LOG_DEBUG,
256 "Frame received (#%lu) - Valid (%liB) - QSize %fMB\n",
258 videoFrame->GetRowBytes() * videoFrame->GetHeight(),
259 (double)qsize / 1024 / 1024);
262 videoFrame->GetBytes(&frameBytes);
263 videoFrame->GetStreamTime(&frameTime, &frameDuration,
264 ctx->video_st->time_base.den);
266 if (videoFrame->GetFlags() & bmdFrameHasNoInputSource) {
267 if (videoFrame->GetPixelFormat() == bmdFormat8BitYUV) {
269 0xEA80EA80, 0xD292D210, 0xA910A9A5, 0x90229035,
270 0x6ADD6ACA, 0x51EF515A, 0x286D28EF, 0x10801080 };
271 int width = videoFrame->GetWidth();
272 int height = videoFrame->GetHeight();
273 unsigned *p = (unsigned *)frameBytes;
275 for (int y = 0; y < height; y++) {
276 for (int x = 0; x < width; x += 2)
277 *p++ = bars[(x * 8) / width];
282 av_log(avctx, AV_LOG_WARNING, "Frame received (#%lu) - No input signal detected "
283 "- Frames dropped %u\n", ctx->frameCount, ++ctx->dropped);
288 av_log(avctx, AV_LOG_WARNING, "Frame received (#%lu) - Input returned "
289 "- Frames dropped %u\n", ctx->frameCount, ++ctx->dropped);
294 pkt.pts = frameTime / ctx->video_st->time_base.num;
296 if (initial_video_pts == AV_NOPTS_VALUE) {
297 initial_video_pts = pkt.pts;
300 pkt.pts -= initial_video_pts;
303 pkt.duration = frameDuration;
304 //To be made sure it still applies
305 pkt.flags |= AV_PKT_FLAG_KEY;
306 pkt.stream_index = ctx->video_st->index;
307 pkt.data = (uint8_t *)frameBytes;
308 pkt.size = videoFrame->GetRowBytes() *
309 videoFrame->GetHeight();
310 //fprintf(stderr,"Video Frame size %d ts %d\n", pkt.size, pkt.pts);
313 if (!no_video && ctx->teletext_lines && videoFrame->GetPixelFormat() == bmdFormat8BitYUV && videoFrame->GetWidth() == 720) {
314 IDeckLinkVideoFrameAncillary *vanc;
316 uint8_t txt_buf0[1611]; // max 35 * 46 bytes decoded teletext lines + 1 byte data_identifier
317 uint8_t *txt_buf = txt_buf0;
319 if (videoFrame->GetAncillaryData(&vanc) == S_OK) {
321 int64_t line_mask = 1;
322 txt_buf[0] = 0x10; // data_identifier - EBU_data
324 for (i = 6; i < 336; i++, line_mask <<= 1) {
326 if ((ctx->teletext_lines & line_mask) && vanc->GetBufferForVerticalBlankingLine(i, (void**)&buf) == S_OK) {
327 if (teletext_data_unit_from_vbi_data(i, buf, txt_buf) >= 0)
334 if (txt_buf - txt_buf0 > 1) {
335 int stuffing_units = (4 - ((45 + txt_buf - txt_buf0) / 46) % 4) % 4;
336 while (stuffing_units--) {
337 memset(txt_buf, 0xff, 46);
338 txt_buf[1] = 0x2c; // data_unit_length
341 av_init_packet(&txt_pkt);
342 txt_pkt.pts = pkt.pts;
343 txt_pkt.dts = pkt.dts;
344 txt_pkt.stream_index = ctx->teletext_st->index;
345 txt_pkt.data = txt_buf0;
346 txt_pkt.size = txt_buf - txt_buf0;
347 if (avpacket_queue_put(&ctx->queue, &txt_pkt) < 0) {
355 if (avpacket_queue_put(&ctx->queue, &pkt) < 0) {
360 // Handle Audio Frame
363 BMDTimeValue audio_pts;
364 av_init_packet(&pkt);
367 pkt.size = audioFrame->GetSampleFrameCount() * ctx->audio_st->codecpar->channels * (16 / 8);
368 audioFrame->GetBytes(&audioFrameBytes);
369 audioFrame->GetPacketTime(&audio_pts, ctx->audio_st->time_base.den);
370 pkt.pts = audio_pts / ctx->audio_st->time_base.num;
372 if (initial_audio_pts == AV_NOPTS_VALUE) {
373 initial_audio_pts = pkt.pts;
376 pkt.pts -= initial_audio_pts;
379 //fprintf(stderr,"Audio Frame size %d ts %d\n", pkt.size, pkt.pts);
380 pkt.flags |= AV_PKT_FLAG_KEY;
381 pkt.stream_index = ctx->audio_st->index;
382 pkt.data = (uint8_t *)audioFrameBytes;
384 if (avpacket_queue_put(&ctx->queue, &pkt) < 0) {
392 HRESULT decklink_input_callback::VideoInputFormatChanged(
393 BMDVideoInputFormatChangedEvents events, IDeckLinkDisplayMode *mode,
394 BMDDetectedVideoInputFormatFlags)
399 static HRESULT decklink_start_input(AVFormatContext *avctx)
401 struct decklink_cctx *cctx = (struct decklink_cctx *) avctx->priv_data;
402 struct decklink_ctx *ctx = (struct decklink_ctx *) cctx->ctx;
404 ctx->input_callback = new decklink_input_callback(avctx);
405 ctx->dli->SetCallback(ctx->input_callback);
406 return ctx->dli->StartStreams();
411 av_cold int ff_decklink_read_close(AVFormatContext *avctx)
413 struct decklink_cctx *cctx = (struct decklink_cctx *) avctx->priv_data;
414 struct decklink_ctx *ctx = (struct decklink_ctx *) cctx->ctx;
416 if (ctx->capture_started) {
417 ctx->dli->StopStreams();
418 ctx->dli->DisableVideoInput();
419 ctx->dli->DisableAudioInput();
427 avpacket_queue_end(&ctx->queue);
429 av_freep(&cctx->ctx);
434 av_cold int ff_decklink_read_header(AVFormatContext *avctx)
436 struct decklink_cctx *cctx = (struct decklink_cctx *) avctx->priv_data;
437 struct decklink_ctx *ctx;
438 IDeckLinkDisplayModeIterator *itermode;
439 IDeckLinkIterator *iter;
440 IDeckLink *dl = NULL;
447 ctx = (struct decklink_ctx *) av_mallocz(sizeof(struct decklink_ctx));
449 return AVERROR(ENOMEM);
450 ctx->list_devices = cctx->list_devices;
451 ctx->list_formats = cctx->list_formats;
452 ctx->teletext_lines = cctx->teletext_lines;
453 ctx->preroll = cctx->preroll;
457 if (ctx->teletext_lines) {
458 av_log(avctx, AV_LOG_ERROR, "Libzvbi support is needed for capturing teletext, please recompile FFmpeg.\n");
459 return AVERROR(ENOSYS);
463 /* Check audio channel option for valid values: 2, 8 or 16 */
464 switch (cctx->audio_channels) {
470 av_log(avctx, AV_LOG_ERROR, "Value of channels option must be one of 2, 8 or 16\n");
471 return AVERROR(EINVAL);
474 iter = CreateDeckLinkIteratorInstance();
476 av_log(avctx, AV_LOG_ERROR, "Could not create DeckLink iterator\n");
480 /* List available devices. */
481 if (ctx->list_devices) {
482 ff_decklink_list_devices(avctx);
486 strcpy (fname, avctx->filename);
487 tmp=strchr (fname, '@');
489 mode_num = atoi (tmp+1);
494 while (iter->Next(&dl) == S_OK) {
495 const char *displayName;
496 ff_decklink_get_display_name(dl, &displayName);
497 if (!strcmp(fname, displayName)) {
498 av_free((void *) displayName);
502 av_free((void *) displayName);
507 av_log(avctx, AV_LOG_ERROR, "Could not open '%s'\n", fname);
511 /* Get input device. */
512 if (ctx->dl->QueryInterface(IID_IDeckLinkInput, (void **) &ctx->dli) != S_OK) {
513 av_log(avctx, AV_LOG_ERROR, "Could not open output device from '%s'\n",
519 /* List supported formats. */
520 if (ctx->list_formats) {
521 ff_decklink_list_formats(avctx, DIRECTION_IN);
527 if (ctx->dli->GetDisplayModeIterator(&itermode) != S_OK) {
528 av_log(avctx, AV_LOG_ERROR, "Could not get Display Mode Iterator\n");
534 if (ff_decklink_set_format(avctx, DIRECTION_IN, mode_num) < 0) {
535 av_log(avctx, AV_LOG_ERROR, "Could not set mode %d for %s\n", mode_num, fname);
543 st = avformat_new_stream(avctx, NULL);
545 av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
548 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
549 st->codecpar->codec_id = AV_CODEC_ID_PCM_S16LE;
550 st->codecpar->sample_rate = bmdAudioSampleRate48kHz;
551 st->codecpar->channels = cctx->audio_channels;
552 avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
555 st = avformat_new_stream(avctx, NULL);
557 av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
560 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
561 st->codecpar->width = ctx->bmd_width;
562 st->codecpar->height = ctx->bmd_height;
564 st->time_base.den = ctx->bmd_tb_den;
565 st->time_base.num = ctx->bmd_tb_num;
566 st->codecpar->bit_rate = av_image_get_buffer_size((AVPixelFormat)st->codecpar->format, ctx->bmd_width, ctx->bmd_height, 1) * 1/av_q2d(st->time_base) * 8;
569 st->codecpar->codec_id = AV_CODEC_ID_V210;
570 st->codecpar->codec_tag = MKTAG('V', '2', '1', '0');
572 st->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
573 st->codecpar->format = AV_PIX_FMT_UYVY422;
574 st->codecpar->codec_tag = MKTAG('U', 'Y', 'V', 'Y');
577 avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
581 if (ctx->teletext_lines) {
582 st = avformat_new_stream(avctx, NULL);
584 av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
587 st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
588 st->time_base.den = ctx->bmd_tb_den;
589 st->time_base.num = ctx->bmd_tb_num;
590 st->codecpar->codec_id = AV_CODEC_ID_DVB_TELETEXT;
591 avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
592 ctx->teletext_st = st;
595 av_log(avctx, AV_LOG_VERBOSE, "Using %d input audio channels\n", ctx->audio_st->codecpar->channels);
596 result = ctx->dli->EnableAudioInput(bmdAudioSampleRate48kHz, bmdAudioSampleType16bitInteger, ctx->audio_st->codecpar->channels);
598 if (result != S_OK) {
599 av_log(avctx, AV_LOG_ERROR, "Cannot enable audio input\n");
603 result = ctx->dli->EnableVideoInput(ctx->bmd_mode,
604 cctx->v210 ? bmdFormat10BitYUV : bmdFormat8BitYUV,
605 bmdVideoInputFlagDefault);
607 if (result != S_OK) {
608 av_log(avctx, AV_LOG_ERROR, "Cannot enable video input\n");
612 avpacket_queue_init (avctx, &ctx->queue);
614 if (decklink_start_input (avctx) != S_OK) {
615 av_log(avctx, AV_LOG_ERROR, "Cannot start input stream\n");
629 int ff_decklink_read_packet(AVFormatContext *avctx, AVPacket *pkt)
631 struct decklink_cctx *cctx = (struct decklink_cctx *) avctx->priv_data;
632 struct decklink_ctx *ctx = (struct decklink_ctx *) cctx->ctx;
633 AVFrame *frame = ctx->video_st->codec->coded_frame;
635 avpacket_queue_get(&ctx->queue, pkt, 1);
636 if (frame && (ctx->bmd_field_dominance == bmdUpperFieldFirst || ctx->bmd_field_dominance == bmdLowerFieldFirst)) {
637 frame->interlaced_frame = 1;
638 if (ctx->bmd_field_dominance == bmdUpperFieldFirst) {
639 frame->top_field_first = 1;