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.

906 lines
30KB

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