]> git.sesse.net Git - ffmpeg/blob - libavdevice/decklink_dec.cpp
ffmpeg: Check avcodec_parameters_to_context() for failure
[ffmpeg] / libavdevice / decklink_dec.cpp
1 /*
2  * Blackmagic DeckLink input
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
22 #include <DeckLinkAPI.h>
23
24 #include <pthread.h>
25 #include <semaphore.h>
26
27 extern "C" {
28 #include "config.h"
29 #include "libavformat/avformat.h"
30 #include "libavformat/internal.h"
31 #include "libavutil/avutil.h"
32 #include "libavutil/common.h"
33 #include "libavutil/imgutils.h"
34 #include "libavutil/time.h"
35 #include "libavutil/mathematics.h"
36 #if CONFIG_LIBZVBI
37 #include <libzvbi.h>
38 #endif
39 }
40
41 #include "decklink_common.h"
42 #include "decklink_dec.h"
43
44 #if CONFIG_LIBZVBI
45 static uint8_t calc_parity_and_line_offset(int line)
46 {
47     uint8_t ret = (line < 313) << 5;
48     if (line >= 7 && line <= 22)
49         ret += line;
50     if (line >= 320 && line <= 335)
51         ret += (line - 313);
52     return ret;
53 }
54
55 int teletext_data_unit_from_vbi_data(int line, uint8_t *src, uint8_t *tgt)
56 {
57     vbi_bit_slicer slicer;
58
59     vbi_bit_slicer_init(&slicer, 720, 13500000, 6937500, 6937500, 0x00aaaae4, 0xffff, 18, 6, 42 * 8, VBI_MODULATION_NRZ_MSB, VBI_PIXFMT_UYVY);
60
61     if (vbi_bit_slice(&slicer, src, tgt + 4) == FALSE)
62         return -1;
63
64     tgt[0] = 0x02; // data_unit_id
65     tgt[1] = 0x2c; // data_unit_length
66     tgt[2] = calc_parity_and_line_offset(line); // field_parity, line_offset
67     tgt[3] = 0xe4; // framing code
68
69     return 0;
70 }
71 #endif
72
73 static void avpacket_queue_init(AVFormatContext *avctx, AVPacketQueue *q)
74 {
75     memset(q, 0, sizeof(AVPacketQueue));
76     pthread_mutex_init(&q->mutex, NULL);
77     pthread_cond_init(&q->cond, NULL);
78     q->avctx = avctx;
79 }
80
81 static void avpacket_queue_flush(AVPacketQueue *q)
82 {
83     AVPacketList *pkt, *pkt1;
84
85     pthread_mutex_lock(&q->mutex);
86     for (pkt = q->first_pkt; pkt != NULL; pkt = pkt1) {
87         pkt1 = pkt->next;
88         av_packet_unref(&pkt->pkt);
89         av_freep(&pkt);
90     }
91     q->last_pkt   = NULL;
92     q->first_pkt  = NULL;
93     q->nb_packets = 0;
94     q->size       = 0;
95     pthread_mutex_unlock(&q->mutex);
96 }
97
98 static void avpacket_queue_end(AVPacketQueue *q)
99 {
100     avpacket_queue_flush(q);
101     pthread_mutex_destroy(&q->mutex);
102     pthread_cond_destroy(&q->cond);
103 }
104
105 static unsigned long long avpacket_queue_size(AVPacketQueue *q)
106 {
107     unsigned long long size;
108     pthread_mutex_lock(&q->mutex);
109     size = q->size;
110     pthread_mutex_unlock(&q->mutex);
111     return size;
112 }
113
114 static int avpacket_queue_put(AVPacketQueue *q, AVPacket *pkt)
115 {
116     AVPacketList *pkt1;
117
118     // Drop Packet if queue size is > 1GB
119     if (avpacket_queue_size(q) >  1024 * 1024 * 1024 ) {
120         av_log(q->avctx, AV_LOG_WARNING,  "Decklink input buffer overrun!\n");
121         return -1;
122     }
123     /* duplicate the packet */
124     if (av_dup_packet(pkt) < 0) {
125         return -1;
126     }
127
128     pkt1 = (AVPacketList *)av_malloc(sizeof(AVPacketList));
129     if (!pkt1) {
130         return -1;
131     }
132     pkt1->pkt  = *pkt;
133     pkt1->next = NULL;
134
135     pthread_mutex_lock(&q->mutex);
136
137     if (!q->last_pkt) {
138         q->first_pkt = pkt1;
139     } else {
140         q->last_pkt->next = pkt1;
141     }
142
143     q->last_pkt = pkt1;
144     q->nb_packets++;
145     q->size += pkt1->pkt.size + sizeof(*pkt1);
146
147     pthread_cond_signal(&q->cond);
148
149     pthread_mutex_unlock(&q->mutex);
150     return 0;
151 }
152
153 static int avpacket_queue_get(AVPacketQueue *q, AVPacket *pkt, int block)
154 {
155     AVPacketList *pkt1;
156     int ret;
157
158     pthread_mutex_lock(&q->mutex);
159
160     for (;; ) {
161         pkt1 = q->first_pkt;
162         if (pkt1) {
163             q->first_pkt = pkt1->next;
164             if (!q->first_pkt) {
165                 q->last_pkt = NULL;
166             }
167             q->nb_packets--;
168             q->size -= pkt1->pkt.size + sizeof(*pkt1);
169             *pkt     = pkt1->pkt;
170             av_free(pkt1);
171             ret = 1;
172             break;
173         } else if (!block) {
174             ret = 0;
175             break;
176         } else {
177             pthread_cond_wait(&q->cond, &q->mutex);
178         }
179     }
180     pthread_mutex_unlock(&q->mutex);
181     return ret;
182 }
183
184 class decklink_input_callback : public IDeckLinkInputCallback
185 {
186 public:
187         decklink_input_callback(AVFormatContext *_avctx);
188         ~decklink_input_callback();
189
190         virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv) { return E_NOINTERFACE; }
191         virtual ULONG STDMETHODCALLTYPE AddRef(void);
192         virtual ULONG STDMETHODCALLTYPE  Release(void);
193         virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents, IDeckLinkDisplayMode*, BMDDetectedVideoInputFormatFlags);
194         virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame*, IDeckLinkAudioInputPacket*);
195
196 private:
197         ULONG           m_refCount;
198         pthread_mutex_t m_mutex;
199         AVFormatContext *avctx;
200         decklink_ctx    *ctx;
201         int no_video;
202         int64_t initial_video_pts;
203         int64_t initial_audio_pts;
204 };
205
206 decklink_input_callback::decklink_input_callback(AVFormatContext *_avctx) : m_refCount(0)
207 {
208     avctx = _avctx;
209     decklink_cctx       *cctx = (struct decklink_cctx *)avctx->priv_data;
210     ctx = (struct decklink_ctx *)cctx->ctx;
211     initial_audio_pts = initial_video_pts = AV_NOPTS_VALUE;
212     pthread_mutex_init(&m_mutex, NULL);
213 }
214
215 decklink_input_callback::~decklink_input_callback()
216 {
217     pthread_mutex_destroy(&m_mutex);
218 }
219
220 ULONG decklink_input_callback::AddRef(void)
221 {
222     pthread_mutex_lock(&m_mutex);
223     m_refCount++;
224     pthread_mutex_unlock(&m_mutex);
225
226     return (ULONG)m_refCount;
227 }
228
229 ULONG decklink_input_callback::Release(void)
230 {
231     pthread_mutex_lock(&m_mutex);
232     m_refCount--;
233     pthread_mutex_unlock(&m_mutex);
234
235     if (m_refCount == 0) {
236         delete this;
237         return 0;
238     }
239
240     return (ULONG)m_refCount;
241 }
242
243 static int64_t get_pkt_pts(IDeckLinkVideoInputFrame *videoFrame,
244                            IDeckLinkAudioInputPacket *audioFrame,
245                            int64_t wallclock,
246                            DecklinkPtsSource pts_src,
247                            AVRational time_base, int64_t *initial_pts)
248 {
249     int64_t pts = AV_NOPTS_VALUE;
250     BMDTimeValue bmd_pts;
251     BMDTimeValue bmd_duration;
252     HRESULT res = E_INVALIDARG;
253     switch (pts_src) {
254         case PTS_SRC_AUDIO:
255             if (audioFrame)
256                 res = audioFrame->GetPacketTime(&bmd_pts, time_base.den);
257             break;
258         case PTS_SRC_VIDEO:
259             if (videoFrame)
260                 res = videoFrame->GetStreamTime(&bmd_pts, &bmd_duration, time_base.den);
261             break;
262         case PTS_SRC_REFERENCE:
263             if (videoFrame)
264                 res = videoFrame->GetHardwareReferenceTimestamp(time_base.den, &bmd_pts, &bmd_duration);
265             break;
266         case PTS_SRC_WALLCLOCK:
267             pts = av_rescale_q(wallclock, AV_TIME_BASE_Q, time_base);
268             break;
269     }
270     if (res == S_OK)
271         pts = bmd_pts / time_base.num;
272
273     if (pts != AV_NOPTS_VALUE && *initial_pts == AV_NOPTS_VALUE)
274         *initial_pts = pts;
275     if (*initial_pts != AV_NOPTS_VALUE)
276         pts -= *initial_pts;
277
278     return pts;
279 }
280
281 HRESULT decklink_input_callback::VideoInputFrameArrived(
282     IDeckLinkVideoInputFrame *videoFrame, IDeckLinkAudioInputPacket *audioFrame)
283 {
284     void *frameBytes;
285     void *audioFrameBytes;
286     BMDTimeValue frameTime;
287     BMDTimeValue frameDuration;
288     int64_t wallclock = 0;
289
290     ctx->frameCount++;
291     if (ctx->audio_pts_source == PTS_SRC_WALLCLOCK || ctx->video_pts_source == PTS_SRC_WALLCLOCK)
292         wallclock = av_gettime_relative();
293
294     // Handle Video Frame
295     if (videoFrame) {
296         AVPacket pkt;
297         av_init_packet(&pkt);
298         if (ctx->frameCount % 25 == 0) {
299             unsigned long long qsize = avpacket_queue_size(&ctx->queue);
300             av_log(avctx, AV_LOG_DEBUG,
301                     "Frame received (#%lu) - Valid (%liB) - QSize %fMB\n",
302                     ctx->frameCount,
303                     videoFrame->GetRowBytes() * videoFrame->GetHeight(),
304                     (double)qsize / 1024 / 1024);
305         }
306
307         videoFrame->GetBytes(&frameBytes);
308         videoFrame->GetStreamTime(&frameTime, &frameDuration,
309                                   ctx->video_st->time_base.den);
310
311         if (videoFrame->GetFlags() & bmdFrameHasNoInputSource) {
312             if (ctx->draw_bars && videoFrame->GetPixelFormat() == bmdFormat8BitYUV) {
313                 unsigned bars[8] = {
314                     0xEA80EA80, 0xD292D210, 0xA910A9A5, 0x90229035,
315                     0x6ADD6ACA, 0x51EF515A, 0x286D28EF, 0x10801080 };
316                 int width  = videoFrame->GetWidth();
317                 int height = videoFrame->GetHeight();
318                 unsigned *p = (unsigned *)frameBytes;
319
320                 for (int y = 0; y < height; y++) {
321                     for (int x = 0; x < width; x += 2)
322                         *p++ = bars[(x * 8) / width];
323                 }
324             }
325
326             if (!no_video) {
327                 av_log(avctx, AV_LOG_WARNING, "Frame received (#%lu) - No input signal detected "
328                         "- Frames dropped %u\n", ctx->frameCount, ++ctx->dropped);
329             }
330             no_video = 1;
331         } else {
332             if (no_video) {
333                 av_log(avctx, AV_LOG_WARNING, "Frame received (#%lu) - Input returned "
334                         "- Frames dropped %u\n", ctx->frameCount, ++ctx->dropped);
335             }
336             no_video = 0;
337         }
338
339         pkt.pts = get_pkt_pts(videoFrame, audioFrame, wallclock, ctx->video_pts_source, ctx->video_st->time_base, &initial_video_pts);
340         pkt.dts = pkt.pts;
341
342         pkt.duration = frameDuration;
343         //To be made sure it still applies
344         pkt.flags       |= AV_PKT_FLAG_KEY;
345         pkt.stream_index = ctx->video_st->index;
346         pkt.data         = (uint8_t *)frameBytes;
347         pkt.size         = videoFrame->GetRowBytes() *
348                            videoFrame->GetHeight();
349         //fprintf(stderr,"Video Frame size %d ts %d\n", pkt.size, pkt.pts);
350
351 #if CONFIG_LIBZVBI
352         if (!no_video && ctx->teletext_lines && videoFrame->GetPixelFormat() == bmdFormat8BitYUV && videoFrame->GetWidth() == 720) {
353             IDeckLinkVideoFrameAncillary *vanc;
354             AVPacket txt_pkt;
355             uint8_t txt_buf0[1611]; // max 35 * 46 bytes decoded teletext lines + 1 byte data_identifier
356             uint8_t *txt_buf = txt_buf0;
357
358             if (videoFrame->GetAncillaryData(&vanc) == S_OK) {
359                 int i;
360                 int64_t line_mask = 1;
361                 txt_buf[0] = 0x10;    // data_identifier - EBU_data
362                 txt_buf++;
363                 for (i = 6; i < 336; i++, line_mask <<= 1) {
364                     uint8_t *buf;
365                     if ((ctx->teletext_lines & line_mask) && vanc->GetBufferForVerticalBlankingLine(i, (void**)&buf) == S_OK) {
366                         if (teletext_data_unit_from_vbi_data(i, buf, txt_buf) >= 0)
367                             txt_buf += 46;
368                     }
369                     if (i == 22)
370                         i = 317;
371                 }
372                 vanc->Release();
373                 if (txt_buf - txt_buf0 > 1) {
374                     int stuffing_units = (4 - ((45 + txt_buf - txt_buf0) / 46) % 4) % 4;
375                     while (stuffing_units--) {
376                         memset(txt_buf, 0xff, 46);
377                         txt_buf[1] = 0x2c; // data_unit_length
378                         txt_buf += 46;
379                     }
380                     av_init_packet(&txt_pkt);
381                     txt_pkt.pts = pkt.pts;
382                     txt_pkt.dts = pkt.dts;
383                     txt_pkt.stream_index = ctx->teletext_st->index;
384                     txt_pkt.data = txt_buf0;
385                     txt_pkt.size = txt_buf - txt_buf0;
386                     if (avpacket_queue_put(&ctx->queue, &txt_pkt) < 0) {
387                         ++ctx->dropped;
388                     }
389                 }
390             }
391         }
392 #endif
393
394         if (avpacket_queue_put(&ctx->queue, &pkt) < 0) {
395             ++ctx->dropped;
396         }
397     }
398
399     // Handle Audio Frame
400     if (audioFrame) {
401         AVPacket pkt;
402         BMDTimeValue audio_pts;
403         av_init_packet(&pkt);
404
405         //hack among hacks
406         pkt.size = audioFrame->GetSampleFrameCount() * ctx->audio_st->codecpar->channels * (16 / 8);
407         audioFrame->GetBytes(&audioFrameBytes);
408         audioFrame->GetPacketTime(&audio_pts, ctx->audio_st->time_base.den);
409         pkt.pts = get_pkt_pts(videoFrame, audioFrame, wallclock, ctx->audio_pts_source, ctx->audio_st->time_base, &initial_audio_pts);
410         pkt.dts = pkt.pts;
411
412         //fprintf(stderr,"Audio Frame size %d ts %d\n", pkt.size, pkt.pts);
413         pkt.flags       |= AV_PKT_FLAG_KEY;
414         pkt.stream_index = ctx->audio_st->index;
415         pkt.data         = (uint8_t *)audioFrameBytes;
416
417         if (avpacket_queue_put(&ctx->queue, &pkt) < 0) {
418             ++ctx->dropped;
419         }
420     }
421
422     return S_OK;
423 }
424
425 HRESULT decklink_input_callback::VideoInputFormatChanged(
426     BMDVideoInputFormatChangedEvents events, IDeckLinkDisplayMode *mode,
427     BMDDetectedVideoInputFormatFlags)
428 {
429     return S_OK;
430 }
431
432 static HRESULT decklink_start_input(AVFormatContext *avctx)
433 {
434     struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
435     struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
436
437     ctx->input_callback = new decklink_input_callback(avctx);
438     ctx->dli->SetCallback(ctx->input_callback);
439     return ctx->dli->StartStreams();
440 }
441
442 extern "C" {
443
444 av_cold int ff_decklink_read_close(AVFormatContext *avctx)
445 {
446     struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
447     struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
448
449     if (ctx->capture_started) {
450         ctx->dli->StopStreams();
451         ctx->dli->DisableVideoInput();
452         ctx->dli->DisableAudioInput();
453     }
454
455     ff_decklink_cleanup(avctx);
456     avpacket_queue_end(&ctx->queue);
457
458     av_freep(&cctx->ctx);
459
460     return 0;
461 }
462
463 av_cold int ff_decklink_read_header(AVFormatContext *avctx)
464 {
465     struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
466     struct decklink_ctx *ctx;
467     AVStream *st;
468     HRESULT result;
469     char fname[1024];
470     char *tmp;
471     int mode_num = 0;
472     int ret;
473
474     ctx = (struct decklink_ctx *) av_mallocz(sizeof(struct decklink_ctx));
475     if (!ctx)
476         return AVERROR(ENOMEM);
477     ctx->list_devices = cctx->list_devices;
478     ctx->list_formats = cctx->list_formats;
479     ctx->teletext_lines = cctx->teletext_lines;
480     ctx->preroll      = cctx->preroll;
481     ctx->duplex_mode  = cctx->duplex_mode;
482     if (cctx->video_input > 0 && (unsigned int)cctx->video_input < FF_ARRAY_ELEMS(decklink_video_connection_map))
483         ctx->video_input = decklink_video_connection_map[cctx->video_input];
484     if (cctx->audio_input > 0 && (unsigned int)cctx->audio_input < FF_ARRAY_ELEMS(decklink_audio_connection_map))
485         ctx->audio_input = decklink_audio_connection_map[cctx->audio_input];
486     ctx->audio_pts_source = cctx->audio_pts_source;
487     ctx->video_pts_source = cctx->video_pts_source;
488     ctx->draw_bars = cctx->draw_bars;
489     cctx->ctx = ctx;
490
491 #if !CONFIG_LIBZVBI
492     if (ctx->teletext_lines) {
493         av_log(avctx, AV_LOG_ERROR, "Libzvbi support is needed for capturing teletext, please recompile FFmpeg.\n");
494         return AVERROR(ENOSYS);
495     }
496 #endif
497
498     /* Check audio channel option for valid values: 2, 8 or 16 */
499     switch (cctx->audio_channels) {
500         case 2:
501         case 8:
502         case 16:
503             break;
504         default:
505             av_log(avctx, AV_LOG_ERROR, "Value of channels option must be one of 2, 8 or 16\n");
506             return AVERROR(EINVAL);
507     }
508
509     /* List available devices. */
510     if (ctx->list_devices) {
511         ff_decklink_list_devices(avctx);
512         return AVERROR_EXIT;
513     }
514
515     strcpy (fname, avctx->filename);
516     tmp=strchr (fname, '@');
517     if (tmp != NULL) {
518         mode_num = atoi (tmp+1);
519         *tmp = 0;
520     }
521
522     ret = ff_decklink_init_device(avctx, fname);
523     if (ret < 0)
524         return ret;
525
526     /* Get input device. */
527     if (ctx->dl->QueryInterface(IID_IDeckLinkInput, (void **) &ctx->dli) != S_OK) {
528         av_log(avctx, AV_LOG_ERROR, "Could not open input device from '%s'\n",
529                avctx->filename);
530         ret = AVERROR(EIO);
531         goto error;
532     }
533
534     /* List supported formats. */
535     if (ctx->list_formats) {
536         ff_decklink_list_formats(avctx, DIRECTION_IN);
537         ret = AVERROR_EXIT;
538         goto error;
539     }
540
541     if (mode_num > 0) {
542         if (ff_decklink_set_format(avctx, DIRECTION_IN, mode_num) < 0) {
543             av_log(avctx, AV_LOG_ERROR, "Could not set mode %d for %s\n", mode_num, fname);
544             ret = AVERROR(EIO);
545             goto error;
546         }
547     }
548
549     /* Setup streams. */
550     st = avformat_new_stream(avctx, NULL);
551     if (!st) {
552         av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
553         ret = AVERROR(ENOMEM);
554         goto error;
555     }
556     st->codecpar->codec_type  = AVMEDIA_TYPE_AUDIO;
557     st->codecpar->codec_id    = AV_CODEC_ID_PCM_S16LE;
558     st->codecpar->sample_rate = bmdAudioSampleRate48kHz;
559     st->codecpar->channels    = cctx->audio_channels;
560     avpriv_set_pts_info(st, 64, 1, 1000000);  /* 64 bits pts in us */
561     ctx->audio_st=st;
562
563     st = avformat_new_stream(avctx, NULL);
564     if (!st) {
565         av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
566         ret = AVERROR(ENOMEM);
567         goto error;
568     }
569     st->codecpar->codec_type  = AVMEDIA_TYPE_VIDEO;
570     st->codecpar->width       = ctx->bmd_width;
571     st->codecpar->height      = ctx->bmd_height;
572
573     st->time_base.den      = ctx->bmd_tb_den;
574     st->time_base.num      = ctx->bmd_tb_num;
575     av_stream_set_r_frame_rate(st, av_make_q(st->time_base.den, st->time_base.num));
576
577     if (cctx->v210) {
578         st->codecpar->codec_id    = AV_CODEC_ID_V210;
579         st->codecpar->codec_tag   = MKTAG('V', '2', '1', '0');
580         st->codecpar->bit_rate    = av_rescale(ctx->bmd_width * ctx->bmd_height * 64, st->time_base.den, st->time_base.num * 3);
581     } else {
582         st->codecpar->codec_id    = AV_CODEC_ID_RAWVIDEO;
583         st->codecpar->format      = AV_PIX_FMT_UYVY422;
584         st->codecpar->codec_tag   = MKTAG('U', 'Y', 'V', 'Y');
585         st->codecpar->bit_rate    = av_rescale(ctx->bmd_width * ctx->bmd_height * 16, st->time_base.den, st->time_base.num);
586     }
587
588     avpriv_set_pts_info(st, 64, 1, 1000000);  /* 64 bits pts in us */
589
590     ctx->video_st=st;
591
592     if (ctx->teletext_lines) {
593         st = avformat_new_stream(avctx, NULL);
594         if (!st) {
595             av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
596             ret = AVERROR(ENOMEM);
597             goto error;
598         }
599         st->codecpar->codec_type  = AVMEDIA_TYPE_SUBTITLE;
600         st->time_base.den         = ctx->bmd_tb_den;
601         st->time_base.num         = ctx->bmd_tb_num;
602         st->codecpar->codec_id    = AV_CODEC_ID_DVB_TELETEXT;
603         avpriv_set_pts_info(st, 64, 1, 1000000);  /* 64 bits pts in us */
604         ctx->teletext_st = st;
605     }
606
607     av_log(avctx, AV_LOG_VERBOSE, "Using %d input audio channels\n", ctx->audio_st->codecpar->channels);
608     result = ctx->dli->EnableAudioInput(bmdAudioSampleRate48kHz, bmdAudioSampleType16bitInteger, ctx->audio_st->codecpar->channels);
609
610     if (result != S_OK) {
611         av_log(avctx, AV_LOG_ERROR, "Cannot enable audio input\n");
612         ret = AVERROR(EIO);
613         goto error;
614     }
615
616     result = ctx->dli->EnableVideoInput(ctx->bmd_mode,
617                                         cctx->v210 ? bmdFormat10BitYUV : bmdFormat8BitYUV,
618                                         bmdVideoInputFlagDefault);
619
620     if (result != S_OK) {
621         av_log(avctx, AV_LOG_ERROR, "Cannot enable video input\n");
622         ret = AVERROR(EIO);
623         goto error;
624     }
625
626     avpacket_queue_init (avctx, &ctx->queue);
627
628     if (decklink_start_input (avctx) != S_OK) {
629         av_log(avctx, AV_LOG_ERROR, "Cannot start input stream\n");
630         ret = AVERROR(EIO);
631         goto error;
632     }
633
634     return 0;
635
636 error:
637     ff_decklink_cleanup(avctx);
638     return ret;
639 }
640
641 int ff_decklink_read_packet(AVFormatContext *avctx, AVPacket *pkt)
642 {
643     struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
644     struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
645     AVFrame *frame = ctx->video_st->codec->coded_frame;
646
647     avpacket_queue_get(&ctx->queue, pkt, 1);
648     if (frame && (ctx->bmd_field_dominance == bmdUpperFieldFirst || ctx->bmd_field_dominance == bmdLowerFieldFirst)) {
649         frame->interlaced_frame = 1;
650         if (ctx->bmd_field_dominance == bmdUpperFieldFirst) {
651             frame->top_field_first = 1;
652         }
653     }
654
655     return 0;
656 }
657
658 } /* extern "C" */