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