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.

913 lines
31KB

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