decklink_dec.cpp 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283
  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. }
  692. }
  693. }
  694. } else {
  695. av_log(avctx, AV_LOG_DEBUG, "Unable to find timecode.\n");
  696. }
  697. }
  698. }
  699. pkt.pts = get_pkt_pts(videoFrame, audioFrame, wallclock, abs_wallclock, ctx->video_pts_source, ctx->video_st->time_base, &initial_video_pts, cctx->copyts);
  700. pkt.dts = pkt.pts;
  701. pkt.duration = frameDuration;
  702. //To be made sure it still applies
  703. pkt.flags |= AV_PKT_FLAG_KEY;
  704. pkt.stream_index = ctx->video_st->index;
  705. pkt.data = (uint8_t *)frameBytes;
  706. pkt.size = videoFrame->GetRowBytes() *
  707. videoFrame->GetHeight();
  708. //fprintf(stderr,"Video Frame size %d ts %d\n", pkt.size, pkt.pts);
  709. if (!no_video) {
  710. IDeckLinkVideoFrameAncillary *vanc;
  711. AVPacket txt_pkt;
  712. uint8_t txt_buf0[3531]; // 35 * 46 bytes decoded teletext lines + 1 byte data_identifier + 1920 bytes OP47 decode buffer
  713. uint8_t *txt_buf = txt_buf0;
  714. if (videoFrame->GetAncillaryData(&vanc) == S_OK) {
  715. int i;
  716. int64_t line_mask = 1;
  717. BMDPixelFormat vanc_format = vanc->GetPixelFormat();
  718. txt_buf[0] = 0x10; // data_identifier - EBU_data
  719. txt_buf++;
  720. #if CONFIG_LIBZVBI
  721. if (ctx->bmd_mode == bmdModePAL && ctx->teletext_lines &&
  722. (vanc_format == bmdFormat8BitYUV || vanc_format == bmdFormat10BitYUV)) {
  723. av_assert0(videoFrame->GetWidth() == 720);
  724. for (i = 6; i < 336; i++, line_mask <<= 1) {
  725. uint8_t *buf;
  726. if ((ctx->teletext_lines & line_mask) && vanc->GetBufferForVerticalBlankingLine(i, (void**)&buf) == S_OK) {
  727. if (vanc_format == bmdFormat8BitYUV)
  728. txt_buf = teletext_data_unit_from_vbi_data(i, buf, txt_buf, VBI_PIXFMT_UYVY);
  729. else
  730. txt_buf = teletext_data_unit_from_vbi_data_10bit(i, buf, txt_buf);
  731. }
  732. if (i == 22)
  733. i = 317;
  734. }
  735. }
  736. #endif
  737. if (vanc_format == bmdFormat10BitYUV && videoFrame->GetWidth() <= MAX_WIDTH_VANC) {
  738. int idx = get_vanc_line_idx(ctx->bmd_mode);
  739. for (i = vanc_line_numbers[idx].vanc_start; i <= vanc_line_numbers[idx].vanc_end; i++) {
  740. uint8_t *buf;
  741. if (vanc->GetBufferForVerticalBlankingLine(i, (void**)&buf) == S_OK) {
  742. uint16_t vanc[MAX_WIDTH_VANC];
  743. size_t vanc_size = videoFrame->GetWidth();
  744. if (ctx->bmd_mode == bmdModeNTSC && videoFrame->GetWidth() * 2 <= MAX_WIDTH_VANC) {
  745. vanc_size = vanc_size * 2;
  746. unpack_v210(vanc, buf, videoFrame->GetWidth());
  747. } else {
  748. extract_luma_from_v210(vanc, buf, videoFrame->GetWidth());
  749. }
  750. txt_buf = get_metadata(avctx, vanc, vanc_size,
  751. txt_buf, sizeof(txt_buf0) - (txt_buf - txt_buf0), &pkt);
  752. }
  753. if (i == vanc_line_numbers[idx].field0_vanc_end)
  754. i = vanc_line_numbers[idx].field1_vanc_start - 1;
  755. }
  756. }
  757. vanc->Release();
  758. if (txt_buf - txt_buf0 > 1) {
  759. int stuffing_units = (4 - ((45 + txt_buf - txt_buf0) / 46) % 4) % 4;
  760. while (stuffing_units--) {
  761. memset(txt_buf, 0xff, 46);
  762. txt_buf[1] = 0x2c; // data_unit_length
  763. txt_buf += 46;
  764. }
  765. av_init_packet(&txt_pkt);
  766. txt_pkt.pts = pkt.pts;
  767. txt_pkt.dts = pkt.dts;
  768. txt_pkt.stream_index = ctx->teletext_st->index;
  769. txt_pkt.data = txt_buf0;
  770. txt_pkt.size = txt_buf - txt_buf0;
  771. if (avpacket_queue_put(&ctx->queue, &txt_pkt) < 0) {
  772. ++ctx->dropped;
  773. }
  774. }
  775. }
  776. }
  777. pkt.buf = av_buffer_create(pkt.data, pkt.size, decklink_object_free, videoFrame, 0);
  778. if (pkt.buf)
  779. videoFrame->AddRef();
  780. if (avpacket_queue_put(&ctx->queue, &pkt) < 0) {
  781. ++ctx->dropped;
  782. }
  783. }
  784. // Handle Audio Frame
  785. if (audioFrame) {
  786. AVPacket pkt;
  787. BMDTimeValue audio_pts;
  788. av_init_packet(&pkt);
  789. //hack among hacks
  790. pkt.size = audioFrame->GetSampleFrameCount() * ctx->audio_st->codecpar->channels * (ctx->audio_depth / 8);
  791. audioFrame->GetBytes(&audioFrameBytes);
  792. audioFrame->GetPacketTime(&audio_pts, ctx->audio_st->time_base.den);
  793. pkt.pts = get_pkt_pts(videoFrame, audioFrame, wallclock, abs_wallclock, ctx->audio_pts_source, ctx->audio_st->time_base, &initial_audio_pts, cctx->copyts);
  794. pkt.dts = pkt.pts;
  795. //fprintf(stderr,"Audio Frame size %d ts %d\n", pkt.size, pkt.pts);
  796. pkt.flags |= AV_PKT_FLAG_KEY;
  797. pkt.stream_index = ctx->audio_st->index;
  798. pkt.data = (uint8_t *)audioFrameBytes;
  799. if (avpacket_queue_put(&ctx->queue, &pkt) < 0) {
  800. ++ctx->dropped;
  801. }
  802. }
  803. return S_OK;
  804. }
  805. HRESULT decklink_input_callback::VideoInputFormatChanged(
  806. BMDVideoInputFormatChangedEvents events, IDeckLinkDisplayMode *mode,
  807. BMDDetectedVideoInputFormatFlags)
  808. {
  809. ctx->bmd_mode = mode->GetDisplayMode();
  810. return S_OK;
  811. }
  812. static int decklink_autodetect(struct decklink_cctx *cctx) {
  813. struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
  814. DECKLINK_BOOL autodetect_supported = false;
  815. int i;
  816. if (ctx->attr->GetFlag(BMDDeckLinkSupportsInputFormatDetection, &autodetect_supported) != S_OK)
  817. return -1;
  818. if (autodetect_supported == false)
  819. return -1;
  820. ctx->autodetect = 1;
  821. ctx->bmd_mode = bmdModeUnknown;
  822. if (ctx->dli->EnableVideoInput(AUTODETECT_DEFAULT_MODE,
  823. bmdFormat8BitYUV,
  824. bmdVideoInputEnableFormatDetection) != S_OK) {
  825. return -1;
  826. }
  827. if (ctx->dli->StartStreams() != S_OK) {
  828. return -1;
  829. }
  830. // 1 second timeout
  831. for (i = 0; i < 10; i++) {
  832. av_usleep(100000);
  833. /* Sometimes VideoInputFrameArrived is called without the
  834. * bmdFrameHasNoInputSource flag before VideoInputFormatChanged.
  835. * So don't break for bmd_mode == AUTODETECT_DEFAULT_MODE. */
  836. if (ctx->bmd_mode != bmdModeUnknown &&
  837. ctx->bmd_mode != AUTODETECT_DEFAULT_MODE)
  838. break;
  839. }
  840. ctx->dli->PauseStreams();
  841. ctx->dli->FlushStreams();
  842. ctx->autodetect = 0;
  843. if (ctx->bmd_mode != bmdModeUnknown) {
  844. cctx->format_code = (char *)av_mallocz(5);
  845. if (!cctx->format_code)
  846. return -1;
  847. AV_WB32(cctx->format_code, ctx->bmd_mode);
  848. return 0;
  849. } else {
  850. return -1;
  851. }
  852. }
  853. extern "C" {
  854. av_cold int ff_decklink_read_close(AVFormatContext *avctx)
  855. {
  856. struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
  857. struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
  858. if (ctx->capture_started) {
  859. ctx->dli->StopStreams();
  860. ctx->dli->DisableVideoInput();
  861. ctx->dli->DisableAudioInput();
  862. }
  863. ff_decklink_cleanup(avctx);
  864. avpacket_queue_end(&ctx->queue);
  865. av_freep(&cctx->ctx);
  866. return 0;
  867. }
  868. av_cold int ff_decklink_read_header(AVFormatContext *avctx)
  869. {
  870. struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
  871. struct decklink_ctx *ctx;
  872. class decklink_allocator *allocator;
  873. class decklink_input_callback *input_callback;
  874. AVStream *st;
  875. HRESULT result;
  876. char fname[1024];
  877. char *tmp;
  878. int mode_num = 0;
  879. int ret;
  880. ctx = (struct decklink_ctx *) av_mallocz(sizeof(struct decklink_ctx));
  881. if (!ctx)
  882. return AVERROR(ENOMEM);
  883. ctx->list_devices = cctx->list_devices;
  884. ctx->list_formats = cctx->list_formats;
  885. ctx->teletext_lines = cctx->teletext_lines;
  886. ctx->preroll = cctx->preroll;
  887. ctx->duplex_mode = cctx->duplex_mode;
  888. if (cctx->tc_format > 0 && (unsigned int)cctx->tc_format < FF_ARRAY_ELEMS(decklink_timecode_format_map))
  889. ctx->tc_format = decklink_timecode_format_map[cctx->tc_format];
  890. if (cctx->video_input > 0 && (unsigned int)cctx->video_input < FF_ARRAY_ELEMS(decklink_video_connection_map))
  891. ctx->video_input = decklink_video_connection_map[cctx->video_input];
  892. if (cctx->audio_input > 0 && (unsigned int)cctx->audio_input < FF_ARRAY_ELEMS(decklink_audio_connection_map))
  893. ctx->audio_input = decklink_audio_connection_map[cctx->audio_input];
  894. ctx->audio_pts_source = cctx->audio_pts_source;
  895. ctx->video_pts_source = cctx->video_pts_source;
  896. ctx->draw_bars = cctx->draw_bars;
  897. ctx->audio_depth = cctx->audio_depth;
  898. cctx->ctx = ctx;
  899. /* Check audio channel option for valid values: 2, 8 or 16 */
  900. switch (cctx->audio_channels) {
  901. case 2:
  902. case 8:
  903. case 16:
  904. break;
  905. default:
  906. av_log(avctx, AV_LOG_ERROR, "Value of channels option must be one of 2, 8 or 16\n");
  907. return AVERROR(EINVAL);
  908. }
  909. /* Check audio bit depth option for valid values: 16 or 32 */
  910. switch (cctx->audio_depth) {
  911. case 16:
  912. case 32:
  913. break;
  914. default:
  915. av_log(avctx, AV_LOG_ERROR, "Value for audio bit depth option must be either 16 or 32\n");
  916. return AVERROR(EINVAL);
  917. }
  918. /* List available devices. */
  919. if (ctx->list_devices) {
  920. ff_decklink_list_devices_legacy(avctx, 1, 0);
  921. return AVERROR_EXIT;
  922. }
  923. if (cctx->v210) {
  924. av_log(avctx, AV_LOG_WARNING, "The bm_v210 option is deprecated and will be removed. Please use the -raw_format yuv422p10.\n");
  925. cctx->raw_format = MKBETAG('v','2','1','0');
  926. }
  927. av_strlcpy(fname, avctx->url, sizeof(fname));
  928. tmp=strchr (fname, '@');
  929. if (tmp != NULL) {
  930. av_log(avctx, AV_LOG_WARNING, "The @mode syntax is deprecated and will be removed. Please use the -format_code option.\n");
  931. mode_num = atoi (tmp+1);
  932. *tmp = 0;
  933. }
  934. ret = ff_decklink_init_device(avctx, fname);
  935. if (ret < 0)
  936. return ret;
  937. /* Get input device. */
  938. if (ctx->dl->QueryInterface(IID_IDeckLinkInput, (void **) &ctx->dli) != S_OK) {
  939. av_log(avctx, AV_LOG_ERROR, "Could not open input device from '%s'\n",
  940. avctx->url);
  941. ret = AVERROR(EIO);
  942. goto error;
  943. }
  944. if (ff_decklink_set_configs(avctx, DIRECTION_IN) < 0) {
  945. av_log(avctx, AV_LOG_ERROR, "Could not set input configuration\n");
  946. ret = AVERROR(EIO);
  947. goto error;
  948. }
  949. /* List supported formats. */
  950. if (ctx->list_formats) {
  951. ff_decklink_list_formats(avctx, DIRECTION_IN);
  952. ret = AVERROR_EXIT;
  953. goto error;
  954. }
  955. input_callback = new decklink_input_callback(avctx);
  956. ret = (ctx->dli->SetCallback(input_callback) == S_OK ? 0 : AVERROR_EXTERNAL);
  957. input_callback->Release();
  958. if (ret < 0) {
  959. av_log(avctx, AV_LOG_ERROR, "Cannot set input callback\n");
  960. goto error;
  961. }
  962. allocator = new decklink_allocator();
  963. ret = (ctx->dli->SetVideoInputFrameMemoryAllocator(allocator) == S_OK ? 0 : AVERROR_EXTERNAL);
  964. allocator->Release();
  965. if (ret < 0) {
  966. av_log(avctx, AV_LOG_ERROR, "Cannot set custom memory allocator\n");
  967. goto error;
  968. }
  969. if (mode_num == 0 && !cctx->format_code) {
  970. if (decklink_autodetect(cctx) < 0) {
  971. av_log(avctx, AV_LOG_ERROR, "Cannot Autodetect input stream or No signal\n");
  972. ret = AVERROR(EIO);
  973. goto error;
  974. }
  975. av_log(avctx, AV_LOG_INFO, "Autodetected the input mode\n");
  976. }
  977. if (ff_decklink_set_format(avctx, DIRECTION_IN, mode_num) < 0) {
  978. av_log(avctx, AV_LOG_ERROR, "Could not set mode number %d or format code %s for %s\n",
  979. mode_num, (cctx->format_code) ? cctx->format_code : "(unset)", fname);
  980. ret = AVERROR(EIO);
  981. goto error;
  982. }
  983. #if !CONFIG_LIBZVBI
  984. if (ctx->teletext_lines && ctx->bmd_mode == bmdModePAL) {
  985. av_log(avctx, AV_LOG_ERROR, "Libzvbi support is needed for capturing SD PAL teletext, please recompile FFmpeg.\n");
  986. ret = AVERROR(ENOSYS);
  987. goto error;
  988. }
  989. #endif
  990. /* Setup streams. */
  991. st = avformat_new_stream(avctx, NULL);
  992. if (!st) {
  993. av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
  994. ret = AVERROR(ENOMEM);
  995. goto error;
  996. }
  997. st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
  998. st->codecpar->codec_id = cctx->audio_depth == 32 ? AV_CODEC_ID_PCM_S32LE : AV_CODEC_ID_PCM_S16LE;
  999. st->codecpar->sample_rate = bmdAudioSampleRate48kHz;
  1000. st->codecpar->channels = cctx->audio_channels;
  1001. avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
  1002. ctx->audio_st=st;
  1003. st = avformat_new_stream(avctx, NULL);
  1004. if (!st) {
  1005. av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
  1006. ret = AVERROR(ENOMEM);
  1007. goto error;
  1008. }
  1009. st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
  1010. st->codecpar->width = ctx->bmd_width;
  1011. st->codecpar->height = ctx->bmd_height;
  1012. st->time_base.den = ctx->bmd_tb_den;
  1013. st->time_base.num = ctx->bmd_tb_num;
  1014. st->r_frame_rate = av_make_q(st->time_base.den, st->time_base.num);
  1015. switch((BMDPixelFormat)cctx->raw_format) {
  1016. case bmdFormat8BitYUV:
  1017. st->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
  1018. st->codecpar->codec_tag = MKTAG('U', 'Y', 'V', 'Y');
  1019. st->codecpar->format = AV_PIX_FMT_UYVY422;
  1020. st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 16, st->time_base.den, st->time_base.num);
  1021. break;
  1022. case bmdFormat10BitYUV:
  1023. st->codecpar->codec_id = AV_CODEC_ID_V210;
  1024. st->codecpar->codec_tag = MKTAG('V','2','1','0');
  1025. st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 64, st->time_base.den, st->time_base.num * 3);
  1026. st->codecpar->bits_per_coded_sample = 10;
  1027. break;
  1028. case bmdFormat8BitARGB:
  1029. st->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
  1030. st->codecpar->format = AV_PIX_FMT_0RGB;
  1031. st->codecpar->codec_tag = avcodec_pix_fmt_to_codec_tag((enum AVPixelFormat)st->codecpar->format);
  1032. st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 32, st->time_base.den, st->time_base.num);
  1033. break;
  1034. case bmdFormat8BitBGRA:
  1035. st->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
  1036. st->codecpar->format = AV_PIX_FMT_BGR0;
  1037. st->codecpar->codec_tag = avcodec_pix_fmt_to_codec_tag((enum AVPixelFormat)st->codecpar->format);
  1038. st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 32, st->time_base.den, st->time_base.num);
  1039. break;
  1040. case bmdFormat10BitRGB:
  1041. st->codecpar->codec_id = AV_CODEC_ID_R210;
  1042. st->codecpar->codec_tag = MKTAG('R','2','1','0');
  1043. st->codecpar->format = AV_PIX_FMT_RGB48LE;
  1044. st->codecpar->bit_rate = av_rescale(ctx->bmd_width * ctx->bmd_height * 30, st->time_base.den, st->time_base.num);
  1045. st->codecpar->bits_per_coded_sample = 10;
  1046. break;
  1047. default:
  1048. av_log(avctx, AV_LOG_ERROR, "Raw Format %.4s not supported\n", (char*) &cctx->raw_format);
  1049. ret = AVERROR(EINVAL);
  1050. goto error;
  1051. }
  1052. switch (ctx->bmd_field_dominance) {
  1053. case bmdUpperFieldFirst:
  1054. st->codecpar->field_order = AV_FIELD_TT;
  1055. break;
  1056. case bmdLowerFieldFirst:
  1057. st->codecpar->field_order = AV_FIELD_BB;
  1058. break;
  1059. case bmdProgressiveFrame:
  1060. case bmdProgressiveSegmentedFrame:
  1061. st->codecpar->field_order = AV_FIELD_PROGRESSIVE;
  1062. break;
  1063. }
  1064. avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
  1065. ctx->video_st=st;
  1066. if (ctx->teletext_lines) {
  1067. st = avformat_new_stream(avctx, NULL);
  1068. if (!st) {
  1069. av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
  1070. ret = AVERROR(ENOMEM);
  1071. goto error;
  1072. }
  1073. st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1074. st->time_base.den = ctx->bmd_tb_den;
  1075. st->time_base.num = ctx->bmd_tb_num;
  1076. st->codecpar->codec_id = AV_CODEC_ID_DVB_TELETEXT;
  1077. avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
  1078. ctx->teletext_st = st;
  1079. }
  1080. av_log(avctx, AV_LOG_VERBOSE, "Using %d input audio channels\n", ctx->audio_st->codecpar->channels);
  1081. result = ctx->dli->EnableAudioInput(bmdAudioSampleRate48kHz, cctx->audio_depth == 32 ? bmdAudioSampleType32bitInteger : bmdAudioSampleType16bitInteger, ctx->audio_st->codecpar->channels);
  1082. if (result != S_OK) {
  1083. av_log(avctx, AV_LOG_ERROR, "Cannot enable audio input\n");
  1084. ret = AVERROR(EIO);
  1085. goto error;
  1086. }
  1087. result = ctx->dli->EnableVideoInput(ctx->bmd_mode,
  1088. (BMDPixelFormat) cctx->raw_format,
  1089. bmdVideoInputFlagDefault);
  1090. if (result != S_OK) {
  1091. av_log(avctx, AV_LOG_ERROR, "Cannot enable video input\n");
  1092. ret = AVERROR(EIO);
  1093. goto error;
  1094. }
  1095. avpacket_queue_init (avctx, &ctx->queue);
  1096. if (ctx->dli->StartStreams() != S_OK) {
  1097. av_log(avctx, AV_LOG_ERROR, "Cannot start input stream\n");
  1098. ret = AVERROR(EIO);
  1099. goto error;
  1100. }
  1101. return 0;
  1102. error:
  1103. ff_decklink_cleanup(avctx);
  1104. return ret;
  1105. }
  1106. int ff_decklink_read_packet(AVFormatContext *avctx, AVPacket *pkt)
  1107. {
  1108. struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
  1109. struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
  1110. avpacket_queue_get(&ctx->queue, pkt, 1);
  1111. if (ctx->tc_format && !(av_dict_get(ctx->video_st->metadata, "timecode", NULL, 0))) {
  1112. int size;
  1113. const uint8_t *side_metadata = av_packet_get_side_data(pkt, AV_PKT_DATA_STRINGS_METADATA, &size);
  1114. if (side_metadata) {
  1115. if (av_packet_unpack_dictionary(side_metadata, size, &ctx->video_st->metadata) < 0)
  1116. av_log(avctx, AV_LOG_ERROR, "Unable to set timecode\n");
  1117. }
  1118. }
  1119. return 0;
  1120. }
  1121. int ff_decklink_list_input_devices(AVFormatContext *avctx, struct AVDeviceInfoList *device_list)
  1122. {
  1123. return ff_decklink_list_devices(avctx, device_list, 1, 0);
  1124. }
  1125. } /* extern "C" */