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