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