1 /*****************************************************************************
2 * decklink.cpp: BlackMagic DeckLink SDI input module
3 *****************************************************************************
4 * Copyright (C) 2010 VideoLAN
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;
11 * version 2 of the License.
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 *****************************************************************************/
29 #define INT64_C(c) c ## LL
32 #include <vlc_common.h>
33 #include <vlc_plugin.h>
34 #include <vlc_input.h>
35 #include <vlc_demux.h>
36 #include <vlc_access.h>
37 #include <vlc_picture.h>
38 #include <vlc_charset.h>
40 #include <vlc_atomic.h>
42 #include <arpa/inet.h>
44 #include <DeckLinkAPI.h>
45 #include <DeckLinkAPIDispatch.cpp>
47 static int Open ( vlc_object_t * );
48 static void Close( vlc_object_t * );
50 #define CARD_INDEX_TEXT N_("Input card to use")
51 #define CARD_INDEX_LONGTEXT N_( \
52 "DeckLink capture card to use, if multiple exist. " \
53 "The cards are numbered from 0." )
55 #define MODE_TEXT N_("Desired input video mode")
56 #define MODE_LONGTEXT N_( \
57 "Desired input video mode for DeckLink captures. " \
58 "This value should be a FOURCC code in textual " \
59 "form, e.g. \"ntsc\"." )
61 #define CACHING_TEXT N_("Caching value in ms")
62 #define CACHING_LONGTEXT N_( \
63 "Caching value for DeckLink captures. This " \
64 "value should be set in milliseconds." )
66 #define AUDIO_CONNECTION_TEXT N_("Audio connection")
67 #define AUDIO_CONNECTION_LONGTEXT N_( \
68 "Audio connection to use for DeckLink captures. " \
69 "Valid choices: embedded, aesebu, analog. " \
70 "Leave blank for card default." )
72 #define RATE_TEXT N_("Audio sampling rate in Hz")
73 #define RATE_LONGTEXT N_( \
74 "Audio sampling rate (in hertz) for DeckLink captures. " \
75 "0 disables audio input." )
77 #define CHANNELS_TEXT N_("Number of audio channels")
78 #define CHANNELS_LONGTEXT N_( \
79 "Number of input audio channels for DeckLink captures. " \
80 "Must be 2, 8 or 16. 0 disables audio input." )
82 #define VIDEO_CONNECTION_TEXT N_("Video connection")
83 #define VIDEO_CONNECTION_LONGTEXT N_( \
84 "Video connection to use for DeckLink captures. " \
85 "Valid choices: sdi, hdmi, opticalsdi, component, " \
86 "composite, svideo. " \
87 "Leave blank for card default." )
89 #define ASPECT_RATIO_TEXT N_("Aspect ratio")
90 #define ASPECT_RATIO_LONGTEXT N_( \
91 "Aspect ratio (4:3, 16:9). Default assumes square pixels." )
94 set_shortname( N_("DeckLink") )
95 set_description( N_("Blackmagic DeckLink SDI input") )
96 set_category( CAT_INPUT )
97 set_subcategory( SUBCAT_INPUT_ACCESS )
99 add_integer( "decklink-card-index", 0, NULL,
100 CARD_INDEX_TEXT, CARD_INDEX_LONGTEXT, true )
101 add_string( "decklink-mode", "pal ", NULL,
102 MODE_TEXT, MODE_LONGTEXT, true )
103 add_integer( "decklink-caching", DEFAULT_PTS_DELAY / 1000, NULL,
104 CACHING_TEXT, CACHING_LONGTEXT, true )
105 add_string( "decklink-audio-connection", 0, NULL,
106 AUDIO_CONNECTION_TEXT, AUDIO_CONNECTION_LONGTEXT, true )
107 add_integer( "decklink-audio-rate", 48000, NULL,
108 RATE_TEXT, RATE_LONGTEXT, true )
109 add_integer( "decklink-audio-channels", 2, NULL,
110 CHANNELS_TEXT, CHANNELS_LONGTEXT, true )
111 add_string( "decklink-video-connection", 0, NULL,
112 VIDEO_CONNECTION_TEXT, VIDEO_CONNECTION_LONGTEXT, true )
113 add_string( "decklink-aspect-ratio", NULL, NULL,
114 ASPECT_RATIO_TEXT, ASPECT_RATIO_LONGTEXT, true )
116 add_shortcut( "decklink" )
117 set_capability( "access_demux", 10 )
118 set_callbacks( Open, Close )
121 static int Demux ( demux_t * );
122 static int Control( demux_t *, int, va_list );
124 class DeckLinkCaptureDelegate;
129 IDeckLinkInput *p_input;
130 DeckLinkCaptureDelegate *p_delegate;
132 es_out_id_t *p_video_es;
133 es_out_id_t *p_audio_es;
137 int i_width, i_height, i_fps_num, i_fps_den;
138 uint32_t i_dominance_flags;
140 int i_rate, i_channels;
142 vlc_mutex_t frame_lock;
143 block_t *p_video_frame; /* protected by <frame_lock> */
144 block_t *p_audio_frame; /* protected by <frame_lock> */
145 vlc_cond_t has_frame; /* related to <frame_lock> */
148 class DeckLinkCaptureDelegate : public IDeckLinkInputCallback
151 DeckLinkCaptureDelegate( demux_t *p_demux ) : p_demux_(p_demux)
153 vlc_atomic_set( &m_ref_, 1 );
156 virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv) { return E_NOINTERFACE; }
158 virtual ULONG STDMETHODCALLTYPE AddRef(void)
160 return vlc_atomic_inc( &m_ref_ );
163 virtual ULONG STDMETHODCALLTYPE Release(void)
165 uintptr_t new_ref = vlc_atomic_dec( &m_ref_ );
171 virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents, IDeckLinkDisplayMode*, BMDDetectedVideoInputFormatFlags);
172 virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame*, IDeckLinkAudioInputPacket*);
179 HRESULT DeckLinkCaptureDelegate::VideoInputFormatChanged(BMDVideoInputFormatChangedEvents events, IDeckLinkDisplayMode *mode, BMDDetectedVideoInputFormatFlags)
181 msg_Dbg( p_demux_, "Video input format changed" );
185 HRESULT DeckLinkCaptureDelegate::VideoInputFrameArrived(IDeckLinkVideoInputFrame* videoFrame, IDeckLinkAudioInputPacket* audioFrame)
187 demux_sys_t *p_sys = p_demux_->p_sys;
188 block_t *p_video_frame = NULL;
189 block_t *p_audio_frame = NULL;
193 if( videoFrame->GetFlags() & bmdFrameHasNoInputSource )
195 msg_Warn( p_demux_, "No input signal detected" );
199 const int i_width = videoFrame->GetWidth();
200 const int i_height = videoFrame->GetHeight();
201 const int i_stride = videoFrame->GetRowBytes();
204 p_video_frame = block_New( p_demux_, i_width * i_height * i_bpp );
207 msg_Err( p_demux_, "Could not allocate memory for video frame" );
212 videoFrame->GetBytes( &frame_bytes );
213 for( int y = 0; y < i_height; ++y )
215 const uint8_t *src = (const uint8_t *)frame_bytes + i_stride * y;
216 uint8_t *dst = (uint8_t *)p_video_frame->p_buffer + i_width * i_bpp * y;
217 memcpy( dst, src, i_width * i_bpp );
220 BMDTimeValue stream_time, frame_duration;
221 videoFrame->GetStreamTime( &stream_time, &frame_duration, CLOCK_FREQ );
222 p_video_frame->i_flags = BLOCK_FLAG_TYPE_I | p_sys->i_dominance_flags;
223 if( p_sys->b_first_frame )
225 p_video_frame->i_flags |= BLOCK_FLAG_DISCONTINUITY;
226 p_sys->b_first_frame = false;
228 p_video_frame->i_pts = p_video_frame->i_dts = VLC_TS_0 + stream_time;
233 const int i_bytes = audioFrame->GetSampleFrameCount() * sizeof(int16_t) * p_sys->i_channels;
235 p_audio_frame = block_New( p_demux_, i_bytes );
238 msg_Err( p_demux_, "Could not allocate memory for audio frame" );
240 block_Release( p_video_frame );
245 audioFrame->GetBytes( &frame_bytes );
246 memcpy( p_audio_frame->p_buffer, frame_bytes, i_bytes );
248 BMDTimeValue packet_time;
249 audioFrame->GetPacketTime( &packet_time, CLOCK_FREQ );
250 p_audio_frame->i_pts = p_audio_frame->i_dts = VLC_TS_0 + packet_time;
253 if( p_video_frame || p_audio_frame )
255 vlc_mutex_lock( &p_sys->frame_lock );
258 if( p_sys->p_video_frame )
259 block_Release( p_sys->p_video_frame );
260 p_sys->p_video_frame = p_video_frame;
264 if( p_sys->p_audio_frame )
265 block_Release( p_sys->p_audio_frame );
266 p_sys->p_audio_frame = p_audio_frame;
268 vlc_cond_signal( &p_sys->has_frame );
269 vlc_mutex_unlock( &p_sys->frame_lock );
275 static int Open( vlc_object_t *p_this )
277 demux_t *p_demux = (demux_t*)p_this;
279 int ret = VLC_SUCCESS;
281 char *psz_display_mode = NULL;
282 char *psz_video_connection = NULL;
283 char *psz_audio_connection = NULL;
287 /* Only when selected */
288 if( *p_demux->psz_access == '\0' )
292 p_demux->pf_demux = Demux;
293 p_demux->pf_control = Control;
294 p_demux->info.i_update = 0;
295 p_demux->info.i_title = 0;
296 p_demux->info.i_seekpoint = 0;
297 p_demux->p_sys = p_sys = (demux_sys_t*)calloc( 1, sizeof( demux_sys_t ) );
301 vlc_mutex_init( &p_sys->frame_lock );
302 vlc_cond_init( &p_sys->has_frame );
303 p_sys->b_first_frame = true;
305 IDeckLinkIterator *decklink_iterator = CreateDeckLinkIteratorInstance();
306 if( !decklink_iterator )
308 msg_Err( p_demux, "DeckLink drivers not found." );
315 i_card_index = var_InheritInteger( p_demux, "decklink-card-index" );
316 for( int i = 0; i <= i_card_index; ++i )
319 p_sys->p_card->Release();
320 result = decklink_iterator->Next( &p_sys->p_card );
327 msg_Err( p_demux, "DeckLink PCI card %d not found", i_card_index );
332 const char *psz_model_name;
333 result = p_sys->p_card->GetModelName( &psz_model_name );
337 msg_Err( p_demux, "Could not get model name" );
342 msg_Dbg( p_demux, "Opened DeckLink PCI card %d (%s)", i_card_index, psz_model_name );
344 if( p_sys->p_card->QueryInterface( IID_IDeckLinkInput, (void**)&p_sys->p_input) != S_OK )
346 msg_Err( p_demux, "Card has no inputs" );
351 /* Set up the video and audio sources. */
352 IDeckLinkConfiguration *p_config;
353 if( p_sys->p_card->QueryInterface( IID_IDeckLinkConfiguration, (void**)&p_config) != S_OK )
355 msg_Err( p_demux, "Failed to get configuration interface" );
360 psz_video_connection = var_CreateGetNonEmptyString( p_demux, "decklink-video-connection" );
361 if( psz_video_connection )
363 BMDVideoConnection conn;
364 if ( !strcmp( psz_video_connection, "sdi" ) )
365 conn = bmdVideoConnectionSDI;
366 else if ( !strcmp( psz_video_connection, "hdmi" ) )
367 conn = bmdVideoConnectionHDMI;
368 else if ( !strcmp( psz_video_connection, "opticalsdi" ) )
369 conn = bmdVideoConnectionOpticalSDI;
370 else if ( !strcmp( psz_video_connection, "component" ) )
371 conn = bmdVideoConnectionComponent;
372 else if ( !strcmp( psz_video_connection, "composite" ) )
373 conn = bmdVideoConnectionComposite;
374 else if ( !strcmp( psz_video_connection, "svideo" ) )
375 conn = bmdVideoConnectionSVideo;
378 msg_Err( p_demux, "Invalid --decklink-video-connection specified; choose one of " \
379 "sdi, hdmi, opticalsdi, component, composite, or svideo." );
384 msg_Dbg( p_demux, "Setting video input format to 0x%x", conn);
385 result = p_config->SetVideoInputFormat( conn );
388 msg_Err( p_demux, "Failed to set video input connection" );
394 psz_audio_connection = var_CreateGetNonEmptyString( p_demux, "decklink-audio-connection" );
395 if( psz_audio_connection )
397 BMDAudioConnection conn;
398 if ( !strcmp( psz_audio_connection, "embedded" ) )
399 conn = bmdAudioConnectionEmbedded;
400 else if ( !strcmp( psz_audio_connection, "aesebu" ) )
401 conn = bmdAudioConnectionAESEBU;
402 else if ( !strcmp( psz_audio_connection, "analog" ) )
403 conn = bmdAudioConnectionAnalog;
406 msg_Err( p_demux, "Invalid --decklink-audio-connection specified; choose one of " \
407 "embedded, aesebu, or analog." );
412 msg_Dbg( p_demux, "Setting audio input format to 0x%x", conn);
413 result = p_config->SetAudioInputFormat( conn );
416 msg_Err( p_demux, "Failed to set audio input connection" );
422 /* Get the list of display modes. */
423 IDeckLinkDisplayModeIterator *p_display_iterator;
424 result = p_sys->p_input->GetDisplayModeIterator( &p_display_iterator );
427 msg_Err( p_demux, "Failed to enumerate display modes" );
432 psz_display_mode = var_InheritString( p_demux, "decklink-mode" );
433 if( !psz_display_mode || strlen( psz_display_mode ) == 0 || strlen( psz_display_mode ) > 4 ) {
434 msg_Err( p_demux, "Missing or invalid --decklink-mode string" );
440 * Pad the --decklink-mode string to four characters, so the user can specify e.g. "pal"
441 * without having to add the trailing space.
443 char sz_display_mode_padded[5];
444 strcpy(sz_display_mode_padded, " ");
445 for( int i = 0; i < strlen( psz_display_mode ); ++i )
446 sz_display_mode_padded[i] = psz_display_mode[i];
448 BMDDisplayMode wanted_mode_id;
449 memcpy( &wanted_mode_id, &sz_display_mode_padded, sizeof(wanted_mode_id) );
451 b_found_mode = false;
455 IDeckLinkDisplayMode *p_display_mode;
456 result = p_display_iterator->Next( &p_display_mode );
457 if( result != S_OK || !p_display_mode )
460 char sz_mode_id_text[5] = {0};
461 BMDDisplayMode mode_id = ntohl( p_display_mode->GetDisplayMode() );
462 memcpy( sz_mode_id_text, &mode_id, sizeof(mode_id) );
464 const char *psz_mode_name;
465 result = p_display_mode->GetName( &psz_mode_name );
468 msg_Err( p_demux, "Failed to get display mode name" );
469 p_display_mode->Release();
474 BMDTimeValue frame_duration, time_scale;
475 result = p_display_mode->GetFrameRate( &frame_duration, &time_scale );
478 msg_Err( p_demux, "Failed to get frame rate" );
479 p_display_mode->Release();
484 const char *psz_field_dominance;
485 uint32_t i_dominance_flags = 0;
486 switch( p_display_mode->GetFieldDominance() )
488 case bmdProgressiveFrame:
489 psz_field_dominance = "";
491 case bmdProgressiveSegmentedFrame:
492 psz_field_dominance = ", segmented";
494 case bmdLowerFieldFirst:
495 psz_field_dominance = ", interlaced [BFF]";
496 i_dominance_flags = BLOCK_FLAG_BOTTOM_FIELD_FIRST;
498 case bmdUpperFieldFirst:
499 psz_field_dominance = ", interlaced [TFF]";
500 i_dominance_flags = BLOCK_FLAG_TOP_FIELD_FIRST;
502 case bmdUnknownFieldDominance:
504 psz_field_dominance = ", unknown field dominance";
508 msg_Dbg( p_demux, "Found mode '%s': %s (%dx%d, %.3f fps%s)",
509 sz_mode_id_text, psz_mode_name,
510 p_display_mode->GetWidth(), p_display_mode->GetHeight(),
511 double(time_scale) / frame_duration, psz_field_dominance );
513 if( wanted_mode_id == mode_id )
516 p_sys->i_width = p_display_mode->GetWidth();
517 p_sys->i_height = p_display_mode->GetHeight();
518 p_sys->i_fps_num = time_scale;
519 p_sys->i_fps_den = frame_duration;
520 p_sys->i_dominance_flags = i_dominance_flags;
523 p_display_mode->Release();
528 msg_Err( p_demux, "Unknown video mode specified. " \
529 "Run VLC with -v --verbose-objects=-all,+decklink " \
530 "to get a list of supported modes." );
535 result = p_sys->p_input->EnableVideoInput( htonl( wanted_mode_id ), bmdFormat8BitYUV, 0 );
538 msg_Err( p_demux, "Failed to enable video input" );
544 p_sys->i_rate = var_InheritInteger( p_demux, "decklink-audio-rate" );
545 p_sys->i_channels = var_InheritInteger( p_demux, "decklink-audio-channels" );
546 if( p_sys->i_rate > 0 && p_sys->i_channels > 0 )
548 result = p_sys->p_input->EnableAudioInput( p_sys->i_rate, bmdAudioSampleType16bitInteger, p_sys->i_channels );
551 msg_Err( p_demux, "Failed to enable audio input" );
557 p_sys->p_delegate = new DeckLinkCaptureDelegate( p_demux );
558 p_sys->p_input->SetCallback( p_sys->p_delegate );
560 result = p_sys->p_input->StartStreams();
563 msg_Err( p_demux, "Could not start streaming from SDI card. This could be caused "
564 "by invalid video mode or flags, access denied, or card already in use." );
569 /* Declare elementary streams */
570 es_format_t video_fmt;
571 es_format_Init( &video_fmt, VIDEO_ES, VLC_CODEC_UYVY );
572 video_fmt.video.i_width = p_sys->i_width;
573 video_fmt.video.i_height = p_sys->i_height;
574 video_fmt.video.i_sar_num = 1;
575 video_fmt.video.i_sar_den = 1;
576 video_fmt.video.i_frame_rate = p_sys->i_fps_num;
577 video_fmt.video.i_frame_rate_base = p_sys->i_fps_den;
578 video_fmt.i_bitrate = video_fmt.video.i_width * video_fmt.video.i_height * video_fmt.video.i_frame_rate * 2 * 8;
580 psz_aspect = var_CreateGetNonEmptyString( p_demux, "decklink-aspect-ratio" );
583 char *psz_denominator = strchr( psz_aspect, ':' );
584 if( psz_denominator )
586 *psz_denominator++ = '\0';
587 video_fmt.video.i_sar_num = atoi( psz_aspect ) * video_fmt.video.i_height;
588 video_fmt.video.i_sar_den = atoi( psz_denominator ) * video_fmt.video.i_width;
593 msg_Dbg( p_demux, "added new video es %4.4s %dx%d",
594 (char*)&video_fmt.i_codec, video_fmt.video.i_width, video_fmt.video.i_height );
595 p_sys->p_video_es = es_out_Add( p_demux->out, &video_fmt );
597 es_format_t audio_fmt;
598 es_format_Init( &audio_fmt, AUDIO_ES, VLC_CODEC_S16N );
599 audio_fmt.audio.i_channels = p_sys->i_channels;
600 audio_fmt.audio.i_rate = p_sys->i_rate;
601 audio_fmt.audio.i_bitspersample = 16;
602 audio_fmt.audio.i_blockalign = audio_fmt.audio.i_channels * audio_fmt.audio.i_bitspersample / 8;
603 audio_fmt.i_bitrate = audio_fmt.audio.i_channels * audio_fmt.audio.i_rate * audio_fmt.audio.i_bitspersample;
605 msg_Dbg( p_demux, "added new audio es %4.4s %dHz %dbpp %dch",
606 (char*)&audio_fmt.i_codec, audio_fmt.audio.i_rate, audio_fmt.audio.i_bitspersample, audio_fmt.audio.i_channels);
607 p_sys->p_audio_es = es_out_Add( p_demux->out, &audio_fmt );
609 /* Update default_pts to a suitable value for access */
610 var_Create( p_demux, "decklink-caching", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
613 if( decklink_iterator )
614 decklink_iterator->Release();
619 free( psz_video_connection );
620 free( psz_audio_connection );
621 free( psz_display_mode );
623 if( p_display_iterator )
624 p_display_iterator->Release();
626 if( ret != VLC_SUCCESS )
632 static void Close( vlc_object_t *p_this )
634 demux_t *p_demux = (demux_t *)p_this;
635 demux_sys_t *p_sys = p_demux->p_sys;
639 p_sys->p_input->StopStreams();
640 p_sys->p_input->Release();
644 p_sys->p_card->Release();
646 if( p_sys->p_delegate )
647 p_sys->p_delegate->Release();
649 if( p_sys->p_video_frame )
650 block_Release( p_sys->p_video_frame );
652 if( p_sys->p_audio_frame )
653 block_Release( p_sys->p_audio_frame );
658 static int Control( demux_t *p_demux, int i_query, va_list args )
660 demux_sys_t *p_sys = p_demux->p_sys;
666 /* Special for access_demux */
667 case DEMUX_CAN_PAUSE:
669 case DEMUX_CAN_CONTROL_PACE:
670 pb = (bool*)va_arg( args, bool * );
674 case DEMUX_GET_PTS_DELAY:
675 pi64 = (int64_t*)va_arg( args, int64_t * );
676 *pi64 = var_GetInteger( p_demux, "decklink-caching" ) * 1000;
680 pi64 = (int64_t*)va_arg( args, int64_t * );
681 *pi64 = p_sys->i_last_pts;
684 /* TODO implement others */
692 static int Demux( demux_t *p_demux )
694 demux_sys_t *p_sys = p_demux->p_sys;
695 block_t *p_video_block = NULL;
696 block_t *p_audio_block = NULL;
698 vlc_mutex_lock( &p_sys->frame_lock );
700 while( !p_sys->p_video_frame && !p_sys->p_audio_frame )
701 vlc_cond_wait( &p_sys->has_frame, &p_sys->frame_lock );
703 p_video_block = p_sys->p_video_frame;
704 p_sys->p_video_frame = NULL;
706 p_audio_block = p_sys->p_audio_frame;
707 p_sys->p_audio_frame = NULL;
709 vlc_mutex_unlock( &p_sys->frame_lock );
713 if( p_video_block->i_pts > p_sys->i_last_pts )
714 p_sys->i_last_pts = p_video_block->i_pts;
715 es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_video_block->i_pts );
716 es_out_Send( p_demux->out, p_sys->p_video_es, p_video_block );
721 if( p_audio_block->i_pts > p_sys->i_last_pts )
722 p_sys->i_last_pts = p_audio_block->i_pts;
723 es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_audio_block->i_pts );
724 es_out_Send( p_demux->out, p_sys->p_audio_es, p_audio_block );