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