FFmpeg
Loading...
Searching...
No Matches
decklink_dec.cpp
Go to the documentation of this file.
1/*
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.
6 *
7 * This file is part of FFmpeg.
8 *
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.
13 *
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.
18 *
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
22 */
23
24#include <atomic>
25#include <vector>
26using std::atomic;
27
28/* Include internal.h first to avoid conflict between winsock.h (used by
29 * DeckLink headers) and winsock2.h (used by libavformat) in MSVC++ builds */
30extern "C" {
32}
33
34#include <DeckLinkAPIVersion.h>
35#include <DeckLinkAPI.h>
36#if BLACKMAGIC_DECKLINK_API_VERSION >= 0x0e030000
37#include <DeckLinkAPI_v14_2_1.h>
38#endif
39
40extern "C" {
41#include "config.h"
44#include "libavutil/avassert.h"
45#include "libavutil/avutil.h"
46#include "libavutil/common.h"
47#include "libavutil/internal.h"
48#include "libavutil/imgutils.h"
50#include "libavutil/time.h"
51#include "libavutil/timecode.h"
53#include "libavutil/reverse.h"
54#include "avdevice.h"
55#if CONFIG_LIBZVBI
56#include <libzvbi.h>
57#endif
58}
59
60#include "decklink_common.h"
61#include "decklink_dec.h"
62
63#define MAX_WIDTH_VANC 1920
64const BMDDisplayMode AUTODETECT_DEFAULT_MODE = bmdModeNTSC;
65
73
74/* These VANC line numbers need not be very accurate. In any case
75 * GetBufferForVerticalBlankingLine() will return an error when invalid
76 * ancillary line number was requested. We just need to make sure that the
77 * entire VANC region is covered, while making sure we don't decode VANC of
78 * another source during switching*/
80 /* SD Modes */
81
82 {bmdModeNTSC, 11, 19, 274, 282},
83 {bmdModeNTSC2398, 11, 19, 274, 282},
84 {bmdModePAL, 7, 22, 320, 335},
85 {bmdModeNTSCp, 11, -1, -1, 39},
86 {bmdModePALp, 7, -1, -1, 45},
87
88 /* HD 1080 Modes */
89
90 {bmdModeHD1080p2398, 8, -1, -1, 42},
91 {bmdModeHD1080p24, 8, -1, -1, 42},
92 {bmdModeHD1080p25, 8, -1, -1, 42},
93 {bmdModeHD1080p2997, 8, -1, -1, 42},
94 {bmdModeHD1080p30, 8, -1, -1, 42},
95 {bmdModeHD1080i50, 8, 20, 570, 585},
96 {bmdModeHD1080i5994, 8, 20, 570, 585},
97 {bmdModeHD1080i6000, 8, 20, 570, 585},
98 {bmdModeHD1080p50, 8, -1, -1, 42},
99 {bmdModeHD1080p5994, 8, -1, -1, 42},
100 {bmdModeHD1080p6000, 8, -1, -1, 42},
101
102 /* HD 720 Modes */
103
104 {bmdModeHD720p50, 8, -1, -1, 26},
105 {bmdModeHD720p5994, 8, -1, -1, 26},
106 {bmdModeHD720p60, 8, -1, -1, 26},
107
108 /* For all other modes, for which we don't support VANC */
109 {bmdModeUnknown, 0, -1, -1, -1}
110};
111
113{
114public:
117
118 // IDeckLinkMemoryAllocator methods
119 virtual HRESULT STDMETHODCALLTYPE AllocateBuffer(unsigned int bufferSize, void* *allocatedBuffer)
120 {
121 void *buf = av_malloc(bufferSize + AV_INPUT_BUFFER_PADDING_SIZE);
122 if (!buf)
123 return E_OUTOFMEMORY;
124 *allocatedBuffer = buf;
125 return S_OK;
126 }
127 virtual HRESULT STDMETHODCALLTYPE ReleaseBuffer(void* buffer)
128 {
130 return S_OK;
131 }
132 virtual HRESULT STDMETHODCALLTYPE Commit() { return S_OK; }
133 virtual HRESULT STDMETHODCALLTYPE Decommit() { return S_OK; }
134
135 // IUnknown methods
136 virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, LPVOID *ppv)
137 {
138 if (DECKLINK_IsEqualIID(riid, IID_IUnknown)) {
139 *ppv = static_cast<IUnknown*>(this);
141 *ppv = static_cast<IDeckLinkMemoryAllocator_v14_2_1*>(this);
142 } else {
143 *ppv = NULL;
144 return E_NOINTERFACE;
145 }
146
147 AddRef();
148 return S_OK;
149 }
150
151 virtual ULONG STDMETHODCALLTYPE AddRef(void) { return ++_refs; }
152 virtual ULONG STDMETHODCALLTYPE Release(void)
153 {
154 int ret = --_refs;
155 if (!ret)
156 delete this;
157 return ret;
158 }
159
160private:
161 std::atomic<int> _refs;
162};
163
164extern "C" {
165static void decklink_object_free(void *opaque, uint8_t *data)
166{
167 IUnknown *obj = (class IUnknown *)opaque;
168 obj->Release();
169}
170}
171
172static int get_vanc_line_idx(BMDDisplayMode mode)
173{
174 unsigned int i;
175 for (i = 0; i < FF_ARRAY_ELEMS(vanc_line_numbers); i++) {
177 return i;
178 }
179 /* Return the VANC idx for Unknown mode */
180 return i - 1;
181}
182
183static inline void clear_parity_bits(uint16_t *buf, int len) {
184 int i;
185 for (i = 0; i < len; i++)
186 buf[i] &= 0xff;
187}
188
189static int check_vanc_parity_checksum(uint16_t *buf, int len, uint16_t checksum) {
190 int i;
191 uint16_t vanc_sum = 0;
192 for (i = 3; i < len - 1; i++) {
193 uint16_t v = buf[i];
194 int np = v >> 8;
195 int p = av_parity(v & 0xff);
196 if ((!!p ^ !!(v & 0x100)) || (np != 1 && np != 2)) {
197 // Parity check failed
198 return -1;
199 }
200 vanc_sum += v;
201 }
202 vanc_sum &= 0x1ff;
203 vanc_sum |= ((~vanc_sum & 0x100) << 1);
204 if (checksum != vanc_sum) {
205 // Checksum verification failed
206 return -1;
207 }
208 return 0;
209}
210
211/* The 10-bit VANC data is packed in V210, we only need the luma component. */
212static void extract_luma_from_v210(uint16_t *dst, const uint8_t *src, int width)
213{
214 int i;
215 for (i = 0; i < width / 3; i++) {
216 *dst++ = (src[1] >> 2) + ((src[2] & 15) << 6);
217 *dst++ = src[4] + ((src[5] & 3) << 8);
218 *dst++ = (src[6] >> 4) + ((src[7] & 63) << 4);
219 src += 8;
220 }
221}
222
223static void unpack_v210(uint16_t *dst, const uint8_t *src, int width)
224{
225 int i;
226 for (i = 0; i < width * 2 / 3; i++) {
227 *dst++ = src[0] + ((src[1] & 3) << 8);
228 *dst++ = (src[1] >> 2) + ((src[2] & 15) << 6);
229 *dst++ = (src[2] >> 4) + ((src[3] & 63) << 4);
230 src += 4;
231 }
232}
233
235{
236 uint8_t ret = (line < 313) << 5;
237 if (line >= 7 && line <= 22)
238 ret += line;
239 if (line >= 320 && line <= 335)
240 ret += (line - 313);
241 return ret;
242}
243
244static void fill_data_unit_head(int line, uint8_t *tgt)
245{
246 tgt[0] = 0x02; // data_unit_id
247 tgt[1] = 0x2c; // data_unit_length
248 tgt[2] = calc_parity_and_line_offset(line); // field_parity, line_offset
249 tgt[3] = 0xe4; // framing code
250}
251
252#if CONFIG_LIBZVBI
253static uint8_t* teletext_data_unit_from_vbi_data(int line, uint8_t *src, uint8_t *tgt, vbi_pixfmt fmt)
254{
255 vbi_bit_slicer slicer;
256
257 vbi_bit_slicer_init(&slicer, 720, 13500000, 6937500, 6937500, 0x00aaaae4, 0xffff, 18, 6, 42 * 8, VBI_MODULATION_NRZ_MSB, fmt);
258
259 if (vbi_bit_slice(&slicer, src, tgt + 4) == FALSE)
260 return tgt;
261
263
264 return tgt + 46;
265}
266
267static uint8_t* teletext_data_unit_from_vbi_data_10bit(int line, uint8_t *src, uint8_t *tgt)
268{
269 uint8_t y[720];
270 uint8_t *py = y;
271 uint8_t *pend = y + 720;
272 /* The 10-bit VBI data is packed in V210, but libzvbi only supports 8-bit,
273 * so we extract the 8 MSBs of the luma component, that is enough for
274 * teletext bit slicing. */
275 while (py < pend) {
276 *py++ = (src[1] >> 4) + ((src[2] & 15) << 4);
277 *py++ = (src[4] >> 2) + ((src[5] & 3 ) << 6);
278 *py++ = (src[6] >> 6) + ((src[7] & 63) << 2);
279 src += 8;
280 }
281 return teletext_data_unit_from_vbi_data(line, y, tgt, VBI_PIXFMT_YUV420);
282}
283#endif
284
285static uint8_t* teletext_data_unit_from_op47_vbi_packet(int line, uint16_t *py, uint8_t *tgt)
286{
287 int i;
288
289 if (py[0] != 0x255 || py[1] != 0x255 || py[2] != 0x227)
290 return tgt;
291
293
294 py += 3;
295 tgt += 4;
296
297 for (i = 0; i < 42; i++)
298 *tgt++ = ff_reverse[py[i] & 255];
299
300 return tgt;
301}
302
304{
305 int shift = -1;
306 if (line >= 6 && line <= 22)
307 shift = line - 6;
308 if (line >= 318 && line <= 335)
309 shift = line - 318 + 17;
310 return shift >= 0 && ((1ULL << shift) & mask);
311}
312
313static uint8_t* teletext_data_unit_from_op47_data(uint16_t *py, uint16_t *pend, uint8_t *tgt, int64_t wanted_lines)
314{
315 if (py < pend - 9) {
316 if (py[0] == 0x151 && py[1] == 0x115 && py[3] == 0x102) { // identifier, identifier, format code for WST teletext
317 uint16_t *descriptors = py + 4;
318 int i;
319 py += 9;
320 for (i = 0; i < 5 && py < pend - 45; i++, py += 45) {
321 int line = (descriptors[i] & 31) + (!(descriptors[i] & 128)) * 313;
322 if (line && linemask_matches(line, wanted_lines))
324 }
325 }
326 }
327 return tgt;
328}
329
330static uint8_t* teletext_data_unit_from_ancillary_packet(uint16_t *py, uint16_t *pend, uint8_t *tgt, int64_t wanted_lines, int allow_multipacket)
331{
332 uint16_t did = py[0]; // data id
333 uint16_t sdid = py[1]; // secondary data id
334 uint16_t dc = py[2] & 255; // data count
335 py += 3;
336 pend = FFMIN(pend, py + dc);
337 if (did == 0x143 && sdid == 0x102) { // subtitle distribution packet
338 tgt = teletext_data_unit_from_op47_data(py, pend, tgt, wanted_lines);
339 } else if (allow_multipacket && did == 0x143 && sdid == 0x203) { // VANC multipacket
340 py += 2; // priority, line/field
341 while (py < pend - 3) {
342 tgt = teletext_data_unit_from_ancillary_packet(py, pend, tgt, wanted_lines, 0);
343 py += 4 + (py[2] & 255); // ndid, nsdid, ndc, line/field
344 }
345 }
346 return tgt;
347}
348
349static uint8_t *vanc_to_cc(AVFormatContext *avctx, uint16_t *buf, size_t words,
350 unsigned &cc_count)
351{
352 size_t i, len = (buf[5] & 0xff) + 6 + 1;
353 uint8_t cdp_sum, rate;
354 uint16_t hdr, ftr;
355 uint8_t *cc;
356 uint16_t *cdp = &buf[6]; // CDP follows
357 if (cdp[0] != 0x96 || cdp[1] != 0x69) {
358 av_log(avctx, AV_LOG_WARNING, "Invalid CDP header 0x%.2x 0x%.2x\n", cdp[0], cdp[1]);
359 return NULL;
360 }
361
362 len -= 7; // remove VANC header and checksum
363
364 if (cdp[2] != len) {
365 av_log(avctx, AV_LOG_WARNING, "CDP len %d != %zu\n", cdp[2], len);
366 return NULL;
367 }
368
369 cdp_sum = 0;
370 for (i = 0; i < len - 1; i++)
371 cdp_sum += cdp[i];
372 cdp_sum = cdp_sum ? 256 - cdp_sum : 0;
373 if (cdp[len - 1] != cdp_sum) {
374 av_log(avctx, AV_LOG_WARNING, "CDP checksum invalid 0x%.4x != 0x%.4x\n", cdp_sum, cdp[len-1]);
375 return NULL;
376 }
377
378 rate = cdp[3];
379 if (!(rate & 0x0f)) {
380 av_log(avctx, AV_LOG_WARNING, "CDP frame rate invalid (0x%.2x)\n", rate);
381 return NULL;
382 }
383 rate >>= 4;
384 if (rate > 8) {
385 av_log(avctx, AV_LOG_WARNING, "CDP frame rate invalid (0x%.2x)\n", rate);
386 return NULL;
387 }
388
389 if (!(cdp[4] & 0x43)) /* ccdata_present | caption_service_active | reserved */ {
390 av_log(avctx, AV_LOG_WARNING, "CDP flags invalid (0x%.2x)\n", cdp[4]);
391 return NULL;
392 }
393
394 hdr = (cdp[5] << 8) | cdp[6];
395 if (cdp[7] != 0x72) /* ccdata_id */ {
396 av_log(avctx, AV_LOG_WARNING, "Invalid ccdata_id 0x%.2x\n", cdp[7]);
397 return NULL;
398 }
399
400 cc_count = cdp[8];
401 if (!(cc_count & 0xe0)) {
402 av_log(avctx, AV_LOG_WARNING, "Invalid cc_count 0x%.2x\n", cc_count);
403 return NULL;
404 }
405
406 cc_count &= 0x1f;
407 if ((len - 13) < cc_count * 3) {
408 av_log(avctx, AV_LOG_WARNING, "Invalid cc_count %d (> %zu)\n", cc_count * 3, len - 13);
409 return NULL;
410 }
411
412 if (cdp[len - 4] != 0x74) /* footer id */ {
413 av_log(avctx, AV_LOG_WARNING, "Invalid footer id 0x%.2x\n", cdp[len-4]);
414 return NULL;
415 }
416
417 ftr = (cdp[len - 3] << 8) | cdp[len - 2];
418 if (ftr != hdr) {
419 av_log(avctx, AV_LOG_WARNING, "Header 0x%.4x != Footer 0x%.4x\n", hdr, ftr);
420 return NULL;
421 }
422
423 cc = (uint8_t *)av_malloc(cc_count * 3);
424 if (cc == NULL) {
425 av_log(avctx, AV_LOG_WARNING, "CC - av_malloc failed for cc_count = %d\n", cc_count);
426 return NULL;
427 }
428
429 for (size_t i = 0; i < cc_count; i++) {
430 cc[3*i + 0] = cdp[9 + 3*i+0] /* & 3 */;
431 cc[3*i + 1] = cdp[9 + 3*i+1];
432 cc[3*i + 2] = cdp[9 + 3*i+2];
433 }
434
435 cc_count *= 3;
436 return cc;
437}
438
439static uint8_t *get_metadata(AVFormatContext *avctx, uint16_t *buf, size_t width,
440 uint8_t *tgt, size_t tgt_size, AVPacket *pkt)
441{
442 decklink_cctx *cctx = (struct decklink_cctx *) avctx->priv_data;
443 uint16_t *max_buf = buf + width;
444
445 while (buf < max_buf - 6) {
446 int len;
447 uint16_t did = buf[3] & 0xFF; // data id
448 uint16_t sdid = buf[4] & 0xFF; // secondary data id
449 /* Check for VANC header */
450 if (buf[0] != 0 || buf[1] != 0x3ff || buf[2] != 0x3ff) {
451 return tgt;
452 }
453
454 len = (buf[5] & 0xff) + 6 + 1;
455 if (len > max_buf - buf) {
456 av_log(avctx, AV_LOG_WARNING, "Data Count (%d) > data left (%zu)\n",
457 len, max_buf - buf);
458 return tgt;
459 }
460
461 if (did == 0x43 && (sdid == 0x02 || sdid == 0x03) && cctx->teletext_lines &&
462 width == 1920 && tgt_size >= 1920) {
463 if (check_vanc_parity_checksum(buf, len, buf[len - 1]) < 0) {
464 av_log(avctx, AV_LOG_WARNING, "VANC parity or checksum incorrect\n");
465 goto skip_packet;
466 }
467 tgt = teletext_data_unit_from_ancillary_packet(buf + 3, buf + len, tgt, cctx->teletext_lines, 1);
468 } else if (did == 0x61 && sdid == 0x01) {
469 unsigned int data_len;
470 uint8_t *data;
471 if (check_vanc_parity_checksum(buf, len, buf[len - 1]) < 0) {
472 av_log(avctx, AV_LOG_WARNING, "VANC parity or checksum incorrect\n");
473 goto skip_packet;
474 }
476 data = vanc_to_cc(avctx, buf, width, data_len);
477 if (data) {
479 av_free(data);
480 }
481 } else {
482 av_log(avctx, AV_LOG_DEBUG, "Unknown meta data DID = 0x%.2x SDID = 0x%.2x\n",
483 did, sdid);
484 }
485skip_packet:
486 buf += len;
487 }
488
489 return tgt;
490}
491
492
494{
495 const uint8_t KLV_DID = 0x44;
496 const uint8_t KLV_IN_VANC_SDID = 0x04;
497
498 struct KLVPacket
499 {
500 uint16_t sequence_counter;
501 std::vector<uint8_t> data;
502 };
503
504 size_t total_size = 0;
505 std::vector<std::vector<KLVPacket>> klv_packets(256);
506
507 IDeckLinkVideoFrameAncillaryPackets *packets = nullptr;
508 if (videoFrame->QueryInterface(IID_IDeckLinkVideoFrameAncillaryPackets, (void**)&packets) != S_OK)
509 return;
510
511 IDeckLinkAncillaryPacketIterator *it = nullptr;
512 if (packets->GetPacketIterator(&it) != S_OK) {
513 packets->Release();
514 return;
515 }
516
517 IDeckLinkAncillaryPacket *packet = nullptr;
518 while (it->Next(&packet) == S_OK) {
519 uint8_t *data = nullptr;
520 uint32_t size = 0;
521
522 if (packet->GetDID() == KLV_DID && packet->GetSDID() == KLV_IN_VANC_SDID) {
523 av_log(avctx, AV_LOG_DEBUG, "Found KLV VANC packet on line: %d\n", packet->GetLineNumber());
524
525 if (packet->GetBytes(bmdAncillaryPacketFormatUInt8, (const void**) &data, &size) == S_OK) {
526 // MID and PSC
527 if (size > 3) {
528 uint8_t mid = data[0];
529 uint16_t psc = data[1] << 8 | data[2];
530
531 av_log(avctx, AV_LOG_DEBUG, "KLV with MID: %d and PSC: %d\n", mid, psc);
532
533 auto& list = klv_packets[mid];
534 uint16_t expected_psc = list.size() + 1;
535
536 if (psc == expected_psc) {
537 uint32_t data_len = size - 3;
538 total_size += data_len;
539
540 KLVPacket packet{ psc };
541 packet.data.resize(data_len);
542 memcpy(packet.data.data(), data + 3, data_len);
543
544 list.push_back(std::move(packet));
545 } else {
546 av_log(avctx, AV_LOG_WARNING, "Out of order PSC: %d for MID: %d\n", psc, mid);
547
548 if (!list.empty()) {
549 for (auto& klv : list)
550 total_size -= klv.data.size();
551
552 list.clear();
553 }
554 }
555 }
556 }
557 }
558
559 packet->Release();
560 }
561
562 it->Release();
563 packets->Release();
564
565 if (total_size > 0) {
566 std::vector<uint8_t> klv;
567 klv.reserve(total_size);
568
569 for (size_t i = 0; i < klv_packets.size(); ++i) {
570 auto& list = klv_packets[i];
571
572 if (list.empty())
573 continue;
574
575 av_log(avctx, AV_LOG_DEBUG, "Joining MID: %d\n", (int)i);
576
577 for (auto& packet : list)
578 klv.insert(klv.end(), packet.data.begin(), packet.data.end());
579 }
580
581 AVPacket klv_packet = { 0 };
582 klv_packet.pts = pts;
583 klv_packet.dts = pts;
584 klv_packet.flags |= AV_PKT_FLAG_KEY;
585 klv_packet.stream_index = ctx->klv_st->index;
586 klv_packet.data = klv.data();
587 klv_packet.size = klv.size();
588
589 if (ff_decklink_packet_queue_put(&ctx->queue, &klv_packet) < 0) {
590 ++ctx->dropped;
591 }
592 }
593}
594
596{
597public:
600
601 virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, LPVOID *ppv)
602 {
603 if (DECKLINK_IsEqualIID(riid, IID_IUnknown)) {
604 *ppv = static_cast<IUnknown*>(this);
606 *ppv = static_cast<IDeckLinkInputCallback_v14_2_1*>(this);
607 } else {
608 *ppv = NULL;
609 return E_NOINTERFACE;
610 }
611
612 AddRef();
613 return S_OK;
614 }
615 virtual ULONG STDMETHODCALLTYPE AddRef(void);
616 virtual ULONG STDMETHODCALLTYPE Release(void);
617 virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents, IDeckLinkDisplayMode*, BMDDetectedVideoInputFormatFlags);
618 virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame_v14_2_1*, IDeckLinkAudioInputPacket*);
619
620private:
621 std::atomic<int> _refs;
628};
629
631{
632 avctx = _avctx;
633 decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
634 ctx = (struct decklink_ctx *)cctx->ctx;
635 no_video = 0;
637 last_video_frame = nullptr;
638}
639
645
647{
648 return ++_refs;
649}
650
652{
653 int ret = --_refs;
654 if (!ret)
655 delete this;
656 return ret;
657}
658
660 IDeckLinkAudioInputPacket *audioFrame,
661 int64_t wallclock,
662 int64_t abs_wallclock,
663 DecklinkPtsSource pts_src,
664 AVRational time_base, int64_t *initial_pts,
665 int copyts)
666{
668 BMDTimeValue bmd_pts;
669 BMDTimeValue bmd_duration;
670 HRESULT res = E_INVALIDARG;
671 switch (pts_src) {
672 case PTS_SRC_AUDIO:
673 if (audioFrame)
674 res = audioFrame->GetPacketTime(&bmd_pts, time_base.den);
675 break;
676 case PTS_SRC_VIDEO:
677 if (videoFrame)
678 res = videoFrame->GetStreamTime(&bmd_pts, &bmd_duration, time_base.den);
679 break;
681 if (videoFrame)
682 res = videoFrame->GetHardwareReferenceTimestamp(time_base.den, &bmd_pts, &bmd_duration);
683 break;
685 /* fall through */
687 {
688 /* MSVC does not support compound literals like AV_TIME_BASE_Q
689 * in C++ code (compiler error C4576) */
690 AVRational timebase;
691 timebase.num = 1;
692 timebase.den = AV_TIME_BASE;
693 if (pts_src == PTS_SRC_WALLCLOCK)
694 pts = av_rescale_q(wallclock, timebase, time_base);
695 else
696 pts = av_rescale_q(abs_wallclock, timebase, time_base);
697 break;
698 }
699 }
700 if (res == S_OK)
701 pts = bmd_pts / time_base.num;
702
703 if (!copyts) {
704 if (pts != AV_NOPTS_VALUE && *initial_pts == AV_NOPTS_VALUE)
705 *initial_pts = pts;
706 if (*initial_pts != AV_NOPTS_VALUE)
707 pts -= *initial_pts;
708 }
709
710 return pts;
711}
712
713static int get_bmd_timecode(AVFormatContext *avctx, AVTimecode *tc, AVRational frame_rate, BMDTimecodeFormat tc_format, IDeckLinkVideoInputFrame_v14_2_1 *videoFrame)
714{
715 IDeckLinkTimecode *timecode;
716 int ret = AVERROR(ENOENT);
717#if BLACKMAGIC_DECKLINK_API_VERSION >= 0x0b000000
718 int hfr = (tc_format == bmdTimecodeRP188HighFrameRate);
719#else
720 int hfr = 0;
721#endif
722 if (videoFrame->GetTimecode(tc_format, &timecode) == S_OK) {
723 uint8_t hh, mm, ss, ff;
724 if (timecode->GetComponents(&hh, &mm, &ss, &ff) == S_OK) {
725 int flags = (timecode->GetFlags() & bmdTimecodeIsDropFrame) ? AV_TIMECODE_FLAG_DROPFRAME : 0;
726 if (!hfr && av_cmp_q(frame_rate, av_make_q(30, 1)) == 1)
727 ff = ff << 1 | !!(timecode->GetFlags() & bmdTimecodeFieldMark);
728 ret = av_timecode_init_from_components(tc, frame_rate, flags, hh, mm, ss, ff, avctx);
729 }
730 timecode->Release();
731 }
732 return ret;
733}
734
736{
737 AVRational frame_rate = ctx->video_st->r_frame_rate;
738 int ret;
739 /* 50/60 fps content has alternating VITC1 and VITC2 timecode (see SMPTE ST
740 * 12-2, section 7), so the native ordering of RP188Any (HFR, VITC1, LTC,
741 * VITC2) would not work because LTC might not contain the field flag.
742 * Therefore we query the types manually. */
743 if (ctx->tc_format == bmdTimecodeRP188Any && av_cmp_q(frame_rate, av_make_q(30, 1)) == 1) {
744#if BLACKMAGIC_DECKLINK_API_VERSION >= 0x0b000000
745 ret = get_bmd_timecode(avctx, tc, frame_rate, bmdTimecodeRP188HighFrameRate, videoFrame);
746 if (ret == AVERROR(ENOENT))
747#endif
748 ret = get_bmd_timecode(avctx, tc, frame_rate, bmdTimecodeRP188VITC1, videoFrame);
749 if (ret == AVERROR(ENOENT))
750 ret = get_bmd_timecode(avctx, tc, frame_rate, bmdTimecodeRP188VITC2, videoFrame);
751 if (ret == AVERROR(ENOENT))
752 ret = get_bmd_timecode(avctx, tc, frame_rate, bmdTimecodeRP188LTC, videoFrame);
753 } else {
754 ret = get_bmd_timecode(avctx, tc, frame_rate, ctx->tc_format, videoFrame);
755 }
756 return ret;
757}
758
760 IDeckLinkVideoInputFrame_v14_2_1 *videoFrame, IDeckLinkAudioInputPacket *audioFrame)
761{
762 void *frameBytes;
763 void *audioFrameBytes;
764 BMDTimeValue frameTime;
765 BMDTimeValue frameDuration;
766 int64_t wallclock = 0, abs_wallclock = 0;
767 int64_t video_pkt_pts, audio_pkt_pts;
768 struct decklink_cctx *cctx = (struct decklink_cctx *) avctx->priv_data;
769
770 if (ctx->autodetect) {
771 if (videoFrame && !(videoFrame->GetFlags() & bmdFrameHasNoInputSource) &&
772 ctx->bmd_mode == bmdModeUnknown)
773 {
774 ctx->bmd_mode = AUTODETECT_DEFAULT_MODE;
775 }
776 return S_OK;
777 }
778
779 // Drop the frames till system's timestamp aligns with the configured value.
780 if (0 == ctx->frameCount && cctx->timestamp_align) {
781 AVRational remainder = av_make_q(av_gettime() % cctx->timestamp_align, 1000000);
782 AVRational frame_duration = av_inv_q(ctx->video_st->r_frame_rate);
783 if (av_cmp_q(remainder, frame_duration) > 0) {
784 ++ctx->dropped;
785 return S_OK;
786 }
787 }
788
789 ctx->frameCount++;
790 if (ctx->audio_pts_source == PTS_SRC_WALLCLOCK || ctx->video_pts_source == PTS_SRC_WALLCLOCK)
791 wallclock = av_gettime_relative();
792 if (ctx->audio_pts_source == PTS_SRC_ABS_WALLCLOCK || ctx->video_pts_source == PTS_SRC_ABS_WALLCLOCK)
793 abs_wallclock = av_gettime();
794 video_pkt_pts = get_pkt_pts(videoFrame, audioFrame, wallclock, abs_wallclock, ctx->video_pts_source, ctx->video_st->time_base, &initial_video_pts, cctx->copyts);
795 audio_pkt_pts = get_pkt_pts(videoFrame, audioFrame, wallclock, abs_wallclock, ctx->audio_pts_source, ctx->audio_st->time_base, &initial_audio_pts, cctx->copyts);
796
797 // Handle Video Frame
798 if (videoFrame) {
799 AVPacket pkt = { 0 };
800 if (ctx->frameCount % 25 == 0) {
801 unsigned long long qsize = ff_decklink_packet_queue_size(&ctx->queue);
803 "Frame received (#%lu) - Valid (%liB) - QSize %fMB\n",
804 ctx->frameCount,
805 videoFrame->GetRowBytes() * videoFrame->GetHeight(),
806 (double)qsize / 1024 / 1024);
807 }
808
809 videoFrame->GetBytes(&frameBytes);
810 videoFrame->GetStreamTime(&frameTime, &frameDuration,
811 ctx->video_st->time_base.den);
812
813 if (videoFrame->GetFlags() & bmdFrameHasNoInputSource) {
814 if (ctx->signal_loss_action == SIGNAL_LOSS_BARS && videoFrame->GetPixelFormat() == bmdFormat8BitYUV) {
815 unsigned bars[8] = {
816 0xEA80EA80, 0xD292D210, 0xA910A9A5, 0x90229035,
817 0x6ADD6ACA, 0x51EF515A, 0x286D28EF, 0x10801080 };
818 int width = videoFrame->GetWidth();
819 int height = videoFrame->GetHeight();
820 unsigned *p = (unsigned *)frameBytes;
821
822 for (int y = 0; y < height; y++) {
823 for (int x = 0; x < width; x += 2)
824 *p++ = bars[(x * 8) / width];
825 }
826 } else if (ctx->signal_loss_action == SIGNAL_LOSS_REPEAT && last_video_frame) {
827 videoFrame = last_video_frame;
828 videoFrame->GetBytes(&frameBytes);
829 }
830
831 if (!no_video) {
832 av_log(avctx, AV_LOG_WARNING, "Frame received (#%lu) - No input signal detected "
833 "- Frames dropped %u\n", ctx->frameCount, ++ctx->dropped);
834 }
835 no_video = 1;
836 } else {
837 if (ctx->signal_loss_action == SIGNAL_LOSS_REPEAT) {
839 last_video_frame->Release();
840 last_video_frame = videoFrame;
841 last_video_frame->AddRef();
842 }
843 if (no_video) {
844 av_log(avctx, AV_LOG_WARNING, "Frame received (#%lu) - Input returned "
845 "- Frames dropped %u\n", ctx->frameCount, ++ctx->dropped);
846 }
847 no_video = 0;
848
849 // Handle Timecode (if requested)
850 if (ctx->tc_format) {
851 AVTimecode tcr;
852 if (get_frame_timecode(avctx, ctx, &tcr, videoFrame) >= 0) {
853 char tcstr[AV_TIMECODE_STR_SIZE];
854 const char *tc = av_timecode_make_string(&tcr, tcstr, 0);
855 if (tc) {
856 AVDictionary* metadata_dict = NULL;
857 uint8_t* packed_metadata;
858
859 if (av_cmp_q(ctx->video_st->r_frame_rate, av_make_q(60, 1)) < 1) {
860 uint32_t tc_data = av_timecode_get_smpte_from_framenum(&tcr, 0);
861 int size = sizeof(uint32_t) * 4;
862 uint32_t *sd = (uint32_t *)av_packet_new_side_data(&pkt, AV_PKT_DATA_S12M_TIMECODE, size);
863
864 if (sd) {
865 *sd = 1; // one TC
866 *(sd + 1) = tc_data; // TC
867 }
868 }
869
870 if (av_dict_set(&metadata_dict, "timecode", tc, 0) >= 0) {
871 size_t metadata_len;
872 packed_metadata = av_packet_pack_dictionary(metadata_dict, &metadata_len);
873 av_dict_free(&metadata_dict);
874 if (packed_metadata) {
875 if (av_packet_add_side_data(&pkt, AV_PKT_DATA_STRINGS_METADATA, packed_metadata, metadata_len) < 0)
876 av_freep(&packed_metadata);
877 else if (!ctx->tc_seen)
878 ctx->tc_seen = ctx->frameCount;
879 }
880 }
881 }
882 } else {
883 av_log(avctx, AV_LOG_DEBUG, "Unable to find timecode.\n");
884 }
885 }
886 }
887
888 if (ctx->tc_format && cctx->wait_for_tc && !ctx->tc_seen) {
889
890 av_log(avctx, AV_LOG_WARNING, "No TC detected yet. wait_for_tc set. Dropping. \n");
891 av_log(avctx, AV_LOG_WARNING, "Frame received (#%lu) - "
892 "- Frames dropped %u\n", ctx->frameCount, ++ctx->dropped);
893 return S_OK;
894 }
895
896 pkt.pts = video_pkt_pts;
897 pkt.dts = pkt.pts;
898
899 pkt.duration = frameDuration;
900 //To be made sure it still applies
901 pkt.flags |= AV_PKT_FLAG_KEY;
902 pkt.stream_index = ctx->video_st->index;
903 pkt.data = (uint8_t *)frameBytes;
904 pkt.size = videoFrame->GetRowBytes() *
905 videoFrame->GetHeight();
906 //fprintf(stderr,"Video Frame size %d ts %d\n", pkt.size, pkt.pts);
907
908 if (!no_video) {
909 IDeckLinkVideoFrameAncillary *vanc;
910 AVPacket txt_pkt = { 0 };
911 uint8_t txt_buf0[3531]; // 35 * 46 bytes decoded teletext lines + 1 byte data_identifier + 1920 bytes OP47 decode buffer
912 uint8_t *txt_buf = txt_buf0;
913
914 if (ctx->enable_klv) {
915 handle_klv(avctx, ctx, videoFrame, pkt.pts);
916 }
917
918 if (videoFrame->GetAncillaryData(&vanc) == S_OK) {
919 int i;
920 BMDPixelFormat vanc_format = vanc->GetPixelFormat();
921 txt_buf[0] = 0x10; // data_identifier - EBU_data
922 txt_buf++;
923#if CONFIG_LIBZVBI
924 if (ctx->bmd_mode == bmdModePAL && ctx->teletext_lines &&
925 (vanc_format == bmdFormat8BitYUV || vanc_format == bmdFormat10BitYUV)) {
926 int64_t line_mask = 1;
927 av_assert0(videoFrame->GetWidth() == 720);
928 for (i = 6; i < 336; i++, line_mask <<= 1) {
929 uint8_t *buf;
930 if ((ctx->teletext_lines & line_mask) && vanc->GetBufferForVerticalBlankingLine(i, (void**)&buf) == S_OK) {
931 if (vanc_format == bmdFormat8BitYUV)
932 txt_buf = teletext_data_unit_from_vbi_data(i, buf, txt_buf, VBI_PIXFMT_UYVY);
933 else
934 txt_buf = teletext_data_unit_from_vbi_data_10bit(i, buf, txt_buf);
935 }
936 if (i == 22)
937 i = 317;
938 }
939 }
940#endif
941 if (vanc_format == bmdFormat10BitYUV && videoFrame->GetWidth() <= MAX_WIDTH_VANC) {
942 int idx = get_vanc_line_idx(ctx->bmd_mode);
943 for (i = vanc_line_numbers[idx].vanc_start; i <= vanc_line_numbers[idx].vanc_end; i++) {
944 uint8_t *buf;
945 if (vanc->GetBufferForVerticalBlankingLine(i, (void**)&buf) == S_OK) {
946 uint16_t vanc[MAX_WIDTH_VANC];
947 size_t vanc_size = videoFrame->GetWidth();
948 if (ctx->bmd_mode == bmdModeNTSC && videoFrame->GetWidth() * 2 <= MAX_WIDTH_VANC) {
949 vanc_size = vanc_size * 2;
950 unpack_v210(vanc, buf, videoFrame->GetWidth());
951 } else {
952 extract_luma_from_v210(vanc, buf, videoFrame->GetWidth());
953 }
954 txt_buf = get_metadata(avctx, vanc, vanc_size,
955 txt_buf, sizeof(txt_buf0) - (txt_buf - txt_buf0), &pkt);
956 }
957 if (i == vanc_line_numbers[idx].field0_vanc_end)
958 i = vanc_line_numbers[idx].field1_vanc_start - 1;
959 }
960 }
961 vanc->Release();
962 if (txt_buf - txt_buf0 > 1) {
963 int stuffing_units = (4 - ((45 + txt_buf - txt_buf0) / 46) % 4) % 4;
964 while (stuffing_units--) {
965 memset(txt_buf, 0xff, 46);
966 txt_buf[1] = 0x2c; // data_unit_length
967 txt_buf += 46;
968 }
969 txt_pkt.pts = pkt.pts;
970 txt_pkt.dts = pkt.dts;
971 txt_pkt.stream_index = ctx->teletext_st->index;
972 txt_pkt.data = txt_buf0;
973 txt_pkt.size = txt_buf - txt_buf0;
974 if (ff_decklink_packet_queue_put(&ctx->queue, &txt_pkt) < 0) {
975 ++ctx->dropped;
976 }
977 }
978 }
979 }
980
981 pkt.buf = av_buffer_create(pkt.data, pkt.size, decklink_object_free, videoFrame, 0);
982 if (pkt.buf)
983 videoFrame->AddRef();
984
985 if (ff_decklink_packet_queue_put(&ctx->queue, &pkt) < 0) {
986 ++ctx->dropped;
987 }
988 }
989
990 // Handle Audio Frame
991 if (audioFrame) {
992 AVPacket pkt = { 0 };
993 BMDTimeValue audio_pts;
994
995 //hack among hacks
996 pkt.size = audioFrame->GetSampleFrameCount() * ctx->audio_st->codecpar->ch_layout.nb_channels * (ctx->audio_depth / 8);
997 audioFrame->GetBytes(&audioFrameBytes);
998 audioFrame->GetPacketTime(&audio_pts, ctx->audio_st->time_base.den);
999 pkt.pts = audio_pkt_pts;
1000 pkt.dts = pkt.pts;
1001
1002 //fprintf(stderr,"Audio Frame size %d ts %d\n", pkt.size, pkt.pts);
1003 pkt.flags |= AV_PKT_FLAG_KEY;
1004 pkt.stream_index = ctx->audio_st->index;
1005 pkt.data = (uint8_t *)audioFrameBytes;
1006
1007 if (ff_decklink_packet_queue_put(&ctx->queue, &pkt) < 0) {
1008 ++ctx->dropped;
1009 }
1010 }
1011
1012 return S_OK;
1013}
1014
1016 BMDVideoInputFormatChangedEvents events, IDeckLinkDisplayMode *mode,
1017 BMDDetectedVideoInputFormatFlags formatFlags)
1018{
1019 struct decklink_cctx *cctx = (struct decklink_cctx *) avctx->priv_data;
1020 ctx->bmd_mode = mode->GetDisplayMode();
1021 // check the C context member to make sure we set both raw_format and bmd_mode with data from the same format change callback
1022 if (!cctx->raw_format)
1023 ctx->raw_format = (formatFlags & bmdDetectedVideoInputRGB444) ? bmdFormat8BitARGB : bmdFormat8BitYUV;
1024 return S_OK;
1025}
1026
1027static int decklink_autodetect(struct decklink_cctx *cctx) {
1028 struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
1029 DECKLINK_BOOL autodetect_supported = false;
1030 int i;
1031
1032 if (ctx->attr->GetFlag(BMDDeckLinkSupportsInputFormatDetection, &autodetect_supported) != S_OK)
1033 return -1;
1034 if (autodetect_supported == false)
1035 return -1;
1036
1037 ctx->autodetect = 1;
1038 ctx->bmd_mode = bmdModeUnknown;
1039 if (ctx->dli->EnableVideoInput(AUTODETECT_DEFAULT_MODE,
1040 bmdFormat8BitYUV,
1041 bmdVideoInputEnableFormatDetection) != S_OK) {
1042 return -1;
1043 }
1044
1045 if (ctx->dli->StartStreams() != S_OK) {
1046 return -1;
1047 }
1048
1049 // 3 second timeout
1050 for (i = 0; i < 30; i++) {
1051 av_usleep(100000);
1052 /* Sometimes VideoInputFrameArrived is called without the
1053 * bmdFrameHasNoInputSource flag before VideoInputFormatChanged.
1054 * So don't break for bmd_mode == AUTODETECT_DEFAULT_MODE. */
1055 if (ctx->bmd_mode != bmdModeUnknown &&
1056 ctx->bmd_mode != AUTODETECT_DEFAULT_MODE)
1057 break;
1058 }
1059
1060 ctx->dli->PauseStreams();
1061 ctx->dli->FlushStreams();
1062 ctx->autodetect = 0;
1063 if (ctx->bmd_mode != bmdModeUnknown) {
1064 cctx->format_code = (char *)av_mallocz(5);
1065 if (!cctx->format_code)
1066 return -1;
1067 AV_WB32(cctx->format_code, ctx->bmd_mode);
1068 return 0;
1069 } else {
1070 return -1;
1071 }
1072
1073}
1074
1075extern "C" {
1076
1078{
1079 struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
1080 struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
1081
1082 if (ctx->dli) {
1083 ctx->dli->StopStreams();
1084 ctx->dli->DisableVideoInput();
1085 ctx->dli->DisableAudioInput();
1086 ctx->dli->SetCallback(nullptr);
1087 }
1088
1089 ff_decklink_cleanup(avctx);
1091
1092 av_freep(&cctx->ctx);
1093
1094 return 0;
1095}
1096
1098{
1099 struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
1100 struct decklink_ctx *ctx;
1101 class decklink_allocator *allocator;
1103 AVStream *st;
1104 HRESULT result;
1105 int ret;
1106
1107 ctx = (struct decklink_ctx *) av_mallocz(sizeof(struct decklink_ctx));
1108 if (!ctx)
1109 return AVERROR(ENOMEM);
1110 ctx->list_devices = cctx->list_devices;
1111 ctx->list_formats = cctx->list_formats;
1112 ctx->enable_klv = cctx->enable_klv;
1113 ctx->teletext_lines = cctx->teletext_lines;
1114 ctx->preroll = cctx->preroll;
1115 ctx->duplex_mode = cctx->duplex_mode;
1116 if (cctx->tc_format > 0 && (unsigned int)cctx->tc_format < FF_ARRAY_ELEMS(decklink_timecode_format_map))
1117 ctx->tc_format = decklink_timecode_format_map[cctx->tc_format];
1118 if (cctx->video_input > 0 && (unsigned int)cctx->video_input < FF_ARRAY_ELEMS(decklink_video_connection_map))
1119 ctx->video_input = decklink_video_connection_map[cctx->video_input];
1120 if (cctx->audio_input > 0 && (unsigned int)cctx->audio_input < FF_ARRAY_ELEMS(decklink_audio_connection_map))
1121 ctx->audio_input = decklink_audio_connection_map[cctx->audio_input];
1122 ctx->audio_pts_source = cctx->audio_pts_source;
1123 ctx->video_pts_source = cctx->video_pts_source;
1124 ctx->draw_bars = cctx->draw_bars;
1125 ctx->signal_loss_action = cctx->signal_loss_action;
1126 if (!ctx->draw_bars && ctx->signal_loss_action == SIGNAL_LOSS_BARS) {
1127 ctx->signal_loss_action = SIGNAL_LOSS_NONE;
1128 av_log(avctx, AV_LOG_WARNING, "Setting signal_loss_action to none because draw_bars is false\n");
1129 }
1130 if (!ctx->draw_bars && ctx->signal_loss_action != SIGNAL_LOSS_NONE) {
1131 av_log(avctx, AV_LOG_ERROR, "options draw_bars and signal_loss_action are mutually exclusive\n");
1132 av_freep(&ctx);
1133 return AVERROR(EINVAL);
1134 }
1135 ctx->audio_depth = cctx->audio_depth;
1136 if (cctx->raw_format > 0 && (unsigned int)cctx->raw_format < FF_ARRAY_ELEMS(decklink_raw_format_map))
1137 ctx->raw_format = decklink_raw_format_map[cctx->raw_format];
1138 cctx->ctx = ctx;
1139
1140 /* Check audio channel option for valid values: 2, 8 or 16 */
1141 switch (cctx->audio_channels) {
1142 case 2:
1143 case 8:
1144 case 16:
1145 break;
1146 default:
1147 av_log(avctx, AV_LOG_ERROR, "Value of channels option must be one of 2, 8 or 16\n");
1148 ret = AVERROR(EINVAL);
1149 goto error;
1150 }
1151
1152 /* Check audio bit depth option for valid values: 16 or 32 */
1153 switch (cctx->audio_depth) {
1154 case 16:
1155 case 32:
1156 break;
1157 default:
1158 av_log(avctx, AV_LOG_ERROR, "Value for audio bit depth option must be either 16 or 32\n");
1159 ret = AVERROR(EINVAL);
1160 goto error;
1161 }
1162
1163 /* List available devices. */
1164 if (ctx->list_devices) {
1166 ret = AVERROR_EXIT;
1167 goto error;
1168 }
1169
1170 ret = ff_decklink_init_device(avctx, avctx->url);
1171 if (ret < 0)
1172 goto error;
1173
1174 /* Get input device. */
1175 if (ctx->dl->QueryInterface(IID_IDeckLinkInput_v14_2_1, (void **) &ctx->dli) != S_OK) {
1176 av_log(avctx, AV_LOG_ERROR, "Could not open input device from '%s'\n",
1177 avctx->url);
1178 ret = AVERROR(EIO);
1179 goto error;
1180 }
1181
1182 if (ff_decklink_set_configs(avctx, DIRECTION_IN) < 0) {
1183 av_log(avctx, AV_LOG_ERROR, "Could not set input configuration\n");
1184 ret = AVERROR(EIO);
1185 goto error;
1186 }
1187
1188 /* List supported formats. */
1189 if (ctx->list_formats) {
1191 ret = AVERROR_EXIT;
1192 goto error;
1193 }
1194
1196 ret = (ctx->dli->SetCallback(input_callback) == S_OK ? 0 : AVERROR_EXTERNAL);
1197 input_callback->Release();
1198 if (ret < 0) {
1199 av_log(avctx, AV_LOG_ERROR, "Cannot set input callback\n");
1200 goto error;
1201 }
1202
1203 allocator = new decklink_allocator();
1204 ret = (ctx->dli->SetVideoInputFrameMemoryAllocator(allocator) == S_OK ? 0 : AVERROR_EXTERNAL);
1205 allocator->Release();
1206 if (ret < 0) {
1207 av_log(avctx, AV_LOG_ERROR, "Cannot set custom memory allocator\n");
1208 goto error;
1209 }
1210
1211 if (!cctx->format_code) {
1212 if (decklink_autodetect(cctx) < 0) {
1213 av_log(avctx, AV_LOG_ERROR, "Cannot Autodetect input stream or No signal\n");
1214 ret = AVERROR(EIO);
1215 goto error;
1216 }
1217 av_log(avctx, AV_LOG_INFO, "Autodetected the input mode\n");
1218 }
1219 if (ctx->raw_format == (BMDPixelFormat)0)
1220 ctx->raw_format = bmdFormat8BitYUV;
1221 if (ff_decklink_set_format(avctx, DIRECTION_IN) < 0) {
1222 av_log(avctx, AV_LOG_ERROR, "Could not set format code %s for %s\n",
1223 cctx->format_code ? cctx->format_code : "(unset)", avctx->url);
1224 ret = AVERROR(EIO);
1225 goto error;
1226 }
1227
1228#if !CONFIG_LIBZVBI
1229 if (ctx->teletext_lines && ctx->bmd_mode == bmdModePAL) {
1230 av_log(avctx, AV_LOG_ERROR, "Libzvbi support is needed for capturing SD PAL teletext, please recompile FFmpeg.\n");
1231 ret = AVERROR(ENOSYS);
1232 goto error;
1233 }
1234#endif
1235
1236 /* Setup streams. */
1237 st = avformat_new_stream(avctx, NULL);
1238 if (!st) {
1239 av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
1240 ret = AVERROR(ENOMEM);
1241 goto error;
1242 }
1245 st->codecpar->sample_rate = bmdAudioSampleRate48kHz;
1247 avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
1248 ctx->audio_st=st;
1249
1250 st = avformat_new_stream(avctx, NULL);
1251 if (!st) {
1252 av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
1253 ret = AVERROR(ENOMEM);
1254 goto error;
1255 }
1257 st->codecpar->width = ctx->bmd_width;
1258 st->codecpar->height = ctx->bmd_height;
1259
1260 st->time_base.den = ctx->bmd_tb_den;
1261 st->time_base.num = ctx->bmd_tb_num;
1263
1264 switch(ctx->raw_format) {
1265 case bmdFormat8BitYUV:
1268 st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 16, st->time_base.den, st->time_base.num);
1269 break;
1270 case bmdFormat10BitYUV:
1272 st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 64, st->time_base.den, st->time_base.num * 3);
1273 break;
1274 case bmdFormat8BitARGB:
1277 st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 32, st->time_base.den, st->time_base.num);
1278 break;
1279 case bmdFormat8BitBGRA:
1282 st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 32, st->time_base.den, st->time_base.num);
1283 break;
1284 case bmdFormat10BitRGB:
1286 st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 30, st->time_base.den, st->time_base.num);
1287 break;
1288 default:
1289 char fourcc_str[AV_FOURCC_MAX_STRING_SIZE] = {0};
1290 av_fourcc_make_string(fourcc_str, ctx->raw_format);
1291 av_log(avctx, AV_LOG_ERROR, "Raw Format %s not supported\n", fourcc_str);
1292 ret = AVERROR(EINVAL);
1293 goto error;
1294 }
1295
1296 switch (ctx->bmd_field_dominance) {
1297 case bmdUpperFieldFirst:
1299 break;
1300 case bmdLowerFieldFirst:
1302 break;
1303 case bmdProgressiveFrame:
1304 case bmdProgressiveSegmentedFrame:
1306 break;
1307 }
1308
1309 avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
1310
1311 ctx->video_st=st;
1312
1313 if (ctx->enable_klv) {
1314 st = avformat_new_stream(avctx, NULL);
1315 if (!st) {
1316 ret = AVERROR(ENOMEM);
1317 goto error;
1318 }
1320 st->time_base.den = ctx->bmd_tb_den;
1321 st->time_base.num = ctx->bmd_tb_num;
1323 avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
1324 ctx->klv_st = st;
1325 }
1326
1327 if (ctx->teletext_lines) {
1328 st = avformat_new_stream(avctx, NULL);
1329 if (!st) {
1330 av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
1331 ret = AVERROR(ENOMEM);
1332 goto error;
1333 }
1335 st->time_base.den = ctx->bmd_tb_den;
1336 st->time_base.num = ctx->bmd_tb_num;
1338 avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
1339 ctx->teletext_st = st;
1340 }
1341
1342 av_log(avctx, AV_LOG_VERBOSE, "Using %d input audio channels\n", ctx->audio_st->codecpar->ch_layout.nb_channels);
1343 result = ctx->dli->EnableAudioInput(bmdAudioSampleRate48kHz, cctx->audio_depth == 32 ? bmdAudioSampleType32bitInteger : bmdAudioSampleType16bitInteger, ctx->audio_st->codecpar->ch_layout.nb_channels);
1344
1345 if (result != S_OK) {
1346 av_log(avctx, AV_LOG_ERROR, "Cannot enable audio input\n");
1347 ret = AVERROR(EIO);
1348 goto error;
1349 }
1350
1351 result = ctx->dli->EnableVideoInput(ctx->bmd_mode,
1352 ctx->raw_format,
1353 bmdVideoInputFlagDefault);
1354
1355 if (result != S_OK) {
1356 av_log(avctx, AV_LOG_ERROR, "Cannot enable video input\n");
1357 ret = AVERROR(EIO);
1358 goto error;
1359 }
1360
1361 ff_decklink_packet_queue_init(avctx, &ctx->queue, cctx->queue_size);
1362
1363 if (ctx->dli->StartStreams() != S_OK) {
1364 av_log(avctx, AV_LOG_ERROR, "Cannot start input stream\n");
1365 ret = AVERROR(EIO);
1366 goto error;
1367 }
1368
1369 return 0;
1370
1371error:
1372 ff_decklink_cleanup(avctx);
1373 av_freep(&cctx->ctx);
1374 return ret;
1375}
1376
1378{
1379 struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
1380 struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
1381
1383
1384 if (ctx->tc_format && !(av_dict_get(ctx->video_st->metadata, "timecode", NULL, 0))) {
1385 size_t size;
1386 const uint8_t *side_metadata = av_packet_get_side_data(pkt, AV_PKT_DATA_STRINGS_METADATA, &size);
1387 if (side_metadata) {
1388 if (av_packet_unpack_dictionary(side_metadata, size, &ctx->video_st->metadata) < 0)
1389 av_log(avctx, AV_LOG_ERROR, "Unable to set timecode\n");
1390 }
1391 }
1392
1393 return 0;
1394}
1395
1397{
1398 return ff_decklink_list_devices(avctx, device_list, 1, 0);
1399}
1400
1401} /* extern "C" */
uint8_t ptrdiff_t const uint8_t ptrdiff_t int intptr_t intptr_t int int16_t * dst
Definition dsp.h:87
static AVFormatContext * ctx
simple assert() macros that are a bit more flexible than ISO C assert().
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition avassert.h:42
Main libavdevice API header.
void avpriv_set_pts_info(AVStream *st, int pts_wrap_bits, unsigned int pts_num, unsigned int pts_den)
Set the time base and wrapping info for a given stream.
Definition avformat.c:834
Main libavformat public API header.
Convenience header that includes libavutil's core.
#define flags(name, subs,...)
Definition cbs_h264.c:74
#define i(width, name, range_min, range_max)
Definition cbs_h264.c:63
#define ss(width, name, subs,...)
Definition cbs_vp9.c:202
common internal and external API header
#define NULL
Definition coverity.c:32
long long int64_t
Definition coverity.c:34
@ AV_FIELD_TT
Top coded_first, top displayed first.
Definition defs.h:214
@ AV_FIELD_BB
Bottom coded first, bottom displayed first.
Definition defs.h:215
@ AV_FIELD_PROGRESSIVE
Definition defs.h:213
static AVPacket * pkt
@ AV_CODEC_ID_V210
Definition codec_id.h:177
@ AV_CODEC_ID_RAWVIDEO
Definition codec_id.h:63
@ AV_CODEC_ID_R210
Definition codec_id.h:183
@ AV_CODEC_ID_PCM_S16LE
Definition codec_id.h:330
@ AV_CODEC_ID_SMPTE_KLV
Definition codec_id.h:604
@ AV_CODEC_ID_PCM_S32LE
Definition codec_id.h:338
@ AV_CODEC_ID_DVB_TELETEXT
Definition codec_id.h:573
#define AV_INPUT_BUFFER_PADDING_SIZE
Required number of additionally allocated bytes at the end of the input bitstream for decoding.
Definition defs.h:40
@ AV_PKT_DATA_STRINGS_METADATA
A list of zero terminated key/value strings.
Definition packet.h:169
@ AV_PKT_DATA_S12M_TIMECODE
Timecode which conforms to SMPTE ST 12-1:2014.
Definition packet.h:288
@ AV_PKT_DATA_A53_CC
ATSC A53 Part 4 Closed Captions.
Definition packet.h:239
uint8_t * av_packet_new_side_data(AVPacket *pkt, enum AVPacketSideDataType type, size_t size)
Allocate new information of a packet.
Definition packet.c:231
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition packet.h:650
uint8_t * av_packet_pack_dictionary(const AVDictionary *dict, size_t *size)
Pack a dictionary for use in side_data.
Definition packet.c:319
int av_packet_add_side_data(AVPacket *pkt, enum AVPacketSideDataType type, uint8_t *data, size_t size)
Wrap an existing array as a packet side data.
Definition packet.c:197
int av_packet_unpack_dictionary(const uint8_t *data, size_t size, AVDictionary **dict)
Unpack a dictionary from side_data.
Definition packet.c:354
uint8_t * av_packet_get_side_data(const AVPacket *pkt, enum AVPacketSideDataType type, size_t *size)
Get side information from packet.
Definition packet.c:252
AVStream * avformat_new_stream(AVFormatContext *s, const struct AVCodec *c)
Add a new stream to a media file.
AVBufferRef * av_buffer_create(uint8_t *data, size_t size, void(*free)(void *opaque, uint8_t *data), void *opaque, int flags)
Create an AVBuffer from an existing array.
Definition buffer.c:55
void av_dict_free(AVDictionary **pm)
Free all the memory allocated for an AVDictionary struct and all keys and values.
Definition dict.c:233
AVDictionaryEntry * av_dict_get(const AVDictionary *m, const char *key, const AVDictionaryEntry *prev, int flags)
Get a dictionary entry with matching key.
Definition dict.c:60
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition dict.c:86
#define AVERROR_EXIT
Immediate exit was requested; the called function should not be restarted.
Definition error.h:58
#define AVERROR_EXTERNAL
Generic error in an external library.
Definition error.h:59
#define AVERROR(e)
Definition error.h:45
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition log.h:231
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition log.h:216
#define AV_LOG_VERBOSE
Detailed information.
Definition log.h:226
#define AV_LOG_INFO
Standard information.
Definition log.h:221
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition log.h:210
static AVRational av_make_q(int num, int den)
Create an AVRational.
Definition rational.h:71
static int av_cmp_q(AVRational a, AVRational b)
Compare two rationals.
Definition rational.h:89
static av_always_inline AVRational av_inv_q(AVRational q)
Invert a rational.
Definition rational.h:159
#define av_parity
Definition intmath.h:157
int64_t av_rescale(int64_t a, int64_t b, int64_t c)
Rescale a 64-bit integer with rounding to nearest.
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
char * av_fourcc_make_string(char *buf, uint32_t fourcc)
Fill the provided buffer with a string containing a FourCC (four-character code) representation.
Definition utils.c:54
#define AV_FOURCC_MAX_STRING_SIZE
Definition avutil.h:321
@ AVMEDIA_TYPE_AUDIO
Definition avutil.h:201
@ AVMEDIA_TYPE_SUBTITLE
Definition avutil.h:203
@ AVMEDIA_TYPE_VIDEO
Definition avutil.h:200
@ AVMEDIA_TYPE_DATA
Opaque data information usually continuous.
Definition avutil.h:202
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition avutil.h:247
#define AV_TIME_BASE
Internal time base represented as integer.
Definition avutil.h:253
misc image utilities
#define AV_WB32(p, v)
static int shift(int a, int b)
Definition bonk.c:261
#define av_cold
Definition attributes.h:117
common internal API header
const uint8_t ff_reverse[256]
Definition reverse.c:23
static const uint16_t mask[17]
Definition lzw.c:38
#define FFMIN(a, b)
Definition macros.h:49
static void input_callback(MMAL_PORT_T *port, MMAL_BUFFER_HEADER_T *buffer)
Definition mmaldec.c:209
const char data[16]
Definition mxf.c:149
#define av_malloc(s)
Definition ops_static.c:52
@ AV_PIX_FMT_BGR0
packed BGR 8:8:8, 32bpp, BGRXBGRX... X=unused/undefined
Definition pixfmt.h:265
@ AV_PIX_FMT_UYVY422
packed YUV 4:2:2, 16bpp, Cb Y0 Cr Y1
Definition pixfmt.h:88
@ AV_PIX_FMT_0RGB
packed RGB 8:8:8, 32bpp, XRGBXRGB... X=unused/undefined
Definition pixfmt.h:262
#define FF_ARRAY_ELEMS(a)
int nb_channels
Number of channels in this layout.
enum AVFieldOrder field_order
The order of the fields in interlaced video.
Definition codec_par.h:182
int height
The height of the video frame in pixels.
Definition codec_par.h:150
AVChannelLayout ch_layout
The channel layout and number of channels.
Definition codec_par.h:207
int width
The width of the video frame in pixels.
Definition codec_par.h:143
int64_t bit_rate
The average bitrate of the encoded data (in bits per second).
Definition codec_par.h:99
enum AVMediaType codec_type
General type of the encoded data.
Definition codec_par.h:53
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition codec_par.h:57
int sample_rate
The number of audio samples per second.
Definition codec_par.h:213
List of devices.
Definition avdevice.h:343
Format I/O context.
Definition avformat.h:1333
char * url
input or output URL.
Definition avformat.h:1449
void * priv_data
Format private data.
Definition avformat.h:1361
This structure stores compressed data.
Definition packet.h:580
int stream_index
Definition packet.h:605
int flags
A combination of AV_PKT_FLAG values.
Definition packet.h:609
int size
Definition packet.h:604
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition packet.h:596
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed.
Definition packet.h:602
uint8_t * data
Definition packet.h:603
Rational number (pair of numerator and denominator).
Definition rational.h:58
int num
Numerator.
Definition rational.h:59
int den
Denominator.
Definition rational.h:60
Stream structure.
Definition avformat.h:766
AVCodecParameters * codecpar
Codec parameters associated with this stream.
Definition avformat.h:789
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented.
Definition avformat.h:805
AVRational r_frame_rate
Real base framerate of the stream.
Definition avformat.h:900
BMDDisplayMode mode
Definition swscale.c:71
#define av_free(p)
#define av_mallocz(s)
#define av_freep(p)
#define av_log(a,...)
static void error(const char *err)
#define src
Definition vp8dsp.c:248
static char buffer[20]
Definition seek.c:32
#define height
Definition dsp.h:89
#define width
Definition dsp.h:89
int av_usleep(unsigned usec)
Sleep for a period of time.
Definition time.c:93
int64_t av_gettime_relative(void)
Get the current time in microseconds since some unspecified starting point.
Definition time.c:57
int64_t av_gettime(void)
Get the current time in microseconds.
Definition time.c:40
int av_timecode_init_from_components(AVTimecode *tc, AVRational rate, int flags, int hh, int mm, int ss, int ff, void *log_ctx)
Init a timecode struct from the passed timecode components.
Definition timecode.c:211
uint32_t av_timecode_get_smpte_from_framenum(const AVTimecode *tc, int framenum)
Convert frame number to SMPTE 12M binary representation.
Definition timecode.c:54
char * av_timecode_make_string(const AVTimecode *tc, char *buf, int framenum_arg)
Load timecode string in buf.
Definition timecode.c:104
Timecode helpers header.
#define AV_TIMECODE_STR_SIZE
Definition timecode.h:33
@ AV_TIMECODE_FLAG_DROPFRAME
timecode is drop frame
Definition timecode.h:36
static int64_t pts
int size
int len