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