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