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.

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