]> git.sesse.net Git - ffmpeg/blob - libavdevice/decklink_dec.cpp
Merge commit '8e67039c6312ba520945f2c01b7b14df056d5ed1'
[ffmpeg] / libavdevice / decklink_dec.cpp
1 /*
2  * Blackmagic DeckLink input
3  * Copyright (c) 2013-2014 Luca Barbato, Deti Fliegl
4  * Copyright (c) 2017 Akamai Technologies, Inc.
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /* Include internal.h first to avoid conflict between winsock.h (used by
24  * DeckLink headers) and winsock2.h (used by libavformat) in MSVC++ builds */
25 extern "C" {
26 #include "libavformat/internal.h"
27 }
28
29 #include <DeckLinkAPI.h>
30
31 extern "C" {
32 #include "config.h"
33 #include "libavformat/avformat.h"
34 #include "libavutil/avassert.h"
35 #include "libavutil/avutil.h"
36 #include "libavutil/common.h"
37 #include "libavutil/imgutils.h"
38 #include "libavutil/time.h"
39 #include "libavutil/mathematics.h"
40 #include "libavutil/reverse.h"
41 #if CONFIG_LIBZVBI
42 #include <libzvbi.h>
43 #endif
44 }
45
46 #include "decklink_common.h"
47 #include "decklink_dec.h"
48
49 static uint8_t calc_parity_and_line_offset(int line)
50 {
51     uint8_t ret = (line < 313) << 5;
52     if (line >= 7 && line <= 22)
53         ret += line;
54     if (line >= 320 && line <= 335)
55         ret += (line - 313);
56     return ret;
57 }
58
59 static void fill_data_unit_head(int line, uint8_t *tgt)
60 {
61     tgt[0] = 0x02; // data_unit_id
62     tgt[1] = 0x2c; // data_unit_length
63     tgt[2] = calc_parity_and_line_offset(line); // field_parity, line_offset
64     tgt[3] = 0xe4; // framing code
65 }
66
67 #if CONFIG_LIBZVBI
68 static uint8_t* teletext_data_unit_from_vbi_data(int line, uint8_t *src, uint8_t *tgt, vbi_pixfmt fmt)
69 {
70     vbi_bit_slicer slicer;
71
72     vbi_bit_slicer_init(&slicer, 720, 13500000, 6937500, 6937500, 0x00aaaae4, 0xffff, 18, 6, 42 * 8, VBI_MODULATION_NRZ_MSB, fmt);
73
74     if (vbi_bit_slice(&slicer, src, tgt + 4) == FALSE)
75         return tgt;
76
77     fill_data_unit_head(line, tgt);
78
79     return tgt + 46;
80 }
81
82 static uint8_t* teletext_data_unit_from_vbi_data_10bit(int line, uint8_t *src, uint8_t *tgt)
83 {
84     uint8_t y[720];
85     uint8_t *py = y;
86     uint8_t *pend = y + 720;
87     /* The 10-bit VBI data is packed in V210, but libzvbi only supports 8-bit,
88      * so we extract the 8 MSBs of the luma component, that is enough for
89      * teletext bit slicing. */
90     while (py < pend) {
91         *py++ = (src[1] >> 4) + ((src[2] & 15) << 4);
92         *py++ = (src[4] >> 2) + ((src[5] & 3 ) << 6);
93         *py++ = (src[6] >> 6) + ((src[7] & 63) << 2);
94         src += 8;
95     }
96     return teletext_data_unit_from_vbi_data(line, y, tgt, VBI_PIXFMT_YUV420);
97 }
98 #endif
99
100 static uint8_t* teletext_data_unit_from_op47_vbi_packet(int line, uint16_t *py, uint8_t *tgt)
101 {
102     int i;
103
104     if (py[0] != 0x255 || py[1] != 0x255 || py[2] != 0x227)
105         return tgt;
106
107     fill_data_unit_head(line, tgt);
108
109     py += 3;
110     tgt += 4;
111
112     for (i = 0; i < 42; i++)
113        *tgt++ = ff_reverse[py[i] & 255];
114
115     return tgt;
116 }
117
118 static int linemask_matches(int line, int64_t mask)
119 {
120     int shift = -1;
121     if (line >= 6 && line <= 22)
122         shift = line - 6;
123     if (line >= 318 && line <= 335)
124         shift = line - 318 + 17;
125     return shift >= 0 && ((1ULL << shift) & mask);
126 }
127
128 static uint8_t* teletext_data_unit_from_op47_data(uint16_t *py, uint16_t *pend, uint8_t *tgt, int64_t wanted_lines)
129 {
130     if (py < pend - 9) {
131         if (py[0] == 0x151 && py[1] == 0x115 && py[3] == 0x102) {       // identifier, identifier, format code for WST teletext
132             uint16_t *descriptors = py + 4;
133             int i;
134             py += 9;
135             for (i = 0; i < 5 && py < pend - 45; i++, py += 45) {
136                 int line = (descriptors[i] & 31) + (!(descriptors[i] & 128)) * 313;
137                 if (line && linemask_matches(line, wanted_lines))
138                     tgt = teletext_data_unit_from_op47_vbi_packet(line, py, tgt);
139             }
140         }
141     }
142     return tgt;
143 }
144
145 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)
146 {
147     uint16_t did = py[0];                                               // data id
148     uint16_t sdid = py[1];                                              // secondary data id
149     uint16_t dc = py[2] & 255;                                          // data count
150     py += 3;
151     pend = FFMIN(pend, py + dc);
152     if (did == 0x143 && sdid == 0x102) {                                // subtitle distribution packet
153         tgt = teletext_data_unit_from_op47_data(py, pend, tgt, wanted_lines);
154     } else if (allow_multipacket && did == 0x143 && sdid == 0x203) {    // VANC multipacket
155         py += 2;                                                        // priority, line/field
156         while (py < pend - 3) {
157             tgt = teletext_data_unit_from_ancillary_packet(py, pend, tgt, wanted_lines, 0);
158             py += 4 + (py[2] & 255);                                    // ndid, nsdid, ndc, line/field
159         }
160     }
161     return tgt;
162 }
163
164 static uint8_t* teletext_data_unit_from_vanc_data(uint8_t *src, uint8_t *tgt, int64_t wanted_lines)
165 {
166     uint16_t y[1920];
167     uint16_t *py = y;
168     uint16_t *pend = y + 1920;
169     /* The 10-bit VANC data is packed in V210, we only need the luma component. */
170     while (py < pend) {
171         *py++ = (src[1] >> 2) + ((src[2] & 15) << 6);
172         *py++ =  src[4]       + ((src[5] &  3) << 8);
173         *py++ = (src[6] >> 4) + ((src[7] & 63) << 4);
174         src += 8;
175     }
176     py = y;
177     while (py < pend - 6) {
178         if (py[0] == 0 && py[1] == 0x3ff && py[2] == 0x3ff) {           // ancillary data flag
179             py += 3;
180             tgt = teletext_data_unit_from_ancillary_packet(py, pend, tgt, wanted_lines, 0);
181             py += py[2] & 255;
182         } else {
183             py++;
184         }
185     }
186     return tgt;
187 }
188
189 static void avpacket_queue_init(AVFormatContext *avctx, AVPacketQueue *q)
190 {
191     struct decklink_cctx *ctx = (struct decklink_cctx *)avctx->priv_data;
192     memset(q, 0, sizeof(AVPacketQueue));
193     pthread_mutex_init(&q->mutex, NULL);
194     pthread_cond_init(&q->cond, NULL);
195     q->avctx = avctx;
196     q->max_q_size = ctx->queue_size;
197 }
198
199 static void avpacket_queue_flush(AVPacketQueue *q)
200 {
201     AVPacketList *pkt, *pkt1;
202
203     pthread_mutex_lock(&q->mutex);
204     for (pkt = q->first_pkt; pkt != NULL; pkt = pkt1) {
205         pkt1 = pkt->next;
206         av_packet_unref(&pkt->pkt);
207         av_freep(&pkt);
208     }
209     q->last_pkt   = NULL;
210     q->first_pkt  = NULL;
211     q->nb_packets = 0;
212     q->size       = 0;
213     pthread_mutex_unlock(&q->mutex);
214 }
215
216 static void avpacket_queue_end(AVPacketQueue *q)
217 {
218     avpacket_queue_flush(q);
219     pthread_mutex_destroy(&q->mutex);
220     pthread_cond_destroy(&q->cond);
221 }
222
223 static unsigned long long avpacket_queue_size(AVPacketQueue *q)
224 {
225     unsigned long long size;
226     pthread_mutex_lock(&q->mutex);
227     size = q->size;
228     pthread_mutex_unlock(&q->mutex);
229     return size;
230 }
231
232 static int avpacket_queue_put(AVPacketQueue *q, AVPacket *pkt)
233 {
234     AVPacketList *pkt1;
235
236     // Drop Packet if queue size is > maximum queue size
237     if (avpacket_queue_size(q) > (uint64_t)q->max_q_size) {
238         av_log(q->avctx, AV_LOG_WARNING,  "Decklink input buffer overrun!\n");
239         return -1;
240     }
241     /* duplicate the packet */
242     if (av_dup_packet(pkt) < 0) {
243         return -1;
244     }
245
246     pkt1 = (AVPacketList *)av_malloc(sizeof(AVPacketList));
247     if (!pkt1) {
248         return -1;
249     }
250     pkt1->pkt  = *pkt;
251     pkt1->next = NULL;
252
253     pthread_mutex_lock(&q->mutex);
254
255     if (!q->last_pkt) {
256         q->first_pkt = pkt1;
257     } else {
258         q->last_pkt->next = pkt1;
259     }
260
261     q->last_pkt = pkt1;
262     q->nb_packets++;
263     q->size += pkt1->pkt.size + sizeof(*pkt1);
264
265     pthread_cond_signal(&q->cond);
266
267     pthread_mutex_unlock(&q->mutex);
268     return 0;
269 }
270
271 static int avpacket_queue_get(AVPacketQueue *q, AVPacket *pkt, int block)
272 {
273     AVPacketList *pkt1;
274     int ret;
275
276     pthread_mutex_lock(&q->mutex);
277
278     for (;; ) {
279         pkt1 = q->first_pkt;
280         if (pkt1) {
281             q->first_pkt = pkt1->next;
282             if (!q->first_pkt) {
283                 q->last_pkt = NULL;
284             }
285             q->nb_packets--;
286             q->size -= pkt1->pkt.size + sizeof(*pkt1);
287             *pkt     = pkt1->pkt;
288             av_free(pkt1);
289             ret = 1;
290             break;
291         } else if (!block) {
292             ret = 0;
293             break;
294         } else {
295             pthread_cond_wait(&q->cond, &q->mutex);
296         }
297     }
298     pthread_mutex_unlock(&q->mutex);
299     return ret;
300 }
301
302 class decklink_input_callback : public IDeckLinkInputCallback
303 {
304 public:
305         decklink_input_callback(AVFormatContext *_avctx);
306         ~decklink_input_callback();
307
308         virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv) { return E_NOINTERFACE; }
309         virtual ULONG STDMETHODCALLTYPE AddRef(void);
310         virtual ULONG STDMETHODCALLTYPE  Release(void);
311         virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents, IDeckLinkDisplayMode*, BMDDetectedVideoInputFormatFlags);
312         virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame*, IDeckLinkAudioInputPacket*);
313
314 private:
315         ULONG           m_refCount;
316         pthread_mutex_t m_mutex;
317         AVFormatContext *avctx;
318         decklink_ctx    *ctx;
319         int no_video;
320         int64_t initial_video_pts;
321         int64_t initial_audio_pts;
322 };
323
324 decklink_input_callback::decklink_input_callback(AVFormatContext *_avctx) : m_refCount(0)
325 {
326     avctx = _avctx;
327     decklink_cctx       *cctx = (struct decklink_cctx *)avctx->priv_data;
328     ctx = (struct decklink_ctx *)cctx->ctx;
329     no_video = 0;
330     initial_audio_pts = initial_video_pts = AV_NOPTS_VALUE;
331     pthread_mutex_init(&m_mutex, NULL);
332 }
333
334 decklink_input_callback::~decklink_input_callback()
335 {
336     pthread_mutex_destroy(&m_mutex);
337 }
338
339 ULONG decklink_input_callback::AddRef(void)
340 {
341     pthread_mutex_lock(&m_mutex);
342     m_refCount++;
343     pthread_mutex_unlock(&m_mutex);
344
345     return (ULONG)m_refCount;
346 }
347
348 ULONG decklink_input_callback::Release(void)
349 {
350     pthread_mutex_lock(&m_mutex);
351     m_refCount--;
352     pthread_mutex_unlock(&m_mutex);
353
354     if (m_refCount == 0) {
355         delete this;
356         return 0;
357     }
358
359     return (ULONG)m_refCount;
360 }
361
362 static int64_t get_pkt_pts(IDeckLinkVideoInputFrame *videoFrame,
363                            IDeckLinkAudioInputPacket *audioFrame,
364                            int64_t wallclock,
365                            DecklinkPtsSource pts_src,
366                            AVRational time_base, int64_t *initial_pts)
367 {
368     int64_t pts = AV_NOPTS_VALUE;
369     BMDTimeValue bmd_pts;
370     BMDTimeValue bmd_duration;
371     HRESULT res = E_INVALIDARG;
372     switch (pts_src) {
373         case PTS_SRC_AUDIO:
374             if (audioFrame)
375                 res = audioFrame->GetPacketTime(&bmd_pts, time_base.den);
376             break;
377         case PTS_SRC_VIDEO:
378             if (videoFrame)
379                 res = videoFrame->GetStreamTime(&bmd_pts, &bmd_duration, time_base.den);
380             break;
381         case PTS_SRC_REFERENCE:
382             if (videoFrame)
383                 res = videoFrame->GetHardwareReferenceTimestamp(time_base.den, &bmd_pts, &bmd_duration);
384             break;
385         case PTS_SRC_WALLCLOCK:
386         {
387             /* MSVC does not support compound literals like AV_TIME_BASE_Q
388              * in C++ code (compiler error C4576) */
389             AVRational timebase;
390             timebase.num = 1;
391             timebase.den = AV_TIME_BASE;
392             pts = av_rescale_q(wallclock, timebase, time_base);
393             break;
394         }
395     }
396     if (res == S_OK)
397         pts = bmd_pts / time_base.num;
398
399     if (pts != AV_NOPTS_VALUE && *initial_pts == AV_NOPTS_VALUE)
400         *initial_pts = pts;
401     if (*initial_pts != AV_NOPTS_VALUE)
402         pts -= *initial_pts;
403
404     return pts;
405 }
406
407 HRESULT decklink_input_callback::VideoInputFrameArrived(
408     IDeckLinkVideoInputFrame *videoFrame, IDeckLinkAudioInputPacket *audioFrame)
409 {
410     void *frameBytes;
411     void *audioFrameBytes;
412     BMDTimeValue frameTime;
413     BMDTimeValue frameDuration;
414     int64_t wallclock = 0;
415
416     ctx->frameCount++;
417     if (ctx->audio_pts_source == PTS_SRC_WALLCLOCK || ctx->video_pts_source == PTS_SRC_WALLCLOCK)
418         wallclock = av_gettime_relative();
419
420     // Handle Video Frame
421     if (videoFrame) {
422         AVPacket pkt;
423         av_init_packet(&pkt);
424         if (ctx->frameCount % 25 == 0) {
425             unsigned long long qsize = avpacket_queue_size(&ctx->queue);
426             av_log(avctx, AV_LOG_DEBUG,
427                     "Frame received (#%lu) - Valid (%liB) - QSize %fMB\n",
428                     ctx->frameCount,
429                     videoFrame->GetRowBytes() * videoFrame->GetHeight(),
430                     (double)qsize / 1024 / 1024);
431         }
432
433         videoFrame->GetBytes(&frameBytes);
434         videoFrame->GetStreamTime(&frameTime, &frameDuration,
435                                   ctx->video_st->time_base.den);
436
437         if (videoFrame->GetFlags() & bmdFrameHasNoInputSource) {
438             if (ctx->draw_bars && videoFrame->GetPixelFormat() == bmdFormat8BitYUV) {
439                 unsigned bars[8] = {
440                     0xEA80EA80, 0xD292D210, 0xA910A9A5, 0x90229035,
441                     0x6ADD6ACA, 0x51EF515A, 0x286D28EF, 0x10801080 };
442                 int width  = videoFrame->GetWidth();
443                 int height = videoFrame->GetHeight();
444                 unsigned *p = (unsigned *)frameBytes;
445
446                 for (int y = 0; y < height; y++) {
447                     for (int x = 0; x < width; x += 2)
448                         *p++ = bars[(x * 8) / width];
449                 }
450             }
451
452             if (!no_video) {
453                 av_log(avctx, AV_LOG_WARNING, "Frame received (#%lu) - No input signal detected "
454                         "- Frames dropped %u\n", ctx->frameCount, ++ctx->dropped);
455             }
456             no_video = 1;
457         } else {
458             if (no_video) {
459                 av_log(avctx, AV_LOG_WARNING, "Frame received (#%lu) - Input returned "
460                         "- Frames dropped %u\n", ctx->frameCount, ++ctx->dropped);
461             }
462             no_video = 0;
463         }
464
465         pkt.pts = get_pkt_pts(videoFrame, audioFrame, wallclock, ctx->video_pts_source, ctx->video_st->time_base, &initial_video_pts);
466         pkt.dts = pkt.pts;
467
468         pkt.duration = frameDuration;
469         //To be made sure it still applies
470         pkt.flags       |= AV_PKT_FLAG_KEY;
471         pkt.stream_index = ctx->video_st->index;
472         pkt.data         = (uint8_t *)frameBytes;
473         pkt.size         = videoFrame->GetRowBytes() *
474                            videoFrame->GetHeight();
475         //fprintf(stderr,"Video Frame size %d ts %d\n", pkt.size, pkt.pts);
476
477         if (!no_video && ctx->teletext_lines) {
478             IDeckLinkVideoFrameAncillary *vanc;
479             AVPacket txt_pkt;
480             uint8_t txt_buf0[3531]; // 35 * 46 bytes decoded teletext lines + 1 byte data_identifier + 1920 bytes OP47 decode buffer
481             uint8_t *txt_buf = txt_buf0;
482
483             if (videoFrame->GetAncillaryData(&vanc) == S_OK) {
484                 int i;
485                 int64_t line_mask = 1;
486                 BMDPixelFormat vanc_format = vanc->GetPixelFormat();
487                 txt_buf[0] = 0x10;    // data_identifier - EBU_data
488                 txt_buf++;
489 #if CONFIG_LIBZVBI
490                 if (ctx->bmd_mode == bmdModePAL && (vanc_format == bmdFormat8BitYUV || vanc_format == bmdFormat10BitYUV)) {
491                     av_assert0(videoFrame->GetWidth() == 720);
492                     for (i = 6; i < 336; i++, line_mask <<= 1) {
493                         uint8_t *buf;
494                         if ((ctx->teletext_lines & line_mask) && vanc->GetBufferForVerticalBlankingLine(i, (void**)&buf) == S_OK) {
495                             if (vanc_format == bmdFormat8BitYUV)
496                                 txt_buf = teletext_data_unit_from_vbi_data(i, buf, txt_buf, VBI_PIXFMT_UYVY);
497                             else
498                                 txt_buf = teletext_data_unit_from_vbi_data_10bit(i, buf, txt_buf);
499                         }
500                         if (i == 22)
501                             i = 317;
502                     }
503                 }
504 #endif
505                 if (videoFrame->GetWidth() == 1920 && vanc_format == bmdFormat10BitYUV) {
506                     int first_active_line = ctx->bmd_field_dominance == bmdProgressiveFrame ? 42 : 584;
507                     for (i = 8; i < first_active_line; i++) {
508                         uint8_t *buf;
509                         if (vanc->GetBufferForVerticalBlankingLine(i, (void**)&buf) == S_OK)
510                             txt_buf = teletext_data_unit_from_vanc_data(buf, txt_buf, ctx->teletext_lines);
511                         if (ctx->bmd_field_dominance != bmdProgressiveFrame && i == 20)     // skip field1 active lines
512                             i = 569;
513                         if (txt_buf - txt_buf0 > 1611) {   // ensure we still have at least 1920 bytes free in the buffer
514                             av_log(avctx, AV_LOG_ERROR, "Too many OP47 teletext packets.\n");
515                             break;
516                         }
517                     }
518                 }
519                 vanc->Release();
520                 if (txt_buf - txt_buf0 > 1) {
521                     int stuffing_units = (4 - ((45 + txt_buf - txt_buf0) / 46) % 4) % 4;
522                     while (stuffing_units--) {
523                         memset(txt_buf, 0xff, 46);
524                         txt_buf[1] = 0x2c; // data_unit_length
525                         txt_buf += 46;
526                     }
527                     av_init_packet(&txt_pkt);
528                     txt_pkt.pts = pkt.pts;
529                     txt_pkt.dts = pkt.dts;
530                     txt_pkt.stream_index = ctx->teletext_st->index;
531                     txt_pkt.data = txt_buf0;
532                     txt_pkt.size = txt_buf - txt_buf0;
533                     if (avpacket_queue_put(&ctx->queue, &txt_pkt) < 0) {
534                         ++ctx->dropped;
535                     }
536                 }
537             }
538         }
539
540         if (avpacket_queue_put(&ctx->queue, &pkt) < 0) {
541             ++ctx->dropped;
542         }
543     }
544
545     // Handle Audio Frame
546     if (audioFrame) {
547         AVPacket pkt;
548         BMDTimeValue audio_pts;
549         av_init_packet(&pkt);
550
551         //hack among hacks
552         pkt.size = audioFrame->GetSampleFrameCount() * ctx->audio_st->codecpar->channels * (16 / 8);
553         audioFrame->GetBytes(&audioFrameBytes);
554         audioFrame->GetPacketTime(&audio_pts, ctx->audio_st->time_base.den);
555         pkt.pts = get_pkt_pts(videoFrame, audioFrame, wallclock, ctx->audio_pts_source, ctx->audio_st->time_base, &initial_audio_pts);
556         pkt.dts = pkt.pts;
557
558         //fprintf(stderr,"Audio Frame size %d ts %d\n", pkt.size, pkt.pts);
559         pkt.flags       |= AV_PKT_FLAG_KEY;
560         pkt.stream_index = ctx->audio_st->index;
561         pkt.data         = (uint8_t *)audioFrameBytes;
562
563         if (avpacket_queue_put(&ctx->queue, &pkt) < 0) {
564             ++ctx->dropped;
565         }
566     }
567
568     return S_OK;
569 }
570
571 HRESULT decklink_input_callback::VideoInputFormatChanged(
572     BMDVideoInputFormatChangedEvents events, IDeckLinkDisplayMode *mode,
573     BMDDetectedVideoInputFormatFlags)
574 {
575     return S_OK;
576 }
577
578 static HRESULT decklink_start_input(AVFormatContext *avctx)
579 {
580     struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
581     struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
582
583     ctx->input_callback = new decklink_input_callback(avctx);
584     ctx->dli->SetCallback(ctx->input_callback);
585     return ctx->dli->StartStreams();
586 }
587
588 extern "C" {
589
590 av_cold int ff_decklink_read_close(AVFormatContext *avctx)
591 {
592     struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
593     struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
594
595     if (ctx->capture_started) {
596         ctx->dli->StopStreams();
597         ctx->dli->DisableVideoInput();
598         ctx->dli->DisableAudioInput();
599     }
600
601     ff_decklink_cleanup(avctx);
602     avpacket_queue_end(&ctx->queue);
603
604     av_freep(&cctx->ctx);
605
606     return 0;
607 }
608
609 av_cold int ff_decklink_read_header(AVFormatContext *avctx)
610 {
611     struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
612     struct decklink_ctx *ctx;
613     AVStream *st;
614     HRESULT result;
615     char fname[1024];
616     char *tmp;
617     int mode_num = 0;
618     int ret;
619
620     ctx = (struct decklink_ctx *) av_mallocz(sizeof(struct decklink_ctx));
621     if (!ctx)
622         return AVERROR(ENOMEM);
623     ctx->list_devices = cctx->list_devices;
624     ctx->list_formats = cctx->list_formats;
625     ctx->teletext_lines = cctx->teletext_lines;
626     ctx->preroll      = cctx->preroll;
627     ctx->duplex_mode  = cctx->duplex_mode;
628     if (cctx->video_input > 0 && (unsigned int)cctx->video_input < FF_ARRAY_ELEMS(decklink_video_connection_map))
629         ctx->video_input = decklink_video_connection_map[cctx->video_input];
630     if (cctx->audio_input > 0 && (unsigned int)cctx->audio_input < FF_ARRAY_ELEMS(decklink_audio_connection_map))
631         ctx->audio_input = decklink_audio_connection_map[cctx->audio_input];
632     ctx->audio_pts_source = cctx->audio_pts_source;
633     ctx->video_pts_source = cctx->video_pts_source;
634     ctx->draw_bars = cctx->draw_bars;
635     cctx->ctx = ctx;
636
637     /* Check audio channel option for valid values: 2, 8 or 16 */
638     switch (cctx->audio_channels) {
639         case 2:
640         case 8:
641         case 16:
642             break;
643         default:
644             av_log(avctx, AV_LOG_ERROR, "Value of channels option must be one of 2, 8 or 16\n");
645             return AVERROR(EINVAL);
646     }
647
648     /* List available devices. */
649     if (ctx->list_devices) {
650         ff_decklink_list_devices(avctx);
651         return AVERROR_EXIT;
652     }
653
654     strcpy (fname, avctx->filename);
655     tmp=strchr (fname, '@');
656     if (tmp != NULL) {
657         av_log(avctx, AV_LOG_WARNING, "The @mode syntax is deprecated and will be removed. Please use the -format_code option.\n");
658         mode_num = atoi (tmp+1);
659         *tmp = 0;
660     }
661
662     ret = ff_decklink_init_device(avctx, fname);
663     if (ret < 0)
664         return ret;
665
666     /* Get input device. */
667     if (ctx->dl->QueryInterface(IID_IDeckLinkInput, (void **) &ctx->dli) != S_OK) {
668         av_log(avctx, AV_LOG_ERROR, "Could not open input device from '%s'\n",
669                avctx->filename);
670         ret = AVERROR(EIO);
671         goto error;
672     }
673
674     /* List supported formats. */
675     if (ctx->list_formats) {
676         ff_decklink_list_formats(avctx, DIRECTION_IN);
677         ret = AVERROR_EXIT;
678         goto error;
679     }
680
681     if (mode_num > 0 || cctx->format_code) {
682         if (ff_decklink_set_format(avctx, DIRECTION_IN, mode_num) < 0) {
683             av_log(avctx, AV_LOG_ERROR, "Could not set mode number %d or format code %s for %s\n",
684                 mode_num, (cctx->format_code) ? cctx->format_code : "(unset)", fname);
685             ret = AVERROR(EIO);
686             goto error;
687         }
688     }
689
690 #if !CONFIG_LIBZVBI
691     if (ctx->teletext_lines && ctx->bmd_mode == bmdModePAL) {
692         av_log(avctx, AV_LOG_ERROR, "Libzvbi support is needed for capturing SD PAL teletext, please recompile FFmpeg.\n");
693         ret = AVERROR(ENOSYS);
694         goto error;
695     }
696 #endif
697
698     /* Setup streams. */
699     st = avformat_new_stream(avctx, NULL);
700     if (!st) {
701         av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
702         ret = AVERROR(ENOMEM);
703         goto error;
704     }
705     st->codecpar->codec_type  = AVMEDIA_TYPE_AUDIO;
706     st->codecpar->codec_id    = AV_CODEC_ID_PCM_S16LE;
707     st->codecpar->sample_rate = bmdAudioSampleRate48kHz;
708     st->codecpar->channels    = cctx->audio_channels;
709     avpriv_set_pts_info(st, 64, 1, 1000000);  /* 64 bits pts in us */
710     ctx->audio_st=st;
711
712     st = avformat_new_stream(avctx, NULL);
713     if (!st) {
714         av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
715         ret = AVERROR(ENOMEM);
716         goto error;
717     }
718     st->codecpar->codec_type  = AVMEDIA_TYPE_VIDEO;
719     st->codecpar->width       = ctx->bmd_width;
720     st->codecpar->height      = ctx->bmd_height;
721
722     st->time_base.den      = ctx->bmd_tb_den;
723     st->time_base.num      = ctx->bmd_tb_num;
724     av_stream_set_r_frame_rate(st, av_make_q(st->time_base.den, st->time_base.num));
725
726     if (cctx->v210) {
727         st->codecpar->codec_id    = AV_CODEC_ID_V210;
728         st->codecpar->codec_tag   = MKTAG('V', '2', '1', '0');
729         st->codecpar->bit_rate    = av_rescale(ctx->bmd_width * ctx->bmd_height * 64, st->time_base.den, st->time_base.num * 3);
730     } else {
731         st->codecpar->codec_id    = AV_CODEC_ID_RAWVIDEO;
732         st->codecpar->format      = AV_PIX_FMT_UYVY422;
733         st->codecpar->codec_tag   = MKTAG('U', 'Y', 'V', 'Y');
734         st->codecpar->bit_rate    = av_rescale(ctx->bmd_width * ctx->bmd_height * 16, st->time_base.den, st->time_base.num);
735     }
736
737     switch (ctx->bmd_field_dominance) {
738     case bmdUpperFieldFirst:
739         st->codecpar->field_order = AV_FIELD_TT;
740         break;
741     case bmdLowerFieldFirst:
742         st->codecpar->field_order = AV_FIELD_BB;
743         break;
744     case bmdProgressiveFrame:
745     case bmdProgressiveSegmentedFrame:
746         st->codecpar->field_order = AV_FIELD_PROGRESSIVE;
747         break;
748     }
749
750     avpriv_set_pts_info(st, 64, 1, 1000000);  /* 64 bits pts in us */
751
752     ctx->video_st=st;
753
754     if (ctx->teletext_lines) {
755         st = avformat_new_stream(avctx, NULL);
756         if (!st) {
757             av_log(avctx, AV_LOG_ERROR, "Cannot add stream\n");
758             ret = AVERROR(ENOMEM);
759             goto error;
760         }
761         st->codecpar->codec_type  = AVMEDIA_TYPE_SUBTITLE;
762         st->time_base.den         = ctx->bmd_tb_den;
763         st->time_base.num         = ctx->bmd_tb_num;
764         st->codecpar->codec_id    = AV_CODEC_ID_DVB_TELETEXT;
765         avpriv_set_pts_info(st, 64, 1, 1000000);  /* 64 bits pts in us */
766         ctx->teletext_st = st;
767     }
768
769     av_log(avctx, AV_LOG_VERBOSE, "Using %d input audio channels\n", ctx->audio_st->codecpar->channels);
770     result = ctx->dli->EnableAudioInput(bmdAudioSampleRate48kHz, bmdAudioSampleType16bitInteger, ctx->audio_st->codecpar->channels);
771
772     if (result != S_OK) {
773         av_log(avctx, AV_LOG_ERROR, "Cannot enable audio input\n");
774         ret = AVERROR(EIO);
775         goto error;
776     }
777
778     result = ctx->dli->EnableVideoInput(ctx->bmd_mode,
779                                         cctx->v210 ? bmdFormat10BitYUV : bmdFormat8BitYUV,
780                                         bmdVideoInputFlagDefault);
781
782     if (result != S_OK) {
783         av_log(avctx, AV_LOG_ERROR, "Cannot enable video input\n");
784         ret = AVERROR(EIO);
785         goto error;
786     }
787
788     avpacket_queue_init (avctx, &ctx->queue);
789
790     if (decklink_start_input (avctx) != S_OK) {
791         av_log(avctx, AV_LOG_ERROR, "Cannot start input stream\n");
792         ret = AVERROR(EIO);
793         goto error;
794     }
795
796     return 0;
797
798 error:
799     ff_decklink_cleanup(avctx);
800     return ret;
801 }
802
803 int ff_decklink_read_packet(AVFormatContext *avctx, AVPacket *pkt)
804 {
805     struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
806     struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
807
808     avpacket_queue_get(&ctx->queue, pkt, 1);
809
810     return 0;
811 }
812
813 } /* extern "C" */