access: add rfb/vnc viewonly module.
[vlc.git] / modules / access / vnc.c
1 /*****************************************************************************
2  * vnc.c: libVNC access
3  *****************************************************************************
4  * Copyright (C) 2013 VideoLAN Authors
5  *****************************************************************************
6  *
7  * This program is free software; you can redistribute it and/or modify it
8  * under the terms of the GNU Lesser General Public License as published by
9  * the Free Software Foundation; either version 2.1 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public License
18  * along with this program; if not, write to the Free Software Foundation,
19  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
20  *****************************************************************************/
21
22 /*****************************************************************************
23  * Preamble
24  *****************************************************************************/
25
26 #ifdef HAVE_CONFIG_H
27 # include "config.h"
28 #endif
29
30 #include <vlc_common.h>
31 #include <vlc_plugin.h>
32 #include <vlc_demux.h>
33 #include <vlc_url.h>
34 #include <vlc_meta.h>
35 #include <vlc_fourcc.h>
36
37 #include <rfb/rfbclient.h>
38
39 #define RFB_USER N_("Username")
40 #define RFB_PASSWORD N_("Password")
41 #define RFB_CA_TEXT N_("X.509 Certificate Authority")
42 #define RFB_CA_LONGTEXT N_("Certificate of the Authority to verify server's against")
43 #define RFB_CRL_TEXT N_("X.509 Certificate Revocation List")
44 #define RFB_CRL_LONGTEXT N_("List of revoked servers certificates")
45 #define RFB_CERT_TEXT N_("X.509 Client certificate")
46 #define RFB_CERT_LONGTEXT N_("Certificate for client authentification")
47 #define RFB_KEY_TEXT N_("X.509 Client private key")
48 #define RFB_KEY_LONGTEXT N_("Private key for authentification by certificate")
49
50 #define RFB_CHROMA N_("Frame buffer depth")
51 #define RFB_CHROMA_LONGTEXT N_("RGB chroma (RV32, RV24, RV16, RGB2)")
52 #define RFB_FPS N_("Frame rate")
53 #define RFB_FPS_LONGTEXT N_("How many times the screen content should be refreshed per second.")
54 #define RFB_COMPRESS N_("Compression level")
55 #define RFB_COMPRESS_LONGTEXT N_("Transfert compression level from 0 (none) to 9 (max)")
56 #define RFB_QUALITY N_("Image quality")
57 #define RFB_QUALITY_LONGTEXT N_("Image quality 1 to 9 (max)")
58
59 #define CFG_PREFIX "rfb-"
60
61 const char *const rgb_chromas[] = { N_("32 bits"), N_("24 bits"), N_("16 bits"), N_("8 bits") };
62 const char *const rgb_chromas_v[] = { "RV32", "RV24", "RV16", "RGB8" };
63
64 /*****************************************************************************
65  * Module descriptor
66  *****************************************************************************/
67 static int  Open ( vlc_object_t * );
68 static void Close( vlc_object_t * );
69
70 vlc_module_begin()
71     set_shortname( N_("VNC") )
72     add_shortcut( "vnc" )
73     set_category( CAT_INPUT )
74     set_subcategory( SUBCAT_INPUT_ACCESS )
75     set_description( N_("VNC client access") )
76     set_capability( "access_demux", 0 )
77
78     add_string( CFG_PREFIX "user", NULL, RFB_USER, RFB_USER, false )
79         change_safe()
80     add_password( CFG_PREFIX "password", NULL, RFB_PASSWORD, RFB_PASSWORD, false )
81         change_safe()
82     add_loadfile( CFG_PREFIX "x509-ca", NULL, RFB_CA_TEXT, RFB_CA_LONGTEXT, true )
83         change_safe()
84     add_loadfile( CFG_PREFIX "x509-crl", NULL, RFB_CRL_TEXT, RFB_CRL_LONGTEXT, true )
85         change_safe()
86     add_loadfile( CFG_PREFIX "x509-client-cert", NULL, RFB_CERT_TEXT, RFB_CERT_LONGTEXT, true )
87         change_safe()
88     add_loadfile( CFG_PREFIX "x509-client-key", NULL, RFB_KEY_TEXT, RFB_KEY_LONGTEXT, true )
89         change_safe()
90
91     add_float( CFG_PREFIX "fps", 5, RFB_FPS, RFB_FPS_LONGTEXT, true )
92     add_string( CFG_PREFIX "chroma", rgb_chromas_v[0], RFB_CHROMA, RFB_CHROMA_LONGTEXT, false )
93         change_string_list (rgb_chromas_v, rgb_chromas)
94         change_safe()
95     add_integer( CFG_PREFIX "compress-level", 0, RFB_COMPRESS, RFB_COMPRESS_LONGTEXT, true )
96         change_integer_range (0, 9)
97         change_safe()
98     add_integer( CFG_PREFIX "quality-level", 9, RFB_QUALITY, RFB_QUALITY_LONGTEXT, true )
99         change_integer_range (1, 9)
100         change_safe()
101
102     set_callbacks( Open, Close )
103 vlc_module_end()
104
105 struct demux_sys_t
106 {
107     vlc_thread_t thread;
108     int i_cancel_state;
109
110     rfbClient* p_client;
111     int i_framebuffersize;
112     block_t *p_block;
113
114     float f_fps;
115     int i_frame_interval;
116     mtime_t i_starttime;
117
118     es_out_id_t *es;
119 };
120
121 static void *DemuxThread( void *p_data );
122
123 /*****************************************************************************
124  * Local prototypes
125  *****************************************************************************/
126
127 static rfbBool mallocFrameBufferHandler( rfbClient* p_client )
128 {
129     vlc_fourcc_t i_chroma;
130     demux_t *p_demux = (demux_t *) rfbClientGetClientData( p_client, DemuxThread );
131     demux_sys_t *p_sys = p_demux->p_sys;
132
133     if ( p_sys->es ) /* Source has changed resolution */
134     {
135         es_out_Del( p_demux->out, p_sys->es );
136         p_sys->es = NULL;
137     }
138
139     int i_width = p_client->width;
140     int i_height = p_client->height;
141     int i_depth = p_client->format.bitsPerPixel;
142
143     switch( i_depth )
144     {
145         case 8:
146             i_chroma = VLC_CODEC_RGB8;
147             break;
148         default:
149         case 16:
150             i_chroma = VLC_CODEC_RGB16;
151             break;
152         case 24:
153             i_chroma = VLC_CODEC_RGB24;
154             break;
155         case 32:
156             i_chroma = VLC_CODEC_RGB32;
157             break;
158     }
159
160     if ( i_chroma != VLC_CODEC_RGB8 ) /* Palette based, no mask */
161     {
162         video_format_t videofmt;
163         memset( &videofmt, 0, sizeof(video_format_t) );
164         videofmt.i_chroma = i_chroma;
165         video_format_FixRgb( &videofmt );
166
167         p_client->format.redShift = videofmt.i_lrshift;
168         p_client->format.greenShift = videofmt.i_lgshift;
169         p_client->format.blueShift = videofmt.i_lbshift;
170         p_client->format.redMax = videofmt.i_rmask >> videofmt.i_lrshift;
171         p_client->format.greenMax = videofmt.i_gmask >> videofmt.i_lgshift;
172         p_client->format.blueMax = videofmt.i_bmask >> videofmt.i_lbshift;
173     }
174
175     /* Set up framebuffer */
176     p_sys->i_framebuffersize = i_width * i_height * i_depth / 8;
177
178     /* Reuse unsent block */
179     if ( p_sys->p_block )
180         p_sys->p_block = block_Realloc( p_sys->p_block, 0, p_sys->i_framebuffersize );
181     else
182         p_sys->p_block = block_Alloc( p_sys->i_framebuffersize );
183
184     if ( p_sys->p_block )
185         p_sys->p_block->i_buffer = p_sys->i_framebuffersize;
186     else
187         return FALSE;
188
189     /* Push our VNC config */
190     SetFormatAndEncodings( p_client );
191
192     /* Now init and fill es format */
193     es_format_t fmt;
194     es_format_Init( &fmt, VIDEO_ES, i_chroma );
195
196     /* Fill input format */
197     fmt.video.i_chroma = i_chroma;
198     fmt.video.i_visible_width =
199             fmt.video.i_width = i_width;
200
201     fmt.video.i_visible_height =
202             fmt.video.i_height = i_height;
203
204     fmt.video.i_frame_rate_base = 1000;
205     fmt.video.i_frame_rate = 1000 * p_sys->f_fps;
206
207     fmt.video.i_bits_per_pixel = i_depth;
208     fmt.video.i_rmask = p_client->format.redMax << p_client->format.redShift;
209     fmt.video.i_gmask = p_client->format.greenMax << p_client->format.greenShift;
210     fmt.video.i_bmask = p_client->format.blueMax << p_client->format.blueShift;
211
212     fmt.video.i_sar_num = fmt.video.i_sar_den = 1;
213
214     /* declare the new es */
215     p_sys->es = es_out_Add( p_demux->out, &fmt );
216
217     return TRUE;
218 }
219
220 /* Auth */
221 static char *getPasswordHandler( rfbClient *p_client )
222 {
223     demux_t *p_demux = (demux_t *) rfbClientGetClientData( p_client, DemuxThread );
224     /* freed by libvnc */
225     return var_InheritString( p_demux, CFG_PREFIX "password" );
226 }
227
228 static rfbCredential* getCredentialHandler( rfbClient *p_client, int i_credentialType )
229 {
230     demux_t *p_demux = (demux_t *) rfbClientGetClientData( p_client, DemuxThread );
231
232     rfbCredential *credential = calloc( 1, sizeof(rfbCredential) );
233     if ( !credential ) return NULL;
234
235     switch( i_credentialType )
236     {
237         case rfbCredentialTypeX509:
238             /* X509None, X509Vnc, X509Plain */
239             credential->x509Credential.x509CACertFile =
240                     var_InheritString( p_demux, CFG_PREFIX "x509-ca" );
241             credential->x509Credential.x509CACrlFile =
242                     var_InheritString( p_demux, CFG_PREFIX "x509-crl" );
243             /* client auth by certificate */
244             credential->x509Credential.x509ClientCertFile =
245                     var_InheritString( p_demux, CFG_PREFIX "x509-client-cert" );
246             credential->x509Credential.x509ClientKeyFile =
247                     var_InheritString( p_demux, CFG_PREFIX "x509-client-key" );
248             break;
249
250         case rfbCredentialTypeUser:
251             credential->userCredential.username =
252                     var_InheritString( p_demux, CFG_PREFIX "user" );
253             credential->userCredential.password =
254                     var_InheritString( p_demux, CFG_PREFIX "password" );
255             break;
256
257         default:
258             free( credential );
259             return NULL; /* Unsupported Auth */
260     }
261     /* freed by libvnc */
262     return credential;
263 }
264
265 /*****************************************************************************
266  * Control:
267  *****************************************************************************/
268 static int Control( demux_t *p_demux, int i_query, va_list args )
269 {
270     bool *pb;
271     int64_t *pi64;
272     double *p_dbl;
273     vlc_meta_t *p_meta;
274
275     switch( i_query )
276     {
277         case DEMUX_CAN_PAUSE:
278         case DEMUX_CAN_SEEK:
279         case DEMUX_CAN_CONTROL_PACE:
280         case DEMUX_CAN_CONTROL_RATE:
281         case DEMUX_HAS_UNSUPPORTED_META:
282             pb = (bool*)va_arg( args, bool * );
283             *pb = false;
284             return VLC_SUCCESS;
285
286         case DEMUX_CAN_RECORD:
287             pb = (bool*)va_arg( args, bool * );
288             *pb = true;
289             return VLC_SUCCESS;
290
291         case DEMUX_GET_PTS_DELAY:
292             pi64 = (int64_t*)va_arg( args, int64_t * );
293             *pi64 = INT64_C(1000)
294                   * var_InheritInteger( p_demux, "network-caching" );
295             return VLC_SUCCESS;
296
297         case DEMUX_GET_TIME:
298             pi64 = (int64_t*)va_arg( args, int64_t * );
299             *pi64 = mdate() - p_demux->p_sys->i_starttime;
300             return VLC_SUCCESS;
301
302         case DEMUX_GET_LENGTH:
303             pi64 = (int64_t*)va_arg( args, int64_t * );
304             *pi64 = 0;
305             return VLC_SUCCESS;
306
307         case DEMUX_GET_FPS:
308             p_dbl = (double*)va_arg( args, double * );
309             *p_dbl = p_demux->p_sys->f_fps;
310             return VLC_SUCCESS;
311
312         case DEMUX_GET_META:
313             p_meta = (vlc_meta_t*)va_arg( args, vlc_meta_t* );
314             vlc_meta_Set( p_meta, vlc_meta_Title, p_demux->psz_location );
315             return VLC_SUCCESS;
316
317         default:
318             return VLC_EGENERIC;
319     }
320 }
321
322 /*****************************************************************************
323  * Demux:
324  *****************************************************************************/
325
326 static void *DemuxThread( void *p_data )
327 {
328     demux_t *p_demux = (demux_t *) p_data;
329     demux_sys_t  *p_sys = p_demux->p_sys;
330     mtime_t i_next_frame_date = mdate() + p_sys->i_frame_interval;
331     int i_status;
332
333     for(;;)
334     {
335         p_sys->i_cancel_state = vlc_savecancel();
336         i_status = WaitForMessage( p_sys->p_client, p_sys->i_frame_interval );
337         vlc_restorecancel( p_sys->i_cancel_state );
338
339         /* Ensure we're not building frames too fast */
340         /* as WaitForMessage takes only a maximum wait */
341         mwait( i_next_frame_date );
342         i_next_frame_date += p_sys->i_frame_interval;
343
344         if ( i_status > 0 )
345         {
346             p_sys->p_client->frameBuffer = p_sys->p_block->p_buffer;
347             p_sys->i_cancel_state = vlc_savecancel();
348             i_status = HandleRFBServerMessage( p_sys->p_client );
349             vlc_restorecancel( p_sys->i_cancel_state );
350             if ( ! i_status )
351             {
352                 msg_Warn( p_demux, "Cannot get announced data. Server closed ?" );
353                 es_out_Del( p_demux->out, p_sys->es );
354                 p_sys->es = NULL;
355                 return NULL;
356             }
357             else
358             {
359                 block_t *p_block = block_Duplicate( p_sys->p_block );
360                 if ( p_block ) /* drop frame/content if no next block */
361                 {
362                     p_sys->p_block->i_dts = p_sys->p_block->i_pts = mdate();
363                     es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->p_block->i_pts );
364                     es_out_Send( p_demux->out, p_sys->es, p_sys->p_block );
365                     p_sys->p_block = p_block;
366                 }
367             }
368         }
369     }
370     return NULL;
371 }
372
373 /*****************************************************************************
374  * Open:
375  *****************************************************************************/
376 static int Open( vlc_object_t *p_this )
377 {
378     demux_t      *p_demux = (demux_t*)p_this;
379     demux_sys_t  *p_sys;
380
381     p_sys = calloc( 1, sizeof(demux_sys_t) );
382     if( !p_sys ) return VLC_ENOMEM;
383
384     p_sys->f_fps = var_InheritFloat( p_demux, CFG_PREFIX "fps" );
385     if ( p_sys->f_fps <= 0 ) p_sys->f_fps = 1.0;
386     p_sys->i_frame_interval = 1000000 / p_sys->f_fps ;
387
388     char *psz_chroma = var_InheritString( p_demux, CFG_PREFIX "chroma" );
389     vlc_fourcc_t i_chroma = vlc_fourcc_GetCodecFromString( VIDEO_ES, psz_chroma );
390     free( psz_chroma );
391     if ( !i_chroma || vlc_fourcc_IsYUV( i_chroma ) )
392     {
393         msg_Err( p_demux, "Only RGB chroma are supported" );
394         free( p_sys );
395         return VLC_EGENERIC;
396     }
397
398     const vlc_chroma_description_t *p_chroma_desc = vlc_fourcc_GetChromaDescription( i_chroma );
399     if ( !p_chroma_desc )
400     {
401         msg_Err( p_demux, "Unable to get RGB chroma description" );
402         free( p_sys );
403         return VLC_EGENERIC;
404     }
405
406 #ifdef NDEBUG
407     rfbEnableClientLogging = FALSE;
408 #endif
409
410     p_sys->p_client = rfbGetClient( p_chroma_desc->pixel_bits / 3, // bitsPerSample
411                                     3, // samplesPerPixel
412                                     p_chroma_desc->pixel_size ); // bytesPerPixel
413     if ( ! p_sys->p_client )
414     {
415         msg_Dbg( p_demux, "Unable to set up client for %s",
416                  vlc_fourcc_GetDescription( VIDEO_ES, i_chroma ) );
417         free( p_sys );
418         return VLC_EGENERIC;
419     }
420
421     msg_Dbg( p_demux, "set up client for %s %d %d %d",
422              vlc_fourcc_GetDescription( VIDEO_ES, i_chroma ),
423              p_chroma_desc->pixel_bits / 3, 3, p_chroma_desc->pixel_size );
424
425     p_sys->p_client->MallocFrameBuffer = mallocFrameBufferHandler;
426     p_sys->p_client->canHandleNewFBSize = TRUE;
427     p_sys->p_client->GetCredential = getCredentialHandler;
428     p_sys->p_client->GetPassword = getPasswordHandler; /* VNC simple auth */
429
430     /* Set compression and quality levels */
431     p_sys->p_client->appData.compressLevel =
432             var_InheritInteger( p_demux, CFG_PREFIX "compress-level" );
433     p_sys->p_client->appData.qualityLevel =
434             var_InheritInteger( p_demux, CFG_PREFIX "quality-level" );
435
436     /* Parse uri params */
437     vlc_url_t url;
438     vlc_UrlParse( &url, p_demux->psz_location, 0 );
439
440     if ( !EMPTY_STR(url.psz_host) )
441         p_sys->p_client->serverHost = strdup( url.psz_host );
442     else
443         p_sys->p_client->serverHost = strdup( "localhost" );
444
445     p_sys->p_client->appData.viewOnly = TRUE;
446     p_sys->p_client->serverPort = ( url.i_port > 0 ) ? url.i_port : 5900;
447
448     msg_Dbg( p_demux, "VNC init %s host=%s pass=%s port=%d",
449              p_demux->psz_location,
450              p_sys->p_client->serverHost,
451              url.psz_password,
452              p_sys->p_client->serverPort );
453
454     vlc_UrlClean( &url );
455
456     /* make demux available for callback handlers */
457     rfbClientSetClientData( p_sys->p_client, DemuxThread, p_demux );
458     p_demux->p_sys = p_sys;
459
460     if( !rfbInitClient( p_sys->p_client, NULL, NULL ) )
461     {
462         msg_Err( p_demux, "can't connect to RFB server" );
463         goto error;
464     }
465
466     p_sys->i_starttime = mdate();
467
468     if ( vlc_clone( &p_sys->thread, DemuxThread, p_demux, VLC_THREAD_PRIORITY_INPUT ) != VLC_SUCCESS )
469     {
470         msg_Err( p_demux, "can't spawn thread" );
471         goto error;
472     }
473
474     p_demux->pf_demux = NULL;
475     p_demux->pf_control = Control;
476
477     return VLC_SUCCESS;
478
479 error:
480     free( p_sys );
481     return VLC_EGENERIC;
482 }
483
484 /*****************************************************************************
485  * Close:
486  *****************************************************************************/
487 static void Close( vlc_object_t *p_this )
488 {
489     demux_t     *p_demux = (demux_t*)p_this;
490     demux_sys_t *p_sys = p_demux->p_sys;
491
492     vlc_cancel( p_sys->thread );
493     vlc_join( p_sys->thread, NULL );
494
495     if ( p_sys->es )
496         es_out_Del( p_demux->out, p_sys->es );
497
498     rfbClientCleanup( p_sys->p_client );
499
500     if ( p_sys->p_block )
501         block_Release( p_sys->p_block );
502
503     free( p_sys );
504 }