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_demux.h>
33 #include <vlc_atomic.h>
35 #include <arpa/inet.h>
37 #include <DeckLinkAPI.h>
38 #include <DeckLinkAPIDispatch.cpp>
40 static int Open ( vlc_object_t * );
41 static void Close( vlc_object_t * );
43 #define CARD_INDEX_TEXT N_("Input card to use")
44 #define CARD_INDEX_LONGTEXT N_( \
45 "DeckLink capture card to use, if multiple exist. " \
46 "The cards are numbered from 0." )
48 #define MODE_TEXT N_("Desired input video mode")
49 #define MODE_LONGTEXT N_( \
50 "Desired input video mode for DeckLink captures. " \
51 "This value should be a FOURCC code in textual " \
52 "form, e.g. \"ntsc\"." )
54 #define CACHING_TEXT N_("Caching value in ms")
55 #define CACHING_LONGTEXT N_( \
56 "Caching value for DeckLink captures. This " \
57 "value should be set in milliseconds." )
59 #define AUDIO_CONNECTION_TEXT N_("Audio connection")
60 #define AUDIO_CONNECTION_LONGTEXT N_( \
61 "Audio connection to use for DeckLink captures. " \
62 "Valid choices: embedded, aesebu, analog. " \
63 "Leave blank for card default." )
65 #define RATE_TEXT N_("Audio sampling rate in Hz")
66 #define RATE_LONGTEXT N_( \
67 "Audio sampling rate (in hertz) for DeckLink captures. " \
68 "0 disables audio input." )
70 #define CHANNELS_TEXT N_("Number of audio channels")
71 #define CHANNELS_LONGTEXT N_( \
72 "Number of input audio channels for DeckLink captures. " \
73 "Must be 2, 8 or 16. 0 disables audio input." )
75 #define VIDEO_CONNECTION_TEXT N_("Video connection")
76 #define VIDEO_CONNECTION_LONGTEXT N_( \
77 "Video connection to use for DeckLink captures. " \
78 "Valid choices: sdi, hdmi, opticalsdi, component, " \
79 "composite, svideo. " \
80 "Leave blank for card default." )
82 #define ASPECT_RATIO_TEXT N_("Aspect ratio")
83 #define ASPECT_RATIO_LONGTEXT N_( \
84 "Aspect ratio (4:3, 16:9). Default assumes square pixels." )
87 set_shortname( N_("DeckLink") )
88 set_description( N_("Blackmagic DeckLink SDI input") )
89 set_category( CAT_INPUT )
90 set_subcategory( SUBCAT_INPUT_ACCESS )
92 add_integer( "decklink-card-index", 0, NULL,
93 CARD_INDEX_TEXT, CARD_INDEX_LONGTEXT, true )
94 add_string( "decklink-mode", "pal ", NULL,
95 MODE_TEXT, MODE_LONGTEXT, true )
96 add_integer( "decklink-caching", DEFAULT_PTS_DELAY / 1000, NULL,
97 CACHING_TEXT, CACHING_LONGTEXT, true )
98 add_string( "decklink-audio-connection", 0, NULL,
99 AUDIO_CONNECTION_TEXT, AUDIO_CONNECTION_LONGTEXT, true )
100 add_integer( "decklink-audio-rate", 48000, NULL,
101 RATE_TEXT, RATE_LONGTEXT, true )
102 add_integer( "decklink-audio-channels", 2, NULL,
103 CHANNELS_TEXT, CHANNELS_LONGTEXT, true )
104 add_string( "decklink-video-connection", 0, NULL,
105 VIDEO_CONNECTION_TEXT, VIDEO_CONNECTION_LONGTEXT, true )
106 add_string( "decklink-aspect-ratio", NULL, NULL,
107 ASPECT_RATIO_TEXT, ASPECT_RATIO_LONGTEXT, true )
109 add_shortcut( "decklink" )
110 set_capability( "access_demux", 10 )
111 set_callbacks( Open, Close )
114 static int Demux ( demux_t * );
115 static int Control( demux_t *, int, va_list );
117 class DeckLinkCaptureDelegate;
122 IDeckLinkInput *p_input;
123 DeckLinkCaptureDelegate *p_delegate;
125 es_out_id_t *p_video_es;
126 es_out_id_t *p_audio_es;
130 uint32_t i_dominance_flags;
133 vlc_mutex_t frame_lock;
134 block_t *p_video_frame; /* protected by <frame_lock> */
135 block_t *p_audio_frame; /* protected by <frame_lock> */
136 vlc_cond_t has_frame; /* related to <frame_lock> */
139 class DeckLinkCaptureDelegate : public IDeckLinkInputCallback
142 DeckLinkCaptureDelegate( demux_t *p_demux ) : p_demux_(p_demux)
144 vlc_atomic_set( &m_ref_, 1 );
147 virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv) { return E_NOINTERFACE; }
149 virtual ULONG STDMETHODCALLTYPE AddRef(void)
151 return vlc_atomic_inc( &m_ref_ );
154 virtual ULONG STDMETHODCALLTYPE Release(void)
156 uintptr_t new_ref = vlc_atomic_dec( &m_ref_ );
162 virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents, IDeckLinkDisplayMode*, BMDDetectedVideoInputFormatFlags)
164 msg_Dbg( p_demux_, "Video input format changed" );
168 virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame*, IDeckLinkAudioInputPacket*);
175 HRESULT DeckLinkCaptureDelegate::VideoInputFrameArrived(IDeckLinkVideoInputFrame* videoFrame, IDeckLinkAudioInputPacket* audioFrame)
177 demux_sys_t *p_sys = p_demux_->p_sys;
178 block_t *p_video_frame = NULL;
179 block_t *p_audio_frame = NULL;
183 if( videoFrame->GetFlags() & bmdFrameHasNoInputSource )
185 msg_Warn( p_demux_, "No input signal detected" );
189 const int i_width = videoFrame->GetWidth();
190 const int i_height = videoFrame->GetHeight();
191 const int i_stride = videoFrame->GetRowBytes();
194 p_video_frame = block_New( p_demux_, i_width * i_height * i_bpp );
197 msg_Err( p_demux_, "Could not allocate memory for video frame" );
202 videoFrame->GetBytes( &frame_bytes );
203 for( int y = 0; y < i_height; ++y )
205 const uint8_t *src = (const uint8_t *)frame_bytes + i_stride * y;
206 uint8_t *dst = p_video_frame->p_buffer + i_width * i_bpp * y;
207 memcpy( dst, src, i_width * i_bpp );
210 BMDTimeValue stream_time, frame_duration;
211 videoFrame->GetStreamTime( &stream_time, &frame_duration, CLOCK_FREQ );
212 p_video_frame->i_flags = BLOCK_FLAG_TYPE_I | p_sys->i_dominance_flags;
213 p_video_frame->i_pts = p_video_frame->i_dts = VLC_TS_0 + stream_time;
218 const int i_bytes = audioFrame->GetSampleFrameCount() * sizeof(int16_t) * p_sys->i_channels;
220 p_audio_frame = block_New( p_demux_, i_bytes );
223 msg_Err( p_demux_, "Could not allocate memory for audio frame" );
225 block_Release( p_video_frame );
230 audioFrame->GetBytes( &frame_bytes );
231 memcpy( p_audio_frame->p_buffer, frame_bytes, i_bytes );
233 BMDTimeValue packet_time;
234 audioFrame->GetPacketTime( &packet_time, CLOCK_FREQ );
235 p_audio_frame->i_pts = p_audio_frame->i_dts = VLC_TS_0 + packet_time;
238 if( p_video_frame || p_audio_frame )
240 vlc_mutex_lock( &p_sys->frame_lock );
243 if( p_sys->p_video_frame )
244 block_Release( p_sys->p_video_frame );
245 p_sys->p_video_frame = p_video_frame;
249 if( p_sys->p_audio_frame )
250 block_Release( p_sys->p_audio_frame );
251 p_sys->p_audio_frame = p_audio_frame;
253 vlc_cond_signal( &p_sys->has_frame );
254 vlc_mutex_unlock( &p_sys->frame_lock );
260 static int Open( vlc_object_t *p_this )
262 demux_t *p_demux = (demux_t*)p_this;
264 int ret = VLC_EGENERIC;
266 char *psz_display_mode = NULL;
267 char *psz_video_connection = NULL;
268 char *psz_audio_connection = NULL;
271 int i_width, i_height, i_fps_num, i_fps_den;
273 unsigned u_aspect_num, u_aspect_den;
275 /* Only when selected */
276 if( *p_demux->psz_access == '\0' )
280 p_demux->pf_demux = Demux;
281 p_demux->pf_control = Control;
282 p_demux->info.i_update = 0;
283 p_demux->info.i_title = 0;
284 p_demux->info.i_seekpoint = 0;
285 p_demux->p_sys = p_sys = (demux_sys_t*)calloc( 1, sizeof( demux_sys_t ) );
289 vlc_mutex_init( &p_sys->frame_lock );
290 vlc_cond_init( &p_sys->has_frame );
291 p_sys->b_first_frame = true;
293 IDeckLinkIterator *decklink_iterator = CreateDeckLinkIteratorInstance();
294 if( !decklink_iterator )
296 msg_Err( p_demux, "DeckLink drivers not found." );
302 i_card_index = var_InheritInteger( p_demux, "decklink-card-index" );
303 if( i_card_index < 0 )
305 msg_Err( p_demux, "Invalid card index %d", i_card_index );
309 for( int i = 0; i <= i_card_index; ++i )
312 p_sys->p_card->Release();
313 result = decklink_iterator->Next( &p_sys->p_card );
320 msg_Err( p_demux, "DeckLink PCI card %d not found", i_card_index );
324 const char *psz_model_name;
325 result = p_sys->p_card->GetModelName( &psz_model_name );
329 msg_Err( p_demux, "Could not get model name" );
333 msg_Dbg( p_demux, "Opened DeckLink PCI card %d (%s)", i_card_index, psz_model_name );
335 if( p_sys->p_card->QueryInterface( IID_IDeckLinkInput, (void**)&p_sys->p_input) != S_OK )
337 msg_Err( p_demux, "Card has no inputs" );
341 /* Set up the video and audio sources. */
342 IDeckLinkConfiguration *p_config;
343 if( p_sys->p_card->QueryInterface( IID_IDeckLinkConfiguration, (void**)&p_config) != S_OK )
345 msg_Err( p_demux, "Failed to get configuration interface" );
349 psz_video_connection = var_CreateGetNonEmptyString( p_demux, "decklink-video-connection" );
350 if( psz_video_connection )
352 BMDVideoConnection conn;
353 if ( !strcmp( psz_video_connection, "sdi" ) )
354 conn = bmdVideoConnectionSDI;
355 else if ( !strcmp( psz_video_connection, "hdmi" ) )
356 conn = bmdVideoConnectionHDMI;
357 else if ( !strcmp( psz_video_connection, "opticalsdi" ) )
358 conn = bmdVideoConnectionOpticalSDI;
359 else if ( !strcmp( psz_video_connection, "component" ) )
360 conn = bmdVideoConnectionComponent;
361 else if ( !strcmp( psz_video_connection, "composite" ) )
362 conn = bmdVideoConnectionComposite;
363 else if ( !strcmp( psz_video_connection, "svideo" ) )
364 conn = bmdVideoConnectionSVideo;
367 msg_Err( p_demux, "Invalid --decklink-video-connection specified; choose one of " \
368 "sdi, hdmi, opticalsdi, component, composite, or svideo." );
372 msg_Dbg( p_demux, "Setting video input format to 0x%x", conn);
373 result = p_config->SetVideoInputFormat( conn );
376 msg_Err( p_demux, "Failed to set video input connection" );
381 psz_audio_connection = var_CreateGetNonEmptyString( p_demux, "decklink-audio-connection" );
382 if( psz_audio_connection )
384 BMDAudioConnection conn;
385 if ( !strcmp( psz_audio_connection, "embedded" ) )
386 conn = bmdAudioConnectionEmbedded;
387 else if ( !strcmp( psz_audio_connection, "aesebu" ) )
388 conn = bmdAudioConnectionAESEBU;
389 else if ( !strcmp( psz_audio_connection, "analog" ) )
390 conn = bmdAudioConnectionAnalog;
393 msg_Err( p_demux, "Invalid --decklink-audio-connection specified; choose one of " \
394 "embedded, aesebu, or analog." );
398 msg_Dbg( p_demux, "Setting audio input format to 0x%x", conn);
399 result = p_config->SetAudioInputFormat( conn );
402 msg_Err( p_demux, "Failed to set audio input connection" );
407 /* Get the list of display modes. */
408 IDeckLinkDisplayModeIterator *p_display_iterator;
409 result = p_sys->p_input->GetDisplayModeIterator( &p_display_iterator );
412 msg_Err( p_demux, "Failed to enumerate display modes" );
416 psz_display_mode = var_CreateGetNonEmptyString( p_demux, "decklink-mode" );
417 if( !psz_display_mode || strlen( psz_display_mode ) > 4 ) {
418 msg_Err( p_demux, "Missing or invalid --decklink-mode string" );
423 * Pad the --decklink-mode string to four characters, so the user can specify e.g. "pal"
424 * without having to add the trailing space.
426 char sz_display_mode_padded[5];
427 strcpy(sz_display_mode_padded, " ");
428 for( int i = 0; i < strlen( psz_display_mode ); ++i )
429 sz_display_mode_padded[i] = psz_display_mode[i];
431 BMDDisplayMode wanted_mode_id;
432 memcpy( &wanted_mode_id, &sz_display_mode_padded, sizeof(wanted_mode_id) );
434 b_found_mode = false;
438 IDeckLinkDisplayMode *p_display_mode;
439 result = p_display_iterator->Next( &p_display_mode );
440 if( result != S_OK || !p_display_mode )
443 char sz_mode_id_text[5] = {0};
444 BMDDisplayMode mode_id = ntohl( p_display_mode->GetDisplayMode() );
445 memcpy( sz_mode_id_text, &mode_id, sizeof(mode_id) );
447 const char *psz_mode_name;
448 result = p_display_mode->GetName( &psz_mode_name );
451 msg_Err( p_demux, "Failed to get display mode name" );
452 p_display_mode->Release();
456 BMDTimeValue frame_duration, time_scale;
457 result = p_display_mode->GetFrameRate( &frame_duration, &time_scale );
460 msg_Err( p_demux, "Failed to get frame rate" );
461 p_display_mode->Release();
465 const char *psz_field_dominance;
466 uint32_t i_dominance_flags = 0;
467 switch( p_display_mode->GetFieldDominance() )
469 case bmdProgressiveFrame:
470 psz_field_dominance = "";
472 case bmdProgressiveSegmentedFrame:
473 psz_field_dominance = ", segmented";
475 case bmdLowerFieldFirst:
476 psz_field_dominance = ", interlaced [BFF]";
477 i_dominance_flags = BLOCK_FLAG_BOTTOM_FIELD_FIRST;
479 case bmdUpperFieldFirst:
480 psz_field_dominance = ", interlaced [TFF]";
481 i_dominance_flags = BLOCK_FLAG_TOP_FIELD_FIRST;
483 case bmdUnknownFieldDominance:
485 psz_field_dominance = ", unknown field dominance";
489 msg_Dbg( p_demux, "Found mode '%s': %s (%dx%d, %.3f fps%s)",
490 sz_mode_id_text, psz_mode_name,
491 p_display_mode->GetWidth(), p_display_mode->GetHeight(),
492 double(time_scale) / frame_duration, psz_field_dominance );
494 if( wanted_mode_id == mode_id )
497 i_width = p_display_mode->GetWidth();
498 i_height = p_display_mode->GetHeight();
499 i_fps_num = time_scale;
500 i_fps_den = frame_duration;
501 p_sys->i_dominance_flags = i_dominance_flags;
504 p_display_mode->Release();
509 msg_Err( p_demux, "Unknown video mode specified. " \
510 "Run VLC with -v --verbose-objects=-all,+decklink " \
511 "to get a list of supported modes." );
515 result = p_sys->p_input->EnableVideoInput( htonl( wanted_mode_id ), bmdFormat8BitYUV, 0 );
518 msg_Err( p_demux, "Failed to enable video input" );
523 p_sys->i_channels = var_InheritInteger( p_demux, "decklink-audio-channels" );
524 i_rate = var_InheritInteger( p_demux, "decklink-audio-rate" );
525 if( i_rate > 0 && p_sys->i_channels > 0 )
527 result = p_sys->p_input->EnableAudioInput( i_rate, bmdAudioSampleType16bitInteger, p_sys->i_channels );
530 msg_Err( p_demux, "Failed to enable audio input" );
535 p_sys->p_delegate = new DeckLinkCaptureDelegate( p_demux );
536 p_sys->p_input->SetCallback( p_sys->p_delegate );
538 result = p_sys->p_input->StartStreams();
541 msg_Err( p_demux, "Could not start streaming from SDI card. This could be caused "
542 "by invalid video mode or flags, access denied, or card already in use." );
546 /* Declare elementary streams */
547 es_format_t video_fmt;
548 es_format_Init( &video_fmt, VIDEO_ES, VLC_CODEC_UYVY );
549 video_fmt.video.i_width = i_width;
550 video_fmt.video.i_height = i_height;
551 video_fmt.video.i_sar_num = 1;
552 video_fmt.video.i_sar_den = 1;
553 video_fmt.video.i_frame_rate = i_fps_num;
554 video_fmt.video.i_frame_rate_base = i_fps_den;
555 video_fmt.i_bitrate = video_fmt.video.i_width * video_fmt.video.i_height * video_fmt.video.i_frame_rate * 2 * 8;
557 if ( !var_InheritURational( p_demux, &u_aspect_num, &u_aspect_den, "decklink-aspect-ratio" ) &&
558 u_aspect_num > 0 && u_aspect_den > 0 ) {
559 video_fmt.video.i_sar_num = u_aspect_num * video_fmt.video.i_height;
560 video_fmt.video.i_sar_den = u_aspect_den * video_fmt.video.i_width;
563 msg_Dbg( p_demux, "added new video es %4.4s %dx%d",
564 (char*)&video_fmt.i_codec, video_fmt.video.i_width, video_fmt.video.i_height );
565 p_sys->p_video_es = es_out_Add( p_demux->out, &video_fmt );
567 es_format_t audio_fmt;
568 es_format_Init( &audio_fmt, AUDIO_ES, VLC_CODEC_S16N );
569 audio_fmt.audio.i_channels = p_sys->i_channels;
570 audio_fmt.audio.i_rate = i_rate;
571 audio_fmt.audio.i_bitspersample = 16;
572 audio_fmt.audio.i_blockalign = audio_fmt.audio.i_channels * audio_fmt.audio.i_bitspersample / 8;
573 audio_fmt.i_bitrate = audio_fmt.audio.i_channels * audio_fmt.audio.i_rate * audio_fmt.audio.i_bitspersample;
575 msg_Dbg( p_demux, "added new audio es %4.4s %dHz %dbpp %dch",
576 (char*)&audio_fmt.i_codec, audio_fmt.audio.i_rate, audio_fmt.audio.i_bitspersample, audio_fmt.audio.i_channels);
577 p_sys->p_audio_es = es_out_Add( p_demux->out, &audio_fmt );
582 if( decklink_iterator )
583 decklink_iterator->Release();
588 free( psz_video_connection );
589 free( psz_audio_connection );
590 free( psz_display_mode );
592 if( p_display_iterator )
593 p_display_iterator->Release();
595 if( ret != VLC_SUCCESS )
601 static void Close( vlc_object_t *p_this )
603 demux_t *p_demux = (demux_t *)p_this;
604 demux_sys_t *p_sys = p_demux->p_sys;
608 p_sys->p_input->StopStreams();
609 p_sys->p_input->Release();
613 p_sys->p_card->Release();
615 if( p_sys->p_delegate )
616 p_sys->p_delegate->Release();
618 if( p_sys->p_video_frame )
619 block_Release( p_sys->p_video_frame );
621 if( p_sys->p_audio_frame )
622 block_Release( p_sys->p_audio_frame );
627 static int Control( demux_t *p_demux, int i_query, va_list args )
629 demux_sys_t *p_sys = p_demux->p_sys;
635 /* Special for access_demux */
636 case DEMUX_CAN_PAUSE:
638 case DEMUX_CAN_CONTROL_PACE:
639 pb = (bool*)va_arg( args, bool * );
643 case DEMUX_GET_PTS_DELAY:
644 pi64 = (int64_t*)va_arg( args, int64_t * );
645 *pi64 = var_InheritInteger( p_demux, "decklink-caching" ) * 1000;
649 pi64 = (int64_t*)va_arg( args, int64_t * );
650 *pi64 = p_sys->i_last_pts;
653 /* TODO implement others */
661 static int Demux( demux_t *p_demux )
663 demux_sys_t *p_sys = p_demux->p_sys;
664 block_t *p_video_block = NULL;
665 block_t *p_audio_block = NULL;
667 vlc_mutex_lock( &p_sys->frame_lock );
669 while( !p_sys->p_video_frame && !p_sys->p_audio_frame )
670 vlc_cond_wait( &p_sys->has_frame, &p_sys->frame_lock );
672 p_video_block = p_sys->p_video_frame;
673 p_sys->p_video_frame = NULL;
675 p_audio_block = p_sys->p_audio_frame;
676 p_sys->p_audio_frame = NULL;
678 vlc_mutex_unlock( &p_sys->frame_lock );
682 if( p_video_block->i_pts > p_sys->i_last_pts )
683 p_sys->i_last_pts = p_video_block->i_pts;
684 es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_video_block->i_pts );
685 es_out_Send( p_demux->out, p_sys->p_video_es, p_video_block );
690 if( p_audio_block->i_pts > p_sys->i_last_pts )
691 p_sys->i_last_pts = p_audio_block->i_pts;
692 es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_audio_block->i_pts );
693 es_out_Send( p_demux->out, p_sys->p_audio_es, p_audio_block );