]> git.sesse.net Git - vlc/blob - modules/access/sdi.cpp
Add video connection selection.
[vlc] / modules / access / sdi.cpp
1 /* BlackMagic SDI driver */
2
3 #ifdef HAVE_CONFIG_H
4 # include "config.h"
5 #endif
6
7 #ifndef INT64_C
8 #define INT64_C(c) c ## LL
9 #endif
10
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>
18 #include <vlc_fs.h>
19
20 #include <arpa/inet.h>
21
22 #include "DeckLinkAPI.h"
23 #include "DeckLinkAPIDispatch.cpp"
24
25 static int  Open ( vlc_object_t * );
26 static void Close( vlc_object_t * );
27
28 #define MODE_TEXT N_("Desired input video mode")
29 #define MODE_LONGTEXT N_( \
30     "Desired input video mode for SDI captures. " \
31     "This value should be a FOURCC code in textual " \
32     "form, e.g. \"ntsc\"." )
33
34 #define CACHING_TEXT N_("Caching value in ms")
35 #define CACHING_LONGTEXT N_( \
36     "Caching value for SDI captures. This " \
37     "value should be set in milliseconds." )
38
39 #define AUDIO_CONNECTION_TEXT N_("Audio connection")
40 #define AUDIO_CONNECTION_LONGTEXT N_( \
41     "Audio connection to use for SDI captures. " \
42     "Valid choices: embedded, aesebu, analog. " \
43     "Leave blank for card default." )
44
45 #define RATE_TEXT N_("Audio sampling rate in Hz")
46 #define RATE_LONGTEXT N_( \
47     "Audio sampling rate (in hertz) for SDI captures. " \
48     "0 disables audio input." )
49
50 #define CHANNELS_TEXT N_("Number of audio channels")
51 #define CHANNELS_LONGTEXT N_( \
52     "Number of input audio channels for SDI captures. " \
53     "Must be 2, 8 or 16. 0 disables audio input." )
54
55 #define VIDEO_CONNECTION_TEXT N_("Video connection")
56 #define VIDEO_CONNECTION_LONGTEXT N_( \
57     "Video connection to use for SDI captures. " \
58     "Valid choices: sdi, hdmi, opticalsdi, component, " \
59     "composite, svideo. " \
60     "Leave blank for card default." )
61
62 #define ASPECT_RATIO_TEXT N_("Aspect ratio")
63 #define ASPECT_RATIO_LONGTEXT N_( \
64     "Aspect ratio (4:3, 16:9). Default assumes square pixels." )
65
66 vlc_module_begin ()
67     set_shortname( N_("SDI") )
68     set_description( N_("BlackMagic SDI input") )
69     set_category( CAT_INPUT )
70     set_subcategory( SUBCAT_INPUT_ACCESS )
71     
72     add_string( "sdi-mode", "pal ", NULL,
73                  MODE_TEXT, MODE_LONGTEXT, true )
74     add_integer( "sdi-caching", DEFAULT_PTS_DELAY / 1000, NULL,
75                  CACHING_TEXT, CACHING_LONGTEXT, true )
76     add_string( "sdi-audio-connection", 0, NULL,
77                  AUDIO_CONNECTION_TEXT, AUDIO_CONNECTION_LONGTEXT, true )
78     add_integer( "sdi-audio-rate", 48000, NULL,
79                  RATE_TEXT, RATE_LONGTEXT, true )
80     add_integer( "sdi-audio-channels", 2, NULL,
81                  CHANNELS_TEXT, CHANNELS_LONGTEXT, true )
82     add_string( "sdi-video-connection", 0, NULL,
83                  VIDEO_CONNECTION_TEXT, VIDEO_CONNECTION_LONGTEXT, true )
84     add_string( "sdi-aspect-ratio", NULL, NULL,
85                 ASPECT_RATIO_TEXT, ASPECT_RATIO_LONGTEXT, true )
86
87     add_shortcut( "sdi" )
88     set_capability( "access_demux", 10 )
89     set_callbacks( Open, Close )
90 vlc_module_end ()
91
92 static int Demux  ( demux_t * );
93 static int Control( demux_t *, int, va_list );
94
95 class DeckLinkCaptureDelegate;
96
97 struct demux_sys_t
98 {
99     IDeckLink *p_card;
100     IDeckLinkInput *p_input;
101     DeckLinkCaptureDelegate *p_delegate;
102
103     es_out_id_t *p_video_es;
104     es_out_id_t *p_audio_es;
105     bool b_first_frame;
106
107     int i_width, i_height, i_fps_num, i_fps_den;
108     uint32_t i_dominance_flags;
109
110     int i_rate, i_channels;
111
112     vlc_mutex_t frame_lock;
113     block_t *p_video_frame;  // protected by <frame_lock>
114     block_t *p_audio_frame;  // protected by <frame_lock>
115     vlc_cond_t has_frame;  // related to <frame_lock>
116 };
117
118 class DeckLinkCaptureDelegate : public IDeckLinkInputCallback
119 {
120 public:
121     DeckLinkCaptureDelegate( demux_t *p_demux ) : p_demux_(p_demux) {}
122
123     // FIXME: These leak.
124     virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv) { return E_NOINTERFACE; }
125     virtual ULONG STDMETHODCALLTYPE AddRef(void) { return 1; }
126     virtual ULONG STDMETHODCALLTYPE Release(void) { return 1; }
127
128     virtual HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents, IDeckLinkDisplayMode*, BMDDetectedVideoInputFormatFlags);
129     virtual HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame*, IDeckLinkAudioInputPacket*);
130
131 private:
132     demux_t *p_demux_;
133 };
134
135 HRESULT DeckLinkCaptureDelegate::VideoInputFormatChanged(BMDVideoInputFormatChangedEvents events, IDeckLinkDisplayMode *mode, BMDDetectedVideoInputFormatFlags)
136 {
137     msg_Dbg( p_demux_, "Video input format changed" );    
138     return S_OK;
139 }
140
141 HRESULT DeckLinkCaptureDelegate::VideoInputFrameArrived(IDeckLinkVideoInputFrame* videoFrame, IDeckLinkAudioInputPacket* audioFrame)
142 {
143     demux_sys_t *p_sys = p_demux_->p_sys;
144     block_t *p_video_frame = NULL;
145     block_t *p_audio_frame = NULL;
146
147     if( videoFrame )
148     {
149         if( videoFrame->GetFlags() & bmdFrameHasNoInputSource )
150         {
151             msg_Warn( p_demux_, "No input signal detected" );
152             return S_OK;
153         }
154
155         const int i_width = videoFrame->GetWidth();
156         const int i_height = videoFrame->GetHeight();
157         const int i_stride = videoFrame->GetRowBytes();
158         const int i_bpp = 2;
159
160         p_video_frame = block_New( p_demux_, i_width * i_height * i_bpp );
161         if( !p_video_frame )
162         {
163             msg_Err( p_demux_, "Could not allocate memory for video frame" );
164             return S_OK;
165         }
166
167         void *frame_bytes;
168         videoFrame->GetBytes( &frame_bytes );
169         for( int y = 0; y < i_height; ++y )
170         {
171             const uint8_t *src = (const uint8_t *)frame_bytes + i_stride * y;
172             uint8_t *dst = (uint8_t *)p_video_frame->p_buffer + i_width * i_bpp * y;
173             memcpy( dst, src, i_width * i_bpp );
174         }
175
176         BMDTimeValue stream_time, frame_duration;
177         videoFrame->GetStreamTime( &stream_time, &frame_duration, CLOCK_FREQ );
178         p_video_frame->i_flags = BLOCK_FLAG_TYPE_I | p_sys->i_dominance_flags;
179         if( p_sys->b_first_frame )
180         {
181             p_video_frame->i_flags |= BLOCK_FLAG_DISCONTINUITY;
182             p_sys->b_first_frame = false;
183         }
184         p_video_frame->i_pts = p_video_frame->i_dts = VLC_TS_0 + stream_time;
185     }
186     
187     if( audioFrame )
188     {
189         const int i_bytes = audioFrame->GetSampleFrameCount() * sizeof(int16_t) * p_sys->i_channels;
190
191         p_audio_frame = block_New( p_demux_, i_bytes );
192         if( !p_audio_frame )
193         {
194             msg_Err( p_demux_, "Could not allocate memory for audio frame" );
195             return S_OK;
196         }
197
198         void *frame_bytes;
199         audioFrame->GetBytes( &frame_bytes );
200         memcpy( p_audio_frame->p_buffer, frame_bytes, i_bytes );
201
202         BMDTimeValue packet_time;
203         audioFrame->GetPacketTime( &packet_time, CLOCK_FREQ );
204         p_audio_frame->i_pts = p_audio_frame->i_dts = VLC_TS_0 + packet_time;
205     }
206
207     if( p_video_frame || p_audio_frame )
208     {
209         vlc_mutex_lock( &p_sys->frame_lock );
210         if( p_video_frame )
211             p_sys->p_video_frame = p_video_frame;  // FIXME: leak
212         if( p_audio_frame )
213             p_sys->p_audio_frame = p_audio_frame;  // FIXME: leak
214         vlc_cond_signal( &p_sys->has_frame );
215         vlc_mutex_unlock( &p_sys->frame_lock );
216     }
217
218     return S_OK;
219 }
220
221 static int Open( vlc_object_t *p_this )
222 {
223     demux_t     *p_demux = (demux_t*)p_this;
224     demux_sys_t *p_sys;
225
226     /* Only when selected */
227     if( *p_demux->psz_access == '\0' )
228         return VLC_EGENERIC;
229
230     /* Set up p_demux */
231     p_demux->pf_demux = Demux;
232     p_demux->pf_control = Control;
233     p_demux->info.i_update = 0;
234     p_demux->info.i_title = 0;
235     p_demux->info.i_seekpoint = 0;
236     p_demux->p_sys = p_sys = (demux_sys_t*)calloc( 1, sizeof( demux_sys_t ) );
237     if( !p_sys )
238         return VLC_ENOMEM;
239
240     vlc_mutex_init( &p_sys->frame_lock );
241     vlc_cond_init( &p_sys->has_frame );
242     p_sys->p_video_frame = NULL;
243
244     IDeckLinkIterator *decklink_iterator = CreateDeckLinkIteratorInstance();
245     if( !decklink_iterator )
246     {
247         msg_Err( p_demux, "DeckLink drivers not found." );
248         // FIXME: Leak here and several other error paths.
249         return VLC_EGENERIC;
250     }
251
252     HRESULT result;
253     result = decklink_iterator->Next( &p_sys->p_card );
254
255     if( result != S_OK )
256     {
257         msg_Err( p_demux, "No DeckLink PCI cards found" );
258         return VLC_EGENERIC;
259     }
260
261     if( p_sys->p_card->QueryInterface( IID_IDeckLinkInput, (void**)&p_sys->p_input) != S_OK )
262     {
263         msg_Err( p_demux, "Card has no inputs" );
264         return VLC_EGENERIC;
265     }
266    
267     // Set up the video and audio sources. 
268     IDeckLinkConfiguration *p_config;
269     if( p_sys->p_card->QueryInterface( IID_IDeckLinkConfiguration, (void**)&p_config) != S_OK )
270     {
271         msg_Err( p_demux, "Failed to get configuration interface" );
272         return VLC_EGENERIC;
273     }
274     
275     char *psz_tmp = var_CreateGetNonEmptyString( p_demux, "sdi-video-connection" );
276     if( psz_tmp )
277     {
278         BMDVideoConnection conn;
279         if ( !strcmp( psz_tmp, "sdi" ) )
280             conn = bmdVideoConnectionSDI;
281         else if ( !strcmp( psz_tmp, "hdmi" ) )
282             conn = bmdVideoConnectionHDMI;
283         else if ( !strcmp( psz_tmp, "opticalsdi" ) )
284             conn = bmdVideoConnectionOpticalSDI;
285         else if ( !strcmp( psz_tmp, "component" ) )
286             conn = bmdVideoConnectionComponent;
287         else if ( !strcmp( psz_tmp, "composite" ) )
288             conn = bmdVideoConnectionComposite;
289         else if ( !strcmp( psz_tmp, "svideo" ) )
290             conn = bmdVideoConnectionSVideo;
291         else
292         {
293             msg_Err( p_demux, "Invalid --sdi-video-connection specified; choose one of " \
294                               "sdi, hdmi, opticalsdi, component, composite, or svideo." );
295             return VLC_EGENERIC;
296         }
297         free( psz_tmp );
298
299         msg_Dbg( p_demux, "Setting video input format to 0x%x", conn);
300         result = p_config->SetVideoInputFormat( conn );
301         if( result != S_OK )
302         {
303             msg_Err( p_demux, "Failed to set video input connection" );
304             return VLC_EGENERIC;
305         }
306     } 
307
308     psz_tmp = var_CreateGetNonEmptyString( p_demux, "sdi-audio-connection" );
309     if( psz_tmp )
310     {
311         BMDAudioConnection conn;
312         if ( !strcmp( psz_tmp, "embedded" ) )
313             conn = bmdAudioConnectionEmbedded;
314         else if ( !strcmp( psz_tmp, "aesebu" ) )
315             conn = bmdAudioConnectionAESEBU;
316         else if ( !strcmp( psz_tmp, "analog" ) )
317             conn = bmdAudioConnectionAnalog;
318         else
319         {
320             msg_Err( p_demux, "Invalid --sdi-audio-connection specified; choose one of " \
321                               "embedded, aesebu, or analog." );
322             return VLC_EGENERIC;
323         }
324         free( psz_tmp );
325
326         msg_Dbg( p_demux, "Setting audio input format to 0x%x", conn);
327         result = p_config->SetAudioInputFormat( conn );
328         if( result != S_OK )
329         {
330             msg_Err( p_demux, "Failed to set audio input connection" );
331             return VLC_EGENERIC;
332         }
333     } 
334
335     // Get the list of display modes.
336     IDeckLinkDisplayModeIterator *p_display_iterator;
337     result = p_sys->p_input->GetDisplayModeIterator( &p_display_iterator );
338     if( result != S_OK )
339     {
340         msg_Err( p_demux, "Failed to enumerate display modes" );
341         return VLC_EGENERIC;
342     }
343     
344     char *mode_string = var_CreateGetString( p_demux, "sdi-mode" );
345     if( !mode_string || strlen( mode_string ) == 0 || strlen( mode_string ) > 4 ) {
346         msg_Err( p_demux, "Missing or invalid --sdi-mode string" );
347         return VLC_EGENERIC;
348     }
349
350     // Pad the --sdi-mode string to four characters, so the user can specify e.g. "pal"
351     // without having to add the trailing space.
352     char mode_string_padded[5];
353     strcpy(mode_string_padded, "    ");
354     for( int i = 0; i < strlen(mode_string); ++i )
355         mode_string_padded[i] = mode_string[i];
356
357     BMDDisplayMode wanted_mode_id;
358     memcpy( &wanted_mode_id, &mode_string_padded, sizeof(wanted_mode_id) );
359     
360     bool b_found_mode = false;
361
362     for (;;)
363     {
364         IDeckLinkDisplayMode *p_display_mode;
365         result = p_display_iterator->Next( &p_display_mode );
366         if( result != S_OK || !p_display_mode )
367         {
368             break; 
369         }
370
371         char mode_id_text[5] = {0};
372         BMDDisplayMode mode_id = ntohl( p_display_mode->GetDisplayMode() );
373         memcpy( mode_id_text, &mode_id, sizeof(mode_id) );
374
375         const char *mode_name;
376         result = p_display_mode->GetName( &mode_name );
377         if( result != S_OK )
378         {
379             msg_Err( p_demux, "Failed to get display mode name" );
380             return VLC_EGENERIC;
381         }
382
383         BMDTimeValue frame_duration, time_scale;
384         result = p_display_mode->GetFrameRate( &frame_duration, &time_scale );
385         if( result != S_OK )
386         {
387             msg_Err( p_demux, "Failed to get frame rate" );
388             return VLC_EGENERIC;
389         }
390
391         const char *field_dominance;
392         uint32_t i_dominance_flags = 0;
393         switch( p_display_mode->GetFieldDominance() )
394         {
395         case bmdProgressiveFrame:
396             field_dominance = "";
397             break;
398         case bmdProgressiveSegmentedFrame:
399             field_dominance = ", segmented";
400             break;
401         case bmdLowerFieldFirst:
402             field_dominance = ", interlaced [BFF]";
403             i_dominance_flags = BLOCK_FLAG_BOTTOM_FIELD_FIRST;
404             break;
405         case bmdUpperFieldFirst:
406             field_dominance = ", interlaced [TFF]";
407             i_dominance_flags = BLOCK_FLAG_TOP_FIELD_FIRST;
408             break;
409         case bmdUnknownFieldDominance:
410         default:
411             field_dominance = ", unknown field dominance";
412             break;
413         }
414
415         msg_Dbg( p_demux, "Found mode '%s': %s (%dx%d, %.3f fps%s)",
416                  mode_id_text, mode_name,
417                  p_display_mode->GetWidth(), p_display_mode->GetHeight(),
418                  double(time_scale) / frame_duration, field_dominance );
419
420         if( wanted_mode_id == mode_id )
421         {
422             b_found_mode = true;
423             p_sys->i_width = p_display_mode->GetWidth();
424             p_sys->i_height = p_display_mode->GetHeight();
425             p_sys->i_fps_num = time_scale;
426             p_sys->i_fps_den = frame_duration;
427             p_sys->i_dominance_flags = i_dominance_flags;
428         }
429     }
430
431     if( !b_found_mode )
432     {
433         msg_Err( p_demux, "Unknown SDI mode specified. " \
434                           "Run VLC with -v --verbose-objects=-all,+sdi " \
435                           "to get a list of supported modes." );
436         return VLC_EGENERIC;
437     }
438
439     result = p_sys->p_input->EnableVideoInput( htonl( wanted_mode_id ), bmdFormat8BitYUV, 0 );
440     if( result != S_OK )
441     {
442         msg_Err( p_demux, "Failed to enable video input" );
443         return VLC_EGENERIC;
444     }
445   
446     // Set up audio. 
447     p_sys->i_rate = var_CreateGetInteger( p_demux, "sdi-audio-rate" );
448     p_sys->i_channels = var_CreateGetInteger( p_demux, "sdi-audio-channels" );
449     if( p_sys->i_rate > 0 && p_sys->i_channels > 0 )
450     {
451         result = p_sys->p_input->EnableAudioInput( p_sys->i_rate, bmdAudioSampleType16bitInteger, p_sys->i_channels );
452         if( result != S_OK )
453         {
454             msg_Err( p_demux, "Failed to enable audio input" );
455             return VLC_EGENERIC;
456         }
457     }
458  
459     p_sys->p_delegate = new DeckLinkCaptureDelegate( p_demux );
460     p_sys->p_input->SetCallback( p_sys->p_delegate );
461
462     result = p_sys->p_input->StartStreams();
463     if( result != S_OK )
464     {
465         msg_Err( p_demux, "Failed to start streams" );
466         return VLC_EGENERIC;
467     }
468
469     /* Declare elementary streams */
470     es_format_t video_fmt;
471     es_format_Init( &video_fmt, VIDEO_ES, VLC_CODEC_UYVY );
472     video_fmt.video.i_width = p_sys->i_width;
473     video_fmt.video.i_height = p_sys->i_height;
474     video_fmt.video.i_sar_num = 1;
475     video_fmt.video.i_sar_den = 1;
476     video_fmt.video.i_frame_rate = p_sys->i_fps_num;
477     video_fmt.video.i_frame_rate_base = p_sys->i_fps_den;
478     video_fmt.i_bitrate = video_fmt.video.i_width * video_fmt.video.i_height * video_fmt.video.i_frame_rate * 2;
479     
480     psz_tmp = var_CreateGetNonEmptyString( p_demux, "sdi-aspect-ratio" );
481     if( psz_tmp )
482     {
483         char *psz_denominator = strchr( psz_tmp, ':' );
484         if( psz_denominator )
485         {
486             *psz_denominator++ = '\0';
487             video_fmt.video.i_sar_num = atoi( psz_tmp )         * video_fmt.video.i_height;
488             video_fmt.video.i_sar_den = atoi( psz_denominator ) * video_fmt.video.i_width;
489         }
490         free( psz_tmp );
491     }
492
493     msg_Dbg( p_demux, "added new video es %4.4s %dx%d",
494              (char*)&video_fmt.i_codec, video_fmt.video.i_width, video_fmt.video.i_height );
495     p_sys->p_video_es = es_out_Add( p_demux->out, &video_fmt );
496     
497     es_format_t audio_fmt;
498     es_format_Init( &audio_fmt, AUDIO_ES, VLC_CODEC_S16N );
499     audio_fmt.audio.i_channels = p_sys->i_channels;
500     audio_fmt.audio.i_rate = p_sys->i_rate;
501     audio_fmt.audio.i_bitspersample = 16;
502     audio_fmt.audio.i_blockalign = audio_fmt.audio.i_channels * audio_fmt.audio.i_bitspersample / 8;
503     audio_fmt.i_bitrate = audio_fmt.audio.i_channels * audio_fmt.audio.i_rate * audio_fmt.audio.i_bitspersample;
504
505     msg_Dbg( p_demux, "added new audio es %4.4s %dHz %dbpp %dch",
506              (char*)&audio_fmt.i_codec, audio_fmt.audio.i_rate, audio_fmt.audio.i_bitspersample, audio_fmt.audio.i_channels);
507     p_sys->p_audio_es = es_out_Add( p_demux->out, &audio_fmt );
508
509     p_sys->b_first_frame = true;
510
511     /* Update default_pts to a suitable value for access */
512     var_Create( p_demux, "sdi-caching", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
513
514     return VLC_SUCCESS;
515 }
516
517 static void Close( vlc_object_t *p_this )
518 {
519     demux_t     *p_demux = (demux_t *)p_this;
520     demux_sys_t *p_sys   = p_demux->p_sys;
521
522     free( p_sys );
523 }
524
525 static int Control( demux_t *p_demux, int i_query, va_list args )
526 {
527     bool *pb;
528     int64_t    *pi64;
529
530     switch( i_query )
531     {
532         /* Special for access_demux */
533         case DEMUX_CAN_PAUSE:
534         case DEMUX_CAN_SEEK:
535         case DEMUX_CAN_CONTROL_PACE:
536             pb = (bool*)va_arg( args, bool * );
537             *pb = false;
538             return VLC_SUCCESS;
539
540         case DEMUX_GET_PTS_DELAY:
541             pi64 = (int64_t*)va_arg( args, int64_t * );
542             *pi64 = var_GetInteger( p_demux, "sdi-caching" ) * 1000;
543             return VLC_SUCCESS;
544
545         case DEMUX_GET_TIME:
546             pi64 = (int64_t*)va_arg( args, int64_t * );
547             *pi64 = mdate();  // FIXME
548             return VLC_SUCCESS;
549
550         /* TODO implement others */
551         default:
552             return VLC_EGENERIC;
553     }
554
555     return VLC_EGENERIC;
556 }
557
558 static int Demux( demux_t *p_demux )
559 {
560     demux_sys_t *p_sys = p_demux->p_sys;
561     block_t *p_video_block = NULL;
562     block_t *p_audio_block = NULL;
563
564     vlc_mutex_lock( &p_sys->frame_lock );
565
566     while( !p_sys->p_video_frame && !p_sys->p_audio_frame )
567         vlc_cond_wait( &p_sys->has_frame, &p_sys->frame_lock );
568
569     p_video_block = p_sys->p_video_frame;
570     p_sys->p_video_frame = NULL;
571
572     p_audio_block = p_sys->p_audio_frame;
573     p_sys->p_audio_frame = NULL;
574
575     vlc_mutex_unlock( &p_sys->frame_lock );
576
577     if( p_video_block )
578     {
579         es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_video_block->i_pts );
580         es_out_Send( p_demux->out, p_sys->p_video_es, p_video_block );
581     }
582     
583     if( p_audio_block )
584     {
585         es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_audio_block->i_pts );
586         es_out_Send( p_demux->out, p_sys->p_audio_es, p_audio_block );
587     }
588
589     return 1;
590 }
591