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