]> git.sesse.net Git - ffmpeg/blob - libavdevice/decklink_dec.cpp
e97a4402ea319aa57284ff26e4688f2526ad2fb1
[ffmpeg] / libavdevice / decklink_dec.cpp
1 /*
2  * Blackmagic DeckLink input
3  * Copyright (c) 2013-2014 Luca Barbato, Deti Fliegl
4  * Copyright (c) 2014 Rafaël Carré
5  * Copyright (c) 2017 Akamai Technologies, Inc.
6  *
7  * This file is part of FFmpeg.
8  *
9  * FFmpeg is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * FFmpeg is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with FFmpeg; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22  */
23
24 /* Include internal.h first to avoid conflict between winsock.h (used by
25  * DeckLink headers) and winsock2.h (used by libavformat) in MSVC++ builds */
26 extern "C" {
27 #include "libavformat/internal.h"
28 }
29
30 #include <DeckLinkAPI.h>
31
32 extern "C" {
33 #include "config.h"
34 #include "libavformat/avformat.h"
35 #include "libavutil/avassert.h"
36 #include "libavutil/avutil.h"
37 #include "libavutil/common.h"
38 #include "libavutil/imgutils.h"
39 #include "libavutil/intreadwrite.h"
40 #include "libavutil/time.h"
41 #include "libavutil/mathematics.h"
42 #include "libavutil/reverse.h"
43 #include "avdevice.h"
44 #if CONFIG_LIBZVBI
45 #include <libzvbi.h>
46 #endif
47 }
48
49 #include "decklink_common.h"
50 #include "decklink_dec.h"
51
52 #define MAX_WIDTH_VANC 1920
53 const BMDDisplayMode AUTODETECT_DEFAULT_MODE = bmdModeNTSC;
54
55 typedef struct VANCLineNumber {
56     BMDDisplayMode mode;
57     int vanc_start;
58     int field0_vanc_end;
59     int field1_vanc_start;
60     int vanc_end;
61 } VANCLineNumber;
62
63 /* These VANC line numbers need not be very accurate. In any case
64  * GetBufferForVerticalBlankingLine() will return an error when invalid
65  * ancillary line number was requested. We just need to make sure that the
66  * entire VANC region is covered, while making sure we don't decode VANC of
67  * another source during switching*/
68 static VANCLineNumber vanc_line_numbers[] = {
69     /* SD Modes */
70
71     {bmdModeNTSC, 11, 19, 274, 282},
72     {bmdModeNTSC2398, 11, 19, 274, 282},
73     {bmdModePAL, 7, 22, 320, 335},
74     {bmdModeNTSCp, 11, -1, -1, 39},
75     {bmdModePALp, 7, -1, -1, 45},
76
77     /* HD 1080 Modes */
78
79     {bmdModeHD1080p2398, 8, -1, -1, 42},
80     {bmdModeHD1080p24, 8, -1, -1, 42},
81     {bmdModeHD1080p25, 8, -1, -1, 42},
82     {bmdModeHD1080p2997, 8, -1, -1, 42},
83     {bmdModeHD1080p30, 8, -1, -1, 42},
84     {bmdModeHD1080i50, 8, 20, 570, 585},
85     {bmdModeHD1080i5994, 8, 20, 570, 585},
86     {bmdModeHD1080i6000, 8, 20, 570, 585},
87     {bmdModeHD1080p50, 8, -1, -1, 42},
88     {bmdModeHD1080p5994, 8, -1, -1, 42},
89     {bmdModeHD1080p6000, 8, -1, -1, 42},
90
91      /* HD 720 Modes */
92
93     {bmdModeHD720p50, 8, -1, -1, 26},
94     {bmdModeHD720p5994, 8, -1, -1, 26},
95     {bmdModeHD720p60, 8, -1, -1, 26},
96
97     /* For all other modes, for which we don't support VANC */
98     {bmdModeUnknown, 0, -1, -1, -1}
99 };
100
101 static int get_vanc_line_idx(BMDDisplayMode mode)
102 {
103     unsigned int i;
104     for (i = 0; i < FF_ARRAY_ELEMS(vanc_line_numbers); i++) {
105         if (mode == vanc_line_numbers[i].mode)
106             return i;
107     }
108     /* Return the VANC idx for Unknown mode */
109     return i - 1;
110 }
111
112 static inline void clear_parity_bits(uint16_t *buf, int len) {
113     int i;
114     for (i = 0; i < len; i++)
115         buf[i] &= 0xff;
116 }
117
118 static int check_vanc_parity_checksum(uint16_t *buf, int len, uint16_t checksum) {
119     int i;
120     uint16_t vanc_sum = 0;
121     for (i = 3; i < len - 1; i++) {
122         uint16_t v = buf[i];
123         int np = v >> 8;
124         int p = av_parity(v & 0xff);
125         if ((!!p ^ !!(v & 0x100)) || (np != 1 && np != 2)) {
126             // Parity check failed
127             return -1;
128         }
129         vanc_sum += v;
130     }
131     vanc_sum &= 0x1ff;
132     vanc_sum |= ((~vanc_sum & 0x100) << 1);
133     if (checksum != vanc_sum) {
134         // Checksum verification failed
135         return -1;
136     }
137     return 0;
138 }
139
140 /* The 10-bit VANC data is packed in V210, we only need the luma component. */
141 static void extract_luma_from_v210(uint16_t *dst, const uint8_t *src, int width)
142 {
143     int i;
144     for (i = 0; i < width / 3; i++) {
145         *dst++ = (src[1] >> 2) + ((src[2] & 15) << 6);
146         *dst++ =  src[4]       + ((src[5] &  3) << 8);
147         *dst++ = (src[6] >> 4) + ((src[7] & 63) << 4);
148         src += 8;
149     }
150 }
151
152 static void unpack_v210(uint16_t *dst, const uint8_t *src, int width)
153 {
154     int i;
155     for (i = 0; i < width * 2 / 3; i++) {
156         *dst++ =  src[0]       + ((src[1] & 3)  << 8);
157         *dst++ = (src[1] >> 2) + ((src[2] & 15) << 6);
158         *dst++ = (src[2] >> 4) + ((src[3] & 63) << 4);
159         src += 4;
160     }
161 }
162
163 static uint8_t calc_parity_and_line_offset(int line)
164 {
165     uint8_t ret = (line < 313) << 5;
166     if (line >= 7 && line <= 22)
167         ret += line;
168     if (line >= 320 && line <= 335)
169         ret += (line - 313);
170     return ret;
171 }
172
173 static void fill_data_unit_head(int line, uint8_t *tgt)
174 {
175     tgt[0] = 0x02; // data_unit_id
176     tgt[1] = 0x2c; // data_unit_length
177     tgt[2] = calc_parity_and_line_offset(line); // field_parity, line_offset
178     tgt[3] = 0xe4; // framing code
179 }
180
181 #if CONFIG_LIBZVBI
182 static uint8_t* teletext_data_unit_from_vbi_data(int line, uint8_t *src, uint8_t *tgt, vbi_pixfmt fmt)
183 {
184     vbi_bit_slicer slicer;
185
186     vbi_bit_slicer_init(&slicer, 720, 13500000, 6937500, 6937500, 0x00aaaae4, 0xffff, 18, 6, 42 * 8, VBI_MODULATION_NRZ_MSB, fmt);
187
188     if (vbi_bit_slice(&slicer, src, tgt + 4) == FALSE)
189         return tgt;
190
191     fill_data_unit_head(line, tgt);
192
193     return tgt + 46;
194 }
195
196 static uint8_t* teletext_data_unit_from_vbi_data_10bit(int line, uint8_t *src, uint8_t *tgt)
197 {
198     uint8_t y[720];
199     uint8_t *py = y;
200     uint8_t *pend = y + 720;
201     /* The 10-bit VBI data is packed in V210, but libzvbi only supports 8-bit,
202      * so we extract the 8 MSBs of the luma component, that is enough for
203      * teletext bit slicing. */
204     while (py < pend) {
205         *py++ = (src[1] >> 4) + ((src[2] & 15) << 4);
206         *py++ = (src[4] >> 2) + ((src[5] & 3 ) << 6);
207         *py++ = (src[6] >> 6) + ((src[7] & 63) << 2);
208         src += 8;
209     }
210     return teletext_data_unit_from_vbi_data(line, y, tgt, VBI_PIXFMT_YUV420);
211 }
212 #endif
213
214 static uint8_t* teletext_data_unit_from_op47_vbi_packet(int line, uint16_t *py, uint8_t *tgt)
215 {
216     int i;
217
218     if (py[0] != 0x255 || py[1] != 0x255 || py[2] != 0x227)
219         return tgt;
220
221     fill_data_unit_head(line, tgt);
222
223     py += 3;
224     tgt += 4;
225
226     for (i = 0; i < 42; i++)
227        *tgt++ = ff_reverse[py[i] & 255];
228
229     return tgt;
230 }
231
232 static int linemask_matches(int line, int64_t mask)
233 {
234     int shift = -1;
235     if (line >= 6 && line <= 22)
236         shift = line - 6;
237     if (line >= 318 && line <= 335)
238         shift = line - 318 + 17;
239     return shift >= 0 && ((1ULL << shift) & mask);
240 }
241
242 static uint8_t* teletext_data_unit_from_op47_data(uint16_t *py, uint16_t *pend, uint8_t *tgt, int64_t wanted_lines)
243 {
244     if (py < pend - 9) {
245         if (py[0] == 0x151 && py[1] == 0x115 && py[3] == 0x102) {       // identifier, identifier, format code for WST teletext
246             uint16_t *descriptors = py + 4;
247             int i;
248             py += 9;
249             for (i = 0; i < 5 && py < pend - 45; i++, py += 45) {
250                 int line = (descriptors[i] & 31) + (!(descriptors[i] & 128)) * 313;
251                 if (line && linemask_matches(line, wanted_lines))
252                     tgt = teletext_data_unit_from_op47_vbi_packet(line, py, tgt);
253             }
254         }
255     }
256     return tgt;
257 }
258
259 static uint8_t* teletext_data_unit_from_ancillary_packet(uint16_t *py, uint16_t *pend, uint8_t *tgt, int64_t wanted_lines, int allow_multipacket)
260 {
261     uint16_t did = py[0];                                               // data id
262     uint16_t sdid = py[1];                                              // secondary data id
263     uint16_t dc = py[2] & 255;                                          // data count
264     py += 3;
265     pend = FFMIN(pend, py + dc);
266     if (did == 0x143 && sdid == 0x102) {                                // subtitle distribution packet
267         tgt = teletext_data_unit_from_op47_data(py, pend, tgt, wanted_lines);
268     } else if (allow_multipacket && did == 0x143 && sdid == 0x203) {    // VANC multipacket
269         py += 2;                                                        // priority, line/field
270         while (py < pend - 3) {
271             tgt = teletext_data_unit_from_ancillary_packet(py, pend, tgt, wanted_lines, 0);
272             py += 4 + (py[2] & 255);                                    // ndid, nsdid, ndc, line/field
273         }
274     }
275     return tgt;
276 }
277
278 static uint8_t *vanc_to_cc(AVFormatContext *avctx, uint16_t *buf, size_t words,
279                            unsigned &cc_count)
280 {
281     size_t i, len = (buf[5] & 0xff) + 6 + 1;
282     uint8_t cdp_sum, rate;
283     uint16_t hdr, ftr;
284     uint8_t *cc;
285     uint16_t *cdp = &buf[6]; // CDP follows
286     if (cdp[0] != 0x96 || cdp[1] != 0x69) {
287         av_log(avctx, AV_LOG_WARNING, "Invalid CDP header 0x%.2x 0x%.2x\n", cdp[0], cdp[1]);
288         return NULL;
289     }
290
291     len -= 7; // remove VANC header and checksum
292
293     if (cdp[2] != len) {
294         av_log(avctx, AV_LOG_WARNING, "CDP len %d != %zu\n", cdp[2], len);
295         return NULL;
296     }
297
298     cdp_sum = 0;
299     for (i = 0; i < len - 1; i++)
300         cdp_sum += cdp[i];
301     cdp_sum = cdp_sum ? 256 - cdp_sum : 0;
302     if (cdp[len - 1] != cdp_sum) {
303         av_log(avctx, AV_LOG_WARNING, "CDP checksum invalid 0x%.4x != 0x%.4x\n", cdp_sum, cdp[len-1]);
304         return NULL;
305     }
306
307     rate = cdp[3];
308     if (!(rate & 0x0f)) {
309         av_log(avctx, AV_LOG_WARNING, "CDP frame rate invalid (0x%.2x)\n", rate);
310         return NULL;
311     }
312     rate >>= 4;
313     if (rate > 8) {
314         av_log(avctx, AV_LOG_WARNING, "CDP frame rate invalid (0x%.2x)\n", rate);
315         return NULL;
316     }
317
318     if (!(cdp[4] & 0x43)) /* ccdata_present | caption_service_active | reserved */ {
319         av_log(avctx, AV_LOG_WARNING, "CDP flags invalid (0x%.2x)\n", cdp[4]);
320         return NULL;
321     }
322
323     hdr = (cdp[5] << 8) | cdp[6];
324     if (cdp[7] != 0x72) /* ccdata_id */ {
325         av_log(avctx, AV_LOG_WARNING, "Invalid ccdata_id 0x%.2x\n", cdp[7]);
326         return NULL;
327     }
328
329     cc_count = cdp[8];
330     if (!(cc_count & 0xe0)) {
331         av_log(avctx, AV_LOG_WARNING, "Invalid cc_count 0x%.2x\n", cc_count);
332         return NULL;
333     }
334
335     cc_count &= 0x1f;
336     if ((len - 13) < cc_count * 3) {
337         av_log(avctx, AV_LOG_WARNING, "Invalid cc_count %d (> %zu)\n", cc_count * 3, len - 13);
338         return NULL;
339     }
340
341     if (cdp[len - 4] != 0x74) /* footer id */ {
342         av_log(avctx, AV_LOG_WARNING, "Invalid footer id 0x%.2x\n", cdp[len-4]);
343         return NULL;
344     }
345
346     ftr = (cdp[len - 3] << 8) | cdp[len - 2];
347     if (ftr != hdr) {
348         av_log(avctx, AV_LOG_WARNING, "Header 0x%.4x != Footer 0x%.4x\n", hdr, ftr);
349         return NULL;
350     }
351
352     cc = (uint8_t *)av_malloc(cc_count * 3);
353     if (cc == NULL) {
354         av_log(avctx, AV_LOG_WARNING, "CC - av_malloc failed for cc_count = %d\n", cc_count);
355         return NULL;
356     }
357
358     for (size_t i = 0; i < cc_count; i++) {
359         cc[3*i + 0] = cdp[9 + 3*i+0] /* & 3 */;
360         cc[3*i + 1] = cdp[9 + 3*i+1];
361         cc[3*i + 2] = cdp[9 + 3*i+2];
362     }
363
364     cc_count *= 3;
365     return cc;
366 }
367
368 static uint8_t *get_metadata(AVFormatContext *avctx, uint16_t *buf, size_t width,
369                              uint8_t *tgt, size_t tgt_size, AVPacket *pkt)
370 {
371     decklink_cctx *cctx = (struct decklink_cctx *) avctx->priv_data;
372     uint16_t *max_buf = buf + width;
373
374     while (buf < max_buf - 6) {
375         int len;
376         uint16_t did = buf[3] & 0xFF;                                  // data id
377         uint16_t sdid = buf[4] & 0xFF;                                 // secondary data id
378         /* Check for VANC header */
379         if (buf[0] != 0 || buf[1] != 0x3ff || buf[2] != 0x3ff) {
380             return tgt;
381         }
382
383         len = (buf[5] & 0xff) + 6 + 1;
384         if (len > max_buf - buf) {
385             av_log(avctx, AV_LOG_WARNING, "Data Count (%d) > data left (%zu)\n",
386                     len, max_buf - buf);
387             return tgt;
388         }
389
390         if (did == 0x43 && (sdid == 0x02 || sdid == 0x03) && cctx->teletext_lines &&
391             width == 1920 && tgt_size >= 1920) {
392             if (check_vanc_parity_checksum(buf, len, buf[len - 1]) < 0) {
393                 av_log(avctx, AV_LOG_WARNING, "VANC parity or checksum incorrect\n");
394                 goto skip_packet;
395             }
396             tgt = teletext_data_unit_from_ancillary_packet(buf + 3, buf + len, tgt, cctx->teletext_lines, 1);
397         } else if (did == 0x61 && sdid == 0x01) {
398             unsigned int data_len;
399             uint8_t *data;
400             if (check_vanc_parity_checksum(buf, len, buf[len - 1]) < 0) {
401                 av_log(avctx, AV_LOG_WARNING, "VANC parity or checksum incorrect\n");
402                 goto skip_packet;
403             }
404             clear_parity_bits(buf, len);
405             data = vanc_to_cc(avctx, buf, width, data_len);
406             if (data) {
407                 if (av_packet_add_side_data(pkt, AV_PKT_DATA_A53_CC, data, data_len) < 0)
408                     av_free(data);
409             }
410         } else {
411             av_log(avctx, AV_LOG_DEBUG, "Unknown meta data DID = 0x%.2x SDID = 0x%.2x\n",
412                     did, sdid);
413         }
414 skip_packet:
415         buf += len;
416     }
417
418     return tgt;
419 }
420
421 static void avpacket_queue_init(AVFormatContext *avctx, AVPacketQueue *q)
422 {
423     struct decklink_cctx *ctx = (struct decklink_cctx *)avctx->priv_data;
424     memset(q, 0, sizeof(AVPacketQueue));
425     pthread_mutex_init(&q->mutex, NULL);
426     pthread_cond_init(&q->cond, NULL);
427     q->avctx = avctx;
428     q->max_q_size = ctx->queue_size;
429 }
430
431 static void avpacket_queue_flush(AVPacketQueue *q)
432 {
433     AVPacketList *pkt, *pkt1;
434
435     pthread_mutex_lock(&q->mutex);
436     for (pkt = q->first_pkt; pkt != NULL; pkt = pkt1) {
437         pkt1 = pkt->next;
438         av_packet_unref(&pkt->pkt);
439         av_freep(&pkt);
440     }
441     q->last_pkt   = NULL;
442     q->first_pkt  = NULL;
443     q->nb_packets = 0;
444     q->size       = 0;
445     pthread_mutex_unlock(&q->mutex);
446 }
447
448 static void avpacket_queue_end(AVPacketQueue *q)
449 {
450     avpacket_queue_flush(q);
451     pthread_mutex_destroy(&q->mutex);
452     pthread_cond_destroy(&q->cond);
453 }
454
455 static unsigned long long avpacket_queue_size(AVPacketQueue *q)
456 {
457     unsigned long long size;
458     pthread_mutex_lock(&q->mutex);
459     size = q->size;
460     pthread_mutex_unlock(&q->mutex);
461     return size;
462 }
463
464 static int avpacket_queue_put(AVPacketQueue *q, AVPacket *pkt)
465 {
466     AVPacketList *pkt1;
467
468     // Drop Packet if queue size is > maximum queue size
469     if (avpacket_queue_size(q) > (uint64_t)q->max_q_size) {
470         av_log(q->avctx, AV_LOG_WARNING,  "Decklink input buffer overrun!\n");
471         return -1;
472     }
473     /* ensure the packet is reference counted */
474     if (av_packet_make_refcounted(pkt) < 0) {
475         return -1;
476     }
477
478     pkt1 = (AVPacketList *)av_malloc(sizeof(AVPacketList));
479     if (!pkt1) {
480         return -1;
481     }
482     av_packet_move_ref(&pkt1->pkt, pkt);
483     pkt1->next = NULL;
484
485     pthread_mutex_lock(&q->mutex);
486
487     if (!q->last_pkt) {
488         q->first_pkt = pkt1;
489     } else {
490         q->last_pkt->next = pkt1;
491     }
492
493     q->last_pkt = pkt1;
494     q->nb_packets++;
495     q->size += pkt1->pkt.size + sizeof(*pkt1);
496
497     pthread_cond_signal(&q->cond);
498
499     pthread_mutex_unlock(&q->mutex);
500     return 0;
501 }
502
503 static int avpacket_queue_get(AVPacketQueue *q, AVPacket *pkt, int block)
504 {
505     AVPacketList *pkt1;
506     int ret;
507
508     pthread_mutex_lock(&q->mutex);
509
510     for (;; ) {
511         pkt1 = q->first_pkt;
512         if (pkt1) {
513             q->first_pkt = pkt1->next;
514             if (!q->first_pkt) {
515                 q->last_pkt = NULL;
516             }
517             q->nb_packets--;
518             q->size -= pkt1->pkt.size + sizeof(*pkt1);
519             *pkt     = pkt1->pkt;
520             av_free(pkt1);
521             ret = 1;
522             break;
523         } else if (!block) {
524             ret = 0;
525             break;
526         } else {
527             pthread_cond_wait(&q->cond, &q->mutex);
528         }
529     }
530     pthread_mutex_unlock(&q->mutex);
531     return ret;
532 }
533
534 class decklink_input_callback : public IDeckLinkInputCallback
535 {
536 public:
537         decklink_input_callback(AVFormatContext *_avctx);
538         ~decklink_input_callback();
539
540         virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv) { return E_NOINTERFACE; }
541         virtual ULONG STDMETHODCALLTYPE AddRef(void);
542         virtual ULONG STDMETHODCALLTYPE  Release(void);
543         virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents, IDeckLinkDisplayMode*, BMDDetectedVideoInputFormatFlags);
544         virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame*, IDeckLinkAudioInputPacket*);
545
546 private:
547         ULONG           m_refCount;
548         pthread_mutex_t m_mutex;
549         AVFormatContext *avctx;
550         decklink_ctx    *ctx;
551         int no_video;
552         int64_t initial_video_pts;
553         int64_t initial_audio_pts;
554 };
555
556 decklink_input_callback::decklink_input_callback(AVFormatContext *_avctx) : m_refCount(0)
557 {
558     avctx = _avctx;
559     decklink_cctx       *cctx = (struct decklink_cctx *)avctx->priv_data;
560     ctx = (struct decklink_ctx *)cctx->ctx;
561     no_video = 0;
562     initial_audio_pts = initial_video_pts = AV_NOPTS_VALUE;
563     pthread_mutex_init(&m_mutex, NULL);
564 }
565
566 decklink_input_callback::~decklink_input_callback()
567 {
568     pthread_mutex_destroy(&m_mutex);
569 }
570
571 ULONG decklink_input_callback::AddRef(void)
572 {
573     pthread_mutex_lock(&m_mutex);
574     m_refCount++;
575     pthread_mutex_unlock(&m_mutex);
576
577     return (ULONG)m_refCount;
578 }
579
580 ULONG decklink_input_callback::Release(void)
581 {
582     pthread_mutex_lock(&m_mutex);
583     m_refCount--;
584     pthread_mutex_unlock(&m_mutex);
585
586     if (m_refCount == 0) {
587         delete this;
588         return 0;
589     }
590
591     return (ULONG)m_refCount;
592 }
593
594 static int64_t get_pkt_pts(IDeckLinkVideoInputFrame *videoFrame,
595                            IDeckLinkAudioInputPacket *audioFrame,
596                            int64_t wallclock,
597                            int64_t abs_wallclock,
598                            DecklinkPtsSource pts_src,
599                            AVRational time_base, int64_t *initial_pts,
600                            int copyts)
601 {
602     int64_t pts = AV_NOPTS_VALUE;
603     BMDTimeValue bmd_pts;
604     BMDTimeValue bmd_duration;
605     HRESULT res = E_INVALIDARG;
606     switch (pts_src) {
607         case PTS_SRC_AUDIO:
608             if (audioFrame)
609                 res = audioFrame->GetPacketTime(&bmd_pts, time_base.den);
610             break;
611         case PTS_SRC_VIDEO:
612             if (videoFrame)
613                 res = videoFrame->GetStreamTime(&bmd_pts, &bmd_duration, time_base.den);
614             break;
615         case PTS_SRC_REFERENCE:
616             if (videoFrame)
617                 res = videoFrame->GetHardwareReferenceTimestamp(time_base.den, &bmd_pts, &bmd_duration);
618             break;
619         case PTS_SRC_WALLCLOCK:
620             /* fall through */
621         case PTS_SRC_ABS_WALLCLOCK:
622         {
623             /* MSVC does not support compound literals like AV_TIME_BASE_Q
624              * in C++ code (compiler error C4576) */
625             AVRational timebase;
626             timebase.num = 1;
627             timebase.den = AV_TIME_BASE;
628             if (pts_src == PTS_SRC_WALLCLOCK)
629                 pts = av_rescale_q(wallclock, timebase, time_base);
630             else
631                 pts = av_rescale_q(abs_wallclock, timebase, time_base);
632             break;
633         }
634     }
635     if (res == S_OK)
636         pts = bmd_pts / time_base.num;
637
638     if (!copyts) {
639         if (pts != AV_NOPTS_VALUE && *initial_pts == AV_NOPTS_VALUE)
640             *initial_pts = pts;
641         if (*initial_pts != AV_NOPTS_VALUE)
642             pts -= *initial_pts;
643     }
644
645     return pts;
646 }
647
648 HRESULT decklink_input_callback::VideoInputFrameArrived(
649     IDeckLinkVideoInputFrame *videoFrame, IDeckLinkAudioInputPacket *audioFrame)
650 {
651     void *frameBytes;
652     void *audioFrameBytes;
653     BMDTimeValue frameTime;
654     BMDTimeValue frameDuration;
655     int64_t wallclock = 0, abs_wallclock = 0;
656     struct decklink_cctx *cctx = (struct decklink_cctx *) avctx->priv_data;
657
658     if (ctx->autodetect) {
659         if (videoFrame && !(videoFrame->GetFlags() & bmdFrameHasNoInputSource) &&
660             ctx->bmd_mode == bmdModeUnknown)
661         {
662             ctx->bmd_mode = AUTODETECT_DEFAULT_MODE;
663         }
664         return S_OK;
665     }
666
667     ctx->frameCount++;
668     if (ctx->audio_pts_source == PTS_SRC_WALLCLOCK || ctx->video_pts_source == PTS_SRC_WALLCLOCK)
669         wallclock = av_gettime_relative();
670     if (ctx->audio_pts_source == PTS_SRC_ABS_WALLCLOCK || ctx->video_pts_source == PTS_SRC_ABS_WALLCLOCK)
671         abs_wallclock = av_gettime();
672
673     // Handle Video Frame
674     if (videoFrame) {
675         AVPacket pkt;
676         av_init_packet(&pkt);
677         if (ctx->frameCount % 25 == 0) {
678             unsigned long long qsize = avpacket_queue_size(&ctx->queue);
679             av_log(avctx, AV_LOG_DEBUG,
680                     "Frame received (#%lu) - Valid (%liB) - QSize %fMB\n",
681                     ctx->frameCount,
682                     videoFrame->GetRowBytes() * videoFrame->GetHeight(),
683                     (double)qsize / 1024 / 1024);
684         }
685
686         videoFrame->GetBytes(&frameBytes);
687         videoFrame->GetStreamTime(&frameTime, &frameDuration,
688                                   ctx->video_st->time_base.den);
689
690         if (videoFrame->GetFlags() & bmdFrameHasNoInputSource) {
691             if (ctx->draw_bars && videoFrame->GetPixelFormat() == bmdFormat8BitYUV) {
692                 unsigned bars[8] = {
693                     0xEA80EA80, 0xD292D210, 0xA910A9A5, 0x90229035,
694                     0x6ADD6ACA, 0x51EF515A, 0x286D28EF, 0x10801080 };
695                 int width  = videoFrame->GetWidth();
696                 int height = videoFrame->GetHeight();
697                 unsigned *p = (unsigned *)frameBytes;
698
699                 for (int y = 0; y < height; y++) {
700                     for (int x = 0; x < width; x += 2)
701                         *p++ = bars[(x * 8) / width];
702                 }
703             }
704
705             if (!no_video) {
706                 av_log(avctx, AV_LOG_WARNING, "Frame received (#%lu) - No input signal detected "
707                         "- Frames dropped %u\n", ctx->frameCount, ++ctx->dropped);
708             }
709             no_video = 1;
710         } else {
711             if (no_video) {
712                 av_log(avctx, AV_LOG_WARNING, "Frame received (#%lu) - Input returned "
713                         "- Frames dropped %u\n", ctx->frameCount, ++ctx->dropped);
714             }
715             no_video = 0;
716         }
717
718         pkt.pts = get_pkt_pts(videoFrame, audioFrame, wallclock, abs_wallclock, ctx->video_pts_source, ctx->video_st->time_base, &initial_video_pts, cctx->copyts);
719         pkt.dts = pkt.pts;
720
721         pkt.duration = frameDuration;
722         //To be made sure it still applies
723         pkt.flags       |= AV_PKT_FLAG_KEY;
724         pkt.stream_index = ctx->video_st->index;
725         pkt.data         = (uint8_t *)frameBytes;
726         pkt.size         = videoFrame->GetRowBytes() *
727                            videoFrame->GetHeight();
728         //fprintf(stderr,"Video Frame size %d ts %d\n", pkt.size, pkt.pts);
729
730         if (!no_video) {
731             IDeckLinkVideoFrameAncillary *vanc;
732             AVPacket txt_pkt;
733             uint8_t txt_buf0[3531]; // 35 * 46 bytes decoded teletext lines + 1 byte data_identifier + 1920 bytes OP47 decode buffer
734             uint8_t *txt_buf = txt_buf0;
735
736             if (videoFrame->GetAncillaryData(&vanc) == S_OK) {
737                 int i;
738                 int64_t line_mask = 1;
739                 BMDPixelFormat vanc_format = vanc->GetPixelFormat();
740                 txt_buf[0] = 0x10;    // data_identifier - EBU_data
741                 txt_buf++;
742 #if CONFIG_LIBZVBI
743                 if (ctx->bmd_mode == bmdModePAL && ctx->teletext_lines &&
744                     (vanc_format == bmdFormat8BitYUV || vanc_format == bmdFormat10BitYUV)) {
745                     av_assert0(videoFrame->GetWidth() == 720);
746                     for (i = 6; i < 336; i++, line_mask <<= 1) {
747                         uint8_t *buf;
748                         if ((ctx->teletext_lines & line_mask) && vanc->GetBufferForVerticalBlankingLine(i, (void**)&buf) == S_OK) {
749                             if (vanc_format == bmdFormat8BitYUV)
750                                 txt_buf = teletext_data_unit_from_vbi_data(i, buf, txt_buf, VBI_PIXFMT_UYVY);
751                             else
752                                 txt_buf = teletext_data_unit_from_vbi_data_10bit(i, buf, txt_buf);
753                         }
754                         if (i == 22)
755                             i = 317;
756                     }
757                 }
758 #endif
759                 if (vanc_format == bmdFormat10BitYUV && videoFrame->GetWidth() <= MAX_WIDTH_VANC) {
760                     int idx = get_vanc_line_idx(ctx->bmd_mode);
761                     for (i = vanc_line_numbers[idx].vanc_start; i <= vanc_line_numbers[idx].vanc_end; i++) {
762                         uint8_t *buf;
763                         if (vanc->GetBufferForVerticalBlankingLine(i, (void**)&buf) == S_OK) {
764                             uint16_t vanc[MAX_WIDTH_VANC];
765                             size_t vanc_size = videoFrame->GetWidth();
766                             if (ctx->bmd_mode == bmdModeNTSC && videoFrame->GetWidth() * 2 <= MAX_WIDTH_VANC) {
767                                 vanc_size = vanc_size * 2;
768                                 unpack_v210(vanc, buf, videoFrame->GetWidth());
769                             } else {
770                                 extract_luma_from_v210(vanc, buf, videoFrame->GetWidth());
771                             }
772                             txt_buf = get_metadata(avctx, vanc, vanc_size,
773                                                    txt_buf, sizeof(txt_buf0) - (txt_buf - txt_buf0), &pkt);
774                         }
775                         if (i == vanc_line_numbers[idx].field0_vanc_end)
776                             i = vanc_line_numbers[idx].field1_vanc_start - 1;
777                     }
778                 }
779                 vanc->Release();
780                 if (txt_buf - txt_buf0 > 1) {
781                     int stuffing_units = (4 - ((45 + txt_buf - txt_buf0) / 46) % 4) % 4;
782                     while (stuffing_units--) {
783                         memset(txt_buf, 0xff, 46);
784                         txt_buf[1] = 0x2c; // data_unit_length
785                         txt_buf += 46;
786                     }
787                     av_init_packet(&txt_pkt);
788                     txt_pkt.pts = pkt.pts;
789                     txt_pkt.dts = pkt.dts;
790                     txt_pkt.stream_index = ctx->teletext_st->index;
791                     txt_pkt.data = txt_buf0;
792                     txt_pkt.size = txt_buf - txt_buf0;
793                     if (avpacket_queue_put(&ctx->queue, &txt_pkt) < 0) {
794                         ++ctx->dropped;
795                     }
796                 }
797             }
798         }
799
800         if (avpacket_queue_put(&ctx->queue, &pkt) < 0) {
801             ++ctx->dropped;
802         }
803     }
804
805     // Handle Audio Frame
806     if (audioFrame) {
807         AVPacket pkt;
808         BMDTimeValue audio_pts;
809         av_init_packet(&pkt);
810
811         //hack among hacks
812         pkt.size = audioFrame->GetSampleFrameCount() * ctx->audio_st->codecpar->channels * (ctx->audio_depth / 8);
813         audioFrame->GetBytes(&audioFrameBytes);
814         audioFrame->GetPacketTime(&audio_pts, ctx->audio_st->time_base.den);
815         pkt.pts = get_pkt_pts(videoFrame, audioFrame, wallclock, abs_wallclock, ctx->audio_pts_source, ctx->audio_st->time_base, &initial_audio_pts, cctx->copyts);
816         pkt.dts = pkt.pts;
817
818         //fprintf(stderr,"Audio Frame size %d ts %d\n", pkt.size, pkt.pts);
819         pkt.flags       |= AV_PKT_FLAG_KEY;
820         pkt.stream_index = ctx->audio_st->index;
821         pkt.data         = (uint8_t *)audioFrameBytes;
822
823         if (avpacket_queue_put(&ctx->queue, &pkt) < 0) {
824             ++ctx->dropped;
825         }
826     }
827
828     return S_OK;
829 }
830
831 HRESULT decklink_input_callback::VideoInputFormatChanged(
832     BMDVideoInputFormatChangedEvents events, IDeckLinkDisplayMode *mode,
833     BMDDetectedVideoInputFormatFlags)
834 {
835     ctx->bmd_mode = mode->GetDisplayMode();
836     return S_OK;
837 }
838
839 static int decklink_autodetect(struct decklink_cctx *cctx) {
840     struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
841     DECKLINK_BOOL autodetect_supported = false;
842     int i;
843
844     if (ctx->attr->GetFlag(BMDDeckLinkSupportsInputFormatDetection, &autodetect_supported) != S_OK)
845         return -1;
846     if (autodetect_supported == false)
847         return -1;
848
849     ctx->autodetect = 1;
850     ctx->bmd_mode  = bmdModeUnknown;
851     if (ctx->dli->EnableVideoInput(AUTODETECT_DEFAULT_MODE,
852                                    bmdFormat8BitYUV,
853                                    bmdVideoInputEnableFormatDetection) != S_OK) {
854         return -1;
855     }
856
857     if (ctx->dli->StartStreams() != S_OK) {
858         return -1;
859     }
860
861     // 1 second timeout
862     for (i = 0; i < 10; i++) {
863         av_usleep(100000);
864         /* Sometimes VideoInputFrameArrived is called without the
865          * bmdFrameHasNoInputSource flag before VideoInputFormatChanged.
866          * So don't break for bmd_mode == AUTODETECT_DEFAULT_MODE. */
867         if (ctx->bmd_mode != bmdModeUnknown &&
868             ctx->bmd_mode != AUTODETECT_DEFAULT_MODE)
869             break;
870     }
871
872     ctx->dli->PauseStreams();
873     ctx->dli->FlushStreams();
874     ctx->autodetect = 0;
875     if (ctx->bmd_mode != bmdModeUnknown) {
876         cctx->format_code = (char *)av_mallocz(5);
877         if (!cctx->format_code)
878             return -1;
879         AV_WB32(cctx->format_code, ctx->bmd_mode);
880         return 0;
881     } else {
882         return -1;
883     }
884
885 }
886
887 extern "C" {
888
889 av_cold int ff_decklink_read_close(AVFormatContext *avctx)
890 {
891     struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
892     struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
893
894     if (ctx->capture_started) {
895         ctx->dli->StopStreams();
896         ctx->dli->DisableVideoInput();
897         ctx->dli->DisableAudioInput();
898     }
899
900     ff_decklink_cleanup(avctx);
901     avpacket_queue_end(&ctx->queue);
902
903     av_freep(&cctx->ctx);
904
905     return 0;
906 }
907
908 av_cold int ff_decklink_read_header(AVFormatContext *avctx)
909 {
910     struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
911     struct decklink_ctx *ctx;
912     AVStream *st;
913     HRESULT result;
914     char fname[1024];
915     char *tmp;
916     int mode_num = 0;
917     int ret;
918
919     ctx = (struct decklink_ctx *) av_mallocz(sizeof(struct decklink_ctx));
920     if (!ctx)
921         return AVERROR(ENOMEM);
922     ctx->list_devices = cctx->list_devices;
923     ctx->list_formats = cctx->list_formats;
924     ctx->teletext_lines = cctx->teletext_lines;
925     ctx->preroll      = cctx->preroll;
926     ctx->duplex_mode  = cctx->duplex_mode;
927     if (cctx->video_input > 0 && (unsigned int)cctx->video_input < FF_ARRAY_ELEMS(decklink_video_connection_map))
928         ctx->video_input = decklink_video_connection_map[cctx->video_input];
929     if (cctx->audio_input > 0 && (unsigned int)cctx->audio_input < FF_ARRAY_ELEMS(decklink_audio_connection_map))
930         ctx->audio_input = decklink_audio_connection_map[cctx->audio_input];
931     ctx->audio_pts_source = cctx->audio_pts_source;
932     ctx->video_pts_source = cctx->video_pts_source;
933     ctx->draw_bars = cctx->draw_bars;
934     ctx->audio_depth = cctx->audio_depth;
935     cctx->ctx = ctx;
936
937     /* Check audio channel option for valid values: 2, 8 or 16 */
938     switch (cctx->audio_channels) {
939         case 2:
940         case 8:
941         case 16:
942             break;
943         default:
944             av_log(avctx, AV_LOG_ERROR, "Value of channels option must be one of 2, 8 or 16\n");
945             return AVERROR(EINVAL);
946     }
947
948     /* Check audio bit depth option for valid values: 16 or 32 */
949     switch (cctx->audio_depth) {
950         case 16:
951         case 32:
952             break;
953         default:
954             av_log(avctx, AV_LOG_ERROR, "Value for audio bit depth option must be either 16 or 32\n");
955             return AVERROR(EINVAL);
956     }
957
958     /* List available devices. */
959     if (ctx->list_devices) {
960         ff_decklink_list_devices_legacy(avctx, 1, 0);
961         return AVERROR_EXIT;
962     }
963
964     if (cctx->v210) {
965         av_log(avctx, AV_LOG_WARNING, "The bm_v210 option is deprecated and will be removed. Please use the -raw_format yuv422p10.\n");
966         cctx->raw_format = MKBETAG('v','2','1','0');
967     }
968
969     av_strlcpy(fname, avctx->url, sizeof(fname));
970     tmp=strchr (fname, '@');
971     if (tmp != NULL) {
972         av_log(avctx, AV_LOG_WARNING, "The @mode syntax is deprecated and will be removed. Please use the -format_code option.\n");
973         mode_num = atoi (tmp+1);
974         *tmp = 0;
975     }
976
977     ret = ff_decklink_init_device(avctx, fname);
978     if (ret < 0)
979         return ret;
980
981     /* Get input device. */
982     if (ctx->dl->QueryInterface(IID_IDeckLinkInput, (void **) &ctx->dli) != S_OK) {
983         av_log(avctx, AV_LOG_ERROR, "Could not open input device from '%s'\n",
984                avctx->url);
985         ret = AVERROR(EIO);
986         goto error;
987     }
988
989     /* List supported formats. */
990     if (ctx->list_formats) {
991         ff_decklink_list_formats(avctx, DIRECTION_IN);
992         ret = AVERROR_EXIT;
993         goto error;
994     }
995
996     if (ff_decklink_set_configs(avctx, DIRECTION_IN) < 0) {
997         av_log(avctx, AV_LOG_ERROR, "Could not set input configuration\n");
998         ret = AVERROR(EIO);
999         goto error;
1000     }
1001
1002     ctx->input_callback = new decklink_input_callback(avctx);
1003     ctx->dli->SetCallback(ctx->input_callback);
1004
1005     if (mode_num == 0 && !cctx->format_code) {
1006         if (decklink_autodetect(cctx) < 0) {
1007             av_log(avctx, AV_LOG_ERROR, "Cannot Autodetect input stream or No signal\n");
1008             ret = AVERROR(EIO);
1009             goto error;
1010         }
1011         av_log(avctx, AV_LOG_INFO, "Autodetected the input mode\n");
1012     }
1013     if (ff_decklink_set_format(avctx, DIRECTION_IN, mode_num) < 0) {
1014         av_log(avctx, AV_LOG_ERROR, "Could not set mode number %d or format code %s for %s\n",
1015             mode_num, (cctx->format_code) ? cctx->format_code : "(unset)", fname);
1016         ret = AVERROR(EIO);
1017         goto error;
1018     }
1019
1020 #if !CONFIG_LIBZVBI
1021     if (ctx->teletext_lines && ctx->bmd_mode == bmdModePAL) {
1022         av_log(avctx, AV_LOG_ERROR, "Libzvbi support is needed for capturing SD PAL teletext, please recompile FFmpeg.\n");
1023         ret = AVERROR(ENOSYS);
1024         goto error;
1025     }
1026 #endif
1027
1028     /* Setup streams. */
1029     st = avformat_new_stream(avctx, NULL);
1030     if (!st) {
1031         av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
1032         ret = AVERROR(ENOMEM);
1033         goto error;
1034     }
1035     st->codecpar->codec_type  = AVMEDIA_TYPE_AUDIO;
1036     st->codecpar->codec_id    = cctx->audio_depth == 32 ? AV_CODEC_ID_PCM_S32LE : AV_CODEC_ID_PCM_S16LE;
1037     st->codecpar->sample_rate = bmdAudioSampleRate48kHz;
1038     st->codecpar->channels    = cctx->audio_channels;
1039     avpriv_set_pts_info(st, 64, 1, 1000000);  /* 64 bits pts in us */
1040     ctx->audio_st=st;
1041
1042     st = avformat_new_stream(avctx, NULL);
1043     if (!st) {
1044         av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
1045         ret = AVERROR(ENOMEM);
1046         goto error;
1047     }
1048     st->codecpar->codec_type  = AVMEDIA_TYPE_VIDEO;
1049     st->codecpar->width       = ctx->bmd_width;
1050     st->codecpar->height      = ctx->bmd_height;
1051
1052     st->time_base.den      = ctx->bmd_tb_den;
1053     st->time_base.num      = ctx->bmd_tb_num;
1054     st->r_frame_rate       = av_make_q(st->time_base.den, st->time_base.num);
1055
1056     switch((BMDPixelFormat)cctx->raw_format) {
1057     case bmdFormat8BitYUV:
1058         st->codecpar->codec_id    = AV_CODEC_ID_RAWVIDEO;
1059         st->codecpar->codec_tag   = MKTAG('U', 'Y', 'V', 'Y');
1060         st->codecpar->format      = AV_PIX_FMT_UYVY422;
1061         st->codecpar->bit_rate    = av_rescale(ctx->bmd_width * ctx->bmd_height * 16, st->time_base.den, st->time_base.num);
1062         break;
1063     case bmdFormat10BitYUV:
1064         st->codecpar->codec_id    = AV_CODEC_ID_V210;
1065         st->codecpar->codec_tag   = MKTAG('V','2','1','0');
1066         st->codecpar->bit_rate    = av_rescale(ctx->bmd_width * ctx->bmd_height * 64, st->time_base.den, st->time_base.num * 3);
1067         st->codecpar->bits_per_coded_sample = 10;
1068         break;
1069     case bmdFormat8BitARGB:
1070         st->codecpar->codec_id    = AV_CODEC_ID_RAWVIDEO;
1071         st->codecpar->codec_tag   = avcodec_pix_fmt_to_codec_tag((enum AVPixelFormat)st->codecpar->format);
1072         st->codecpar->format      = AV_PIX_FMT_0RGB;
1073         st->codecpar->bit_rate    = av_rescale(ctx->bmd_width * ctx->bmd_height * 32, st->time_base.den, st->time_base.num);
1074         break;
1075     case bmdFormat8BitBGRA:
1076         st->codecpar->codec_id    = AV_CODEC_ID_RAWVIDEO;
1077         st->codecpar->codec_tag   = avcodec_pix_fmt_to_codec_tag((enum AVPixelFormat)st->codecpar->format);
1078         st->codecpar->format      = AV_PIX_FMT_BGR0;
1079         st->codecpar->bit_rate    = av_rescale(ctx->bmd_width * ctx->bmd_height * 32, st->time_base.den, st->time_base.num);
1080         break;
1081     case bmdFormat10BitRGB:
1082         st->codecpar->codec_id    = AV_CODEC_ID_R210;
1083         st->codecpar->codec_tag   = MKTAG('R','2','1','0');
1084         st->codecpar->format      = AV_PIX_FMT_RGB48LE;
1085         st->codecpar->bit_rate    = av_rescale(ctx->bmd_width * ctx->bmd_height * 30, st->time_base.den, st->time_base.num);
1086         st->codecpar->bits_per_coded_sample = 10;
1087         break;
1088     default:
1089         av_log(avctx, AV_LOG_ERROR, "Raw Format %.4s not supported\n", (char*) &cctx->raw_format);
1090         ret = AVERROR(EINVAL);
1091         goto error;
1092     }
1093
1094     switch (ctx->bmd_field_dominance) {
1095     case bmdUpperFieldFirst:
1096         st->codecpar->field_order = AV_FIELD_TT;
1097         break;
1098     case bmdLowerFieldFirst:
1099         st->codecpar->field_order = AV_FIELD_BB;
1100         break;
1101     case bmdProgressiveFrame:
1102     case bmdProgressiveSegmentedFrame:
1103         st->codecpar->field_order = AV_FIELD_PROGRESSIVE;
1104         break;
1105     }
1106
1107     avpriv_set_pts_info(st, 64, 1, 1000000);  /* 64 bits pts in us */
1108
1109     ctx->video_st=st;
1110
1111     if (ctx->teletext_lines) {
1112         st = avformat_new_stream(avctx, NULL);
1113         if (!st) {
1114             av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
1115             ret = AVERROR(ENOMEM);
1116             goto error;
1117         }
1118         st->codecpar->codec_type  = AVMEDIA_TYPE_SUBTITLE;
1119         st->time_base.den         = ctx->bmd_tb_den;
1120         st->time_base.num         = ctx->bmd_tb_num;
1121         st->codecpar->codec_id    = AV_CODEC_ID_DVB_TELETEXT;
1122         avpriv_set_pts_info(st, 64, 1, 1000000);  /* 64 bits pts in us */
1123         ctx->teletext_st = st;
1124     }
1125
1126     av_log(avctx, AV_LOG_VERBOSE, "Using %d input audio channels\n", ctx->audio_st->codecpar->channels);
1127     result = ctx->dli->EnableAudioInput(bmdAudioSampleRate48kHz, cctx->audio_depth == 32 ? bmdAudioSampleType32bitInteger : bmdAudioSampleType16bitInteger, ctx->audio_st->codecpar->channels);
1128
1129     if (result != S_OK) {
1130         av_log(avctx, AV_LOG_ERROR, "Cannot enable audio input\n");
1131         ret = AVERROR(EIO);
1132         goto error;
1133     }
1134
1135     result = ctx->dli->EnableVideoInput(ctx->bmd_mode,
1136                                         (BMDPixelFormat) cctx->raw_format,
1137                                         bmdVideoInputFlagDefault);
1138
1139     if (result != S_OK) {
1140         av_log(avctx, AV_LOG_ERROR, "Cannot enable video input\n");
1141         ret = AVERROR(EIO);
1142         goto error;
1143     }
1144
1145     avpacket_queue_init (avctx, &ctx->queue);
1146
1147     if (ctx->dli->StartStreams() != S_OK) {
1148         av_log(avctx, AV_LOG_ERROR, "Cannot start input stream\n");
1149         ret = AVERROR(EIO);
1150         goto error;
1151     }
1152
1153     return 0;
1154
1155 error:
1156     ff_decklink_cleanup(avctx);
1157     return ret;
1158 }
1159
1160 int ff_decklink_read_packet(AVFormatContext *avctx, AVPacket *pkt)
1161 {
1162     struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
1163     struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
1164
1165     avpacket_queue_get(&ctx->queue, pkt, 1);
1166
1167     return 0;
1168 }
1169
1170 int ff_decklink_list_input_devices(AVFormatContext *avctx, struct AVDeviceInfoList *device_list)
1171 {
1172     return ff_decklink_list_devices(avctx, device_list, 1, 0);
1173 }
1174
1175 } /* extern "C" */