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 <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:
48  _ctx(ctx), _avframe(avframe), _avpacket(NULL), _codec_id(codec_id), _height(height), _width(width), _refs(1) { }
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  {
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  {
64  return bmdFormat8BitYUV;
65  else
66  return bmdFormat10BitYUV;
67  }
68  virtual BMDFrameFlags STDMETHODCALLTYPE GetFlags (void)
69  {
71  return _avframe->linesize[0] < 0 ? bmdFrameFlagFlipVertical : bmdFrameFlagDefault;
72  else
73  return bmdFrameFlagDefault;
74  }
75 
76  virtual HRESULT STDMETHODCALLTYPE GetBytes (void **buffer)
77  {
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) {
100  delete this;
101  }
102  return ret;
103  }
104 
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);
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 
143 {
144  struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
145  struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
147 
148  if (ctx->video) {
149  av_log(avctx, AV_LOG_ERROR, "Only one video stream is supported!\n");
150  return -1;
151  }
152 
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  /* The device expects the framerate to be fixed. */
197  avpriv_set_pts_info(st, 64, st->time_base.num, st->time_base.den);
198 
199  ctx->video = 1;
200 
201  return 0;
202 }
203 
205 {
206  struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
207  struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
209 
210  if (ctx->audio) {
211  av_log(avctx, AV_LOG_ERROR, "Only one audio stream is supported!\n");
212  return -1;
213  }
214  if (c->sample_rate != 48000) {
215  av_log(avctx, AV_LOG_ERROR, "Unsupported sample rate!"
216  " Only 48kHz is supported.\n");
217  return -1;
218  }
219  if (c->channels != 2 && c->channels != 8 && c->channels != 16) {
220  av_log(avctx, AV_LOG_ERROR, "Unsupported number of channels!"
221  " Only 2, 8 or 16 channels are supported.\n");
222  return -1;
223  }
224  if (ctx->dlo->EnableAudioOutput(bmdAudioSampleRate48kHz,
225  bmdAudioSampleType16bitInteger,
226  c->channels,
227  bmdAudioOutputStreamTimestamped) != S_OK) {
228  av_log(avctx, AV_LOG_ERROR, "Could not enable audio output!\n");
229  return -1;
230  }
231  if (ctx->dlo->BeginAudioPreroll() != S_OK) {
232  av_log(avctx, AV_LOG_ERROR, "Could not begin audio preroll!\n");
233  return -1;
234  }
235 
236  /* The device expects the sample rate to be fixed. */
237  avpriv_set_pts_info(st, 64, 1, c->sample_rate);
238  ctx->channels = c->channels;
239 
240  ctx->audio = 1;
241 
242  return 0;
243 }
244 
246 {
247  struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
248  struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
249 
250  if (ctx->playback_started) {
251  BMDTimeValue actual;
252  ctx->dlo->StopScheduledPlayback(ctx->last_pts * ctx->bmd_tb_num,
253  &actual, ctx->bmd_tb_den);
254  ctx->dlo->DisableVideoOutput();
255  if (ctx->audio)
256  ctx->dlo->DisableAudioOutput();
257  }
258 
259  ff_decklink_cleanup(avctx);
260 
261  if (ctx->output_callback)
262  delete ctx->output_callback;
263 
264  pthread_mutex_destroy(&ctx->mutex);
265  pthread_cond_destroy(&ctx->cond);
266 
267  av_freep(&cctx->ctx);
268 
269  return 0;
270 }
271 
273 {
274  struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
275  struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
276  AVStream *st = avctx->streams[pkt->stream_index];
277  AVFrame *avframe = NULL, *tmp = (AVFrame *)pkt->data;
278  AVPacket *avpacket = NULL;
280  buffercount_type buffered;
281  HRESULT hr;
282 
284  if (tmp->format != AV_PIX_FMT_UYVY422 ||
285  tmp->width != ctx->bmd_width ||
286  tmp->height != ctx->bmd_height) {
287  av_log(avctx, AV_LOG_ERROR, "Got a frame with invalid pixel format or dimension.\n");
288  return AVERROR(EINVAL);
289  }
290 
291  avframe = av_frame_clone(tmp);
292  if (!avframe) {
293  av_log(avctx, AV_LOG_ERROR, "Could not clone video frame.\n");
294  return AVERROR(EIO);
295  }
296 
297  frame = new decklink_frame(ctx, avframe, st->codecpar->codec_id, avframe->height, avframe->width);
298  } else {
299  avpacket = av_packet_clone(pkt);
300  if (!avpacket) {
301  av_log(avctx, AV_LOG_ERROR, "Could not clone video frame.\n");
302  return AVERROR(EIO);
303  }
304 
305  frame = new decklink_frame(ctx, avpacket, st->codecpar->codec_id, ctx->bmd_height, ctx->bmd_width);
306  }
307 
308  if (!frame) {
309  av_log(avctx, AV_LOG_ERROR, "Could not create new frame.\n");
310  av_frame_free(&avframe);
311  av_packet_free(&avpacket);
312  return AVERROR(EIO);
313  }
314 
315  /* Always keep at most one second of frames buffered. */
316  pthread_mutex_lock(&ctx->mutex);
317  while (ctx->frames_buffer_available_spots == 0) {
318  pthread_cond_wait(&ctx->cond, &ctx->mutex);
319  }
320  ctx->frames_buffer_available_spots--;
321  pthread_mutex_unlock(&ctx->mutex);
322 
323  /* Schedule frame for playback. */
324  hr = ctx->dlo->ScheduleVideoFrame((class IDeckLinkVideoFrame *) frame,
325  pkt->pts * ctx->bmd_tb_num,
326  ctx->bmd_tb_num, ctx->bmd_tb_den);
327  /* Pass ownership to DeckLink, or release on failure */
328  frame->Release();
329  if (hr != S_OK) {
330  av_log(avctx, AV_LOG_ERROR, "Could not schedule video frame."
331  " error %08x.\n", (uint32_t) hr);
332  return AVERROR(EIO);
333  }
334 
335  ctx->dlo->GetBufferedVideoFrameCount(&buffered);
336  av_log(avctx, AV_LOG_DEBUG, "Buffered video frames: %d.\n", (int) buffered);
337  if (pkt->pts > 2 && buffered <= 2)
338  av_log(avctx, AV_LOG_WARNING, "There are not enough buffered video frames."
339  " Video may misbehave!\n");
340 
341  /* Preroll video frames. */
342  if (!ctx->playback_started && pkt->pts > ctx->frames_preroll) {
343  av_log(avctx, AV_LOG_DEBUG, "Ending audio preroll.\n");
344  if (ctx->audio && ctx->dlo->EndAudioPreroll() != S_OK) {
345  av_log(avctx, AV_LOG_ERROR, "Could not end audio preroll!\n");
346  return AVERROR(EIO);
347  }
348  av_log(avctx, AV_LOG_DEBUG, "Starting scheduled playback.\n");
349  if (ctx->dlo->StartScheduledPlayback(0, ctx->bmd_tb_den, 1.0) != S_OK) {
350  av_log(avctx, AV_LOG_ERROR, "Could not start scheduled playback!\n");
351  return AVERROR(EIO);
352  }
353  ctx->playback_started = 1;
354  }
355 
356  return 0;
357 }
358 
360 {
361  struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
362  struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
363  int sample_count = pkt->size / (ctx->channels << 1);
364  buffercount_type buffered;
365 
366  ctx->dlo->GetBufferedAudioSampleFrameCount(&buffered);
367  if (pkt->pts > 1 && !buffered)
368  av_log(avctx, AV_LOG_WARNING, "There's no buffered audio."
369  " Audio will misbehave!\n");
370 
371  if (ctx->dlo->ScheduleAudioSamples(pkt->data, sample_count, pkt->pts,
372  bmdAudioSampleRate48kHz, NULL) != S_OK) {
373  av_log(avctx, AV_LOG_ERROR, "Could not schedule audio samples.\n");
374  return AVERROR(EIO);
375  }
376 
377  return 0;
378 }
379 
380 extern "C" {
381 
383 {
384  struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
385  struct decklink_ctx *ctx;
386  unsigned int n;
387  int ret;
388 
389  ctx = (struct decklink_ctx *) av_mallocz(sizeof(struct decklink_ctx));
390  if (!ctx)
391  return AVERROR(ENOMEM);
392  ctx->list_devices = cctx->list_devices;
393  ctx->list_formats = cctx->list_formats;
394  ctx->preroll = cctx->preroll;
395  cctx->ctx = ctx;
396 
397  /* List available devices and exit. */
398  if (ctx->list_devices) {
399  ff_decklink_list_devices_legacy(avctx, 0, 1);
400  return AVERROR_EXIT;
401  }
402 
403  ret = ff_decklink_init_device(avctx, avctx->url);
404  if (ret < 0)
405  return ret;
406 
407  /* Get output device. */
408  if (ctx->dl->QueryInterface(IID_IDeckLinkOutput, (void **) &ctx->dlo) != S_OK) {
409  av_log(avctx, AV_LOG_ERROR, "Could not open output device from '%s'\n",
410  avctx->url);
411  ret = AVERROR(EIO);
412  goto error;
413  }
414 
415  /* List supported formats. */
416  if (ctx->list_formats) {
418  ret = AVERROR_EXIT;
419  goto error;
420  }
421 
422  /* Setup streams. */
423  ret = AVERROR(EIO);
424  for (n = 0; n < avctx->nb_streams; n++) {
425  AVStream *st = avctx->streams[n];
427  if (c->codec_type == AVMEDIA_TYPE_AUDIO) {
428  if (decklink_setup_audio(avctx, st))
429  goto error;
430  } else if (c->codec_type == AVMEDIA_TYPE_VIDEO) {
431  if (decklink_setup_video(avctx, st))
432  goto error;
433  } else {
434  av_log(avctx, AV_LOG_ERROR, "Unsupported stream type.\n");
435  goto error;
436  }
437  }
438 
439  return 0;
440 
441 error:
442  ff_decklink_cleanup(avctx);
443  return ret;
444 }
445 
447 {
448  struct decklink_cctx *cctx = (struct decklink_cctx *)avctx->priv_data;
449  struct decklink_ctx *ctx = (struct decklink_ctx *)cctx->ctx;
450  AVStream *st = avctx->streams[pkt->stream_index];
451 
452  ctx->last_pts = FFMAX(ctx->last_pts, pkt->pts);
453 
455  return decklink_write_video_packet(avctx, pkt);
456  else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
457  return decklink_write_audio_packet(avctx, pkt);
458 
459  return AVERROR(EIO);
460 }
461 
463 {
464  return ff_decklink_list_devices(avctx, device_list, 0, 1);
465 }
466 
467 } /* extern "C" */
packed YUV 4:2:2, 16bpp, Cb Y0 Cr Y1
Definition: pixfmt.h:77
#define NULL
Definition: coverity.c:32
enum AVFieldOrder field_order
Video only.
Definition: avcodec.h:3965
static av_always_inline int pthread_mutex_destroy(pthread_mutex_t *mutex)
Definition: os2threads.h:108
static const char * format[]
Definition: af_aiir.c:311
#define S_OK
Definition: windows2linux.h:40
This structure describes decoded (raw) audio or video data.
Definition: frame.h:218
#define pthread_mutex_lock(a)
Definition: ffprobe.c:61
static av_always_inline int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
Definition: os2threads.h:166
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:4820
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition: avcodec.h:3884
int num
Numerator.
Definition: rational.h:59
int size
Definition: avcodec.h:1431
void * av_mallocz(size_t size)
Allocate a memory block with alignment suitable for all memory accesses (including vectors if availab...
Definition: mem.c:236
static AVPacket pkt
static av_always_inline int pthread_cond_destroy(pthread_cond_t *cond)
Definition: os2threads.h:140
This struct describes the properties of an encoded stream.
Definition: avcodec.h:3876
Format I/O context.
Definition: avformat.h:1342
void av_packet_free(AVPacket **pkt)
Free the packet, if the packet is reference counted, it will be unreferenced first.
Definition: avpacket.c:62
#define av_cold
Definition: attributes.h:82
int width
Video only.
Definition: avcodec.h:3950
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:1410
static AVFrame * frame
#define height
uint8_t * data
Definition: avcodec.h:1430
#define E_NOINTERFACE
Definition: windows2linux.h:42
#define av_log(a,...)
Main libavdevice API header.
AVCodecID
Identify the syntax and semantics of the bitstream.
Definition: avcodec.h:215
int width
Definition: frame.h:276
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:176
AVPacket * av_packet_clone(const AVPacket *src)
Create a new packet that references the same data as src.
Definition: avpacket.c:634
#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:202
char * url
input or output URL.
Definition: avformat.h:1438
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: log.h:197
enum AVMediaType codec_type
General type of the encoded data.
Definition: avcodec.h:3880
uint16_t width
Definition: gdv.c:47
#define FFMAX(a, b)
Definition: common.h:94
unsigned int nb_streams
Number of elements in AVFormatContext.streams.
Definition: avformat.h:1398
#define FFMIN(a, b)
Definition: common.h:96
AVFormatContext * ctx
Definition: movenc.c:48
static av_always_inline int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr)
Definition: os2threads.h:100
int n
Definition: avisynth_c.h:684
enum AVCodecID codec_id
Definition: vaapi_decode.c:362
#define pthread_mutex_unlock(a)
Definition: ffprobe.c:65
Passthrough codec, AVFrames wrapped in AVPacket.
Definition: avcodec.h:691
#define AVERROR_EXIT
Immediate exit was requested; the called function should not be restarted.
Definition: error.h:56
static void error(const char *err)
AVFrame * av_frame_clone(const AVFrame *src)
Create a new frame that references the same data as src.
Definition: frame.c:538
Stream structure.
Definition: avformat.h:873
int linesize[AV_NUM_DATA_POINTERS]
For video, size in bytes of each picture line.
Definition: frame.h:249
void * LPVOID
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition: avpacket.c:592
List of devices.
Definition: avdevice.h:460
void av_frame_unref(AVFrame *frame)
Unreference all the buffers referenced by frame and reset the frame fields.
Definition: frame.c:551
DWORD HRESULT
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition: frame.h:232
int sample_rate
Audio only.
Definition: avcodec.h:3994
Main libavformat public API header.
if(ret< 0)
Definition: vf_mcdeint.c:279
static double c[64]
uint32_t ULONG
static av_always_inline int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr)
Definition: os2threads.h:129
int den
Denominator.
Definition: rational.h:60
#define S_FALSE
Definition: windows2linux.h:41
static av_always_inline int pthread_cond_broadcast(pthread_cond_t *cond)
Definition: os2threads.h:158
void * priv_data
Format private data.
Definition: avformat.h:1370
int channels
Audio only.
Definition: avcodec.h:3990
int height
Definition: frame.h:276
#define av_freep(p)
AVCodecParameters * codecpar
Codec parameters associated with this stream.
Definition: avformat.h:1020
int stream_index
Definition: avcodec.h:1432
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avformat.h:902
This structure stores compressed data.
Definition: avcodec.h:1407
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: avcodec.h:1423
GLuint buffer
Definition: opengl_enc.c:102
static uint8_t tmp[11]
Definition: aes_ctr.c:26