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.

1073 lines
36KB

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