decklink_dec.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. /*
  2. * Blackmagic DeckLink output
  3. * Copyright (c) 2013-2014 Luca Barbato, Deti Fliegl
  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 <DeckLinkAPI.h>
  22. #include <pthread.h>
  23. #include <semaphore.h>
  24. extern "C" {
  25. #include "libavformat/avformat.h"
  26. #include "libavformat/internal.h"
  27. #include "libavutil/imgutils.h"
  28. }
  29. #include "decklink_common.h"
  30. #include "decklink_dec.h"
  31. static void avpacket_queue_init(AVFormatContext *avctx, AVPacketQueue *q)
  32. {
  33. memset(q, 0, sizeof(AVPacketQueue));
  34. pthread_mutex_init(&q->mutex, NULL);
  35. pthread_cond_init(&q->cond, NULL);
  36. q->avctx = avctx;
  37. }
  38. static void avpacket_queue_flush(AVPacketQueue *q)
  39. {
  40. AVPacketList *pkt, *pkt1;
  41. pthread_mutex_lock(&q->mutex);
  42. for (pkt = q->first_pkt; pkt != NULL; pkt = pkt1) {
  43. pkt1 = pkt->next;
  44. av_free_packet(&pkt->pkt);
  45. av_freep(&pkt);
  46. }
  47. q->last_pkt = NULL;
  48. q->first_pkt = NULL;
  49. q->nb_packets = 0;
  50. q->size = 0;
  51. pthread_mutex_unlock(&q->mutex);
  52. }
  53. static void avpacket_queue_end(AVPacketQueue *q)
  54. {
  55. avpacket_queue_flush(q);
  56. pthread_mutex_destroy(&q->mutex);
  57. pthread_cond_destroy(&q->cond);
  58. }
  59. static unsigned long long avpacket_queue_size(AVPacketQueue *q)
  60. {
  61. unsigned long long size;
  62. pthread_mutex_lock(&q->mutex);
  63. size = q->size;
  64. pthread_mutex_unlock(&q->mutex);
  65. return size;
  66. }
  67. static int avpacket_queue_put(AVPacketQueue *q, AVPacket *pkt)
  68. {
  69. AVPacketList *pkt1;
  70. // Drop Packet if queue size is > 1GB
  71. if (avpacket_queue_size(q) > 1024 * 1024 * 1024 ) {
  72. av_log(q->avctx, AV_LOG_WARNING, "Decklink input buffer overrun!\n");
  73. return -1;
  74. }
  75. /* duplicate the packet */
  76. if (av_dup_packet(pkt) < 0) {
  77. return -1;
  78. }
  79. pkt1 = (AVPacketList *)av_malloc(sizeof(AVPacketList));
  80. if (!pkt1) {
  81. return -1;
  82. }
  83. pkt1->pkt = *pkt;
  84. pkt1->next = NULL;
  85. pthread_mutex_lock(&q->mutex);
  86. if (!q->last_pkt) {
  87. q->first_pkt = pkt1;
  88. } else {
  89. q->last_pkt->next = pkt1;
  90. }
  91. q->last_pkt = pkt1;
  92. q->nb_packets++;
  93. q->size += pkt1->pkt.size + sizeof(*pkt1);
  94. pthread_cond_signal(&q->cond);
  95. pthread_mutex_unlock(&q->mutex);
  96. return 0;
  97. }
  98. static int avpacket_queue_get(AVPacketQueue *q, AVPacket *pkt, int block)
  99. {
  100. AVPacketList *pkt1;
  101. int ret;
  102. pthread_mutex_lock(&q->mutex);
  103. for (;; ) {
  104. pkt1 = q->first_pkt;
  105. if (pkt1) {
  106. q->first_pkt = pkt1->next;
  107. if (!q->first_pkt) {
  108. q->last_pkt = NULL;
  109. }
  110. q->nb_packets--;
  111. q->size -= pkt1->pkt.size + sizeof(*pkt1);
  112. *pkt = pkt1->pkt;
  113. av_free(pkt1);
  114. ret = 1;
  115. break;
  116. } else if (!block) {
  117. ret = 0;
  118. break;
  119. } else {
  120. pthread_cond_wait(&q->cond, &q->mutex);
  121. }
  122. }
  123. pthread_mutex_unlock(&q->mutex);
  124. return ret;
  125. }
  126. class decklink_input_callback : public IDeckLinkInputCallback
  127. {
  128. public:
  129. decklink_input_callback(AVFormatContext *_avctx);
  130. ~decklink_input_callback();
  131. virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv) { return E_NOINTERFACE; }
  132. virtual ULONG STDMETHODCALLTYPE AddRef(void);
  133. virtual ULONG STDMETHODCALLTYPE Release(void);
  134. virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents, IDeckLinkDisplayMode*, BMDDetectedVideoInputFormatFlags);
  135. virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame*, IDeckLinkAudioInputPacket*);
  136. private:
  137. ULONG m_refCount;
  138. pthread_mutex_t m_mutex;
  139. AVFormatContext *avctx;
  140. decklink_ctx *ctx;
  141. int no_video;
  142. int64_t initial_video_pts;
  143. int64_t initial_audio_pts;
  144. };
  145. decklink_input_callback::decklink_input_callback(AVFormatContext *_avctx) : m_refCount(0)
  146. {
  147. avctx = _avctx;
  148. decklink_cctx *cctx = (struct decklink_cctx *) avctx->priv_data;
  149. ctx = (struct decklink_ctx *) cctx->ctx;
  150. initial_audio_pts = initial_video_pts = AV_NOPTS_VALUE;
  151. pthread_mutex_init(&m_mutex, NULL);
  152. }
  153. decklink_input_callback::~decklink_input_callback()
  154. {
  155. pthread_mutex_destroy(&m_mutex);
  156. }
  157. ULONG decklink_input_callback::AddRef(void)
  158. {
  159. pthread_mutex_lock(&m_mutex);
  160. m_refCount++;
  161. pthread_mutex_unlock(&m_mutex);
  162. return (ULONG)m_refCount;
  163. }
  164. ULONG decklink_input_callback::Release(void)
  165. {
  166. pthread_mutex_lock(&m_mutex);
  167. m_refCount--;
  168. pthread_mutex_unlock(&m_mutex);
  169. if (m_refCount == 0) {
  170. delete this;
  171. return 0;
  172. }
  173. return (ULONG)m_refCount;
  174. }
  175. HRESULT decklink_input_callback::VideoInputFrameArrived(
  176. IDeckLinkVideoInputFrame *videoFrame, IDeckLinkAudioInputPacket *audioFrame)
  177. {
  178. void *frameBytes;
  179. void *audioFrameBytes;
  180. BMDTimeValue frameTime;
  181. BMDTimeValue frameDuration;
  182. ctx->frameCount++;
  183. // Handle Video Frame
  184. if (videoFrame) {
  185. AVPacket pkt;
  186. AVCodecContext *c;
  187. av_init_packet(&pkt);
  188. c = ctx->video_st->codec;
  189. if (ctx->frameCount % 25 == 0) {
  190. unsigned long long qsize = avpacket_queue_size(&ctx->queue);
  191. av_log(avctx, AV_LOG_DEBUG,
  192. "Frame received (#%lu) - Valid (%liB) - QSize %fMB\n",
  193. ctx->frameCount,
  194. videoFrame->GetRowBytes() * videoFrame->GetHeight(),
  195. (double)qsize / 1024 / 1024);
  196. }
  197. videoFrame->GetBytes(&frameBytes);
  198. videoFrame->GetStreamTime(&frameTime, &frameDuration,
  199. ctx->video_st->time_base.den);
  200. if (videoFrame->GetFlags() & bmdFrameHasNoInputSource) {
  201. if (videoFrame->GetPixelFormat() == bmdFormat8BitYUV) {
  202. unsigned bars[8] = {
  203. 0xEA80EA80, 0xD292D210, 0xA910A9A5, 0x90229035,
  204. 0x6ADD6ACA, 0x51EF515A, 0x286D28EF, 0x10801080 };
  205. int width = videoFrame->GetWidth();
  206. int height = videoFrame->GetHeight();
  207. unsigned *p = (unsigned *)frameBytes;
  208. for (int y = 0; y < height; y++) {
  209. for (int x = 0; x < width; x += 2)
  210. *p++ = bars[(x * 8) / width];
  211. }
  212. }
  213. if (!no_video) {
  214. av_log(avctx, AV_LOG_WARNING, "Frame received (#%lu) - No input signal detected "
  215. "- Frames dropped %u\n", ctx->frameCount, ++ctx->dropped);
  216. }
  217. no_video = 1;
  218. } else {
  219. if (no_video) {
  220. av_log(avctx, AV_LOG_WARNING, "Frame received (#%lu) - Input returned "
  221. "- Frames dropped %u\n", ctx->frameCount, ++ctx->dropped);
  222. }
  223. no_video = 0;
  224. }
  225. pkt.pts = frameTime / ctx->video_st->time_base.num;
  226. if (initial_video_pts == AV_NOPTS_VALUE) {
  227. initial_video_pts = pkt.pts;
  228. }
  229. pkt.pts -= initial_video_pts;
  230. pkt.dts = pkt.pts;
  231. pkt.duration = frameDuration;
  232. //To be made sure it still applies
  233. pkt.flags |= AV_PKT_FLAG_KEY;
  234. pkt.stream_index = ctx->video_st->index;
  235. pkt.data = (uint8_t *)frameBytes;
  236. pkt.size = videoFrame->GetRowBytes() *
  237. videoFrame->GetHeight();
  238. //fprintf(stderr,"Video Frame size %d ts %d\n", pkt.size, pkt.pts);
  239. c->frame_number++;
  240. if (avpacket_queue_put(&ctx->queue, &pkt) < 0) {
  241. ++ctx->dropped;
  242. }
  243. }
  244. // Handle Audio Frame
  245. if (audioFrame) {
  246. AVCodecContext *c;
  247. AVPacket pkt;
  248. BMDTimeValue audio_pts;
  249. av_init_packet(&pkt);
  250. c = ctx->audio_st->codec;
  251. //hack among hacks
  252. pkt.size = audioFrame->GetSampleFrameCount() * ctx->audio_st->codec->channels * (16 / 8);
  253. audioFrame->GetBytes(&audioFrameBytes);
  254. audioFrame->GetPacketTime(&audio_pts, ctx->audio_st->time_base.den);
  255. pkt.pts = audio_pts / ctx->audio_st->time_base.num;
  256. if (initial_audio_pts == AV_NOPTS_VALUE) {
  257. initial_audio_pts = pkt.pts;
  258. }
  259. pkt.pts -= initial_audio_pts;
  260. pkt.dts = pkt.pts;
  261. //fprintf(stderr,"Audio Frame size %d ts %d\n", pkt.size, pkt.pts);
  262. pkt.flags |= AV_PKT_FLAG_KEY;
  263. pkt.stream_index = ctx->audio_st->index;
  264. pkt.data = (uint8_t *)audioFrameBytes;
  265. c->frame_number++;
  266. if (avpacket_queue_put(&ctx->queue, &pkt) < 0) {
  267. ++ctx->dropped;
  268. }
  269. }
  270. return S_OK;
  271. }
  272. HRESULT decklink_input_callback::VideoInputFormatChanged(
  273. BMDVideoInputFormatChangedEvents events, IDeckLinkDisplayMode *mode,
  274. BMDDetectedVideoInputFormatFlags)
  275. {
  276. return S_OK;
  277. }
  278. static HRESULT decklink_start_input(AVFormatContext *avctx)
  279. {
  280. struct decklink_cctx *cctx = (struct decklink_cctx *) avctx->priv_data;
  281. struct decklink_ctx *ctx = (struct decklink_ctx *) cctx->ctx;
  282. ctx->input_callback = new decklink_input_callback(avctx);
  283. ctx->dli->SetCallback(ctx->input_callback);
  284. return ctx->dli->StartStreams();
  285. }
  286. extern "C" {
  287. av_cold int ff_decklink_read_close(AVFormatContext *avctx)
  288. {
  289. struct decklink_cctx *cctx = (struct decklink_cctx *) avctx->priv_data;
  290. struct decklink_ctx *ctx = (struct decklink_ctx *) cctx->ctx;
  291. if (ctx->capture_started) {
  292. ctx->dli->StopStreams();
  293. ctx->dli->DisableVideoInput();
  294. ctx->dli->DisableAudioInput();
  295. }
  296. if (ctx->dli)
  297. ctx->dli->Release();
  298. if (ctx->dl)
  299. ctx->dl->Release();
  300. avpacket_queue_end(&ctx->queue);
  301. av_freep(&cctx->ctx);
  302. return 0;
  303. }
  304. av_cold int ff_decklink_read_header(AVFormatContext *avctx)
  305. {
  306. struct decklink_cctx *cctx = (struct decklink_cctx *) avctx->priv_data;
  307. struct decklink_ctx *ctx;
  308. IDeckLinkDisplayModeIterator *itermode;
  309. IDeckLinkIterator *iter;
  310. IDeckLink *dl = NULL;
  311. AVStream *st;
  312. HRESULT result;
  313. char fname[1024];
  314. char *tmp;
  315. int mode_num = 0;
  316. ctx = (struct decklink_ctx *) av_mallocz(sizeof(struct decklink_ctx));
  317. if (!ctx)
  318. return AVERROR(ENOMEM);
  319. ctx->list_devices = cctx->list_devices;
  320. ctx->list_formats = cctx->list_formats;
  321. ctx->preroll = cctx->preroll;
  322. cctx->ctx = ctx;
  323. iter = CreateDeckLinkIteratorInstance();
  324. if (!iter) {
  325. av_log(avctx, AV_LOG_ERROR, "Could not create DeckLink iterator\n");
  326. return AVERROR(EIO);
  327. }
  328. /* List available devices. */
  329. if (ctx->list_devices) {
  330. ff_decklink_list_devices(avctx);
  331. return AVERROR_EXIT;
  332. }
  333. strcpy (fname, avctx->filename);
  334. tmp=strchr (fname, '@');
  335. if (tmp != NULL) {
  336. mode_num = atoi (tmp+1);
  337. *tmp = 0;
  338. }
  339. /* Open device. */
  340. while (iter->Next(&dl) == S_OK) {
  341. const char *displayName;
  342. ff_decklink_get_display_name(dl, &displayName);
  343. if (!strcmp(fname, displayName)) {
  344. av_free((void *) displayName);
  345. ctx->dl = dl;
  346. break;
  347. }
  348. av_free((void *) displayName);
  349. dl->Release();
  350. }
  351. iter->Release();
  352. if (!ctx->dl) {
  353. av_log(avctx, AV_LOG_ERROR, "Could not open '%s'\n", fname);
  354. return AVERROR(EIO);
  355. }
  356. /* Get input device. */
  357. if (ctx->dl->QueryInterface(IID_IDeckLinkInput, (void **) &ctx->dli) != S_OK) {
  358. av_log(avctx, AV_LOG_ERROR, "Could not open output device from '%s'\n",
  359. avctx->filename);
  360. ctx->dl->Release();
  361. return AVERROR(EIO);
  362. }
  363. /* List supported formats. */
  364. if (ctx->list_formats) {
  365. ff_decklink_list_formats(avctx, DIRECTION_IN);
  366. ctx->dli->Release();
  367. ctx->dl->Release();
  368. return AVERROR_EXIT;
  369. }
  370. if (ctx->dli->GetDisplayModeIterator(&itermode) != S_OK) {
  371. av_log(avctx, AV_LOG_ERROR, "Could not get Display Mode Iterator\n");
  372. ctx->dl->Release();
  373. return AVERROR(EIO);
  374. }
  375. if (mode_num > 0) {
  376. if (ff_decklink_set_format(avctx, DIRECTION_IN, mode_num) < 0) {
  377. av_log(avctx, AV_LOG_ERROR, "Could not set mode %d for %s\n", mode_num, fname);
  378. goto error;
  379. }
  380. }
  381. itermode->Release();
  382. /* Setup streams. */
  383. st = avformat_new_stream(avctx, NULL);
  384. if (!st) {
  385. av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
  386. goto error;
  387. }
  388. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  389. st->codec->codec_id = AV_CODEC_ID_PCM_S16LE;
  390. st->codec->sample_rate = bmdAudioSampleRate48kHz;
  391. st->codec->channels = 2;
  392. avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
  393. ctx->audio_st=st;
  394. st = avformat_new_stream(avctx, NULL);
  395. if (!st) {
  396. av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
  397. goto error;
  398. }
  399. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  400. st->codec->width = ctx->bmd_width;
  401. st->codec->height = ctx->bmd_height;
  402. st->codec->time_base.den = ctx->bmd_tb_den;
  403. st->codec->time_base.num = ctx->bmd_tb_num;
  404. st->codec->bit_rate = avpicture_get_size(st->codec->pix_fmt, ctx->bmd_width, ctx->bmd_height) * 1/av_q2d(st->codec->time_base) * 8;
  405. if (cctx->v210) {
  406. st->codec->codec_id = AV_CODEC_ID_V210;
  407. st->codec->codec_tag = MKTAG('V', '2', '1', '0');
  408. } else {
  409. st->codec->codec_id = AV_CODEC_ID_RAWVIDEO;
  410. st->codec->pix_fmt = AV_PIX_FMT_UYVY422;
  411. st->codec->codec_tag = MKTAG('U', 'Y', 'V', 'Y');
  412. }
  413. avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
  414. ctx->video_st=st;
  415. result = ctx->dli->EnableAudioInput(bmdAudioSampleRate48kHz, bmdAudioSampleType16bitInteger, 2);
  416. if (result != S_OK) {
  417. av_log(avctx, AV_LOG_ERROR, "Cannot enable audio input\n");
  418. goto error;
  419. }
  420. result = ctx->dli->EnableVideoInput(ctx->bmd_mode,
  421. cctx->v210 ? bmdFormat10BitYUV : bmdFormat8BitYUV,
  422. bmdVideoInputFlagDefault);
  423. if (result != S_OK) {
  424. av_log(avctx, AV_LOG_ERROR, "Cannot enable video input\n");
  425. goto error;
  426. }
  427. avpacket_queue_init (avctx, &ctx->queue);
  428. if (decklink_start_input (avctx) != S_OK) {
  429. av_log(avctx, AV_LOG_ERROR, "Cannot start input stream\n");
  430. goto error;
  431. }
  432. return 0;
  433. error:
  434. ctx->dli->Release();
  435. ctx->dl->Release();
  436. return AVERROR(EIO);
  437. }
  438. int ff_decklink_read_packet(AVFormatContext *avctx, AVPacket *pkt)
  439. {
  440. struct decklink_cctx *cctx = (struct decklink_cctx *) avctx->priv_data;
  441. struct decklink_ctx *ctx = (struct decklink_ctx *) cctx->ctx;
  442. AVFrame *frame = ctx->video_st->codec->coded_frame;
  443. avpacket_queue_get(&ctx->queue, pkt, 1);
  444. if (frame && (ctx->bmd_field_dominance == bmdUpperFieldFirst || ctx->bmd_field_dominance == bmdLowerFieldFirst)) {
  445. frame->interlaced_frame = 1;
  446. if (ctx->bmd_field_dominance == bmdUpperFieldFirst) {
  447. frame->top_field_first = 1;
  448. }
  449. }
  450. return 0;
  451. }
  452. } /* extern "C" */