1 /* BlackMagic SDI driver */
8 #define INT64_C(c) c ## LL
11 #include <vlc_common.h>
12 #include <vlc_plugin.h>
13 #include <vlc_input.h>
14 #include <vlc_demux.h>
15 #include <vlc_access.h>
16 #include <vlc_picture.h>
17 #include <vlc_charset.h>
20 #include <arpa/inet.h>
22 #include "DeckLinkAPI.h"
23 #include "DeckLinkAPIDispatch.cpp"
25 static int Open ( vlc_object_t * );
26 static void Close( vlc_object_t * );
28 #define CARD_INDEX_TEXT N_("Input card to use")
29 #define CARD_INDEX_LONGTEXT N_( \
30 "SDI capture card to use, if multiple exist. " \
31 "The cards are numbered from 0." )
33 #define MODE_TEXT N_("Desired input video mode")
34 #define MODE_LONGTEXT N_( \
35 "Desired input video mode for SDI captures. " \
36 "This value should be a FOURCC code in textual " \
37 "form, e.g. \"ntsc\"." )
39 #define CACHING_TEXT N_("Caching value in ms")
40 #define CACHING_LONGTEXT N_( \
41 "Caching value for SDI captures. This " \
42 "value should be set in milliseconds." )
44 #define AUDIO_CONNECTION_TEXT N_("Audio connection")
45 #define AUDIO_CONNECTION_LONGTEXT N_( \
46 "Audio connection to use for SDI captures. " \
47 "Valid choices: embedded, aesebu, analog. " \
48 "Leave blank for card default." )
50 #define RATE_TEXT N_("Audio sampling rate in Hz")
51 #define RATE_LONGTEXT N_( \
52 "Audio sampling rate (in hertz) for SDI captures. " \
53 "0 disables audio input." )
55 #define CHANNELS_TEXT N_("Number of audio channels")
56 #define CHANNELS_LONGTEXT N_( \
57 "Number of input audio channels for SDI captures. " \
58 "Must be 2, 8 or 16. 0 disables audio input." )
60 #define VIDEO_CONNECTION_TEXT N_("Video connection")
61 #define VIDEO_CONNECTION_LONGTEXT N_( \
62 "Video connection to use for SDI captures. " \
63 "Valid choices: sdi, hdmi, opticalsdi, component, " \
64 "composite, svideo. " \
65 "Leave blank for card default." )
67 #define ASPECT_RATIO_TEXT N_("Aspect ratio")
68 #define ASPECT_RATIO_LONGTEXT N_( \
69 "Aspect ratio (4:3, 16:9). Default assumes square pixels." )
72 set_shortname( N_("SDI") )
73 set_description( N_("BlackMagic SDI input") )
74 set_category( CAT_INPUT )
75 set_subcategory( SUBCAT_INPUT_ACCESS )
77 add_integer( "sdi-card-index", 0, NULL,
78 CARD_INDEX_TEXT, CARD_INDEX_LONGTEXT, true )
79 add_string( "sdi-mode", "pal ", NULL,
80 MODE_TEXT, MODE_LONGTEXT, true )
81 add_integer( "sdi-caching", DEFAULT_PTS_DELAY / 1000, NULL,
82 CACHING_TEXT, CACHING_LONGTEXT, true )
83 add_string( "sdi-audio-connection", 0, NULL,
84 AUDIO_CONNECTION_TEXT, AUDIO_CONNECTION_LONGTEXT, true )
85 add_integer( "sdi-audio-rate", 48000, NULL,
86 RATE_TEXT, RATE_LONGTEXT, true )
87 add_integer( "sdi-audio-channels", 2, NULL,
88 CHANNELS_TEXT, CHANNELS_LONGTEXT, true )
89 add_string( "sdi-video-connection", 0, NULL,
90 VIDEO_CONNECTION_TEXT, VIDEO_CONNECTION_LONGTEXT, true )
91 add_string( "sdi-aspect-ratio", NULL, NULL,
92 ASPECT_RATIO_TEXT, ASPECT_RATIO_LONGTEXT, true )
95 set_capability( "access_demux", 10 )
96 set_callbacks( Open, Close )
99 static int Demux ( demux_t * );
100 static int Control( demux_t *, int, va_list );
102 class DeckLinkCaptureDelegate;
107 IDeckLinkInput *p_input;
108 DeckLinkCaptureDelegate *p_delegate;
110 es_out_id_t *p_video_es;
111 es_out_id_t *p_audio_es;
114 int i_width, i_height, i_fps_num, i_fps_den;
115 uint32_t i_dominance_flags;
117 int i_rate, i_channels;
119 vlc_mutex_t frame_lock;
120 block_t *p_video_frame; // protected by <frame_lock>
121 block_t *p_audio_frame; // protected by <frame_lock>
122 vlc_cond_t has_frame; // related to <frame_lock>
125 class DeckLinkCaptureDelegate : public IDeckLinkInputCallback
128 DeckLinkCaptureDelegate( demux_t *p_demux ) : p_demux_(p_demux) {}
130 // FIXME: These leak.
131 virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv) { return E_NOINTERFACE; }
132 virtual ULONG STDMETHODCALLTYPE AddRef(void) { return 1; }
133 virtual ULONG STDMETHODCALLTYPE Release(void) { return 1; }
135 virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents, IDeckLinkDisplayMode*, BMDDetectedVideoInputFormatFlags);
136 virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame*, IDeckLinkAudioInputPacket*);
142 HRESULT DeckLinkCaptureDelegate::VideoInputFormatChanged(BMDVideoInputFormatChangedEvents events, IDeckLinkDisplayMode *mode, BMDDetectedVideoInputFormatFlags)
144 msg_Dbg( p_demux_, "Video input format changed" );
148 HRESULT DeckLinkCaptureDelegate::VideoInputFrameArrived(IDeckLinkVideoInputFrame* videoFrame, IDeckLinkAudioInputPacket* audioFrame)
150 demux_sys_t *p_sys = p_demux_->p_sys;
151 block_t *p_video_frame = NULL;
152 block_t *p_audio_frame = NULL;
156 if( videoFrame->GetFlags() & bmdFrameHasNoInputSource )
158 msg_Warn( p_demux_, "No input signal detected" );
162 const int i_width = videoFrame->GetWidth();
163 const int i_height = videoFrame->GetHeight();
164 const int i_stride = videoFrame->GetRowBytes();
167 p_video_frame = block_New( p_demux_, i_width * i_height * i_bpp );
170 msg_Err( p_demux_, "Could not allocate memory for video frame" );
175 videoFrame->GetBytes( &frame_bytes );
176 for( int y = 0; y < i_height; ++y )
178 const uint8_t *src = (const uint8_t *)frame_bytes + i_stride * y;
179 uint8_t *dst = (uint8_t *)p_video_frame->p_buffer + i_width * i_bpp * y;
180 memcpy( dst, src, i_width * i_bpp );
183 BMDTimeValue stream_time, frame_duration;
184 videoFrame->GetStreamTime( &stream_time, &frame_duration, CLOCK_FREQ );
185 p_video_frame->i_flags = BLOCK_FLAG_TYPE_I | p_sys->i_dominance_flags;
186 if( p_sys->b_first_frame )
188 p_video_frame->i_flags |= BLOCK_FLAG_DISCONTINUITY;
189 p_sys->b_first_frame = false;
191 p_video_frame->i_pts = p_video_frame->i_dts = VLC_TS_0 + stream_time;
196 const int i_bytes = audioFrame->GetSampleFrameCount() * sizeof(int16_t) * p_sys->i_channels;
198 p_audio_frame = block_New( p_demux_, i_bytes );
201 msg_Err( p_demux_, "Could not allocate memory for audio frame" );
206 audioFrame->GetBytes( &frame_bytes );
207 memcpy( p_audio_frame->p_buffer, frame_bytes, i_bytes );
209 BMDTimeValue packet_time;
210 audioFrame->GetPacketTime( &packet_time, CLOCK_FREQ );
211 p_audio_frame->i_pts = p_audio_frame->i_dts = VLC_TS_0 + packet_time;
214 if( p_video_frame || p_audio_frame )
216 vlc_mutex_lock( &p_sys->frame_lock );
218 p_sys->p_video_frame = p_video_frame; // FIXME: leak
220 p_sys->p_audio_frame = p_audio_frame; // FIXME: leak
221 vlc_cond_signal( &p_sys->has_frame );
222 vlc_mutex_unlock( &p_sys->frame_lock );
228 static int Open( vlc_object_t *p_this )
230 demux_t *p_demux = (demux_t*)p_this;
233 /* Only when selected */
234 if( *p_demux->psz_access == '\0' )
238 p_demux->pf_demux = Demux;
239 p_demux->pf_control = Control;
240 p_demux->info.i_update = 0;
241 p_demux->info.i_title = 0;
242 p_demux->info.i_seekpoint = 0;
243 p_demux->p_sys = p_sys = (demux_sys_t*)calloc( 1, sizeof( demux_sys_t ) );
247 vlc_mutex_init( &p_sys->frame_lock );
248 vlc_cond_init( &p_sys->has_frame );
249 p_sys->p_video_frame = NULL;
251 IDeckLinkIterator *decklink_iterator = CreateDeckLinkIteratorInstance();
252 if( !decklink_iterator )
254 msg_Err( p_demux, "DeckLink drivers not found." );
255 // FIXME: Leak here and several other error paths.
261 int i_card_index = var_CreateGetInteger( p_demux, "sdi-card-index" );
262 for( int i = 0; i <= i_card_index; ++i )
264 result = decklink_iterator->Next( &p_sys->p_card );
271 msg_Err( p_demux, "DeckLink PCI card %d not found", i_card_index );
275 const char *psz_model_name;
276 result = p_sys->p_card->GetModelName( &psz_model_name );
280 msg_Err( p_demux, "Could not get model name" );
284 msg_Dbg( p_demux, "Opened DeckLink PCI card %d (%s)", i_card_index, psz_model_name );
286 if( p_sys->p_card->QueryInterface( IID_IDeckLinkInput, (void**)&p_sys->p_input) != S_OK )
288 msg_Err( p_demux, "Card has no inputs" );
292 // Set up the video and audio sources.
293 IDeckLinkConfiguration *p_config;
294 if( p_sys->p_card->QueryInterface( IID_IDeckLinkConfiguration, (void**)&p_config) != S_OK )
296 msg_Err( p_demux, "Failed to get configuration interface" );
300 char *psz_tmp = var_CreateGetNonEmptyString( p_demux, "sdi-video-connection" );
303 BMDVideoConnection conn;
304 if ( !strcmp( psz_tmp, "sdi" ) )
305 conn = bmdVideoConnectionSDI;
306 else if ( !strcmp( psz_tmp, "hdmi" ) )
307 conn = bmdVideoConnectionHDMI;
308 else if ( !strcmp( psz_tmp, "opticalsdi" ) )
309 conn = bmdVideoConnectionOpticalSDI;
310 else if ( !strcmp( psz_tmp, "component" ) )
311 conn = bmdVideoConnectionComponent;
312 else if ( !strcmp( psz_tmp, "composite" ) )
313 conn = bmdVideoConnectionComposite;
314 else if ( !strcmp( psz_tmp, "svideo" ) )
315 conn = bmdVideoConnectionSVideo;
318 msg_Err( p_demux, "Invalid --sdi-video-connection specified; choose one of " \
319 "sdi, hdmi, opticalsdi, component, composite, or svideo." );
324 msg_Dbg( p_demux, "Setting video input format to 0x%x", conn);
325 result = p_config->SetVideoInputFormat( conn );
328 msg_Err( p_demux, "Failed to set video input connection" );
333 psz_tmp = var_CreateGetNonEmptyString( p_demux, "sdi-audio-connection" );
336 BMDAudioConnection conn;
337 if ( !strcmp( psz_tmp, "embedded" ) )
338 conn = bmdAudioConnectionEmbedded;
339 else if ( !strcmp( psz_tmp, "aesebu" ) )
340 conn = bmdAudioConnectionAESEBU;
341 else if ( !strcmp( psz_tmp, "analog" ) )
342 conn = bmdAudioConnectionAnalog;
345 msg_Err( p_demux, "Invalid --sdi-audio-connection specified; choose one of " \
346 "embedded, aesebu, or analog." );
351 msg_Dbg( p_demux, "Setting audio input format to 0x%x", conn);
352 result = p_config->SetAudioInputFormat( conn );
355 msg_Err( p_demux, "Failed to set audio input connection" );
360 // Get the list of display modes.
361 IDeckLinkDisplayModeIterator *p_display_iterator;
362 result = p_sys->p_input->GetDisplayModeIterator( &p_display_iterator );
365 msg_Err( p_demux, "Failed to enumerate display modes" );
369 char *psz_display_mode = var_CreateGetString( p_demux, "sdi-mode" );
370 if( !psz_display_mode || strlen( psz_display_mode ) == 0 || strlen( psz_display_mode ) > 4 ) {
371 msg_Err( p_demux, "Missing or invalid --sdi-mode string" );
375 // Pad the --sdi-mode string to four characters, so the user can specify e.g. "pal"
376 // without having to add the trailing space.
377 char sz_display_mode_padded[5];
378 strcpy(sz_display_mode_padded, " ");
379 for( int i = 0; i < strlen( psz_display_mode ); ++i )
380 sz_display_mode_padded[i] = psz_display_mode[i];
382 BMDDisplayMode wanted_mode_id;
383 memcpy( &wanted_mode_id, &sz_display_mode_padded, sizeof(wanted_mode_id) );
385 bool b_found_mode = false;
389 IDeckLinkDisplayMode *p_display_mode;
390 result = p_display_iterator->Next( &p_display_mode );
391 if( result != S_OK || !p_display_mode )
396 char sz_mode_id_text[5] = {0};
397 BMDDisplayMode mode_id = ntohl( p_display_mode->GetDisplayMode() );
398 memcpy( sz_mode_id_text, &mode_id, sizeof(mode_id) );
400 const char *psz_mode_name;
401 result = p_display_mode->GetName( &psz_mode_name );
404 msg_Err( p_demux, "Failed to get display mode name" );
408 BMDTimeValue frame_duration, time_scale;
409 result = p_display_mode->GetFrameRate( &frame_duration, &time_scale );
412 msg_Err( p_demux, "Failed to get frame rate" );
416 const char *psz_field_dominance;
417 uint32_t i_dominance_flags = 0;
418 switch( p_display_mode->GetFieldDominance() )
420 case bmdProgressiveFrame:
421 psz_field_dominance = "";
423 case bmdProgressiveSegmentedFrame:
424 psz_field_dominance = ", segmented";
426 case bmdLowerFieldFirst:
427 psz_field_dominance = ", interlaced [BFF]";
428 i_dominance_flags = BLOCK_FLAG_BOTTOM_FIELD_FIRST;
430 case bmdUpperFieldFirst:
431 psz_field_dominance = ", interlaced [TFF]";
432 i_dominance_flags = BLOCK_FLAG_TOP_FIELD_FIRST;
434 case bmdUnknownFieldDominance:
436 psz_field_dominance = ", unknown field dominance";
440 msg_Dbg( p_demux, "Found mode '%s': %s (%dx%d, %.3f fps%s)",
441 sz_mode_id_text, psz_mode_name,
442 p_display_mode->GetWidth(), p_display_mode->GetHeight(),
443 double(time_scale) / frame_duration, psz_field_dominance );
445 if( wanted_mode_id == mode_id )
448 p_sys->i_width = p_display_mode->GetWidth();
449 p_sys->i_height = p_display_mode->GetHeight();
450 p_sys->i_fps_num = time_scale;
451 p_sys->i_fps_den = frame_duration;
452 p_sys->i_dominance_flags = i_dominance_flags;
458 msg_Err( p_demux, "Unknown SDI mode specified. " \
459 "Run VLC with -v --verbose-objects=-all,+sdi " \
460 "to get a list of supported modes." );
464 result = p_sys->p_input->EnableVideoInput( htonl( wanted_mode_id ), bmdFormat8BitYUV, 0 );
467 msg_Err( p_demux, "Failed to enable video input" );
472 p_sys->i_rate = var_CreateGetInteger( p_demux, "sdi-audio-rate" );
473 p_sys->i_channels = var_CreateGetInteger( p_demux, "sdi-audio-channels" );
474 if( p_sys->i_rate > 0 && p_sys->i_channels > 0 )
476 result = p_sys->p_input->EnableAudioInput( p_sys->i_rate, bmdAudioSampleType16bitInteger, p_sys->i_channels );
479 msg_Err( p_demux, "Failed to enable audio input" );
484 p_sys->p_delegate = new DeckLinkCaptureDelegate( p_demux );
485 p_sys->p_input->SetCallback( p_sys->p_delegate );
487 result = p_sys->p_input->StartStreams();
490 msg_Err( p_demux, "Failed to start streams" );
494 /* Declare elementary streams */
495 es_format_t video_fmt;
496 es_format_Init( &video_fmt, VIDEO_ES, VLC_CODEC_UYVY );
497 video_fmt.video.i_width = p_sys->i_width;
498 video_fmt.video.i_height = p_sys->i_height;
499 video_fmt.video.i_sar_num = 1;
500 video_fmt.video.i_sar_den = 1;
501 video_fmt.video.i_frame_rate = p_sys->i_fps_num;
502 video_fmt.video.i_frame_rate_base = p_sys->i_fps_den;
503 video_fmt.i_bitrate = video_fmt.video.i_width * video_fmt.video.i_height * video_fmt.video.i_frame_rate * 2 * 8;
505 psz_tmp = var_CreateGetNonEmptyString( p_demux, "sdi-aspect-ratio" );
508 char *psz_denominator = strchr( psz_tmp, ':' );
509 if( psz_denominator )
511 *psz_denominator++ = '\0';
512 video_fmt.video.i_sar_num = atoi( psz_tmp ) * video_fmt.video.i_height;
513 video_fmt.video.i_sar_den = atoi( psz_denominator ) * video_fmt.video.i_width;
518 msg_Dbg( p_demux, "added new video es %4.4s %dx%d",
519 (char*)&video_fmt.i_codec, video_fmt.video.i_width, video_fmt.video.i_height );
520 p_sys->p_video_es = es_out_Add( p_demux->out, &video_fmt );
522 es_format_t audio_fmt;
523 es_format_Init( &audio_fmt, AUDIO_ES, VLC_CODEC_S16N );
524 audio_fmt.audio.i_channels = p_sys->i_channels;
525 audio_fmt.audio.i_rate = p_sys->i_rate;
526 audio_fmt.audio.i_bitspersample = 16;
527 audio_fmt.audio.i_blockalign = audio_fmt.audio.i_channels * audio_fmt.audio.i_bitspersample / 8;
528 audio_fmt.i_bitrate = audio_fmt.audio.i_channels * audio_fmt.audio.i_rate * audio_fmt.audio.i_bitspersample;
530 msg_Dbg( p_demux, "added new audio es %4.4s %dHz %dbpp %dch",
531 (char*)&audio_fmt.i_codec, audio_fmt.audio.i_rate, audio_fmt.audio.i_bitspersample, audio_fmt.audio.i_channels);
532 p_sys->p_audio_es = es_out_Add( p_demux->out, &audio_fmt );
534 p_sys->b_first_frame = true;
536 /* Update default_pts to a suitable value for access */
537 var_Create( p_demux, "sdi-caching", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
542 static void Close( vlc_object_t *p_this )
544 demux_t *p_demux = (demux_t *)p_this;
545 demux_sys_t *p_sys = p_demux->p_sys;
550 static int Control( demux_t *p_demux, int i_query, va_list args )
557 /* Special for access_demux */
558 case DEMUX_CAN_PAUSE:
560 case DEMUX_CAN_CONTROL_PACE:
561 pb = (bool*)va_arg( args, bool * );
565 case DEMUX_GET_PTS_DELAY:
566 pi64 = (int64_t*)va_arg( args, int64_t * );
567 *pi64 = var_GetInteger( p_demux, "sdi-caching" ) * 1000;
571 pi64 = (int64_t*)va_arg( args, int64_t * );
572 *pi64 = mdate(); // FIXME
575 /* TODO implement others */
583 static int Demux( demux_t *p_demux )
585 demux_sys_t *p_sys = p_demux->p_sys;
586 block_t *p_video_block = NULL;
587 block_t *p_audio_block = NULL;
589 vlc_mutex_lock( &p_sys->frame_lock );
591 while( !p_sys->p_video_frame && !p_sys->p_audio_frame )
592 vlc_cond_wait( &p_sys->has_frame, &p_sys->frame_lock );
594 p_video_block = p_sys->p_video_frame;
595 p_sys->p_video_frame = NULL;
597 p_audio_block = p_sys->p_audio_frame;
598 p_sys->p_audio_frame = NULL;
600 vlc_mutex_unlock( &p_sys->frame_lock );
604 es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_video_block->i_pts );
605 es_out_Send( p_demux->out, p_sys->p_video_es, p_video_block );
610 es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_audio_block->i_pts );
611 es_out_Send( p_demux->out, p_sys->p_audio_es, p_audio_block );