FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
decklink_enc.cpp
Go to the documentation of this file.
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 }
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, long width,
42  long height, void *buffer) :
43  _ctx(ctx), _avframe(avframe), _width(width),
44  _height(height), _buffer(buffer), _refs(0) { }
45 
46  virtual long STDMETHODCALLTYPE GetWidth (void) { return _width; }
47  virtual long STDMETHODCALLTYPE GetHeight (void) { return _height; }
48  virtual long STDMETHODCALLTYPE GetRowBytes (void) { return _width<<1; }
49  virtual BMDPixelFormat STDMETHODCALLTYPE GetPixelFormat(void) { return bmdFormat8BitYUV; }
50  virtual BMDFrameFlags STDMETHODCALLTYPE GetFlags (void) { return bmdVideoOutputFlagDefault; }
51  virtual HRESULT STDMETHODCALLTYPE GetBytes (void **buffer) { *buffer = _buffer; return S_OK; }
52 
53  virtual HRESULT STDMETHODCALLTYPE GetTimecode (BMDTimecodeFormat format, IDeckLinkTimecode **timecode) { return S_FALSE; }
54  virtual HRESULT STDMETHODCALLTYPE GetAncillaryData(IDeckLinkVideoFrameAncillary **ancillary) { return S_FALSE; }
55 
56  virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv) { return E_NOINTERFACE; }
57  virtual ULONG STDMETHODCALLTYPE AddRef(void) { return ++_refs; }
58  virtual ULONG STDMETHODCALLTYPE Release(void) { if (!--_refs) delete this; return _refs; }
59 
60  struct decklink_ctx *_ctx;
62 
63 private:
64  long _width;
65  long _height;
66  void *_buffer;
67  int _refs;
68 };
69 
70 class decklink_output_callback : public IDeckLinkVideoOutputCallback
71 {
72 public:
73  virtual HRESULT STDMETHODCALLTYPE ScheduledFrameCompleted(IDeckLinkVideoFrame *_frame, BMDOutputFrameCompletionResult result)
74  {
75  decklink_frame *frame = static_cast<decklink_frame *>(_frame);
76  struct decklink_ctx *ctx = frame->_ctx;
77  AVFrame *avframe = frame->_avframe;
78 
79  av_frame_free(&avframe);
80 
81  sem_post(&ctx->semaphore);
82 
83  return S_OK;
84  }
85  virtual HRESULT STDMETHODCALLTYPE ScheduledPlaybackHasStopped(void) { return S_OK; }
86  virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv) { return E_NOINTERFACE; }
87  virtual ULONG STDMETHODCALLTYPE AddRef(void) { return 1; }
88  virtual ULONG STDMETHODCALLTYPE Release(void) { return 1; }
89 };
90 
92 {
93  struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
94  struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
95  AVCodecContext *c = st->codec;
96 
97  if (ctx->video) {
98  av_log(avctx, AV_LOG_ERROR, "Only one video stream is supported!\n");
99  return -1;
100  }
101 
102  if (c->pix_fmt != AV_PIX_FMT_UYVY422) {
103  av_log(avctx, AV_LOG_ERROR, "Unsupported pixel format!"
104  " Only AV_PIX_FMT_UYVY422 is supported.\n");
105  return -1;
106  }
107  if (ff_decklink_set_format(avctx, c->width, c->height,
108  c->time_base.num, c->time_base.den)) {
109  av_log(avctx, AV_LOG_ERROR, "Unsupported video size or framerate!"
110  " Check available formats with -list_formats 1.\n");
111  return -1;
112  }
113  if (ctx->dlo->EnableVideoOutput(ctx->bmd_mode,
114  bmdVideoOutputFlagDefault) != S_OK) {
115  av_log(avctx, AV_LOG_ERROR, "Could not enable video output!\n");
116  return -1;
117  }
118 
119  /* Set callback. */
120  ctx->output_callback = new decklink_output_callback();
121  ctx->dlo->SetScheduledFrameCompletionCallback(ctx->output_callback);
122 
123  /* Start video semaphore. */
124  ctx->frames_preroll = c->time_base.den * ctx->preroll;
125  if (c->time_base.den > 1000)
126  ctx->frames_preroll /= 1000;
127 
128  /* Buffer twice as many frames as the preroll. */
129  ctx->frames_buffer = ctx->frames_preroll * 2;
130  ctx->frames_buffer = FFMIN(ctx->frames_buffer, 60);
131  sem_init(&ctx->semaphore, 0, ctx->frames_buffer);
132 
133  /* The device expects the framerate to be fixed. */
135 
136  ctx->video = 1;
137 
138  return 0;
139 }
140 
142 {
143  struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
144  struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
145  AVCodecContext *c = st->codec;
146 
147  if (ctx->audio) {
148  av_log(avctx, AV_LOG_ERROR, "Only one audio stream is supported!\n");
149  return -1;
150  }
151  if (c->sample_rate != 48000) {
152  av_log(avctx, AV_LOG_ERROR, "Unsupported sample rate!"
153  " Only 48kHz is supported.\n");
154  return -1;
155  }
156  if (c->channels != 2 && c->channels != 8) {
157  av_log(avctx, AV_LOG_ERROR, "Unsupported number of channels!"
158  " Only stereo and 7.1 are supported.\n");
159  return -1;
160  }
161  if (ctx->dlo->EnableAudioOutput(bmdAudioSampleRate48kHz,
162  bmdAudioSampleType16bitInteger,
163  c->channels,
164  bmdAudioOutputStreamTimestamped) != S_OK) {
165  av_log(avctx, AV_LOG_ERROR, "Could not enable audio output!\n");
166  return -1;
167  }
168  if (ctx->dlo->BeginAudioPreroll() != S_OK) {
169  av_log(avctx, AV_LOG_ERROR, "Could not begin audio preroll!\n");
170  return -1;
171  }
172 
173  /* The device expects the sample rate to be fixed. */
174  avpriv_set_pts_info(st, 64, 1, c->sample_rate);
175  ctx->channels = c->channels;
176 
177  ctx->audio = 1;
178 
179  return 0;
180 }
181 
183 {
184  struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
185  struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
186 
187  if (ctx->playback_started) {
188  BMDTimeValue actual;
189  ctx->dlo->StopScheduledPlayback(ctx->last_pts * ctx->bmd_tb_num,
190  &actual, ctx->bmd_tb_den);
191  ctx->dlo->DisableVideoOutput();
192  if (ctx->audio)
193  ctx->dlo->DisableAudioOutput();
194  }
195 
196  ff_decklink_cleanup(avctx);
197 
198  if (ctx->output_callback)
199  delete ctx->output_callback;
200 
201  sem_destroy(&ctx->semaphore);
202 
203  av_freep(&cctx->ctx);
204 
205  return 0;
206 }
207 
209 {
210  struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
211  struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
212  AVPicture *avpicture = (AVPicture *) pkt->data;
213  AVFrame *avframe, *tmp;
215  buffercount_type buffered;
216  HRESULT hr;
217 
218  /* HACK while av_uncoded_frame() isn't implemented */
219  int ret;
220 
221  tmp = av_frame_alloc();
222  if (!tmp)
223  return AVERROR(ENOMEM);
224  tmp->format = AV_PIX_FMT_UYVY422;
225  tmp->width = ctx->bmd_width;
226  tmp->height = ctx->bmd_height;
227  ret = av_frame_get_buffer(tmp, 32);
228  if (ret < 0) {
229  av_frame_free(&tmp);
230  return ret;
231  }
232  av_image_copy(tmp->data, tmp->linesize, (const uint8_t **) avpicture->data,
233  avpicture->linesize, (AVPixelFormat) tmp->format, tmp->width,
234  tmp->height);
235  avframe = av_frame_clone(tmp);
236  av_frame_free(&tmp);
237  if (!avframe) {
238  av_log(avctx, AV_LOG_ERROR, "Could not clone video frame.\n");
239  return AVERROR(EIO);
240  }
241  /* end HACK */
242 
243  frame = new decklink_frame(ctx, avframe, ctx->bmd_width, ctx->bmd_height,
244  (void *) avframe->data[0]);
245  if (!frame) {
246  av_log(avctx, AV_LOG_ERROR, "Could not create new frame.\n");
247  return AVERROR(EIO);
248  }
249 
250  /* Always keep at most one second of frames buffered. */
251  sem_wait(&ctx->semaphore);
252 
253  /* Schedule frame for playback. */
254  hr = ctx->dlo->ScheduleVideoFrame((struct IDeckLinkVideoFrame *) frame,
255  pkt->pts * ctx->bmd_tb_num,
256  ctx->bmd_tb_num, ctx->bmd_tb_den);
257  if (hr != S_OK) {
258  av_log(avctx, AV_LOG_ERROR, "Could not schedule video frame."
259  " error %08x.\n", (uint32_t) hr);
260  frame->Release();
261  return AVERROR(EIO);
262  }
263 
264  ctx->dlo->GetBufferedVideoFrameCount(&buffered);
265  av_log(avctx, AV_LOG_DEBUG, "Buffered video frames: %d.\n", (int) buffered);
266  if (pkt->pts > 2 && buffered <= 2)
267  av_log(avctx, AV_LOG_WARNING, "There are not enough buffered video frames."
268  " Video may misbehave!\n");
269 
270  /* Preroll video frames. */
271  if (!ctx->playback_started && pkt->pts > ctx->frames_preroll) {
272  av_log(avctx, AV_LOG_DEBUG, "Ending audio preroll.\n");
273  if (ctx->audio && ctx->dlo->EndAudioPreroll() != S_OK) {
274  av_log(avctx, AV_LOG_ERROR, "Could not end audio preroll!\n");
275  return AVERROR(EIO);
276  }
277  av_log(avctx, AV_LOG_DEBUG, "Starting scheduled playback.\n");
278  if (ctx->dlo->StartScheduledPlayback(0, ctx->bmd_tb_den, 1.0) != S_OK) {
279  av_log(avctx, AV_LOG_ERROR, "Could not start scheduled playback!\n");
280  return AVERROR(EIO);
281  }
282  ctx->playback_started = 1;
283  }
284 
285  return 0;
286 }
287 
289 {
290  struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
291  struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
292  int sample_count = pkt->size / (ctx->channels << 1);
293  buffercount_type buffered;
294 
295  ctx->dlo->GetBufferedAudioSampleFrameCount(&buffered);
296  if (pkt->pts > 1 && !buffered)
297  av_log(avctx, AV_LOG_WARNING, "There's no buffered audio."
298  " Audio will misbehave!\n");
299 
300  if (ctx->dlo->ScheduleAudioSamples(pkt->data, sample_count, pkt->pts,
301  bmdAudioSampleRate48kHz, NULL) != S_OK) {
302  av_log(avctx, AV_LOG_ERROR, "Could not schedule audio samples.\n");
303  return AVERROR(EIO);
304  }
305 
306  return 0;
307 }
308 
309 extern "C" {
310 
312 {
313  struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
314  struct decklink_ctx *ctx;
315  unsigned int n;
316  int ret;
317 
318  ctx = (struct decklink_ctx *) av_mallocz(sizeof(struct decklink_ctx));
319  if (!ctx)
320  return AVERROR(ENOMEM);
321  ctx->list_devices = cctx->list_devices;
322  ctx->list_formats = cctx->list_formats;
323  ctx->preroll = cctx->preroll;
324  cctx->ctx = ctx;
325 
326  /* List available devices. */
327  if (ctx->list_devices) {
329  return AVERROR_EXIT;
330  }
331 
332  ret = ff_decklink_init_device(avctx, avctx->filename);
333  if (ret < 0)
334  return ret;
335 
336  /* Get output device. */
337  if (ctx->dl->QueryInterface(IID_IDeckLinkOutput, (void **) &ctx->dlo) != S_OK) {
338  av_log(avctx, AV_LOG_ERROR, "Could not open output device from '%s'\n",
339  avctx->filename);
340  ret = AVERROR(EIO);
341  goto error;
342  }
343 
344  /* List supported formats. */
345  if (ctx->list_formats) {
347  ret = AVERROR_EXIT;
348  goto error;
349  }
350 
351  /* Setup streams. */
352  ret = AVERROR(EIO);
353  for (n = 0; n < avctx->nb_streams; n++) {
354  AVStream *st = avctx->streams[n];
355  AVCodecContext *c = st->codec;
356  if (c->codec_type == AVMEDIA_TYPE_AUDIO) {
357  if (decklink_setup_audio(avctx, st))
358  goto error;
359  } else if (c->codec_type == AVMEDIA_TYPE_VIDEO) {
360  if (decklink_setup_video(avctx, st))
361  goto error;
362  } else {
363  av_log(avctx, AV_LOG_ERROR, "Unsupported stream type.\n");
364  goto error;
365  }
366  }
367 
368  return 0;
369 
370 error:
371  ff_decklink_cleanup(avctx);
372  return ret;
373 }
374 
376 {
377  struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
378  struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
379  AVStream *st = avctx->streams[pkt->stream_index];
380 
381  ctx->last_pts = FFMAX(ctx->last_pts, pkt->pts);
382 
383  if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
384  return decklink_write_video_packet(avctx, pkt);
385  else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
386  return decklink_write_audio_packet(avctx, pkt);
387 
388  return AVERROR(EIO);
389 }
390 
391 } /* extern "C" */
packed YUV 4:2:2, 16bpp, Cb Y0 Cr Y1
Definition: pixfmt.h:82
#define NULL
Definition: coverity.c:32
#define S_OK
Definition: windows2linux.h:40
This structure describes decoded (raw) audio or video data.
Definition: frame.h:184
misc image utilities
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:182
void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits, unsigned int pts_num, unsigned int pts_den)
Set the time base and wrapping info for a given stream.
Definition: utils.c:4560
int num
Numerator.
Definition: rational.h:59
int size
Definition: avcodec.h:1602
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
Definition: avcodec.h:1904
void * av_mallocz(size_t size)
Allocate a memory block with alignment suitable for all memory accesses (including vectors if availab...
Definition: mem.c:252
static AVPacket pkt
Picture data structure.
Definition: avcodec.h:3889
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avcodec.h:1813
Format I/O context.
Definition: avformat.h:1338
uint8_t
#define av_cold
Definition: attributes.h:82
AVFrame * av_frame_alloc(void)
Allocate an AVFrame and set its fields to default values.
Definition: frame.c:145
attribute_deprecated int linesize[AV_NUM_DATA_POINTERS]
number of bytes per line
Definition: avcodec.h:3893
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:1406
static AVFrame * frame
#define height
#define sem_init
Definition: semaphore.h:40
uint8_t * data
Definition: avcodec.h:1601
#define E_NOINTERFACE
Definition: windows2linux.h:42
#define sem_post(psem)
Definition: semaphore.h:26
#define av_log(a,...)
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:176
#define AVERROR(e)
Definition: error.h:43
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
Definition: frame.c:158
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: log.h:197
#define sem_destroy(psem)
Definition: semaphore.h:29
#define FFMAX(a, b)
Definition: common.h:94
void av_image_copy(uint8_t *dst_data[4], int dst_linesizes[4], const uint8_t *src_data[4], const int src_linesizes[4], enum AVPixelFormat pix_fmt, int width, int height)
Copy image in src_data to dst_data.
Definition: imgutils.c:302
unsigned int nb_streams
Number of elements in AVFormatContext.streams.
Definition: avformat.h:1394
char filename[1024]
input or output filename
Definition: avformat.h:1414
#define FFMIN(a, b)
Definition: common.h:96
#define width
int width
picture width / height.
Definition: avcodec.h:1863
AVFormatContext * ctx
Definition: movenc.c:48
attribute_deprecated uint8_t * data[AV_NUM_DATA_POINTERS]
pointers to the image data planes
Definition: avcodec.h:3891
int n
Definition: avisynth_c.h:684
#define AVERROR_EXIT
Immediate exit was requested; the called function should not be restarted.
Definition: error.h:56
AVFrame * av_frame_clone(const AVFrame *src)
Create a new frame that references the same data as src.
Definition: frame.c:480
Stream structure.
Definition: avformat.h:889
enum AVMediaType codec_type
Definition: avcodec.h:1684
int sample_rate
samples per second
Definition: avcodec.h:2438
void * LPVOID
main external API structure.
Definition: avcodec.h:1676
static const char * format
Definition: movenc.c:47
int av_frame_get_buffer(AVFrame *frame, int align)
Allocate new buffer(s) for audio or video data.
Definition: frame.c:275
DWORD HRESULT
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition: frame.h:198
Main libavformat public API header.
static double c[64]
uint32_t ULONG
int den
Denominator.
Definition: rational.h:60
#define S_FALSE
Definition: windows2linux.h:41
int channels
number of audio channels
Definition: avcodec.h:2439
static uint8_t tmp[8]
Definition: des.c:38
void * priv_data
Format private data.
Definition: avformat.h:1366
#define sem_wait(psem)
Definition: semaphore.h:27
#define av_freep(p)
int stream_index
Definition: avcodec.h:1603
AVPixelFormat
Pixel format.
Definition: pixfmt.h:60
This structure stores compressed data.
Definition: avcodec.h:1578
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: avcodec.h:1594
GLuint buffer
Definition: opengl_enc.c:102