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