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