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