]> git.sesse.net Git - ffmpeg/blob - libavdevice/decklink_enc.cpp
Merge commit 'ea8ae27a5e112d06fd5625f640e40849e6313f0c'
[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
42
43 /* DeckLink callback class declaration */
44 class decklink_frame : public IDeckLinkVideoFrame
45 {
46 public:
47     decklink_frame(struct decklink_ctx *ctx, AVFrame *avframe, AVCodecID codec_id, int height, int width) :
48         _ctx(ctx), _avframe(avframe), _avpacket(NULL), _codec_id(codec_id), _height(height), _width(width),  _refs(1) { }
49     decklink_frame(struct decklink_ctx *ctx, AVPacket *avpacket, AVCodecID codec_id, int height, int width) :
50         _ctx(ctx), _avframe(NULL), _avpacket(avpacket), _codec_id(codec_id), _height(height), _width(width), _refs(1) { }
51
52     virtual long           STDMETHODCALLTYPE GetWidth      (void)          { return _width; }
53     virtual long           STDMETHODCALLTYPE GetHeight     (void)          { return _height; }
54     virtual long           STDMETHODCALLTYPE GetRowBytes   (void)
55     {
56       if (_codec_id == AV_CODEC_ID_WRAPPED_AVFRAME)
57           return _avframe->linesize[0] < 0 ? -_avframe->linesize[0] : _avframe->linesize[0];
58       else
59           return ((GetWidth() + 47) / 48) * 128;
60     }
61     virtual BMDPixelFormat STDMETHODCALLTYPE GetPixelFormat(void)
62     {
63         if (_codec_id == AV_CODEC_ID_WRAPPED_AVFRAME)
64             return bmdFormat8BitYUV;
65         else
66             return bmdFormat10BitYUV;
67     }
68     virtual BMDFrameFlags  STDMETHODCALLTYPE GetFlags      (void)
69     {
70        if (_codec_id == AV_CODEC_ID_WRAPPED_AVFRAME)
71            return _avframe->linesize[0] < 0 ? bmdFrameFlagFlipVertical : bmdFrameFlagDefault;
72        else
73            return bmdFrameFlagDefault;
74     }
75
76     virtual HRESULT        STDMETHODCALLTYPE GetBytes      (void **buffer)
77     {
78         if (_codec_id == AV_CODEC_ID_WRAPPED_AVFRAME) {
79             if (_avframe->linesize[0] < 0)
80                 *buffer = (void *)(_avframe->data[0] + _avframe->linesize[0] * (_avframe->height - 1));
81             else
82                 *buffer = (void *)(_avframe->data[0]);
83         } else {
84             *buffer = (void *)(_avpacket->data);
85         }
86         return S_OK;
87     }
88
89     virtual HRESULT STDMETHODCALLTYPE GetTimecode     (BMDTimecodeFormat format, IDeckLinkTimecode **timecode) { return S_FALSE; }
90     virtual HRESULT STDMETHODCALLTYPE GetAncillaryData(IDeckLinkVideoFrameAncillary **ancillary)               { return S_FALSE; }
91
92     virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv) { return E_NOINTERFACE; }
93     virtual ULONG   STDMETHODCALLTYPE AddRef(void)                            { return ++_refs; }
94     virtual ULONG   STDMETHODCALLTYPE Release(void)
95     {
96         int ret = --_refs;
97         if (!ret) {
98             av_frame_free(&_avframe);
99             av_packet_free(&_avpacket);
100             delete this;
101         }
102         return ret;
103     }
104
105     struct decklink_ctx *_ctx;
106     AVFrame *_avframe;
107     AVPacket *_avpacket;
108     AVCodecID _codec_id;
109     int _height;
110     int _width;
111
112 private:
113     std::atomic<int>  _refs;
114 };
115
116 class decklink_output_callback : public IDeckLinkVideoOutputCallback
117 {
118 public:
119     virtual HRESULT STDMETHODCALLTYPE ScheduledFrameCompleted(IDeckLinkVideoFrame *_frame, BMDOutputFrameCompletionResult result)
120     {
121         decklink_frame *frame = static_cast<decklink_frame *>(_frame);
122         struct decklink_ctx *ctx = frame->_ctx;
123
124         if (frame->_avframe)
125             av_frame_unref(frame->_avframe);
126         if (frame->_avpacket)
127             av_packet_unref(frame->_avpacket);
128
129         pthread_mutex_lock(&ctx->mutex);
130         ctx->frames_buffer_available_spots++;
131         pthread_cond_broadcast(&ctx->cond);
132         pthread_mutex_unlock(&ctx->mutex);
133
134         return S_OK;
135     }
136     virtual HRESULT STDMETHODCALLTYPE ScheduledPlaybackHasStopped(void)       { return S_OK; }
137     virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv) { return E_NOINTERFACE; }
138     virtual ULONG   STDMETHODCALLTYPE AddRef(void)                            { return 1; }
139     virtual ULONG   STDMETHODCALLTYPE Release(void)                           { return 1; }
140 };
141
142 static int decklink_setup_video(AVFormatContext *avctx, AVStream *st)
143 {
144     struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
145     struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
146     AVCodecParameters *c = st->codecpar;
147
148     if (ctx->video) {
149         av_log(avctx, AV_LOG_ERROR, "Only one video stream is supported!\n");
150         return -1;
151     }
152
153     if (c->codec_id == AV_CODEC_ID_WRAPPED_AVFRAME) {
154         if (c->format != AV_PIX_FMT_UYVY422) {
155             av_log(avctx, AV_LOG_ERROR, "Unsupported pixel format!"
156                    " Only AV_PIX_FMT_UYVY422 is supported.\n");
157             return -1;
158         }
159     } else if (c->codec_id != AV_CODEC_ID_V210) {
160         av_log(avctx, AV_LOG_ERROR, "Unsupported codec type!"
161                " Only V210 and wrapped frame with AV_PIX_FMT_UYVY422 are supported.\n");
162         return -1;
163     }
164
165     if (ff_decklink_set_configs(avctx, DIRECTION_OUT) < 0) {
166         av_log(avctx, AV_LOG_ERROR, "Could not set output configuration\n");
167         return -1;
168     }
169     if (ff_decklink_set_format(avctx, c->width, c->height,
170                             st->time_base.num, st->time_base.den, c->field_order)) {
171         av_log(avctx, AV_LOG_ERROR, "Unsupported video size, framerate or field order!"
172                " Check available formats with -list_formats 1.\n");
173         return -1;
174     }
175     if (ctx->dlo->EnableVideoOutput(ctx->bmd_mode,
176                                     bmdVideoOutputFlagDefault) != S_OK) {
177         av_log(avctx, AV_LOG_ERROR, "Could not enable video output!\n");
178         return -1;
179     }
180
181     /* Set callback. */
182     ctx->output_callback = new decklink_output_callback();
183     ctx->dlo->SetScheduledFrameCompletionCallback(ctx->output_callback);
184
185     ctx->frames_preroll = st->time_base.den * ctx->preroll;
186     if (st->time_base.den > 1000)
187         ctx->frames_preroll /= 1000;
188
189     /* Buffer twice as many frames as the preroll. */
190     ctx->frames_buffer = ctx->frames_preroll * 2;
191     ctx->frames_buffer = FFMIN(ctx->frames_buffer, 60);
192     pthread_mutex_init(&ctx->mutex, NULL);
193     pthread_cond_init(&ctx->cond, NULL);
194     ctx->frames_buffer_available_spots = ctx->frames_buffer;
195
196     av_log(avctx, AV_LOG_DEBUG, "output: %s, preroll: %d, frames buffer size: %d\n",
197            avctx->url, ctx->frames_preroll, ctx->frames_buffer);
198
199     /* The device expects the framerate to be fixed. */
200     avpriv_set_pts_info(st, 64, st->time_base.num, st->time_base.den);
201
202     ctx->video = 1;
203
204     return 0;
205 }
206
207 static int decklink_setup_audio(AVFormatContext *avctx, AVStream *st)
208 {
209     struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
210     struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
211     AVCodecParameters *c = st->codecpar;
212
213     if (ctx->audio) {
214         av_log(avctx, AV_LOG_ERROR, "Only one audio stream is supported!\n");
215         return -1;
216     }
217     if (c->sample_rate != 48000) {
218         av_log(avctx, AV_LOG_ERROR, "Unsupported sample rate!"
219                " Only 48kHz is supported.\n");
220         return -1;
221     }
222     if (c->channels != 2 && c->channels != 8 && c->channels != 16) {
223         av_log(avctx, AV_LOG_ERROR, "Unsupported number of channels!"
224                " Only 2, 8 or 16 channels are supported.\n");
225         return -1;
226     }
227     if (ctx->dlo->EnableAudioOutput(bmdAudioSampleRate48kHz,
228                                     bmdAudioSampleType16bitInteger,
229                                     c->channels,
230                                     bmdAudioOutputStreamTimestamped) != S_OK) {
231         av_log(avctx, AV_LOG_ERROR, "Could not enable audio output!\n");
232         return -1;
233     }
234     if (ctx->dlo->BeginAudioPreroll() != S_OK) {
235         av_log(avctx, AV_LOG_ERROR, "Could not begin audio preroll!\n");
236         return -1;
237     }
238
239     /* The device expects the sample rate to be fixed. */
240     avpriv_set_pts_info(st, 64, 1, c->sample_rate);
241     ctx->channels = c->channels;
242
243     ctx->audio = 1;
244
245     return 0;
246 }
247
248 av_cold int ff_decklink_write_trailer(AVFormatContext *avctx)
249 {
250     struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
251     struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
252
253     if (ctx->playback_started) {
254         BMDTimeValue actual;
255         ctx->dlo->StopScheduledPlayback(ctx->last_pts * ctx->bmd_tb_num,
256                                         &actual, ctx->bmd_tb_den);
257         ctx->dlo->DisableVideoOutput();
258         if (ctx->audio)
259             ctx->dlo->DisableAudioOutput();
260     }
261
262     ff_decklink_cleanup(avctx);
263
264     if (ctx->output_callback)
265         delete ctx->output_callback;
266
267     pthread_mutex_destroy(&ctx->mutex);
268     pthread_cond_destroy(&ctx->cond);
269
270     av_freep(&cctx->ctx);
271
272     return 0;
273 }
274
275 static int decklink_write_video_packet(AVFormatContext *avctx, AVPacket *pkt)
276 {
277     struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
278     struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
279     AVStream *st = avctx->streams[pkt->stream_index];
280     AVFrame *avframe = NULL, *tmp = (AVFrame *)pkt->data;
281     AVPacket *avpacket = NULL;
282     decklink_frame *frame;
283     buffercount_type buffered;
284     HRESULT hr;
285
286     if (st->codecpar->codec_id == AV_CODEC_ID_WRAPPED_AVFRAME) {
287         if (tmp->format != AV_PIX_FMT_UYVY422 ||
288             tmp->width  != ctx->bmd_width ||
289             tmp->height != ctx->bmd_height) {
290             av_log(avctx, AV_LOG_ERROR, "Got a frame with invalid pixel format or dimension.\n");
291             return AVERROR(EINVAL);
292         }
293
294         avframe = av_frame_clone(tmp);
295         if (!avframe) {
296             av_log(avctx, AV_LOG_ERROR, "Could not clone video frame.\n");
297             return AVERROR(EIO);
298         }
299
300         frame = new decklink_frame(ctx, avframe, st->codecpar->codec_id, avframe->height, avframe->width);
301     } else {
302         avpacket = av_packet_clone(pkt);
303         if (!avpacket) {
304             av_log(avctx, AV_LOG_ERROR, "Could not clone video frame.\n");
305             return AVERROR(EIO);
306         }
307
308         frame = new decklink_frame(ctx, avpacket, st->codecpar->codec_id, ctx->bmd_height, ctx->bmd_width);
309     }
310
311     if (!frame) {
312         av_log(avctx, AV_LOG_ERROR, "Could not create new frame.\n");
313         av_frame_free(&avframe);
314         av_packet_free(&avpacket);
315         return AVERROR(EIO);
316     }
317
318     /* Always keep at most one second of frames buffered. */
319     pthread_mutex_lock(&ctx->mutex);
320     while (ctx->frames_buffer_available_spots == 0) {
321         pthread_cond_wait(&ctx->cond, &ctx->mutex);
322     }
323     ctx->frames_buffer_available_spots--;
324     pthread_mutex_unlock(&ctx->mutex);
325
326     /* Schedule frame for playback. */
327     hr = ctx->dlo->ScheduleVideoFrame((class IDeckLinkVideoFrame *) frame,
328                                       pkt->pts * ctx->bmd_tb_num,
329                                       ctx->bmd_tb_num, ctx->bmd_tb_den);
330     /* Pass ownership to DeckLink, or release on failure */
331     frame->Release();
332     if (hr != S_OK) {
333         av_log(avctx, AV_LOG_ERROR, "Could not schedule video frame."
334                 " error %08x.\n", (uint32_t) hr);
335         return AVERROR(EIO);
336     }
337
338     ctx->dlo->GetBufferedVideoFrameCount(&buffered);
339     av_log(avctx, AV_LOG_DEBUG, "Buffered video frames: %d.\n", (int) buffered);
340     if (pkt->pts > 2 && buffered <= 2)
341         av_log(avctx, AV_LOG_WARNING, "There are not enough buffered video frames."
342                " Video may misbehave!\n");
343
344     /* Preroll video frames. */
345     if (!ctx->playback_started && pkt->pts > ctx->frames_preroll) {
346         av_log(avctx, AV_LOG_DEBUG, "Ending audio preroll.\n");
347         if (ctx->audio && ctx->dlo->EndAudioPreroll() != S_OK) {
348             av_log(avctx, AV_LOG_ERROR, "Could not end audio preroll!\n");
349             return AVERROR(EIO);
350         }
351         av_log(avctx, AV_LOG_DEBUG, "Starting scheduled playback.\n");
352         if (ctx->dlo->StartScheduledPlayback(0, ctx->bmd_tb_den, 1.0) != S_OK) {
353             av_log(avctx, AV_LOG_ERROR, "Could not start scheduled playback!\n");
354             return AVERROR(EIO);
355         }
356         ctx->playback_started = 1;
357     }
358
359     return 0;
360 }
361
362 static int decklink_write_audio_packet(AVFormatContext *avctx, AVPacket *pkt)
363 {
364     struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
365     struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
366     int sample_count = pkt->size / (ctx->channels << 1);
367     buffercount_type buffered;
368
369     ctx->dlo->GetBufferedAudioSampleFrameCount(&buffered);
370     if (pkt->pts > 1 && !buffered)
371         av_log(avctx, AV_LOG_WARNING, "There's no buffered audio."
372                " Audio will misbehave!\n");
373
374     if (ctx->dlo->ScheduleAudioSamples(pkt->data, sample_count, pkt->pts,
375                                        bmdAudioSampleRate48kHz, NULL) != S_OK) {
376         av_log(avctx, AV_LOG_ERROR, "Could not schedule audio samples.\n");
377         return AVERROR(EIO);
378     }
379
380     return 0;
381 }
382
383 extern "C" {
384
385 av_cold int ff_decklink_write_header(AVFormatContext *avctx)
386 {
387     struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
388     struct decklink_ctx *ctx;
389     unsigned int n;
390     int ret;
391
392     ctx = (struct decklink_ctx *) av_mallocz(sizeof(struct decklink_ctx));
393     if (!ctx)
394         return AVERROR(ENOMEM);
395     ctx->list_devices = cctx->list_devices;
396     ctx->list_formats = cctx->list_formats;
397     ctx->preroll      = cctx->preroll;
398     cctx->ctx = ctx;
399
400     /* List available devices and exit. */
401     if (ctx->list_devices) {
402         ff_decklink_list_devices_legacy(avctx, 0, 1);
403         return AVERROR_EXIT;
404     }
405
406     ret = ff_decklink_init_device(avctx, avctx->url);
407     if (ret < 0)
408         return ret;
409
410     /* Get output device. */
411     if (ctx->dl->QueryInterface(IID_IDeckLinkOutput, (void **) &ctx->dlo) != S_OK) {
412         av_log(avctx, AV_LOG_ERROR, "Could not open output device from '%s'\n",
413                avctx->url);
414         ret = AVERROR(EIO);
415         goto error;
416     }
417
418     /* List supported formats. */
419     if (ctx->list_formats) {
420         ff_decklink_list_formats(avctx);
421         ret = AVERROR_EXIT;
422         goto error;
423     }
424
425     /* Setup streams. */
426     ret = AVERROR(EIO);
427     for (n = 0; n < avctx->nb_streams; n++) {
428         AVStream *st = avctx->streams[n];
429         AVCodecParameters *c = st->codecpar;
430         if        (c->codec_type == AVMEDIA_TYPE_AUDIO) {
431             if (decklink_setup_audio(avctx, st))
432                 goto error;
433         } else if (c->codec_type == AVMEDIA_TYPE_VIDEO) {
434             if (decklink_setup_video(avctx, st))
435                 goto error;
436         } else {
437             av_log(avctx, AV_LOG_ERROR, "Unsupported stream type.\n");
438             goto error;
439         }
440     }
441
442     return 0;
443
444 error:
445     ff_decklink_cleanup(avctx);
446     return ret;
447 }
448
449 int ff_decklink_write_packet(AVFormatContext *avctx, AVPacket *pkt)
450 {
451     struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
452     struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
453     AVStream *st = avctx->streams[pkt->stream_index];
454
455     ctx->last_pts = FFMAX(ctx->last_pts, pkt->pts);
456
457     if      (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
458         return decklink_write_video_packet(avctx, pkt);
459     else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
460         return decklink_write_audio_packet(avctx, pkt);
461
462     return AVERROR(EIO);
463 }
464
465 int ff_decklink_list_output_devices(AVFormatContext *avctx, struct AVDeviceInfoList *device_list)
466 {
467     return ff_decklink_list_devices(avctx, device_list, 0, 1);
468 }
469
470 } /* extern "C" */