Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / chromecast / browser / cast_browser_main_parts.cc
blob81701cb2d9812077968fa19270037f700c76f89b
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chromecast/browser/cast_browser_main_parts.h"
7 #include <string>
8 #if !defined(OS_ANDROID)
9 #include <signal.h>
10 #include <sys/prctl.h>
11 #endif
13 #include "base/command_line.h"
14 #include "base/files/file_util.h"
15 #include "base/message_loop/message_loop.h"
16 #include "base/path_service.h"
17 #include "base/prefs/pref_registry_simple.h"
18 #include "base/run_loop.h"
19 #include "base/thread_task_runner_handle.h"
20 #include "cc/base/switches.h"
21 #include "chromecast/base/cast_paths.h"
22 #include "chromecast/base/cast_sys_info_util.h"
23 #include "chromecast/base/chromecast_switches.h"
24 #include "chromecast/base/metrics/cast_metrics_helper.h"
25 #include "chromecast/base/metrics/grouped_histogram.h"
26 #include "chromecast/browser/cast_browser_context.h"
27 #include "chromecast/browser/cast_browser_process.h"
28 #include "chromecast/browser/cast_net_log.h"
29 #include "chromecast/browser/devtools/remote_debugging_server.h"
30 #include "chromecast/browser/metrics/cast_metrics_prefs.h"
31 #include "chromecast/browser/metrics/cast_metrics_service_client.h"
32 #include "chromecast/browser/pref_service_helper.h"
33 #include "chromecast/browser/service/cast_service.h"
34 #include "chromecast/browser/url_request_context_factory.h"
35 #include "chromecast/common/platform_client_auth.h"
36 #include "chromecast/media/base/key_systems_common.h"
37 #include "chromecast/media/base/media_message_loop.h"
38 #include "chromecast/net/connectivity_checker.h"
39 #include "chromecast/public/cast_media_shlib.h"
40 #include "chromecast/public/cast_sys_info.h"
41 #include "content/public/browser/browser_thread.h"
42 #include "content/public/browser/gpu_data_manager.h"
43 #include "content/public/common/content_switches.h"
44 #include "media/audio/audio_manager.h"
45 #include "media/audio/audio_manager_factory.h"
46 #include "media/base/browser_cdm_factory.h"
47 #include "media/base/media.h"
48 #include "ui/compositor/compositor_switches.h"
50 #if defined(OS_ANDROID)
51 #include "chromecast/app/android/crash_handler.h"
52 #include "chromecast/browser/media/cast_media_client_android.h"
53 #include "components/crash/browser/crash_dump_manager_android.h"
54 #include "media/base/android/media_client_android.h"
55 #include "net/android/network_change_notifier_factory_android.h"
56 #else
57 #include "chromecast/browser/media/cast_browser_cdm_factory.h"
58 #include "chromecast/net/network_change_notifier_factory_cast.h"
59 #endif
61 #if defined(USE_AURA)
62 #include "chromecast/graphics/cast_screen.h"
63 #include "ui/aura/env.h"
64 #include "ui/gfx/screen.h"
65 #endif
67 namespace {
69 #if !defined(OS_ANDROID)
70 int kSignalsToRunClosure[] = { SIGTERM, SIGINT, };
72 // Closure to run on SIGTERM and SIGINT.
73 base::Closure* g_signal_closure = NULL;
75 void RunClosureOnSignal(int signum) {
76 LOG(ERROR) << "Got signal " << signum;
77 DCHECK(g_signal_closure);
78 // Expect main thread got this signal. Otherwise, weak_ptr of run_loop will
79 // crash the process.
80 g_signal_closure->Run();
83 void RegisterClosureOnSignal(const base::Closure& closure) {
84 DCHECK(!g_signal_closure);
85 DCHECK_GT(arraysize(kSignalsToRunClosure), 0U);
87 // Allow memory leak by intention.
88 g_signal_closure = new base::Closure(closure);
90 struct sigaction sa_new;
91 memset(&sa_new, 0, sizeof(sa_new));
92 sa_new.sa_handler = RunClosureOnSignal;
93 sigfillset(&sa_new.sa_mask);
94 sa_new.sa_flags = SA_RESTART;
96 for (size_t i = 0; i < arraysize(kSignalsToRunClosure); i++) {
97 struct sigaction sa_old;
98 if (sigaction(kSignalsToRunClosure[i], &sa_new, &sa_old) == -1) {
99 NOTREACHED();
100 } else {
101 DCHECK_EQ(sa_old.sa_handler, SIG_DFL);
105 // Get the first signal to exit when the parent process dies.
106 prctl(PR_SET_PDEATHSIG, kSignalsToRunClosure[0]);
109 const int kKillOnAlarmTimeoutSec = 5; // 5 seconds
111 void KillOnAlarm(int signum) {
112 LOG(ERROR) << "Got alarm signal for termination: " << signum;
113 raise(SIGKILL);
116 void RegisterKillOnAlarm(int timeout_seconds) {
117 struct sigaction sa_new;
118 memset(&sa_new, 0, sizeof(sa_new));
119 sa_new.sa_handler = KillOnAlarm;
120 sigfillset(&sa_new.sa_mask);
121 sa_new.sa_flags = SA_RESTART;
123 struct sigaction sa_old;
124 if (sigaction(SIGALRM, &sa_new, &sa_old) == -1) {
125 NOTREACHED();
126 } else {
127 DCHECK_EQ(sa_old.sa_handler, SIG_DFL);
130 if (alarm(timeout_seconds) > 0)
131 NOTREACHED() << "Previous alarm() was cancelled";
134 void DeregisterKillOnAlarm() {
135 // Explicitly cancel any outstanding alarm() calls.
136 alarm(0);
138 struct sigaction sa_new;
139 memset(&sa_new, 0, sizeof(sa_new));
140 sa_new.sa_handler = SIG_DFL;
141 sigfillset(&sa_new.sa_mask);
142 sa_new.sa_flags = SA_RESTART;
144 struct sigaction sa_old;
145 if (sigaction(SIGALRM, &sa_new, &sa_old) == -1) {
146 NOTREACHED();
147 } else {
148 DCHECK_EQ(sa_old.sa_handler, KillOnAlarm);
151 #endif // !defined(OS_ANDROID)
153 } // namespace
155 namespace chromecast {
156 namespace shell {
158 namespace {
160 struct DefaultCommandLineSwitch {
161 const char* const switch_name;
162 const char* const switch_value;
165 DefaultCommandLineSwitch g_default_switches[] = {
166 #if defined(OS_ANDROID)
167 // Disables Chromecast-specific WiFi-related features on ATV for now.
168 { switches::kNoWifi, "" },
169 { switches::kEnableOverlayFullscreenVideo, ""},
170 { switches::kDisableGestureRequirementForMediaPlayback, ""},
171 #endif
172 // Always enable HTMLMediaElement logs.
173 { switches::kBlinkPlatformLogChannels, "Media"},
174 #if defined(DISABLE_DISPLAY)
175 { switches::kDisableGpu, "" },
176 #endif
177 #if defined(OS_LINUX)
178 #if defined(ARCH_CPU_X86_FAMILY)
179 // This is needed for now to enable the egltest Ozone platform to work with
180 // current Linux/NVidia OpenGL drivers.
181 { switches::kIgnoreGpuBlacklist, ""},
182 #elif defined(ARCH_CPU_ARM_FAMILY)
183 // On Linux arm, enable CMA pipeline by default.
184 { switches::kEnableCmaMediaPipeline, "" },
185 #if !defined(DISABLE_DISPLAY)
186 { switches::kEnableHardwareOverlays, "" },
187 #endif
188 #endif
189 #endif // defined(OS_LINUX)
190 // Needed to fix a bug where the raster thread doesn't get scheduled for a
191 // substantial time (~5 seconds). See https://crbug.com/441895.
192 { switches::kUseNormalPriorityForTileTaskWorkerThreads, "" },
193 { NULL, NULL }, // Termination
196 void AddDefaultCommandLineSwitches(base::CommandLine* command_line) {
197 int i = 0;
198 while (g_default_switches[i].switch_name != NULL) {
199 command_line->AppendSwitchASCII(
200 std::string(g_default_switches[i].switch_name),
201 std::string(g_default_switches[i].switch_value));
202 ++i;
206 } // namespace
208 CastBrowserMainParts::CastBrowserMainParts(
209 const content::MainFunctionParams& parameters,
210 URLRequestContextFactory* url_request_context_factory,
211 scoped_ptr<::media::AudioManagerFactory> audio_manager_factory)
212 : BrowserMainParts(),
213 cast_browser_process_(new CastBrowserProcess()),
214 parameters_(parameters),
215 url_request_context_factory_(url_request_context_factory),
216 audio_manager_factory_(audio_manager_factory.Pass()),
217 net_log_(new CastNetLog()) {
218 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
219 AddDefaultCommandLineSwitches(command_line);
222 CastBrowserMainParts::~CastBrowserMainParts() {
225 void CastBrowserMainParts::PreMainMessageLoopStart() {
226 // GroupedHistograms needs to be initialized before any threads are created
227 // to prevent race conditions between calls to Preregister and those threads
228 // attempting to collect metrics.
229 // This call must also be before NetworkChangeNotifier, as it generates
230 // Net/DNS metrics.
231 metrics::PreregisterAllGroupedHistograms();
233 // Set the platform's implementation of AudioManagerFactory.
234 if (audio_manager_factory_)
235 ::media::AudioManager::SetFactory(audio_manager_factory_.release());
237 #if defined(OS_ANDROID)
238 net::NetworkChangeNotifier::SetFactory(
239 new net::NetworkChangeNotifierFactoryAndroid());
240 #else
241 net::NetworkChangeNotifier::SetFactory(
242 new NetworkChangeNotifierFactoryCast());
243 #endif // defined(OS_ANDROID)
246 void CastBrowserMainParts::PostMainMessageLoopStart() {
247 cast_browser_process_->SetMetricsHelper(make_scoped_ptr(
248 new metrics::CastMetricsHelper(base::ThreadTaskRunnerHandle::Get())));
250 #if defined(OS_ANDROID)
251 base::MessageLoopForUI::current()->Start();
252 #endif // defined(OS_ANDROID)
255 int CastBrowserMainParts::PreCreateThreads() {
256 #if defined(OS_ANDROID)
257 // GPU process is started immediately after threads are created, requiring
258 // CrashDumpManager to be initialized beforehand.
259 base::FilePath crash_dumps_dir;
260 if (!chromecast::CrashHandler::GetCrashDumpLocation(&crash_dumps_dir)) {
261 LOG(ERROR) << "Could not find crash dump location.";
263 cast_browser_process_->SetCrashDumpManager(
264 make_scoped_ptr(new breakpad::CrashDumpManager(crash_dumps_dir)));
265 #else
266 base::FilePath home_dir;
267 CHECK(PathService::Get(DIR_CAST_HOME, &home_dir));
268 if (!base::CreateDirectory(home_dir))
269 return 1;
270 #endif
272 #if defined(USE_AURA)
273 // Screen can (and should) exist even with no displays connected. Its presence
274 // is assumed as an interface to access display information, e.g. from metrics
275 // code. See CastContentWindow::CreateWindowTree for update when resolution
276 // is available.
277 cast_browser_process_->SetCastScreen(make_scoped_ptr(new CastScreen));
278 DCHECK(!gfx::Screen::GetScreenByType(gfx::SCREEN_TYPE_NATIVE));
279 gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_NATIVE,
280 cast_browser_process_->cast_screen());
281 #endif
283 #if !defined(OS_ANDROID)
284 // Set GL strings so GPU config code can make correct feature blacklisting/
285 // whitelisting decisions.
286 // Note: SetGLStrings MUST be called after GpuDataManager::Initialize.
287 scoped_ptr<CastSysInfo> sys_info = CreateSysInfo();
288 content::GpuDataManager::GetInstance()->SetGLStrings(
289 sys_info->GetGlVendor(), sys_info->GetGlRenderer(),
290 sys_info->GetGlVersion());
291 #endif // !defined(OS_ANDROID)
293 return 0;
296 void CastBrowserMainParts::PreMainMessageLoopRun() {
297 scoped_refptr<PrefRegistrySimple> pref_registry(new PrefRegistrySimple());
298 metrics::RegisterPrefs(pref_registry.get());
299 cast_browser_process_->SetPrefService(
300 PrefServiceHelper::CreatePrefService(pref_registry.get()));
302 const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
303 #if defined(OS_ANDROID)
304 ::media::SetMediaClientAndroid(new media::CastMediaClientAndroid());
305 #else
306 if (cmd_line->HasSwitch(switches::kEnableCmaMediaPipeline))
307 ::media::SetBrowserCdmFactory(new media::CastBrowserCdmFactory());
308 #endif // defined(OS_ANDROID)
310 cast_browser_process_->SetConnectivityChecker(
311 ConnectivityChecker::Create(
312 content::BrowserThread::GetMessageLoopProxyForThread(
313 content::BrowserThread::IO)));
315 cast_browser_process_->SetNetLog(net_log_.get());
317 url_request_context_factory_->InitializeOnUIThread(net_log_.get());
319 cast_browser_process_->SetBrowserContext(
320 make_scoped_ptr(new CastBrowserContext(url_request_context_factory_)));
321 cast_browser_process_->SetMetricsServiceClient(
322 metrics::CastMetricsServiceClient::Create(
323 content::BrowserThread::GetBlockingPool(),
324 cast_browser_process_->pref_service(),
325 cast_browser_process_->browser_context()->GetRequestContext()));
327 if (!PlatformClientAuth::Initialize())
328 LOG(ERROR) << "PlatformClientAuth::Initialize failed.";
330 cast_browser_process_->SetRemoteDebuggingServer(
331 make_scoped_ptr(new RemoteDebuggingServer()));
333 media::MediaMessageLoop::GetTaskRunner()->PostTask(
334 FROM_HERE,
335 base::Bind(&media::CastMediaShlib::Initialize, cmd_line->argv()));
336 ::media::InitializeMediaLibrary();
338 cast_browser_process_->SetCastService(CastService::Create(
339 cast_browser_process_->browser_context(),
340 cast_browser_process_->pref_service(),
341 cast_browser_process_->metrics_service_client(),
342 url_request_context_factory_->GetSystemGetter()));
343 cast_browser_process_->cast_service()->Initialize();
345 // Initializing metrics service and network delegates must happen after cast
346 // service is intialized because CastMetricsServiceClient and
347 // CastNetworkDelegate may use components initialized by cast service.
348 cast_browser_process_->metrics_service_client()
349 ->Initialize(cast_browser_process_->cast_service());
350 url_request_context_factory_->InitializeNetworkDelegates();
352 cast_browser_process_->cast_service()->Start();
355 bool CastBrowserMainParts::MainMessageLoopRun(int* result_code) {
356 #if defined(OS_ANDROID)
357 // Android does not use native main MessageLoop.
358 NOTREACHED();
359 return true;
360 #else
361 base::RunLoop run_loop;
362 base::Closure quit_closure(run_loop.QuitClosure());
363 RegisterClosureOnSignal(quit_closure);
365 // If parameters_.ui_task is not NULL, we are running browser tests.
366 if (parameters_.ui_task) {
367 base::MessageLoop* message_loop = base::MessageLoopForUI::current();
368 message_loop->PostTask(FROM_HERE, *parameters_.ui_task);
369 message_loop->PostTask(FROM_HERE, quit_closure);
372 run_loop.Run();
374 // Once the main loop has stopped running, we give the browser process a few
375 // seconds to stop cast service and finalize all resources. If a hang occurs
376 // and cast services refuse to terminate successfully, then we SIGKILL the
377 // current process to avoid indefinte hangs.
378 RegisterKillOnAlarm(kKillOnAlarmTimeoutSec);
380 cast_browser_process_->cast_service()->Stop();
381 return true;
382 #endif
385 void CastBrowserMainParts::PostMainMessageLoopRun() {
386 #if defined(OS_ANDROID)
387 // Android does not use native main MessageLoop.
388 NOTREACHED();
389 #else
390 cast_browser_process_->cast_service()->Finalize();
391 cast_browser_process_->metrics_service_client()->Finalize();
392 cast_browser_process_.reset();
394 #if defined(USE_AURA)
395 aura::Env::DeleteInstance();
396 #endif
398 DeregisterKillOnAlarm();
399 #endif
401 // Finalize CastMediaShlib on media thread to ensure it's not accessed
402 // after Finalize.
403 media::MediaMessageLoop::GetTaskRunner()->PostTask(
404 FROM_HERE, base::Bind(&media::CastMediaShlib::Finalize));
407 } // namespace shell
408 } // namespace chromecast