]> git.sesse.net Git - vlc/blob - src/win32/specific.c
Win32 R/W locks: fix/add comments, add asserts
[vlc] / src / win32 / specific.c
1 /*****************************************************************************
2  * specific.c: Win32 specific initilization
3  *****************************************************************************
4  * Copyright (C) 2001-2004, 2010 the VideoLAN team
5  *
6  * Authors: Samuel Hocevar <sam@zoy.org>
7  *          Gildas Bazin <gbazin@videolan.org>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 #ifdef HAVE_CONFIG_H
25 # include "config.h"
26 #endif
27
28 #define UNICODE
29 #include <vlc_common.h>
30 #include "../libvlc.h"
31 #include <vlc_playlist.h>
32 #include <vlc_url.h>
33
34 #include "../config/vlc_getopt.h"
35
36 #if !defined( UNDER_CE )
37 #   include <io.h>
38 #   include <fcntl.h>
39 #   include  <mmsystem.h>
40 #endif
41
42 #include <winsock.h>
43
44 /*****************************************************************************
45  * system_Init: initialize winsock and misc other things.
46  *****************************************************************************/
47 void system_Init( libvlc_int_t *p_this, int *pi_argc, const char *ppsz_argv[] )
48 {
49     VLC_UNUSED( p_this ); VLC_UNUSED( pi_argc ); VLC_UNUSED( ppsz_argv );
50     WSADATA Data;
51     MEMORY_BASIC_INFORMATION mbi;
52
53     /* Get our full path */
54     char psz_path[MAX_PATH];
55     char *psz_vlc;
56
57     wchar_t psz_wpath[MAX_PATH];
58     if( VirtualQuery(system_Init, &mbi, sizeof(mbi) ) )
59     {
60         HMODULE hMod = (HMODULE) mbi.AllocationBase;
61         if( GetModuleFileName( hMod, psz_wpath, MAX_PATH ) )
62         {
63             WideCharToMultiByte( CP_UTF8, 0, psz_wpath, -1,
64                                 psz_path, MAX_PATH, NULL, NULL );
65         }
66         else psz_path[0] = '\0';
67     }
68     else psz_path[0] = '\0';
69
70     psz_vlc = strrchr( psz_path, '\\' );
71     if( psz_vlc )
72         *psz_vlc = '\0';
73
74     {
75         /* remove trailing \.libs from executable dir path if seen,
76            we assume we are running vlc through libtool wrapper in build dir */
77         size_t len = strlen(psz_path);
78         if( len >= 5 && !stricmp(psz_path + len - 5, "\\.libs" ) )
79             psz_path[len - 5] = '\0';
80     }
81
82     psz_vlcpath = strdup( psz_path );
83
84     /* Set the default file-translation mode */
85 #if !defined( UNDER_CE )
86     _fmode = _O_BINARY;
87     _setmode( _fileno( stdin ), _O_BINARY ); /* Needed for pipes */
88
89     timeBeginPeriod(5);
90 #endif
91
92     /* Call mdate() once to make sure it is initialized properly */
93     mdate();
94
95     /* WinSock Library Init. */
96     if( !WSAStartup( MAKEWORD( 2, 2 ), &Data ) )
97     {
98         /* Aah, pretty useless check, we should always have Winsock 2.2
99          * since it appeared in Win98. */
100         if( LOBYTE( Data.wVersion ) != 2 || HIBYTE( Data.wVersion ) != 2 )
101             /* We could not find a suitable WinSock DLL. */
102             WSACleanup( );
103         else
104             /* Everything went ok. */
105             return;
106     }
107
108     /* Let's try with WinSock 1.1 */
109     if( !WSAStartup( MAKEWORD( 1, 1 ), &Data ) )
110     {
111         /* Confirm that the WinSock DLL supports 1.1.*/
112         if( LOBYTE( Data.wVersion ) != 1 || HIBYTE( Data.wVersion ) != 1 )
113             /* We could not find a suitable WinSock DLL. */
114             WSACleanup( );
115         else
116             /* Everything went ok. */
117             return;
118     }
119
120     fprintf( stderr, "error: can't initialize WinSocks\n" );
121 }
122
123 /*****************************************************************************
124  * system_Configure: check for system specific configuration options.
125  *****************************************************************************/
126 static unsigned __stdcall IPCHelperThread( void * );
127 LRESULT CALLBACK WMCOPYWNDPROC( HWND, UINT, WPARAM, LPARAM );
128 static vlc_object_t *p_helper = NULL;
129 static unsigned long hIPCHelper;
130 static HANDLE hIPCHelperReady;
131
132 typedef struct
133 {
134   int argc;
135   int enqueue;
136   char data[];
137 } vlc_ipc_data_t;
138
139 void system_Configure( libvlc_int_t *p_this, int i_argc, const char *const ppsz_argv[] )
140 {
141 #if !defined( UNDER_CE )
142     /* Raise default priority of the current process */
143 #ifndef ABOVE_NORMAL_PRIORITY_CLASS
144 #   define ABOVE_NORMAL_PRIORITY_CLASS 0x00008000
145 #endif
146     if( var_InheritBool( p_this, "high-priority" ) )
147     {
148         if( SetPriorityClass( GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS )
149              || SetPriorityClass( GetCurrentProcess(), HIGH_PRIORITY_CLASS ) )
150         {
151             msg_Dbg( p_this, "raised process priority" );
152         }
153         else
154         {
155             msg_Dbg( p_this, "could not raise process priority" );
156         }
157     }
158
159     if( var_InheritBool( p_this, "one-instance" )
160      || ( var_InheritBool( p_this, "one-instance-when-started-from-file" )
161        && var_InheritBool( p_this, "started-from-file" ) ) )
162     {
163         HANDLE hmutex;
164
165         msg_Info( p_this, "one instance mode ENABLED");
166
167         /* Use a named mutex to check if another instance is already running */
168         if( !( hmutex = CreateMutex( 0, TRUE, L"VLC ipc "VERSION ) ) )
169         {
170             /* Failed for some reason. Just ignore the option and go on as
171              * normal. */
172             msg_Err( p_this, "one instance mode DISABLED "
173                      "(mutex couldn't be created)" );
174             return;
175         }
176
177         if( GetLastError() != ERROR_ALREADY_EXISTS )
178         {
179             /* We are the 1st instance. */
180             static const char typename[] = "ipc helper";
181             p_helper =
182                 vlc_custom_create( p_this, sizeof(vlc_object_t),
183                                    VLC_OBJECT_GENERIC, typename );
184
185             /* Run the helper thread */
186             hIPCHelperReady = CreateEvent( NULL, FALSE, FALSE, NULL );
187             hIPCHelper = _beginthreadex( NULL, 0, IPCHelperThread, p_helper,
188                                          0, NULL );
189             if( hIPCHelper )
190                 WaitForSingleObject( hIPCHelperReady, INFINITE );
191             else
192             {
193                 msg_Err( p_this, "one instance mode DISABLED "
194                          "(IPC helper thread couldn't be created)" );
195                 vlc_object_release (p_helper);
196                 p_helper = NULL;
197             }
198             vlc_object_attach (p_helper, p_this);
199             CloseHandle( hIPCHelperReady );
200
201             /* Initialization done.
202              * Release the mutex to unblock other instances */
203             ReleaseMutex( hmutex );
204         }
205         else
206         {
207             /* Another instance is running */
208
209             HWND ipcwindow;
210
211             /* Wait until the 1st instance is initialized */
212             WaitForSingleObject( hmutex, INFINITE );
213
214             /* Locate the window created by the IPC helper thread of the
215              * 1st instance */
216             if( !( ipcwindow = FindWindow( 0, L"VLC ipc "VERSION ) ) )
217             {
218                 msg_Err( p_this, "one instance mode DISABLED "
219                          "(couldn't find 1st instance of program)" );
220                 ReleaseMutex( hmutex );
221                 return;
222             }
223
224             /* We assume that the remaining parameters are filenames
225              * and their input options */
226             if( i_argc > 0 )
227             {
228                 COPYDATASTRUCT wm_data;
229                 int i_opt;
230                 vlc_ipc_data_t *p_data;
231                 size_t i_data = sizeof (*p_data);
232
233                 for( i_opt = 0; i_opt < i_argc; i_opt++ )
234                 {
235                     i_data += sizeof (size_t);
236                     i_data += strlen( ppsz_argv[ i_opt ] ) + 1;
237                 }
238
239                 p_data = malloc( i_data );
240                 p_data->argc = i_argc;
241                 p_data->enqueue = var_InheritBool( p_this, "playlist-enqueue" );
242                 i_data = 0;
243                 for( i_opt = 0; i_opt < i_argc; i_opt++ )
244                 {
245                     size_t i_len = strlen( ppsz_argv[ i_opt ] ) + 1;
246                     /* Windows will never switch to an architecture
247                      * with stronger alignment requirements, right. */
248                     *((size_t *)(p_data->data + i_data)) = i_len;
249                     i_data += sizeof (size_t);
250                     memcpy( &p_data->data[i_data], ppsz_argv[ i_opt ], i_len );
251                     i_data += i_len;
252                 }
253                 i_data += sizeof (*p_data);
254
255                 /* Send our playlist items to the 1st instance */
256                 wm_data.dwData = 0;
257                 wm_data.cbData = i_data;
258                 wm_data.lpData = p_data;
259                 SendMessage( ipcwindow, WM_COPYDATA, 0, (LPARAM)&wm_data );
260             }
261
262             /* Initialization done.
263              * Release the mutex to unblock other instances */
264             ReleaseMutex( hmutex );
265
266             /* Bye bye */
267             system_End( p_this );
268             exit( 0 );
269         }
270     }
271
272 #endif
273 }
274
275 static unsigned __stdcall IPCHelperThread( void *data )
276 {
277     vlc_object_t *p_this = data;
278     HWND ipcwindow;
279     MSG message;
280
281     ipcwindow =
282         CreateWindow( L"STATIC",                     /* name of window class */
283                   L"VLC ipc "VERSION,               /* window title bar text */
284                   0,                                         /* window style */
285                   0,                                 /* default X coordinate */
286                   0,                                 /* default Y coordinate */
287                   0,                                         /* window width */
288                   0,                                        /* window height */
289                   NULL,                                  /* no parent window */
290                   NULL,                            /* no menu in this window */
291                   GetModuleHandle(NULL),  /* handle of this program instance */
292                   NULL );                               /* sent to WM_CREATE */
293
294     SetWindowLongPtr( ipcwindow, GWLP_WNDPROC, (LRESULT)WMCOPYWNDPROC );
295     SetWindowLongPtr( ipcwindow, GWLP_USERDATA, (LONG_PTR)p_this );
296
297     /* Signal the creation of the thread and events queue */
298     SetEvent( hIPCHelperReady );
299
300     while( GetMessage( &message, NULL, 0, 0 ) )
301     {
302         TranslateMessage( &message );
303         DispatchMessage( &message );
304     }
305     return 0;
306 }
307
308 LRESULT CALLBACK WMCOPYWNDPROC( HWND hwnd, UINT uMsg, WPARAM wParam,
309                                 LPARAM lParam )
310 {
311     if( uMsg == WM_QUIT  )
312     {
313         PostQuitMessage( 0 );
314     }
315     else if( uMsg == WM_COPYDATA )
316     {
317         COPYDATASTRUCT *pwm_data = (COPYDATASTRUCT*)lParam;
318         vlc_object_t *p_this;
319         playlist_t *p_playlist;
320
321         p_this = (vlc_object_t *)
322             (uintptr_t)GetWindowLongPtr( hwnd, GWLP_USERDATA );
323
324         if( !p_this ) return 0;
325
326         /* Add files to the playlist */
327         p_playlist = pl_Get( p_this );
328
329         if( pwm_data->lpData )
330         {
331             char **ppsz_argv;
332             vlc_ipc_data_t *p_data = (vlc_ipc_data_t *)pwm_data->lpData;
333             size_t i_data = 0;
334             int i_argc = p_data->argc, i_opt, i_options;
335
336             ppsz_argv = (char **)malloc( i_argc * sizeof(char *) );
337             for( i_opt = 0; i_opt < i_argc; i_opt++ )
338             {
339                 ppsz_argv[i_opt] = p_data->data + i_data + sizeof(int);
340                 i_data += sizeof(int) + *((int *)(p_data->data + i_data));
341             }
342
343             for( i_opt = 0; i_opt < i_argc; i_opt++ )
344             {
345                 i_options = 0;
346
347                 /* Count the input options */
348                 while( i_opt + i_options + 1 < i_argc &&
349                         *ppsz_argv[ i_opt + i_options + 1 ] == ':' )
350                 {
351                     i_options++;
352                 }
353
354                 char *psz_URI = make_URI( ppsz_argv[i_opt], NULL );
355                 playlist_AddExt( p_playlist, psz_URI,
356                         NULL, PLAYLIST_APPEND |
357                         ( ( i_opt || p_data->enqueue ) ? 0 : PLAYLIST_GO ),
358                         PLAYLIST_END, -1,
359                         i_options,
360                         (char const **)( i_options ? &ppsz_argv[i_opt+1] : NULL ),
361                         VLC_INPUT_OPTION_TRUSTED,
362                         true, pl_Unlocked );
363
364                 i_opt += i_options;
365                 free( psz_URI );
366             }
367
368             free( ppsz_argv );
369         }
370     }
371
372     return DefWindowProc( hwnd, uMsg, wParam, lParam );
373 }
374
375 /*****************************************************************************
376  * system_End: terminate winsock.
377  *****************************************************************************/
378 void system_End( libvlc_int_t *p_this )
379 {
380     HWND ipcwindow;
381     if( p_this )
382     {
383         free( psz_vlcpath );
384         psz_vlcpath = NULL;
385     }
386
387     if (p_helper && p_helper->p_parent == VLC_OBJECT(p_this) )
388     {
389         /* this is the first instance (in a one-instance system)
390          * it is the owner of the helper thread
391          */
392         if( ( ipcwindow = FindWindow( 0, L"VLC ipc "VERSION ) ) != 0 )
393         {
394             SendMessage( ipcwindow, WM_QUIT, 0, 0 );
395         }
396
397         /* FIXME: thread-safety... */
398         vlc_object_release (p_helper);
399         p_helper = NULL;
400     }
401
402 #if !defined( UNDER_CE )
403     timeEndPeriod(5);
404 #endif
405
406     WSACleanup();
407 }