decklink_dec.cpp 44 KB

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