1 /*****************************************************************************
2 * decklink.cpp: BlackMagic DeckLink SDI input module
3 *****************************************************************************
4 * Copyright (C) 2010 Steinar H. Gunderson
6 * Authors: Steinar H. Gunderson <steinar+vlc@gunderson.no>
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 *****************************************************************************/
24 #define __STDC_CONSTANT_MACROS 1
30 #include <vlc_common.h>
31 #include <vlc_plugin.h>
32 #include <vlc_input.h>
33 #include <vlc_demux.h>
34 #include <vlc_access.h>
35 #include <vlc_picture.h>
36 #include <vlc_charset.h>
38 #include <vlc_atomic.h>
40 #include <arpa/inet.h>
42 #include <DeckLinkAPI.h>
43 #include <DeckLinkAPIDispatch.cpp>
45 static int Open ( vlc_object_t * );
46 static void Close( vlc_object_t * );
48 #define CARD_INDEX_TEXT N_("Input card to use")
49 #define CARD_INDEX_LONGTEXT N_( \
50 "DeckLink capture card to use, if multiple exist. " \
51 "The cards are numbered from 0." )
53 #define MODE_TEXT N_("Desired input video mode")
54 #define MODE_LONGTEXT N_( \
55 "Desired input video mode for DeckLink captures. " \
56 "This value should be a FOURCC code in textual " \
57 "form, e.g. \"ntsc\"." )
59 #define CACHING_TEXT N_("Caching value in ms")
60 #define CACHING_LONGTEXT N_( \
61 "Caching value for DeckLink captures. This " \
62 "value should be set in milliseconds." )
64 #define AUDIO_CONNECTION_TEXT N_("Audio connection")
65 #define AUDIO_CONNECTION_LONGTEXT N_( \
66 "Audio connection to use for DeckLink captures. " \
67 "Valid choices: embedded, aesebu, analog. " \
68 "Leave blank for card default." )
70 #define RATE_TEXT N_("Audio sampling rate in Hz")
71 #define RATE_LONGTEXT N_( \
72 "Audio sampling rate (in hertz) for DeckLink captures. " \
73 "0 disables audio input." )
75 #define CHANNELS_TEXT N_("Number of audio channels")
76 #define CHANNELS_LONGTEXT N_( \
77 "Number of input audio channels for DeckLink captures. " \
78 "Must be 2, 8 or 16. 0 disables audio input." )
80 #define VIDEO_CONNECTION_TEXT N_("Video connection")
81 #define VIDEO_CONNECTION_LONGTEXT N_( \
82 "Video connection to use for DeckLink captures. " \
83 "Valid choices: sdi, hdmi, opticalsdi, component, " \
84 "composite, svideo. " \
85 "Leave blank for card default." )
87 #define ASPECT_RATIO_TEXT N_("Aspect ratio")
88 #define ASPECT_RATIO_LONGTEXT N_( \
89 "Aspect ratio (4:3, 16:9). Default assumes square pixels." )
92 set_shortname( N_("DeckLink") )
93 set_description( N_("Blackmagic DeckLink SDI input") )
94 set_category( CAT_INPUT )
95 set_subcategory( SUBCAT_INPUT_ACCESS )
97 add_integer( "decklink-card-index", 0, NULL,
98 CARD_INDEX_TEXT, CARD_INDEX_LONGTEXT, true )
99 add_string( "decklink-mode", "pal ", NULL,
100 MODE_TEXT, MODE_LONGTEXT, true )
101 add_integer( "decklink-caching", DEFAULT_PTS_DELAY / 1000, NULL,
102 CACHING_TEXT, CACHING_LONGTEXT, true )
103 add_string( "decklink-audio-connection", 0, NULL,
104 AUDIO_CONNECTION_TEXT, AUDIO_CONNECTION_LONGTEXT, true )
105 add_integer( "decklink-audio-rate", 48000, NULL,
106 RATE_TEXT, RATE_LONGTEXT, true )
107 add_integer( "decklink-audio-channels", 2, NULL,
108 CHANNELS_TEXT, CHANNELS_LONGTEXT, true )
109 add_string( "decklink-video-connection", 0, NULL,
110 VIDEO_CONNECTION_TEXT, VIDEO_CONNECTION_LONGTEXT, true )
111 add_string( "decklink-aspect-ratio", NULL, NULL,
112 ASPECT_RATIO_TEXT, ASPECT_RATIO_LONGTEXT, true )
114 add_shortcut( "decklink" )
115 set_capability( "access_demux", 10 )
116 set_callbacks( Open, Close )
119 static int Demux ( demux_t * );
120 static int Control( demux_t *, int, va_list );
122 class DeckLinkCaptureDelegate;
127 IDeckLinkInput *p_input;
128 DeckLinkCaptureDelegate *p_delegate;
130 es_out_id_t *p_video_es;
131 es_out_id_t *p_audio_es;
135 int i_width, i_height, i_fps_num, i_fps_den;
136 uint32_t i_dominance_flags;
138 int i_rate, i_channels;
140 vlc_mutex_t frame_lock;
141 block_t *p_video_frame; /* protected by <frame_lock> */
142 block_t *p_audio_frame; /* protected by <frame_lock> */
143 vlc_cond_t has_frame; /* related to <frame_lock> */
146 class DeckLinkCaptureDelegate : public IDeckLinkInputCallback
149 DeckLinkCaptureDelegate( demux_t *p_demux ) : p_demux_(p_demux)
151 vlc_atomic_set( &m_ref_, 1 );
154 virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv) { return E_NOINTERFACE; }
156 virtual ULONG STDMETHODCALLTYPE AddRef(void)
158 return vlc_atomic_inc( &m_ref_ );
161 virtual ULONG STDMETHODCALLTYPE Release(void)
163 uintptr_t new_ref = vlc_atomic_dec( &m_ref_ );
169 virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents, IDeckLinkDisplayMode*, BMDDetectedVideoInputFormatFlags);
170 virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame*, IDeckLinkAudioInputPacket*);
177 HRESULT DeckLinkCaptureDelegate::VideoInputFormatChanged(BMDVideoInputFormatChangedEvents events, IDeckLinkDisplayMode *mode, BMDDetectedVideoInputFormatFlags)
179 msg_Dbg( p_demux_, "Video input format changed" );
183 HRESULT DeckLinkCaptureDelegate::VideoInputFrameArrived(IDeckLinkVideoInputFrame* videoFrame, IDeckLinkAudioInputPacket* audioFrame)
185 demux_sys_t *p_sys = p_demux_->p_sys;
186 block_t *p_video_frame = NULL;
187 block_t *p_audio_frame = NULL;
191 if( videoFrame->GetFlags() & bmdFrameHasNoInputSource )
193 msg_Warn( p_demux_, "No input signal detected" );
197 const int i_width = videoFrame->GetWidth();
198 const int i_height = videoFrame->GetHeight();
199 const int i_stride = videoFrame->GetRowBytes();
202 p_video_frame = block_New( p_demux_, i_width * i_height * i_bpp );
205 msg_Err( p_demux_, "Could not allocate memory for video frame" );
210 videoFrame->GetBytes( &frame_bytes );
211 for( int y = 0; y < i_height; ++y )
213 const uint8_t *src = (const uint8_t *)frame_bytes + i_stride * y;
214 uint8_t *dst = (uint8_t *)p_video_frame->p_buffer + i_width * i_bpp * y;
215 memcpy( dst, src, i_width * i_bpp );
218 BMDTimeValue stream_time, frame_duration;
219 videoFrame->GetStreamTime( &stream_time, &frame_duration, CLOCK_FREQ );
220 p_video_frame->i_flags = BLOCK_FLAG_TYPE_I | p_sys->i_dominance_flags;
221 if( p_sys->b_first_frame )
223 p_video_frame->i_flags |= BLOCK_FLAG_DISCONTINUITY;
224 p_sys->b_first_frame = false;
226 p_video_frame->i_pts = p_video_frame->i_dts = VLC_TS_0 + stream_time;
231 const int i_bytes = audioFrame->GetSampleFrameCount() * sizeof(int16_t) * p_sys->i_channels;
233 p_audio_frame = block_New( p_demux_, i_bytes );
236 msg_Err( p_demux_, "Could not allocate memory for audio frame" );
238 block_Release( p_video_frame );
243 audioFrame->GetBytes( &frame_bytes );
244 memcpy( p_audio_frame->p_buffer, frame_bytes, i_bytes );
246 BMDTimeValue packet_time;
247 audioFrame->GetPacketTime( &packet_time, CLOCK_FREQ );
248 p_audio_frame->i_pts = p_audio_frame->i_dts = VLC_TS_0 + packet_time;
251 if( p_video_frame || p_audio_frame )
253 vlc_mutex_lock( &p_sys->frame_lock );
256 if( p_sys->p_video_frame )
257 block_Release( p_sys->p_video_frame );
258 p_sys->p_video_frame = p_video_frame;
262 if( p_sys->p_audio_frame )
263 block_Release( p_sys->p_audio_frame );
264 p_sys->p_audio_frame = p_audio_frame;
266 vlc_cond_signal( &p_sys->has_frame );
267 vlc_mutex_unlock( &p_sys->frame_lock );
273 static int Open( vlc_object_t *p_this )
275 demux_t *p_demux = (demux_t*)p_this;
277 int ret = VLC_SUCCESS;
279 char *psz_display_mode = NULL;
280 char *psz_video_connection = NULL;
281 char *psz_audio_connection = NULL;
285 /* Only when selected */
286 if( *p_demux->psz_access == '\0' )
290 p_demux->pf_demux = Demux;
291 p_demux->pf_control = Control;
292 p_demux->info.i_update = 0;
293 p_demux->info.i_title = 0;
294 p_demux->info.i_seekpoint = 0;
295 p_demux->p_sys = p_sys = (demux_sys_t*)calloc( 1, sizeof( demux_sys_t ) );
299 vlc_mutex_init( &p_sys->frame_lock );
300 vlc_cond_init( &p_sys->has_frame );
301 p_sys->b_first_frame = true;
303 IDeckLinkIterator *decklink_iterator = CreateDeckLinkIteratorInstance();
304 if( !decklink_iterator )
306 msg_Err( p_demux, "DeckLink drivers not found." );
313 i_card_index = var_InheritInteger( p_demux, "decklink-card-index" );
314 for( int i = 0; i <= i_card_index; ++i )
317 p_sys->p_card->Release();
318 result = decklink_iterator->Next( &p_sys->p_card );
325 msg_Err( p_demux, "DeckLink PCI card %d not found", i_card_index );
330 const char *psz_model_name;
331 result = p_sys->p_card->GetModelName( &psz_model_name );
335 msg_Err( p_demux, "Could not get model name" );
340 msg_Dbg( p_demux, "Opened DeckLink PCI card %d (%s)", i_card_index, psz_model_name );
342 if( p_sys->p_card->QueryInterface( IID_IDeckLinkInput, (void**)&p_sys->p_input) != S_OK )
344 msg_Err( p_demux, "Card has no inputs" );
349 /* Set up the video and audio sources. */
350 IDeckLinkConfiguration *p_config;
351 if( p_sys->p_card->QueryInterface( IID_IDeckLinkConfiguration, (void**)&p_config) != S_OK )
353 msg_Err( p_demux, "Failed to get configuration interface" );
358 psz_video_connection = var_CreateGetNonEmptyString( p_demux, "decklink-video-connection" );
359 if( psz_video_connection )
361 BMDVideoConnection conn;
362 if ( !strcmp( psz_video_connection, "sdi" ) )
363 conn = bmdVideoConnectionSDI;
364 else if ( !strcmp( psz_video_connection, "hdmi" ) )
365 conn = bmdVideoConnectionHDMI;
366 else if ( !strcmp( psz_video_connection, "opticalsdi" ) )
367 conn = bmdVideoConnectionOpticalSDI;
368 else if ( !strcmp( psz_video_connection, "component" ) )
369 conn = bmdVideoConnectionComponent;
370 else if ( !strcmp( psz_video_connection, "composite" ) )
371 conn = bmdVideoConnectionComposite;
372 else if ( !strcmp( psz_video_connection, "svideo" ) )
373 conn = bmdVideoConnectionSVideo;
376 msg_Err( p_demux, "Invalid --decklink-video-connection specified; choose one of " \
377 "sdi, hdmi, opticalsdi, component, composite, or svideo." );
382 msg_Dbg( p_demux, "Setting video input format to 0x%x", conn);
383 result = p_config->SetVideoInputFormat( conn );
386 msg_Err( p_demux, "Failed to set video input connection" );
392 psz_audio_connection = var_CreateGetNonEmptyString( p_demux, "decklink-audio-connection" );
393 if( psz_audio_connection )
395 BMDAudioConnection conn;
396 if ( !strcmp( psz_audio_connection, "embedded" ) )
397 conn = bmdAudioConnectionEmbedded;
398 else if ( !strcmp( psz_audio_connection, "aesebu" ) )
399 conn = bmdAudioConnectionAESEBU;
400 else if ( !strcmp( psz_audio_connection, "analog" ) )
401 conn = bmdAudioConnectionAnalog;
404 msg_Err( p_demux, "Invalid --decklink-audio-connection specified; choose one of " \
405 "embedded, aesebu, or analog." );
410 msg_Dbg( p_demux, "Setting audio input format to 0x%x", conn);
411 result = p_config->SetAudioInputFormat( conn );
414 msg_Err( p_demux, "Failed to set audio input connection" );
420 /* Get the list of display modes. */
421 IDeckLinkDisplayModeIterator *p_display_iterator;
422 result = p_sys->p_input->GetDisplayModeIterator( &p_display_iterator );
425 msg_Err( p_demux, "Failed to enumerate display modes" );
430 psz_display_mode = var_InheritString( p_demux, "decklink-mode" );
431 if( !psz_display_mode || strlen( psz_display_mode ) == 0 || strlen( psz_display_mode ) > 4 ) {
432 msg_Err( p_demux, "Missing or invalid --decklink-mode string" );
438 * Pad the --decklink-mode string to four characters, so the user can specify e.g. "pal"
439 * without having to add the trailing space.
441 char sz_display_mode_padded[5];
442 strcpy(sz_display_mode_padded, " ");
443 for( int i = 0; i < strlen( psz_display_mode ); ++i )
444 sz_display_mode_padded[i] = psz_display_mode[i];
446 BMDDisplayMode wanted_mode_id;
447 memcpy( &wanted_mode_id, &sz_display_mode_padded, sizeof(wanted_mode_id) );
449 b_found_mode = false;
453 IDeckLinkDisplayMode *p_display_mode;
454 result = p_display_iterator->Next( &p_display_mode );
455 if( result != S_OK || !p_display_mode )
458 char sz_mode_id_text[5] = {0};
459 BMDDisplayMode mode_id = ntohl( p_display_mode->GetDisplayMode() );
460 memcpy( sz_mode_id_text, &mode_id, sizeof(mode_id) );
462 const char *psz_mode_name;
463 result = p_display_mode->GetName( &psz_mode_name );
466 msg_Err( p_demux, "Failed to get display mode name" );
467 p_display_mode->Release();
472 BMDTimeValue frame_duration, time_scale;
473 result = p_display_mode->GetFrameRate( &frame_duration, &time_scale );
476 msg_Err( p_demux, "Failed to get frame rate" );
477 p_display_mode->Release();
482 const char *psz_field_dominance;
483 uint32_t i_dominance_flags = 0;
484 switch( p_display_mode->GetFieldDominance() )
486 case bmdProgressiveFrame:
487 psz_field_dominance = "";
489 case bmdProgressiveSegmentedFrame:
490 psz_field_dominance = ", segmented";
492 case bmdLowerFieldFirst:
493 psz_field_dominance = ", interlaced [BFF]";
494 i_dominance_flags = BLOCK_FLAG_BOTTOM_FIELD_FIRST;
496 case bmdUpperFieldFirst:
497 psz_field_dominance = ", interlaced [TFF]";
498 i_dominance_flags = BLOCK_FLAG_TOP_FIELD_FIRST;
500 case bmdUnknownFieldDominance:
502 psz_field_dominance = ", unknown field dominance";
506 msg_Dbg( p_demux, "Found mode '%s': %s (%dx%d, %.3f fps%s)",
507 sz_mode_id_text, psz_mode_name,
508 p_display_mode->GetWidth(), p_display_mode->GetHeight(),
509 double(time_scale) / frame_duration, psz_field_dominance );
511 if( wanted_mode_id == mode_id )
514 p_sys->i_width = p_display_mode->GetWidth();
515 p_sys->i_height = p_display_mode->GetHeight();
516 p_sys->i_fps_num = time_scale;
517 p_sys->i_fps_den = frame_duration;
518 p_sys->i_dominance_flags = i_dominance_flags;
521 p_display_mode->Release();
526 msg_Err( p_demux, "Unknown video mode specified. " \
527 "Run VLC with -v --verbose-objects=-all,+decklink " \
528 "to get a list of supported modes." );
533 result = p_sys->p_input->EnableVideoInput( htonl( wanted_mode_id ), bmdFormat8BitYUV, 0 );
536 msg_Err( p_demux, "Failed to enable video input" );
542 p_sys->i_rate = var_InheritInteger( p_demux, "decklink-audio-rate" );
543 p_sys->i_channels = var_InheritInteger( p_demux, "decklink-audio-channels" );
544 if( p_sys->i_rate > 0 && p_sys->i_channels > 0 )
546 result = p_sys->p_input->EnableAudioInput( p_sys->i_rate, bmdAudioSampleType16bitInteger, p_sys->i_channels );
549 msg_Err( p_demux, "Failed to enable audio input" );
555 p_sys->p_delegate = new DeckLinkCaptureDelegate( p_demux );
556 p_sys->p_input->SetCallback( p_sys->p_delegate );
558 result = p_sys->p_input->StartStreams();
561 msg_Err( p_demux, "Could not start streaming from SDI card. This could be caused "
562 "by invalid video mode or flags, access denied, or card already in use." );
567 /* Declare elementary streams */
568 es_format_t video_fmt;
569 es_format_Init( &video_fmt, VIDEO_ES, VLC_CODEC_UYVY );
570 video_fmt.video.i_width = p_sys->i_width;
571 video_fmt.video.i_height = p_sys->i_height;
572 video_fmt.video.i_sar_num = 1;
573 video_fmt.video.i_sar_den = 1;
574 video_fmt.video.i_frame_rate = p_sys->i_fps_num;
575 video_fmt.video.i_frame_rate_base = p_sys->i_fps_den;
576 video_fmt.i_bitrate = video_fmt.video.i_width * video_fmt.video.i_height * video_fmt.video.i_frame_rate * 2 * 8;
578 psz_aspect = var_CreateGetNonEmptyString( p_demux, "decklink-aspect-ratio" );
581 char *psz_denominator = strchr( psz_aspect, ':' );
582 if( psz_denominator )
584 *psz_denominator++ = '\0';
585 video_fmt.video.i_sar_num = atoi( psz_aspect ) * video_fmt.video.i_height;
586 video_fmt.video.i_sar_den = atoi( psz_denominator ) * video_fmt.video.i_width;
591 msg_Dbg( p_demux, "added new video es %4.4s %dx%d",
592 (char*)&video_fmt.i_codec, video_fmt.video.i_width, video_fmt.video.i_height );
593 p_sys->p_video_es = es_out_Add( p_demux->out, &video_fmt );
595 es_format_t audio_fmt;
596 es_format_Init( &audio_fmt, AUDIO_ES, VLC_CODEC_S16N );
597 audio_fmt.audio.i_channels = p_sys->i_channels;
598 audio_fmt.audio.i_rate = p_sys->i_rate;
599 audio_fmt.audio.i_bitspersample = 16;
600 audio_fmt.audio.i_blockalign = audio_fmt.audio.i_channels * audio_fmt.audio.i_bitspersample / 8;
601 audio_fmt.i_bitrate = audio_fmt.audio.i_channels * audio_fmt.audio.i_rate * audio_fmt.audio.i_bitspersample;
603 msg_Dbg( p_demux, "added new audio es %4.4s %dHz %dbpp %dch",
604 (char*)&audio_fmt.i_codec, audio_fmt.audio.i_rate, audio_fmt.audio.i_bitspersample, audio_fmt.audio.i_channels);
605 p_sys->p_audio_es = es_out_Add( p_demux->out, &audio_fmt );
607 /* Update default_pts to a suitable value for access */
608 var_Create( p_demux, "decklink-caching", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
611 if( decklink_iterator )
612 decklink_iterator->Release();
617 free( psz_video_connection );
618 free( psz_audio_connection );
619 free( psz_display_mode );
621 if( p_display_iterator )
622 p_display_iterator->Release();
624 if( ret != VLC_SUCCESS )
630 static void Close( vlc_object_t *p_this )
632 demux_t *p_demux = (demux_t *)p_this;
633 demux_sys_t *p_sys = p_demux->p_sys;
637 p_sys->p_input->StopStreams();
638 p_sys->p_input->Release();
642 p_sys->p_card->Release();
644 if( p_sys->p_delegate )
645 p_sys->p_delegate->Release();
647 if( p_sys->p_video_frame )
648 block_Release( p_sys->p_video_frame );
650 if( p_sys->p_audio_frame )
651 block_Release( p_sys->p_audio_frame );
656 static int Control( demux_t *p_demux, int i_query, va_list args )
658 demux_sys_t *p_sys = p_demux->p_sys;
664 /* Special for access_demux */
665 case DEMUX_CAN_PAUSE:
667 case DEMUX_CAN_CONTROL_PACE:
668 pb = (bool*)va_arg( args, bool * );
672 case DEMUX_GET_PTS_DELAY:
673 pi64 = (int64_t*)va_arg( args, int64_t * );
674 *pi64 = var_GetInteger( p_demux, "decklink-caching" ) * 1000;
678 pi64 = (int64_t*)va_arg( args, int64_t * );
679 *pi64 = p_sys->i_last_pts;
682 /* TODO implement others */
690 static int Demux( demux_t *p_demux )
692 demux_sys_t *p_sys = p_demux->p_sys;
693 block_t *p_video_block = NULL;
694 block_t *p_audio_block = NULL;
696 vlc_mutex_lock( &p_sys->frame_lock );
698 while( !p_sys->p_video_frame && !p_sys->p_audio_frame )
699 vlc_cond_wait( &p_sys->has_frame, &p_sys->frame_lock );
701 p_video_block = p_sys->p_video_frame;
702 p_sys->p_video_frame = NULL;
704 p_audio_block = p_sys->p_audio_frame;
705 p_sys->p_audio_frame = NULL;
707 vlc_mutex_unlock( &p_sys->frame_lock );
711 if( p_video_block->i_pts > p_sys->i_last_pts )
712 p_sys->i_last_pts = p_video_block->i_pts;
713 es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_video_block->i_pts );
714 es_out_Send( p_demux->out, p_sys->p_video_es, p_video_block );
719 if( p_audio_block->i_pts > p_sys->i_last_pts )
720 p_sys->i_last_pts = p_audio_block->i_pts;
721 es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_audio_block->i_pts );
722 es_out_Send( p_demux->out, p_sys->p_audio_es, p_audio_block );