]> git.sesse.net Git - ffmpeg/blob - libavdevice/decklink_enc.cpp
Merge commit 'a70eac7a9b193e8434b5bed90bd72aa4cb688363'
[ffmpeg] / libavdevice / decklink_enc.cpp
1 /*
2  * Blackmagic DeckLink output
3  * Copyright (c) 2013-2014 Ramiro Polla
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 <atomic>
23 using std::atomic;
24
25 /* Include internal.h first to avoid conflict between winsock.h (used by
26  * DeckLink headers) and winsock2.h (used by libavformat) in MSVC++ builds */
27 extern "C" {
28 #include "libavformat/internal.h"
29 }
30
31 #include <DeckLinkAPI.h>
32
33 extern "C" {
34 #include "libavformat/avformat.h"
35 #include "libavutil/imgutils.h"
36 #include "avdevice.h"
37 }
38
39 #include "decklink_common.h"
40 #include "decklink_enc.h"
41 #if CONFIG_LIBKLVANC
42 #include "libklvanc/vanc.h"
43 #include "libklvanc/vanc-lines.h"
44 #include "libklvanc/pixels.h"
45 #endif
46
47 /* DeckLink callback class declaration */
48 class decklink_frame : public IDeckLinkVideoFrame
49 {
50 public:
51     decklink_frame(struct decklink_ctx *ctx, AVFrame *avframe, AVCodecID codec_id, int height, int width) :
52         _ctx(ctx), _avframe(avframe), _avpacket(NULL), _codec_id(codec_id), _ancillary(NULL), _height(height), _width(width),  _refs(1) { }
53     decklink_frame(struct decklink_ctx *ctx, AVPacket *avpacket, AVCodecID codec_id, int height, int width) :
54         _ctx(ctx), _avframe(NULL), _avpacket(avpacket), _codec_id(codec_id), _ancillary(NULL), _height(height), _width(width), _refs(1) { }
55     virtual long           STDMETHODCALLTYPE GetWidth      (void)          { return _width; }
56     virtual long           STDMETHODCALLTYPE GetHeight     (void)          { return _height; }
57     virtual long           STDMETHODCALLTYPE GetRowBytes   (void)
58     {
59       if (_codec_id == AV_CODEC_ID_WRAPPED_AVFRAME)
60           return _avframe->linesize[0] < 0 ? -_avframe->linesize[0] : _avframe->linesize[0];
61       else
62           return ((GetWidth() + 47) / 48) * 128;
63     }
64     virtual BMDPixelFormat STDMETHODCALLTYPE GetPixelFormat(void)
65     {
66         if (_codec_id == AV_CODEC_ID_WRAPPED_AVFRAME)
67             return bmdFormat8BitYUV;
68         else
69             return bmdFormat10BitYUV;
70     }
71     virtual BMDFrameFlags  STDMETHODCALLTYPE GetFlags      (void)
72     {
73        if (_codec_id == AV_CODEC_ID_WRAPPED_AVFRAME)
74            return _avframe->linesize[0] < 0 ? bmdFrameFlagFlipVertical : bmdFrameFlagDefault;
75        else
76            return bmdFrameFlagDefault;
77     }
78
79     virtual HRESULT        STDMETHODCALLTYPE GetBytes      (void **buffer)
80     {
81         if (_codec_id == AV_CODEC_ID_WRAPPED_AVFRAME) {
82             if (_avframe->linesize[0] < 0)
83                 *buffer = (void *)(_avframe->data[0] + _avframe->linesize[0] * (_avframe->height - 1));
84             else
85                 *buffer = (void *)(_avframe->data[0]);
86         } else {
87             *buffer = (void *)(_avpacket->data);
88         }
89         return S_OK;
90     }
91
92     virtual HRESULT STDMETHODCALLTYPE GetTimecode     (BMDTimecodeFormat format, IDeckLinkTimecode **timecode) { return S_FALSE; }
93     virtual HRESULT STDMETHODCALLTYPE GetAncillaryData(IDeckLinkVideoFrameAncillary **ancillary)
94     {
95         *ancillary = _ancillary;
96         if (_ancillary) {
97             _ancillary->AddRef();
98             return S_OK;
99         } else {
100             return S_FALSE;
101         }
102     }
103     virtual HRESULT STDMETHODCALLTYPE SetAncillaryData(IDeckLinkVideoFrameAncillary *ancillary)
104     {
105         if (_ancillary)
106             _ancillary->Release();
107         _ancillary = ancillary;
108         _ancillary->AddRef();
109         return S_OK;
110     }
111     virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv) { return E_NOINTERFACE; }
112     virtual ULONG   STDMETHODCALLTYPE AddRef(void)                            { return ++_refs; }
113     virtual ULONG   STDMETHODCALLTYPE Release(void)
114     {
115         int ret = --_refs;
116         if (!ret) {
117             av_frame_free(&_avframe);
118             av_packet_free(&_avpacket);
119             if (_ancillary)
120                 _ancillary->Release();
121             delete this;
122         }
123         return ret;
124     }
125
126     struct decklink_ctx *_ctx;
127     AVFrame *_avframe;
128     AVPacket *_avpacket;
129     AVCodecID _codec_id;
130     IDeckLinkVideoFrameAncillary *_ancillary;
131     int _height;
132     int _width;
133
134 private:
135     std::atomic<int>  _refs;
136 };
137
138 class decklink_output_callback : public IDeckLinkVideoOutputCallback
139 {
140 public:
141     virtual HRESULT STDMETHODCALLTYPE ScheduledFrameCompleted(IDeckLinkVideoFrame *_frame, BMDOutputFrameCompletionResult result)
142     {
143         decklink_frame *frame = static_cast<decklink_frame *>(_frame);
144         struct decklink_ctx *ctx = frame->_ctx;
145
146         if (frame->_avframe)
147             av_frame_unref(frame->_avframe);
148         if (frame->_avpacket)
149             av_packet_unref(frame->_avpacket);
150
151         pthread_mutex_lock(&ctx->mutex);
152         ctx->frames_buffer_available_spots++;
153         pthread_cond_broadcast(&ctx->cond);
154         pthread_mutex_unlock(&ctx->mutex);
155
156         return S_OK;
157     }
158     virtual HRESULT STDMETHODCALLTYPE ScheduledPlaybackHasStopped(void)       { return S_OK; }
159     virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv) { return E_NOINTERFACE; }
160     virtual ULONG   STDMETHODCALLTYPE AddRef(void)                            { return 1; }
161     virtual ULONG   STDMETHODCALLTYPE Release(void)                           { return 1; }
162 };
163
164 static int decklink_setup_video(AVFormatContext *avctx, AVStream *st)
165 {
166     struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
167     struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
168     AVCodecParameters *c = st->codecpar;
169
170     if (ctx->video) {
171         av_log(avctx, AV_LOG_ERROR, "Only one video stream is supported!\n");
172         return -1;
173     }
174
175     if (c->codec_id == AV_CODEC_ID_WRAPPED_AVFRAME) {
176         if (c->format != AV_PIX_FMT_UYVY422) {
177             av_log(avctx, AV_LOG_ERROR, "Unsupported pixel format!"
178                    " Only AV_PIX_FMT_UYVY422 is supported.\n");
179             return -1;
180         }
181         ctx->raw_format = bmdFormat8BitYUV;
182     } else if (c->codec_id != AV_CODEC_ID_V210) {
183         av_log(avctx, AV_LOG_ERROR, "Unsupported codec type!"
184                " Only V210 and wrapped frame with AV_PIX_FMT_UYVY422 are supported.\n");
185         return -1;
186     } else {
187         ctx->raw_format = bmdFormat10BitYUV;
188     }
189
190     if (ff_decklink_set_configs(avctx, DIRECTION_OUT) < 0) {
191         av_log(avctx, AV_LOG_ERROR, "Could not set output configuration\n");
192         return -1;
193     }
194     if (ff_decklink_set_format(avctx, c->width, c->height,
195                             st->time_base.num, st->time_base.den, c->field_order)) {
196         av_log(avctx, AV_LOG_ERROR, "Unsupported video size, framerate or field order!"
197                " Check available formats with -list_formats 1.\n");
198         return -1;
199     }
200     if (ctx->dlo->EnableVideoOutput(ctx->bmd_mode,
201                                     ctx->supports_vanc ? bmdVideoOutputVANC : bmdVideoOutputFlagDefault) != S_OK) {
202         av_log(avctx, AV_LOG_ERROR, "Could not enable video output!\n");
203         return -1;
204     }
205
206     /* Set callback. */
207     ctx->output_callback = new decklink_output_callback();
208     ctx->dlo->SetScheduledFrameCompletionCallback(ctx->output_callback);
209
210     ctx->frames_preroll = st->time_base.den * ctx->preroll;
211     if (st->time_base.den > 1000)
212         ctx->frames_preroll /= 1000;
213
214     /* Buffer twice as many frames as the preroll. */
215     ctx->frames_buffer = ctx->frames_preroll * 2;
216     ctx->frames_buffer = FFMIN(ctx->frames_buffer, 60);
217     pthread_mutex_init(&ctx->mutex, NULL);
218     pthread_cond_init(&ctx->cond, NULL);
219     ctx->frames_buffer_available_spots = ctx->frames_buffer;
220
221     av_log(avctx, AV_LOG_DEBUG, "output: %s, preroll: %d, frames buffer size: %d\n",
222            avctx->url, ctx->frames_preroll, ctx->frames_buffer);
223
224     /* The device expects the framerate to be fixed. */
225     avpriv_set_pts_info(st, 64, st->time_base.num, st->time_base.den);
226
227     ctx->video = 1;
228
229     return 0;
230 }
231
232 static int decklink_setup_audio(AVFormatContext *avctx, AVStream *st)
233 {
234     struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
235     struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
236     AVCodecParameters *c = st->codecpar;
237
238     if (ctx->audio) {
239         av_log(avctx, AV_LOG_ERROR, "Only one audio stream is supported!\n");
240         return -1;
241     }
242     if (c->sample_rate != 48000) {
243         av_log(avctx, AV_LOG_ERROR, "Unsupported sample rate!"
244                " Only 48kHz is supported.\n");
245         return -1;
246     }
247     if (c->channels != 2 && c->channels != 8 && c->channels != 16) {
248         av_log(avctx, AV_LOG_ERROR, "Unsupported number of channels!"
249                " Only 2, 8 or 16 channels are supported.\n");
250         return -1;
251     }
252     if (ctx->dlo->EnableAudioOutput(bmdAudioSampleRate48kHz,
253                                     bmdAudioSampleType16bitInteger,
254                                     c->channels,
255                                     bmdAudioOutputStreamTimestamped) != S_OK) {
256         av_log(avctx, AV_LOG_ERROR, "Could not enable audio output!\n");
257         return -1;
258     }
259     if (ctx->dlo->BeginAudioPreroll() != S_OK) {
260         av_log(avctx, AV_LOG_ERROR, "Could not begin audio preroll!\n");
261         return -1;
262     }
263
264     /* The device expects the sample rate to be fixed. */
265     avpriv_set_pts_info(st, 64, 1, c->sample_rate);
266     ctx->channels = c->channels;
267
268     ctx->audio = 1;
269
270     return 0;
271 }
272
273 av_cold int ff_decklink_write_trailer(AVFormatContext *avctx)
274 {
275     struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
276     struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
277
278     if (ctx->playback_started) {
279         BMDTimeValue actual;
280         ctx->dlo->StopScheduledPlayback(ctx->last_pts * ctx->bmd_tb_num,
281                                         &actual, ctx->bmd_tb_den);
282         ctx->dlo->DisableVideoOutput();
283         if (ctx->audio)
284             ctx->dlo->DisableAudioOutput();
285     }
286
287     ff_decklink_cleanup(avctx);
288
289     if (ctx->output_callback)
290         delete ctx->output_callback;
291
292     pthread_mutex_destroy(&ctx->mutex);
293     pthread_cond_destroy(&ctx->cond);
294
295 #if CONFIG_LIBKLVANC
296     klvanc_context_destroy(ctx->vanc_ctx);
297 #endif
298
299     av_freep(&cctx->ctx);
300
301     return 0;
302 }
303
304 #if CONFIG_LIBKLVANC
305 static void construct_cc(AVFormatContext *avctx, struct decklink_ctx *ctx,
306                          AVPacket *pkt, struct klvanc_line_set_s *vanc_lines)
307 {
308     struct klvanc_packet_eia_708b_s *cdp;
309     uint16_t *cdp_words;
310     uint16_t len;
311     uint8_t cc_count;
312     int size, ret, i;
313
314     const uint8_t *data = av_packet_get_side_data(pkt, AV_PKT_DATA_A53_CC, &size);
315     if (!data)
316         return;
317
318     cc_count = size / 3;
319
320     ret = klvanc_create_eia708_cdp(&cdp);
321     if (ret)
322         return;
323
324     ret = klvanc_set_framerate_EIA_708B(cdp, ctx->bmd_tb_num, ctx->bmd_tb_den);
325     if (ret) {
326         av_log(avctx, AV_LOG_ERROR, "Invalid framerate specified: %lld/%lld\n",
327                ctx->bmd_tb_num, ctx->bmd_tb_den);
328         klvanc_destroy_eia708_cdp(cdp);
329         return;
330     }
331
332     if (cc_count > KLVANC_MAX_CC_COUNT) {
333         av_log(avctx, AV_LOG_ERROR, "Illegal cc_count received: %d\n", cc_count);
334         cc_count = KLVANC_MAX_CC_COUNT;
335     }
336
337     /* CC data */
338     cdp->header.ccdata_present = 1;
339     cdp->header.caption_service_active = 1;
340     cdp->ccdata.cc_count = cc_count;
341     for (i = 0; i < cc_count; i++) {
342         if (data [3*i] & 0x04)
343             cdp->ccdata.cc[i].cc_valid = 1;
344         cdp->ccdata.cc[i].cc_type = data[3*i] & 0x03;
345         cdp->ccdata.cc[i].cc_data[0] = data[3*i+1];
346         cdp->ccdata.cc[i].cc_data[1] = data[3*i+2];
347     }
348
349     klvanc_finalize_EIA_708B(cdp, ctx->cdp_sequence_num++);
350     ret = klvanc_convert_EIA_708B_to_words(cdp, &cdp_words, &len);
351     klvanc_destroy_eia708_cdp(cdp);
352     if (ret != 0) {
353         av_log(avctx, AV_LOG_ERROR, "Failed converting 708 packet to words\n");
354         return;
355     }
356
357     ret = klvanc_line_insert(ctx->vanc_ctx, vanc_lines, cdp_words, len, 11, 0);
358     free(cdp_words);
359     if (ret != 0) {
360         av_log(avctx, AV_LOG_ERROR, "VANC line insertion failed\n");
361         return;
362     }
363 }
364
365 static int decklink_construct_vanc(AVFormatContext *avctx, struct decklink_ctx *ctx,
366                                    AVPacket *pkt, decklink_frame *frame)
367 {
368     struct klvanc_line_set_s vanc_lines = { 0 };
369     int ret = 0, i;
370
371     if (!ctx->supports_vanc)
372         return 0;
373
374     construct_cc(avctx, ctx, pkt, &vanc_lines);
375
376     IDeckLinkVideoFrameAncillary *vanc;
377     int result = ctx->dlo->CreateAncillaryData(bmdFormat10BitYUV, &vanc);
378     if (result != S_OK) {
379         av_log(avctx, AV_LOG_ERROR, "Failed to create vanc\n");
380         ret = AVERROR(EIO);
381         goto done;
382     }
383
384     /* Now that we've got all the VANC lines in a nice orderly manner, generate the
385        final VANC sections for the Decklink output */
386     for (i = 0; i < vanc_lines.num_lines; i++) {
387         struct klvanc_line_s *line = vanc_lines.lines[i];
388         int real_line;
389         void *buf;
390
391         if (!line)
392             break;
393
394         /* FIXME: include hack for certain Decklink cards which mis-represent
395            line numbers for pSF frames */
396         real_line = line->line_number;
397
398         result = vanc->GetBufferForVerticalBlankingLine(real_line, &buf);
399         if (result != S_OK) {
400             av_log(avctx, AV_LOG_ERROR, "Failed to get VANC line %d: %d", real_line, result);
401             continue;
402         }
403
404         /* Generate the full line taking into account all VANC packets on that line */
405         result = klvanc_generate_vanc_line_v210(ctx->vanc_ctx, line, (uint8_t *) buf,
406                                                 ctx->bmd_width);
407         if (result) {
408             av_log(avctx, AV_LOG_ERROR, "Failed to generate VANC line\n");
409             continue;
410         }
411     }
412
413     result = frame->SetAncillaryData(vanc);
414     vanc->Release();
415     if (result != S_OK) {
416         av_log(avctx, AV_LOG_ERROR, "Failed to set vanc: %d", result);
417         ret = AVERROR(EIO);
418     }
419
420 done:
421     for (i = 0; i < vanc_lines.num_lines; i++)
422         klvanc_line_free(vanc_lines.lines[i]);
423
424     return ret;
425 }
426 #endif
427
428 static int decklink_write_video_packet(AVFormatContext *avctx, AVPacket *pkt)
429 {
430     struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
431     struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
432     AVStream *st = avctx->streams[pkt->stream_index];
433     AVFrame *avframe = NULL, *tmp = (AVFrame *)pkt->data;
434     AVPacket *avpacket = NULL;
435     decklink_frame *frame;
436     buffercount_type buffered;
437     HRESULT hr;
438
439     if (st->codecpar->codec_id == AV_CODEC_ID_WRAPPED_AVFRAME) {
440         if (tmp->format != AV_PIX_FMT_UYVY422 ||
441             tmp->width  != ctx->bmd_width ||
442             tmp->height != ctx->bmd_height) {
443             av_log(avctx, AV_LOG_ERROR, "Got a frame with invalid pixel format or dimension.\n");
444             return AVERROR(EINVAL);
445         }
446
447         avframe = av_frame_clone(tmp);
448         if (!avframe) {
449             av_log(avctx, AV_LOG_ERROR, "Could not clone video frame.\n");
450             return AVERROR(EIO);
451         }
452
453         frame = new decklink_frame(ctx, avframe, st->codecpar->codec_id, avframe->height, avframe->width);
454     } else {
455         avpacket = av_packet_clone(pkt);
456         if (!avpacket) {
457             av_log(avctx, AV_LOG_ERROR, "Could not clone video frame.\n");
458             return AVERROR(EIO);
459         }
460
461         frame = new decklink_frame(ctx, avpacket, st->codecpar->codec_id, ctx->bmd_height, ctx->bmd_width);
462
463 #if CONFIG_LIBKLVANC
464         if (decklink_construct_vanc(avctx, ctx, pkt, frame))
465             av_log(avctx, AV_LOG_ERROR, "Failed to construct VANC\n");
466 #endif
467     }
468
469     if (!frame) {
470         av_log(avctx, AV_LOG_ERROR, "Could not create new frame.\n");
471         av_frame_free(&avframe);
472         av_packet_free(&avpacket);
473         return AVERROR(EIO);
474     }
475
476     /* Always keep at most one second of frames buffered. */
477     pthread_mutex_lock(&ctx->mutex);
478     while (ctx->frames_buffer_available_spots == 0) {
479         pthread_cond_wait(&ctx->cond, &ctx->mutex);
480     }
481     ctx->frames_buffer_available_spots--;
482     pthread_mutex_unlock(&ctx->mutex);
483
484     /* Schedule frame for playback. */
485     hr = ctx->dlo->ScheduleVideoFrame((class IDeckLinkVideoFrame *) frame,
486                                       pkt->pts * ctx->bmd_tb_num,
487                                       ctx->bmd_tb_num, ctx->bmd_tb_den);
488     /* Pass ownership to DeckLink, or release on failure */
489     frame->Release();
490     if (hr != S_OK) {
491         av_log(avctx, AV_LOG_ERROR, "Could not schedule video frame."
492                 " error %08x.\n", (uint32_t) hr);
493         return AVERROR(EIO);
494     }
495
496     ctx->dlo->GetBufferedVideoFrameCount(&buffered);
497     av_log(avctx, AV_LOG_DEBUG, "Buffered video frames: %d.\n", (int) buffered);
498     if (pkt->pts > 2 && buffered <= 2)
499         av_log(avctx, AV_LOG_WARNING, "There are not enough buffered video frames."
500                " Video may misbehave!\n");
501
502     /* Preroll video frames. */
503     if (!ctx->playback_started && pkt->pts > ctx->frames_preroll) {
504         av_log(avctx, AV_LOG_DEBUG, "Ending audio preroll.\n");
505         if (ctx->audio && ctx->dlo->EndAudioPreroll() != S_OK) {
506             av_log(avctx, AV_LOG_ERROR, "Could not end audio preroll!\n");
507             return AVERROR(EIO);
508         }
509         av_log(avctx, AV_LOG_DEBUG, "Starting scheduled playback.\n");
510         if (ctx->dlo->StartScheduledPlayback(0, ctx->bmd_tb_den, 1.0) != S_OK) {
511             av_log(avctx, AV_LOG_ERROR, "Could not start scheduled playback!\n");
512             return AVERROR(EIO);
513         }
514         ctx->playback_started = 1;
515     }
516
517     return 0;
518 }
519
520 static int decklink_write_audio_packet(AVFormatContext *avctx, AVPacket *pkt)
521 {
522     struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
523     struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
524     int sample_count = pkt->size / (ctx->channels << 1);
525     buffercount_type buffered;
526
527     ctx->dlo->GetBufferedAudioSampleFrameCount(&buffered);
528     if (pkt->pts > 1 && !buffered)
529         av_log(avctx, AV_LOG_WARNING, "There's no buffered audio."
530                " Audio will misbehave!\n");
531
532     if (ctx->dlo->ScheduleAudioSamples(pkt->data, sample_count, pkt->pts,
533                                        bmdAudioSampleRate48kHz, NULL) != S_OK) {
534         av_log(avctx, AV_LOG_ERROR, "Could not schedule audio samples.\n");
535         return AVERROR(EIO);
536     }
537
538     return 0;
539 }
540
541 extern "C" {
542
543 av_cold int ff_decklink_write_header(AVFormatContext *avctx)
544 {
545     struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
546     struct decklink_ctx *ctx;
547     unsigned int n;
548     int ret;
549
550     ctx = (struct decklink_ctx *) av_mallocz(sizeof(struct decklink_ctx));
551     if (!ctx)
552         return AVERROR(ENOMEM);
553     ctx->list_devices = cctx->list_devices;
554     ctx->list_formats = cctx->list_formats;
555     ctx->preroll      = cctx->preroll;
556     ctx->duplex_mode  = cctx->duplex_mode;
557     cctx->ctx = ctx;
558 #if CONFIG_LIBKLVANC
559     if (klvanc_context_create(&ctx->vanc_ctx) < 0) {
560         av_log(avctx, AV_LOG_ERROR, "Cannot create VANC library context\n");
561         return AVERROR(ENOMEM);
562     }
563     ctx->supports_vanc = 1;
564 #endif
565
566     /* List available devices and exit. */
567     if (ctx->list_devices) {
568         ff_decklink_list_devices_legacy(avctx, 0, 1);
569         return AVERROR_EXIT;
570     }
571
572     ret = ff_decklink_init_device(avctx, avctx->url);
573     if (ret < 0)
574         return ret;
575
576     /* Get output device. */
577     if (ctx->dl->QueryInterface(IID_IDeckLinkOutput, (void **) &ctx->dlo) != S_OK) {
578         av_log(avctx, AV_LOG_ERROR, "Could not open output device from '%s'\n",
579                avctx->url);
580         ret = AVERROR(EIO);
581         goto error;
582     }
583
584     /* List supported formats. */
585     if (ctx->list_formats) {
586         ff_decklink_list_formats(avctx);
587         ret = AVERROR_EXIT;
588         goto error;
589     }
590
591     /* Setup streams. */
592     ret = AVERROR(EIO);
593     for (n = 0; n < avctx->nb_streams; n++) {
594         AVStream *st = avctx->streams[n];
595         AVCodecParameters *c = st->codecpar;
596         if        (c->codec_type == AVMEDIA_TYPE_AUDIO) {
597             if (decklink_setup_audio(avctx, st))
598                 goto error;
599         } else if (c->codec_type == AVMEDIA_TYPE_VIDEO) {
600             if (decklink_setup_video(avctx, st))
601                 goto error;
602         } else {
603             av_log(avctx, AV_LOG_ERROR, "Unsupported stream type.\n");
604             goto error;
605         }
606     }
607
608     return 0;
609
610 error:
611     ff_decklink_cleanup(avctx);
612     return ret;
613 }
614
615 int ff_decklink_write_packet(AVFormatContext *avctx, AVPacket *pkt)
616 {
617     struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
618     struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
619     AVStream *st = avctx->streams[pkt->stream_index];
620
621     ctx->last_pts = FFMAX(ctx->last_pts, pkt->pts);
622
623     if      (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
624         return decklink_write_video_packet(avctx, pkt);
625     else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
626         return decklink_write_audio_packet(avctx, pkt);
627
628     return AVERROR(EIO);
629 }
630
631 int ff_decklink_list_output_devices(AVFormatContext *avctx, struct AVDeviceInfoList *device_list)
632 {
633     return ff_decklink_list_devices(avctx, device_list, 0, 1);
634 }
635
636 } /* extern "C" */