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