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