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