decklink_enc.cpp 33 KB

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