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