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_content_browser_client.h"
29 #include "chromecast/browser/cast_net_log.h"
30 #include "chromecast/browser/devtools/remote_debugging_server.h"
31 #include "chromecast/browser/metrics/cast_metrics_prefs.h"
32 #include "chromecast/browser/metrics/cast_metrics_service_client.h"
33 #include "chromecast/browser/pref_service_helper.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 "chromecast/service/cast_service.h"
42 #include "content/public/browser/browser_thread.h"
43 #include "content/public/browser/gpu_data_manager.h"
44 #include "content/public/common/content_switches.h"
45 #include "media/audio/audio_manager.h"
46 #include "media/audio/audio_manager_factory.h"
47 #include "media/base/browser_cdm_factory.h"
48 #include "media/base/media.h"
49 #include "ui/compositor/compositor_switches.h"
51 #if defined(OS_ANDROID)
52 #include "chromecast/app/android/crash_handler.h"
53 #include "chromecast/browser/media/cast_media_client_android.h"
54 #include "components/crash/browser/crash_dump_manager_android.h"
55 #include "media/base/android/media_client_android.h"
56 #include "net/android/network_change_notifier_factory_android.h"
58 #include "chromecast/browser/media/cast_browser_cdm_factory.h"
59 #include "chromecast/net/network_change_notifier_factory_cast.h"
63 #include "chromecast/graphics/cast_screen.h"
64 #include "ui/aura/env.h"
65 #include "ui/gfx/screen.h"
70 #if !defined(OS_ANDROID)
71 int kSignalsToRunClosure
[] = { SIGTERM
, SIGINT
, };
73 // Closure to run on SIGTERM and SIGINT.
74 base::Closure
* g_signal_closure
= NULL
;
76 void RunClosureOnSignal(int signum
) {
77 LOG(ERROR
) << "Got signal " << signum
;
78 DCHECK(g_signal_closure
);
79 // Expect main thread got this signal. Otherwise, weak_ptr of run_loop will
81 g_signal_closure
->Run();
84 void RegisterClosureOnSignal(const base::Closure
& closure
) {
85 DCHECK(!g_signal_closure
);
86 DCHECK_GT(arraysize(kSignalsToRunClosure
), 0U);
88 // Allow memory leak by intention.
89 g_signal_closure
= new base::Closure(closure
);
91 struct sigaction sa_new
;
92 memset(&sa_new
, 0, sizeof(sa_new
));
93 sa_new
.sa_handler
= RunClosureOnSignal
;
94 sigfillset(&sa_new
.sa_mask
);
95 sa_new
.sa_flags
= SA_RESTART
;
97 for (size_t i
= 0; i
< arraysize(kSignalsToRunClosure
); i
++) {
98 struct sigaction sa_old
;
99 if (sigaction(kSignalsToRunClosure
[i
], &sa_new
, &sa_old
) == -1) {
102 DCHECK_EQ(sa_old
.sa_handler
, SIG_DFL
);
106 // Get the first signal to exit when the parent process dies.
107 prctl(PR_SET_PDEATHSIG
, kSignalsToRunClosure
[0]);
110 const int kKillOnAlarmTimeoutSec
= 5; // 5 seconds
112 void KillOnAlarm(int signum
) {
113 LOG(ERROR
) << "Got alarm signal for termination: " << signum
;
117 void RegisterKillOnAlarm(int timeout_seconds
) {
118 struct sigaction sa_new
;
119 memset(&sa_new
, 0, sizeof(sa_new
));
120 sa_new
.sa_handler
= KillOnAlarm
;
121 sigfillset(&sa_new
.sa_mask
);
122 sa_new
.sa_flags
= SA_RESTART
;
124 struct sigaction sa_old
;
125 if (sigaction(SIGALRM
, &sa_new
, &sa_old
) == -1) {
128 DCHECK_EQ(sa_old
.sa_handler
, SIG_DFL
);
131 if (alarm(timeout_seconds
) > 0)
132 NOTREACHED() << "Previous alarm() was cancelled";
135 void DeregisterKillOnAlarm() {
136 // Explicitly cancel any outstanding alarm() calls.
139 struct sigaction sa_new
;
140 memset(&sa_new
, 0, sizeof(sa_new
));
141 sa_new
.sa_handler
= SIG_DFL
;
142 sigfillset(&sa_new
.sa_mask
);
143 sa_new
.sa_flags
= SA_RESTART
;
145 struct sigaction sa_old
;
146 if (sigaction(SIGALRM
, &sa_new
, &sa_old
) == -1) {
149 DCHECK_EQ(sa_old
.sa_handler
, KillOnAlarm
);
152 #endif // !defined(OS_ANDROID)
156 namespace chromecast
{
161 struct DefaultCommandLineSwitch
{
162 const char* const switch_name
;
163 const char* const switch_value
;
166 DefaultCommandLineSwitch g_default_switches
[] = {
167 #if defined(OS_ANDROID)
168 // Disables Chromecast-specific WiFi-related features on ATV for now.
169 { switches::kNoWifi
, "" },
170 { switches::kDisableGestureRequirementForMediaPlayback
, ""},
172 // Always enable HTMLMediaElement logs.
173 { switches::kBlinkPlatformLogChannels
, "Media"},
174 #if defined(DISABLE_DISPLAY)
175 { switches::kDisableGpu
, "" },
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
, "" },
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 // Needed so that our call to GpuDataManager::SetGLStrings doesn't race
194 // against GPU process creation (which is otherwise triggered from
195 // BrowserThreadsStarted). The GPU process will be created as soon as a
196 // renderer needs it, which always happens after main loop starts.
197 { switches::kDisableGpuEarlyInit
, "" },
198 { NULL
, NULL
}, // Termination
201 void AddDefaultCommandLineSwitches(base::CommandLine
* command_line
) {
203 while (g_default_switches
[i
].switch_name
!= NULL
) {
204 command_line
->AppendSwitchASCII(
205 std::string(g_default_switches
[i
].switch_name
),
206 std::string(g_default_switches
[i
].switch_value
));
213 CastBrowserMainParts::CastBrowserMainParts(
214 const content::MainFunctionParams
& parameters
,
215 URLRequestContextFactory
* url_request_context_factory
,
216 scoped_ptr
<::media::AudioManagerFactory
> audio_manager_factory
)
217 : BrowserMainParts(),
218 cast_browser_process_(new CastBrowserProcess()),
219 parameters_(parameters
),
220 url_request_context_factory_(url_request_context_factory
),
221 audio_manager_factory_(audio_manager_factory
.Pass()),
222 net_log_(new CastNetLog()) {
223 base::CommandLine
* command_line
= base::CommandLine::ForCurrentProcess();
224 AddDefaultCommandLineSwitches(command_line
);
227 CastBrowserMainParts::~CastBrowserMainParts() {
230 void CastBrowserMainParts::PreMainMessageLoopStart() {
231 // GroupedHistograms needs to be initialized before any threads are created
232 // to prevent race conditions between calls to Preregister and those threads
233 // attempting to collect metrics.
234 // This call must also be before NetworkChangeNotifier, as it generates
236 metrics::PreregisterAllGroupedHistograms();
238 // Set the platform's implementation of AudioManagerFactory.
239 if (audio_manager_factory_
)
240 ::media::AudioManager::SetFactory(audio_manager_factory_
.release());
242 #if defined(OS_ANDROID)
243 net::NetworkChangeNotifier::SetFactory(
244 new net::NetworkChangeNotifierFactoryAndroid());
246 net::NetworkChangeNotifier::SetFactory(
247 new NetworkChangeNotifierFactoryCast());
248 #endif // defined(OS_ANDROID)
251 void CastBrowserMainParts::PostMainMessageLoopStart() {
252 cast_browser_process_
->SetMetricsHelper(make_scoped_ptr(
253 new metrics::CastMetricsHelper(base::ThreadTaskRunnerHandle::Get())));
255 #if defined(OS_ANDROID)
256 base::MessageLoopForUI::current()->Start();
257 #endif // defined(OS_ANDROID)
260 int CastBrowserMainParts::PreCreateThreads() {
261 #if defined(OS_ANDROID)
262 // GPU process is started immediately after threads are created, requiring
263 // CrashDumpManager to be initialized beforehand.
264 base::FilePath crash_dumps_dir
;
265 if (!chromecast::CrashHandler::GetCrashDumpLocation(&crash_dumps_dir
)) {
266 LOG(ERROR
) << "Could not find crash dump location.";
268 cast_browser_process_
->SetCrashDumpManager(
269 make_scoped_ptr(new breakpad::CrashDumpManager(crash_dumps_dir
)));
271 base::FilePath home_dir
;
272 CHECK(PathService::Get(DIR_CAST_HOME
, &home_dir
));
273 if (!base::CreateDirectory(home_dir
))
277 #if defined(USE_AURA)
278 // Screen can (and should) exist even with no displays connected. Its presence
279 // is assumed as an interface to access display information, e.g. from metrics
280 // code. See CastContentWindow::CreateWindowTree for update when resolution
282 cast_browser_process_
->SetCastScreen(make_scoped_ptr(new CastScreen
));
283 DCHECK(!gfx::Screen::GetScreenByType(gfx::SCREEN_TYPE_NATIVE
));
284 gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_NATIVE
,
285 cast_browser_process_
->cast_screen());
290 void CastBrowserMainParts::PreMainMessageLoopRun() {
291 #if !defined(OS_ANDROID)
292 // Set GL strings so GPU config code can make correct feature blacklisting/
293 // whitelisting decisions.
294 // Note: SetGLStrings MUST be called after GpuDataManager::Initialize.
295 scoped_ptr
<CastSysInfo
> sys_info
= CreateSysInfo();
296 content::GpuDataManager::GetInstance()->SetGLStrings(
297 sys_info
->GetGlVendor(), sys_info
->GetGlRenderer(),
298 sys_info
->GetGlVersion());
299 #endif // !defined(OS_ANDROID)
301 scoped_refptr
<PrefRegistrySimple
> pref_registry(new PrefRegistrySimple());
302 metrics::RegisterPrefs(pref_registry
.get());
303 cast_browser_process_
->SetPrefService(
304 PrefServiceHelper::CreatePrefService(pref_registry
.get()));
306 const base::CommandLine
* cmd_line
= base::CommandLine::ForCurrentProcess();
307 #if defined(OS_ANDROID)
308 ::media::SetMediaClientAndroid(new media::CastMediaClientAndroid());
310 if (cmd_line
->HasSwitch(switches::kEnableCmaMediaPipeline
))
311 ::media::SetBrowserCdmFactory(new media::CastBrowserCdmFactory());
312 #endif // defined(OS_ANDROID)
314 cast_browser_process_
->SetConnectivityChecker(
315 ConnectivityChecker::Create(
316 content::BrowserThread::GetMessageLoopProxyForThread(
317 content::BrowserThread::IO
)));
319 cast_browser_process_
->SetNetLog(net_log_
.get());
321 url_request_context_factory_
->InitializeOnUIThread(net_log_
.get());
323 cast_browser_process_
->SetBrowserContext(
324 make_scoped_ptr(new CastBrowserContext(url_request_context_factory_
)));
325 cast_browser_process_
->SetMetricsServiceClient(
326 metrics::CastMetricsServiceClient::Create(
327 content::BrowserThread::GetBlockingPool(),
328 cast_browser_process_
->pref_service(),
329 cast_browser_process_
->browser_context()->GetRequestContext()));
331 if (!PlatformClientAuth::Initialize())
332 LOG(ERROR
) << "PlatformClientAuth::Initialize failed.";
334 cast_browser_process_
->SetRemoteDebuggingServer(
335 make_scoped_ptr(new RemoteDebuggingServer()));
337 media::MediaMessageLoop::GetTaskRunner()->PostTask(
339 base::Bind(&media::CastMediaShlib::Initialize
, cmd_line
->argv()));
340 ::media::InitializeMediaLibrary();
342 cast_browser_process_
->SetCastService(
343 cast_browser_process_
->browser_client()->CreateCastService(
344 cast_browser_process_
->browser_context(),
345 cast_browser_process_
->pref_service(),
346 url_request_context_factory_
->GetSystemGetter()));
347 cast_browser_process_
->cast_service()->Initialize();
349 // Initializing metrics service and network delegates must happen after cast
350 // service is intialized because CastMetricsServiceClient and
351 // CastNetworkDelegate may use components initialized by cast service.
352 cast_browser_process_
->metrics_service_client()
353 ->Initialize(cast_browser_process_
->cast_service());
354 url_request_context_factory_
->InitializeNetworkDelegates();
356 cast_browser_process_
->cast_service()->Start();
359 bool CastBrowserMainParts::MainMessageLoopRun(int* result_code
) {
360 #if defined(OS_ANDROID)
361 // Android does not use native main MessageLoop.
365 base::RunLoop run_loop
;
366 base::Closure
quit_closure(run_loop
.QuitClosure());
367 RegisterClosureOnSignal(quit_closure
);
369 // If parameters_.ui_task is not NULL, we are running browser tests.
370 if (parameters_
.ui_task
) {
371 base::MessageLoop
* message_loop
= base::MessageLoopForUI::current();
372 message_loop
->PostTask(FROM_HERE
, *parameters_
.ui_task
);
373 message_loop
->PostTask(FROM_HERE
, quit_closure
);
378 // Once the main loop has stopped running, we give the browser process a few
379 // seconds to stop cast service and finalize all resources. If a hang occurs
380 // and cast services refuse to terminate successfully, then we SIGKILL the
381 // current process to avoid indefinte hangs.
382 RegisterKillOnAlarm(kKillOnAlarmTimeoutSec
);
384 cast_browser_process_
->cast_service()->Stop();
389 void CastBrowserMainParts::PostMainMessageLoopRun() {
390 #if defined(OS_ANDROID)
391 // Android does not use native main MessageLoop.
394 cast_browser_process_
->cast_service()->Finalize();
395 cast_browser_process_
->metrics_service_client()->Finalize();
396 cast_browser_process_
.reset();
398 #if defined(USE_AURA)
399 aura::Env::DeleteInstance();
402 DeregisterKillOnAlarm();
407 } // namespace chromecast