demux: ogg: check first frame granule index
[vlc.git] / bin / darwinvlc.m
blobed0e6e159435979cb4f84e49f57987e12ec8a4bf
1 /*****************************************************************************
2  * darwinvlc.m: OS X specific main executable for VLC media player
3  *****************************************************************************
4  * Copyright (C) 2013-2015 VLC authors and VideoLAN
5  *
6  * Authors: Felix Paul Kühne <fkuehne at videolan dot org>
7  *          David Fuhrmann <dfuhrmann at videolan dot 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  *****************************************************************************/
24 #ifdef HAVE_CONFIG_H
25 # include "config.h"
26 #endif
28 #include <vlc/vlc.h>
29 #include <vlc_common.h>
30 #include <vlc_charset.h>
32 #include <stdlib.h>
33 #include <locale.h>
34 #include <signal.h>
35 #include <string.h>
37 #import <CoreFoundation/CoreFoundation.h>
38 #import <Cocoa/Cocoa.h>
40 #ifdef HAVE_BREAKPAD
41 #import <Breakpad/Breakpad.h>
42 #endif
45 /**
46  * Handler called when VLC asks to terminate the program.
47  */
48 static void vlc_terminate(void *data)
50     (void)data;
52     dispatch_async(dispatch_get_main_queue(), ^{
53         /*
54          * Stop the main loop. When using the CoreFoundation mainloop, simply
55          * CFRunLoopStop can be used.
56          *
57          * But this does not work when having an interface.
58          * In this case, [NSApp stop:nil] needs to be used, but the used flag is only
59          * evaluated at the end of main loop event processing. This is always true
60          * in the case of code inside a action method. But here, this is
61          * not true and thus we need to send an dummy event to make sure the stop
62          * flag is actually processed by the main loop.
63          */
64         if (NSApp == nil) {
65             CFRunLoopStop(CFRunLoopGetCurrent());
66         } else {
68             [NSApp stop:nil];
69             NSEvent* event = [NSEvent otherEventWithType:NSApplicationDefined
70                                                 location:NSMakePoint(0,0)
71                                            modifierFlags:0
72                                                timestamp:0.0
73                                             windowNumber:0
74                                                  context:nil
75                                                  subtype:0
76                                                    data1:0
77                                                    data2:0];
78             [NSApp postEvent:event atStart:YES];
79         }
81     });
84 #ifdef HAVE_BREAKPAD
85 BreakpadRef initBreakpad()
87     BreakpadRef bp = nil;
89     /* Create caches directory in case it does not exist */
90     NSFileManager *fileManager = [NSFileManager defaultManager];
91     NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
92     NSString *bundleName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
93     NSString *cacheAppPath = [cachePath stringByAppendingPathComponent:bundleName];
94     if (![fileManager fileExistsAtPath:cacheAppPath]) {
95         [fileManager createDirectoryAtPath:cacheAppPath withIntermediateDirectories:NO attributes:nil error:nil];
96     }
98     /* Get Info.plist config */
99     NSMutableDictionary *breakpad_config = [[[NSBundle mainBundle] infoDictionary] mutableCopy];
101     /* Use in-process reporting */
102     [breakpad_config setObject:[NSNumber numberWithBool:YES]
103                         forKey:@BREAKPAD_IN_PROCESS];
105     /* Set dump location */
106     [breakpad_config setObject:cacheAppPath
107                         forKey:@BREAKPAD_DUMP_DIRECTORY];
109     bp = BreakpadCreate(breakpad_config);
110     return bp;
112 #endif
114 /*****************************************************************************
115  * main: parse command line, start interface and spawn threads.
116  *****************************************************************************/
117 int main(int i_argc, const char *ppsz_argv[])
119     /* The so-called POSIX-compliant MacOS X reportedly processes SIGPIPE even
120      * if it is blocked in all thread.
121      * Note: this is NOT an excuse for not protecting against SIGPIPE. If
122      * LibVLC runs outside of VLC, we cannot rely on this code snippet. */
123     signal(SIGPIPE, SIG_IGN);
124     /* Restore SIGCHLD in case our parent process ignores it. */
125     signal(SIGCHLD, SIG_DFL);
127 #ifndef NDEBUG
128     /* Activate malloc checking routines to detect heap corruptions. */
129     setenv("MALLOC_CHECK_", "2", 1);
130 #endif
132 #ifdef TOP_BUILDDIR
133     setenv("VLC_PLUGIN_PATH", TOP_BUILDDIR"/modules", 1);
134     setenv("VLC_DATA_PATH", TOP_SRCDIR"/share", 1);
135 #endif
137 #ifndef ALLOW_RUN_AS_ROOT
138     if (geteuid() == 0)
139     {
140         fprintf(stderr, "VLC is not supposed to be run as root. Sorry.\n"
141         "If you need to use real-time priorities and/or privileged TCP ports\n"
142         "you can use %s-wrapper (make sure it is Set-UID root and\n"
143         "cannot be run by non-trusted users first).\n", ppsz_argv[0]);
144         return 1;
145     }
146 #endif
148     setlocale(LC_ALL, "");
150     if (isatty(STDERR_FILENO))
151         /* This message clutters error logs. It is printed only on a TTY.
152          * Fortunately, LibVLC prints version info with -vv anyway. */
153         fprintf(stderr, "VLC media player %s (revision %s)\n",
154                  libvlc_get_version(), libvlc_get_changeset());
156     sigset_t set;
158     sigemptyset(&set);
159     /*
160      * The darwin version of VLC used GCD to dequeue interesting signals.
161      * For this to work, those signals must be blocked.
162      *
163      * There are two advantages over traditional signal handlers:
164      *  - handling is done on a separate thread: no need to worry about async-safety,
165      *  - EINTR is not generated: other threads need not handle that error.
166      * That being said, some LibVLC programs do not use sigwait(). Therefore
167      * EINTR must still be handled cleanly, notably from poll() calls.
168      *
169      * Signals that request a clean shutdown.
170      * We have to handle SIGTERM cleanly because of daemon mode. */
171     sigaddset(&set, SIGINT);
172     sigaddset(&set, SIGTERM);
174     /* SIGPIPE can happen and would crash the process. On modern systems,
175      * the MSG_NOSIGNAL flag protects socket write operations against SIGPIPE.
176      * But we still need to block SIGPIPE when:
177      *  - writing to pipes,
178      *  - using write() instead of send() for code not specific to sockets.
179      * LibVLC code assumes that SIGPIPE is blocked. Other LibVLC applications
180      * shall block it (or handle it somehow) too.
181      */
182     sigaddset(&set, SIGPIPE);
184     /* SIGCHLD must be dequeued to clean up zombie child processes.
185      * Furthermore the handler must not be set to SIG_IGN (see above).
186      * We cannot pragmatically handle EINTR, short reads and short writes
187      * in every code paths (including underlying libraries). So we just
188      * block SIGCHLD in all threads, and dequeue it below. */
189     sigaddset(&set, SIGCHLD);
191     /* Block all these signals */
192     pthread_sigmask(SIG_SETMASK, &set, NULL);
194     /* Handle signals with GCD */
195     dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
196     dispatch_source_t sigIntSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, SIGINT, 0, queue);
197     dispatch_source_t sigTermSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, SIGTERM, 0, queue);
198     dispatch_source_t sigChldSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, SIGCHLD, 0, queue);
200     if (!sigIntSource || !sigTermSource || !sigChldSource)
201         abort();
203     dispatch_source_set_event_handler(sigIntSource, ^{
204         vlc_terminate(nil);
205     });
206     dispatch_source_set_event_handler(sigTermSource, ^{
207         vlc_terminate(nil);
208     });
210     dispatch_source_set_event_handler(sigChldSource, ^{
211         int status;
212         while(waitpid(-1, &status, WNOHANG) > 0)
213             ;
214     });
216     dispatch_resume(sigIntSource);
217     dispatch_resume(sigTermSource);
218     dispatch_resume(sigChldSource);
221     /* Handle parameters */
222     const char *argv[i_argc + 2];
223     int argc = 0;
225     argv[argc++] = "--no-ignore-config";
226     argv[argc++] = "--media-library";
228     /* overwrite system language on Mac */
229     char *lang = NULL;
231     for (int i = 0; i < i_argc; i++) {
232         if (!strncmp(ppsz_argv[i], "--language", 10)) {
233             lang = strstr(ppsz_argv[i], "=");
234             ppsz_argv++, i_argc--;
235             continue;
236         }
237     }
238     if (lang && strncmp( lang, "auto", 4 )) {
239         char tmp[11];
240         snprintf(tmp, 11, "LANG%s", lang);
241         putenv(tmp);
242     }
244     if (!lang) {
245         CFStringRef language;
246         language = (CFStringRef)CFPreferencesCopyAppValue(CFSTR("language"),
247                                                           kCFPreferencesCurrentApplication);
248         if (language) {
249             lang = FromCFString(language, kCFStringEncodingUTF8);
250             if (strncmp( lang, "auto", 4 )) {
251                 char tmp[11];
252                 snprintf(tmp, 11, "LANG=%s", lang);
253                 putenv(tmp);
254             }
255             free(lang);
256             CFRelease(language);
257         }
258     }
260     ppsz_argv++; i_argc--; /* skip executable path */
262     /* When VLC.app is run by double clicking in Mac OS X < 10.9, the 2nd arg
263      * is the PSN - process serial number (a unique PID-ish thingie)
264      * still ok for real Darwin & when run from command line
265      * for example -psn_0_9306113 */
266     if (i_argc >= 1 && !strncmp(*ppsz_argv, "-psn" , 4))
267         ppsz_argv++, i_argc--;
269     memcpy (argv + argc, ppsz_argv, i_argc * sizeof(*argv));
270     argc += i_argc;
271     argv[argc] = NULL;
273     /* Initialize libvlc */
274     libvlc_instance_t *vlc = libvlc_new(argc, argv);
275     if (vlc == NULL)
276         return 1;
278     int ret = 1;
279     libvlc_set_exit_handler(vlc, vlc_terminate, NULL);
280     libvlc_set_app_id(vlc, "org.VideoLAN.VLC", PACKAGE_VERSION, PACKAGE_NAME);
281     libvlc_set_user_agent(vlc, "VLC media player", "VLC/"PACKAGE_VERSION);
283     libvlc_add_intf(vlc, "hotkeys,none");
285     if (libvlc_add_intf(vlc, NULL)) {
286         fprintf(stderr, "VLC cannot start any interface. Exiting.\n");
287         goto out;
288     }
289     libvlc_playlist_play(vlc);
291     /*
292      * Run the main loop. If the mac interface is not initialized, only the CoreFoundation
293      * runloop is used. Otherwise, [NSApp run] needs to be called, which setups more stuff
294      * before actually starting the loop.
295      */
296 #ifdef HAVE_BREAKPAD
297     BreakpadRef breakpad;
298     breakpad = initBreakpad();
299 #endif
300     @autoreleasepool {
301         if(NSApp == nil) {
302             CFRunLoopRun();
304         } else {
305             [NSApp run];
306         }
307     }
309     ret = 0;
310     /* Cleanup */
311 out:
312     dispatch_release(sigIntSource);
313     dispatch_release(sigTermSource);
314     dispatch_release(sigChldSource);
316     libvlc_release(vlc);
318 #ifdef HAVE_BREAKPAD
319     BreakpadRelease(breakpad);
320 #endif
322     return ret;