You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

538 lines
15KB

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