decklink_dec.cpp 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453
  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 <atomic>
  24. #include <vector>
  25. using std::atomic;
  26. /* Include internal.h first to avoid conflict between winsock.h (used by
  27. * DeckLink headers) and winsock2.h (used by libavformat) in MSVC++ builds */
  28. extern "C" {
  29. #include "libavformat/internal.h"
  30. }
  31. #include <DeckLinkAPI.h>
  32. extern "C" {
  33. #include "config.h"
  34. #include "libavcodec/packet_internal.h"
  35. #include "libavformat/avformat.h"
  36. #include "libavutil/avassert.h"
  37. #include "libavutil/avutil.h"
  38. #include "libavutil/common.h"
  39. #include "libavutil/internal.h"
  40. #include "libavutil/imgutils.h"
  41. #include "libavutil/intreadwrite.h"
  42. #include "libavutil/time.h"
  43. #include "libavutil/timecode.h"
  44. #include "libavutil/mathematics.h"
  45. #include "libavutil/reverse.h"
  46. #include "avdevice.h"
  47. #if CONFIG_LIBZVBI
  48. #include <libzvbi.h>
  49. #endif
  50. }
  51. #include "decklink_common.h"
  52. #include "decklink_dec.h"
  53. #define MAX_WIDTH_VANC 1920
  54. const BMDDisplayMode AUTODETECT_DEFAULT_MODE = bmdModeNTSC;
  55. typedef struct VANCLineNumber {
  56. BMDDisplayMode mode;
  57. int vanc_start;
  58. int field0_vanc_end;
  59. int field1_vanc_start;
  60. int vanc_end;
  61. } VANCLineNumber;
  62. /* These VANC line numbers need not be very accurate. In any case
  63. * GetBufferForVerticalBlankingLine() will return an error when invalid
  64. * ancillary line number was requested. We just need to make sure that the
  65. * entire VANC region is covered, while making sure we don't decode VANC of
  66. * another source during switching*/
  67. static VANCLineNumber vanc_line_numbers[] = {
  68. /* SD Modes */
  69. {bmdModeNTSC, 11, 19, 274, 282},
  70. {bmdModeNTSC2398, 11, 19, 274, 282},
  71. {bmdModePAL, 7, 22, 320, 335},
  72. {bmdModeNTSCp, 11, -1, -1, 39},
  73. {bmdModePALp, 7, -1, -1, 45},
  74. /* HD 1080 Modes */
  75. {bmdModeHD1080p2398, 8, -1, -1, 42},
  76. {bmdModeHD1080p24, 8, -1, -1, 42},
  77. {bmdModeHD1080p25, 8, -1, -1, 42},
  78. {bmdModeHD1080p2997, 8, -1, -1, 42},
  79. {bmdModeHD1080p30, 8, -1, -1, 42},
  80. {bmdModeHD1080i50, 8, 20, 570, 585},
  81. {bmdModeHD1080i5994, 8, 20, 570, 585},
  82. {bmdModeHD1080i6000, 8, 20, 570, 585},
  83. {bmdModeHD1080p50, 8, -1, -1, 42},
  84. {bmdModeHD1080p5994, 8, -1, -1, 42},
  85. {bmdModeHD1080p6000, 8, -1, -1, 42},
  86. /* HD 720 Modes */
  87. {bmdModeHD720p50, 8, -1, -1, 26},
  88. {bmdModeHD720p5994, 8, -1, -1, 26},
  89. {bmdModeHD720p60, 8, -1, -1, 26},
  90. /* For all other modes, for which we don't support VANC */
  91. {bmdModeUnknown, 0, -1, -1, -1}
  92. };
  93. class decklink_allocator : public IDeckLinkMemoryAllocator
  94. {
  95. public:
  96. decklink_allocator(): _refs(1) { }
  97. virtual ~decklink_allocator() { }
  98. // IDeckLinkMemoryAllocator methods
  99. virtual HRESULT STDMETHODCALLTYPE AllocateBuffer(unsigned int bufferSize, void* *allocatedBuffer)
  100. {
  101. void *buf = av_malloc(bufferSize + AV_INPUT_BUFFER_PADDING_SIZE);
  102. if (!buf)
  103. return E_OUTOFMEMORY;
  104. *allocatedBuffer = buf;
  105. return S_OK;
  106. }
  107. virtual HRESULT STDMETHODCALLTYPE ReleaseBuffer(void* buffer)
  108. {
  109. av_free(buffer);
  110. return S_OK;
  111. }
  112. virtual HRESULT STDMETHODCALLTYPE Commit() { return S_OK; }
  113. virtual HRESULT STDMETHODCALLTYPE Decommit() { return S_OK; }
  114. // IUnknown methods
  115. virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv) { return E_NOINTERFACE; }
  116. virtual ULONG STDMETHODCALLTYPE AddRef(void) { return ++_refs; }
  117. virtual ULONG STDMETHODCALLTYPE Release(void)
  118. {
  119. int ret = --_refs;
  120. if (!ret)
  121. delete this;
  122. return ret;
  123. }
  124. private:
  125. std::atomic<int> _refs;
  126. };
  127. extern "C" {
  128. static void decklink_object_free(void *opaque, uint8_t *data)
  129. {
  130. IUnknown *obj = (class IUnknown *)opaque;
  131. obj->Release();
  132. }
  133. }
  134. static int get_vanc_line_idx(BMDDisplayMode mode)
  135. {
  136. unsigned int i;
  137. for (i = 0; i < FF_ARRAY_ELEMS(vanc_line_numbers); i++) {
  138. if (mode == vanc_line_numbers[i].mode)
  139. return i;
  140. }
  141. /* Return the VANC idx for Unknown mode */
  142. return i - 1;
  143. }
  144. static inline void clear_parity_bits(uint16_t *buf, int len) {
  145. int i;
  146. for (i = 0; i < len; i++)
  147. buf[i] &= 0xff;
  148. }
  149. static int check_vanc_parity_checksum(uint16_t *buf, int len, uint16_t checksum) {
  150. int i;
  151. uint16_t vanc_sum = 0;
  152. for (i = 3; i < len - 1; i++) {
  153. uint16_t v = buf[i];
  154. int np = v >> 8;
  155. int p = av_parity(v & 0xff);
  156. if ((!!p ^ !!(v & 0x100)) || (np != 1 && np != 2)) {
  157. // Parity check failed
  158. return -1;
  159. }
  160. vanc_sum += v;
  161. }
  162. vanc_sum &= 0x1ff;
  163. vanc_sum |= ((~vanc_sum & 0x100) << 1);
  164. if (checksum != vanc_sum) {
  165. // Checksum verification failed
  166. return -1;
  167. }
  168. return 0;
  169. }
  170. /* The 10-bit VANC data is packed in V210, we only need the luma component. */
  171. static void extract_luma_from_v210(uint16_t *dst, const uint8_t *src, int width)
  172. {
  173. int i;
  174. for (i = 0; i < width / 3; i++) {
  175. *dst++ = (src[1] >> 2) + ((src[2] & 15) << 6);
  176. *dst++ = src[4] + ((src[5] & 3) << 8);
  177. *dst++ = (src[6] >> 4) + ((src[7] & 63) << 4);
  178. src += 8;
  179. }
  180. }
  181. static void unpack_v210(uint16_t *dst, const uint8_t *src, int width)
  182. {
  183. int i;
  184. for (i = 0; i < width * 2 / 3; i++) {
  185. *dst++ = src[0] + ((src[1] & 3) << 8);
  186. *dst++ = (src[1] >> 2) + ((src[2] & 15) << 6);
  187. *dst++ = (src[2] >> 4) + ((src[3] & 63) << 4);
  188. src += 4;
  189. }
  190. }
  191. static uint8_t calc_parity_and_line_offset(int line)
  192. {
  193. uint8_t ret = (line < 313) << 5;
  194. if (line >= 7 && line <= 22)
  195. ret += line;
  196. if (line >= 320 && line <= 335)
  197. ret += (line - 313);
  198. return ret;
  199. }
  200. static void fill_data_unit_head(int line, uint8_t *tgt)
  201. {
  202. tgt[0] = 0x02; // data_unit_id
  203. tgt[1] = 0x2c; // data_unit_length
  204. tgt[2] = calc_parity_and_line_offset(line); // field_parity, line_offset
  205. tgt[3] = 0xe4; // framing code
  206. }
  207. #if CONFIG_LIBZVBI
  208. static uint8_t* teletext_data_unit_from_vbi_data(int line, uint8_t *src, uint8_t *tgt, vbi_pixfmt fmt)
  209. {
  210. vbi_bit_slicer slicer;
  211. vbi_bit_slicer_init(&slicer, 720, 13500000, 6937500, 6937500, 0x00aaaae4, 0xffff, 18, 6, 42 * 8, VBI_MODULATION_NRZ_MSB, fmt);
  212. if (vbi_bit_slice(&slicer, src, tgt + 4) == FALSE)
  213. return tgt;
  214. fill_data_unit_head(line, tgt);
  215. return tgt + 46;
  216. }
  217. static uint8_t* teletext_data_unit_from_vbi_data_10bit(int line, uint8_t *src, uint8_t *tgt)
  218. {
  219. uint8_t y[720];
  220. uint8_t *py = y;
  221. uint8_t *pend = y + 720;
  222. /* The 10-bit VBI data is packed in V210, but libzvbi only supports 8-bit,
  223. * so we extract the 8 MSBs of the luma component, that is enough for
  224. * teletext bit slicing. */
  225. while (py < pend) {
  226. *py++ = (src[1] >> 4) + ((src[2] & 15) << 4);
  227. *py++ = (src[4] >> 2) + ((src[5] & 3 ) << 6);
  228. *py++ = (src[6] >> 6) + ((src[7] & 63) << 2);
  229. src += 8;
  230. }
  231. return teletext_data_unit_from_vbi_data(line, y, tgt, VBI_PIXFMT_YUV420);
  232. }
  233. #endif
  234. static uint8_t* teletext_data_unit_from_op47_vbi_packet(int line, uint16_t *py, uint8_t *tgt)
  235. {
  236. int i;
  237. if (py[0] != 0x255 || py[1] != 0x255 || py[2] != 0x227)
  238. return tgt;
  239. fill_data_unit_head(line, tgt);
  240. py += 3;
  241. tgt += 4;
  242. for (i = 0; i < 42; i++)
  243. *tgt++ = ff_reverse[py[i] & 255];
  244. return tgt;
  245. }
  246. static int linemask_matches(int line, int64_t mask)
  247. {
  248. int shift = -1;
  249. if (line >= 6 && line <= 22)
  250. shift = line - 6;
  251. if (line >= 318 && line <= 335)
  252. shift = line - 318 + 17;
  253. return shift >= 0 && ((1ULL << shift) & mask);
  254. }
  255. static uint8_t* teletext_data_unit_from_op47_data(uint16_t *py, uint16_t *pend, uint8_t *tgt, int64_t wanted_lines)
  256. {
  257. if (py < pend - 9) {
  258. if (py[0] == 0x151 && py[1] == 0x115 && py[3] == 0x102) { // identifier, identifier, format code for WST teletext
  259. uint16_t *descriptors = py + 4;
  260. int i;
  261. py += 9;
  262. for (i = 0; i < 5 && py < pend - 45; i++, py += 45) {
  263. int line = (descriptors[i] & 31) + (!(descriptors[i] & 128)) * 313;
  264. if (line && linemask_matches(line, wanted_lines))
  265. tgt = teletext_data_unit_from_op47_vbi_packet(line, py, tgt);
  266. }
  267. }
  268. }
  269. return tgt;
  270. }
  271. 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)
  272. {
  273. uint16_t did = py[0]; // data id
  274. uint16_t sdid = py[1]; // secondary data id
  275. uint16_t dc = py[2] & 255; // data count
  276. py += 3;
  277. pend = FFMIN(pend, py + dc);
  278. if (did == 0x143 && sdid == 0x102) { // subtitle distribution packet
  279. tgt = teletext_data_unit_from_op47_data(py, pend, tgt, wanted_lines);
  280. } else if (allow_multipacket && did == 0x143 && sdid == 0x203) { // VANC multipacket
  281. py += 2; // priority, line/field
  282. while (py < pend - 3) {
  283. tgt = teletext_data_unit_from_ancillary_packet(py, pend, tgt, wanted_lines, 0);
  284. py += 4 + (py[2] & 255); // ndid, nsdid, ndc, line/field
  285. }
  286. }
  287. return tgt;
  288. }
  289. static uint8_t *vanc_to_cc(AVFormatContext *avctx, uint16_t *buf, size_t words,
  290. unsigned &cc_count)
  291. {
  292. size_t i, len = (buf[5] & 0xff) + 6 + 1;
  293. uint8_t cdp_sum, rate;
  294. uint16_t hdr, ftr;
  295. uint8_t *cc;
  296. uint16_t *cdp = &buf[6]; // CDP follows
  297. if (cdp[0] != 0x96 || cdp[1] != 0x69) {
  298. av_log(avctx, AV_LOG_WARNING, "Invalid CDP header 0x%.2x 0x%.2x\n", cdp[0], cdp[1]);
  299. return NULL;
  300. }
  301. len -= 7; // remove VANC header and checksum
  302. if (cdp[2] != len) {
  303. av_log(avctx, AV_LOG_WARNING, "CDP len %d != %zu\n", cdp[2], len);
  304. return NULL;
  305. }
  306. cdp_sum = 0;
  307. for (i = 0; i < len - 1; i++)
  308. cdp_sum += cdp[i];
  309. cdp_sum = cdp_sum ? 256 - cdp_sum : 0;
  310. if (cdp[len - 1] != cdp_sum) {
  311. av_log(avctx, AV_LOG_WARNING, "CDP checksum invalid 0x%.4x != 0x%.4x\n", cdp_sum, cdp[len-1]);
  312. return NULL;
  313. }
  314. rate = cdp[3];
  315. if (!(rate & 0x0f)) {
  316. av_log(avctx, AV_LOG_WARNING, "CDP frame rate invalid (0x%.2x)\n", rate);
  317. return NULL;
  318. }
  319. rate >>= 4;
  320. if (rate > 8) {
  321. av_log(avctx, AV_LOG_WARNING, "CDP frame rate invalid (0x%.2x)\n", rate);
  322. return NULL;
  323. }
  324. if (!(cdp[4] & 0x43)) /* ccdata_present | caption_service_active | reserved */ {
  325. av_log(avctx, AV_LOG_WARNING, "CDP flags invalid (0x%.2x)\n", cdp[4]);
  326. return NULL;
  327. }
  328. hdr = (cdp[5] << 8) | cdp[6];
  329. if (cdp[7] != 0x72) /* ccdata_id */ {
  330. av_log(avctx, AV_LOG_WARNING, "Invalid ccdata_id 0x%.2x\n", cdp[7]);
  331. return NULL;
  332. }
  333. cc_count = cdp[8];
  334. if (!(cc_count & 0xe0)) {
  335. av_log(avctx, AV_LOG_WARNING, "Invalid cc_count 0x%.2x\n", cc_count);
  336. return NULL;
  337. }
  338. cc_count &= 0x1f;
  339. if ((len - 13) < cc_count * 3) {
  340. av_log(avctx, AV_LOG_WARNING, "Invalid cc_count %d (> %zu)\n", cc_count * 3, len - 13);
  341. return NULL;
  342. }
  343. if (cdp[len - 4] != 0x74) /* footer id */ {
  344. av_log(avctx, AV_LOG_WARNING, "Invalid footer id 0x%.2x\n", cdp[len-4]);
  345. return NULL;
  346. }
  347. ftr = (cdp[len - 3] << 8) | cdp[len - 2];
  348. if (ftr != hdr) {
  349. av_log(avctx, AV_LOG_WARNING, "Header 0x%.4x != Footer 0x%.4x\n", hdr, ftr);
  350. return NULL;
  351. }
  352. cc = (uint8_t *)av_malloc(cc_count * 3);
  353. if (cc == NULL) {
  354. av_log(avctx, AV_LOG_WARNING, "CC - av_malloc failed for cc_count = %d\n", cc_count);
  355. return NULL;
  356. }
  357. for (size_t i = 0; i < cc_count; i++) {
  358. cc[3*i + 0] = cdp[9 + 3*i+0] /* & 3 */;
  359. cc[3*i + 1] = cdp[9 + 3*i+1];
  360. cc[3*i + 2] = cdp[9 + 3*i+2];
  361. }
  362. cc_count *= 3;
  363. return cc;
  364. }
  365. static uint8_t *get_metadata(AVFormatContext *avctx, uint16_t *buf, size_t width,
  366. uint8_t *tgt, size_t tgt_size, AVPacket *pkt)
  367. {
  368. decklink_cctx *cctx = (struct decklink_cctx *) avctx->priv_data;
  369. uint16_t *max_buf = buf + width;
  370. while (buf < max_buf - 6) {
  371. int len;
  372. uint16_t did = buf[3] & 0xFF; // data id
  373. uint16_t sdid = buf[4] & 0xFF; // secondary data id
  374. /* Check for VANC header */
  375. if (buf[0] != 0 || buf[1] != 0x3ff || buf[2] != 0x3ff) {
  376. return tgt;
  377. }
  378. len = (buf[5] & 0xff) + 6 + 1;
  379. if (len > max_buf - buf) {
  380. av_log(avctx, AV_LOG_WARNING, "Data Count (%d) > data left (%zu)\n",
  381. len, max_buf - buf);
  382. return tgt;
  383. }
  384. if (did == 0x43 && (sdid == 0x02 || sdid == 0x03) && cctx->teletext_lines &&
  385. width == 1920 && tgt_size >= 1920) {
  386. if (check_vanc_parity_checksum(buf, len, buf[len - 1]) < 0) {
  387. av_log(avctx, AV_LOG_WARNING, "VANC parity or checksum incorrect\n");
  388. goto skip_packet;
  389. }
  390. tgt = teletext_data_unit_from_ancillary_packet(buf + 3, buf + len, tgt, cctx->teletext_lines, 1);
  391. } else if (did == 0x61 && sdid == 0x01) {
  392. unsigned int data_len;
  393. uint8_t *data;
  394. if (check_vanc_parity_checksum(buf, len, buf[len - 1]) < 0) {
  395. av_log(avctx, AV_LOG_WARNING, "VANC parity or checksum incorrect\n");
  396. goto skip_packet;
  397. }
  398. clear_parity_bits(buf, len);
  399. data = vanc_to_cc(avctx, buf, width, data_len);
  400. if (data) {
  401. if (av_packet_add_side_data(pkt, AV_PKT_DATA_A53_CC, data, data_len) < 0)
  402. av_free(data);
  403. }
  404. } else {
  405. av_log(avctx, AV_LOG_DEBUG, "Unknown meta data DID = 0x%.2x SDID = 0x%.2x\n",
  406. did, sdid);
  407. }
  408. skip_packet:
  409. buf += len;
  410. }
  411. return tgt;
  412. }
  413. static void avpacket_queue_init(AVFormatContext *avctx, AVPacketQueue *q)
  414. {
  415. struct decklink_cctx *ctx = (struct decklink_cctx *)avctx->priv_data;
  416. memset(q, 0, sizeof(AVPacketQueue));
  417. pthread_mutex_init(&q->mutex, NULL);
  418. pthread_cond_init(&q->cond, NULL);
  419. q->avctx = avctx;
  420. q->max_q_size = ctx->queue_size;
  421. }
  422. static void avpacket_queue_flush(AVPacketQueue *q)
  423. {
  424. PacketListEntry *pkt, *pkt1;
  425. pthread_mutex_lock(&q->mutex);
  426. for (pkt = q->pkt_list.head; pkt != NULL; pkt = pkt1) {
  427. pkt1 = pkt->next;
  428. av_packet_unref(&pkt->pkt);
  429. av_freep(&pkt);
  430. }
  431. q->pkt_list.head = NULL;
  432. q->pkt_list.tail = NULL;
  433. q->nb_packets = 0;
  434. q->size = 0;
  435. pthread_mutex_unlock(&q->mutex);
  436. }
  437. static void avpacket_queue_end(AVPacketQueue *q)
  438. {
  439. avpacket_queue_flush(q);
  440. pthread_mutex_destroy(&q->mutex);
  441. pthread_cond_destroy(&q->cond);
  442. }
  443. static unsigned long long avpacket_queue_size(AVPacketQueue *q)
  444. {
  445. unsigned long long size;
  446. pthread_mutex_lock(&q->mutex);
  447. size = q->size;
  448. pthread_mutex_unlock(&q->mutex);
  449. return size;
  450. }
  451. static int avpacket_queue_put(AVPacketQueue *q, AVPacket *pkt)
  452. {
  453. PacketListEntry *pkt1;
  454. // Drop Packet if queue size is > maximum queue size
  455. if (avpacket_queue_size(q) > (uint64_t)q->max_q_size) {
  456. av_packet_unref(pkt);
  457. av_log(q->avctx, AV_LOG_WARNING, "Decklink input buffer overrun!\n");
  458. return -1;
  459. }
  460. /* ensure the packet is reference counted */
  461. if (av_packet_make_refcounted(pkt) < 0) {
  462. av_packet_unref(pkt);
  463. return -1;
  464. }
  465. pkt1 = (PacketListEntry *)av_malloc(sizeof(*pkt1));
  466. if (!pkt1) {
  467. av_packet_unref(pkt);
  468. return -1;
  469. }
  470. av_packet_move_ref(&pkt1->pkt, pkt);
  471. pkt1->next = NULL;
  472. pthread_mutex_lock(&q->mutex);
  473. if (!q->pkt_list.tail) {
  474. q->pkt_list.head = pkt1;
  475. } else {
  476. q->pkt_list.tail->next = pkt1;
  477. }
  478. q->pkt_list.tail = pkt1;
  479. q->nb_packets++;
  480. q->size += pkt1->pkt.size + sizeof(*pkt1);
  481. pthread_cond_signal(&q->cond);
  482. pthread_mutex_unlock(&q->mutex);
  483. return 0;
  484. }
  485. static int avpacket_queue_get(AVPacketQueue *q, AVPacket *pkt, int block)
  486. {
  487. int ret;
  488. pthread_mutex_lock(&q->mutex);
  489. for (;; ) {
  490. PacketListEntry *pkt1 = q->pkt_list.head;
  491. if (pkt1) {
  492. q->pkt_list.head = pkt1->next;
  493. if (!q->pkt_list.head) {
  494. q->pkt_list.tail = NULL;
  495. }
  496. q->nb_packets--;
  497. q->size -= pkt1->pkt.size + sizeof(*pkt1);
  498. *pkt = pkt1->pkt;
  499. av_free(pkt1);
  500. ret = 1;
  501. break;
  502. } else if (!block) {
  503. ret = 0;
  504. break;
  505. } else {
  506. pthread_cond_wait(&q->cond, &q->mutex);
  507. }
  508. }
  509. pthread_mutex_unlock(&q->mutex);
  510. return ret;
  511. }
  512. static void handle_klv(AVFormatContext *avctx, decklink_ctx *ctx, IDeckLinkVideoInputFrame *videoFrame, int64_t pts)
  513. {
  514. const uint8_t KLV_DID = 0x44;
  515. const uint8_t KLV_IN_VANC_SDID = 0x04;
  516. struct KLVPacket
  517. {
  518. uint16_t sequence_counter;
  519. std::vector<uint8_t> data;
  520. };
  521. size_t total_size = 0;
  522. std::vector<std::vector<KLVPacket>> klv_packets(256);
  523. IDeckLinkVideoFrameAncillaryPackets *packets = nullptr;
  524. if (videoFrame->QueryInterface(IID_IDeckLinkVideoFrameAncillaryPackets, (void**)&packets) != S_OK)
  525. return;
  526. IDeckLinkAncillaryPacketIterator *it = nullptr;
  527. if (packets->GetPacketIterator(&it) != S_OK) {
  528. packets->Release();
  529. return;
  530. }
  531. IDeckLinkAncillaryPacket *packet = nullptr;
  532. while (it->Next(&packet) == S_OK) {
  533. uint8_t *data = nullptr;
  534. uint32_t size = 0;
  535. if (packet->GetDID() == KLV_DID && packet->GetSDID() == KLV_IN_VANC_SDID) {
  536. av_log(avctx, AV_LOG_DEBUG, "Found KLV VANC packet on line: %d\n", packet->GetLineNumber());
  537. if (packet->GetBytes(bmdAncillaryPacketFormatUInt8, (const void**) &data, &size) == S_OK) {
  538. // MID and PSC
  539. if (size > 3) {
  540. uint8_t mid = data[0];
  541. uint16_t psc = data[1] << 8 | data[2];
  542. av_log(avctx, AV_LOG_DEBUG, "KLV with MID: %d and PSC: %d\n", mid, psc);
  543. auto& list = klv_packets[mid];
  544. uint16_t expected_psc = list.size() + 1;
  545. if (psc == expected_psc) {
  546. uint32_t data_len = size - 3;
  547. total_size += data_len;
  548. KLVPacket packet{ psc };
  549. packet.data.resize(data_len);
  550. memcpy(packet.data.data(), data + 3, data_len);
  551. list.push_back(std::move(packet));
  552. } else {
  553. av_log(avctx, AV_LOG_WARNING, "Out of order PSC: %d for MID: %d\n", psc, mid);
  554. if (!list.empty()) {
  555. for (auto& klv : list)
  556. total_size -= klv.data.size();
  557. list.clear();
  558. }
  559. }
  560. }
  561. }
  562. }
  563. packet->Release();
  564. }
  565. it->Release();
  566. packets->Release();
  567. if (total_size > 0) {
  568. std::vector<uint8_t> klv;
  569. klv.reserve(total_size);
  570. for (size_t i = 0; i < klv_packets.size(); ++i) {
  571. auto& list = klv_packets[i];
  572. if (list.empty())
  573. continue;
  574. av_log(avctx, AV_LOG_DEBUG, "Joining MID: %d\n", (int)i);
  575. for (auto& packet : list)
  576. klv.insert(klv.end(), packet.data.begin(), packet.data.end());
  577. }
  578. AVPacket klv_packet = { 0 };
  579. klv_packet.pts = pts;
  580. klv_packet.dts = pts;
  581. klv_packet.flags |= AV_PKT_FLAG_KEY;
  582. klv_packet.stream_index = ctx->klv_st->index;
  583. klv_packet.data = klv.data();
  584. klv_packet.size = klv.size();
  585. if (avpacket_queue_put(&ctx->queue, &klv_packet) < 0) {
  586. ++ctx->dropped;
  587. }
  588. }
  589. }
  590. class decklink_input_callback : public IDeckLinkInputCallback
  591. {
  592. public:
  593. decklink_input_callback(AVFormatContext *_avctx);
  594. ~decklink_input_callback();
  595. virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv) { return E_NOINTERFACE; }
  596. virtual ULONG STDMETHODCALLTYPE AddRef(void);
  597. virtual ULONG STDMETHODCALLTYPE Release(void);
  598. virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents, IDeckLinkDisplayMode*, BMDDetectedVideoInputFormatFlags);
  599. virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame*, IDeckLinkAudioInputPacket*);
  600. private:
  601. std::atomic<int> _refs;
  602. AVFormatContext *avctx;
  603. decklink_ctx *ctx;
  604. int no_video;
  605. int64_t initial_video_pts;
  606. int64_t initial_audio_pts;
  607. };
  608. decklink_input_callback::decklink_input_callback(AVFormatContext *_avctx) : _refs(1)
  609. {
  610. avctx = _avctx;
  611. decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
  612. ctx = (struct decklink_ctx *)cctx->ctx;
  613. no_video = 0;
  614. initial_audio_pts = initial_video_pts = AV_NOPTS_VALUE;
  615. }
  616. decklink_input_callback::~decklink_input_callback()
  617. {
  618. }
  619. ULONG decklink_input_callback::AddRef(void)
  620. {
  621. return ++_refs;
  622. }
  623. ULONG decklink_input_callback::Release(void)
  624. {
  625. int ret = --_refs;
  626. if (!ret)
  627. delete this;
  628. return ret;
  629. }
  630. static int64_t get_pkt_pts(IDeckLinkVideoInputFrame *videoFrame,
  631. IDeckLinkAudioInputPacket *audioFrame,
  632. int64_t wallclock,
  633. int64_t abs_wallclock,
  634. DecklinkPtsSource pts_src,
  635. AVRational time_base, int64_t *initial_pts,
  636. int copyts)
  637. {
  638. int64_t pts = AV_NOPTS_VALUE;
  639. BMDTimeValue bmd_pts;
  640. BMDTimeValue bmd_duration;
  641. HRESULT res = E_INVALIDARG;
  642. switch (pts_src) {
  643. case PTS_SRC_AUDIO:
  644. if (audioFrame)
  645. res = audioFrame->GetPacketTime(&bmd_pts, time_base.den);
  646. break;
  647. case PTS_SRC_VIDEO:
  648. if (videoFrame)
  649. res = videoFrame->GetStreamTime(&bmd_pts, &bmd_duration, time_base.den);
  650. break;
  651. case PTS_SRC_REFERENCE:
  652. if (videoFrame)
  653. res = videoFrame->GetHardwareReferenceTimestamp(time_base.den, &bmd_pts, &bmd_duration);
  654. break;
  655. case PTS_SRC_WALLCLOCK:
  656. /* fall through */
  657. case PTS_SRC_ABS_WALLCLOCK:
  658. {
  659. /* MSVC does not support compound literals like AV_TIME_BASE_Q
  660. * in C++ code (compiler error C4576) */
  661. AVRational timebase;
  662. timebase.num = 1;
  663. timebase.den = AV_TIME_BASE;
  664. if (pts_src == PTS_SRC_WALLCLOCK)
  665. pts = av_rescale_q(wallclock, timebase, time_base);
  666. else
  667. pts = av_rescale_q(abs_wallclock, timebase, time_base);
  668. break;
  669. }
  670. }
  671. if (res == S_OK)
  672. pts = bmd_pts / time_base.num;
  673. if (!copyts) {
  674. if (pts != AV_NOPTS_VALUE && *initial_pts == AV_NOPTS_VALUE)
  675. *initial_pts = pts;
  676. if (*initial_pts != AV_NOPTS_VALUE)
  677. pts -= *initial_pts;
  678. }
  679. return pts;
  680. }
  681. static int get_bmd_timecode(AVFormatContext *avctx, AVTimecode *tc, AVRational frame_rate, BMDTimecodeFormat tc_format, IDeckLinkVideoInputFrame *videoFrame)
  682. {
  683. IDeckLinkTimecode *timecode;
  684. int ret = AVERROR(ENOENT);
  685. #if BLACKMAGIC_DECKLINK_API_VERSION >= 0x0b000000
  686. int hfr = (tc_format == bmdTimecodeRP188HighFrameRate);
  687. #else
  688. int hfr = 0;
  689. #endif
  690. if (videoFrame->GetTimecode(tc_format, &timecode) == S_OK) {
  691. uint8_t hh, mm, ss, ff;
  692. if (timecode->GetComponents(&hh, &mm, &ss, &ff) == S_OK) {
  693. int flags = (timecode->GetFlags() & bmdTimecodeIsDropFrame) ? AV_TIMECODE_FLAG_DROPFRAME : 0;
  694. if (!hfr && av_cmp_q(frame_rate, av_make_q(30, 1)) == 1)
  695. ff = ff << 1 | !!(timecode->GetFlags() & bmdTimecodeFieldMark);
  696. ret = av_timecode_init_from_components(tc, frame_rate, flags, hh, mm, ss, ff, avctx);
  697. }
  698. timecode->Release();
  699. }
  700. return ret;
  701. }
  702. static int get_frame_timecode(AVFormatContext *avctx, decklink_ctx *ctx, AVTimecode *tc, IDeckLinkVideoInputFrame *videoFrame)
  703. {
  704. AVRational frame_rate = ctx->video_st->r_frame_rate;
  705. int ret;
  706. /* 50/60 fps content has alternating VITC1 and VITC2 timecode (see SMPTE ST
  707. * 12-2, section 7), so the native ordering of RP188Any (HFR, VITC1, LTC,
  708. * VITC2) would not work because LTC might not contain the field flag.
  709. * Therefore we query the types manually. */
  710. if (ctx->tc_format == bmdTimecodeRP188Any && av_cmp_q(frame_rate, av_make_q(30, 1)) == 1) {
  711. #if BLACKMAGIC_DECKLINK_API_VERSION >= 0x0b000000
  712. ret = get_bmd_timecode(avctx, tc, frame_rate, bmdTimecodeRP188HighFrameRate, videoFrame);
  713. if (ret == AVERROR(ENOENT))
  714. #endif
  715. ret = get_bmd_timecode(avctx, tc, frame_rate, bmdTimecodeRP188VITC1, videoFrame);
  716. if (ret == AVERROR(ENOENT))
  717. ret = get_bmd_timecode(avctx, tc, frame_rate, bmdTimecodeRP188VITC2, videoFrame);
  718. if (ret == AVERROR(ENOENT))
  719. ret = get_bmd_timecode(avctx, tc, frame_rate, bmdTimecodeRP188LTC, videoFrame);
  720. } else {
  721. ret = get_bmd_timecode(avctx, tc, frame_rate, ctx->tc_format, videoFrame);
  722. }
  723. return ret;
  724. }
  725. HRESULT decklink_input_callback::VideoInputFrameArrived(
  726. IDeckLinkVideoInputFrame *videoFrame, IDeckLinkAudioInputPacket *audioFrame)
  727. {
  728. void *frameBytes;
  729. void *audioFrameBytes;
  730. BMDTimeValue frameTime;
  731. BMDTimeValue frameDuration;
  732. int64_t wallclock = 0, abs_wallclock = 0;
  733. struct decklink_cctx *cctx = (struct decklink_cctx *) avctx->priv_data;
  734. if (ctx->autodetect) {
  735. if (videoFrame && !(videoFrame->GetFlags() & bmdFrameHasNoInputSource) &&
  736. ctx->bmd_mode == bmdModeUnknown)
  737. {
  738. ctx->bmd_mode = AUTODETECT_DEFAULT_MODE;
  739. }
  740. return S_OK;
  741. }
  742. // Drop the frames till system's timestamp aligns with the configured value.
  743. if (0 == ctx->frameCount && cctx->timestamp_align) {
  744. AVRational remainder = av_make_q(av_gettime() % cctx->timestamp_align, 1000000);
  745. AVRational frame_duration = av_inv_q(ctx->video_st->r_frame_rate);
  746. if (av_cmp_q(remainder, frame_duration) > 0) {
  747. ++ctx->dropped;
  748. return S_OK;
  749. }
  750. }
  751. ctx->frameCount++;
  752. if (ctx->audio_pts_source == PTS_SRC_WALLCLOCK || ctx->video_pts_source == PTS_SRC_WALLCLOCK)
  753. wallclock = av_gettime_relative();
  754. if (ctx->audio_pts_source == PTS_SRC_ABS_WALLCLOCK || ctx->video_pts_source == PTS_SRC_ABS_WALLCLOCK)
  755. abs_wallclock = av_gettime();
  756. // Handle Video Frame
  757. if (videoFrame) {
  758. AVPacket pkt = { 0 };
  759. if (ctx->frameCount % 25 == 0) {
  760. unsigned long long qsize = avpacket_queue_size(&ctx->queue);
  761. av_log(avctx, AV_LOG_DEBUG,
  762. "Frame received (#%lu) - Valid (%liB) - QSize %fMB\n",
  763. ctx->frameCount,
  764. videoFrame->GetRowBytes() * videoFrame->GetHeight(),
  765. (double)qsize / 1024 / 1024);
  766. }
  767. videoFrame->GetBytes(&frameBytes);
  768. videoFrame->GetStreamTime(&frameTime, &frameDuration,
  769. ctx->video_st->time_base.den);
  770. if (videoFrame->GetFlags() & bmdFrameHasNoInputSource) {
  771. if (ctx->draw_bars && videoFrame->GetPixelFormat() == bmdFormat8BitYUV) {
  772. unsigned bars[8] = {
  773. 0xEA80EA80, 0xD292D210, 0xA910A9A5, 0x90229035,
  774. 0x6ADD6ACA, 0x51EF515A, 0x286D28EF, 0x10801080 };
  775. int width = videoFrame->GetWidth();
  776. int height = videoFrame->GetHeight();
  777. unsigned *p = (unsigned *)frameBytes;
  778. for (int y = 0; y < height; y++) {
  779. for (int x = 0; x < width; x += 2)
  780. *p++ = bars[(x * 8) / width];
  781. }
  782. }
  783. if (!no_video) {
  784. av_log(avctx, AV_LOG_WARNING, "Frame received (#%lu) - No input signal detected "
  785. "- Frames dropped %u\n", ctx->frameCount, ++ctx->dropped);
  786. }
  787. no_video = 1;
  788. } else {
  789. if (no_video) {
  790. av_log(avctx, AV_LOG_WARNING, "Frame received (#%lu) - Input returned "
  791. "- Frames dropped %u\n", ctx->frameCount, ++ctx->dropped);
  792. }
  793. no_video = 0;
  794. // Handle Timecode (if requested)
  795. if (ctx->tc_format) {
  796. AVTimecode tcr;
  797. if (get_frame_timecode(avctx, ctx, &tcr, videoFrame) >= 0) {
  798. char tcstr[AV_TIMECODE_STR_SIZE];
  799. const char *tc = av_timecode_make_string(&tcr, tcstr, 0);
  800. if (tc) {
  801. AVDictionary* metadata_dict = NULL;
  802. uint8_t* packed_metadata;
  803. if (av_cmp_q(ctx->video_st->r_frame_rate, av_make_q(60, 1)) < 1) {
  804. uint32_t tc_data = av_timecode_get_smpte_from_framenum(&tcr, 0);
  805. int size = sizeof(uint32_t) * 4;
  806. uint32_t *sd = (uint32_t *)av_packet_new_side_data(&pkt, AV_PKT_DATA_S12M_TIMECODE, size);
  807. if (sd) {
  808. *sd = 1; // one TC
  809. *(sd + 1) = tc_data; // TC
  810. }
  811. }
  812. if (av_dict_set(&metadata_dict, "timecode", tc, 0) >= 0) {
  813. size_t metadata_len;
  814. packed_metadata = av_packet_pack_dictionary(metadata_dict, &metadata_len);
  815. av_dict_free(&metadata_dict);
  816. if (packed_metadata) {
  817. if (av_packet_add_side_data(&pkt, AV_PKT_DATA_STRINGS_METADATA, packed_metadata, metadata_len) < 0)
  818. av_freep(&packed_metadata);
  819. else if (!ctx->tc_seen)
  820. ctx->tc_seen = ctx->frameCount;
  821. }
  822. }
  823. }
  824. } else {
  825. av_log(avctx, AV_LOG_DEBUG, "Unable to find timecode.\n");
  826. }
  827. }
  828. }
  829. if (ctx->tc_format && cctx->wait_for_tc && !ctx->tc_seen) {
  830. av_log(avctx, AV_LOG_WARNING, "No TC detected yet. wait_for_tc set. Dropping. \n");
  831. av_log(avctx, AV_LOG_WARNING, "Frame received (#%lu) - "
  832. "- Frames dropped %u\n", ctx->frameCount, ++ctx->dropped);
  833. return S_OK;
  834. }
  835. pkt.pts = get_pkt_pts(videoFrame, audioFrame, wallclock, abs_wallclock, ctx->video_pts_source, ctx->video_st->time_base, &initial_video_pts, cctx->copyts);
  836. pkt.dts = pkt.pts;
  837. pkt.duration = frameDuration;
  838. //To be made sure it still applies
  839. pkt.flags |= AV_PKT_FLAG_KEY;
  840. pkt.stream_index = ctx->video_st->index;
  841. pkt.data = (uint8_t *)frameBytes;
  842. pkt.size = videoFrame->GetRowBytes() *
  843. videoFrame->GetHeight();
  844. //fprintf(stderr,"Video Frame size %d ts %d\n", pkt.size, pkt.pts);
  845. if (!no_video) {
  846. IDeckLinkVideoFrameAncillary *vanc;
  847. AVPacket txt_pkt = { 0 };
  848. uint8_t txt_buf0[3531]; // 35 * 46 bytes decoded teletext lines + 1 byte data_identifier + 1920 bytes OP47 decode buffer
  849. uint8_t *txt_buf = txt_buf0;
  850. if (ctx->enable_klv) {
  851. handle_klv(avctx, ctx, videoFrame, pkt.pts);
  852. }
  853. if (videoFrame->GetAncillaryData(&vanc) == S_OK) {
  854. int i;
  855. BMDPixelFormat vanc_format = vanc->GetPixelFormat();
  856. txt_buf[0] = 0x10; // data_identifier - EBU_data
  857. txt_buf++;
  858. #if CONFIG_LIBZVBI
  859. if (ctx->bmd_mode == bmdModePAL && ctx->teletext_lines &&
  860. (vanc_format == bmdFormat8BitYUV || vanc_format == bmdFormat10BitYUV)) {
  861. int64_t line_mask = 1;
  862. av_assert0(videoFrame->GetWidth() == 720);
  863. for (i = 6; i < 336; i++, line_mask <<= 1) {
  864. uint8_t *buf;
  865. if ((ctx->teletext_lines & line_mask) && vanc->GetBufferForVerticalBlankingLine(i, (void**)&buf) == S_OK) {
  866. if (vanc_format == bmdFormat8BitYUV)
  867. txt_buf = teletext_data_unit_from_vbi_data(i, buf, txt_buf, VBI_PIXFMT_UYVY);
  868. else
  869. txt_buf = teletext_data_unit_from_vbi_data_10bit(i, buf, txt_buf);
  870. }
  871. if (i == 22)
  872. i = 317;
  873. }
  874. }
  875. #endif
  876. if (vanc_format == bmdFormat10BitYUV && videoFrame->GetWidth() <= MAX_WIDTH_VANC) {
  877. int idx = get_vanc_line_idx(ctx->bmd_mode);
  878. for (i = vanc_line_numbers[idx].vanc_start; i <= vanc_line_numbers[idx].vanc_end; i++) {
  879. uint8_t *buf;
  880. if (vanc->GetBufferForVerticalBlankingLine(i, (void**)&buf) == S_OK) {
  881. uint16_t vanc[MAX_WIDTH_VANC];
  882. size_t vanc_size = videoFrame->GetWidth();
  883. if (ctx->bmd_mode == bmdModeNTSC && videoFrame->GetWidth() * 2 <= MAX_WIDTH_VANC) {
  884. vanc_size = vanc_size * 2;
  885. unpack_v210(vanc, buf, videoFrame->GetWidth());
  886. } else {
  887. extract_luma_from_v210(vanc, buf, videoFrame->GetWidth());
  888. }
  889. txt_buf = get_metadata(avctx, vanc, vanc_size,
  890. txt_buf, sizeof(txt_buf0) - (txt_buf - txt_buf0), &pkt);
  891. }
  892. if (i == vanc_line_numbers[idx].field0_vanc_end)
  893. i = vanc_line_numbers[idx].field1_vanc_start - 1;
  894. }
  895. }
  896. vanc->Release();
  897. if (txt_buf - txt_buf0 > 1) {
  898. int stuffing_units = (4 - ((45 + txt_buf - txt_buf0) / 46) % 4) % 4;
  899. while (stuffing_units--) {
  900. memset(txt_buf, 0xff, 46);
  901. txt_buf[1] = 0x2c; // data_unit_length
  902. txt_buf += 46;
  903. }
  904. txt_pkt.pts = pkt.pts;
  905. txt_pkt.dts = pkt.dts;
  906. txt_pkt.stream_index = ctx->teletext_st->index;
  907. txt_pkt.data = txt_buf0;
  908. txt_pkt.size = txt_buf - txt_buf0;
  909. if (avpacket_queue_put(&ctx->queue, &txt_pkt) < 0) {
  910. ++ctx->dropped;
  911. }
  912. }
  913. }
  914. }
  915. pkt.buf = av_buffer_create(pkt.data, pkt.size, decklink_object_free, videoFrame, 0);
  916. if (pkt.buf)
  917. videoFrame->AddRef();
  918. if (avpacket_queue_put(&ctx->queue, &pkt) < 0) {
  919. ++ctx->dropped;
  920. }
  921. }
  922. // Handle Audio Frame
  923. if (audioFrame) {
  924. AVPacket pkt = { 0 };
  925. BMDTimeValue audio_pts;
  926. //hack among hacks
  927. pkt.size = audioFrame->GetSampleFrameCount() * ctx->audio_st->codecpar->ch_layout.nb_channels * (ctx->audio_depth / 8);
  928. audioFrame->GetBytes(&audioFrameBytes);
  929. audioFrame->GetPacketTime(&audio_pts, ctx->audio_st->time_base.den);
  930. pkt.pts = get_pkt_pts(videoFrame, audioFrame, wallclock, abs_wallclock, ctx->audio_pts_source, ctx->audio_st->time_base, &initial_audio_pts, cctx->copyts);
  931. pkt.dts = pkt.pts;
  932. //fprintf(stderr,"Audio Frame size %d ts %d\n", pkt.size, pkt.pts);
  933. pkt.flags |= AV_PKT_FLAG_KEY;
  934. pkt.stream_index = ctx->audio_st->index;
  935. pkt.data = (uint8_t *)audioFrameBytes;
  936. if (avpacket_queue_put(&ctx->queue, &pkt) < 0) {
  937. ++ctx->dropped;
  938. }
  939. }
  940. return S_OK;
  941. }
  942. HRESULT decklink_input_callback::VideoInputFormatChanged(
  943. BMDVideoInputFormatChangedEvents events, IDeckLinkDisplayMode *mode,
  944. BMDDetectedVideoInputFormatFlags formatFlags)
  945. {
  946. struct decklink_cctx *cctx = (struct decklink_cctx *) avctx->priv_data;
  947. ctx->bmd_mode = mode->GetDisplayMode();
  948. // check the C context member to make sure we set both raw_format and bmd_mode with data from the same format change callback
  949. if (!cctx->raw_format)
  950. ctx->raw_format = (formatFlags & bmdDetectedVideoInputRGB444) ? bmdFormat8BitARGB : bmdFormat8BitYUV;
  951. return S_OK;
  952. }
  953. static int decklink_autodetect(struct decklink_cctx *cctx) {
  954. struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
  955. DECKLINK_BOOL autodetect_supported = false;
  956. int i;
  957. if (ctx->attr->GetFlag(BMDDeckLinkSupportsInputFormatDetection, &autodetect_supported) != S_OK)
  958. return -1;
  959. if (autodetect_supported == false)
  960. return -1;
  961. ctx->autodetect = 1;
  962. ctx->bmd_mode = bmdModeUnknown;
  963. if (ctx->dli->EnableVideoInput(AUTODETECT_DEFAULT_MODE,
  964. bmdFormat8BitYUV,
  965. bmdVideoInputEnableFormatDetection) != S_OK) {
  966. return -1;
  967. }
  968. if (ctx->dli->StartStreams() != S_OK) {
  969. return -1;
  970. }
  971. // 3 second timeout
  972. for (i = 0; i < 30; i++) {
  973. av_usleep(100000);
  974. /* Sometimes VideoInputFrameArrived is called without the
  975. * bmdFrameHasNoInputSource flag before VideoInputFormatChanged.
  976. * So don't break for bmd_mode == AUTODETECT_DEFAULT_MODE. */
  977. if (ctx->bmd_mode != bmdModeUnknown &&
  978. ctx->bmd_mode != AUTODETECT_DEFAULT_MODE)
  979. break;
  980. }
  981. ctx->dli->PauseStreams();
  982. ctx->dli->FlushStreams();
  983. ctx->autodetect = 0;
  984. if (ctx->bmd_mode != bmdModeUnknown) {
  985. cctx->format_code = (char *)av_mallocz(5);
  986. if (!cctx->format_code)
  987. return -1;
  988. AV_WB32(cctx->format_code, ctx->bmd_mode);
  989. return 0;
  990. } else {
  991. return -1;
  992. }
  993. }
  994. extern "C" {
  995. av_cold int ff_decklink_read_close(AVFormatContext *avctx)
  996. {
  997. struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
  998. struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
  999. if (ctx->dli) {
  1000. ctx->dli->StopStreams();
  1001. ctx->dli->DisableVideoInput();
  1002. ctx->dli->DisableAudioInput();
  1003. }
  1004. ff_decklink_cleanup(avctx);
  1005. avpacket_queue_end(&ctx->queue);
  1006. av_freep(&cctx->ctx);
  1007. return 0;
  1008. }
  1009. av_cold int ff_decklink_read_header(AVFormatContext *avctx)
  1010. {
  1011. struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
  1012. struct decklink_ctx *ctx;
  1013. class decklink_allocator *allocator;
  1014. class decklink_input_callback *input_callback;
  1015. AVStream *st;
  1016. HRESULT result;
  1017. int ret;
  1018. ctx = (struct decklink_ctx *) av_mallocz(sizeof(struct decklink_ctx));
  1019. if (!ctx)
  1020. return AVERROR(ENOMEM);
  1021. ctx->list_devices = cctx->list_devices;
  1022. ctx->list_formats = cctx->list_formats;
  1023. ctx->enable_klv = cctx->enable_klv;
  1024. ctx->teletext_lines = cctx->teletext_lines;
  1025. ctx->preroll = cctx->preroll;
  1026. ctx->duplex_mode = cctx->duplex_mode;
  1027. if (cctx->tc_format > 0 && (unsigned int)cctx->tc_format < FF_ARRAY_ELEMS(decklink_timecode_format_map))
  1028. ctx->tc_format = decklink_timecode_format_map[cctx->tc_format];
  1029. if (cctx->video_input > 0 && (unsigned int)cctx->video_input < FF_ARRAY_ELEMS(decklink_video_connection_map))
  1030. ctx->video_input = decklink_video_connection_map[cctx->video_input];
  1031. if (cctx->audio_input > 0 && (unsigned int)cctx->audio_input < FF_ARRAY_ELEMS(decklink_audio_connection_map))
  1032. ctx->audio_input = decklink_audio_connection_map[cctx->audio_input];
  1033. ctx->audio_pts_source = cctx->audio_pts_source;
  1034. ctx->video_pts_source = cctx->video_pts_source;
  1035. ctx->draw_bars = cctx->draw_bars;
  1036. ctx->audio_depth = cctx->audio_depth;
  1037. if (cctx->raw_format > 0 && (unsigned int)cctx->raw_format < FF_ARRAY_ELEMS(decklink_raw_format_map))
  1038. ctx->raw_format = decklink_raw_format_map[cctx->raw_format];
  1039. cctx->ctx = ctx;
  1040. /* Check audio channel option for valid values: 2, 8 or 16 */
  1041. switch (cctx->audio_channels) {
  1042. case 2:
  1043. case 8:
  1044. case 16:
  1045. break;
  1046. default:
  1047. av_log(avctx, AV_LOG_ERROR, "Value of channels option must be one of 2, 8 or 16\n");
  1048. return AVERROR(EINVAL);
  1049. }
  1050. /* Check audio bit depth option for valid values: 16 or 32 */
  1051. switch (cctx->audio_depth) {
  1052. case 16:
  1053. case 32:
  1054. break;
  1055. default:
  1056. av_log(avctx, AV_LOG_ERROR, "Value for audio bit depth option must be either 16 or 32\n");
  1057. return AVERROR(EINVAL);
  1058. }
  1059. /* List available devices. */
  1060. if (ctx->list_devices) {
  1061. ff_decklink_list_devices_legacy(avctx, 1, 0);
  1062. return AVERROR_EXIT;
  1063. }
  1064. ret = ff_decklink_init_device(avctx, avctx->url);
  1065. if (ret < 0)
  1066. return ret;
  1067. /* Get input device. */
  1068. if (ctx->dl->QueryInterface(IID_IDeckLinkInput, (void **) &ctx->dli) != S_OK) {
  1069. av_log(avctx, AV_LOG_ERROR, "Could not open input device from '%s'\n",
  1070. avctx->url);
  1071. ret = AVERROR(EIO);
  1072. goto error;
  1073. }
  1074. if (ff_decklink_set_configs(avctx, DIRECTION_IN) < 0) {
  1075. av_log(avctx, AV_LOG_ERROR, "Could not set input configuration\n");
  1076. ret = AVERROR(EIO);
  1077. goto error;
  1078. }
  1079. /* List supported formats. */
  1080. if (ctx->list_formats) {
  1081. ff_decklink_list_formats(avctx, DIRECTION_IN);
  1082. ret = AVERROR_EXIT;
  1083. goto error;
  1084. }
  1085. input_callback = new decklink_input_callback(avctx);
  1086. ret = (ctx->dli->SetCallback(input_callback) == S_OK ? 0 : AVERROR_EXTERNAL);
  1087. input_callback->Release();
  1088. if (ret < 0) {
  1089. av_log(avctx, AV_LOG_ERROR, "Cannot set input callback\n");
  1090. goto error;
  1091. }
  1092. allocator = new decklink_allocator();
  1093. ret = (ctx->dli->SetVideoInputFrameMemoryAllocator(allocator) == S_OK ? 0 : AVERROR_EXTERNAL);
  1094. allocator->Release();
  1095. if (ret < 0) {
  1096. av_log(avctx, AV_LOG_ERROR, "Cannot set custom memory allocator\n");
  1097. goto error;
  1098. }
  1099. if (!cctx->format_code) {
  1100. if (decklink_autodetect(cctx) < 0) {
  1101. av_log(avctx, AV_LOG_ERROR, "Cannot Autodetect input stream or No signal\n");
  1102. ret = AVERROR(EIO);
  1103. goto error;
  1104. }
  1105. av_log(avctx, AV_LOG_INFO, "Autodetected the input mode\n");
  1106. }
  1107. if (ctx->raw_format == (BMDPixelFormat)0)
  1108. ctx->raw_format = bmdFormat8BitYUV;
  1109. if (ff_decklink_set_format(avctx, DIRECTION_IN) < 0) {
  1110. av_log(avctx, AV_LOG_ERROR, "Could not set format code %s for %s\n",
  1111. cctx->format_code ? cctx->format_code : "(unset)", avctx->url);
  1112. ret = AVERROR(EIO);
  1113. goto error;
  1114. }
  1115. #if !CONFIG_LIBZVBI
  1116. if (ctx->teletext_lines && ctx->bmd_mode == bmdModePAL) {
  1117. av_log(avctx, AV_LOG_ERROR, "Libzvbi support is needed for capturing SD PAL teletext, please recompile FFmpeg.\n");
  1118. ret = AVERROR(ENOSYS);
  1119. goto error;
  1120. }
  1121. #endif
  1122. /* Setup streams. */
  1123. st = avformat_new_stream(avctx, NULL);
  1124. if (!st) {
  1125. av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
  1126. ret = AVERROR(ENOMEM);
  1127. goto error;
  1128. }
  1129. st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
  1130. st->codecpar->codec_id = cctx->audio_depth == 32 ? AV_CODEC_ID_PCM_S32LE : AV_CODEC_ID_PCM_S16LE;
  1131. st->codecpar->sample_rate = bmdAudioSampleRate48kHz;
  1132. st->codecpar->ch_layout.nb_channels = cctx->audio_channels;
  1133. avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
  1134. ctx->audio_st=st;
  1135. st = avformat_new_stream(avctx, NULL);
  1136. if (!st) {
  1137. av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
  1138. ret = AVERROR(ENOMEM);
  1139. goto error;
  1140. }
  1141. st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
  1142. st->codecpar->width = ctx->bmd_width;
  1143. st->codecpar->height = ctx->bmd_height;
  1144. st->time_base.den = ctx->bmd_tb_den;
  1145. st->time_base.num = ctx->bmd_tb_num;
  1146. st->r_frame_rate = av_make_q(st->time_base.den, st->time_base.num);
  1147. switch(ctx->raw_format) {
  1148. case bmdFormat8BitYUV:
  1149. st->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
  1150. st->codecpar->format = AV_PIX_FMT_UYVY422;
  1151. st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 16, st->time_base.den, st->time_base.num);
  1152. break;
  1153. case bmdFormat10BitYUV:
  1154. st->codecpar->codec_id = AV_CODEC_ID_V210;
  1155. st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 64, st->time_base.den, st->time_base.num * 3);
  1156. break;
  1157. case bmdFormat8BitARGB:
  1158. st->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
  1159. st->codecpar->format = AV_PIX_FMT_0RGB;
  1160. st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 32, st->time_base.den, st->time_base.num);
  1161. break;
  1162. case bmdFormat8BitBGRA:
  1163. st->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
  1164. st->codecpar->format = AV_PIX_FMT_BGR0;
  1165. st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 32, st->time_base.den, st->time_base.num);
  1166. break;
  1167. case bmdFormat10BitRGB:
  1168. st->codecpar->codec_id = AV_CODEC_ID_R210;
  1169. st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 30, st->time_base.den, st->time_base.num);
  1170. break;
  1171. default:
  1172. char fourcc_str[AV_FOURCC_MAX_STRING_SIZE] = {0};
  1173. av_fourcc_make_string(fourcc_str, ctx->raw_format);
  1174. av_log(avctx, AV_LOG_ERROR, "Raw Format %s not supported\n", fourcc_str);
  1175. ret = AVERROR(EINVAL);
  1176. goto error;
  1177. }
  1178. switch (ctx->bmd_field_dominance) {
  1179. case bmdUpperFieldFirst:
  1180. st->codecpar->field_order = AV_FIELD_TT;
  1181. break;
  1182. case bmdLowerFieldFirst:
  1183. st->codecpar->field_order = AV_FIELD_BB;
  1184. break;
  1185. case bmdProgressiveFrame:
  1186. case bmdProgressiveSegmentedFrame:
  1187. st->codecpar->field_order = AV_FIELD_PROGRESSIVE;
  1188. break;
  1189. }
  1190. avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
  1191. ctx->video_st=st;
  1192. if (ctx->enable_klv) {
  1193. st = avformat_new_stream(avctx, NULL);
  1194. if (!st) {
  1195. ret = AVERROR(ENOMEM);
  1196. goto error;
  1197. }
  1198. st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
  1199. st->time_base.den = ctx->bmd_tb_den;
  1200. st->time_base.num = ctx->bmd_tb_num;
  1201. st->codecpar->codec_id = AV_CODEC_ID_SMPTE_KLV;
  1202. avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
  1203. ctx->klv_st = st;
  1204. }
  1205. if (ctx->teletext_lines) {
  1206. st = avformat_new_stream(avctx, NULL);
  1207. if (!st) {
  1208. av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
  1209. ret = AVERROR(ENOMEM);
  1210. goto error;
  1211. }
  1212. st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1213. st->time_base.den = ctx->bmd_tb_den;
  1214. st->time_base.num = ctx->bmd_tb_num;
  1215. st->codecpar->codec_id = AV_CODEC_ID_DVB_TELETEXT;
  1216. avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
  1217. ctx->teletext_st = st;
  1218. }
  1219. av_log(avctx, AV_LOG_VERBOSE, "Using %d input audio channels\n", ctx->audio_st->codecpar->ch_layout.nb_channels);
  1220. result = ctx->dli->EnableAudioInput(bmdAudioSampleRate48kHz, cctx->audio_depth == 32 ? bmdAudioSampleType32bitInteger : bmdAudioSampleType16bitInteger, ctx->audio_st->codecpar->ch_layout.nb_channels);
  1221. if (result != S_OK) {
  1222. av_log(avctx, AV_LOG_ERROR, "Cannot enable audio input\n");
  1223. ret = AVERROR(EIO);
  1224. goto error;
  1225. }
  1226. result = ctx->dli->EnableVideoInput(ctx->bmd_mode,
  1227. ctx->raw_format,
  1228. bmdVideoInputFlagDefault);
  1229. if (result != S_OK) {
  1230. av_log(avctx, AV_LOG_ERROR, "Cannot enable video input\n");
  1231. ret = AVERROR(EIO);
  1232. goto error;
  1233. }
  1234. avpacket_queue_init (avctx, &ctx->queue);
  1235. if (ctx->dli->StartStreams() != S_OK) {
  1236. av_log(avctx, AV_LOG_ERROR, "Cannot start input stream\n");
  1237. ret = AVERROR(EIO);
  1238. goto error;
  1239. }
  1240. return 0;
  1241. error:
  1242. ff_decklink_cleanup(avctx);
  1243. return ret;
  1244. }
  1245. int ff_decklink_read_packet(AVFormatContext *avctx, AVPacket *pkt)
  1246. {
  1247. struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
  1248. struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
  1249. avpacket_queue_get(&ctx->queue, pkt, 1);
  1250. if (ctx->tc_format && !(av_dict_get(ctx->video_st->metadata, "timecode", NULL, 0))) {
  1251. size_t size;
  1252. const uint8_t *side_metadata = av_packet_get_side_data(pkt, AV_PKT_DATA_STRINGS_METADATA, &size);
  1253. if (side_metadata) {
  1254. if (av_packet_unpack_dictionary(side_metadata, size, &ctx->video_st->metadata) < 0)
  1255. av_log(avctx, AV_LOG_ERROR, "Unable to set timecode\n");
  1256. }
  1257. }
  1258. return 0;
  1259. }
  1260. int ff_decklink_list_input_devices(AVFormatContext *avctx, struct AVDeviceInfoList *device_list)
  1261. {
  1262. return ff_decklink_list_devices(avctx, device_list, 1, 0);
  1263. }
  1264. } /* extern "C" */