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.

1065 lines
35KB

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