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.

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