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