2 * Blackmagic DeckLink input
3 * Copyright (c) 2013-2014 Luca Barbato, Deti Fliegl
4 * Copyright (c) 2014 Rafaël Carré
5 * Copyright (c) 2017 Akamai Technologies, Inc.
7 * This file is part of FFmpeg.
9 * FFmpeg is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * FFmpeg is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with FFmpeg; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
27 /* Include internal.h first to avoid conflict between winsock.h (used by
28 * DeckLink headers) and winsock2.h (used by libavformat) in MSVC++ builds */
30 #include "libavformat/internal.h"
33 #include <DeckLinkAPI.h>
37 #include "libavformat/avformat.h"
38 #include "libavutil/avassert.h"
39 #include "libavutil/avutil.h"
40 #include "libavutil/common.h"
41 #include "libavutil/imgutils.h"
42 #include "libavutil/intreadwrite.h"
43 #include "libavutil/time.h"
44 #include "libavutil/mathematics.h"
45 #include "libavutil/reverse.h"
52 #include "decklink_common.h"
53 #include "decklink_dec.h"
55 #define MAX_WIDTH_VANC 1920
56 const BMDDisplayMode AUTODETECT_DEFAULT_MODE = bmdModeNTSC;
58 typedef struct VANCLineNumber {
62 int field1_vanc_start;
66 /* These VANC line numbers need not be very accurate. In any case
67 * GetBufferForVerticalBlankingLine() will return an error when invalid
68 * ancillary line number was requested. We just need to make sure that the
69 * entire VANC region is covered, while making sure we don't decode VANC of
70 * another source during switching*/
71 static VANCLineNumber vanc_line_numbers[] = {
74 {bmdModeNTSC, 11, 19, 274, 282},
75 {bmdModeNTSC2398, 11, 19, 274, 282},
76 {bmdModePAL, 7, 22, 320, 335},
77 {bmdModeNTSCp, 11, -1, -1, 39},
78 {bmdModePALp, 7, -1, -1, 45},
82 {bmdModeHD1080p2398, 8, -1, -1, 42},
83 {bmdModeHD1080p24, 8, -1, -1, 42},
84 {bmdModeHD1080p25, 8, -1, -1, 42},
85 {bmdModeHD1080p2997, 8, -1, -1, 42},
86 {bmdModeHD1080p30, 8, -1, -1, 42},
87 {bmdModeHD1080i50, 8, 20, 570, 585},
88 {bmdModeHD1080i5994, 8, 20, 570, 585},
89 {bmdModeHD1080i6000, 8, 20, 570, 585},
90 {bmdModeHD1080p50, 8, -1, -1, 42},
91 {bmdModeHD1080p5994, 8, -1, -1, 42},
92 {bmdModeHD1080p6000, 8, -1, -1, 42},
96 {bmdModeHD720p50, 8, -1, -1, 26},
97 {bmdModeHD720p5994, 8, -1, -1, 26},
98 {bmdModeHD720p60, 8, -1, -1, 26},
100 /* For all other modes, for which we don't support VANC */
101 {bmdModeUnknown, 0, -1, -1, -1}
104 class decklink_allocator : public IDeckLinkMemoryAllocator
107 decklink_allocator(): _refs(1) { }
108 virtual ~decklink_allocator() { }
110 // IDeckLinkMemoryAllocator methods
111 virtual HRESULT STDMETHODCALLTYPE AllocateBuffer(unsigned int bufferSize, void* *allocatedBuffer)
113 void *buf = av_malloc(bufferSize + AV_INPUT_BUFFER_PADDING_SIZE);
115 return E_OUTOFMEMORY;
116 *allocatedBuffer = buf;
119 virtual HRESULT STDMETHODCALLTYPE ReleaseBuffer(void* buffer)
124 virtual HRESULT STDMETHODCALLTYPE Commit() { return S_OK; }
125 virtual HRESULT STDMETHODCALLTYPE Decommit() { return S_OK; }
128 virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv) { return E_NOINTERFACE; }
129 virtual ULONG STDMETHODCALLTYPE AddRef(void) { return ++_refs; }
130 virtual ULONG STDMETHODCALLTYPE Release(void)
139 std::atomic<int> _refs;
143 static void decklink_object_free(void *opaque, uint8_t *data)
145 IUnknown *obj = (class IUnknown *)opaque;
150 static int get_vanc_line_idx(BMDDisplayMode mode)
153 for (i = 0; i < FF_ARRAY_ELEMS(vanc_line_numbers); i++) {
154 if (mode == vanc_line_numbers[i].mode)
157 /* Return the VANC idx for Unknown mode */
161 static inline void clear_parity_bits(uint16_t *buf, int len) {
163 for (i = 0; i < len; i++)
167 static int check_vanc_parity_checksum(uint16_t *buf, int len, uint16_t checksum) {
169 uint16_t vanc_sum = 0;
170 for (i = 3; i < len - 1; i++) {
173 int p = av_parity(v & 0xff);
174 if ((!!p ^ !!(v & 0x100)) || (np != 1 && np != 2)) {
175 // Parity check failed
181 vanc_sum |= ((~vanc_sum & 0x100) << 1);
182 if (checksum != vanc_sum) {
183 // Checksum verification failed
189 /* The 10-bit VANC data is packed in V210, we only need the luma component. */
190 static void extract_luma_from_v210(uint16_t *dst, const uint8_t *src, int width)
193 for (i = 0; i < width / 3; i++) {
194 *dst++ = (src[1] >> 2) + ((src[2] & 15) << 6);
195 *dst++ = src[4] + ((src[5] & 3) << 8);
196 *dst++ = (src[6] >> 4) + ((src[7] & 63) << 4);
201 static void unpack_v210(uint16_t *dst, const uint8_t *src, int width)
204 for (i = 0; i < width * 2 / 3; i++) {
205 *dst++ = src[0] + ((src[1] & 3) << 8);
206 *dst++ = (src[1] >> 2) + ((src[2] & 15) << 6);
207 *dst++ = (src[2] >> 4) + ((src[3] & 63) << 4);
212 static uint8_t calc_parity_and_line_offset(int line)
214 uint8_t ret = (line < 313) << 5;
215 if (line >= 7 && line <= 22)
217 if (line >= 320 && line <= 335)
222 static void fill_data_unit_head(int line, uint8_t *tgt)
224 tgt[0] = 0x02; // data_unit_id
225 tgt[1] = 0x2c; // data_unit_length
226 tgt[2] = calc_parity_and_line_offset(line); // field_parity, line_offset
227 tgt[3] = 0xe4; // framing code
231 static uint8_t* teletext_data_unit_from_vbi_data(int line, uint8_t *src, uint8_t *tgt, vbi_pixfmt fmt)
233 vbi_bit_slicer slicer;
235 vbi_bit_slicer_init(&slicer, 720, 13500000, 6937500, 6937500, 0x00aaaae4, 0xffff, 18, 6, 42 * 8, VBI_MODULATION_NRZ_MSB, fmt);
237 if (vbi_bit_slice(&slicer, src, tgt + 4) == FALSE)
240 fill_data_unit_head(line, tgt);
245 static uint8_t* teletext_data_unit_from_vbi_data_10bit(int line, uint8_t *src, uint8_t *tgt)
249 uint8_t *pend = y + 720;
250 /* The 10-bit VBI data is packed in V210, but libzvbi only supports 8-bit,
251 * so we extract the 8 MSBs of the luma component, that is enough for
252 * teletext bit slicing. */
254 *py++ = (src[1] >> 4) + ((src[2] & 15) << 4);
255 *py++ = (src[4] >> 2) + ((src[5] & 3 ) << 6);
256 *py++ = (src[6] >> 6) + ((src[7] & 63) << 2);
259 return teletext_data_unit_from_vbi_data(line, y, tgt, VBI_PIXFMT_YUV420);
263 static uint8_t* teletext_data_unit_from_op47_vbi_packet(int line, uint16_t *py, uint8_t *tgt)
267 if (py[0] != 0x255 || py[1] != 0x255 || py[2] != 0x227)
270 fill_data_unit_head(line, tgt);
275 for (i = 0; i < 42; i++)
276 *tgt++ = ff_reverse[py[i] & 255];
281 static int linemask_matches(int line, int64_t mask)
284 if (line >= 6 && line <= 22)
286 if (line >= 318 && line <= 335)
287 shift = line - 318 + 17;
288 return shift >= 0 && ((1ULL << shift) & mask);
291 static uint8_t* teletext_data_unit_from_op47_data(uint16_t *py, uint16_t *pend, uint8_t *tgt, int64_t wanted_lines)
294 if (py[0] == 0x151 && py[1] == 0x115 && py[3] == 0x102) { // identifier, identifier, format code for WST teletext
295 uint16_t *descriptors = py + 4;
298 for (i = 0; i < 5 && py < pend - 45; i++, py += 45) {
299 int line = (descriptors[i] & 31) + (!(descriptors[i] & 128)) * 313;
300 if (line && linemask_matches(line, wanted_lines))
301 tgt = teletext_data_unit_from_op47_vbi_packet(line, py, tgt);
308 static uint8_t* teletext_data_unit_from_ancillary_packet(uint16_t *py, uint16_t *pend, uint8_t *tgt, int64_t wanted_lines, int allow_multipacket)
310 uint16_t did = py[0]; // data id
311 uint16_t sdid = py[1]; // secondary data id
312 uint16_t dc = py[2] & 255; // data count
314 pend = FFMIN(pend, py + dc);
315 if (did == 0x143 && sdid == 0x102) { // subtitle distribution packet
316 tgt = teletext_data_unit_from_op47_data(py, pend, tgt, wanted_lines);
317 } else if (allow_multipacket && did == 0x143 && sdid == 0x203) { // VANC multipacket
318 py += 2; // priority, line/field
319 while (py < pend - 3) {
320 tgt = teletext_data_unit_from_ancillary_packet(py, pend, tgt, wanted_lines, 0);
321 py += 4 + (py[2] & 255); // ndid, nsdid, ndc, line/field
327 static uint8_t *vanc_to_cc(AVFormatContext *avctx, uint16_t *buf, size_t words,
330 size_t i, len = (buf[5] & 0xff) + 6 + 1;
331 uint8_t cdp_sum, rate;
334 uint16_t *cdp = &buf[6]; // CDP follows
335 if (cdp[0] != 0x96 || cdp[1] != 0x69) {
336 av_log(avctx, AV_LOG_WARNING, "Invalid CDP header 0x%.2x 0x%.2x\n", cdp[0], cdp[1]);
340 len -= 7; // remove VANC header and checksum
343 av_log(avctx, AV_LOG_WARNING, "CDP len %d != %zu\n", cdp[2], len);
348 for (i = 0; i < len - 1; i++)
350 cdp_sum = cdp_sum ? 256 - cdp_sum : 0;
351 if (cdp[len - 1] != cdp_sum) {
352 av_log(avctx, AV_LOG_WARNING, "CDP checksum invalid 0x%.4x != 0x%.4x\n", cdp_sum, cdp[len-1]);
357 if (!(rate & 0x0f)) {
358 av_log(avctx, AV_LOG_WARNING, "CDP frame rate invalid (0x%.2x)\n", rate);
363 av_log(avctx, AV_LOG_WARNING, "CDP frame rate invalid (0x%.2x)\n", rate);
367 if (!(cdp[4] & 0x43)) /* ccdata_present | caption_service_active | reserved */ {
368 av_log(avctx, AV_LOG_WARNING, "CDP flags invalid (0x%.2x)\n", cdp[4]);
372 hdr = (cdp[5] << 8) | cdp[6];
373 if (cdp[7] != 0x72) /* ccdata_id */ {
374 av_log(avctx, AV_LOG_WARNING, "Invalid ccdata_id 0x%.2x\n", cdp[7]);
379 if (!(cc_count & 0xe0)) {
380 av_log(avctx, AV_LOG_WARNING, "Invalid cc_count 0x%.2x\n", cc_count);
385 if ((len - 13) < cc_count * 3) {
386 av_log(avctx, AV_LOG_WARNING, "Invalid cc_count %d (> %zu)\n", cc_count * 3, len - 13);
390 if (cdp[len - 4] != 0x74) /* footer id */ {
391 av_log(avctx, AV_LOG_WARNING, "Invalid footer id 0x%.2x\n", cdp[len-4]);
395 ftr = (cdp[len - 3] << 8) | cdp[len - 2];
397 av_log(avctx, AV_LOG_WARNING, "Header 0x%.4x != Footer 0x%.4x\n", hdr, ftr);
401 cc = (uint8_t *)av_malloc(cc_count * 3);
403 av_log(avctx, AV_LOG_WARNING, "CC - av_malloc failed for cc_count = %d\n", cc_count);
407 for (size_t i = 0; i < cc_count; i++) {
408 cc[3*i + 0] = cdp[9 + 3*i+0] /* & 3 */;
409 cc[3*i + 1] = cdp[9 + 3*i+1];
410 cc[3*i + 2] = cdp[9 + 3*i+2];
417 static uint8_t *get_metadata(AVFormatContext *avctx, uint16_t *buf, size_t width,
418 uint8_t *tgt, size_t tgt_size, AVPacket *pkt)
420 decklink_cctx *cctx = (struct decklink_cctx *) avctx->priv_data;
421 uint16_t *max_buf = buf + width;
423 while (buf < max_buf - 6) {
425 uint16_t did = buf[3] & 0xFF; // data id
426 uint16_t sdid = buf[4] & 0xFF; // secondary data id
427 /* Check for VANC header */
428 if (buf[0] != 0 || buf[1] != 0x3ff || buf[2] != 0x3ff) {
432 len = (buf[5] & 0xff) + 6 + 1;
433 if (len > max_buf - buf) {
434 av_log(avctx, AV_LOG_WARNING, "Data Count (%d) > data left (%zu)\n",
439 if (did == 0x43 && (sdid == 0x02 || sdid == 0x03) && cctx->teletext_lines &&
440 width == 1920 && tgt_size >= 1920) {
441 if (check_vanc_parity_checksum(buf, len, buf[len - 1]) < 0) {
442 av_log(avctx, AV_LOG_WARNING, "VANC parity or checksum incorrect\n");
445 tgt = teletext_data_unit_from_ancillary_packet(buf + 3, buf + len, tgt, cctx->teletext_lines, 1);
446 } else if (did == 0x61 && sdid == 0x01) {
447 unsigned int data_len;
449 if (check_vanc_parity_checksum(buf, len, buf[len - 1]) < 0) {
450 av_log(avctx, AV_LOG_WARNING, "VANC parity or checksum incorrect\n");
453 clear_parity_bits(buf, len);
454 data = vanc_to_cc(avctx, buf, width, data_len);
456 if (av_packet_add_side_data(pkt, AV_PKT_DATA_A53_CC, data, data_len) < 0)
460 av_log(avctx, AV_LOG_DEBUG, "Unknown meta data DID = 0x%.2x SDID = 0x%.2x\n",
470 static void avpacket_queue_init(AVFormatContext *avctx, AVPacketQueue *q)
472 struct decklink_cctx *ctx = (struct decklink_cctx *)avctx->priv_data;
473 memset(q, 0, sizeof(AVPacketQueue));
474 pthread_mutex_init(&q->mutex, NULL);
475 pthread_cond_init(&q->cond, NULL);
477 q->max_q_size = ctx->queue_size;
480 static void avpacket_queue_flush(AVPacketQueue *q)
482 AVPacketList *pkt, *pkt1;
484 pthread_mutex_lock(&q->mutex);
485 for (pkt = q->first_pkt; pkt != NULL; pkt = pkt1) {
487 av_packet_unref(&pkt->pkt);
494 pthread_mutex_unlock(&q->mutex);
497 static void avpacket_queue_end(AVPacketQueue *q)
499 avpacket_queue_flush(q);
500 pthread_mutex_destroy(&q->mutex);
501 pthread_cond_destroy(&q->cond);
504 static unsigned long long avpacket_queue_size(AVPacketQueue *q)
506 unsigned long long size;
507 pthread_mutex_lock(&q->mutex);
509 pthread_mutex_unlock(&q->mutex);
513 static int avpacket_queue_put(AVPacketQueue *q, AVPacket *pkt)
517 // Drop Packet if queue size is > maximum queue size
518 if (avpacket_queue_size(q) > (uint64_t)q->max_q_size) {
519 av_packet_unref(pkt);
520 av_log(q->avctx, AV_LOG_WARNING, "Decklink input buffer overrun!\n");
523 /* ensure the packet is reference counted */
524 if (av_packet_make_refcounted(pkt) < 0) {
525 av_packet_unref(pkt);
529 pkt1 = (AVPacketList *)av_malloc(sizeof(AVPacketList));
531 av_packet_unref(pkt);
534 av_packet_move_ref(&pkt1->pkt, pkt);
537 pthread_mutex_lock(&q->mutex);
542 q->last_pkt->next = pkt1;
547 q->size += pkt1->pkt.size + sizeof(*pkt1);
549 pthread_cond_signal(&q->cond);
551 pthread_mutex_unlock(&q->mutex);
555 static int avpacket_queue_get(AVPacketQueue *q, AVPacket *pkt, int block)
560 pthread_mutex_lock(&q->mutex);
565 q->first_pkt = pkt1->next;
570 q->size -= pkt1->pkt.size + sizeof(*pkt1);
579 pthread_cond_wait(&q->cond, &q->mutex);
582 pthread_mutex_unlock(&q->mutex);
586 class decklink_input_callback : public IDeckLinkInputCallback
589 decklink_input_callback(AVFormatContext *_avctx);
590 ~decklink_input_callback();
592 virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv) { return E_NOINTERFACE; }
593 virtual ULONG STDMETHODCALLTYPE AddRef(void);
594 virtual ULONG STDMETHODCALLTYPE Release(void);
595 virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents, IDeckLinkDisplayMode*, BMDDetectedVideoInputFormatFlags);
596 virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame*, IDeckLinkAudioInputPacket*);
599 std::atomic<int> _refs;
600 AVFormatContext *avctx;
603 int64_t initial_video_pts;
604 int64_t initial_audio_pts;
607 decklink_input_callback::decklink_input_callback(AVFormatContext *_avctx) : _refs(1)
610 decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
611 ctx = (struct decklink_ctx *)cctx->ctx;
613 initial_audio_pts = initial_video_pts = AV_NOPTS_VALUE;
616 decklink_input_callback::~decklink_input_callback()
620 ULONG decklink_input_callback::AddRef(void)
625 ULONG decklink_input_callback::Release(void)
633 static int64_t get_pkt_pts(IDeckLinkVideoInputFrame *videoFrame,
634 IDeckLinkAudioInputPacket *audioFrame,
636 int64_t abs_wallclock,
637 DecklinkPtsSource pts_src,
638 AVRational time_base, int64_t *initial_pts,
641 int64_t pts = AV_NOPTS_VALUE;
642 BMDTimeValue bmd_pts;
643 BMDTimeValue bmd_duration;
644 HRESULT res = E_INVALIDARG;
648 res = audioFrame->GetPacketTime(&bmd_pts, time_base.den);
652 res = videoFrame->GetStreamTime(&bmd_pts, &bmd_duration, time_base.den);
654 case PTS_SRC_REFERENCE:
656 res = videoFrame->GetHardwareReferenceTimestamp(time_base.den, &bmd_pts, &bmd_duration);
658 case PTS_SRC_WALLCLOCK:
660 case PTS_SRC_ABS_WALLCLOCK:
662 /* MSVC does not support compound literals like AV_TIME_BASE_Q
663 * in C++ code (compiler error C4576) */
666 timebase.den = AV_TIME_BASE;
667 if (pts_src == PTS_SRC_WALLCLOCK)
668 pts = av_rescale_q(wallclock, timebase, time_base);
670 pts = av_rescale_q(abs_wallclock, timebase, time_base);
675 pts = bmd_pts / time_base.num;
678 if (pts != AV_NOPTS_VALUE && *initial_pts == AV_NOPTS_VALUE)
680 if (*initial_pts != AV_NOPTS_VALUE)
687 HRESULT decklink_input_callback::VideoInputFrameArrived(
688 IDeckLinkVideoInputFrame *videoFrame, IDeckLinkAudioInputPacket *audioFrame)
691 void *audioFrameBytes;
692 BMDTimeValue frameTime;
693 BMDTimeValue frameDuration;
694 int64_t wallclock = 0, abs_wallclock = 0;
695 struct decklink_cctx *cctx = (struct decklink_cctx *) avctx->priv_data;
697 if (ctx->autodetect) {
698 if (videoFrame && !(videoFrame->GetFlags() & bmdFrameHasNoInputSource) &&
699 ctx->bmd_mode == bmdModeUnknown)
701 ctx->bmd_mode = AUTODETECT_DEFAULT_MODE;
706 // Drop the frames till system's timestamp aligns with the configured value.
707 if (0 == ctx->frameCount && cctx->timestamp_align) {
708 AVRational remainder = av_make_q(av_gettime() % cctx->timestamp_align, 1000000);
709 AVRational frame_duration = av_inv_q(ctx->video_st->r_frame_rate);
710 if (av_cmp_q(remainder, frame_duration) > 0) {
717 if (ctx->audio_pts_source == PTS_SRC_WALLCLOCK || ctx->video_pts_source == PTS_SRC_WALLCLOCK)
718 wallclock = av_gettime_relative();
719 if (ctx->audio_pts_source == PTS_SRC_ABS_WALLCLOCK || ctx->video_pts_source == PTS_SRC_ABS_WALLCLOCK)
720 abs_wallclock = av_gettime();
722 // Handle Video Frame
725 av_init_packet(&pkt);
726 if (ctx->frameCount % 25 == 0) {
727 unsigned long long qsize = avpacket_queue_size(&ctx->queue);
728 av_log(avctx, AV_LOG_DEBUG,
729 "Frame received (#%lu) - Valid (%liB) - QSize %fMB\n",
731 videoFrame->GetRowBytes() * videoFrame->GetHeight(),
732 (double)qsize / 1024 / 1024);
735 videoFrame->GetBytes(&frameBytes);
736 videoFrame->GetStreamTime(&frameTime, &frameDuration,
737 ctx->video_st->time_base.den);
739 if (videoFrame->GetFlags() & bmdFrameHasNoInputSource) {
740 if (ctx->draw_bars && videoFrame->GetPixelFormat() == bmdFormat8BitYUV) {
742 0xEA80EA80, 0xD292D210, 0xA910A9A5, 0x90229035,
743 0x6ADD6ACA, 0x51EF515A, 0x286D28EF, 0x10801080 };
744 int width = videoFrame->GetWidth();
745 int height = videoFrame->GetHeight();
746 unsigned *p = (unsigned *)frameBytes;
748 for (int y = 0; y < height; y++) {
749 for (int x = 0; x < width; x += 2)
750 *p++ = bars[(x * 8) / width];
755 av_log(avctx, AV_LOG_WARNING, "Frame received (#%lu) - No input signal detected "
756 "- Frames dropped %u\n", ctx->frameCount, ++ctx->dropped);
761 av_log(avctx, AV_LOG_WARNING, "Frame received (#%lu) - Input returned "
762 "- Frames dropped %u\n", ctx->frameCount, ++ctx->dropped);
766 // Handle Timecode (if requested)
767 if (ctx->tc_format) {
768 IDeckLinkTimecode *timecode;
769 if (videoFrame->GetTimecode(ctx->tc_format, &timecode) == S_OK) {
770 const char *tc = NULL;
771 DECKLINK_STR decklink_tc;
772 if (timecode->GetString(&decklink_tc) == S_OK) {
773 tc = DECKLINK_STRDUP(decklink_tc);
774 DECKLINK_FREE(decklink_tc);
778 AVDictionary* metadata_dict = NULL;
780 uint8_t* packed_metadata;
781 if (av_dict_set(&metadata_dict, "timecode", tc, AV_DICT_DONT_STRDUP_VAL) >= 0) {
782 packed_metadata = av_packet_pack_dictionary(metadata_dict, &metadata_len);
783 av_dict_free(&metadata_dict);
784 if (packed_metadata) {
785 if (av_packet_add_side_data(&pkt, AV_PKT_DATA_STRINGS_METADATA, packed_metadata, metadata_len) < 0)
786 av_freep(&packed_metadata);
787 else if (!ctx->tc_seen)
788 ctx->tc_seen = ctx->frameCount;
793 av_log(avctx, AV_LOG_DEBUG, "Unable to find timecode.\n");
798 if (ctx->tc_format && cctx->wait_for_tc && !ctx->tc_seen) {
800 av_log(avctx, AV_LOG_WARNING, "No TC detected yet. wait_for_tc set. Dropping. \n");
801 av_log(avctx, AV_LOG_WARNING, "Frame received (#%lu) - "
802 "- Frames dropped %u\n", ctx->frameCount, ++ctx->dropped);
806 pkt.pts = get_pkt_pts(videoFrame, audioFrame, wallclock, abs_wallclock, ctx->video_pts_source, ctx->video_st->time_base, &initial_video_pts, cctx->copyts);
809 pkt.duration = frameDuration;
810 //To be made sure it still applies
811 pkt.flags |= AV_PKT_FLAG_KEY;
812 pkt.stream_index = ctx->video_st->index;
813 pkt.data = (uint8_t *)frameBytes;
814 pkt.size = videoFrame->GetRowBytes() *
815 videoFrame->GetHeight();
816 //fprintf(stderr,"Video Frame size %d ts %d\n", pkt.size, pkt.pts);
819 IDeckLinkVideoFrameAncillary *vanc;
821 uint8_t txt_buf0[3531]; // 35 * 46 bytes decoded teletext lines + 1 byte data_identifier + 1920 bytes OP47 decode buffer
822 uint8_t *txt_buf = txt_buf0;
824 if (videoFrame->GetAncillaryData(&vanc) == S_OK) {
826 int64_t line_mask = 1;
827 BMDPixelFormat vanc_format = vanc->GetPixelFormat();
828 txt_buf[0] = 0x10; // data_identifier - EBU_data
831 if (ctx->bmd_mode == bmdModePAL && ctx->teletext_lines &&
832 (vanc_format == bmdFormat8BitYUV || vanc_format == bmdFormat10BitYUV)) {
833 av_assert0(videoFrame->GetWidth() == 720);
834 for (i = 6; i < 336; i++, line_mask <<= 1) {
836 if ((ctx->teletext_lines & line_mask) && vanc->GetBufferForVerticalBlankingLine(i, (void**)&buf) == S_OK) {
837 if (vanc_format == bmdFormat8BitYUV)
838 txt_buf = teletext_data_unit_from_vbi_data(i, buf, txt_buf, VBI_PIXFMT_UYVY);
840 txt_buf = teletext_data_unit_from_vbi_data_10bit(i, buf, txt_buf);
847 if (vanc_format == bmdFormat10BitYUV && videoFrame->GetWidth() <= MAX_WIDTH_VANC) {
848 int idx = get_vanc_line_idx(ctx->bmd_mode);
849 for (i = vanc_line_numbers[idx].vanc_start; i <= vanc_line_numbers[idx].vanc_end; i++) {
851 if (vanc->GetBufferForVerticalBlankingLine(i, (void**)&buf) == S_OK) {
852 uint16_t vanc[MAX_WIDTH_VANC];
853 size_t vanc_size = videoFrame->GetWidth();
854 if (ctx->bmd_mode == bmdModeNTSC && videoFrame->GetWidth() * 2 <= MAX_WIDTH_VANC) {
855 vanc_size = vanc_size * 2;
856 unpack_v210(vanc, buf, videoFrame->GetWidth());
858 extract_luma_from_v210(vanc, buf, videoFrame->GetWidth());
860 txt_buf = get_metadata(avctx, vanc, vanc_size,
861 txt_buf, sizeof(txt_buf0) - (txt_buf - txt_buf0), &pkt);
863 if (i == vanc_line_numbers[idx].field0_vanc_end)
864 i = vanc_line_numbers[idx].field1_vanc_start - 1;
868 if (txt_buf - txt_buf0 > 1) {
869 int stuffing_units = (4 - ((45 + txt_buf - txt_buf0) / 46) % 4) % 4;
870 while (stuffing_units--) {
871 memset(txt_buf, 0xff, 46);
872 txt_buf[1] = 0x2c; // data_unit_length
875 av_init_packet(&txt_pkt);
876 txt_pkt.pts = pkt.pts;
877 txt_pkt.dts = pkt.dts;
878 txt_pkt.stream_index = ctx->teletext_st->index;
879 txt_pkt.data = txt_buf0;
880 txt_pkt.size = txt_buf - txt_buf0;
881 if (avpacket_queue_put(&ctx->queue, &txt_pkt) < 0) {
888 pkt.buf = av_buffer_create(pkt.data, pkt.size, decklink_object_free, videoFrame, 0);
890 videoFrame->AddRef();
892 if (avpacket_queue_put(&ctx->queue, &pkt) < 0) {
897 // Handle Audio Frame
900 BMDTimeValue audio_pts;
901 av_init_packet(&pkt);
904 pkt.size = audioFrame->GetSampleFrameCount() * ctx->audio_st->codecpar->channels * (ctx->audio_depth / 8);
905 audioFrame->GetBytes(&audioFrameBytes);
906 audioFrame->GetPacketTime(&audio_pts, ctx->audio_st->time_base.den);
907 pkt.pts = get_pkt_pts(videoFrame, audioFrame, wallclock, abs_wallclock, ctx->audio_pts_source, ctx->audio_st->time_base, &initial_audio_pts, cctx->copyts);
910 //fprintf(stderr,"Audio Frame size %d ts %d\n", pkt.size, pkt.pts);
911 pkt.flags |= AV_PKT_FLAG_KEY;
912 pkt.stream_index = ctx->audio_st->index;
913 pkt.data = (uint8_t *)audioFrameBytes;
915 if (avpacket_queue_put(&ctx->queue, &pkt) < 0) {
923 HRESULT decklink_input_callback::VideoInputFormatChanged(
924 BMDVideoInputFormatChangedEvents events, IDeckLinkDisplayMode *mode,
925 BMDDetectedVideoInputFormatFlags)
927 ctx->bmd_mode = mode->GetDisplayMode();
931 static int decklink_autodetect(struct decklink_cctx *cctx) {
932 struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
933 DECKLINK_BOOL autodetect_supported = false;
936 if (ctx->attr->GetFlag(BMDDeckLinkSupportsInputFormatDetection, &autodetect_supported) != S_OK)
938 if (autodetect_supported == false)
942 ctx->bmd_mode = bmdModeUnknown;
943 if (ctx->dli->EnableVideoInput(AUTODETECT_DEFAULT_MODE,
945 bmdVideoInputEnableFormatDetection) != S_OK) {
949 if (ctx->dli->StartStreams() != S_OK) {
954 for (i = 0; i < 10; i++) {
956 /* Sometimes VideoInputFrameArrived is called without the
957 * bmdFrameHasNoInputSource flag before VideoInputFormatChanged.
958 * So don't break for bmd_mode == AUTODETECT_DEFAULT_MODE. */
959 if (ctx->bmd_mode != bmdModeUnknown &&
960 ctx->bmd_mode != AUTODETECT_DEFAULT_MODE)
964 ctx->dli->PauseStreams();
965 ctx->dli->FlushStreams();
967 if (ctx->bmd_mode != bmdModeUnknown) {
968 cctx->format_code = (char *)av_mallocz(5);
969 if (!cctx->format_code)
971 AV_WB32(cctx->format_code, ctx->bmd_mode);
981 av_cold int ff_decklink_read_close(AVFormatContext *avctx)
983 struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
984 struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
986 if (ctx->capture_started) {
987 ctx->dli->StopStreams();
988 ctx->dli->DisableVideoInput();
989 ctx->dli->DisableAudioInput();
992 ff_decklink_cleanup(avctx);
993 avpacket_queue_end(&ctx->queue);
995 av_freep(&cctx->ctx);
1000 av_cold int ff_decklink_read_header(AVFormatContext *avctx)
1002 struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
1003 struct decklink_ctx *ctx;
1004 class decklink_allocator *allocator;
1005 class decklink_input_callback *input_callback;
1013 ctx = (struct decklink_ctx *) av_mallocz(sizeof(struct decklink_ctx));
1015 return AVERROR(ENOMEM);
1016 ctx->list_devices = cctx->list_devices;
1017 ctx->list_formats = cctx->list_formats;
1018 ctx->teletext_lines = cctx->teletext_lines;
1019 ctx->preroll = cctx->preroll;
1020 ctx->duplex_mode = cctx->duplex_mode;
1021 if (cctx->tc_format > 0 && (unsigned int)cctx->tc_format < FF_ARRAY_ELEMS(decklink_timecode_format_map))
1022 ctx->tc_format = decklink_timecode_format_map[cctx->tc_format];
1023 if (cctx->video_input > 0 && (unsigned int)cctx->video_input < FF_ARRAY_ELEMS(decklink_video_connection_map))
1024 ctx->video_input = decklink_video_connection_map[cctx->video_input];
1025 if (cctx->audio_input > 0 && (unsigned int)cctx->audio_input < FF_ARRAY_ELEMS(decklink_audio_connection_map))
1026 ctx->audio_input = decklink_audio_connection_map[cctx->audio_input];
1027 ctx->audio_pts_source = cctx->audio_pts_source;
1028 ctx->video_pts_source = cctx->video_pts_source;
1029 ctx->draw_bars = cctx->draw_bars;
1030 ctx->audio_depth = cctx->audio_depth;
1033 /* Check audio channel option for valid values: 2, 8 or 16 */
1034 switch (cctx->audio_channels) {
1040 av_log(avctx, AV_LOG_ERROR, "Value of channels option must be one of 2, 8 or 16\n");
1041 return AVERROR(EINVAL);
1044 /* Check audio bit depth option for valid values: 16 or 32 */
1045 switch (cctx->audio_depth) {
1050 av_log(avctx, AV_LOG_ERROR, "Value for audio bit depth option must be either 16 or 32\n");
1051 return AVERROR(EINVAL);
1054 /* List available devices. */
1055 if (ctx->list_devices) {
1056 ff_decklink_list_devices_legacy(avctx, 1, 0);
1057 return AVERROR_EXIT;
1061 av_log(avctx, AV_LOG_WARNING, "The bm_v210 option is deprecated and will be removed. Please use the -raw_format yuv422p10.\n");
1062 cctx->raw_format = MKBETAG('v','2','1','0');
1065 av_strlcpy(fname, avctx->url, sizeof(fname));
1066 tmp=strchr (fname, '@');
1068 av_log(avctx, AV_LOG_WARNING, "The @mode syntax is deprecated and will be removed. Please use the -format_code option.\n");
1069 mode_num = atoi (tmp+1);
1073 ret = ff_decklink_init_device(avctx, fname);
1077 /* Get input device. */
1078 if (ctx->dl->QueryInterface(IID_IDeckLinkInput, (void **) &ctx->dli) != S_OK) {
1079 av_log(avctx, AV_LOG_ERROR, "Could not open input device from '%s'\n",
1085 if (ff_decklink_set_configs(avctx, DIRECTION_IN) < 0) {
1086 av_log(avctx, AV_LOG_ERROR, "Could not set input configuration\n");
1091 /* List supported formats. */
1092 if (ctx->list_formats) {
1093 ff_decklink_list_formats(avctx, DIRECTION_IN);
1098 input_callback = new decklink_input_callback(avctx);
1099 ret = (ctx->dli->SetCallback(input_callback) == S_OK ? 0 : AVERROR_EXTERNAL);
1100 input_callback->Release();
1102 av_log(avctx, AV_LOG_ERROR, "Cannot set input callback\n");
1106 allocator = new decklink_allocator();
1107 ret = (ctx->dli->SetVideoInputFrameMemoryAllocator(allocator) == S_OK ? 0 : AVERROR_EXTERNAL);
1108 allocator->Release();
1110 av_log(avctx, AV_LOG_ERROR, "Cannot set custom memory allocator\n");
1114 if (mode_num == 0 && !cctx->format_code) {
1115 if (decklink_autodetect(cctx) < 0) {
1116 av_log(avctx, AV_LOG_ERROR, "Cannot Autodetect input stream or No signal\n");
1120 av_log(avctx, AV_LOG_INFO, "Autodetected the input mode\n");
1122 if (ff_decklink_set_format(avctx, DIRECTION_IN, mode_num) < 0) {
1123 av_log(avctx, AV_LOG_ERROR, "Could not set mode number %d or format code %s for %s\n",
1124 mode_num, (cctx->format_code) ? cctx->format_code : "(unset)", fname);
1130 if (ctx->teletext_lines && ctx->bmd_mode == bmdModePAL) {
1131 av_log(avctx, AV_LOG_ERROR, "Libzvbi support is needed for capturing SD PAL teletext, please recompile FFmpeg.\n");
1132 ret = AVERROR(ENOSYS);
1137 /* Setup streams. */
1138 st = avformat_new_stream(avctx, NULL);
1140 av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
1141 ret = AVERROR(ENOMEM);
1144 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
1145 st->codecpar->codec_id = cctx->audio_depth == 32 ? AV_CODEC_ID_PCM_S32LE : AV_CODEC_ID_PCM_S16LE;
1146 st->codecpar->sample_rate = bmdAudioSampleRate48kHz;
1147 st->codecpar->channels = cctx->audio_channels;
1148 avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
1151 st = avformat_new_stream(avctx, NULL);
1153 av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
1154 ret = AVERROR(ENOMEM);
1157 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
1158 st->codecpar->width = ctx->bmd_width;
1159 st->codecpar->height = ctx->bmd_height;
1161 st->time_base.den = ctx->bmd_tb_den;
1162 st->time_base.num = ctx->bmd_tb_num;
1163 st->r_frame_rate = av_make_q(st->time_base.den, st->time_base.num);
1165 switch((BMDPixelFormat)cctx->raw_format) {
1166 case bmdFormat8BitYUV:
1167 st->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
1168 st->codecpar->codec_tag = MKTAG('U', 'Y', 'V', 'Y');
1169 st->codecpar->format = AV_PIX_FMT_UYVY422;
1170 st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 16, st->time_base.den, st->time_base.num);
1172 case bmdFormat10BitYUV:
1173 st->codecpar->codec_id = AV_CODEC_ID_V210;
1174 st->codecpar->codec_tag = MKTAG('V','2','1','0');
1175 st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 64, st->time_base.den, st->time_base.num * 3);
1176 st->codecpar->bits_per_coded_sample = 10;
1178 case bmdFormat8BitARGB:
1179 st->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
1180 st->codecpar->format = AV_PIX_FMT_0RGB;
1181 st->codecpar->codec_tag = avcodec_pix_fmt_to_codec_tag((enum AVPixelFormat)st->codecpar->format);
1182 st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 32, st->time_base.den, st->time_base.num);
1184 case bmdFormat8BitBGRA:
1185 st->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
1186 st->codecpar->format = AV_PIX_FMT_BGR0;
1187 st->codecpar->codec_tag = avcodec_pix_fmt_to_codec_tag((enum AVPixelFormat)st->codecpar->format);
1188 st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 32, st->time_base.den, st->time_base.num);
1190 case bmdFormat10BitRGB:
1191 st->codecpar->codec_id = AV_CODEC_ID_R210;
1192 st->codecpar->codec_tag = MKTAG('R','2','1','0');
1193 st->codecpar->format = AV_PIX_FMT_RGB48LE;
1194 st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 30, st->time_base.den, st->time_base.num);
1195 st->codecpar->bits_per_coded_sample = 10;
1198 av_log(avctx, AV_LOG_ERROR, "Raw Format %.4s not supported\n", (char*) &cctx->raw_format);
1199 ret = AVERROR(EINVAL);
1203 switch (ctx->bmd_field_dominance) {
1204 case bmdUpperFieldFirst:
1205 st->codecpar->field_order = AV_FIELD_TT;
1207 case bmdLowerFieldFirst:
1208 st->codecpar->field_order = AV_FIELD_BB;
1210 case bmdProgressiveFrame:
1211 case bmdProgressiveSegmentedFrame:
1212 st->codecpar->field_order = AV_FIELD_PROGRESSIVE;
1216 avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
1220 if (ctx->teletext_lines) {
1221 st = avformat_new_stream(avctx, NULL);
1223 av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
1224 ret = AVERROR(ENOMEM);
1227 st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
1228 st->time_base.den = ctx->bmd_tb_den;
1229 st->time_base.num = ctx->bmd_tb_num;
1230 st->codecpar->codec_id = AV_CODEC_ID_DVB_TELETEXT;
1231 avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
1232 ctx->teletext_st = st;
1235 av_log(avctx, AV_LOG_VERBOSE, "Using %d input audio channels\n", ctx->audio_st->codecpar->channels);
1236 result = ctx->dli->EnableAudioInput(bmdAudioSampleRate48kHz, cctx->audio_depth == 32 ? bmdAudioSampleType32bitInteger : bmdAudioSampleType16bitInteger, ctx->audio_st->codecpar->channels);
1238 if (result != S_OK) {
1239 av_log(avctx, AV_LOG_ERROR, "Cannot enable audio input\n");
1244 result = ctx->dli->EnableVideoInput(ctx->bmd_mode,
1245 (BMDPixelFormat) cctx->raw_format,
1246 bmdVideoInputFlagDefault);
1248 if (result != S_OK) {
1249 av_log(avctx, AV_LOG_ERROR, "Cannot enable video input\n");
1254 avpacket_queue_init (avctx, &ctx->queue);
1256 if (ctx->dli->StartStreams() != S_OK) {
1257 av_log(avctx, AV_LOG_ERROR, "Cannot start input stream\n");
1265 ff_decklink_cleanup(avctx);
1269 int ff_decklink_read_packet(AVFormatContext *avctx, AVPacket *pkt)
1271 struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
1272 struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
1274 avpacket_queue_get(&ctx->queue, pkt, 1);
1276 if (ctx->tc_format && !(av_dict_get(ctx->video_st->metadata, "timecode", NULL, 0))) {
1278 const uint8_t *side_metadata = av_packet_get_side_data(pkt, AV_PKT_DATA_STRINGS_METADATA, &size);
1279 if (side_metadata) {
1280 if (av_packet_unpack_dictionary(side_metadata, size, &ctx->video_st->metadata) < 0)
1281 av_log(avctx, AV_LOG_ERROR, "Unable to set timecode\n");
1288 int ff_decklink_list_input_devices(AVFormatContext *avctx, struct AVDeviceInfoList *device_list)
1290 return ff_decklink_list_devices(avctx, device_list, 1, 0);