decklink_enc.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866
  1. /*
  2. * Blackmagic DeckLink output
  3. * Copyright (c) 2013-2014 Ramiro Polla
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include <atomic>
  22. using std::atomic;
  23. /* Include internal.h first to avoid conflict between winsock.h (used by
  24. * DeckLink headers) and winsock2.h (used by libavformat) in MSVC++ builds */
  25. extern "C" {
  26. #include "libavformat/internal.h"
  27. }
  28. #include <DeckLinkAPI.h>
  29. extern "C" {
  30. #include "libavformat/avformat.h"
  31. #include "libavcodec/bytestream.h"
  32. #include "libavutil/internal.h"
  33. #include "libavutil/imgutils.h"
  34. #include "avdevice.h"
  35. }
  36. #include "decklink_common.h"
  37. #include "decklink_enc.h"
  38. #if CONFIG_LIBKLVANC
  39. #include "libklvanc/vanc.h"
  40. #include "libklvanc/vanc-lines.h"
  41. #include "libklvanc/pixels.h"
  42. #endif
  43. /* DeckLink callback class declaration */
  44. class decklink_frame : public IDeckLinkVideoFrame
  45. {
  46. public:
  47. decklink_frame(struct decklink_ctx *ctx, AVFrame *avframe, AVCodecID codec_id, int height, int width) :
  48. _ctx(ctx), _avframe(avframe), _avpacket(NULL), _codec_id(codec_id), _ancillary(NULL), _height(height), _width(width), _refs(1) { }
  49. decklink_frame(struct decklink_ctx *ctx, AVPacket *avpacket, AVCodecID codec_id, int height, int width) :
  50. _ctx(ctx), _avframe(NULL), _avpacket(avpacket), _codec_id(codec_id), _ancillary(NULL), _height(height), _width(width), _refs(1) { }
  51. virtual long STDMETHODCALLTYPE GetWidth (void) { return _width; }
  52. virtual long STDMETHODCALLTYPE GetHeight (void) { return _height; }
  53. virtual long STDMETHODCALLTYPE GetRowBytes (void)
  54. {
  55. if (_codec_id == AV_CODEC_ID_WRAPPED_AVFRAME)
  56. return _avframe->linesize[0] < 0 ? -_avframe->linesize[0] : _avframe->linesize[0];
  57. else
  58. return ((GetWidth() + 47) / 48) * 128;
  59. }
  60. virtual BMDPixelFormat STDMETHODCALLTYPE GetPixelFormat(void)
  61. {
  62. if (_codec_id == AV_CODEC_ID_WRAPPED_AVFRAME)
  63. return bmdFormat8BitYUV;
  64. else
  65. return bmdFormat10BitYUV;
  66. }
  67. virtual BMDFrameFlags STDMETHODCALLTYPE GetFlags (void)
  68. {
  69. if (_codec_id == AV_CODEC_ID_WRAPPED_AVFRAME)
  70. return _avframe->linesize[0] < 0 ? bmdFrameFlagFlipVertical : bmdFrameFlagDefault;
  71. else
  72. return bmdFrameFlagDefault;
  73. }
  74. virtual HRESULT STDMETHODCALLTYPE GetBytes (void **buffer)
  75. {
  76. if (_codec_id == AV_CODEC_ID_WRAPPED_AVFRAME) {
  77. if (_avframe->linesize[0] < 0)
  78. *buffer = (void *)(_avframe->data[0] + _avframe->linesize[0] * (_avframe->height - 1));
  79. else
  80. *buffer = (void *)(_avframe->data[0]);
  81. } else {
  82. *buffer = (void *)(_avpacket->data);
  83. }
  84. return S_OK;
  85. }
  86. virtual HRESULT STDMETHODCALLTYPE GetTimecode (BMDTimecodeFormat format, IDeckLinkTimecode **timecode) { return S_FALSE; }
  87. virtual HRESULT STDMETHODCALLTYPE GetAncillaryData(IDeckLinkVideoFrameAncillary **ancillary)
  88. {
  89. *ancillary = _ancillary;
  90. if (_ancillary) {
  91. _ancillary->AddRef();
  92. return S_OK;
  93. } else {
  94. return S_FALSE;
  95. }
  96. }
  97. virtual HRESULT STDMETHODCALLTYPE SetAncillaryData(IDeckLinkVideoFrameAncillary *ancillary)
  98. {
  99. if (_ancillary)
  100. _ancillary->Release();
  101. _ancillary = ancillary;
  102. _ancillary->AddRef();
  103. return S_OK;
  104. }
  105. virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv) { return E_NOINTERFACE; }
  106. virtual ULONG STDMETHODCALLTYPE AddRef(void) { return ++_refs; }
  107. virtual ULONG STDMETHODCALLTYPE Release(void)
  108. {
  109. int ret = --_refs;
  110. if (!ret) {
  111. av_frame_free(&_avframe);
  112. av_packet_free(&_avpacket);
  113. if (_ancillary)
  114. _ancillary->Release();
  115. delete this;
  116. }
  117. return ret;
  118. }
  119. struct decklink_ctx *_ctx;
  120. AVFrame *_avframe;
  121. AVPacket *_avpacket;
  122. AVCodecID _codec_id;
  123. IDeckLinkVideoFrameAncillary *_ancillary;
  124. int _height;
  125. int _width;
  126. private:
  127. std::atomic<int> _refs;
  128. };
  129. class decklink_output_callback : public IDeckLinkVideoOutputCallback
  130. {
  131. public:
  132. virtual HRESULT STDMETHODCALLTYPE ScheduledFrameCompleted(IDeckLinkVideoFrame *_frame, BMDOutputFrameCompletionResult result)
  133. {
  134. decklink_frame *frame = static_cast<decklink_frame *>(_frame);
  135. struct decklink_ctx *ctx = frame->_ctx;
  136. if (frame->_avframe)
  137. av_frame_unref(frame->_avframe);
  138. if (frame->_avpacket)
  139. av_packet_unref(frame->_avpacket);
  140. pthread_mutex_lock(&ctx->mutex);
  141. ctx->frames_buffer_available_spots++;
  142. pthread_cond_broadcast(&ctx->cond);
  143. pthread_mutex_unlock(&ctx->mutex);
  144. return S_OK;
  145. }
  146. virtual HRESULT STDMETHODCALLTYPE ScheduledPlaybackHasStopped(void) { return S_OK; }
  147. virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv) { return E_NOINTERFACE; }
  148. virtual ULONG STDMETHODCALLTYPE AddRef(void) { return 1; }
  149. virtual ULONG STDMETHODCALLTYPE Release(void) { return 1; }
  150. };
  151. static int decklink_setup_video(AVFormatContext *avctx, AVStream *st)
  152. {
  153. struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
  154. struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
  155. AVCodecParameters *c = st->codecpar;
  156. if (ctx->video) {
  157. av_log(avctx, AV_LOG_ERROR, "Only one video stream is supported!\n");
  158. return -1;
  159. }
  160. if (c->codec_id == AV_CODEC_ID_WRAPPED_AVFRAME) {
  161. if (c->format != AV_PIX_FMT_UYVY422) {
  162. av_log(avctx, AV_LOG_ERROR, "Unsupported pixel format!"
  163. " Only AV_PIX_FMT_UYVY422 is supported.\n");
  164. return -1;
  165. }
  166. ctx->raw_format = bmdFormat8BitYUV;
  167. } else if (c->codec_id != AV_CODEC_ID_V210) {
  168. av_log(avctx, AV_LOG_ERROR, "Unsupported codec type!"
  169. " Only V210 and wrapped frame with AV_PIX_FMT_UYVY422 are supported.\n");
  170. return -1;
  171. } else {
  172. ctx->raw_format = bmdFormat10BitYUV;
  173. }
  174. if (ff_decklink_set_configs(avctx, DIRECTION_OUT) < 0) {
  175. av_log(avctx, AV_LOG_ERROR, "Could not set output configuration\n");
  176. return -1;
  177. }
  178. if (ff_decklink_set_format(avctx, c->width, c->height,
  179. st->time_base.num, st->time_base.den, c->field_order)) {
  180. av_log(avctx, AV_LOG_ERROR, "Unsupported video size, framerate or field order!"
  181. " Check available formats with -list_formats 1.\n");
  182. return -1;
  183. }
  184. if (ctx->supports_vanc && ctx->dlo->EnableVideoOutput(ctx->bmd_mode, bmdVideoOutputVANC) != S_OK) {
  185. av_log(avctx, AV_LOG_WARNING, "Could not enable video output with VANC! Trying without...\n");
  186. ctx->supports_vanc = 0;
  187. }
  188. if (!ctx->supports_vanc && ctx->dlo->EnableVideoOutput(ctx->bmd_mode, bmdVideoOutputFlagDefault) != S_OK) {
  189. av_log(avctx, AV_LOG_ERROR, "Could not enable video output!\n");
  190. return -1;
  191. }
  192. /* Set callback. */
  193. ctx->output_callback = new decklink_output_callback();
  194. ctx->dlo->SetScheduledFrameCompletionCallback(ctx->output_callback);
  195. ctx->frames_preroll = st->time_base.den * ctx->preroll;
  196. if (st->time_base.den > 1000)
  197. ctx->frames_preroll /= 1000;
  198. /* Buffer twice as many frames as the preroll. */
  199. ctx->frames_buffer = ctx->frames_preroll * 2;
  200. ctx->frames_buffer = FFMIN(ctx->frames_buffer, 60);
  201. pthread_mutex_init(&ctx->mutex, NULL);
  202. pthread_cond_init(&ctx->cond, NULL);
  203. ctx->frames_buffer_available_spots = ctx->frames_buffer;
  204. av_log(avctx, AV_LOG_DEBUG, "output: %s, preroll: %d, frames buffer size: %d\n",
  205. avctx->url, ctx->frames_preroll, ctx->frames_buffer);
  206. /* The device expects the framerate to be fixed. */
  207. avpriv_set_pts_info(st, 64, st->time_base.num, st->time_base.den);
  208. ctx->video = 1;
  209. return 0;
  210. }
  211. static int decklink_setup_audio(AVFormatContext *avctx, AVStream *st)
  212. {
  213. struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
  214. struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
  215. AVCodecParameters *c = st->codecpar;
  216. if (ctx->audio) {
  217. av_log(avctx, AV_LOG_ERROR, "Only one audio stream is supported!\n");
  218. return -1;
  219. }
  220. if (c->codec_id == AV_CODEC_ID_AC3) {
  221. /* Regardless of the number of channels in the codec, we're only
  222. using 2 SDI audio channels at 48000Hz */
  223. ctx->channels = 2;
  224. } else if (c->codec_id == AV_CODEC_ID_PCM_S16LE) {
  225. if (c->sample_rate != 48000) {
  226. av_log(avctx, AV_LOG_ERROR, "Unsupported sample rate!"
  227. " Only 48kHz is supported.\n");
  228. return -1;
  229. }
  230. if (c->ch_layout.nb_channels != 2 && c->ch_layout.nb_channels != 8 && c->ch_layout.nb_channels != 16) {
  231. av_log(avctx, AV_LOG_ERROR, "Unsupported number of channels!"
  232. " Only 2, 8 or 16 channels are supported.\n");
  233. return -1;
  234. }
  235. ctx->channels = c->ch_layout.nb_channels;
  236. } else {
  237. av_log(avctx, AV_LOG_ERROR, "Unsupported codec specified!"
  238. " Only PCM_S16LE and AC-3 are supported.\n");
  239. return -1;
  240. }
  241. if (ctx->dlo->EnableAudioOutput(bmdAudioSampleRate48kHz,
  242. bmdAudioSampleType16bitInteger,
  243. ctx->channels,
  244. bmdAudioOutputStreamTimestamped) != S_OK) {
  245. av_log(avctx, AV_LOG_ERROR, "Could not enable audio output!\n");
  246. return -1;
  247. }
  248. if (ctx->dlo->BeginAudioPreroll() != S_OK) {
  249. av_log(avctx, AV_LOG_ERROR, "Could not begin audio preroll!\n");
  250. return -1;
  251. }
  252. /* The device expects the sample rate to be fixed. */
  253. avpriv_set_pts_info(st, 64, 1, 48000);
  254. ctx->audio = 1;
  255. return 0;
  256. }
  257. /* Wrap the AC-3 packet into an S337 payload that is in S16LE format which can be easily
  258. injected into the PCM stream. Note: despite the function name, only AC-3 is implemented */
  259. static int create_s337_payload(AVPacket *pkt, uint8_t **outbuf, int *outsize)
  260. {
  261. /* Note: if the packet size is not divisible by four, we need to make the actual
  262. payload larger to ensure it ends on an two channel S16LE boundary */
  263. int payload_size = FFALIGN(pkt->size, 4) + 8;
  264. uint16_t bitcount = pkt->size * 8;
  265. uint8_t *s337_payload;
  266. PutByteContext pb;
  267. /* Sanity check: According to SMPTE ST 340:2015 Sec 4.1, the AC-3 sync frame will
  268. exactly match the 1536 samples of baseband (PCM) audio that it represents. */
  269. if (pkt->size > 1536)
  270. return AVERROR(EINVAL);
  271. /* Encapsulate AC3 syncframe into SMPTE 337 packet */
  272. s337_payload = (uint8_t *) av_malloc(payload_size);
  273. if (s337_payload == NULL)
  274. return AVERROR(ENOMEM);
  275. bytestream2_init_writer(&pb, s337_payload, payload_size);
  276. bytestream2_put_le16u(&pb, 0xf872); /* Sync word 1 */
  277. bytestream2_put_le16u(&pb, 0x4e1f); /* Sync word 1 */
  278. bytestream2_put_le16u(&pb, 0x0001); /* Burst Info, including data type (1=ac3) */
  279. bytestream2_put_le16u(&pb, bitcount); /* Length code */
  280. for (int i = 0; i < (pkt->size - 1); i += 2)
  281. bytestream2_put_le16u(&pb, (pkt->data[i] << 8) | pkt->data[i+1]);
  282. /* Ensure final payload is aligned on 4-byte boundary */
  283. if (pkt->size & 1)
  284. bytestream2_put_le16u(&pb, pkt->data[pkt->size - 1] << 8);
  285. if ((pkt->size & 3) == 1 || (pkt->size & 3) == 2)
  286. bytestream2_put_le16u(&pb, 0);
  287. *outsize = payload_size;
  288. *outbuf = s337_payload;
  289. return 0;
  290. }
  291. static int decklink_setup_subtitle(AVFormatContext *avctx, AVStream *st)
  292. {
  293. int ret = -1;
  294. switch(st->codecpar->codec_id) {
  295. #if CONFIG_LIBKLVANC
  296. case AV_CODEC_ID_EIA_608:
  297. /* No special setup required */
  298. ret = 0;
  299. break;
  300. #endif
  301. default:
  302. av_log(avctx, AV_LOG_ERROR, "Unsupported subtitle codec specified\n");
  303. break;
  304. }
  305. return ret;
  306. }
  307. av_cold int ff_decklink_write_trailer(AVFormatContext *avctx)
  308. {
  309. struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
  310. struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
  311. if (ctx->playback_started) {
  312. BMDTimeValue actual;
  313. ctx->dlo->StopScheduledPlayback(ctx->last_pts * ctx->bmd_tb_num,
  314. &actual, ctx->bmd_tb_den);
  315. ctx->dlo->DisableVideoOutput();
  316. if (ctx->audio)
  317. ctx->dlo->DisableAudioOutput();
  318. }
  319. ff_decklink_cleanup(avctx);
  320. if (ctx->output_callback)
  321. delete ctx->output_callback;
  322. pthread_mutex_destroy(&ctx->mutex);
  323. pthread_cond_destroy(&ctx->cond);
  324. #if CONFIG_LIBKLVANC
  325. klvanc_context_destroy(ctx->vanc_ctx);
  326. #endif
  327. ff_ccfifo_freep(&ctx->cc_fifo);
  328. av_freep(&cctx->ctx);
  329. return 0;
  330. }
  331. #if CONFIG_LIBKLVANC
  332. static void construct_cc(AVFormatContext *avctx, struct decklink_ctx *ctx,
  333. AVPacket *pkt, struct klvanc_line_set_s *vanc_lines)
  334. {
  335. struct klvanc_packet_eia_708b_s *cdp;
  336. uint16_t *cdp_words;
  337. uint16_t len;
  338. uint8_t cc_count;
  339. size_t size;
  340. int ret, i;
  341. const uint8_t *data = av_packet_get_side_data(pkt, AV_PKT_DATA_A53_CC, &size);
  342. if (!data)
  343. return;
  344. cc_count = size / 3;
  345. ret = klvanc_create_eia708_cdp(&cdp);
  346. if (ret)
  347. return;
  348. ret = klvanc_set_framerate_EIA_708B(cdp, ctx->bmd_tb_num, ctx->bmd_tb_den);
  349. if (ret) {
  350. av_log(avctx, AV_LOG_ERROR, "Invalid framerate specified: %lld/%lld\n",
  351. ctx->bmd_tb_num, ctx->bmd_tb_den);
  352. klvanc_destroy_eia708_cdp(cdp);
  353. return;
  354. }
  355. if (cc_count > KLVANC_MAX_CC_COUNT) {
  356. av_log(avctx, AV_LOG_ERROR, "Illegal cc_count received: %d\n", cc_count);
  357. cc_count = KLVANC_MAX_CC_COUNT;
  358. }
  359. /* CC data */
  360. cdp->header.ccdata_present = 1;
  361. cdp->header.caption_service_active = 1;
  362. cdp->ccdata.cc_count = cc_count;
  363. for (i = 0; i < cc_count; i++) {
  364. if (data [3*i] & 0x04)
  365. cdp->ccdata.cc[i].cc_valid = 1;
  366. cdp->ccdata.cc[i].cc_type = data[3*i] & 0x03;
  367. cdp->ccdata.cc[i].cc_data[0] = data[3*i+1];
  368. cdp->ccdata.cc[i].cc_data[1] = data[3*i+2];
  369. }
  370. klvanc_finalize_EIA_708B(cdp, ctx->cdp_sequence_num++);
  371. ret = klvanc_convert_EIA_708B_to_words(cdp, &cdp_words, &len);
  372. klvanc_destroy_eia708_cdp(cdp);
  373. if (ret != 0) {
  374. av_log(avctx, AV_LOG_ERROR, "Failed converting 708 packet to words\n");
  375. return;
  376. }
  377. ret = klvanc_line_insert(ctx->vanc_ctx, vanc_lines, cdp_words, len, 11, 0);
  378. free(cdp_words);
  379. if (ret != 0) {
  380. av_log(avctx, AV_LOG_ERROR, "VANC line insertion failed\n");
  381. return;
  382. }
  383. }
  384. /* See SMPTE ST 2016-3:2009 */
  385. static void construct_afd(AVFormatContext *avctx, struct decklink_ctx *ctx,
  386. AVPacket *pkt, struct klvanc_line_set_s *vanc_lines,
  387. AVStream *st)
  388. {
  389. struct klvanc_packet_afd_s *afd = NULL;
  390. uint16_t *afd_words = NULL;
  391. uint16_t len;
  392. size_t size;
  393. int f1_line = 12, f2_line = 0, ret;
  394. const uint8_t *data = av_packet_get_side_data(pkt, AV_PKT_DATA_AFD, &size);
  395. if (!data || size == 0)
  396. return;
  397. ret = klvanc_create_AFD(&afd);
  398. if (ret)
  399. return;
  400. ret = klvanc_set_AFD_val(afd, data[0]);
  401. if (ret) {
  402. av_log(avctx, AV_LOG_ERROR, "Invalid AFD value specified: %d\n",
  403. data[0]);
  404. klvanc_destroy_AFD(afd);
  405. return;
  406. }
  407. /* Compute the AR flag based on the DAR (see ST 2016-1:2009 Sec 9.1). Note, we treat
  408. anything below 1.4 as 4:3 (as opposed to the standard 1.33), because there are lots
  409. of streams in the field that aren't *exactly* 4:3 but a tiny bit larger after doing
  410. the math... */
  411. if (av_cmp_q((AVRational) {st->codecpar->width * st->codecpar->sample_aspect_ratio.num,
  412. st->codecpar->height * st->codecpar->sample_aspect_ratio.den}, (AVRational) {14, 10}) == 1)
  413. afd->aspectRatio = ASPECT_16x9;
  414. else
  415. afd->aspectRatio = ASPECT_4x3;
  416. ret = klvanc_convert_AFD_to_words(afd, &afd_words, &len);
  417. if (ret) {
  418. av_log(avctx, AV_LOG_ERROR, "Failed converting AFD packet to words\n");
  419. goto out;
  420. }
  421. ret = klvanc_line_insert(ctx->vanc_ctx, vanc_lines, afd_words, len, f1_line, 0);
  422. if (ret) {
  423. av_log(avctx, AV_LOG_ERROR, "VANC line insertion failed\n");
  424. goto out;
  425. }
  426. /* For interlaced video, insert into both fields. Switching lines for field 2
  427. derived from SMPTE RP 168:2009, Sec 6, Table 2. */
  428. switch (ctx->bmd_mode) {
  429. case bmdModeNTSC:
  430. case bmdModeNTSC2398:
  431. f2_line = 273 - 10 + f1_line;
  432. break;
  433. case bmdModePAL:
  434. f2_line = 319 - 6 + f1_line;
  435. break;
  436. case bmdModeHD1080i50:
  437. case bmdModeHD1080i5994:
  438. case bmdModeHD1080i6000:
  439. f2_line = 569 - 7 + f1_line;
  440. break;
  441. default:
  442. f2_line = 0;
  443. break;
  444. }
  445. if (f2_line > 0) {
  446. ret = klvanc_line_insert(ctx->vanc_ctx, vanc_lines, afd_words, len, f2_line, 0);
  447. if (ret) {
  448. av_log(avctx, AV_LOG_ERROR, "VANC line insertion failed\n");
  449. goto out;
  450. }
  451. }
  452. out:
  453. if (afd)
  454. klvanc_destroy_AFD(afd);
  455. if (afd_words)
  456. free(afd_words);
  457. }
  458. /* Parse any EIA-608 subtitles sitting on the queue, and write packet side data
  459. that will later be handled by construct_cc... */
  460. static void parse_608subs(AVFormatContext *avctx, struct decklink_ctx *ctx, AVPacket *pkt)
  461. {
  462. size_t cc_size = ff_ccfifo_getoutputsize(ctx->cc_fifo);
  463. uint8_t *cc_data;
  464. if (!ff_ccfifo_ccdetected(ctx->cc_fifo))
  465. return;
  466. cc_data = av_packet_new_side_data(pkt, AV_PKT_DATA_A53_CC, cc_size);
  467. if (cc_data)
  468. ff_ccfifo_injectbytes(ctx->cc_fifo, cc_data, cc_size);
  469. }
  470. static int decklink_construct_vanc(AVFormatContext *avctx, struct decklink_ctx *ctx,
  471. AVPacket *pkt, decklink_frame *frame,
  472. AVStream *st)
  473. {
  474. struct klvanc_line_set_s vanc_lines = { 0 };
  475. int ret = 0, i;
  476. if (!ctx->supports_vanc)
  477. return 0;
  478. parse_608subs(avctx, ctx, pkt);
  479. construct_cc(avctx, ctx, pkt, &vanc_lines);
  480. construct_afd(avctx, ctx, pkt, &vanc_lines, st);
  481. IDeckLinkVideoFrameAncillary *vanc;
  482. int result = ctx->dlo->CreateAncillaryData(bmdFormat10BitYUV, &vanc);
  483. if (result != S_OK) {
  484. av_log(avctx, AV_LOG_ERROR, "Failed to create vanc\n");
  485. ret = AVERROR(EIO);
  486. goto done;
  487. }
  488. /* Now that we've got all the VANC lines in a nice orderly manner, generate the
  489. final VANC sections for the Decklink output */
  490. for (i = 0; i < vanc_lines.num_lines; i++) {
  491. struct klvanc_line_s *line = vanc_lines.lines[i];
  492. int real_line;
  493. void *buf;
  494. if (!line)
  495. break;
  496. /* FIXME: include hack for certain Decklink cards which mis-represent
  497. line numbers for pSF frames */
  498. real_line = line->line_number;
  499. result = vanc->GetBufferForVerticalBlankingLine(real_line, &buf);
  500. if (result != S_OK) {
  501. av_log(avctx, AV_LOG_ERROR, "Failed to get VANC line %d: %d", real_line, result);
  502. continue;
  503. }
  504. /* Generate the full line taking into account all VANC packets on that line */
  505. result = klvanc_generate_vanc_line_v210(ctx->vanc_ctx, line, (uint8_t *) buf,
  506. ctx->bmd_width);
  507. if (result) {
  508. av_log(avctx, AV_LOG_ERROR, "Failed to generate VANC line\n");
  509. continue;
  510. }
  511. }
  512. result = frame->SetAncillaryData(vanc);
  513. vanc->Release();
  514. if (result != S_OK) {
  515. av_log(avctx, AV_LOG_ERROR, "Failed to set vanc: %d", result);
  516. ret = AVERROR(EIO);
  517. }
  518. done:
  519. for (i = 0; i < vanc_lines.num_lines; i++)
  520. klvanc_line_free(vanc_lines.lines[i]);
  521. return ret;
  522. }
  523. #endif
  524. static int decklink_write_video_packet(AVFormatContext *avctx, AVPacket *pkt)
  525. {
  526. struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
  527. struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
  528. AVStream *st = avctx->streams[pkt->stream_index];
  529. AVFrame *avframe = NULL, *tmp = (AVFrame *)pkt->data;
  530. AVPacket *avpacket = NULL;
  531. decklink_frame *frame;
  532. uint32_t buffered;
  533. HRESULT hr;
  534. ctx->last_pts = FFMAX(ctx->last_pts, pkt->pts);
  535. if (st->codecpar->codec_id == AV_CODEC_ID_WRAPPED_AVFRAME) {
  536. if (tmp->format != AV_PIX_FMT_UYVY422 ||
  537. tmp->width != ctx->bmd_width ||
  538. tmp->height != ctx->bmd_height) {
  539. av_log(avctx, AV_LOG_ERROR, "Got a frame with invalid pixel format or dimension.\n");
  540. return AVERROR(EINVAL);
  541. }
  542. avframe = av_frame_clone(tmp);
  543. if (!avframe) {
  544. av_log(avctx, AV_LOG_ERROR, "Could not clone video frame.\n");
  545. return AVERROR(EIO);
  546. }
  547. frame = new decklink_frame(ctx, avframe, st->codecpar->codec_id, avframe->height, avframe->width);
  548. } else {
  549. avpacket = av_packet_clone(pkt);
  550. if (!avpacket) {
  551. av_log(avctx, AV_LOG_ERROR, "Could not clone video frame.\n");
  552. return AVERROR(EIO);
  553. }
  554. frame = new decklink_frame(ctx, avpacket, st->codecpar->codec_id, ctx->bmd_height, ctx->bmd_width);
  555. #if CONFIG_LIBKLVANC
  556. if (decklink_construct_vanc(avctx, ctx, pkt, frame, st))
  557. av_log(avctx, AV_LOG_ERROR, "Failed to construct VANC\n");
  558. #endif
  559. }
  560. if (!frame) {
  561. av_log(avctx, AV_LOG_ERROR, "Could not create new frame.\n");
  562. av_frame_free(&avframe);
  563. av_packet_free(&avpacket);
  564. return AVERROR(EIO);
  565. }
  566. /* Always keep at most one second of frames buffered. */
  567. pthread_mutex_lock(&ctx->mutex);
  568. while (ctx->frames_buffer_available_spots == 0) {
  569. pthread_cond_wait(&ctx->cond, &ctx->mutex);
  570. }
  571. ctx->frames_buffer_available_spots--;
  572. pthread_mutex_unlock(&ctx->mutex);
  573. if (ctx->first_pts == AV_NOPTS_VALUE)
  574. ctx->first_pts = pkt->pts;
  575. /* Schedule frame for playback. */
  576. hr = ctx->dlo->ScheduleVideoFrame((class IDeckLinkVideoFrame *) frame,
  577. pkt->pts * ctx->bmd_tb_num,
  578. ctx->bmd_tb_num, ctx->bmd_tb_den);
  579. /* Pass ownership to DeckLink, or release on failure */
  580. frame->Release();
  581. if (hr != S_OK) {
  582. av_log(avctx, AV_LOG_ERROR, "Could not schedule video frame."
  583. " error %08x.\n", (uint32_t) hr);
  584. return AVERROR(EIO);
  585. }
  586. ctx->dlo->GetBufferedVideoFrameCount(&buffered);
  587. av_log(avctx, AV_LOG_DEBUG, "Buffered video frames: %d.\n", (int) buffered);
  588. if (pkt->pts > 2 && buffered <= 2)
  589. av_log(avctx, AV_LOG_WARNING, "There are not enough buffered video frames."
  590. " Video may misbehave!\n");
  591. /* Preroll video frames. */
  592. if (!ctx->playback_started && pkt->pts > (ctx->first_pts + ctx->frames_preroll)) {
  593. av_log(avctx, AV_LOG_DEBUG, "Ending audio preroll.\n");
  594. if (ctx->audio && ctx->dlo->EndAudioPreroll() != S_OK) {
  595. av_log(avctx, AV_LOG_ERROR, "Could not end audio preroll!\n");
  596. return AVERROR(EIO);
  597. }
  598. av_log(avctx, AV_LOG_DEBUG, "Starting scheduled playback.\n");
  599. if (ctx->dlo->StartScheduledPlayback(ctx->first_pts * ctx->bmd_tb_num, ctx->bmd_tb_den, 1.0) != S_OK) {
  600. av_log(avctx, AV_LOG_ERROR, "Could not start scheduled playback!\n");
  601. return AVERROR(EIO);
  602. }
  603. ctx->playback_started = 1;
  604. }
  605. return 0;
  606. }
  607. static int decklink_write_audio_packet(AVFormatContext *avctx, AVPacket *pkt)
  608. {
  609. struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
  610. struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
  611. AVStream *st = avctx->streams[pkt->stream_index];
  612. int sample_count;
  613. uint32_t buffered;
  614. uint8_t *outbuf = NULL;
  615. int ret = 0;
  616. ctx->dlo->GetBufferedAudioSampleFrameCount(&buffered);
  617. if (pkt->pts > 1 && !buffered)
  618. av_log(avctx, AV_LOG_WARNING, "There's no buffered audio."
  619. " Audio will misbehave!\n");
  620. if (st->codecpar->codec_id == AV_CODEC_ID_AC3) {
  621. /* Encapsulate AC3 syncframe into SMPTE 337 packet */
  622. int outbuf_size;
  623. ret = create_s337_payload(pkt, &outbuf, &outbuf_size);
  624. if (ret < 0)
  625. return ret;
  626. sample_count = outbuf_size / 4;
  627. } else {
  628. sample_count = pkt->size / (ctx->channels << 1);
  629. outbuf = pkt->data;
  630. }
  631. if (ctx->dlo->ScheduleAudioSamples(outbuf, sample_count, pkt->pts,
  632. bmdAudioSampleRate48kHz, NULL) != S_OK) {
  633. av_log(avctx, AV_LOG_ERROR, "Could not schedule audio samples.\n");
  634. ret = AVERROR(EIO);
  635. }
  636. if (st->codecpar->codec_id == AV_CODEC_ID_AC3)
  637. av_freep(&outbuf);
  638. return ret;
  639. }
  640. static int decklink_write_subtitle_packet(AVFormatContext *avctx, AVPacket *pkt)
  641. {
  642. struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
  643. struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
  644. ff_ccfifo_extractbytes(ctx->cc_fifo, pkt->data, pkt->size);
  645. return 0;
  646. }
  647. extern "C" {
  648. av_cold int ff_decklink_write_header(AVFormatContext *avctx)
  649. {
  650. struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
  651. struct decklink_ctx *ctx;
  652. unsigned int n;
  653. int ret;
  654. ctx = (struct decklink_ctx *) av_mallocz(sizeof(struct decklink_ctx));
  655. if (!ctx)
  656. return AVERROR(ENOMEM);
  657. ctx->list_devices = cctx->list_devices;
  658. ctx->list_formats = cctx->list_formats;
  659. ctx->preroll = cctx->preroll;
  660. ctx->duplex_mode = cctx->duplex_mode;
  661. ctx->first_pts = AV_NOPTS_VALUE;
  662. if (cctx->link > 0 && (unsigned int)cctx->link < FF_ARRAY_ELEMS(decklink_link_conf_map))
  663. ctx->link = decklink_link_conf_map[cctx->link];
  664. cctx->ctx = ctx;
  665. #if CONFIG_LIBKLVANC
  666. if (klvanc_context_create(&ctx->vanc_ctx) < 0) {
  667. av_log(avctx, AV_LOG_ERROR, "Cannot create VANC library context\n");
  668. return AVERROR(ENOMEM);
  669. }
  670. ctx->supports_vanc = 1;
  671. #endif
  672. /* List available devices and exit. */
  673. if (ctx->list_devices) {
  674. ff_decklink_list_devices_legacy(avctx, 0, 1);
  675. return AVERROR_EXIT;
  676. }
  677. ret = ff_decklink_init_device(avctx, avctx->url);
  678. if (ret < 0)
  679. return ret;
  680. /* Get output device. */
  681. if (ctx->dl->QueryInterface(IID_IDeckLinkOutput, (void **) &ctx->dlo) != S_OK) {
  682. av_log(avctx, AV_LOG_ERROR, "Could not open output device from '%s'\n",
  683. avctx->url);
  684. ret = AVERROR(EIO);
  685. goto error;
  686. }
  687. /* List supported formats. */
  688. if (ctx->list_formats) {
  689. ff_decklink_list_formats(avctx);
  690. ret = AVERROR_EXIT;
  691. goto error;
  692. }
  693. /* Setup streams. */
  694. ret = AVERROR(EIO);
  695. for (n = 0; n < avctx->nb_streams; n++) {
  696. AVStream *st = avctx->streams[n];
  697. AVCodecParameters *c = st->codecpar;
  698. if (c->codec_type == AVMEDIA_TYPE_AUDIO) {
  699. if (decklink_setup_audio(avctx, st))
  700. goto error;
  701. } else if (c->codec_type == AVMEDIA_TYPE_VIDEO) {
  702. if (decklink_setup_video(avctx, st))
  703. goto error;
  704. } else if (c->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  705. if (decklink_setup_subtitle(avctx, st))
  706. goto error;
  707. } else {
  708. av_log(avctx, AV_LOG_ERROR, "Unsupported stream type.\n");
  709. goto error;
  710. }
  711. }
  712. for (n = 0; n < avctx->nb_streams; n++) {
  713. AVStream *st = avctx->streams[n];
  714. AVCodecParameters *c = st->codecpar;
  715. if(c->codec_type == AVMEDIA_TYPE_SUBTITLE)
  716. avpriv_set_pts_info(st, 64, ctx->bmd_tb_num, ctx->bmd_tb_den);
  717. }
  718. if (!(ctx->cc_fifo = ff_ccfifo_alloc(av_make_q(ctx->bmd_tb_den, ctx->bmd_tb_num), avctx))) {
  719. av_log(ctx, AV_LOG_ERROR, "Failure to setup CC FIFO queue\n");
  720. ret = AVERROR(ENOMEM);
  721. goto error;
  722. }
  723. return 0;
  724. error:
  725. ff_decklink_cleanup(avctx);
  726. return ret;
  727. }
  728. int ff_decklink_write_packet(AVFormatContext *avctx, AVPacket *pkt)
  729. {
  730. AVStream *st = avctx->streams[pkt->stream_index];
  731. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
  732. return decklink_write_video_packet(avctx, pkt);
  733. else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
  734. return decklink_write_audio_packet(avctx, pkt);
  735. else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
  736. return decklink_write_subtitle_packet(avctx, pkt);
  737. return AVERROR(EIO);
  738. }
  739. int ff_decklink_list_output_devices(AVFormatContext *avctx, struct AVDeviceInfoList *device_list)
  740. {
  741. return ff_decklink_list_devices(avctx, device_list, 0, 1);
  742. }
  743. } /* extern "C" */