OSDN Git Service

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