decklink_dec.cpp 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370
  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 handle_klv(AVFormatContext *avctx, decklink_ctx *ctx, IDeckLinkVideoInputFrame *videoFrame, int64_t pts)
  414. {
  415. const uint8_t KLV_DID = 0x44;
  416. const uint8_t KLV_IN_VANC_SDID = 0x04;
  417. struct KLVPacket
  418. {
  419. uint16_t sequence_counter;
  420. std::vector<uint8_t> data;
  421. };
  422. size_t total_size = 0;
  423. std::vector<std::vector<KLVPacket>> klv_packets(256);
  424. IDeckLinkVideoFrameAncillaryPackets *packets = nullptr;
  425. if (videoFrame->QueryInterface(IID_IDeckLinkVideoFrameAncillaryPackets, (void**)&packets) != S_OK)
  426. return;
  427. IDeckLinkAncillaryPacketIterator *it = nullptr;
  428. if (packets->GetPacketIterator(&it) != S_OK) {
  429. packets->Release();
  430. return;
  431. }
  432. IDeckLinkAncillaryPacket *packet = nullptr;
  433. while (it->Next(&packet) == S_OK) {
  434. uint8_t *data = nullptr;
  435. uint32_t size = 0;
  436. if (packet->GetDID() == KLV_DID && packet->GetSDID() == KLV_IN_VANC_SDID) {
  437. av_log(avctx, AV_LOG_DEBUG, "Found KLV VANC packet on line: %d\n", packet->GetLineNumber());
  438. if (packet->GetBytes(bmdAncillaryPacketFormatUInt8, (const void**) &data, &size) == S_OK) {
  439. // MID and PSC
  440. if (size > 3) {
  441. uint8_t mid = data[0];
  442. uint16_t psc = data[1] << 8 | data[2];
  443. av_log(avctx, AV_LOG_DEBUG, "KLV with MID: %d and PSC: %d\n", mid, psc);
  444. auto& list = klv_packets[mid];
  445. uint16_t expected_psc = list.size() + 1;
  446. if (psc == expected_psc) {
  447. uint32_t data_len = size - 3;
  448. total_size += data_len;
  449. KLVPacket packet{ psc };
  450. packet.data.resize(data_len);
  451. memcpy(packet.data.data(), data + 3, data_len);
  452. list.push_back(std::move(packet));
  453. } else {
  454. av_log(avctx, AV_LOG_WARNING, "Out of order PSC: %d for MID: %d\n", psc, mid);
  455. if (!list.empty()) {
  456. for (auto& klv : list)
  457. total_size -= klv.data.size();
  458. list.clear();
  459. }
  460. }
  461. }
  462. }
  463. }
  464. packet->Release();
  465. }
  466. it->Release();
  467. packets->Release();
  468. if (total_size > 0) {
  469. std::vector<uint8_t> klv;
  470. klv.reserve(total_size);
  471. for (size_t i = 0; i < klv_packets.size(); ++i) {
  472. auto& list = klv_packets[i];
  473. if (list.empty())
  474. continue;
  475. av_log(avctx, AV_LOG_DEBUG, "Joining MID: %d\n", (int)i);
  476. for (auto& packet : list)
  477. klv.insert(klv.end(), packet.data.begin(), packet.data.end());
  478. }
  479. AVPacket klv_packet = { 0 };
  480. klv_packet.pts = pts;
  481. klv_packet.dts = pts;
  482. klv_packet.flags |= AV_PKT_FLAG_KEY;
  483. klv_packet.stream_index = ctx->klv_st->index;
  484. klv_packet.data = klv.data();
  485. klv_packet.size = klv.size();
  486. if (ff_decklink_packet_queue_put(&ctx->queue, &klv_packet) < 0) {
  487. ++ctx->dropped;
  488. }
  489. }
  490. }
  491. class decklink_input_callback : public IDeckLinkInputCallback
  492. {
  493. public:
  494. explicit decklink_input_callback(AVFormatContext *_avctx);
  495. ~decklink_input_callback();
  496. virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv) { return E_NOINTERFACE; }
  497. virtual ULONG STDMETHODCALLTYPE AddRef(void);
  498. virtual ULONG STDMETHODCALLTYPE Release(void);
  499. virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents, IDeckLinkDisplayMode*, BMDDetectedVideoInputFormatFlags);
  500. virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame*, IDeckLinkAudioInputPacket*);
  501. private:
  502. std::atomic<int> _refs;
  503. AVFormatContext *avctx;
  504. decklink_ctx *ctx;
  505. int no_video;
  506. int64_t initial_video_pts;
  507. int64_t initial_audio_pts;
  508. IDeckLinkVideoInputFrame* last_video_frame;
  509. };
  510. decklink_input_callback::decklink_input_callback(AVFormatContext *_avctx) : _refs(1)
  511. {
  512. avctx = _avctx;
  513. decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
  514. ctx = (struct decklink_ctx *)cctx->ctx;
  515. no_video = 0;
  516. initial_audio_pts = initial_video_pts = AV_NOPTS_VALUE;
  517. last_video_frame = nullptr;
  518. }
  519. decklink_input_callback::~decklink_input_callback()
  520. {
  521. if (last_video_frame)
  522. last_video_frame->Release();
  523. }
  524. ULONG decklink_input_callback::AddRef(void)
  525. {
  526. return ++_refs;
  527. }
  528. ULONG decklink_input_callback::Release(void)
  529. {
  530. int ret = --_refs;
  531. if (!ret)
  532. delete this;
  533. return ret;
  534. }
  535. static int64_t get_pkt_pts(IDeckLinkVideoInputFrame *videoFrame,
  536. IDeckLinkAudioInputPacket *audioFrame,
  537. int64_t wallclock,
  538. int64_t abs_wallclock,
  539. DecklinkPtsSource pts_src,
  540. AVRational time_base, int64_t *initial_pts,
  541. int copyts)
  542. {
  543. int64_t pts = AV_NOPTS_VALUE;
  544. BMDTimeValue bmd_pts;
  545. BMDTimeValue bmd_duration;
  546. HRESULT res = E_INVALIDARG;
  547. switch (pts_src) {
  548. case PTS_SRC_AUDIO:
  549. if (audioFrame)
  550. res = audioFrame->GetPacketTime(&bmd_pts, time_base.den);
  551. break;
  552. case PTS_SRC_VIDEO:
  553. if (videoFrame)
  554. res = videoFrame->GetStreamTime(&bmd_pts, &bmd_duration, time_base.den);
  555. break;
  556. case PTS_SRC_REFERENCE:
  557. if (videoFrame)
  558. res = videoFrame->GetHardwareReferenceTimestamp(time_base.den, &bmd_pts, &bmd_duration);
  559. break;
  560. case PTS_SRC_WALLCLOCK:
  561. /* fall through */
  562. case PTS_SRC_ABS_WALLCLOCK:
  563. {
  564. /* MSVC does not support compound literals like AV_TIME_BASE_Q
  565. * in C++ code (compiler error C4576) */
  566. AVRational timebase;
  567. timebase.num = 1;
  568. timebase.den = AV_TIME_BASE;
  569. if (pts_src == PTS_SRC_WALLCLOCK)
  570. pts = av_rescale_q(wallclock, timebase, time_base);
  571. else
  572. pts = av_rescale_q(abs_wallclock, timebase, time_base);
  573. break;
  574. }
  575. }
  576. if (res == S_OK)
  577. pts = bmd_pts / time_base.num;
  578. if (!copyts) {
  579. if (pts != AV_NOPTS_VALUE && *initial_pts == AV_NOPTS_VALUE)
  580. *initial_pts = pts;
  581. if (*initial_pts != AV_NOPTS_VALUE)
  582. pts -= *initial_pts;
  583. }
  584. return pts;
  585. }
  586. static int get_bmd_timecode(AVFormatContext *avctx, AVTimecode *tc, AVRational frame_rate, BMDTimecodeFormat tc_format, IDeckLinkVideoInputFrame *videoFrame)
  587. {
  588. IDeckLinkTimecode *timecode;
  589. int ret = AVERROR(ENOENT);
  590. #if BLACKMAGIC_DECKLINK_API_VERSION >= 0x0b000000
  591. int hfr = (tc_format == bmdTimecodeRP188HighFrameRate);
  592. #else
  593. int hfr = 0;
  594. #endif
  595. if (videoFrame->GetTimecode(tc_format, &timecode) == S_OK) {
  596. uint8_t hh, mm, ss, ff;
  597. if (timecode->GetComponents(&hh, &mm, &ss, &ff) == S_OK) {
  598. int flags = (timecode->GetFlags() & bmdTimecodeIsDropFrame) ? AV_TIMECODE_FLAG_DROPFRAME : 0;
  599. if (!hfr && av_cmp_q(frame_rate, av_make_q(30, 1)) == 1)
  600. ff = ff << 1 | !!(timecode->GetFlags() & bmdTimecodeFieldMark);
  601. ret = av_timecode_init_from_components(tc, frame_rate, flags, hh, mm, ss, ff, avctx);
  602. }
  603. timecode->Release();
  604. }
  605. return ret;
  606. }
  607. static int get_frame_timecode(AVFormatContext *avctx, decklink_ctx *ctx, AVTimecode *tc, IDeckLinkVideoInputFrame *videoFrame)
  608. {
  609. AVRational frame_rate = ctx->video_st->r_frame_rate;
  610. int ret;
  611. /* 50/60 fps content has alternating VITC1 and VITC2 timecode (see SMPTE ST
  612. * 12-2, section 7), so the native ordering of RP188Any (HFR, VITC1, LTC,
  613. * VITC2) would not work because LTC might not contain the field flag.
  614. * Therefore we query the types manually. */
  615. if (ctx->tc_format == bmdTimecodeRP188Any && av_cmp_q(frame_rate, av_make_q(30, 1)) == 1) {
  616. #if BLACKMAGIC_DECKLINK_API_VERSION >= 0x0b000000
  617. ret = get_bmd_timecode(avctx, tc, frame_rate, bmdTimecodeRP188HighFrameRate, videoFrame);
  618. if (ret == AVERROR(ENOENT))
  619. #endif
  620. ret = get_bmd_timecode(avctx, tc, frame_rate, bmdTimecodeRP188VITC1, videoFrame);
  621. if (ret == AVERROR(ENOENT))
  622. ret = get_bmd_timecode(avctx, tc, frame_rate, bmdTimecodeRP188VITC2, videoFrame);
  623. if (ret == AVERROR(ENOENT))
  624. ret = get_bmd_timecode(avctx, tc, frame_rate, bmdTimecodeRP188LTC, videoFrame);
  625. } else {
  626. ret = get_bmd_timecode(avctx, tc, frame_rate, ctx->tc_format, videoFrame);
  627. }
  628. return ret;
  629. }
  630. HRESULT decklink_input_callback::VideoInputFrameArrived(
  631. IDeckLinkVideoInputFrame *videoFrame, IDeckLinkAudioInputPacket *audioFrame)
  632. {
  633. void *frameBytes;
  634. void *audioFrameBytes;
  635. BMDTimeValue frameTime;
  636. BMDTimeValue frameDuration;
  637. int64_t wallclock = 0, abs_wallclock = 0;
  638. int64_t video_pkt_pts, audio_pkt_pts;
  639. struct decklink_cctx *cctx = (struct decklink_cctx *) avctx->priv_data;
  640. if (ctx->autodetect) {
  641. if (videoFrame && !(videoFrame->GetFlags() & bmdFrameHasNoInputSource) &&
  642. ctx->bmd_mode == bmdModeUnknown)
  643. {
  644. ctx->bmd_mode = AUTODETECT_DEFAULT_MODE;
  645. }
  646. return S_OK;
  647. }
  648. // Drop the frames till system's timestamp aligns with the configured value.
  649. if (0 == ctx->frameCount && cctx->timestamp_align) {
  650. AVRational remainder = av_make_q(av_gettime() % cctx->timestamp_align, 1000000);
  651. AVRational frame_duration = av_inv_q(ctx->video_st->r_frame_rate);
  652. if (av_cmp_q(remainder, frame_duration) > 0) {
  653. ++ctx->dropped;
  654. return S_OK;
  655. }
  656. }
  657. ctx->frameCount++;
  658. if (ctx->audio_pts_source == PTS_SRC_WALLCLOCK || ctx->video_pts_source == PTS_SRC_WALLCLOCK)
  659. wallclock = av_gettime_relative();
  660. if (ctx->audio_pts_source == PTS_SRC_ABS_WALLCLOCK || ctx->video_pts_source == PTS_SRC_ABS_WALLCLOCK)
  661. abs_wallclock = av_gettime();
  662. video_pkt_pts = get_pkt_pts(videoFrame, audioFrame, wallclock, abs_wallclock, ctx->video_pts_source, ctx->video_st->time_base, &initial_video_pts, cctx->copyts);
  663. audio_pkt_pts = get_pkt_pts(videoFrame, audioFrame, wallclock, abs_wallclock, ctx->audio_pts_source, ctx->audio_st->time_base, &initial_audio_pts, cctx->copyts);
  664. // Handle Video Frame
  665. if (videoFrame) {
  666. AVPacket pkt = { 0 };
  667. if (ctx->frameCount % 25 == 0) {
  668. unsigned long long qsize = ff_decklink_packet_queue_size(&ctx->queue);
  669. av_log(avctx, AV_LOG_DEBUG,
  670. "Frame received (#%lu) - Valid (%liB) - QSize %fMB\n",
  671. ctx->frameCount,
  672. videoFrame->GetRowBytes() * videoFrame->GetHeight(),
  673. (double)qsize / 1024 / 1024);
  674. }
  675. videoFrame->GetBytes(&frameBytes);
  676. videoFrame->GetStreamTime(&frameTime, &frameDuration,
  677. ctx->video_st->time_base.den);
  678. if (videoFrame->GetFlags() & bmdFrameHasNoInputSource) {
  679. if (ctx->signal_loss_action == SIGNAL_LOSS_BARS && videoFrame->GetPixelFormat() == bmdFormat8BitYUV) {
  680. unsigned bars[8] = {
  681. 0xEA80EA80, 0xD292D210, 0xA910A9A5, 0x90229035,
  682. 0x6ADD6ACA, 0x51EF515A, 0x286D28EF, 0x10801080 };
  683. int width = videoFrame->GetWidth();
  684. int height = videoFrame->GetHeight();
  685. unsigned *p = (unsigned *)frameBytes;
  686. for (int y = 0; y < height; y++) {
  687. for (int x = 0; x < width; x += 2)
  688. *p++ = bars[(x * 8) / width];
  689. }
  690. } else if (ctx->signal_loss_action == SIGNAL_LOSS_REPEAT && last_video_frame) {
  691. videoFrame = last_video_frame;
  692. videoFrame->GetBytes(&frameBytes);
  693. }
  694. if (!no_video) {
  695. av_log(avctx, AV_LOG_WARNING, "Frame received (#%lu) - No input signal detected "
  696. "- Frames dropped %u\n", ctx->frameCount, ++ctx->dropped);
  697. }
  698. no_video = 1;
  699. } else {
  700. if (ctx->signal_loss_action == SIGNAL_LOSS_REPEAT) {
  701. if (last_video_frame)
  702. last_video_frame->Release();
  703. last_video_frame = videoFrame;
  704. last_video_frame->AddRef();
  705. }
  706. if (no_video) {
  707. av_log(avctx, AV_LOG_WARNING, "Frame received (#%lu) - Input returned "
  708. "- Frames dropped %u\n", ctx->frameCount, ++ctx->dropped);
  709. }
  710. no_video = 0;
  711. // Handle Timecode (if requested)
  712. if (ctx->tc_format) {
  713. AVTimecode tcr;
  714. if (get_frame_timecode(avctx, ctx, &tcr, videoFrame) >= 0) {
  715. char tcstr[AV_TIMECODE_STR_SIZE];
  716. const char *tc = av_timecode_make_string(&tcr, tcstr, 0);
  717. if (tc) {
  718. AVDictionary* metadata_dict = NULL;
  719. uint8_t* packed_metadata;
  720. if (av_cmp_q(ctx->video_st->r_frame_rate, av_make_q(60, 1)) < 1) {
  721. uint32_t tc_data = av_timecode_get_smpte_from_framenum(&tcr, 0);
  722. int size = sizeof(uint32_t) * 4;
  723. uint32_t *sd = (uint32_t *)av_packet_new_side_data(&pkt, AV_PKT_DATA_S12M_TIMECODE, size);
  724. if (sd) {
  725. *sd = 1; // one TC
  726. *(sd + 1) = tc_data; // TC
  727. }
  728. }
  729. if (av_dict_set(&metadata_dict, "timecode", tc, 0) >= 0) {
  730. size_t metadata_len;
  731. packed_metadata = av_packet_pack_dictionary(metadata_dict, &metadata_len);
  732. av_dict_free(&metadata_dict);
  733. if (packed_metadata) {
  734. if (av_packet_add_side_data(&pkt, AV_PKT_DATA_STRINGS_METADATA, packed_metadata, metadata_len) < 0)
  735. av_freep(&packed_metadata);
  736. else if (!ctx->tc_seen)
  737. ctx->tc_seen = ctx->frameCount;
  738. }
  739. }
  740. }
  741. } else {
  742. av_log(avctx, AV_LOG_DEBUG, "Unable to find timecode.\n");
  743. }
  744. }
  745. }
  746. if (ctx->tc_format && cctx->wait_for_tc && !ctx->tc_seen) {
  747. av_log(avctx, AV_LOG_WARNING, "No TC detected yet. wait_for_tc set. Dropping. \n");
  748. av_log(avctx, AV_LOG_WARNING, "Frame received (#%lu) - "
  749. "- Frames dropped %u\n", ctx->frameCount, ++ctx->dropped);
  750. return S_OK;
  751. }
  752. pkt.pts = video_pkt_pts;
  753. pkt.dts = pkt.pts;
  754. pkt.duration = frameDuration;
  755. //To be made sure it still applies
  756. pkt.flags |= AV_PKT_FLAG_KEY;
  757. pkt.stream_index = ctx->video_st->index;
  758. pkt.data = (uint8_t *)frameBytes;
  759. pkt.size = videoFrame->GetRowBytes() *
  760. videoFrame->GetHeight();
  761. //fprintf(stderr,"Video Frame size %d ts %d\n", pkt.size, pkt.pts);
  762. if (!no_video) {
  763. IDeckLinkVideoFrameAncillary *vanc;
  764. AVPacket txt_pkt = { 0 };
  765. uint8_t txt_buf0[3531]; // 35 * 46 bytes decoded teletext lines + 1 byte data_identifier + 1920 bytes OP47 decode buffer
  766. uint8_t *txt_buf = txt_buf0;
  767. if (ctx->enable_klv) {
  768. handle_klv(avctx, ctx, videoFrame, pkt.pts);
  769. }
  770. if (videoFrame->GetAncillaryData(&vanc) == S_OK) {
  771. int i;
  772. BMDPixelFormat vanc_format = vanc->GetPixelFormat();
  773. txt_buf[0] = 0x10; // data_identifier - EBU_data
  774. txt_buf++;
  775. #if CONFIG_LIBZVBI
  776. if (ctx->bmd_mode == bmdModePAL && ctx->teletext_lines &&
  777. (vanc_format == bmdFormat8BitYUV || vanc_format == bmdFormat10BitYUV)) {
  778. int64_t line_mask = 1;
  779. av_assert0(videoFrame->GetWidth() == 720);
  780. for (i = 6; i < 336; i++, line_mask <<= 1) {
  781. uint8_t *buf;
  782. if ((ctx->teletext_lines & line_mask) && vanc->GetBufferForVerticalBlankingLine(i, (void**)&buf) == S_OK) {
  783. if (vanc_format == bmdFormat8BitYUV)
  784. txt_buf = teletext_data_unit_from_vbi_data(i, buf, txt_buf, VBI_PIXFMT_UYVY);
  785. else
  786. txt_buf = teletext_data_unit_from_vbi_data_10bit(i, buf, txt_buf);
  787. }
  788. if (i == 22)
  789. i = 317;
  790. }
  791. }
  792. #endif
  793. if (vanc_format == bmdFormat10BitYUV && videoFrame->GetWidth() <= MAX_WIDTH_VANC) {
  794. int idx = get_vanc_line_idx(ctx->bmd_mode);
  795. for (i = vanc_line_numbers[idx].vanc_start; i <= vanc_line_numbers[idx].vanc_end; i++) {
  796. uint8_t *buf;
  797. if (vanc->GetBufferForVerticalBlankingLine(i, (void**)&buf) == S_OK) {
  798. uint16_t vanc[MAX_WIDTH_VANC];
  799. size_t vanc_size = videoFrame->GetWidth();
  800. if (ctx->bmd_mode == bmdModeNTSC && videoFrame->GetWidth() * 2 <= MAX_WIDTH_VANC) {
  801. vanc_size = vanc_size * 2;
  802. unpack_v210(vanc, buf, videoFrame->GetWidth());
  803. } else {
  804. extract_luma_from_v210(vanc, buf, videoFrame->GetWidth());
  805. }
  806. txt_buf = get_metadata(avctx, vanc, vanc_size,
  807. txt_buf, sizeof(txt_buf0) - (txt_buf - txt_buf0), &pkt);
  808. }
  809. if (i == vanc_line_numbers[idx].field0_vanc_end)
  810. i = vanc_line_numbers[idx].field1_vanc_start - 1;
  811. }
  812. }
  813. vanc->Release();
  814. if (txt_buf - txt_buf0 > 1) {
  815. int stuffing_units = (4 - ((45 + txt_buf - txt_buf0) / 46) % 4) % 4;
  816. while (stuffing_units--) {
  817. memset(txt_buf, 0xff, 46);
  818. txt_buf[1] = 0x2c; // data_unit_length
  819. txt_buf += 46;
  820. }
  821. txt_pkt.pts = pkt.pts;
  822. txt_pkt.dts = pkt.dts;
  823. txt_pkt.stream_index = ctx->teletext_st->index;
  824. txt_pkt.data = txt_buf0;
  825. txt_pkt.size = txt_buf - txt_buf0;
  826. if (ff_decklink_packet_queue_put(&ctx->queue, &txt_pkt) < 0) {
  827. ++ctx->dropped;
  828. }
  829. }
  830. }
  831. }
  832. pkt.buf = av_buffer_create(pkt.data, pkt.size, decklink_object_free, videoFrame, 0);
  833. if (pkt.buf)
  834. videoFrame->AddRef();
  835. if (ff_decklink_packet_queue_put(&ctx->queue, &pkt) < 0) {
  836. ++ctx->dropped;
  837. }
  838. }
  839. // Handle Audio Frame
  840. if (audioFrame) {
  841. AVPacket pkt = { 0 };
  842. BMDTimeValue audio_pts;
  843. //hack among hacks
  844. pkt.size = audioFrame->GetSampleFrameCount() * ctx->audio_st->codecpar->ch_layout.nb_channels * (ctx->audio_depth / 8);
  845. audioFrame->GetBytes(&audioFrameBytes);
  846. audioFrame->GetPacketTime(&audio_pts, ctx->audio_st->time_base.den);
  847. pkt.pts = audio_pkt_pts;
  848. pkt.dts = pkt.pts;
  849. //fprintf(stderr,"Audio Frame size %d ts %d\n", pkt.size, pkt.pts);
  850. pkt.flags |= AV_PKT_FLAG_KEY;
  851. pkt.stream_index = ctx->audio_st->index;
  852. pkt.data = (uint8_t *)audioFrameBytes;
  853. if (ff_decklink_packet_queue_put(&ctx->queue, &pkt) < 0) {
  854. ++ctx->dropped;
  855. }
  856. }
  857. return S_OK;
  858. }
  859. HRESULT decklink_input_callback::VideoInputFormatChanged(
  860. BMDVideoInputFormatChangedEvents events, IDeckLinkDisplayMode *mode,
  861. BMDDetectedVideoInputFormatFlags formatFlags)
  862. {
  863. struct decklink_cctx *cctx = (struct decklink_cctx *) avctx->priv_data;
  864. ctx->bmd_mode = mode->GetDisplayMode();
  865. // check the C context member to make sure we set both raw_format and bmd_mode with data from the same format change callback
  866. if (!cctx->raw_format)
  867. ctx->raw_format = (formatFlags & bmdDetectedVideoInputRGB444) ? bmdFormat8BitARGB : bmdFormat8BitYUV;
  868. return S_OK;
  869. }
  870. static int decklink_autodetect(struct decklink_cctx *cctx) {
  871. struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
  872. DECKLINK_BOOL autodetect_supported = false;
  873. int i;
  874. if (ctx->attr->GetFlag(BMDDeckLinkSupportsInputFormatDetection, &autodetect_supported) != S_OK)
  875. return -1;
  876. if (autodetect_supported == false)
  877. return -1;
  878. ctx->autodetect = 1;
  879. ctx->bmd_mode = bmdModeUnknown;
  880. if (ctx->dli->EnableVideoInput(AUTODETECT_DEFAULT_MODE,
  881. bmdFormat8BitYUV,
  882. bmdVideoInputEnableFormatDetection) != S_OK) {
  883. return -1;
  884. }
  885. if (ctx->dli->StartStreams() != S_OK) {
  886. return -1;
  887. }
  888. // 3 second timeout
  889. for (i = 0; i < 30; i++) {
  890. av_usleep(100000);
  891. /* Sometimes VideoInputFrameArrived is called without the
  892. * bmdFrameHasNoInputSource flag before VideoInputFormatChanged.
  893. * So don't break for bmd_mode == AUTODETECT_DEFAULT_MODE. */
  894. if (ctx->bmd_mode != bmdModeUnknown &&
  895. ctx->bmd_mode != AUTODETECT_DEFAULT_MODE)
  896. break;
  897. }
  898. ctx->dli->PauseStreams();
  899. ctx->dli->FlushStreams();
  900. ctx->autodetect = 0;
  901. if (ctx->bmd_mode != bmdModeUnknown) {
  902. cctx->format_code = (char *)av_mallocz(5);
  903. if (!cctx->format_code)
  904. return -1;
  905. AV_WB32(cctx->format_code, ctx->bmd_mode);
  906. return 0;
  907. } else {
  908. return -1;
  909. }
  910. }
  911. extern "C" {
  912. av_cold int ff_decklink_read_close(AVFormatContext *avctx)
  913. {
  914. struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
  915. struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
  916. if (ctx->dli) {
  917. ctx->dli->StopStreams();
  918. ctx->dli->DisableVideoInput();
  919. ctx->dli->DisableAudioInput();
  920. ctx->dli->SetCallback(nullptr);
  921. }
  922. ff_decklink_cleanup(avctx);
  923. ff_decklink_packet_queue_end(&ctx->queue);
  924. av_freep(&cctx->ctx);
  925. return 0;
  926. }
  927. av_cold int ff_decklink_read_header(AVFormatContext *avctx)
  928. {
  929. struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
  930. struct decklink_ctx *ctx;
  931. class decklink_allocator *allocator;
  932. class decklink_input_callback *input_callback;
  933. AVStream *st;
  934. HRESULT result;
  935. int ret;
  936. ctx = (struct decklink_ctx *) av_mallocz(sizeof(struct decklink_ctx));
  937. if (!ctx)
  938. return AVERROR(ENOMEM);
  939. ctx->list_devices = cctx->list_devices;
  940. ctx->list_formats = cctx->list_formats;
  941. ctx->enable_klv = cctx->enable_klv;
  942. ctx->teletext_lines = cctx->teletext_lines;
  943. ctx->preroll = cctx->preroll;
  944. ctx->duplex_mode = cctx->duplex_mode;
  945. if (cctx->tc_format > 0 && (unsigned int)cctx->tc_format < FF_ARRAY_ELEMS(decklink_timecode_format_map))
  946. ctx->tc_format = decklink_timecode_format_map[cctx->tc_format];
  947. if (cctx->video_input > 0 && (unsigned int)cctx->video_input < FF_ARRAY_ELEMS(decklink_video_connection_map))
  948. ctx->video_input = decklink_video_connection_map[cctx->video_input];
  949. if (cctx->audio_input > 0 && (unsigned int)cctx->audio_input < FF_ARRAY_ELEMS(decklink_audio_connection_map))
  950. ctx->audio_input = decklink_audio_connection_map[cctx->audio_input];
  951. ctx->audio_pts_source = cctx->audio_pts_source;
  952. ctx->video_pts_source = cctx->video_pts_source;
  953. ctx->draw_bars = cctx->draw_bars;
  954. ctx->signal_loss_action = cctx->signal_loss_action;
  955. if (!ctx->draw_bars && ctx->signal_loss_action == SIGNAL_LOSS_BARS) {
  956. ctx->signal_loss_action = SIGNAL_LOSS_NONE;
  957. av_log(avctx, AV_LOG_WARNING, "Setting signal_loss_action to none because draw_bars is false\n");
  958. }
  959. if (!ctx->draw_bars && ctx->signal_loss_action != SIGNAL_LOSS_NONE) {
  960. av_log(avctx, AV_LOG_ERROR, "options draw_bars and signal_loss_action are mutually exclusive\n");
  961. av_freep(&ctx);
  962. return AVERROR(EINVAL);
  963. }
  964. ctx->audio_depth = cctx->audio_depth;
  965. if (cctx->raw_format > 0 && (unsigned int)cctx->raw_format < FF_ARRAY_ELEMS(decklink_raw_format_map))
  966. ctx->raw_format = decklink_raw_format_map[cctx->raw_format];
  967. cctx->ctx = ctx;
  968. /* Check audio channel option for valid values: 2, 8 or 16 */
  969. switch (cctx->audio_channels) {
  970. case 2:
  971. case 8:
  972. case 16:
  973. break;
  974. default:
  975. av_log(avctx, AV_LOG_ERROR, "Value of channels option must be one of 2, 8 or 16\n");
  976. ret = AVERROR(EINVAL);
  977. goto error;
  978. }
  979. /* Check audio bit depth option for valid values: 16 or 32 */
  980. switch (cctx->audio_depth) {
  981. case 16:
  982. case 32:
  983. break;
  984. default:
  985. av_log(avctx, AV_LOG_ERROR, "Value for audio bit depth option must be either 16 or 32\n");
  986. ret = AVERROR(EINVAL);
  987. goto error;
  988. }
  989. /* List available devices. */
  990. if (ctx->list_devices) {
  991. ff_decklink_list_devices_legacy(avctx, 1, 0);
  992. ret = AVERROR_EXIT;
  993. goto error;
  994. }
  995. ret = ff_decklink_init_device(avctx, avctx->url);
  996. if (ret < 0)
  997. goto error;
  998. /* Get input device. */
  999. if (ctx->dl->QueryInterface(IID_IDeckLinkInput, (void **) &ctx->dli) != S_OK) {
  1000. av_log(avctx, AV_LOG_ERROR, "Could not open input device from '%s'\n",
  1001. avctx->url);
  1002. ret = AVERROR(EIO);
  1003. goto error;
  1004. }
  1005. if (ff_decklink_set_configs(avctx, DIRECTION_IN) < 0) {
  1006. av_log(avctx, AV_LOG_ERROR, "Could not set input configuration\n");
  1007. ret = AVERROR(EIO);
  1008. goto error;
  1009. }
  1010. /* List supported formats. */
  1011. if (ctx->list_formats) {
  1012. ff_decklink_list_formats(avctx, DIRECTION_IN);
  1013. ret = AVERROR_EXIT;
  1014. goto error;
  1015. }
  1016. input_callback = new decklink_input_callback(avctx);
  1017. ret = (ctx->dli->SetCallback(input_callback) == S_OK ? 0 : AVERROR_EXTERNAL);
  1018. input_callback->Release();
  1019. if (ret < 0) {
  1020. av_log(avctx, AV_LOG_ERROR, "Cannot set input callback\n");
  1021. goto error;
  1022. }
  1023. allocator = new decklink_allocator();
  1024. ret = (ctx->dli->SetVideoInputFrameMemoryAllocator(allocator) == S_OK ? 0 : AVERROR_EXTERNAL);
  1025. allocator->Release();
  1026. if (ret < 0) {
  1027. av_log(avctx, AV_LOG_ERROR, "Cannot set custom memory allocator\n");
  1028. goto error;
  1029. }
  1030. if (!cctx->format_code) {
  1031. if (decklink_autodetect(cctx) < 0) {
  1032. av_log(avctx, AV_LOG_ERROR, "Cannot Autodetect input stream or No signal\n");
  1033. ret = AVERROR(EIO);
  1034. goto error;
  1035. }
  1036. av_log(avctx, AV_LOG_INFO, "Autodetected the input mode\n");
  1037. }
  1038. if (ctx->raw_format == (BMDPixelFormat)0)
  1039. ctx->raw_format = bmdFormat8BitYUV;
  1040. if (ff_decklink_set_format(avctx, DIRECTION_IN) < 0) {
  1041. av_log(avctx, AV_LOG_ERROR, "Could not set format code %s for %s\n",
  1042. cctx->format_code ? cctx->format_code : "(unset)", avctx->url);
  1043. ret = AVERROR(EIO);
  1044. goto error;
  1045. }
  1046. #if !CONFIG_LIBZVBI
  1047. if (ctx->teletext_lines && ctx->bmd_mode == bmdModePAL) {
  1048. av_log(avctx, AV_LOG_ERROR, "Libzvbi support is needed for capturing SD PAL teletext, please recompile FFmpeg.\n");
  1049. ret = AVERROR(ENOSYS);
  1050. goto error;
  1051. }
  1052. #endif
  1053. /* Setup streams. */
  1054. st = avformat_new_stream(avctx, NULL);
  1055. if (!st) {
  1056. av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
  1057. ret = AVERROR(ENOMEM);
  1058. goto error;
  1059. }
  1060. st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
  1061. st->codecpar->codec_id = cctx->audio_depth == 32 ? AV_CODEC_ID_PCM_S32LE : AV_CODEC_ID_PCM_S16LE;
  1062. st->codecpar->sample_rate = bmdAudioSampleRate48kHz;
  1063. st->codecpar->ch_layout.nb_channels = cctx->audio_channels;
  1064. avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
  1065. ctx->audio_st=st;
  1066. st = avformat_new_stream(avctx, NULL);
  1067. if (!st) {
  1068. av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
  1069. ret = AVERROR(ENOMEM);
  1070. goto error;
  1071. }
  1072. st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
  1073. st->codecpar->width = ctx->bmd_width;
  1074. st->codecpar->height = ctx->bmd_height;
  1075. st->time_base.den = ctx->bmd_tb_den;
  1076. st->time_base.num = ctx->bmd_tb_num;
  1077. st->r_frame_rate = av_make_q(st->time_base.den, st->time_base.num);
  1078. switch(ctx->raw_format) {
  1079. case bmdFormat8BitYUV:
  1080. st->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
  1081. st->codecpar->format = AV_PIX_FMT_UYVY422;
  1082. st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 16, st->time_base.den, st->time_base.num);
  1083. break;
  1084. case bmdFormat10BitYUV:
  1085. st->codecpar->codec_id = AV_CODEC_ID_V210;
  1086. st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 64, st->time_base.den, st->time_base.num * 3);
  1087. break;
  1088. case bmdFormat8BitARGB:
  1089. st->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
  1090. st->codecpar->format = AV_PIX_FMT_0RGB;
  1091. st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 32, st->time_base.den, st->time_base.num);
  1092. break;
  1093. case bmdFormat8BitBGRA:
  1094. st->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
  1095. st->codecpar->format = AV_PIX_FMT_BGR0;
  1096. st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 32, st->time_base.den, st->time_base.num);
  1097. break;
  1098. case bmdFormat10BitRGB:
  1099. st->codecpar->codec_id = AV_CODEC_ID_R210;
  1100. st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 30, st->time_base.den, st->time_base.num);
  1101. break;
  1102. default:
  1103. char fourcc_str[AV_FOURCC_MAX_STRING_SIZE] = {0};
  1104. av_fourcc_make_string(fourcc_str, ctx->raw_format);
  1105. av_log(avctx, AV_LOG_ERROR, "Raw Format %s not supported\n", fourcc_str);
  1106. ret = AVERROR(EINVAL);
  1107. goto error;
  1108. }
  1109. switch (ctx->bmd_field_dominance) {
  1110. case bmdUpperFieldFirst:
  1111. st->codecpar->field_order = AV_FIELD_TT;
  1112. break;
  1113. case bmdLowerFieldFirst:
  1114. st->codecpar->field_order = AV_FIELD_BB;
  1115. break;
  1116. case bmdProgressiveFrame:
  1117. case bmdProgressiveSegmentedFrame:
  1118. st->codecpar->field_order = AV_FIELD_PROGRESSIVE;
  1119. break;
  1120. }
  1121. avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
  1122. ctx->video_st=st;
  1123. if (ctx->enable_klv) {
  1124. st = avformat_new_stream(avctx, NULL);
  1125. if (!st) {
  1126. ret = AVERROR(ENOMEM);
  1127. goto error;
  1128. }
  1129. st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
  1130. st->time_base.den = ctx->bmd_tb_den;
  1131. st->time_base.num = ctx->bmd_tb_num;
  1132. st->codecpar->codec_id = AV_CODEC_ID_SMPTE_KLV;
  1133. avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
  1134. ctx->klv_st = st;
  1135. }
  1136. if (ctx->teletext_lines) {
  1137. st = avformat_new_stream(avctx, NULL);
  1138. if (!st) {
  1139. av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
  1140. ret = AVERROR(ENOMEM);
  1141. goto error;
  1142. }
  1143. st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1144. st->time_base.den = ctx->bmd_tb_den;
  1145. st->time_base.num = ctx->bmd_tb_num;
  1146. st->codecpar->codec_id = AV_CODEC_ID_DVB_TELETEXT;
  1147. avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
  1148. ctx->teletext_st = st;
  1149. }
  1150. av_log(avctx, AV_LOG_VERBOSE, "Using %d input audio channels\n", ctx->audio_st->codecpar->ch_layout.nb_channels);
  1151. result = ctx->dli->EnableAudioInput(bmdAudioSampleRate48kHz, cctx->audio_depth == 32 ? bmdAudioSampleType32bitInteger : bmdAudioSampleType16bitInteger, ctx->audio_st->codecpar->ch_layout.nb_channels);
  1152. if (result != S_OK) {
  1153. av_log(avctx, AV_LOG_ERROR, "Cannot enable audio input\n");
  1154. ret = AVERROR(EIO);
  1155. goto error;
  1156. }
  1157. result = ctx->dli->EnableVideoInput(ctx->bmd_mode,
  1158. ctx->raw_format,
  1159. bmdVideoInputFlagDefault);
  1160. if (result != S_OK) {
  1161. av_log(avctx, AV_LOG_ERROR, "Cannot enable video input\n");
  1162. ret = AVERROR(EIO);
  1163. goto error;
  1164. }
  1165. ff_decklink_packet_queue_init(avctx, &ctx->queue, cctx->queue_size);
  1166. if (ctx->dli->StartStreams() != S_OK) {
  1167. av_log(avctx, AV_LOG_ERROR, "Cannot start input stream\n");
  1168. ret = AVERROR(EIO);
  1169. goto error;
  1170. }
  1171. return 0;
  1172. error:
  1173. ff_decklink_cleanup(avctx);
  1174. av_freep(&cctx->ctx);
  1175. return ret;
  1176. }
  1177. int ff_decklink_read_packet(AVFormatContext *avctx, AVPacket *pkt)
  1178. {
  1179. struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
  1180. struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
  1181. ff_decklink_packet_queue_get(&ctx->queue, pkt, 1);
  1182. if (ctx->tc_format && !(av_dict_get(ctx->video_st->metadata, "timecode", NULL, 0))) {
  1183. size_t size;
  1184. const uint8_t *side_metadata = av_packet_get_side_data(pkt, AV_PKT_DATA_STRINGS_METADATA, &size);
  1185. if (side_metadata) {
  1186. if (av_packet_unpack_dictionary(side_metadata, size, &ctx->video_st->metadata) < 0)
  1187. av_log(avctx, AV_LOG_ERROR, "Unable to set timecode\n");
  1188. }
  1189. }
  1190. return 0;
  1191. }
  1192. int ff_decklink_list_input_devices(AVFormatContext *avctx, struct AVDeviceInfoList *device_list)
  1193. {
  1194. return ff_decklink_list_devices(avctx, device_list, 1, 0);
  1195. }
  1196. } /* extern "C" */