Contribs:srt: use CMakeList directly
[vlc.git] / bin / darwinvlc.m
blobe3da5722a03e7d5fad8adc93357c26a9e4ebd0ba
1 /*****************************************************************************
2  * darwinvlc.m: OS X specific main executable for VLC media player
3  *****************************************************************************
4  * Copyright (C) 2013-2015 VLC authors and VideoLAN
5  * $Id$
6  *
7  * Authors: Felix Paul Kühne <fkuehne at videolan dot org>
8  *          David Fuhrmann <dfuhrmann at videolan dot org>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
25 #ifdef HAVE_CONFIG_H
26 # include "config.h"
27 #endif
29 #include <vlc/vlc.h>
30 #include <stdlib.h>
31 #include <locale.h>
32 #include <signal.h>
33 #include <string.h>
35 #import <CoreFoundation/CoreFoundation.h>
36 #import <Cocoa/Cocoa.h>
38 #ifdef HAVE_BREAKPAD
39 #import <Breakpad/Breakpad.h>
40 #endif
43 /**
44  * Handler called when VLC asks to terminate the program.
45  */
46 static void vlc_terminate(void *data)
48     (void)data;
50     dispatch_async(dispatch_get_main_queue(), ^{
51         /*
52          * Stop the main loop. When using the CoreFoundation mainloop, simply
53          * CFRunLoopStop can be used.
54          *
55          * But this does not work when having an interface.
56          * In this case, [NSApp stop:nil] needs to be used, but the used flag is only
57          * evaluated at the end of main loop event processing. This is always true
58          * in the case of code inside a action method. But here, this is
59          * not true and thus we need to send an dummy event to make sure the stop
60          * flag is actually processed by the main loop.
61          */
62         if (NSApp == nil) {
63             CFRunLoopStop(CFRunLoopGetCurrent());
64         } else {
66             [NSApp stop:nil];
67             NSEvent* event = [NSEvent otherEventWithType:NSApplicationDefined
68                                                 location:NSMakePoint(0,0)
69                                            modifierFlags:0
70                                                timestamp:0.0
71                                             windowNumber:0
72                                                  context:nil
73                                                  subtype:0
74                                                    data1:0
75                                                    data2:0];
76             [NSApp postEvent:event atStart:YES];
77         }
79     });
82 #ifdef HAVE_BREAKPAD
83 BreakpadRef initBreakpad()
85     BreakpadRef bp = nil;
87     /* Create caches directory in case it does not exist */
88     NSFileManager *fileManager = [NSFileManager defaultManager];
89     NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
90     NSString *bundleName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
91     NSString *cacheAppPath = [cachePath stringByAppendingPathComponent:bundleName];
92     if (![fileManager fileExistsAtPath:cacheAppPath]) {
93         [fileManager createDirectoryAtPath:cacheAppPath withIntermediateDirectories:NO attributes:nil error:nil];
94     }
96     /* Get Info.plist config */
97     NSMutableDictionary *breakpad_config = [[[NSBundle mainBundle] infoDictionary] mutableCopy];
99     /* Use in-process reporting */
100     [breakpad_config setObject:[NSNumber numberWithBool:YES]
101                         forKey:@BREAKPAD_IN_PROCESS];
103     /* Set dump location */
104     [breakpad_config setObject:cacheAppPath
105                         forKey:@BREAKPAD_DUMP_DIRECTORY];
107     bp = BreakpadCreate(breakpad_config);
108     return bp;
110 #endif
112 /*****************************************************************************
113  * main: parse command line, start interface and spawn threads.
114  *****************************************************************************/
115 int main(int i_argc, const char *ppsz_argv[])
117     /* The so-called POSIX-compliant MacOS X reportedly processes SIGPIPE even
118      * if it is blocked in all thread.
119      * Note: this is NOT an excuse for not protecting against SIGPIPE. If
120      * LibVLC runs outside of VLC, we cannot rely on this code snippet. */
121     signal(SIGPIPE, SIG_IGN);
122     /* Restore SIGCHLD in case our parent process ignores it. */
123     signal(SIGCHLD, SIG_DFL);
125 #ifndef NDEBUG
126     /* Activate malloc checking routines to detect heap corruptions. */
127     setenv("MALLOC_CHECK_", "2", 1);
128 #endif
130 #ifdef TOP_BUILDDIR
131     setenv("VLC_PLUGIN_PATH", TOP_BUILDDIR"/modules", 1);
132     setenv("VLC_DATA_PATH", TOP_SRCDIR"/share", 1);
133 #endif
135 #ifndef ALLOW_RUN_AS_ROOT
136     if (geteuid() == 0)
137     {
138         fprintf(stderr, "VLC is not supposed to be run as root. Sorry.\n"
139         "If you need to use real-time priorities and/or privileged TCP ports\n"
140         "you can use %s-wrapper (make sure it is Set-UID root and\n"
141         "cannot be run by non-trusted users first).\n", ppsz_argv[0]);
142         return 1;
143     }
144 #endif
146     setlocale(LC_ALL, "");
148     if (isatty(STDERR_FILENO))
149         /* This message clutters error logs. It is printed only on a TTY.
150          * Fortunately, LibVLC prints version info with -vv anyway. */
151         fprintf(stderr, "VLC media player %s (revision %s)\n",
152                  libvlc_get_version(), libvlc_get_changeset());
154     sigset_t set;
156     sigemptyset(&set);
157     /*
158      * The darwin version of VLC used GCD to dequeue interesting signals.
159      * For this to work, those signals must be blocked.
160      *
161      * There are two advantages over traditional signal handlers:
162      *  - handling is done on a separate thread: no need to worry about async-safety,
163      *  - EINTR is not generated: other threads need not handle that error.
164      * That being said, some LibVLC programs do not use sigwait(). Therefore
165      * EINTR must still be handled cleanly, notably from poll() calls.
166      *
167      * Signals that request a clean shutdown.
168      * We have to handle SIGTERM cleanly because of daemon mode. */
169     sigaddset(&set, SIGINT);
170     sigaddset(&set, SIGTERM);
172     /* SIGPIPE can happen and would crash the process. On modern systems,
173      * the MSG_NOSIGNAL flag protects socket write operations against SIGPIPE.
174      * But we still need to block SIGPIPE when:
175      *  - writing to pipes,
176      *  - using write() instead of send() for code not specific to sockets.
177      * LibVLC code assumes that SIGPIPE is blocked. Other LibVLC applications
178      * shall block it (or handle it somehow) too.
179      */
180     sigaddset(&set, SIGPIPE);
182     /* SIGCHLD must be dequeued to clean up zombie child processes.
183      * Furthermore the handler must not be set to SIG_IGN (see above).
184      * We cannot pragmatically handle EINTR, short reads and short writes
185      * in every code paths (including underlying libraries). So we just
186      * block SIGCHLD in all threads, and dequeue it below. */
187     sigaddset(&set, SIGCHLD);
189     /* Block all these signals */
190     pthread_sigmask(SIG_SETMASK, &set, NULL);
192     /* Handle signals with GCD */
193     dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
194     dispatch_source_t sigIntSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, SIGINT, 0, queue);
195     dispatch_source_t sigTermSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, SIGTERM, 0, queue);
196     dispatch_source_t sigChldSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, SIGCHLD, 0, queue);
198     if (!sigIntSource || !sigTermSource || !sigChldSource)
199         abort();
201     dispatch_source_set_event_handler(sigIntSource, ^{
202         vlc_terminate(nil);
203     });
204     dispatch_source_set_event_handler(sigTermSource, ^{
205         vlc_terminate(nil);
206     });
208     dispatch_source_set_event_handler(sigChldSource, ^{
209         int status;
210         while(waitpid(-1, &status, WNOHANG) > 0)
211             ;
212     });
214     dispatch_resume(sigIntSource);
215     dispatch_resume(sigTermSource);
216     dispatch_resume(sigChldSource);
219     /* Handle parameters */
220     const char *argv[i_argc + 2];
221     int argc = 0;
223     argv[argc++] = "--no-ignore-config";
224     argv[argc++] = "--media-library";
226     /* overwrite system language on Mac */
227     char *lang = NULL;
229     for (int i = 0; i < i_argc; i++) {
230         if (!strncmp(ppsz_argv[i], "--language", 10)) {
231             lang = strstr(ppsz_argv[i], "=");
232             ppsz_argv++, i_argc--;
233             continue;
234         }
235     }
236     if (lang && strncmp( lang, "auto", 4 )) {
237         char tmp[11];
238         snprintf(tmp, 11, "LANG%s", lang);
239         putenv(tmp);
240     }
242     if (!lang) {
243         CFStringRef language;
244         language = (CFStringRef)CFPreferencesCopyAppValue(CFSTR("language"),
245                                                           kCFPreferencesCurrentApplication);
246         if (language) {
247             CFIndex length = CFStringGetLength(language) + 1;
248             if (length > 0) {
249                 CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8);
250                 lang = (char *)malloc(maxSize);
251                 if(lang) {
252                     CFStringGetCString(language, lang, maxSize - 1, kCFStringEncodingUTF8);
253                     if (strncmp( lang, "auto", 4 )) {
254                         char tmp[11];
255                         snprintf(tmp, 11, "LANG=%s", lang);
256                         putenv(tmp);
258                     }
259                 }
260                 free(lang);
261             }
262             CFRelease(language);
263         }
264     }
266     ppsz_argv++; i_argc--; /* skip executable path */
268     /* When VLC.app is run by double clicking in Mac OS X < 10.9, the 2nd arg
269      * is the PSN - process serial number (a unique PID-ish thingie)
270      * still ok for real Darwin & when run from command line
271      * for example -psn_0_9306113 */
272     if (i_argc >= 1 && !strncmp(*ppsz_argv, "-psn" , 4))
273         ppsz_argv++, i_argc--;
275     memcpy (argv + argc, ppsz_argv, i_argc * sizeof(*argv));
276     argc += i_argc;
277     argv[argc] = NULL;
279     /* Initialize libvlc */
280     libvlc_instance_t *vlc = libvlc_new(argc, argv);
281     if (vlc == NULL)
282         return 1;
284     int ret = 1;
285     libvlc_set_exit_handler(vlc, vlc_terminate, NULL);
286     libvlc_set_app_id(vlc, "org.VideoLAN.VLC", PACKAGE_VERSION, PACKAGE_NAME);
287     libvlc_set_user_agent(vlc, "VLC media player", "VLC/"PACKAGE_VERSION);
289     libvlc_add_intf(vlc, "hotkeys,none");
291     if (libvlc_add_intf(vlc, NULL))
292         goto out;
293     libvlc_playlist_play(vlc, -1, 0, NULL);
295     /*
296      * Run the main loop. If the mac interface is not initialized, only the CoreFoundation
297      * runloop is used. Otherwise, [NSApp run] needs to be called, which setups more stuff
298      * before actually starting the loop.
299      */
300 #ifdef HAVE_BREAKPAD
301     BreakpadRef breakpad;
302     breakpad = initBreakpad();
303 #endif
304     @autoreleasepool {
305         if(NSApp == nil) {
306             CFRunLoopRun();
308         } else {
309             [NSApp run];
310         }
311     }
313     ret = 0;
314     /* Cleanup */
315 out:
316     dispatch_release(sigIntSource);
317     dispatch_release(sigTermSource);
318     dispatch_release(sigChldSource);
320     libvlc_release(vlc);
322 #ifdef HAVE_BREAKPAD
323     BreakpadRelease(breakpad);
324 #endif
326     return ret;