You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1458 lines
50KB

  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. #include <atomic>
  24. #include <vector>
  25. using std::atomic;
  26. /* Include internal.h first to avoid conflict between winsock.h (used by
  27. * DeckLink headers) and winsock2.h (used by libavformat) in MSVC++ builds */
  28. extern "C" {
  29. #include "libavformat/internal.h"
  30. }
  31. #include <DeckLinkAPI.h>
  32. extern "C" {
  33. #include "config.h"
  34. #include "libavformat/avformat.h"
  35. #include "libavutil/avassert.h"
  36. #include "libavutil/avutil.h"
  37. #include "libavutil/common.h"
  38. #include "libavutil/internal.h"
  39. #include "libavutil/imgutils.h"
  40. #include "libavutil/intreadwrite.h"
  41. #include "libavutil/time.h"
  42. #include "libavutil/timecode.h"
  43. #include "libavutil/mathematics.h"
  44. #include "libavutil/reverse.h"
  45. #include "avdevice.h"
  46. #if CONFIG_LIBZVBI
  47. #include <libzvbi.h>
  48. #endif
  49. }
  50. #include "decklink_common.h"
  51. #include "decklink_dec.h"
  52. #define MAX_WIDTH_VANC 1920
  53. const BMDDisplayMode AUTODETECT_DEFAULT_MODE = bmdModeNTSC;
  54. typedef struct VANCLineNumber {
  55. BMDDisplayMode mode;
  56. int vanc_start;
  57. int field0_vanc_end;
  58. int field1_vanc_start;
  59. int vanc_end;
  60. } VANCLineNumber;
  61. /* These VANC line numbers need not be very accurate. In any case
  62. * GetBufferForVerticalBlankingLine() will return an error when invalid
  63. * ancillary line number was requested. We just need to make sure that the
  64. * entire VANC region is covered, while making sure we don't decode VANC of
  65. * another source during switching*/
  66. static VANCLineNumber vanc_line_numbers[] = {
  67. /* SD Modes */
  68. {bmdModeNTSC, 11, 19, 274, 282},
  69. {bmdModeNTSC2398, 11, 19, 274, 282},
  70. {bmdModePAL, 7, 22, 320, 335},
  71. {bmdModeNTSCp, 11, -1, -1, 39},
  72. {bmdModePALp, 7, -1, -1, 45},
  73. /* HD 1080 Modes */
  74. {bmdModeHD1080p2398, 8, -1, -1, 42},
  75. {bmdModeHD1080p24, 8, -1, -1, 42},
  76. {bmdModeHD1080p25, 8, -1, -1, 42},
  77. {bmdModeHD1080p2997, 8, -1, -1, 42},
  78. {bmdModeHD1080p30, 8, -1, -1, 42},
  79. {bmdModeHD1080i50, 8, 20, 570, 585},
  80. {bmdModeHD1080i5994, 8, 20, 570, 585},
  81. {bmdModeHD1080i6000, 8, 20, 570, 585},
  82. {bmdModeHD1080p50, 8, -1, -1, 42},
  83. {bmdModeHD1080p5994, 8, -1, -1, 42},
  84. {bmdModeHD1080p6000, 8, -1, -1, 42},
  85. /* HD 720 Modes */
  86. {bmdModeHD720p50, 8, -1, -1, 26},
  87. {bmdModeHD720p5994, 8, -1, -1, 26},
  88. {bmdModeHD720p60, 8, -1, -1, 26},
  89. /* For all other modes, for which we don't support VANC */
  90. {bmdModeUnknown, 0, -1, -1, -1}
  91. };
  92. class decklink_allocator : public IDeckLinkMemoryAllocator
  93. {
  94. public:
  95. decklink_allocator(): _refs(1) { }
  96. virtual ~decklink_allocator() { }
  97. // IDeckLinkMemoryAllocator methods
  98. virtual HRESULT STDMETHODCALLTYPE AllocateBuffer(unsigned int bufferSize, void* *allocatedBuffer)
  99. {
  100. void *buf = av_malloc(bufferSize + AV_INPUT_BUFFER_PADDING_SIZE);
  101. if (!buf)
  102. return E_OUTOFMEMORY;
  103. *allocatedBuffer = buf;
  104. return S_OK;
  105. }
  106. virtual HRESULT STDMETHODCALLTYPE ReleaseBuffer(void* buffer)
  107. {
  108. av_free(buffer);
  109. return S_OK;
  110. }
  111. virtual HRESULT STDMETHODCALLTYPE Commit() { return S_OK; }
  112. virtual HRESULT STDMETHODCALLTYPE Decommit() { return S_OK; }
  113. // IUnknown methods
  114. virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv) { return E_NOINTERFACE; }
  115. virtual ULONG STDMETHODCALLTYPE AddRef(void) { return ++_refs; }
  116. virtual ULONG STDMETHODCALLTYPE Release(void)
  117. {
  118. int ret = --_refs;
  119. if (!ret)
  120. delete this;
  121. return ret;
  122. }
  123. private:
  124. std::atomic<int> _refs;
  125. };
  126. extern "C" {
  127. static void decklink_object_free(void *opaque, uint8_t *data)
  128. {
  129. IUnknown *obj = (class IUnknown *)opaque;
  130. obj->Release();
  131. }
  132. }
  133. static int get_vanc_line_idx(BMDDisplayMode mode)
  134. {
  135. unsigned int i;
  136. for (i = 0; i < FF_ARRAY_ELEMS(vanc_line_numbers); i++) {
  137. if (mode == vanc_line_numbers[i].mode)
  138. return i;
  139. }
  140. /* Return the VANC idx for Unknown mode */
  141. return i - 1;
  142. }
  143. static inline void clear_parity_bits(uint16_t *buf, int len) {
  144. int i;
  145. for (i = 0; i < len; i++)
  146. buf[i] &= 0xff;
  147. }
  148. static int check_vanc_parity_checksum(uint16_t *buf, int len, uint16_t checksum) {
  149. int i;
  150. uint16_t vanc_sum = 0;
  151. for (i = 3; i < len - 1; i++) {
  152. uint16_t v = buf[i];
  153. int np = v >> 8;
  154. int p = av_parity(v & 0xff);
  155. if ((!!p ^ !!(v & 0x100)) || (np != 1 && np != 2)) {
  156. // Parity check failed
  157. return -1;
  158. }
  159. vanc_sum += v;
  160. }
  161. vanc_sum &= 0x1ff;
  162. vanc_sum |= ((~vanc_sum & 0x100) << 1);
  163. if (checksum != vanc_sum) {
  164. // Checksum verification failed
  165. return -1;
  166. }
  167. return 0;
  168. }
  169. /* The 10-bit VANC data is packed in V210, we only need the luma component. */
  170. static void extract_luma_from_v210(uint16_t *dst, const uint8_t *src, int width)
  171. {
  172. int i;
  173. for (i = 0; i < width / 3; i++) {
  174. *dst++ = (src[1] >> 2) + ((src[2] & 15) << 6);
  175. *dst++ = src[4] + ((src[5] & 3) << 8);
  176. *dst++ = (src[6] >> 4) + ((src[7] & 63) << 4);
  177. src += 8;
  178. }
  179. }
  180. static void unpack_v210(uint16_t *dst, const uint8_t *src, int width)
  181. {
  182. int i;
  183. for (i = 0; i < width * 2 / 3; i++) {
  184. *dst++ = src[0] + ((src[1] & 3) << 8);
  185. *dst++ = (src[1] >> 2) + ((src[2] & 15) << 6);
  186. *dst++ = (src[2] >> 4) + ((src[3] & 63) << 4);
  187. src += 4;
  188. }
  189. }
  190. static uint8_t calc_parity_and_line_offset(int line)
  191. {
  192. uint8_t ret = (line < 313) << 5;
  193. if (line >= 7 && line <= 22)
  194. ret += line;
  195. if (line >= 320 && line <= 335)
  196. ret += (line - 313);
  197. return ret;
  198. }
  199. static void fill_data_unit_head(int line, uint8_t *tgt)
  200. {
  201. tgt[0] = 0x02; // data_unit_id
  202. tgt[1] = 0x2c; // data_unit_length
  203. tgt[2] = calc_parity_and_line_offset(line); // field_parity, line_offset
  204. tgt[3] = 0xe4; // framing code
  205. }
  206. #if CONFIG_LIBZVBI
  207. static uint8_t* teletext_data_unit_from_vbi_data(int line, uint8_t *src, uint8_t *tgt, vbi_pixfmt fmt)
  208. {
  209. vbi_bit_slicer slicer;
  210. vbi_bit_slicer_init(&slicer, 720, 13500000, 6937500, 6937500, 0x00aaaae4, 0xffff, 18, 6, 42 * 8, VBI_MODULATION_NRZ_MSB, fmt);
  211. if (vbi_bit_slice(&slicer, src, tgt + 4) == FALSE)
  212. return tgt;
  213. fill_data_unit_head(line, tgt);
  214. return tgt + 46;
  215. }
  216. static uint8_t* teletext_data_unit_from_vbi_data_10bit(int line, uint8_t *src, uint8_t *tgt)
  217. {
  218. uint8_t y[720];
  219. uint8_t *py = y;
  220. uint8_t *pend = y + 720;
  221. /* The 10-bit VBI data is packed in V210, but libzvbi only supports 8-bit,
  222. * so we extract the 8 MSBs of the luma component, that is enough for
  223. * teletext bit slicing. */
  224. while (py < pend) {
  225. *py++ = (src[1] >> 4) + ((src[2] & 15) << 4);
  226. *py++ = (src[4] >> 2) + ((src[5] & 3 ) << 6);
  227. *py++ = (src[6] >> 6) + ((src[7] & 63) << 2);
  228. src += 8;
  229. }
  230. return teletext_data_unit_from_vbi_data(line, y, tgt, VBI_PIXFMT_YUV420);
  231. }
  232. #endif
  233. static uint8_t* teletext_data_unit_from_op47_vbi_packet(int line, uint16_t *py, uint8_t *tgt)
  234. {
  235. int i;
  236. if (py[0] != 0x255 || py[1] != 0x255 || py[2] != 0x227)
  237. return tgt;
  238. fill_data_unit_head(line, tgt);
  239. py += 3;
  240. tgt += 4;
  241. for (i = 0; i < 42; i++)
  242. *tgt++ = ff_reverse[py[i] & 255];
  243. return tgt;
  244. }
  245. static int linemask_matches(int line, int64_t mask)
  246. {
  247. int shift = -1;
  248. if (line >= 6 && line <= 22)
  249. shift = line - 6;
  250. if (line >= 318 && line <= 335)
  251. shift = line - 318 + 17;
  252. return shift >= 0 && ((1ULL << shift) & mask);
  253. }
  254. static uint8_t* teletext_data_unit_from_op47_data(uint16_t *py, uint16_t *pend, uint8_t *tgt, int64_t wanted_lines)
  255. {
  256. if (py < pend - 9) {
  257. if (py[0] == 0x151 && py[1] == 0x115 && py[3] == 0x102) { // identifier, identifier, format code for WST teletext
  258. uint16_t *descriptors = py + 4;
  259. int i;
  260. py += 9;
  261. for (i = 0; i < 5 && py < pend - 45; i++, py += 45) {
  262. int line = (descriptors[i] & 31) + (!(descriptors[i] & 128)) * 313;
  263. if (line && linemask_matches(line, wanted_lines))
  264. tgt = teletext_data_unit_from_op47_vbi_packet(line, py, tgt);
  265. }
  266. }
  267. }
  268. return tgt;
  269. }
  270. 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)
  271. {
  272. uint16_t did = py[0]; // data id
  273. uint16_t sdid = py[1]; // secondary data id
  274. uint16_t dc = py[2] & 255; // data count
  275. py += 3;
  276. pend = FFMIN(pend, py + dc);
  277. if (did == 0x143 && sdid == 0x102) { // subtitle distribution packet
  278. tgt = teletext_data_unit_from_op47_data(py, pend, tgt, wanted_lines);
  279. } else if (allow_multipacket && did == 0x143 && sdid == 0x203) { // VANC multipacket
  280. py += 2; // priority, line/field
  281. while (py < pend - 3) {
  282. tgt = teletext_data_unit_from_ancillary_packet(py, pend, tgt, wanted_lines, 0);
  283. py += 4 + (py[2] & 255); // ndid, nsdid, ndc, line/field
  284. }
  285. }
  286. return tgt;
  287. }
  288. static uint8_t *vanc_to_cc(AVFormatContext *avctx, uint16_t *buf, size_t words,
  289. unsigned &cc_count)
  290. {
  291. size_t i, len = (buf[5] & 0xff) + 6 + 1;
  292. uint8_t cdp_sum, rate;
  293. uint16_t hdr, ftr;
  294. uint8_t *cc;
  295. uint16_t *cdp = &buf[6]; // CDP follows
  296. if (cdp[0] != 0x96 || cdp[1] != 0x69) {
  297. av_log(avctx, AV_LOG_WARNING, "Invalid CDP header 0x%.2x 0x%.2x\n", cdp[0], cdp[1]);
  298. return NULL;
  299. }
  300. len -= 7; // remove VANC header and checksum
  301. if (cdp[2] != len) {
  302. av_log(avctx, AV_LOG_WARNING, "CDP len %d != %zu\n", cdp[2], len);
  303. return NULL;
  304. }
  305. cdp_sum = 0;
  306. for (i = 0; i < len - 1; i++)
  307. cdp_sum += cdp[i];
  308. cdp_sum = cdp_sum ? 256 - cdp_sum : 0;
  309. if (cdp[len - 1] != cdp_sum) {
  310. av_log(avctx, AV_LOG_WARNING, "CDP checksum invalid 0x%.4x != 0x%.4x\n", cdp_sum, cdp[len-1]);
  311. return NULL;
  312. }
  313. rate = cdp[3];
  314. if (!(rate & 0x0f)) {
  315. av_log(avctx, AV_LOG_WARNING, "CDP frame rate invalid (0x%.2x)\n", rate);
  316. return NULL;
  317. }
  318. rate >>= 4;
  319. if (rate > 8) {
  320. av_log(avctx, AV_LOG_WARNING, "CDP frame rate invalid (0x%.2x)\n", rate);
  321. return NULL;
  322. }
  323. if (!(cdp[4] & 0x43)) /* ccdata_present | caption_service_active | reserved */ {
  324. av_log(avctx, AV_LOG_WARNING, "CDP flags invalid (0x%.2x)\n", cdp[4]);
  325. return NULL;
  326. }
  327. hdr = (cdp[5] << 8) | cdp[6];
  328. if (cdp[7] != 0x72) /* ccdata_id */ {
  329. av_log(avctx, AV_LOG_WARNING, "Invalid ccdata_id 0x%.2x\n", cdp[7]);
  330. return NULL;
  331. }
  332. cc_count = cdp[8];
  333. if (!(cc_count & 0xe0)) {
  334. av_log(avctx, AV_LOG_WARNING, "Invalid cc_count 0x%.2x\n", cc_count);
  335. return NULL;
  336. }
  337. cc_count &= 0x1f;
  338. if ((len - 13) < cc_count * 3) {
  339. av_log(avctx, AV_LOG_WARNING, "Invalid cc_count %d (> %zu)\n", cc_count * 3, len - 13);
  340. return NULL;
  341. }
  342. if (cdp[len - 4] != 0x74) /* footer id */ {
  343. av_log(avctx, AV_LOG_WARNING, "Invalid footer id 0x%.2x\n", cdp[len-4]);
  344. return NULL;
  345. }
  346. ftr = (cdp[len - 3] << 8) | cdp[len - 2];
  347. if (ftr != hdr) {
  348. av_log(avctx, AV_LOG_WARNING, "Header 0x%.4x != Footer 0x%.4x\n", hdr, ftr);
  349. return NULL;
  350. }
  351. cc = (uint8_t *)av_malloc(cc_count * 3);
  352. if (cc == NULL) {
  353. av_log(avctx, AV_LOG_WARNING, "CC - av_malloc failed for cc_count = %d\n", cc_count);
  354. return NULL;
  355. }
  356. for (size_t i = 0; i < cc_count; i++) {
  357. cc[3*i + 0] = cdp[9 + 3*i+0] /* & 3 */;
  358. cc[3*i + 1] = cdp[9 + 3*i+1];
  359. cc[3*i + 2] = cdp[9 + 3*i+2];
  360. }
  361. cc_count *= 3;
  362. return cc;
  363. }
  364. static uint8_t *get_metadata(AVFormatContext *avctx, uint16_t *buf, size_t width,
  365. uint8_t *tgt, size_t tgt_size, AVPacket *pkt)
  366. {
  367. decklink_cctx *cctx = (struct decklink_cctx *) avctx->priv_data;
  368. uint16_t *max_buf = buf + width;
  369. while (buf < max_buf - 6) {
  370. int len;
  371. uint16_t did = buf[3] & 0xFF; // data id
  372. uint16_t sdid = buf[4] & 0xFF; // secondary data id
  373. /* Check for VANC header */
  374. if (buf[0] != 0 || buf[1] != 0x3ff || buf[2] != 0x3ff) {
  375. return tgt;
  376. }
  377. len = (buf[5] & 0xff) + 6 + 1;
  378. if (len > max_buf - buf) {
  379. av_log(avctx, AV_LOG_WARNING, "Data Count (%d) > data left (%zu)\n",
  380. len, max_buf - buf);
  381. return tgt;
  382. }
  383. if (did == 0x43 && (sdid == 0x02 || sdid == 0x03) && cctx->teletext_lines &&
  384. width == 1920 && tgt_size >= 1920) {
  385. if (check_vanc_parity_checksum(buf, len, buf[len - 1]) < 0) {
  386. av_log(avctx, AV_LOG_WARNING, "VANC parity or checksum incorrect\n");
  387. goto skip_packet;
  388. }
  389. tgt = teletext_data_unit_from_ancillary_packet(buf + 3, buf + len, tgt, cctx->teletext_lines, 1);
  390. } else if (did == 0x61 && sdid == 0x01) {
  391. unsigned int data_len;
  392. uint8_t *data;
  393. if (check_vanc_parity_checksum(buf, len, buf[len - 1]) < 0) {
  394. av_log(avctx, AV_LOG_WARNING, "VANC parity or checksum incorrect\n");
  395. goto skip_packet;
  396. }
  397. clear_parity_bits(buf, len);
  398. data = vanc_to_cc(avctx, buf, width, data_len);
  399. if (data) {
  400. if (av_packet_add_side_data(pkt, AV_PKT_DATA_A53_CC, data, data_len) < 0)
  401. av_free(data);
  402. }
  403. } else {
  404. av_log(avctx, AV_LOG_DEBUG, "Unknown meta data DID = 0x%.2x SDID = 0x%.2x\n",
  405. did, sdid);
  406. }
  407. skip_packet:
  408. buf += len;
  409. }
  410. return tgt;
  411. }
  412. static void avpacket_queue_init(AVFormatContext *avctx, AVPacketQueue *q)
  413. {
  414. struct decklink_cctx *ctx = (struct decklink_cctx *)avctx->priv_data;
  415. memset(q, 0, sizeof(AVPacketQueue));
  416. pthread_mutex_init(&q->mutex, NULL);
  417. pthread_cond_init(&q->cond, NULL);
  418. q->avctx = avctx;
  419. q->max_q_size = ctx->queue_size;
  420. }
  421. static void avpacket_queue_flush(AVPacketQueue *q)
  422. {
  423. AVPacketList *pkt, *pkt1;
  424. pthread_mutex_lock(&q->mutex);
  425. for (pkt = q->first_pkt; pkt != NULL; pkt = pkt1) {
  426. pkt1 = pkt->next;
  427. av_packet_unref(&pkt->pkt);
  428. av_freep(&pkt);
  429. }
  430. q->last_pkt = NULL;
  431. q->first_pkt = NULL;
  432. q->nb_packets = 0;
  433. q->size = 0;
  434. pthread_mutex_unlock(&q->mutex);
  435. }
  436. static void avpacket_queue_end(AVPacketQueue *q)
  437. {
  438. avpacket_queue_flush(q);
  439. pthread_mutex_destroy(&q->mutex);
  440. pthread_cond_destroy(&q->cond);
  441. }
  442. static unsigned long long avpacket_queue_size(AVPacketQueue *q)
  443. {
  444. unsigned long long size;
  445. pthread_mutex_lock(&q->mutex);
  446. size = q->size;
  447. pthread_mutex_unlock(&q->mutex);
  448. return size;
  449. }
  450. static int avpacket_queue_put(AVPacketQueue *q, AVPacket *pkt)
  451. {
  452. AVPacketList *pkt1;
  453. // Drop Packet if queue size is > maximum queue size
  454. if (avpacket_queue_size(q) > (uint64_t)q->max_q_size) {
  455. av_packet_unref(pkt);
  456. av_log(q->avctx, AV_LOG_WARNING, "Decklink input buffer overrun!\n");
  457. return -1;
  458. }
  459. /* ensure the packet is reference counted */
  460. if (av_packet_make_refcounted(pkt) < 0) {
  461. av_packet_unref(pkt);
  462. return -1;
  463. }
  464. pkt1 = (AVPacketList *)av_malloc(sizeof(AVPacketList));
  465. if (!pkt1) {
  466. av_packet_unref(pkt);
  467. return -1;
  468. }
  469. av_packet_move_ref(&pkt1->pkt, pkt);
  470. pkt1->next = NULL;
  471. pthread_mutex_lock(&q->mutex);
  472. if (!q->last_pkt) {
  473. q->first_pkt = pkt1;
  474. } else {
  475. q->last_pkt->next = pkt1;
  476. }
  477. q->last_pkt = pkt1;
  478. q->nb_packets++;
  479. q->size += pkt1->pkt.size + sizeof(*pkt1);
  480. pthread_cond_signal(&q->cond);
  481. pthread_mutex_unlock(&q->mutex);
  482. return 0;
  483. }
  484. static int avpacket_queue_get(AVPacketQueue *q, AVPacket *pkt, int block)
  485. {
  486. AVPacketList *pkt1;
  487. int ret;
  488. pthread_mutex_lock(&q->mutex);
  489. for (;; ) {
  490. pkt1 = q->first_pkt;
  491. if (pkt1) {
  492. q->first_pkt = pkt1->next;
  493. if (!q->first_pkt) {
  494. q->last_pkt = NULL;
  495. }
  496. q->nb_packets--;
  497. q->size -= pkt1->pkt.size + sizeof(*pkt1);
  498. *pkt = pkt1->pkt;
  499. av_free(pkt1);
  500. ret = 1;
  501. break;
  502. } else if (!block) {
  503. ret = 0;
  504. break;
  505. } else {
  506. pthread_cond_wait(&q->cond, &q->mutex);
  507. }
  508. }
  509. pthread_mutex_unlock(&q->mutex);
  510. return ret;
  511. }
  512. static void handle_klv(AVFormatContext *avctx, decklink_ctx *ctx, IDeckLinkVideoInputFrame *videoFrame, int64_t pts)
  513. {
  514. const uint8_t KLV_DID = 0x44;
  515. const uint8_t KLV_IN_VANC_SDID = 0x04;
  516. struct KLVPacket
  517. {
  518. uint16_t sequence_counter;
  519. std::vector<uint8_t> data;
  520. };
  521. size_t total_size = 0;
  522. std::vector<std::vector<KLVPacket>> klv_packets(256);
  523. IDeckLinkVideoFrameAncillaryPackets *packets = nullptr;
  524. if (videoFrame->QueryInterface(IID_IDeckLinkVideoFrameAncillaryPackets, (void**)&packets) != S_OK)
  525. return;
  526. IDeckLinkAncillaryPacketIterator *it = nullptr;
  527. if (packets->GetPacketIterator(&it) != S_OK) {
  528. packets->Release();
  529. return;
  530. }
  531. IDeckLinkAncillaryPacket *packet = nullptr;
  532. while (it->Next(&packet) == S_OK) {
  533. uint8_t *data = nullptr;
  534. uint32_t size = 0;
  535. if (packet->GetDID() == KLV_DID && packet->GetSDID() == KLV_IN_VANC_SDID) {
  536. av_log(avctx, AV_LOG_DEBUG, "Found KLV VANC packet on line: %d\n", packet->GetLineNumber());
  537. if (packet->GetBytes(bmdAncillaryPacketFormatUInt8, (const void**) &data, &size) == S_OK) {
  538. // MID and PSC
  539. if (size > 3) {
  540. uint8_t mid = data[0];
  541. uint16_t psc = data[1] << 8 | data[2];
  542. av_log(avctx, AV_LOG_DEBUG, "KLV with MID: %d and PSC: %d\n", mid, psc);
  543. auto& list = klv_packets[mid];
  544. uint16_t expected_psc = list.size() + 1;
  545. if (psc == expected_psc) {
  546. uint32_t data_len = size - 3;
  547. total_size += data_len;
  548. KLVPacket packet{ psc };
  549. packet.data.resize(data_len);
  550. memcpy(packet.data.data(), data + 3, data_len);
  551. list.push_back(std::move(packet));
  552. } else {
  553. av_log(avctx, AV_LOG_WARNING, "Out of order PSC: %d for MID: %d\n", psc, mid);
  554. if (!list.empty()) {
  555. for (auto& klv : list)
  556. total_size -= klv.data.size();
  557. list.clear();
  558. }
  559. }
  560. }
  561. }
  562. }
  563. packet->Release();
  564. }
  565. it->Release();
  566. packets->Release();
  567. if (total_size > 0) {
  568. std::vector<uint8_t> klv;
  569. klv.reserve(total_size);
  570. for (size_t i = 0; i < klv_packets.size(); ++i) {
  571. auto& list = klv_packets[i];
  572. if (list.empty())
  573. continue;
  574. av_log(avctx, AV_LOG_DEBUG, "Joining MID: %d\n", (int)i);
  575. for (auto& packet : list)
  576. klv.insert(klv.end(), packet.data.begin(), packet.data.end());
  577. }
  578. AVPacket klv_packet;
  579. av_init_packet(&klv_packet);
  580. klv_packet.pts = pts;
  581. klv_packet.dts = pts;
  582. klv_packet.flags |= AV_PKT_FLAG_KEY;
  583. klv_packet.stream_index = ctx->klv_st->index;
  584. klv_packet.data = klv.data();
  585. klv_packet.size = klv.size();
  586. if (avpacket_queue_put(&ctx->queue, &klv_packet) < 0) {
  587. ++ctx->dropped;
  588. }
  589. }
  590. }
  591. class decklink_input_callback : public IDeckLinkInputCallback
  592. {
  593. public:
  594. decklink_input_callback(AVFormatContext *_avctx);
  595. ~decklink_input_callback();
  596. virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv) { return E_NOINTERFACE; }
  597. virtual ULONG STDMETHODCALLTYPE AddRef(void);
  598. virtual ULONG STDMETHODCALLTYPE Release(void);
  599. virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents, IDeckLinkDisplayMode*, BMDDetectedVideoInputFormatFlags);
  600. virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame*, IDeckLinkAudioInputPacket*);
  601. private:
  602. std::atomic<int> _refs;
  603. AVFormatContext *avctx;
  604. decklink_ctx *ctx;
  605. int no_video;
  606. int64_t initial_video_pts;
  607. int64_t initial_audio_pts;
  608. };
  609. decklink_input_callback::decklink_input_callback(AVFormatContext *_avctx) : _refs(1)
  610. {
  611. avctx = _avctx;
  612. decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
  613. ctx = (struct decklink_ctx *)cctx->ctx;
  614. no_video = 0;
  615. initial_audio_pts = initial_video_pts = AV_NOPTS_VALUE;
  616. }
  617. decklink_input_callback::~decklink_input_callback()
  618. {
  619. }
  620. ULONG decklink_input_callback::AddRef(void)
  621. {
  622. return ++_refs;
  623. }
  624. ULONG decklink_input_callback::Release(void)
  625. {
  626. int ret = --_refs;
  627. if (!ret)
  628. delete this;
  629. return ret;
  630. }
  631. static int64_t get_pkt_pts(IDeckLinkVideoInputFrame *videoFrame,
  632. IDeckLinkAudioInputPacket *audioFrame,
  633. int64_t wallclock,
  634. int64_t abs_wallclock,
  635. DecklinkPtsSource pts_src,
  636. AVRational time_base, int64_t *initial_pts,
  637. int copyts)
  638. {
  639. int64_t pts = AV_NOPTS_VALUE;
  640. BMDTimeValue bmd_pts;
  641. BMDTimeValue bmd_duration;
  642. HRESULT res = E_INVALIDARG;
  643. switch (pts_src) {
  644. case PTS_SRC_AUDIO:
  645. if (audioFrame)
  646. res = audioFrame->GetPacketTime(&bmd_pts, time_base.den);
  647. break;
  648. case PTS_SRC_VIDEO:
  649. if (videoFrame)
  650. res = videoFrame->GetStreamTime(&bmd_pts, &bmd_duration, time_base.den);
  651. break;
  652. case PTS_SRC_REFERENCE:
  653. if (videoFrame)
  654. res = videoFrame->GetHardwareReferenceTimestamp(time_base.den, &bmd_pts, &bmd_duration);
  655. break;
  656. case PTS_SRC_WALLCLOCK:
  657. /* fall through */
  658. case PTS_SRC_ABS_WALLCLOCK:
  659. {
  660. /* MSVC does not support compound literals like AV_TIME_BASE_Q
  661. * in C++ code (compiler error C4576) */
  662. AVRational timebase;
  663. timebase.num = 1;
  664. timebase.den = AV_TIME_BASE;
  665. if (pts_src == PTS_SRC_WALLCLOCK)
  666. pts = av_rescale_q(wallclock, timebase, time_base);
  667. else
  668. pts = av_rescale_q(abs_wallclock, timebase, time_base);
  669. break;
  670. }
  671. }
  672. if (res == S_OK)
  673. pts = bmd_pts / time_base.num;
  674. if (!copyts) {
  675. if (pts != AV_NOPTS_VALUE && *initial_pts == AV_NOPTS_VALUE)
  676. *initial_pts = pts;
  677. if (*initial_pts != AV_NOPTS_VALUE)
  678. pts -= *initial_pts;
  679. }
  680. return pts;
  681. }
  682. static int get_bmd_timecode(AVFormatContext *avctx, AVTimecode *tc, AVRational frame_rate, BMDTimecodeFormat tc_format, IDeckLinkVideoInputFrame *videoFrame)
  683. {
  684. IDeckLinkTimecode *timecode;
  685. int ret = AVERROR(ENOENT);
  686. #if BLACKMAGIC_DECKLINK_API_VERSION >= 0x0b000000
  687. int hfr = (tc_format == bmdTimecodeRP188HighFrameRate);
  688. #else
  689. int hfr = 0;
  690. #endif
  691. if (videoFrame->GetTimecode(tc_format, &timecode) == S_OK) {
  692. uint8_t hh, mm, ss, ff;
  693. if (timecode->GetComponents(&hh, &mm, &ss, &ff) == S_OK) {
  694. int flags = (timecode->GetFlags() & bmdTimecodeIsDropFrame) ? AV_TIMECODE_FLAG_DROPFRAME : 0;
  695. if (!hfr && av_cmp_q(frame_rate, av_make_q(30, 1)) == 1)
  696. ff = ff << 1 | !!(timecode->GetFlags() & bmdTimecodeFieldMark);
  697. ret = av_timecode_init_from_components(tc, frame_rate, flags, hh, mm, ss, ff, avctx);
  698. }
  699. timecode->Release();
  700. }
  701. return ret;
  702. }
  703. static int get_frame_timecode(AVFormatContext *avctx, decklink_ctx *ctx, AVTimecode *tc, IDeckLinkVideoInputFrame *videoFrame)
  704. {
  705. AVRational frame_rate = ctx->video_st->r_frame_rate;
  706. int ret;
  707. /* 50/60 fps content has alternating VITC1 and VITC2 timecode (see SMPTE ST
  708. * 12-2, section 7), so the native ordering of RP188Any (HFR, VITC1, LTC,
  709. * VITC2) would not work because LTC might not contain the field flag.
  710. * Therefore we query the types manually. */
  711. if (ctx->tc_format == bmdTimecodeRP188Any && av_cmp_q(frame_rate, av_make_q(30, 1)) == 1) {
  712. #if BLACKMAGIC_DECKLINK_API_VERSION >= 0x0b000000
  713. ret = get_bmd_timecode(avctx, tc, frame_rate, bmdTimecodeRP188HighFrameRate, videoFrame);
  714. if (ret == AVERROR(ENOENT))
  715. #endif
  716. ret = get_bmd_timecode(avctx, tc, frame_rate, bmdTimecodeRP188VITC1, videoFrame);
  717. if (ret == AVERROR(ENOENT))
  718. ret = get_bmd_timecode(avctx, tc, frame_rate, bmdTimecodeRP188VITC2, videoFrame);
  719. if (ret == AVERROR(ENOENT))
  720. ret = get_bmd_timecode(avctx, tc, frame_rate, bmdTimecodeRP188LTC, videoFrame);
  721. } else {
  722. ret = get_bmd_timecode(avctx, tc, frame_rate, ctx->tc_format, videoFrame);
  723. }
  724. return ret;
  725. }
  726. HRESULT decklink_input_callback::VideoInputFrameArrived(
  727. IDeckLinkVideoInputFrame *videoFrame, IDeckLinkAudioInputPacket *audioFrame)
  728. {
  729. void *frameBytes;
  730. void *audioFrameBytes;
  731. BMDTimeValue frameTime;
  732. BMDTimeValue frameDuration;
  733. int64_t wallclock = 0, abs_wallclock = 0;
  734. struct decklink_cctx *cctx = (struct decklink_cctx *) avctx->priv_data;
  735. if (ctx->autodetect) {
  736. if (videoFrame && !(videoFrame->GetFlags() & bmdFrameHasNoInputSource) &&
  737. ctx->bmd_mode == bmdModeUnknown)
  738. {
  739. ctx->bmd_mode = AUTODETECT_DEFAULT_MODE;
  740. }
  741. return S_OK;
  742. }
  743. // Drop the frames till system's timestamp aligns with the configured value.
  744. if (0 == ctx->frameCount && cctx->timestamp_align) {
  745. AVRational remainder = av_make_q(av_gettime() % cctx->timestamp_align, 1000000);
  746. AVRational frame_duration = av_inv_q(ctx->video_st->r_frame_rate);
  747. if (av_cmp_q(remainder, frame_duration) > 0) {
  748. ++ctx->dropped;
  749. return S_OK;
  750. }
  751. }
  752. ctx->frameCount++;
  753. if (ctx->audio_pts_source == PTS_SRC_WALLCLOCK || ctx->video_pts_source == PTS_SRC_WALLCLOCK)
  754. wallclock = av_gettime_relative();
  755. if (ctx->audio_pts_source == PTS_SRC_ABS_WALLCLOCK || ctx->video_pts_source == PTS_SRC_ABS_WALLCLOCK)
  756. abs_wallclock = av_gettime();
  757. // Handle Video Frame
  758. if (videoFrame) {
  759. AVPacket pkt;
  760. av_init_packet(&pkt);
  761. if (ctx->frameCount % 25 == 0) {
  762. unsigned long long qsize = avpacket_queue_size(&ctx->queue);
  763. av_log(avctx, AV_LOG_DEBUG,
  764. "Frame received (#%lu) - Valid (%liB) - QSize %fMB\n",
  765. ctx->frameCount,
  766. videoFrame->GetRowBytes() * videoFrame->GetHeight(),
  767. (double)qsize / 1024 / 1024);
  768. }
  769. videoFrame->GetBytes(&frameBytes);
  770. videoFrame->GetStreamTime(&frameTime, &frameDuration,
  771. ctx->video_st->time_base.den);
  772. if (videoFrame->GetFlags() & bmdFrameHasNoInputSource) {
  773. if (ctx->draw_bars && videoFrame->GetPixelFormat() == bmdFormat8BitYUV) {
  774. unsigned bars[8] = {
  775. 0xEA80EA80, 0xD292D210, 0xA910A9A5, 0x90229035,
  776. 0x6ADD6ACA, 0x51EF515A, 0x286D28EF, 0x10801080 };
  777. int width = videoFrame->GetWidth();
  778. int height = videoFrame->GetHeight();
  779. unsigned *p = (unsigned *)frameBytes;
  780. for (int y = 0; y < height; y++) {
  781. for (int x = 0; x < width; x += 2)
  782. *p++ = bars[(x * 8) / width];
  783. }
  784. }
  785. if (!no_video) {
  786. av_log(avctx, AV_LOG_WARNING, "Frame received (#%lu) - No input signal detected "
  787. "- Frames dropped %u\n", ctx->frameCount, ++ctx->dropped);
  788. }
  789. no_video = 1;
  790. } else {
  791. if (no_video) {
  792. av_log(avctx, AV_LOG_WARNING, "Frame received (#%lu) - Input returned "
  793. "- Frames dropped %u\n", ctx->frameCount, ++ctx->dropped);
  794. }
  795. no_video = 0;
  796. // Handle Timecode (if requested)
  797. if (ctx->tc_format) {
  798. AVTimecode tcr;
  799. if (get_frame_timecode(avctx, ctx, &tcr, videoFrame) >= 0) {
  800. char tcstr[AV_TIMECODE_STR_SIZE];
  801. const char *tc = av_timecode_make_string(&tcr, tcstr, 0);
  802. if (tc) {
  803. AVDictionary* metadata_dict = NULL;
  804. int metadata_len;
  805. uint8_t* packed_metadata;
  806. if (av_cmp_q(ctx->video_st->r_frame_rate, av_make_q(60, 1)) < 1) {
  807. uint32_t tc_data = av_timecode_get_smpte_from_framenum(&tcr, 0);
  808. int size = sizeof(uint32_t) * 4;
  809. uint32_t *sd = (uint32_t *)av_packet_new_side_data(&pkt, AV_PKT_DATA_S12M_TIMECODE, size);
  810. if (sd) {
  811. *sd = 1; // one TC
  812. *(sd + 1) = tc_data; // TC
  813. }
  814. }
  815. if (av_dict_set(&metadata_dict, "timecode", tc, 0) >= 0) {
  816. packed_metadata = av_packet_pack_dictionary(metadata_dict, &metadata_len);
  817. av_dict_free(&metadata_dict);
  818. if (packed_metadata) {
  819. if (av_packet_add_side_data(&pkt, AV_PKT_DATA_STRINGS_METADATA, packed_metadata, metadata_len) < 0)
  820. av_freep(&packed_metadata);
  821. else if (!ctx->tc_seen)
  822. ctx->tc_seen = ctx->frameCount;
  823. }
  824. }
  825. }
  826. } else {
  827. av_log(avctx, AV_LOG_DEBUG, "Unable to find timecode.\n");
  828. }
  829. }
  830. }
  831. if (ctx->tc_format && cctx->wait_for_tc && !ctx->tc_seen) {
  832. av_log(avctx, AV_LOG_WARNING, "No TC detected yet. wait_for_tc set. Dropping. \n");
  833. av_log(avctx, AV_LOG_WARNING, "Frame received (#%lu) - "
  834. "- Frames dropped %u\n", ctx->frameCount, ++ctx->dropped);
  835. return S_OK;
  836. }
  837. pkt.pts = get_pkt_pts(videoFrame, audioFrame, wallclock, abs_wallclock, ctx->video_pts_source, ctx->video_st->time_base, &initial_video_pts, cctx->copyts);
  838. pkt.dts = pkt.pts;
  839. pkt.duration = frameDuration;
  840. //To be made sure it still applies
  841. pkt.flags |= AV_PKT_FLAG_KEY;
  842. pkt.stream_index = ctx->video_st->index;
  843. pkt.data = (uint8_t *)frameBytes;
  844. pkt.size = videoFrame->GetRowBytes() *
  845. videoFrame->GetHeight();
  846. //fprintf(stderr,"Video Frame size %d ts %d\n", pkt.size, pkt.pts);
  847. if (!no_video) {
  848. IDeckLinkVideoFrameAncillary *vanc;
  849. AVPacket txt_pkt;
  850. uint8_t txt_buf0[3531]; // 35 * 46 bytes decoded teletext lines + 1 byte data_identifier + 1920 bytes OP47 decode buffer
  851. uint8_t *txt_buf = txt_buf0;
  852. if (ctx->enable_klv) {
  853. handle_klv(avctx, ctx, videoFrame, pkt.pts);
  854. }
  855. if (videoFrame->GetAncillaryData(&vanc) == S_OK) {
  856. int i;
  857. BMDPixelFormat vanc_format = vanc->GetPixelFormat();
  858. txt_buf[0] = 0x10; // data_identifier - EBU_data
  859. txt_buf++;
  860. #if CONFIG_LIBZVBI
  861. if (ctx->bmd_mode == bmdModePAL && ctx->teletext_lines &&
  862. (vanc_format == bmdFormat8BitYUV || vanc_format == bmdFormat10BitYUV)) {
  863. int64_t line_mask = 1;
  864. av_assert0(videoFrame->GetWidth() == 720);
  865. for (i = 6; i < 336; i++, line_mask <<= 1) {
  866. uint8_t *buf;
  867. if ((ctx->teletext_lines & line_mask) && vanc->GetBufferForVerticalBlankingLine(i, (void**)&buf) == S_OK) {
  868. if (vanc_format == bmdFormat8BitYUV)
  869. txt_buf = teletext_data_unit_from_vbi_data(i, buf, txt_buf, VBI_PIXFMT_UYVY);
  870. else
  871. txt_buf = teletext_data_unit_from_vbi_data_10bit(i, buf, txt_buf);
  872. }
  873. if (i == 22)
  874. i = 317;
  875. }
  876. }
  877. #endif
  878. if (vanc_format == bmdFormat10BitYUV && videoFrame->GetWidth() <= MAX_WIDTH_VANC) {
  879. int idx = get_vanc_line_idx(ctx->bmd_mode);
  880. for (i = vanc_line_numbers[idx].vanc_start; i <= vanc_line_numbers[idx].vanc_end; i++) {
  881. uint8_t *buf;
  882. if (vanc->GetBufferForVerticalBlankingLine(i, (void**)&buf) == S_OK) {
  883. uint16_t vanc[MAX_WIDTH_VANC];
  884. size_t vanc_size = videoFrame->GetWidth();
  885. if (ctx->bmd_mode == bmdModeNTSC && videoFrame->GetWidth() * 2 <= MAX_WIDTH_VANC) {
  886. vanc_size = vanc_size * 2;
  887. unpack_v210(vanc, buf, videoFrame->GetWidth());
  888. } else {
  889. extract_luma_from_v210(vanc, buf, videoFrame->GetWidth());
  890. }
  891. txt_buf = get_metadata(avctx, vanc, vanc_size,
  892. txt_buf, sizeof(txt_buf0) - (txt_buf - txt_buf0), &pkt);
  893. }
  894. if (i == vanc_line_numbers[idx].field0_vanc_end)
  895. i = vanc_line_numbers[idx].field1_vanc_start - 1;
  896. }
  897. }
  898. vanc->Release();
  899. if (txt_buf - txt_buf0 > 1) {
  900. int stuffing_units = (4 - ((45 + txt_buf - txt_buf0) / 46) % 4) % 4;
  901. while (stuffing_units--) {
  902. memset(txt_buf, 0xff, 46);
  903. txt_buf[1] = 0x2c; // data_unit_length
  904. txt_buf += 46;
  905. }
  906. av_init_packet(&txt_pkt);
  907. txt_pkt.pts = pkt.pts;
  908. txt_pkt.dts = pkt.dts;
  909. txt_pkt.stream_index = ctx->teletext_st->index;
  910. txt_pkt.data = txt_buf0;
  911. txt_pkt.size = txt_buf - txt_buf0;
  912. if (avpacket_queue_put(&ctx->queue, &txt_pkt) < 0) {
  913. ++ctx->dropped;
  914. }
  915. }
  916. }
  917. }
  918. pkt.buf = av_buffer_create(pkt.data, pkt.size, decklink_object_free, videoFrame, 0);
  919. if (pkt.buf)
  920. videoFrame->AddRef();
  921. if (avpacket_queue_put(&ctx->queue, &pkt) < 0) {
  922. ++ctx->dropped;
  923. }
  924. }
  925. // Handle Audio Frame
  926. if (audioFrame) {
  927. AVPacket pkt;
  928. BMDTimeValue audio_pts;
  929. av_init_packet(&pkt);
  930. //hack among hacks
  931. pkt.size = audioFrame->GetSampleFrameCount() * ctx->audio_st->codecpar->channels * (ctx->audio_depth / 8);
  932. audioFrame->GetBytes(&audioFrameBytes);
  933. audioFrame->GetPacketTime(&audio_pts, ctx->audio_st->time_base.den);
  934. pkt.pts = get_pkt_pts(videoFrame, audioFrame, wallclock, abs_wallclock, ctx->audio_pts_source, ctx->audio_st->time_base, &initial_audio_pts, cctx->copyts);
  935. pkt.dts = pkt.pts;
  936. //fprintf(stderr,"Audio Frame size %d ts %d\n", pkt.size, pkt.pts);
  937. pkt.flags |= AV_PKT_FLAG_KEY;
  938. pkt.stream_index = ctx->audio_st->index;
  939. pkt.data = (uint8_t *)audioFrameBytes;
  940. if (avpacket_queue_put(&ctx->queue, &pkt) < 0) {
  941. ++ctx->dropped;
  942. }
  943. }
  944. return S_OK;
  945. }
  946. HRESULT decklink_input_callback::VideoInputFormatChanged(
  947. BMDVideoInputFormatChangedEvents events, IDeckLinkDisplayMode *mode,
  948. BMDDetectedVideoInputFormatFlags formatFlags)
  949. {
  950. struct decklink_cctx *cctx = (struct decklink_cctx *) avctx->priv_data;
  951. ctx->bmd_mode = mode->GetDisplayMode();
  952. // check the C context member to make sure we set both raw_format and bmd_mode with data from the same format change callback
  953. if (!cctx->raw_format)
  954. ctx->raw_format = (formatFlags & bmdDetectedVideoInputRGB444) ? bmdFormat8BitARGB : bmdFormat8BitYUV;
  955. return S_OK;
  956. }
  957. static int decklink_autodetect(struct decklink_cctx *cctx) {
  958. struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
  959. DECKLINK_BOOL autodetect_supported = false;
  960. int i;
  961. if (ctx->attr->GetFlag(BMDDeckLinkSupportsInputFormatDetection, &autodetect_supported) != S_OK)
  962. return -1;
  963. if (autodetect_supported == false)
  964. return -1;
  965. ctx->autodetect = 1;
  966. ctx->bmd_mode = bmdModeUnknown;
  967. if (ctx->dli->EnableVideoInput(AUTODETECT_DEFAULT_MODE,
  968. bmdFormat8BitYUV,
  969. bmdVideoInputEnableFormatDetection) != S_OK) {
  970. return -1;
  971. }
  972. if (ctx->dli->StartStreams() != S_OK) {
  973. return -1;
  974. }
  975. // 3 second timeout
  976. for (i = 0; i < 30; i++) {
  977. av_usleep(100000);
  978. /* Sometimes VideoInputFrameArrived is called without the
  979. * bmdFrameHasNoInputSource flag before VideoInputFormatChanged.
  980. * So don't break for bmd_mode == AUTODETECT_DEFAULT_MODE. */
  981. if (ctx->bmd_mode != bmdModeUnknown &&
  982. ctx->bmd_mode != AUTODETECT_DEFAULT_MODE)
  983. break;
  984. }
  985. ctx->dli->PauseStreams();
  986. ctx->dli->FlushStreams();
  987. ctx->autodetect = 0;
  988. if (ctx->bmd_mode != bmdModeUnknown) {
  989. cctx->format_code = (char *)av_mallocz(5);
  990. if (!cctx->format_code)
  991. return -1;
  992. AV_WB32(cctx->format_code, ctx->bmd_mode);
  993. return 0;
  994. } else {
  995. return -1;
  996. }
  997. }
  998. extern "C" {
  999. av_cold int ff_decklink_read_close(AVFormatContext *avctx)
  1000. {
  1001. struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
  1002. struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
  1003. if (ctx->dli) {
  1004. ctx->dli->StopStreams();
  1005. ctx->dli->DisableVideoInput();
  1006. ctx->dli->DisableAudioInput();
  1007. }
  1008. ff_decklink_cleanup(avctx);
  1009. avpacket_queue_end(&ctx->queue);
  1010. av_freep(&cctx->ctx);
  1011. return 0;
  1012. }
  1013. av_cold int ff_decklink_read_header(AVFormatContext *avctx)
  1014. {
  1015. struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
  1016. struct decklink_ctx *ctx;
  1017. class decklink_allocator *allocator;
  1018. class decklink_input_callback *input_callback;
  1019. AVStream *st;
  1020. HRESULT result;
  1021. int ret;
  1022. ctx = (struct decklink_ctx *) av_mallocz(sizeof(struct decklink_ctx));
  1023. if (!ctx)
  1024. return AVERROR(ENOMEM);
  1025. ctx->list_devices = cctx->list_devices;
  1026. ctx->list_formats = cctx->list_formats;
  1027. ctx->enable_klv = cctx->enable_klv;
  1028. ctx->teletext_lines = cctx->teletext_lines;
  1029. ctx->preroll = cctx->preroll;
  1030. ctx->duplex_mode = cctx->duplex_mode;
  1031. if (cctx->tc_format > 0 && (unsigned int)cctx->tc_format < FF_ARRAY_ELEMS(decklink_timecode_format_map))
  1032. ctx->tc_format = decklink_timecode_format_map[cctx->tc_format];
  1033. if (cctx->video_input > 0 && (unsigned int)cctx->video_input < FF_ARRAY_ELEMS(decklink_video_connection_map))
  1034. ctx->video_input = decklink_video_connection_map[cctx->video_input];
  1035. if (cctx->audio_input > 0 && (unsigned int)cctx->audio_input < FF_ARRAY_ELEMS(decklink_audio_connection_map))
  1036. ctx->audio_input = decklink_audio_connection_map[cctx->audio_input];
  1037. ctx->audio_pts_source = cctx->audio_pts_source;
  1038. ctx->video_pts_source = cctx->video_pts_source;
  1039. ctx->draw_bars = cctx->draw_bars;
  1040. ctx->audio_depth = cctx->audio_depth;
  1041. if (cctx->raw_format > 0 && (unsigned int)cctx->raw_format < FF_ARRAY_ELEMS(decklink_raw_format_map))
  1042. ctx->raw_format = decklink_raw_format_map[cctx->raw_format];
  1043. cctx->ctx = ctx;
  1044. /* Check audio channel option for valid values: 2, 8 or 16 */
  1045. switch (cctx->audio_channels) {
  1046. case 2:
  1047. case 8:
  1048. case 16:
  1049. break;
  1050. default:
  1051. av_log(avctx, AV_LOG_ERROR, "Value of channels option must be one of 2, 8 or 16\n");
  1052. return AVERROR(EINVAL);
  1053. }
  1054. /* Check audio bit depth option for valid values: 16 or 32 */
  1055. switch (cctx->audio_depth) {
  1056. case 16:
  1057. case 32:
  1058. break;
  1059. default:
  1060. av_log(avctx, AV_LOG_ERROR, "Value for audio bit depth option must be either 16 or 32\n");
  1061. return AVERROR(EINVAL);
  1062. }
  1063. /* List available devices. */
  1064. if (ctx->list_devices) {
  1065. ff_decklink_list_devices_legacy(avctx, 1, 0);
  1066. return AVERROR_EXIT;
  1067. }
  1068. ret = ff_decklink_init_device(avctx, avctx->url);
  1069. if (ret < 0)
  1070. return ret;
  1071. /* Get input device. */
  1072. if (ctx->dl->QueryInterface(IID_IDeckLinkInput, (void **) &ctx->dli) != S_OK) {
  1073. av_log(avctx, AV_LOG_ERROR, "Could not open input device from '%s'\n",
  1074. avctx->url);
  1075. ret = AVERROR(EIO);
  1076. goto error;
  1077. }
  1078. if (ff_decklink_set_configs(avctx, DIRECTION_IN) < 0) {
  1079. av_log(avctx, AV_LOG_ERROR, "Could not set input configuration\n");
  1080. ret = AVERROR(EIO);
  1081. goto error;
  1082. }
  1083. /* List supported formats. */
  1084. if (ctx->list_formats) {
  1085. ff_decklink_list_formats(avctx, DIRECTION_IN);
  1086. ret = AVERROR_EXIT;
  1087. goto error;
  1088. }
  1089. input_callback = new decklink_input_callback(avctx);
  1090. ret = (ctx->dli->SetCallback(input_callback) == S_OK ? 0 : AVERROR_EXTERNAL);
  1091. input_callback->Release();
  1092. if (ret < 0) {
  1093. av_log(avctx, AV_LOG_ERROR, "Cannot set input callback\n");
  1094. goto error;
  1095. }
  1096. allocator = new decklink_allocator();
  1097. ret = (ctx->dli->SetVideoInputFrameMemoryAllocator(allocator) == S_OK ? 0 : AVERROR_EXTERNAL);
  1098. allocator->Release();
  1099. if (ret < 0) {
  1100. av_log(avctx, AV_LOG_ERROR, "Cannot set custom memory allocator\n");
  1101. goto error;
  1102. }
  1103. if (!cctx->format_code) {
  1104. if (decklink_autodetect(cctx) < 0) {
  1105. av_log(avctx, AV_LOG_ERROR, "Cannot Autodetect input stream or No signal\n");
  1106. ret = AVERROR(EIO);
  1107. goto error;
  1108. }
  1109. av_log(avctx, AV_LOG_INFO, "Autodetected the input mode\n");
  1110. }
  1111. if (ctx->raw_format == (BMDPixelFormat)0)
  1112. ctx->raw_format = bmdFormat8BitYUV;
  1113. if (ff_decklink_set_format(avctx, DIRECTION_IN) < 0) {
  1114. av_log(avctx, AV_LOG_ERROR, "Could not set format code %s for %s\n",
  1115. cctx->format_code ? cctx->format_code : "(unset)", avctx->url);
  1116. ret = AVERROR(EIO);
  1117. goto error;
  1118. }
  1119. #if !CONFIG_LIBZVBI
  1120. if (ctx->teletext_lines && ctx->bmd_mode == bmdModePAL) {
  1121. av_log(avctx, AV_LOG_ERROR, "Libzvbi support is needed for capturing SD PAL teletext, please recompile FFmpeg.\n");
  1122. ret = AVERROR(ENOSYS);
  1123. goto error;
  1124. }
  1125. #endif
  1126. /* Setup streams. */
  1127. st = avformat_new_stream(avctx, NULL);
  1128. if (!st) {
  1129. av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
  1130. ret = AVERROR(ENOMEM);
  1131. goto error;
  1132. }
  1133. st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
  1134. st->codecpar->codec_id = cctx->audio_depth == 32 ? AV_CODEC_ID_PCM_S32LE : AV_CODEC_ID_PCM_S16LE;
  1135. st->codecpar->sample_rate = bmdAudioSampleRate48kHz;
  1136. st->codecpar->channels = cctx->audio_channels;
  1137. avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
  1138. ctx->audio_st=st;
  1139. st = avformat_new_stream(avctx, NULL);
  1140. if (!st) {
  1141. av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
  1142. ret = AVERROR(ENOMEM);
  1143. goto error;
  1144. }
  1145. st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
  1146. st->codecpar->width = ctx->bmd_width;
  1147. st->codecpar->height = ctx->bmd_height;
  1148. st->time_base.den = ctx->bmd_tb_den;
  1149. st->time_base.num = ctx->bmd_tb_num;
  1150. st->r_frame_rate = av_make_q(st->time_base.den, st->time_base.num);
  1151. switch(ctx->raw_format) {
  1152. case bmdFormat8BitYUV:
  1153. st->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
  1154. st->codecpar->format = AV_PIX_FMT_UYVY422;
  1155. st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 16, st->time_base.den, st->time_base.num);
  1156. break;
  1157. case bmdFormat10BitYUV:
  1158. st->codecpar->codec_id = AV_CODEC_ID_V210;
  1159. st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 64, st->time_base.den, st->time_base.num * 3);
  1160. break;
  1161. case bmdFormat8BitARGB:
  1162. st->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
  1163. st->codecpar->format = AV_PIX_FMT_0RGB;
  1164. st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 32, st->time_base.den, st->time_base.num);
  1165. break;
  1166. case bmdFormat8BitBGRA:
  1167. st->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
  1168. st->codecpar->format = AV_PIX_FMT_BGR0;
  1169. st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 32, st->time_base.den, st->time_base.num);
  1170. break;
  1171. case bmdFormat10BitRGB:
  1172. st->codecpar->codec_id = AV_CODEC_ID_R210;
  1173. st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 30, st->time_base.den, st->time_base.num);
  1174. break;
  1175. default:
  1176. char fourcc_str[AV_FOURCC_MAX_STRING_SIZE] = {0};
  1177. av_fourcc_make_string(fourcc_str, ctx->raw_format);
  1178. av_log(avctx, AV_LOG_ERROR, "Raw Format %s not supported\n", fourcc_str);
  1179. ret = AVERROR(EINVAL);
  1180. goto error;
  1181. }
  1182. switch (ctx->bmd_field_dominance) {
  1183. case bmdUpperFieldFirst:
  1184. st->codecpar->field_order = AV_FIELD_TT;
  1185. break;
  1186. case bmdLowerFieldFirst:
  1187. st->codecpar->field_order = AV_FIELD_BB;
  1188. break;
  1189. case bmdProgressiveFrame:
  1190. case bmdProgressiveSegmentedFrame:
  1191. st->codecpar->field_order = AV_FIELD_PROGRESSIVE;
  1192. break;
  1193. }
  1194. avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
  1195. ctx->video_st=st;
  1196. if (ctx->enable_klv) {
  1197. st = avformat_new_stream(avctx, NULL);
  1198. if (!st) {
  1199. ret = AVERROR(ENOMEM);
  1200. goto error;
  1201. }
  1202. st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
  1203. st->time_base.den = ctx->bmd_tb_den;
  1204. st->time_base.num = ctx->bmd_tb_num;
  1205. st->codecpar->codec_id = AV_CODEC_ID_SMPTE_KLV;
  1206. avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
  1207. ctx->klv_st = st;
  1208. }
  1209. if (ctx->teletext_lines) {
  1210. st = avformat_new_stream(avctx, NULL);
  1211. if (!st) {
  1212. av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
  1213. ret = AVERROR(ENOMEM);
  1214. goto error;
  1215. }
  1216. st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1217. st->time_base.den = ctx->bmd_tb_den;
  1218. st->time_base.num = ctx->bmd_tb_num;
  1219. st->codecpar->codec_id = AV_CODEC_ID_DVB_TELETEXT;
  1220. avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
  1221. ctx->teletext_st = st;
  1222. }
  1223. av_log(avctx, AV_LOG_VERBOSE, "Using %d input audio channels\n", ctx->audio_st->codecpar->channels);
  1224. result = ctx->dli->EnableAudioInput(bmdAudioSampleRate48kHz, cctx->audio_depth == 32 ? bmdAudioSampleType32bitInteger : bmdAudioSampleType16bitInteger, ctx->audio_st->codecpar->channels);
  1225. if (result != S_OK) {
  1226. av_log(avctx, AV_LOG_ERROR, "Cannot enable audio input\n");
  1227. ret = AVERROR(EIO);
  1228. goto error;
  1229. }
  1230. result = ctx->dli->EnableVideoInput(ctx->bmd_mode,
  1231. ctx->raw_format,
  1232. bmdVideoInputFlagDefault);
  1233. if (result != S_OK) {
  1234. av_log(avctx, AV_LOG_ERROR, "Cannot enable video input\n");
  1235. ret = AVERROR(EIO);
  1236. goto error;
  1237. }
  1238. avpacket_queue_init (avctx, &ctx->queue);
  1239. if (ctx->dli->StartStreams() != S_OK) {
  1240. av_log(avctx, AV_LOG_ERROR, "Cannot start input stream\n");
  1241. ret = AVERROR(EIO);
  1242. goto error;
  1243. }
  1244. return 0;
  1245. error:
  1246. ff_decklink_cleanup(avctx);
  1247. return ret;
  1248. }
  1249. int ff_decklink_read_packet(AVFormatContext *avctx, AVPacket *pkt)
  1250. {
  1251. struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
  1252. struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
  1253. avpacket_queue_get(&ctx->queue, pkt, 1);
  1254. if (ctx->tc_format && !(av_dict_get(ctx->video_st->metadata, "timecode", NULL, 0))) {
  1255. buffer_size_t size;
  1256. const uint8_t *side_metadata = av_packet_get_side_data(pkt, AV_PKT_DATA_STRINGS_METADATA, &size);
  1257. if (side_metadata) {
  1258. if (av_packet_unpack_dictionary(side_metadata, size, &ctx->video_st->metadata) < 0)
  1259. av_log(avctx, AV_LOG_ERROR, "Unable to set timecode\n");
  1260. }
  1261. }
  1262. return 0;
  1263. }
  1264. int ff_decklink_list_input_devices(AVFormatContext *avctx, struct AVDeviceInfoList *device_list)
  1265. {
  1266. return ff_decklink_list_devices(avctx, device_list, 1, 0);
  1267. }
  1268. } /* extern "C" */