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.

1067 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++) {
  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, 1);
  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. int ret;
  395. // Drop Packet if queue size is > maximum queue size
  396. if (avpacket_queue_size(q) > (uint64_t)q->max_q_size) {
  397. av_log(q->avctx, AV_LOG_WARNING, "Decklink input buffer overrun!\n");
  398. return -1;
  399. }
  400. pkt1 = (AVPacketList *)av_mallocz(sizeof(AVPacketList));
  401. if (!pkt1) {
  402. return -1;
  403. }
  404. ret = av_packet_ref(&pkt1->pkt, pkt);
  405. av_packet_unref(pkt);
  406. if (ret < 0) {
  407. av_free(pkt1);
  408. return -1;
  409. }
  410. pkt1->next = NULL;
  411. pthread_mutex_lock(&q->mutex);
  412. if (!q->last_pkt) {
  413. q->first_pkt = pkt1;
  414. } else {
  415. q->last_pkt->next = pkt1;
  416. }
  417. q->last_pkt = pkt1;
  418. q->nb_packets++;
  419. q->size += pkt1->pkt.size + sizeof(*pkt1);
  420. pthread_cond_signal(&q->cond);
  421. pthread_mutex_unlock(&q->mutex);
  422. return 0;
  423. }
  424. static int avpacket_queue_get(AVPacketQueue *q, AVPacket *pkt, int block)
  425. {
  426. AVPacketList *pkt1;
  427. int ret;
  428. pthread_mutex_lock(&q->mutex);
  429. for (;; ) {
  430. pkt1 = q->first_pkt;
  431. if (pkt1) {
  432. q->first_pkt = pkt1->next;
  433. if (!q->first_pkt) {
  434. q->last_pkt = NULL;
  435. }
  436. q->nb_packets--;
  437. q->size -= pkt1->pkt.size + sizeof(*pkt1);
  438. *pkt = pkt1->pkt;
  439. av_free(pkt1);
  440. ret = 1;
  441. break;
  442. } else if (!block) {
  443. ret = 0;
  444. break;
  445. } else {
  446. pthread_cond_wait(&q->cond, &q->mutex);
  447. }
  448. }
  449. pthread_mutex_unlock(&q->mutex);
  450. return ret;
  451. }
  452. class decklink_input_callback : public IDeckLinkInputCallback
  453. {
  454. public:
  455. decklink_input_callback(AVFormatContext *_avctx);
  456. ~decklink_input_callback();
  457. virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv) { return E_NOINTERFACE; }
  458. virtual ULONG STDMETHODCALLTYPE AddRef(void);
  459. virtual ULONG STDMETHODCALLTYPE Release(void);
  460. virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents, IDeckLinkDisplayMode*, BMDDetectedVideoInputFormatFlags);
  461. virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame*, IDeckLinkAudioInputPacket*);
  462. private:
  463. ULONG m_refCount;
  464. pthread_mutex_t m_mutex;
  465. AVFormatContext *avctx;
  466. decklink_ctx *ctx;
  467. int no_video;
  468. int64_t initial_video_pts;
  469. int64_t initial_audio_pts;
  470. };
  471. decklink_input_callback::decklink_input_callback(AVFormatContext *_avctx) : m_refCount(0)
  472. {
  473. avctx = _avctx;
  474. decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
  475. ctx = (struct decklink_ctx *)cctx->ctx;
  476. no_video = 0;
  477. initial_audio_pts = initial_video_pts = AV_NOPTS_VALUE;
  478. pthread_mutex_init(&m_mutex, NULL);
  479. }
  480. decklink_input_callback::~decklink_input_callback()
  481. {
  482. pthread_mutex_destroy(&m_mutex);
  483. }
  484. ULONG decklink_input_callback::AddRef(void)
  485. {
  486. pthread_mutex_lock(&m_mutex);
  487. m_refCount++;
  488. pthread_mutex_unlock(&m_mutex);
  489. return (ULONG)m_refCount;
  490. }
  491. ULONG decklink_input_callback::Release(void)
  492. {
  493. pthread_mutex_lock(&m_mutex);
  494. m_refCount--;
  495. pthread_mutex_unlock(&m_mutex);
  496. if (m_refCount == 0) {
  497. delete this;
  498. return 0;
  499. }
  500. return (ULONG)m_refCount;
  501. }
  502. static int64_t get_pkt_pts(IDeckLinkVideoInputFrame *videoFrame,
  503. IDeckLinkAudioInputPacket *audioFrame,
  504. int64_t wallclock,
  505. DecklinkPtsSource pts_src,
  506. AVRational time_base, int64_t *initial_pts)
  507. {
  508. int64_t pts = AV_NOPTS_VALUE;
  509. BMDTimeValue bmd_pts;
  510. BMDTimeValue bmd_duration;
  511. HRESULT res = E_INVALIDARG;
  512. switch (pts_src) {
  513. case PTS_SRC_AUDIO:
  514. if (audioFrame)
  515. res = audioFrame->GetPacketTime(&bmd_pts, time_base.den);
  516. break;
  517. case PTS_SRC_VIDEO:
  518. if (videoFrame)
  519. res = videoFrame->GetStreamTime(&bmd_pts, &bmd_duration, time_base.den);
  520. break;
  521. case PTS_SRC_REFERENCE:
  522. if (videoFrame)
  523. res = videoFrame->GetHardwareReferenceTimestamp(time_base.den, &bmd_pts, &bmd_duration);
  524. break;
  525. case PTS_SRC_WALLCLOCK:
  526. {
  527. /* MSVC does not support compound literals like AV_TIME_BASE_Q
  528. * in C++ code (compiler error C4576) */
  529. AVRational timebase;
  530. timebase.num = 1;
  531. timebase.den = AV_TIME_BASE;
  532. pts = av_rescale_q(wallclock, timebase, time_base);
  533. break;
  534. }
  535. }
  536. if (res == S_OK)
  537. pts = bmd_pts / time_base.num;
  538. if (pts != AV_NOPTS_VALUE && *initial_pts == AV_NOPTS_VALUE)
  539. *initial_pts = pts;
  540. if (*initial_pts != AV_NOPTS_VALUE)
  541. pts -= *initial_pts;
  542. return pts;
  543. }
  544. HRESULT decklink_input_callback::VideoInputFrameArrived(
  545. IDeckLinkVideoInputFrame *videoFrame, IDeckLinkAudioInputPacket *audioFrame)
  546. {
  547. void *frameBytes;
  548. void *audioFrameBytes;
  549. BMDTimeValue frameTime;
  550. BMDTimeValue frameDuration;
  551. int64_t wallclock = 0;
  552. ctx->frameCount++;
  553. if (ctx->audio_pts_source == PTS_SRC_WALLCLOCK || ctx->video_pts_source == PTS_SRC_WALLCLOCK)
  554. wallclock = av_gettime_relative();
  555. // Handle Video Frame
  556. if (videoFrame) {
  557. AVPacket pkt;
  558. av_init_packet(&pkt);
  559. if (ctx->frameCount % 25 == 0) {
  560. unsigned long long qsize = avpacket_queue_size(&ctx->queue);
  561. av_log(avctx, AV_LOG_DEBUG,
  562. "Frame received (#%lu) - Valid (%liB) - QSize %fMB\n",
  563. ctx->frameCount,
  564. videoFrame->GetRowBytes() * videoFrame->GetHeight(),
  565. (double)qsize / 1024 / 1024);
  566. }
  567. videoFrame->GetBytes(&frameBytes);
  568. videoFrame->GetStreamTime(&frameTime, &frameDuration,
  569. ctx->video_st->time_base.den);
  570. if (videoFrame->GetFlags() & bmdFrameHasNoInputSource) {
  571. if (ctx->draw_bars && videoFrame->GetPixelFormat() == bmdFormat8BitYUV) {
  572. unsigned bars[8] = {
  573. 0xEA80EA80, 0xD292D210, 0xA910A9A5, 0x90229035,
  574. 0x6ADD6ACA, 0x51EF515A, 0x286D28EF, 0x10801080 };
  575. int width = videoFrame->GetWidth();
  576. int height = videoFrame->GetHeight();
  577. unsigned *p = (unsigned *)frameBytes;
  578. for (int y = 0; y < height; y++) {
  579. for (int x = 0; x < width; x += 2)
  580. *p++ = bars[(x * 8) / width];
  581. }
  582. }
  583. if (!no_video) {
  584. av_log(avctx, AV_LOG_WARNING, "Frame received (#%lu) - No input signal detected "
  585. "- Frames dropped %u\n", ctx->frameCount, ++ctx->dropped);
  586. }
  587. no_video = 1;
  588. } else {
  589. if (no_video) {
  590. av_log(avctx, AV_LOG_WARNING, "Frame received (#%lu) - Input returned "
  591. "- Frames dropped %u\n", ctx->frameCount, ++ctx->dropped);
  592. }
  593. no_video = 0;
  594. }
  595. pkt.pts = get_pkt_pts(videoFrame, audioFrame, wallclock, ctx->video_pts_source, ctx->video_st->time_base, &initial_video_pts);
  596. pkt.dts = pkt.pts;
  597. pkt.duration = frameDuration;
  598. //To be made sure it still applies
  599. pkt.flags |= AV_PKT_FLAG_KEY;
  600. pkt.stream_index = ctx->video_st->index;
  601. pkt.data = (uint8_t *)frameBytes;
  602. pkt.size = videoFrame->GetRowBytes() *
  603. videoFrame->GetHeight();
  604. //fprintf(stderr,"Video Frame size %d ts %d\n", pkt.size, pkt.pts);
  605. if (!no_video) {
  606. IDeckLinkVideoFrameAncillary *vanc;
  607. AVPacket txt_pkt;
  608. uint8_t txt_buf0[3531]; // 35 * 46 bytes decoded teletext lines + 1 byte data_identifier + 1920 bytes OP47 decode buffer
  609. uint8_t *txt_buf = txt_buf0;
  610. if (videoFrame->GetAncillaryData(&vanc) == S_OK) {
  611. int i;
  612. int64_t line_mask = 1;
  613. BMDPixelFormat vanc_format = vanc->GetPixelFormat();
  614. txt_buf[0] = 0x10; // data_identifier - EBU_data
  615. txt_buf++;
  616. #if CONFIG_LIBZVBI
  617. if (ctx->bmd_mode == bmdModePAL && ctx->teletext_lines &&
  618. (vanc_format == bmdFormat8BitYUV || vanc_format == bmdFormat10BitYUV)) {
  619. av_assert0(videoFrame->GetWidth() == 720);
  620. for (i = 6; i < 336; i++, line_mask <<= 1) {
  621. uint8_t *buf;
  622. if ((ctx->teletext_lines & line_mask) && vanc->GetBufferForVerticalBlankingLine(i, (void**)&buf) == S_OK) {
  623. if (vanc_format == bmdFormat8BitYUV)
  624. txt_buf = teletext_data_unit_from_vbi_data(i, buf, txt_buf, VBI_PIXFMT_UYVY);
  625. else
  626. txt_buf = teletext_data_unit_from_vbi_data_10bit(i, buf, txt_buf);
  627. }
  628. if (i == 22)
  629. i = 317;
  630. }
  631. }
  632. #endif
  633. if (vanc_format == bmdFormat10BitYUV && videoFrame->GetWidth() <= MAX_WIDTH_VANC) {
  634. int idx = get_vanc_line_idx(ctx->bmd_mode);
  635. for (i = vanc_line_numbers[idx].vanc_start; i <= vanc_line_numbers[idx].vanc_end; i++) {
  636. uint8_t *buf;
  637. if (vanc->GetBufferForVerticalBlankingLine(i, (void**)&buf) == S_OK) {
  638. uint16_t luma_vanc[MAX_WIDTH_VANC];
  639. extract_luma_from_v210(luma_vanc, buf, videoFrame->GetWidth());
  640. txt_buf = get_metadata(avctx, luma_vanc, videoFrame->GetWidth(),
  641. txt_buf, sizeof(txt_buf0) - (txt_buf - txt_buf0), &pkt);
  642. }
  643. if (i == vanc_line_numbers[idx].field0_vanc_end)
  644. i = vanc_line_numbers[idx].field1_vanc_start - 1;
  645. }
  646. }
  647. vanc->Release();
  648. if (txt_buf - txt_buf0 > 1) {
  649. int stuffing_units = (4 - ((45 + txt_buf - txt_buf0) / 46) % 4) % 4;
  650. while (stuffing_units--) {
  651. memset(txt_buf, 0xff, 46);
  652. txt_buf[1] = 0x2c; // data_unit_length
  653. txt_buf += 46;
  654. }
  655. av_init_packet(&txt_pkt);
  656. txt_pkt.pts = pkt.pts;
  657. txt_pkt.dts = pkt.dts;
  658. txt_pkt.stream_index = ctx->teletext_st->index;
  659. txt_pkt.data = txt_buf0;
  660. txt_pkt.size = txt_buf - txt_buf0;
  661. if (avpacket_queue_put(&ctx->queue, &txt_pkt) < 0) {
  662. ++ctx->dropped;
  663. }
  664. }
  665. }
  666. }
  667. if (avpacket_queue_put(&ctx->queue, &pkt) < 0) {
  668. ++ctx->dropped;
  669. }
  670. }
  671. // Handle Audio Frame
  672. if (audioFrame) {
  673. AVPacket pkt;
  674. BMDTimeValue audio_pts;
  675. av_init_packet(&pkt);
  676. //hack among hacks
  677. pkt.size = audioFrame->GetSampleFrameCount() * ctx->audio_st->codecpar->channels * (16 / 8);
  678. audioFrame->GetBytes(&audioFrameBytes);
  679. audioFrame->GetPacketTime(&audio_pts, ctx->audio_st->time_base.den);
  680. pkt.pts = get_pkt_pts(videoFrame, audioFrame, wallclock, ctx->audio_pts_source, ctx->audio_st->time_base, &initial_audio_pts);
  681. pkt.dts = pkt.pts;
  682. //fprintf(stderr,"Audio Frame size %d ts %d\n", pkt.size, pkt.pts);
  683. pkt.flags |= AV_PKT_FLAG_KEY;
  684. pkt.stream_index = ctx->audio_st->index;
  685. pkt.data = (uint8_t *)audioFrameBytes;
  686. if (avpacket_queue_put(&ctx->queue, &pkt) < 0) {
  687. ++ctx->dropped;
  688. }
  689. }
  690. return S_OK;
  691. }
  692. HRESULT decklink_input_callback::VideoInputFormatChanged(
  693. BMDVideoInputFormatChangedEvents events, IDeckLinkDisplayMode *mode,
  694. BMDDetectedVideoInputFormatFlags)
  695. {
  696. return S_OK;
  697. }
  698. static HRESULT decklink_start_input(AVFormatContext *avctx)
  699. {
  700. struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
  701. struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
  702. ctx->input_callback = new decklink_input_callback(avctx);
  703. ctx->dli->SetCallback(ctx->input_callback);
  704. return ctx->dli->StartStreams();
  705. }
  706. extern "C" {
  707. av_cold int ff_decklink_read_close(AVFormatContext *avctx)
  708. {
  709. struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
  710. struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
  711. if (ctx->capture_started) {
  712. ctx->dli->StopStreams();
  713. ctx->dli->DisableVideoInput();
  714. ctx->dli->DisableAudioInput();
  715. }
  716. ff_decklink_cleanup(avctx);
  717. avpacket_queue_end(&ctx->queue);
  718. av_freep(&cctx->ctx);
  719. return 0;
  720. }
  721. av_cold int ff_decklink_read_header(AVFormatContext *avctx)
  722. {
  723. struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
  724. struct decklink_ctx *ctx;
  725. AVStream *st;
  726. HRESULT result;
  727. char fname[1024];
  728. char *tmp;
  729. int mode_num = 0;
  730. int ret;
  731. ctx = (struct decklink_ctx *) av_mallocz(sizeof(struct decklink_ctx));
  732. if (!ctx)
  733. return AVERROR(ENOMEM);
  734. ctx->list_devices = cctx->list_devices;
  735. ctx->list_formats = cctx->list_formats;
  736. ctx->teletext_lines = cctx->teletext_lines;
  737. ctx->preroll = cctx->preroll;
  738. ctx->duplex_mode = cctx->duplex_mode;
  739. if (cctx->video_input > 0 && (unsigned int)cctx->video_input < FF_ARRAY_ELEMS(decklink_video_connection_map))
  740. ctx->video_input = decklink_video_connection_map[cctx->video_input];
  741. if (cctx->audio_input > 0 && (unsigned int)cctx->audio_input < FF_ARRAY_ELEMS(decklink_audio_connection_map))
  742. ctx->audio_input = decklink_audio_connection_map[cctx->audio_input];
  743. ctx->audio_pts_source = cctx->audio_pts_source;
  744. ctx->video_pts_source = cctx->video_pts_source;
  745. ctx->draw_bars = cctx->draw_bars;
  746. cctx->ctx = ctx;
  747. /* Check audio channel option for valid values: 2, 8 or 16 */
  748. switch (cctx->audio_channels) {
  749. case 2:
  750. case 8:
  751. case 16:
  752. break;
  753. default:
  754. av_log(avctx, AV_LOG_ERROR, "Value of channels option must be one of 2, 8 or 16\n");
  755. return AVERROR(EINVAL);
  756. }
  757. /* List available devices. */
  758. if (ctx->list_devices) {
  759. ff_decklink_list_devices(avctx);
  760. return AVERROR_EXIT;
  761. }
  762. if (cctx->v210) {
  763. av_log(avctx, AV_LOG_WARNING, "The bm_v210 option is deprecated and will be removed. Please use the -raw_format yuv422p10.\n");
  764. cctx->raw_format = MKBETAG('v','2','1','0');
  765. }
  766. strcpy (fname, avctx->filename);
  767. tmp=strchr (fname, '@');
  768. if (tmp != NULL) {
  769. av_log(avctx, AV_LOG_WARNING, "The @mode syntax is deprecated and will be removed. Please use the -format_code option.\n");
  770. mode_num = atoi (tmp+1);
  771. *tmp = 0;
  772. }
  773. ret = ff_decklink_init_device(avctx, fname);
  774. if (ret < 0)
  775. return ret;
  776. /* Get input device. */
  777. if (ctx->dl->QueryInterface(IID_IDeckLinkInput, (void **) &ctx->dli) != S_OK) {
  778. av_log(avctx, AV_LOG_ERROR, "Could not open input device from '%s'\n",
  779. avctx->filename);
  780. ret = AVERROR(EIO);
  781. goto error;
  782. }
  783. /* List supported formats. */
  784. if (ctx->list_formats) {
  785. ff_decklink_list_formats(avctx, DIRECTION_IN);
  786. ret = AVERROR_EXIT;
  787. goto error;
  788. }
  789. if (mode_num > 0 || cctx->format_code) {
  790. if (ff_decklink_set_format(avctx, DIRECTION_IN, mode_num) < 0) {
  791. av_log(avctx, AV_LOG_ERROR, "Could not set mode number %d or format code %s for %s\n",
  792. mode_num, (cctx->format_code) ? cctx->format_code : "(unset)", fname);
  793. ret = AVERROR(EIO);
  794. goto error;
  795. }
  796. }
  797. #if !CONFIG_LIBZVBI
  798. if (ctx->teletext_lines && ctx->bmd_mode == bmdModePAL) {
  799. av_log(avctx, AV_LOG_ERROR, "Libzvbi support is needed for capturing SD PAL teletext, please recompile FFmpeg.\n");
  800. ret = AVERROR(ENOSYS);
  801. goto error;
  802. }
  803. #endif
  804. /* Setup streams. */
  805. st = avformat_new_stream(avctx, NULL);
  806. if (!st) {
  807. av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
  808. ret = AVERROR(ENOMEM);
  809. goto error;
  810. }
  811. st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
  812. st->codecpar->codec_id = AV_CODEC_ID_PCM_S16LE;
  813. st->codecpar->sample_rate = bmdAudioSampleRate48kHz;
  814. st->codecpar->channels = cctx->audio_channels;
  815. avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
  816. ctx->audio_st=st;
  817. st = avformat_new_stream(avctx, NULL);
  818. if (!st) {
  819. av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
  820. ret = AVERROR(ENOMEM);
  821. goto error;
  822. }
  823. st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
  824. st->codecpar->width = ctx->bmd_width;
  825. st->codecpar->height = ctx->bmd_height;
  826. st->time_base.den = ctx->bmd_tb_den;
  827. st->time_base.num = ctx->bmd_tb_num;
  828. av_stream_set_r_frame_rate(st, av_make_q(st->time_base.den, st->time_base.num));
  829. switch((BMDPixelFormat)cctx->raw_format) {
  830. case bmdFormat8BitYUV:
  831. st->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
  832. st->codecpar->codec_tag = MKTAG('U', 'Y', 'V', 'Y');
  833. st->codecpar->format = AV_PIX_FMT_UYVY422;
  834. st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 16, st->time_base.den, st->time_base.num);
  835. break;
  836. case bmdFormat10BitYUV:
  837. st->codecpar->codec_id = AV_CODEC_ID_V210;
  838. st->codecpar->codec_tag = MKTAG('V','2','1','0');
  839. st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 64, st->time_base.den, st->time_base.num * 3);
  840. st->codecpar->bits_per_coded_sample = 10;
  841. break;
  842. case bmdFormat8BitARGB:
  843. st->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
  844. st->codecpar->codec_tag = avcodec_pix_fmt_to_codec_tag((enum AVPixelFormat)st->codecpar->format);;
  845. st->codecpar->format = AV_PIX_FMT_0RGB;
  846. st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 32, st->time_base.den, st->time_base.num);
  847. break;
  848. case bmdFormat8BitBGRA:
  849. st->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
  850. st->codecpar->codec_tag = avcodec_pix_fmt_to_codec_tag((enum AVPixelFormat)st->codecpar->format);
  851. st->codecpar->format = AV_PIX_FMT_BGR0;
  852. st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 32, st->time_base.den, st->time_base.num);
  853. break;
  854. case bmdFormat10BitRGB:
  855. st->codecpar->codec_id = AV_CODEC_ID_R210;
  856. st->codecpar->codec_tag = MKTAG('R','2','1','0');
  857. st->codecpar->format = AV_PIX_FMT_RGB48LE;
  858. st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 30, st->time_base.den, st->time_base.num);
  859. st->codecpar->bits_per_coded_sample = 10;
  860. break;
  861. default:
  862. av_log(avctx, AV_LOG_ERROR, "Raw Format %.4s not supported\n", (char*) &cctx->raw_format);
  863. ret = AVERROR(EINVAL);
  864. goto error;
  865. }
  866. switch (ctx->bmd_field_dominance) {
  867. case bmdUpperFieldFirst:
  868. st->codecpar->field_order = AV_FIELD_TT;
  869. break;
  870. case bmdLowerFieldFirst:
  871. st->codecpar->field_order = AV_FIELD_BB;
  872. break;
  873. case bmdProgressiveFrame:
  874. case bmdProgressiveSegmentedFrame:
  875. st->codecpar->field_order = AV_FIELD_PROGRESSIVE;
  876. break;
  877. }
  878. avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
  879. ctx->video_st=st;
  880. if (ctx->teletext_lines) {
  881. st = avformat_new_stream(avctx, NULL);
  882. if (!st) {
  883. av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
  884. ret = AVERROR(ENOMEM);
  885. goto error;
  886. }
  887. st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
  888. st->time_base.den = ctx->bmd_tb_den;
  889. st->time_base.num = ctx->bmd_tb_num;
  890. st->codecpar->codec_id = AV_CODEC_ID_DVB_TELETEXT;
  891. avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
  892. ctx->teletext_st = st;
  893. }
  894. av_log(avctx, AV_LOG_VERBOSE, "Using %d input audio channels\n", ctx->audio_st->codecpar->channels);
  895. result = ctx->dli->EnableAudioInput(bmdAudioSampleRate48kHz, bmdAudioSampleType16bitInteger, ctx->audio_st->codecpar->channels);
  896. if (result != S_OK) {
  897. av_log(avctx, AV_LOG_ERROR, "Cannot enable audio input\n");
  898. ret = AVERROR(EIO);
  899. goto error;
  900. }
  901. result = ctx->dli->EnableVideoInput(ctx->bmd_mode,
  902. (BMDPixelFormat) cctx->raw_format,
  903. bmdVideoInputFlagDefault);
  904. if (result != S_OK) {
  905. av_log(avctx, AV_LOG_ERROR, "Cannot enable video input\n");
  906. ret = AVERROR(EIO);
  907. goto error;
  908. }
  909. avpacket_queue_init (avctx, &ctx->queue);
  910. if (decklink_start_input (avctx) != S_OK) {
  911. av_log(avctx, AV_LOG_ERROR, "Cannot start input stream\n");
  912. ret = AVERROR(EIO);
  913. goto error;
  914. }
  915. return 0;
  916. error:
  917. ff_decklink_cleanup(avctx);
  918. return ret;
  919. }
  920. int ff_decklink_read_packet(AVFormatContext *avctx, AVPacket *pkt)
  921. {
  922. struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
  923. struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
  924. avpacket_queue_get(&ctx->queue, pkt, 1);
  925. return 0;
  926. }
  927. } /* extern "C" */