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.

1274 lines
43KB

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