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
24 /* Include internal.h first to avoid conflict between winsock.h (used by
25 * DeckLink headers) and winsock2.h (used by libavformat) in MSVC++ builds */
27 #include "libavformat/internal.h"
30 #include <DeckLinkAPI.h>
34 #include "libavformat/avformat.h"
35 #include "libavutil/avassert.h"
36 #include "libavutil/avutil.h"
37 #include "libavutil/common.h"
38 #include "libavutil/imgutils.h"
39 #include "libavutil/intreadwrite.h"
40 #include "libavutil/time.h"
41 #include "libavutil/mathematics.h"
42 #include "libavutil/reverse.h"
49 #include "decklink_common.h"
50 #include "decklink_dec.h"
52 #define MAX_WIDTH_VANC 1920
53 const BMDDisplayMode AUTODETECT_DEFAULT_MODE = bmdModeNTSC;
55 typedef struct VANCLineNumber {
59 int field1_vanc_start;
63 /* These VANC line numbers need not be very accurate. In any case
64 * GetBufferForVerticalBlankingLine() will return an error when invalid
65 * ancillary line number was requested. We just need to make sure that the
66 * entire VANC region is covered, while making sure we don't decode VANC of
67 * another source during switching*/
68 static VANCLineNumber vanc_line_numbers[] = {
71 {bmdModeNTSC, 11, 19, 274, 282},
72 {bmdModeNTSC2398, 11, 19, 274, 282},
73 {bmdModePAL, 7, 22, 320, 335},
74 {bmdModeNTSCp, 11, -1, -1, 39},
75 {bmdModePALp, 7, -1, -1, 45},
79 {bmdModeHD1080p2398, 8, -1, -1, 42},
80 {bmdModeHD1080p24, 8, -1, -1, 42},
81 {bmdModeHD1080p25, 8, -1, -1, 42},
82 {bmdModeHD1080p2997, 8, -1, -1, 42},
83 {bmdModeHD1080p30, 8, -1, -1, 42},
84 {bmdModeHD1080i50, 8, 20, 570, 585},
85 {bmdModeHD1080i5994, 8, 20, 570, 585},
86 {bmdModeHD1080i6000, 8, 20, 570, 585},
87 {bmdModeHD1080p50, 8, -1, -1, 42},
88 {bmdModeHD1080p5994, 8, -1, -1, 42},
89 {bmdModeHD1080p6000, 8, -1, -1, 42},
93 {bmdModeHD720p50, 8, -1, -1, 26},
94 {bmdModeHD720p5994, 8, -1, -1, 26},
95 {bmdModeHD720p60, 8, -1, -1, 26},
97 /* For all other modes, for which we don't support VANC */
98 {bmdModeUnknown, 0, -1, -1, -1}
101 static int get_vanc_line_idx(BMDDisplayMode mode)
104 for (i = 0; i < FF_ARRAY_ELEMS(vanc_line_numbers); i++) {
105 if (mode == vanc_line_numbers[i].mode)
108 /* Return the VANC idx for Unknown mode */
112 static inline void clear_parity_bits(uint16_t *buf, int len) {
114 for (i = 0; i < len; i++)
118 static int check_vanc_parity_checksum(uint16_t *buf, int len, uint16_t checksum) {
120 uint16_t vanc_sum = 0;
121 for (i = 3; i < len - 1; i++) {
124 int p = av_parity(v & 0xff);
125 if ((!!p ^ !!(v & 0x100)) || (np != 1 && np != 2)) {
126 // Parity check failed
132 vanc_sum |= ((~vanc_sum & 0x100) << 1);
133 if (checksum != vanc_sum) {
134 // Checksum verification failed
140 /* The 10-bit VANC data is packed in V210, we only need the luma component. */
141 static void extract_luma_from_v210(uint16_t *dst, const uint8_t *src, int width)
144 for (i = 0; i < width / 3; i++) {
145 *dst++ = (src[1] >> 2) + ((src[2] & 15) << 6);
146 *dst++ = src[4] + ((src[5] & 3) << 8);
147 *dst++ = (src[6] >> 4) + ((src[7] & 63) << 4);
152 static void unpack_v210(uint16_t *dst, const uint8_t *src, int width)
155 for (i = 0; i < width * 2 / 3; i++) {
156 *dst++ = src[0] + ((src[1] & 3) << 8);
157 *dst++ = (src[1] >> 2) + ((src[2] & 15) << 6);
158 *dst++ = (src[2] >> 4) + ((src[3] & 63) << 4);
163 static uint8_t calc_parity_and_line_offset(int line)
165 uint8_t ret = (line < 313) << 5;
166 if (line >= 7 && line <= 22)
168 if (line >= 320 && line <= 335)
173 static void fill_data_unit_head(int line, uint8_t *tgt)
175 tgt[0] = 0x02; // data_unit_id
176 tgt[1] = 0x2c; // data_unit_length
177 tgt[2] = calc_parity_and_line_offset(line); // field_parity, line_offset
178 tgt[3] = 0xe4; // framing code
182 static uint8_t* teletext_data_unit_from_vbi_data(int line, uint8_t *src, uint8_t *tgt, vbi_pixfmt fmt)
184 vbi_bit_slicer slicer;
186 vbi_bit_slicer_init(&slicer, 720, 13500000, 6937500, 6937500, 0x00aaaae4, 0xffff, 18, 6, 42 * 8, VBI_MODULATION_NRZ_MSB, fmt);
188 if (vbi_bit_slice(&slicer, src, tgt + 4) == FALSE)
191 fill_data_unit_head(line, tgt);
196 static uint8_t* teletext_data_unit_from_vbi_data_10bit(int line, uint8_t *src, uint8_t *tgt)
200 uint8_t *pend = y + 720;
201 /* The 10-bit VBI data is packed in V210, but libzvbi only supports 8-bit,
202 * so we extract the 8 MSBs of the luma component, that is enough for
203 * teletext bit slicing. */
205 *py++ = (src[1] >> 4) + ((src[2] & 15) << 4);
206 *py++ = (src[4] >> 2) + ((src[5] & 3 ) << 6);
207 *py++ = (src[6] >> 6) + ((src[7] & 63) << 2);
210 return teletext_data_unit_from_vbi_data(line, y, tgt, VBI_PIXFMT_YUV420);
214 static uint8_t* teletext_data_unit_from_op47_vbi_packet(int line, uint16_t *py, uint8_t *tgt)
218 if (py[0] != 0x255 || py[1] != 0x255 || py[2] != 0x227)
221 fill_data_unit_head(line, tgt);
226 for (i = 0; i < 42; i++)
227 *tgt++ = ff_reverse[py[i] & 255];
232 static int linemask_matches(int line, int64_t mask)
235 if (line >= 6 && line <= 22)
237 if (line >= 318 && line <= 335)
238 shift = line - 318 + 17;
239 return shift >= 0 && ((1ULL << shift) & mask);
242 static uint8_t* teletext_data_unit_from_op47_data(uint16_t *py, uint16_t *pend, uint8_t *tgt, int64_t wanted_lines)
245 if (py[0] == 0x151 && py[1] == 0x115 && py[3] == 0x102) { // identifier, identifier, format code for WST teletext
246 uint16_t *descriptors = py + 4;
249 for (i = 0; i < 5 && py < pend - 45; i++, py += 45) {
250 int line = (descriptors[i] & 31) + (!(descriptors[i] & 128)) * 313;
251 if (line && linemask_matches(line, wanted_lines))
252 tgt = teletext_data_unit_from_op47_vbi_packet(line, py, tgt);
259 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)
261 uint16_t did = py[0]; // data id
262 uint16_t sdid = py[1]; // secondary data id
263 uint16_t dc = py[2] & 255; // data count
265 pend = FFMIN(pend, py + dc);
266 if (did == 0x143 && sdid == 0x102) { // subtitle distribution packet
267 tgt = teletext_data_unit_from_op47_data(py, pend, tgt, wanted_lines);
268 } else if (allow_multipacket && did == 0x143 && sdid == 0x203) { // VANC multipacket
269 py += 2; // priority, line/field
270 while (py < pend - 3) {
271 tgt = teletext_data_unit_from_ancillary_packet(py, pend, tgt, wanted_lines, 0);
272 py += 4 + (py[2] & 255); // ndid, nsdid, ndc, line/field
278 static uint8_t *vanc_to_cc(AVFormatContext *avctx, uint16_t *buf, size_t words,
281 size_t i, len = (buf[5] & 0xff) + 6 + 1;
282 uint8_t cdp_sum, rate;
285 uint16_t *cdp = &buf[6]; // CDP follows
286 if (cdp[0] != 0x96 || cdp[1] != 0x69) {
287 av_log(avctx, AV_LOG_WARNING, "Invalid CDP header 0x%.2x 0x%.2x\n", cdp[0], cdp[1]);
291 len -= 7; // remove VANC header and checksum
294 av_log(avctx, AV_LOG_WARNING, "CDP len %d != %zu\n", cdp[2], len);
299 for (i = 0; i < len - 1; i++)
301 cdp_sum = cdp_sum ? 256 - cdp_sum : 0;
302 if (cdp[len - 1] != cdp_sum) {
303 av_log(avctx, AV_LOG_WARNING, "CDP checksum invalid 0x%.4x != 0x%.4x\n", cdp_sum, cdp[len-1]);
308 if (!(rate & 0x0f)) {
309 av_log(avctx, AV_LOG_WARNING, "CDP frame rate invalid (0x%.2x)\n", rate);
314 av_log(avctx, AV_LOG_WARNING, "CDP frame rate invalid (0x%.2x)\n", rate);
318 if (!(cdp[4] & 0x43)) /* ccdata_present | caption_service_active | reserved */ {
319 av_log(avctx, AV_LOG_WARNING, "CDP flags invalid (0x%.2x)\n", cdp[4]);
323 hdr = (cdp[5] << 8) | cdp[6];
324 if (cdp[7] != 0x72) /* ccdata_id */ {
325 av_log(avctx, AV_LOG_WARNING, "Invalid ccdata_id 0x%.2x\n", cdp[7]);
330 if (!(cc_count & 0xe0)) {
331 av_log(avctx, AV_LOG_WARNING, "Invalid cc_count 0x%.2x\n", cc_count);
336 if ((len - 13) < cc_count * 3) {
337 av_log(avctx, AV_LOG_WARNING, "Invalid cc_count %d (> %zu)\n", cc_count * 3, len - 13);
341 if (cdp[len - 4] != 0x74) /* footer id */ {
342 av_log(avctx, AV_LOG_WARNING, "Invalid footer id 0x%.2x\n", cdp[len-4]);
346 ftr = (cdp[len - 3] << 8) | cdp[len - 2];
348 av_log(avctx, AV_LOG_WARNING, "Header 0x%.4x != Footer 0x%.4x\n", hdr, ftr);
352 cc = (uint8_t *)av_malloc(cc_count * 3);
354 av_log(avctx, AV_LOG_WARNING, "CC - av_malloc failed for cc_count = %d\n", cc_count);
358 for (size_t i = 0; i < cc_count; i++) {
359 cc[3*i + 0] = cdp[9 + 3*i+0] /* & 3 */;
360 cc[3*i + 1] = cdp[9 + 3*i+1];
361 cc[3*i + 2] = cdp[9 + 3*i+2];
368 static uint8_t *get_metadata(AVFormatContext *avctx, uint16_t *buf, size_t width,
369 uint8_t *tgt, size_t tgt_size, AVPacket *pkt)
371 decklink_cctx *cctx = (struct decklink_cctx *) avctx->priv_data;
372 uint16_t *max_buf = buf + width;
374 while (buf < max_buf - 6) {
376 uint16_t did = buf[3] & 0xFF; // data id
377 uint16_t sdid = buf[4] & 0xFF; // secondary data id
378 /* Check for VANC header */
379 if (buf[0] != 0 || buf[1] != 0x3ff || buf[2] != 0x3ff) {
383 len = (buf[5] & 0xff) + 6 + 1;
384 if (len > max_buf - buf) {
385 av_log(avctx, AV_LOG_WARNING, "Data Count (%d) > data left (%zu)\n",
390 if (did == 0x43 && (sdid == 0x02 || sdid == 0x03) && cctx->teletext_lines &&
391 width == 1920 && tgt_size >= 1920) {
392 if (check_vanc_parity_checksum(buf, len, buf[len - 1]) < 0) {
393 av_log(avctx, AV_LOG_WARNING, "VANC parity or checksum incorrect\n");
396 tgt = teletext_data_unit_from_ancillary_packet(buf + 3, buf + len, tgt, cctx->teletext_lines, 1);
397 } else if (did == 0x61 && sdid == 0x01) {
398 unsigned int data_len;
400 if (check_vanc_parity_checksum(buf, len, buf[len - 1]) < 0) {
401 av_log(avctx, AV_LOG_WARNING, "VANC parity or checksum incorrect\n");
404 clear_parity_bits(buf, len);
405 data = vanc_to_cc(avctx, buf, width, data_len);
407 if (av_packet_add_side_data(pkt, AV_PKT_DATA_A53_CC, data, data_len) < 0)
411 av_log(avctx, AV_LOG_DEBUG, "Unknown meta data DID = 0x%.2x SDID = 0x%.2x\n",
421 static void avpacket_queue_init(AVFormatContext *avctx, AVPacketQueue *q)
423 struct decklink_cctx *ctx = (struct decklink_cctx *)avctx->priv_data;
424 memset(q, 0, sizeof(AVPacketQueue));
425 pthread_mutex_init(&q->mutex, NULL);
426 pthread_cond_init(&q->cond, NULL);
428 q->max_q_size = ctx->queue_size;
431 static void avpacket_queue_flush(AVPacketQueue *q)
433 AVPacketList *pkt, *pkt1;
435 pthread_mutex_lock(&q->mutex);
436 for (pkt = q->first_pkt; pkt != NULL; pkt = pkt1) {
438 av_packet_unref(&pkt->pkt);
445 pthread_mutex_unlock(&q->mutex);
448 static void avpacket_queue_end(AVPacketQueue *q)
450 avpacket_queue_flush(q);
451 pthread_mutex_destroy(&q->mutex);
452 pthread_cond_destroy(&q->cond);
455 static unsigned long long avpacket_queue_size(AVPacketQueue *q)
457 unsigned long long size;
458 pthread_mutex_lock(&q->mutex);
460 pthread_mutex_unlock(&q->mutex);
464 static int avpacket_queue_put(AVPacketQueue *q, AVPacket *pkt)
469 // Drop Packet if queue size is > maximum queue size
470 if (avpacket_queue_size(q) > (uint64_t)q->max_q_size) {
471 av_log(q->avctx, AV_LOG_WARNING, "Decklink input buffer overrun!\n");
475 pkt1 = (AVPacketList *)av_mallocz(sizeof(AVPacketList));
479 ret = av_packet_ref(&pkt1->pkt, pkt);
480 av_packet_unref(pkt);
487 pthread_mutex_lock(&q->mutex);
492 q->last_pkt->next = pkt1;
497 q->size += pkt1->pkt.size + sizeof(*pkt1);
499 pthread_cond_signal(&q->cond);
501 pthread_mutex_unlock(&q->mutex);
505 static int avpacket_queue_get(AVPacketQueue *q, AVPacket *pkt, int block)
510 pthread_mutex_lock(&q->mutex);
515 q->first_pkt = pkt1->next;
520 q->size -= pkt1->pkt.size + sizeof(*pkt1);
529 pthread_cond_wait(&q->cond, &q->mutex);
532 pthread_mutex_unlock(&q->mutex);
536 class decklink_input_callback : public IDeckLinkInputCallback
539 decklink_input_callback(AVFormatContext *_avctx);
540 ~decklink_input_callback();
542 virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv) { return E_NOINTERFACE; }
543 virtual ULONG STDMETHODCALLTYPE AddRef(void);
544 virtual ULONG STDMETHODCALLTYPE Release(void);
545 virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents, IDeckLinkDisplayMode*, BMDDetectedVideoInputFormatFlags);
546 virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame*, IDeckLinkAudioInputPacket*);
550 pthread_mutex_t m_mutex;
551 AVFormatContext *avctx;
554 int64_t initial_video_pts;
555 int64_t initial_audio_pts;
558 decklink_input_callback::decklink_input_callback(AVFormatContext *_avctx) : m_refCount(0)
561 decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
562 ctx = (struct decklink_ctx *)cctx->ctx;
564 initial_audio_pts = initial_video_pts = AV_NOPTS_VALUE;
565 pthread_mutex_init(&m_mutex, NULL);
568 decklink_input_callback::~decklink_input_callback()
570 pthread_mutex_destroy(&m_mutex);
573 ULONG decklink_input_callback::AddRef(void)
575 pthread_mutex_lock(&m_mutex);
577 pthread_mutex_unlock(&m_mutex);
579 return (ULONG)m_refCount;
582 ULONG decklink_input_callback::Release(void)
584 pthread_mutex_lock(&m_mutex);
586 pthread_mutex_unlock(&m_mutex);
588 if (m_refCount == 0) {
593 return (ULONG)m_refCount;
596 static int64_t get_pkt_pts(IDeckLinkVideoInputFrame *videoFrame,
597 IDeckLinkAudioInputPacket *audioFrame,
599 int64_t abs_wallclock,
600 DecklinkPtsSource pts_src,
601 AVRational time_base, int64_t *initial_pts,
604 int64_t pts = AV_NOPTS_VALUE;
605 BMDTimeValue bmd_pts;
606 BMDTimeValue bmd_duration;
607 HRESULT res = E_INVALIDARG;
611 res = audioFrame->GetPacketTime(&bmd_pts, time_base.den);
615 res = videoFrame->GetStreamTime(&bmd_pts, &bmd_duration, time_base.den);
617 case PTS_SRC_REFERENCE:
619 res = videoFrame->GetHardwareReferenceTimestamp(time_base.den, &bmd_pts, &bmd_duration);
621 case PTS_SRC_WALLCLOCK:
623 case PTS_SRC_ABS_WALLCLOCK:
625 /* MSVC does not support compound literals like AV_TIME_BASE_Q
626 * in C++ code (compiler error C4576) */
629 timebase.den = AV_TIME_BASE;
630 if (pts_src == PTS_SRC_WALLCLOCK)
631 pts = av_rescale_q(wallclock, timebase, time_base);
633 pts = av_rescale_q(abs_wallclock, timebase, time_base);
638 pts = bmd_pts / time_base.num;
641 if (pts != AV_NOPTS_VALUE && *initial_pts == AV_NOPTS_VALUE)
643 if (*initial_pts != AV_NOPTS_VALUE)
650 HRESULT decklink_input_callback::VideoInputFrameArrived(
651 IDeckLinkVideoInputFrame *videoFrame, IDeckLinkAudioInputPacket *audioFrame)
654 void *audioFrameBytes;
655 BMDTimeValue frameTime;
656 BMDTimeValue frameDuration;
657 int64_t wallclock = 0, abs_wallclock = 0;
658 struct decklink_cctx *cctx = (struct decklink_cctx *) avctx->priv_data;
660 if (ctx->autodetect) {
661 if (videoFrame && !(videoFrame->GetFlags() & bmdFrameHasNoInputSource) &&
662 ctx->bmd_mode == bmdModeUnknown)
664 ctx->bmd_mode = AUTODETECT_DEFAULT_MODE;
670 if (ctx->audio_pts_source == PTS_SRC_WALLCLOCK || ctx->video_pts_source == PTS_SRC_WALLCLOCK)
671 wallclock = av_gettime_relative();
672 if (ctx->audio_pts_source == PTS_SRC_ABS_WALLCLOCK || ctx->video_pts_source == PTS_SRC_ABS_WALLCLOCK)
673 abs_wallclock = av_gettime();
675 // Handle Video Frame
678 av_init_packet(&pkt);
679 if (ctx->frameCount % 25 == 0) {
680 unsigned long long qsize = avpacket_queue_size(&ctx->queue);
681 av_log(avctx, AV_LOG_DEBUG,
682 "Frame received (#%lu) - Valid (%liB) - QSize %fMB\n",
684 videoFrame->GetRowBytes() * videoFrame->GetHeight(),
685 (double)qsize / 1024 / 1024);
688 videoFrame->GetBytes(&frameBytes);
689 videoFrame->GetStreamTime(&frameTime, &frameDuration,
690 ctx->video_st->time_base.den);
692 if (videoFrame->GetFlags() & bmdFrameHasNoInputSource) {
693 if (ctx->draw_bars && videoFrame->GetPixelFormat() == bmdFormat8BitYUV) {
695 0xEA80EA80, 0xD292D210, 0xA910A9A5, 0x90229035,
696 0x6ADD6ACA, 0x51EF515A, 0x286D28EF, 0x10801080 };
697 int width = videoFrame->GetWidth();
698 int height = videoFrame->GetHeight();
699 unsigned *p = (unsigned *)frameBytes;
701 for (int y = 0; y < height; y++) {
702 for (int x = 0; x < width; x += 2)
703 *p++ = bars[(x * 8) / width];
708 av_log(avctx, AV_LOG_WARNING, "Frame received (#%lu) - No input signal detected "
709 "- Frames dropped %u\n", ctx->frameCount, ++ctx->dropped);
714 av_log(avctx, AV_LOG_WARNING, "Frame received (#%lu) - Input returned "
715 "- Frames dropped %u\n", ctx->frameCount, ++ctx->dropped);
720 pkt.pts = get_pkt_pts(videoFrame, audioFrame, wallclock, abs_wallclock, ctx->video_pts_source, ctx->video_st->time_base, &initial_video_pts, cctx->copyts);
723 pkt.duration = frameDuration;
724 //To be made sure it still applies
725 pkt.flags |= AV_PKT_FLAG_KEY;
726 pkt.stream_index = ctx->video_st->index;
727 pkt.data = (uint8_t *)frameBytes;
728 pkt.size = videoFrame->GetRowBytes() *
729 videoFrame->GetHeight();
730 //fprintf(stderr,"Video Frame size %d ts %d\n", pkt.size, pkt.pts);
733 IDeckLinkVideoFrameAncillary *vanc;
735 uint8_t txt_buf0[3531]; // 35 * 46 bytes decoded teletext lines + 1 byte data_identifier + 1920 bytes OP47 decode buffer
736 uint8_t *txt_buf = txt_buf0;
738 if (videoFrame->GetAncillaryData(&vanc) == S_OK) {
740 int64_t line_mask = 1;
741 BMDPixelFormat vanc_format = vanc->GetPixelFormat();
742 txt_buf[0] = 0x10; // data_identifier - EBU_data
745 if (ctx->bmd_mode == bmdModePAL && ctx->teletext_lines &&
746 (vanc_format == bmdFormat8BitYUV || vanc_format == bmdFormat10BitYUV)) {
747 av_assert0(videoFrame->GetWidth() == 720);
748 for (i = 6; i < 336; i++, line_mask <<= 1) {
750 if ((ctx->teletext_lines & line_mask) && vanc->GetBufferForVerticalBlankingLine(i, (void**)&buf) == S_OK) {
751 if (vanc_format == bmdFormat8BitYUV)
752 txt_buf = teletext_data_unit_from_vbi_data(i, buf, txt_buf, VBI_PIXFMT_UYVY);
754 txt_buf = teletext_data_unit_from_vbi_data_10bit(i, buf, txt_buf);
761 if (vanc_format == bmdFormat10BitYUV && videoFrame->GetWidth() <= MAX_WIDTH_VANC) {
762 int idx = get_vanc_line_idx(ctx->bmd_mode);
763 for (i = vanc_line_numbers[idx].vanc_start; i <= vanc_line_numbers[idx].vanc_end; i++) {
765 if (vanc->GetBufferForVerticalBlankingLine(i, (void**)&buf) == S_OK) {
766 uint16_t vanc[MAX_WIDTH_VANC];
767 size_t vanc_size = videoFrame->GetWidth();
768 if (ctx->bmd_mode == bmdModeNTSC && videoFrame->GetWidth() * 2 <= MAX_WIDTH_VANC) {
769 vanc_size = vanc_size * 2;
770 unpack_v210(vanc, buf, videoFrame->GetWidth());
772 extract_luma_from_v210(vanc, buf, videoFrame->GetWidth());
774 txt_buf = get_metadata(avctx, vanc, vanc_size,
775 txt_buf, sizeof(txt_buf0) - (txt_buf - txt_buf0), &pkt);
777 if (i == vanc_line_numbers[idx].field0_vanc_end)
778 i = vanc_line_numbers[idx].field1_vanc_start - 1;
782 if (txt_buf - txt_buf0 > 1) {
783 int stuffing_units = (4 - ((45 + txt_buf - txt_buf0) / 46) % 4) % 4;
784 while (stuffing_units--) {
785 memset(txt_buf, 0xff, 46);
786 txt_buf[1] = 0x2c; // data_unit_length
789 av_init_packet(&txt_pkt);
790 txt_pkt.pts = pkt.pts;
791 txt_pkt.dts = pkt.dts;
792 txt_pkt.stream_index = ctx->teletext_st->index;
793 txt_pkt.data = txt_buf0;
794 txt_pkt.size = txt_buf - txt_buf0;
795 if (avpacket_queue_put(&ctx->queue, &txt_pkt) < 0) {
802 if (avpacket_queue_put(&ctx->queue, &pkt) < 0) {
807 // Handle Audio Frame
810 BMDTimeValue audio_pts;
811 av_init_packet(&pkt);
814 pkt.size = audioFrame->GetSampleFrameCount() * ctx->audio_st->codecpar->channels * (ctx->audio_depth / 8);
815 audioFrame->GetBytes(&audioFrameBytes);
816 audioFrame->GetPacketTime(&audio_pts, ctx->audio_st->time_base.den);
817 pkt.pts = get_pkt_pts(videoFrame, audioFrame, wallclock, abs_wallclock, ctx->audio_pts_source, ctx->audio_st->time_base, &initial_audio_pts, cctx->copyts);
820 //fprintf(stderr,"Audio Frame size %d ts %d\n", pkt.size, pkt.pts);
821 pkt.flags |= AV_PKT_FLAG_KEY;
822 pkt.stream_index = ctx->audio_st->index;
823 pkt.data = (uint8_t *)audioFrameBytes;
825 if (avpacket_queue_put(&ctx->queue, &pkt) < 0) {
833 HRESULT decklink_input_callback::VideoInputFormatChanged(
834 BMDVideoInputFormatChangedEvents events, IDeckLinkDisplayMode *mode,
835 BMDDetectedVideoInputFormatFlags)
837 ctx->bmd_mode = mode->GetDisplayMode();
841 static int decklink_autodetect(struct decklink_cctx *cctx) {
842 struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
843 DECKLINK_BOOL autodetect_supported = false;
846 if (ctx->attr->GetFlag(BMDDeckLinkSupportsInputFormatDetection, &autodetect_supported) != S_OK)
848 if (autodetect_supported == false)
852 ctx->bmd_mode = bmdModeUnknown;
853 if (ctx->dli->EnableVideoInput(AUTODETECT_DEFAULT_MODE,
855 bmdVideoInputEnableFormatDetection) != S_OK) {
859 if (ctx->dli->StartStreams() != S_OK) {
864 for (i = 0; i < 10; i++) {
866 /* Sometimes VideoInputFrameArrived is called without the
867 * bmdFrameHasNoInputSource flag before VideoInputFormatChanged.
868 * So don't break for bmd_mode == AUTODETECT_DEFAULT_MODE. */
869 if (ctx->bmd_mode != bmdModeUnknown &&
870 ctx->bmd_mode != AUTODETECT_DEFAULT_MODE)
874 ctx->dli->PauseStreams();
875 ctx->dli->FlushStreams();
877 if (ctx->bmd_mode != bmdModeUnknown) {
878 cctx->format_code = (char *)av_mallocz(5);
879 if (!cctx->format_code)
881 AV_WB32(cctx->format_code, ctx->bmd_mode);
891 av_cold int ff_decklink_read_close(AVFormatContext *avctx)
893 struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
894 struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
896 if (ctx->capture_started) {
897 ctx->dli->StopStreams();
898 ctx->dli->DisableVideoInput();
899 ctx->dli->DisableAudioInput();
902 ff_decklink_cleanup(avctx);
903 avpacket_queue_end(&ctx->queue);
905 av_freep(&cctx->ctx);
910 av_cold int ff_decklink_read_header(AVFormatContext *avctx)
912 struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
913 struct decklink_ctx *ctx;
921 ctx = (struct decklink_ctx *) av_mallocz(sizeof(struct decklink_ctx));
923 return AVERROR(ENOMEM);
924 ctx->list_devices = cctx->list_devices;
925 ctx->list_formats = cctx->list_formats;
926 ctx->teletext_lines = cctx->teletext_lines;
927 ctx->preroll = cctx->preroll;
928 ctx->duplex_mode = cctx->duplex_mode;
929 if (cctx->video_input > 0 && (unsigned int)cctx->video_input < FF_ARRAY_ELEMS(decklink_video_connection_map))
930 ctx->video_input = decklink_video_connection_map[cctx->video_input];
931 if (cctx->audio_input > 0 && (unsigned int)cctx->audio_input < FF_ARRAY_ELEMS(decklink_audio_connection_map))
932 ctx->audio_input = decklink_audio_connection_map[cctx->audio_input];
933 ctx->audio_pts_source = cctx->audio_pts_source;
934 ctx->video_pts_source = cctx->video_pts_source;
935 ctx->draw_bars = cctx->draw_bars;
936 ctx->audio_depth = cctx->audio_depth;
939 /* Check audio channel option for valid values: 2, 8 or 16 */
940 switch (cctx->audio_channels) {
946 av_log(avctx, AV_LOG_ERROR, "Value of channels option must be one of 2, 8 or 16\n");
947 return AVERROR(EINVAL);
950 /* Check audio bit depth option for valid values: 16 or 32 */
951 switch (cctx->audio_depth) {
956 av_log(avctx, AV_LOG_ERROR, "Value for audio bit depth option must be either 16 or 32\n");
957 return AVERROR(EINVAL);
960 /* List available devices. */
961 if (ctx->list_devices) {
962 ff_decklink_list_devices_legacy(avctx, 1, 0);
967 av_log(avctx, AV_LOG_WARNING, "The bm_v210 option is deprecated and will be removed. Please use the -raw_format yuv422p10.\n");
968 cctx->raw_format = MKBETAG('v','2','1','0');
971 av_strlcpy(fname, avctx->url, sizeof(fname));
972 tmp=strchr (fname, '@');
974 av_log(avctx, AV_LOG_WARNING, "The @mode syntax is deprecated and will be removed. Please use the -format_code option.\n");
975 mode_num = atoi (tmp+1);
979 ret = ff_decklink_init_device(avctx, fname);
983 /* Get input device. */
984 if (ctx->dl->QueryInterface(IID_IDeckLinkInput, (void **) &ctx->dli) != S_OK) {
985 av_log(avctx, AV_LOG_ERROR, "Could not open input device from '%s'\n",
991 /* List supported formats. */
992 if (ctx->list_formats) {
993 ff_decklink_list_formats(avctx, DIRECTION_IN);
998 if (ff_decklink_set_configs(avctx, DIRECTION_IN) < 0) {
999 av_log(avctx, AV_LOG_ERROR, "Could not set input configuration\n");
1004 ctx->input_callback = new decklink_input_callback(avctx);
1005 ctx->dli->SetCallback(ctx->input_callback);
1007 if (mode_num == 0 && !cctx->format_code) {
1008 if (decklink_autodetect(cctx) < 0) {
1009 av_log(avctx, AV_LOG_ERROR, "Cannot Autodetect input stream or No signal\n");
1013 av_log(avctx, AV_LOG_INFO, "Autodetected the input mode\n");
1015 if (ff_decklink_set_format(avctx, DIRECTION_IN, mode_num) < 0) {
1016 av_log(avctx, AV_LOG_ERROR, "Could not set mode number %d or format code %s for %s\n",
1017 mode_num, (cctx->format_code) ? cctx->format_code : "(unset)", fname);
1023 if (ctx->teletext_lines && ctx->bmd_mode == bmdModePAL) {
1024 av_log(avctx, AV_LOG_ERROR, "Libzvbi support is needed for capturing SD PAL teletext, please recompile FFmpeg.\n");
1025 ret = AVERROR(ENOSYS);
1030 /* Setup streams. */
1031 st = avformat_new_stream(avctx, NULL);
1033 av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
1034 ret = AVERROR(ENOMEM);
1037 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
1038 st->codecpar->codec_id = cctx->audio_depth == 32 ? AV_CODEC_ID_PCM_S32LE : AV_CODEC_ID_PCM_S16LE;
1039 st->codecpar->sample_rate = bmdAudioSampleRate48kHz;
1040 st->codecpar->channels = cctx->audio_channels;
1041 avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
1044 st = avformat_new_stream(avctx, NULL);
1046 av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
1047 ret = AVERROR(ENOMEM);
1050 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
1051 st->codecpar->width = ctx->bmd_width;
1052 st->codecpar->height = ctx->bmd_height;
1054 st->time_base.den = ctx->bmd_tb_den;
1055 st->time_base.num = ctx->bmd_tb_num;
1056 st->r_frame_rate = av_make_q(st->time_base.den, st->time_base.num);
1058 switch((BMDPixelFormat)cctx->raw_format) {
1059 case bmdFormat8BitYUV:
1060 st->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
1061 st->codecpar->codec_tag = MKTAG('U', 'Y', 'V', 'Y');
1062 st->codecpar->format = AV_PIX_FMT_UYVY422;
1063 st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 16, st->time_base.den, st->time_base.num);
1065 case bmdFormat10BitYUV:
1066 st->codecpar->codec_id = AV_CODEC_ID_V210;
1067 st->codecpar->codec_tag = MKTAG('V','2','1','0');
1068 st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 64, st->time_base.den, st->time_base.num * 3);
1069 st->codecpar->bits_per_coded_sample = 10;
1071 case bmdFormat8BitARGB:
1072 st->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
1073 st->codecpar->codec_tag = avcodec_pix_fmt_to_codec_tag((enum AVPixelFormat)st->codecpar->format);
1074 st->codecpar->format = AV_PIX_FMT_0RGB;
1075 st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 32, st->time_base.den, st->time_base.num);
1077 case bmdFormat8BitBGRA:
1078 st->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
1079 st->codecpar->codec_tag = avcodec_pix_fmt_to_codec_tag((enum AVPixelFormat)st->codecpar->format);
1080 st->codecpar->format = AV_PIX_FMT_BGR0;
1081 st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 32, st->time_base.den, st->time_base.num);
1083 case bmdFormat10BitRGB:
1084 st->codecpar->codec_id = AV_CODEC_ID_R210;
1085 st->codecpar->codec_tag = MKTAG('R','2','1','0');
1086 st->codecpar->format = AV_PIX_FMT_RGB48LE;
1087 st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 30, st->time_base.den, st->time_base.num);
1088 st->codecpar->bits_per_coded_sample = 10;
1091 av_log(avctx, AV_LOG_ERROR, "Raw Format %.4s not supported\n", (char*) &cctx->raw_format);
1092 ret = AVERROR(EINVAL);
1096 switch (ctx->bmd_field_dominance) {
1097 case bmdUpperFieldFirst:
1098 st->codecpar->field_order = AV_FIELD_TT;
1100 case bmdLowerFieldFirst:
1101 st->codecpar->field_order = AV_FIELD_BB;
1103 case bmdProgressiveFrame:
1104 case bmdProgressiveSegmentedFrame:
1105 st->codecpar->field_order = AV_FIELD_PROGRESSIVE;
1109 avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
1113 if (ctx->teletext_lines) {
1114 st = avformat_new_stream(avctx, NULL);
1116 av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
1117 ret = AVERROR(ENOMEM);
1120 st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
1121 st->time_base.den = ctx->bmd_tb_den;
1122 st->time_base.num = ctx->bmd_tb_num;
1123 st->codecpar->codec_id = AV_CODEC_ID_DVB_TELETEXT;
1124 avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
1125 ctx->teletext_st = st;
1128 av_log(avctx, AV_LOG_VERBOSE, "Using %d input audio channels\n", ctx->audio_st->codecpar->channels);
1129 result = ctx->dli->EnableAudioInput(bmdAudioSampleRate48kHz, cctx->audio_depth == 32 ? bmdAudioSampleType32bitInteger : bmdAudioSampleType16bitInteger, ctx->audio_st->codecpar->channels);
1131 if (result != S_OK) {
1132 av_log(avctx, AV_LOG_ERROR, "Cannot enable audio input\n");
1137 result = ctx->dli->EnableVideoInput(ctx->bmd_mode,
1138 (BMDPixelFormat) cctx->raw_format,
1139 bmdVideoInputFlagDefault);
1141 if (result != S_OK) {
1142 av_log(avctx, AV_LOG_ERROR, "Cannot enable video input\n");
1147 avpacket_queue_init (avctx, &ctx->queue);
1149 if (ctx->dli->StartStreams() != S_OK) {
1150 av_log(avctx, AV_LOG_ERROR, "Cannot start input stream\n");
1158 ff_decklink_cleanup(avctx);
1162 int ff_decklink_read_packet(AVFormatContext *avctx, AVPacket *pkt)
1164 struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
1165 struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
1167 avpacket_queue_get(&ctx->queue, pkt, 1);
1172 int ff_decklink_list_input_devices(AVFormatContext *avctx, struct AVDeviceInfoList *device_list)
1174 return ff_decklink_list_devices(avctx, device_list, 1, 0);