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"
8 #if !defined(OS_ANDROID)
10 #include <sys/prctl.h>
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"
57 #include "chromecast/browser/media/cast_browser_cdm_factory.h"
58 #include "chromecast/net/network_change_notifier_factory_cast.h"
62 #include "chromecast/graphics/cast_screen.h"
63 #include "ui/aura/env.h"
64 #include "ui/gfx/screen.h"
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
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) {
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
;
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) {
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.
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) {
148 DCHECK_EQ(sa_old
.sa_handler
, KillOnAlarm
);
151 #endif // !defined(OS_ANDROID)
155 namespace chromecast
{
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::kDisableGestureRequirementForMediaPlayback
, ""},
171 // Always enable HTMLMediaElement logs.
172 { switches::kBlinkPlatformLogChannels
, "Media"},
173 #if defined(DISABLE_DISPLAY)
174 { switches::kDisableGpu
, "" },
176 #if defined(OS_LINUX)
177 #if defined(ARCH_CPU_X86_FAMILY)
178 // This is needed for now to enable the egltest Ozone platform to work with
179 // current Linux/NVidia OpenGL drivers.
180 { switches::kIgnoreGpuBlacklist
, ""},
181 #elif defined(ARCH_CPU_ARM_FAMILY)
182 // On Linux arm, enable CMA pipeline by default.
183 { switches::kEnableCmaMediaPipeline
, "" },
184 #if !defined(DISABLE_DISPLAY)
185 { switches::kEnableHardwareOverlays
, "" },
188 #endif // defined(OS_LINUX)
189 // Needed to fix a bug where the raster thread doesn't get scheduled for a
190 // substantial time (~5 seconds). See https://crbug.com/441895.
191 { switches::kUseNormalPriorityForTileTaskWorkerThreads
, "" },
192 { NULL
, NULL
}, // Termination
195 void AddDefaultCommandLineSwitches(base::CommandLine
* command_line
) {
197 while (g_default_switches
[i
].switch_name
!= NULL
) {
198 command_line
->AppendSwitchASCII(
199 std::string(g_default_switches
[i
].switch_name
),
200 std::string(g_default_switches
[i
].switch_value
));
207 CastBrowserMainParts::CastBrowserMainParts(
208 const content::MainFunctionParams
& parameters
,
209 URLRequestContextFactory
* url_request_context_factory
,
210 scoped_ptr
<::media::AudioManagerFactory
> audio_manager_factory
)
211 : BrowserMainParts(),
212 cast_browser_process_(new CastBrowserProcess()),
213 parameters_(parameters
),
214 url_request_context_factory_(url_request_context_factory
),
215 audio_manager_factory_(audio_manager_factory
.Pass()),
216 net_log_(new CastNetLog()) {
217 base::CommandLine
* command_line
= base::CommandLine::ForCurrentProcess();
218 AddDefaultCommandLineSwitches(command_line
);
221 CastBrowserMainParts::~CastBrowserMainParts() {
224 void CastBrowserMainParts::PreMainMessageLoopStart() {
225 // GroupedHistograms needs to be initialized before any threads are created
226 // to prevent race conditions between calls to Preregister and those threads
227 // attempting to collect metrics.
228 // This call must also be before NetworkChangeNotifier, as it generates
230 metrics::PreregisterAllGroupedHistograms();
232 // Set the platform's implementation of AudioManagerFactory.
233 if (audio_manager_factory_
)
234 ::media::AudioManager::SetFactory(audio_manager_factory_
.release());
236 #if defined(OS_ANDROID)
237 net::NetworkChangeNotifier::SetFactory(
238 new net::NetworkChangeNotifierFactoryAndroid());
240 net::NetworkChangeNotifier::SetFactory(
241 new NetworkChangeNotifierFactoryCast());
242 #endif // defined(OS_ANDROID)
245 void CastBrowserMainParts::PostMainMessageLoopStart() {
246 cast_browser_process_
->SetMetricsHelper(make_scoped_ptr(
247 new metrics::CastMetricsHelper(base::ThreadTaskRunnerHandle::Get())));
249 #if defined(OS_ANDROID)
250 base::MessageLoopForUI::current()->Start();
251 #endif // defined(OS_ANDROID)
254 int CastBrowserMainParts::PreCreateThreads() {
255 #if defined(OS_ANDROID)
256 // GPU process is started immediately after threads are created, requiring
257 // CrashDumpManager to be initialized beforehand.
258 base::FilePath crash_dumps_dir
;
259 if (!chromecast::CrashHandler::GetCrashDumpLocation(&crash_dumps_dir
)) {
260 LOG(ERROR
) << "Could not find crash dump location.";
262 cast_browser_process_
->SetCrashDumpManager(
263 make_scoped_ptr(new breakpad::CrashDumpManager(crash_dumps_dir
)));
265 base::FilePath home_dir
;
266 CHECK(PathService::Get(DIR_CAST_HOME
, &home_dir
));
267 if (!base::CreateDirectory(home_dir
))
271 #if defined(USE_AURA)
272 // Screen can (and should) exist even with no displays connected. Its presence
273 // is assumed as an interface to access display information, e.g. from metrics
274 // code. See CastContentWindow::CreateWindowTree for update when resolution
276 cast_browser_process_
->SetCastScreen(make_scoped_ptr(new CastScreen
));
277 DCHECK(!gfx::Screen::GetScreenByType(gfx::SCREEN_TYPE_NATIVE
));
278 gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_NATIVE
,
279 cast_browser_process_
->cast_screen());
282 #if !defined(OS_ANDROID)
283 // Set GL strings so GPU config code can make correct feature blacklisting/
284 // whitelisting decisions.
285 // Note: SetGLStrings MUST be called after GpuDataManager::Initialize.
286 scoped_ptr
<CastSysInfo
> sys_info
= CreateSysInfo();
287 content::GpuDataManager::GetInstance()->SetGLStrings(
288 sys_info
->GetGlVendor(), sys_info
->GetGlRenderer(),
289 sys_info
->GetGlVersion());
290 #endif // !defined(OS_ANDROID)
295 void CastBrowserMainParts::PreMainMessageLoopRun() {
296 scoped_refptr
<PrefRegistrySimple
> pref_registry(new PrefRegistrySimple());
297 metrics::RegisterPrefs(pref_registry
.get());
298 cast_browser_process_
->SetPrefService(
299 PrefServiceHelper::CreatePrefService(pref_registry
.get()));
301 const base::CommandLine
* cmd_line
= base::CommandLine::ForCurrentProcess();
302 #if defined(OS_ANDROID)
303 ::media::SetMediaClientAndroid(new media::CastMediaClientAndroid());
305 if (cmd_line
->HasSwitch(switches::kEnableCmaMediaPipeline
))
306 ::media::SetBrowserCdmFactory(new media::CastBrowserCdmFactory());
307 #endif // defined(OS_ANDROID)
309 cast_browser_process_
->SetConnectivityChecker(
310 ConnectivityChecker::Create(
311 content::BrowserThread::GetMessageLoopProxyForThread(
312 content::BrowserThread::IO
)));
314 cast_browser_process_
->SetNetLog(net_log_
.get());
316 url_request_context_factory_
->InitializeOnUIThread(net_log_
.get());
318 cast_browser_process_
->SetBrowserContext(
319 make_scoped_ptr(new CastBrowserContext(url_request_context_factory_
)));
320 cast_browser_process_
->SetMetricsServiceClient(
321 metrics::CastMetricsServiceClient::Create(
322 content::BrowserThread::GetBlockingPool(),
323 cast_browser_process_
->pref_service(),
324 cast_browser_process_
->browser_context()->GetRequestContext()));
326 if (!PlatformClientAuth::Initialize())
327 LOG(ERROR
) << "PlatformClientAuth::Initialize failed.";
329 cast_browser_process_
->SetRemoteDebuggingServer(
330 make_scoped_ptr(new RemoteDebuggingServer()));
332 media::MediaMessageLoop::GetTaskRunner()->PostTask(
334 base::Bind(&media::CastMediaShlib::Initialize
, cmd_line
->argv()));
335 ::media::InitializeMediaLibrary();
337 cast_browser_process_
->SetCastService(CastService::Create(
338 cast_browser_process_
->browser_context(),
339 cast_browser_process_
->pref_service(),
340 cast_browser_process_
->metrics_service_client(),
341 url_request_context_factory_
->GetSystemGetter()));
342 cast_browser_process_
->cast_service()->Initialize();
344 // Initializing metrics service and network delegates must happen after cast
345 // service is intialized because CastMetricsServiceClient and
346 // CastNetworkDelegate may use components initialized by cast service.
347 cast_browser_process_
->metrics_service_client()
348 ->Initialize(cast_browser_process_
->cast_service());
349 url_request_context_factory_
->InitializeNetworkDelegates();
351 cast_browser_process_
->cast_service()->Start();
354 bool CastBrowserMainParts::MainMessageLoopRun(int* result_code
) {
355 #if defined(OS_ANDROID)
356 // Android does not use native main MessageLoop.
360 base::RunLoop run_loop
;
361 base::Closure
quit_closure(run_loop
.QuitClosure());
362 RegisterClosureOnSignal(quit_closure
);
364 // If parameters_.ui_task is not NULL, we are running browser tests.
365 if (parameters_
.ui_task
) {
366 base::MessageLoop
* message_loop
= base::MessageLoopForUI::current();
367 message_loop
->PostTask(FROM_HERE
, *parameters_
.ui_task
);
368 message_loop
->PostTask(FROM_HERE
, quit_closure
);
373 // Once the main loop has stopped running, we give the browser process a few
374 // seconds to stop cast service and finalize all resources. If a hang occurs
375 // and cast services refuse to terminate successfully, then we SIGKILL the
376 // current process to avoid indefinte hangs.
377 RegisterKillOnAlarm(kKillOnAlarmTimeoutSec
);
379 cast_browser_process_
->cast_service()->Stop();
384 void CastBrowserMainParts::PostMainMessageLoopRun() {
385 #if defined(OS_ANDROID)
386 // Android does not use native main MessageLoop.
389 cast_browser_process_
->cast_service()->Finalize();
390 cast_browser_process_
->metrics_service_client()->Finalize();
391 cast_browser_process_
.reset();
393 #if defined(USE_AURA)
394 aura::Env::DeleteInstance();
397 DeregisterKillOnAlarm();
400 // Finalize CastMediaShlib on media thread to ensure it's not accessed
402 media::MediaMessageLoop::GetTaskRunner()->PostTask(
403 FROM_HERE
, base::Bind(&media::CastMediaShlib::Finalize
));
407 } // namespace chromecast