1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/renderer/render_thread_impl.h"
14 #include "base/allocator/allocator_extension.h"
15 #include "base/allocator/partition_alloc_support.h"
16 #include "base/at_exit.h"
17 #include "base/command_line.h"
18 #include "base/containers/contains.h"
19 #include "base/debug/crash_logging.h"
20 #include "base/feature_list.h"
21 #include "base/functional/bind.h"
22 #include "base/functional/callback_helpers.h"
23 #include "base/lazy_instance.h"
24 #include "base/logging.h"
25 #include "base/memory/discardable_memory_allocator.h"
26 #include "base/memory/scoped_refptr.h"
27 #include "base/message_loop/message_pump_type.h"
28 #include "base/metrics/field_trial.h"
29 #include "base/metrics/histogram_functions.h"
30 #include "base/metrics/histogram_macros.h"
31 #include "base/metrics/histogram_macros_local.h"
32 #include "base/observer_list.h"
33 #include "base/path_service.h"
34 #include "base/process/process_metrics.h"
35 #include "base/ranges/algorithm.h"
36 #include "base/run_loop.h"
37 #include "base/strings/string_number_conversions.h"
38 #include "base/strings/string_split.h"
39 #include "base/strings/sys_string_conversions.h"
40 #include "base/strings/utf_string_conversions.h"
41 #include "base/synchronization/waitable_event.h"
42 #include "base/task/bind_post_task.h"
43 #include "base/task/sequenced_task_runner.h"
44 #include "base/task/single_thread_task_runner.h"
45 #include "base/task/task_traits.h"
46 #include "base/task/thread_pool.h"
47 #include "base/threading/simple_thread.h"
48 #include "base/threading/thread_restrictions.h"
49 #include "base/trace_event/memory_dump_manager.h"
50 #include "base/trace_event/memory_pressure_level_proto.h"
51 #include "base/trace_event/trace_event.h"
52 #include "base/trace_event/typed_macros.h"
53 #include "base/values.h"
54 #include "build/build_config.h"
55 #include "build/chromeos_buildflags.h"
56 #include "cc/base/histograms.h"
57 #include "cc/base/switches.h"
58 #include "cc/mojo_embedder/async_layer_tree_frame_sink.h"
59 #include "cc/raster/task_graph_runner.h"
60 #include "cc/tiles/image_decode_cache_utils.h"
61 #include "cc/trees/layer_tree_frame_sink.h"
62 #include "cc/trees/layer_tree_settings.h"
63 #include "cc/trees/raster_context_provider_wrapper.h"
64 #include "cc/trees/ukm_manager.h"
65 #include "components/discardable_memory/client/client_discardable_shared_memory_manager.h"
66 #include "components/metrics/public/mojom/single_sample_metrics.mojom.h"
67 #include "components/metrics/single_sample_metrics.h"
68 #include "components/viz/common/features.h"
69 #include "components/viz/common/frame_sinks/copy_output_request.h"
70 #include "components/viz/common/switches.h"
71 #include "content/child/runtime_features.h"
72 #include "content/common/buildflags.h"
73 #include "content/common/content_constants_internal.h"
74 #include "content/common/content_switches_internal.h"
75 #include "content/common/features.h"
76 #include "content/common/main_frame_counter.h"
77 #include "content/common/process_visibility_tracker.h"
78 #include "content/common/pseudonymization_salt.h"
79 #include "content/public/common/content_client.h"
80 #include "content/public/common/content_constants.h"
81 #include "content/public/common/content_features.h"
82 #include "content/public/common/content_paths.h"
83 #include "content/public/common/content_switches.h"
84 #include "content/public/common/gpu_stream_constants.h"
85 #include "content/public/common/url_constants.h"
86 #include "content/public/renderer/content_renderer_client.h"
87 #include "content/public/renderer/render_frame.h"
88 #include "content/public/renderer/render_thread_observer.h"
89 #include "content/renderer/agent_scheduling_group.h"
90 #include "content/renderer/browser_exposed_renderer_interfaces.h"
91 #include "content/renderer/effective_connection_type_helper.h"
92 #include "content/renderer/media/codec_factory.h"
93 #include "content/renderer/media/gpu/gpu_video_accelerator_factories_impl.h"
94 #include "content/renderer/media/media_factory.h"
95 #include "content/renderer/media/render_media_client.h"
96 #include "content/renderer/net_info_helper.h"
97 #include "content/renderer/render_process_impl.h"
98 #include "content/renderer/renderer_blink_platform_impl.h"
99 #include "content/renderer/service_worker/service_worker_context_client.h"
100 #include "content/renderer/variations_render_thread_observer.h"
101 #include "content/renderer/worker/embedded_shared_worker_stub.h"
102 #include "content/renderer/worker/worker_thread_registry.h"
103 #include "device/gamepad/public/cpp/gamepads.h"
104 #include "gin/public/debug.h"
105 #include "gpu/GLES2/gl2extchromium.h"
106 #include "gpu/command_buffer/client/context_support.h"
107 #include "gpu/command_buffer/client/gles2_interface.h"
108 #include "gpu/command_buffer/client/raster_interface.h"
109 #include "gpu/command_buffer/client/shared_memory_limits.h"
110 #include "gpu/config/gpu_driver_bug_workarounds.h"
111 #include "gpu/config/gpu_finch_features.h"
112 #include "gpu/config/gpu_switches.h"
113 #include "gpu/ipc/client/command_buffer_proxy_impl.h"
114 #include "gpu/ipc/client/gpu_channel_host.h"
115 #include "ipc/ipc_channel_handle.h"
116 #include "ipc/ipc_channel_mojo.h"
117 #include "ipc/ipc_platform_file.h"
118 #include "media/base/decoder_factory.h"
119 #include "media/base/media.h"
120 #include "media/base/media_switches.h"
121 #include "media/media_buildflags.h"
122 #include "media/renderers/default_decoder_factory.h"
123 #include "media/video/gpu_video_accelerator_factories.h"
124 #include "mojo/public/cpp/bindings/binder_map.h"
125 #include "mojo/public/cpp/bindings/callback_helpers.h"
126 #include "mojo/public/cpp/bindings/pending_receiver.h"
127 #include "mojo/public/cpp/bindings/self_owned_receiver.h"
128 #include "mojo/public/cpp/system/message_pipe.h"
129 #include "net/base/net_errors.h"
130 #include "net/base/port_util.h"
131 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
132 #include "net/base/url_util.h"
133 #include "ppapi/buildflags/buildflags.h"
134 #include "services/metrics/public/cpp/mojo_ukm_recorder.h"
135 #include "services/metrics/public/cpp/ukm_recorder.h"
136 #include "services/network/public/cpp/network_switches.h"
137 #include "services/service_manager/public/cpp/interface_provider.h"
138 #include "services/viz/public/cpp/gpu/context_provider_command_buffer.h"
139 #include "services/viz/public/cpp/gpu/gpu.h"
140 #include "skia/ext/skia_memory_dump_provider.h"
141 #include "third_party/abseil-cpp/absl/base/attributes.h"
142 #include "third_party/blink/public/common/features.h"
143 #include "third_party/blink/public/common/origin_trials/origin_trials_settings_provider.h"
144 #include "third_party/blink/public/common/page/launching_process_state.h"
145 #include "third_party/blink/public/common/privacy_budget/active_sampling.h"
146 #include "third_party/blink/public/common/privacy_budget/identifiability_study_settings.h"
147 #include "third_party/blink/public/common/switches.h"
148 #include "third_party/blink/public/mojom/origin_trials/origin_trials_settings.mojom.h"
149 #include "third_party/blink/public/platform/modules/video_capture/web_video_capture_impl_manager.h"
150 #include "third_party/blink/public/platform/scheduler/web_thread_scheduler.h"
151 #include "third_party/blink/public/platform/web_cache.h"
152 #include "third_party/blink/public/platform/web_image_generator.h"
153 #include "third_party/blink/public/platform/web_memory_pressure_listener.h"
154 #include "third_party/blink/public/platform/web_network_state_notifier.h"
155 #include "third_party/blink/public/platform/web_runtime_features.h"
156 #include "third_party/blink/public/platform/web_scoped_page_pauser.h"
157 #include "third_party/blink/public/platform/web_string.h"
158 #include "third_party/blink/public/platform/web_theme_engine.h"
159 #include "third_party/blink/public/web/blink.h"
160 #include "third_party/blink/public/web/web_document.h"
161 #include "third_party/blink/public/web/web_frame.h"
162 #include "third_party/blink/public/web/web_render_theme.h"
163 #include "third_party/blink/public/web/web_security_policy.h"
164 #include "third_party/blink/public/web/web_user_level_memory_pressure_signal_generator.h"
165 #include "third_party/blink/public/web/web_view.h"
166 #include "third_party/skia/include/core/SkFontMgr.h"
167 #include "third_party/skia/include/core/SkGraphics.h"
168 #include "ui/base/ui_base_features.h"
169 #include "ui/base/ui_base_switches.h"
170 #include "ui/base/ui_base_switches_util.h"
171 #include "ui/display/display_switches.h"
172 #include "v8/include/v8-extension.h"
174 #if BUILDFLAG(IS_ANDROID)
175 #include <cpu-features.h>
176 #include "content/renderer/media/android/stream_texture_factory.h"
177 #include "media/base/android/media_codec_util.h"
180 #if BUILDFLAG(IS_MAC)
181 #include "base/mac/mac_util.h"
182 #include "content/renderer/theme_helper_mac.h"
185 #if BUILDFLAG(IS_WIN)
188 #include "content/renderer/media/win/dcomp_texture_factory.h"
189 #include "content/renderer/media/win/overlay_state_service_provider.h"
190 #include "media/base/win/mf_feature_checks.h"
193 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
194 #include "content/child/sandboxed_process_thread_type_handler.h"
197 #ifdef ENABLE_VTUNE_JIT_INTERFACE
198 #include "v8/src/third_party/vtune/v8-vtune.h"
201 #if defined(ENABLE_IPC_FUZZER)
202 #include "content/common/external_ipc_dumper.h"
203 #include "mojo/public/cpp/bindings/message_dumper.h"
206 #if BUILDFLAG(IS_APPLE)
207 #include <malloc/malloc.h>
212 #if BUILDFLAG(ENABLE_MOJO_VIDEO_DECODER)
213 #include "content/renderer/media/codec_factory_mojo.h"
214 #include "media/mojo/mojom/interface_factory.mojom.h"
217 #if BUILDFLAG(IS_FUCHSIA)
218 #include "content/renderer/media/codec_factory_fuchsia.h"
219 #include "media/mojo/mojom/fuchsia_media.mojom.h"
222 #if BUILDFLAG(CLANG_PROFILING_INSIDE_SANDBOX)
223 #include "base/test/clang_profiling.h"
230 using ::base::PassKey;
231 using ::blink::WebDocument;
232 using ::blink::WebFrame;
233 using ::blink::WebNetworkStateNotifier;
234 using ::blink::WebRuntimeFeatures;
235 using ::blink::WebSecurityPolicy;
236 using ::blink::WebString;
237 using ::blink::WebView;
239 // An implementation of mojom::RenderMessageFilter which can be mocked out
240 // for tests which may indirectly send messages over this interface.
241 mojom::RenderMessageFilter* g_render_message_filter_for_testing;
243 // An implementation of RendererBlinkPlatformImpl which can be mocked out
245 RendererBlinkPlatformImpl* g_current_blink_platform_impl_for_testing;
247 // Keep the global RenderThreadImpl in a TLS slot so it is impossible to access
248 // incorrectly from the wrong thread.
249 ABSL_CONST_INIT thread_local RenderThreadImpl* render_thread = nullptr;
251 base::LazyInstance<scoped_refptr<base::SingleThreadTaskRunner>>::
252 DestructorAtExit g_main_task_runner = LAZY_INSTANCE_INITIALIZER;
254 // v8::MemoryPressureLevel should correspond to base::MemoryPressureListener.
255 static_assert(static_cast<v8::MemoryPressureLevel>(
256 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE) ==
257 v8::MemoryPressureLevel::kNone,
258 "none level not align");
260 static_cast<v8::MemoryPressureLevel>(
261 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE) ==
262 v8::MemoryPressureLevel::kModerate,
263 "moderate level not align");
265 static_cast<v8::MemoryPressureLevel>(
266 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL) ==
267 v8::MemoryPressureLevel::kCritical,
268 "critical level not align");
270 // Feature to migrate the Media thread to a SequencedTaskRunner backed from
271 // the base::ThreadPool. Does not currently work on Fuchsia due to FIDL
272 // requiring thread affinity.
273 BASE_DECLARE_FEATURE(kUseThreadPoolForMediaTaskRunner){
274 "UseThreadPoolForMediaTaskRunner", base::FEATURE_DISABLED_BY_DEFAULT};
276 // Updates the crash key for whether this renderer is foregrounded.
277 void UpdateForegroundCrashKey(bool foreground) {
278 static auto* const crash_key = base::debug::AllocateCrashKeyString(
279 "renderer_foreground", base::debug::CrashKeySize::Size32);
280 base::debug::SetCrashKeyString(crash_key, foreground ? "true" : "false");
283 scoped_refptr<viz::ContextProviderCommandBuffer> CreateOffscreenContext(
284 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host,
285 const gpu::SharedMemoryLimits& limits,
286 bool support_locking,
287 bool support_gles2_interface,
288 bool support_raster_interface,
289 bool support_oop_rasterization,
290 bool support_grcontext,
291 bool automatic_flushes,
292 viz::command_buffer_metrics::ContextType type,
294 gpu::SchedulingPriority stream_priority) {
295 DCHECK(gpu_channel_host);
296 // This is used to create a few different offscreen contexts:
297 // - The shared main thread context, used by blink for 2D Canvas.
298 // - The compositor worker context, used for GPU raster.
299 // - The media context, used for accelerated video decoding.
300 // This is for an offscreen context, so the default framebuffer doesn't need
301 // alpha, depth, stencil, antialiasing.
302 gpu::ContextCreationAttribs attributes;
303 attributes.bind_generates_resource = false;
304 attributes.lose_context_when_out_of_memory = true;
305 attributes.enable_gles2_interface = support_gles2_interface;
306 attributes.enable_raster_interface = support_raster_interface;
307 attributes.enable_grcontext = support_grcontext;
308 // Using RasterDecoder for OOP-R backend, so we need support_raster_interface
309 // and !support_gles2_interface.
310 attributes.enable_oop_rasterization = support_oop_rasterization &&
311 support_raster_interface &&
312 !support_gles2_interface;
313 return base::MakeRefCounted<viz::ContextProviderCommandBuffer>(
314 std::move(gpu_channel_host), stream_id, stream_priority,
315 gpu::kNullSurfaceHandle,
316 GURL("chrome://gpu/RenderThreadImpl::CreateOffscreenContext/" +
317 viz::command_buffer_metrics::ContextTypeToString(type)),
318 automatic_flushes, support_locking, support_grcontext, limits, attributes,
322 // Hook that allows single-sample metric code from //components/metrics to
323 // connect from the renderer process to the browser process.
324 void CreateSingleSampleMetricsProvider(
325 mojo::SharedRemote<mojom::ChildProcessHost> process_host,
326 mojo::PendingReceiver<metrics::mojom::SingleSampleMetricsProvider>
328 process_host->BindHostReceiver(std::move(receiver));
331 static bool IsSingleProcess() {
332 return base::CommandLine::ForCurrentProcess()->HasSwitch(
333 switches::kSingleProcess);
338 RenderThreadImpl::HistogramCustomizer::HistogramCustomizer() {
339 custom_histograms_.insert("V8.MemoryHeapSampleTotalCommitted");
342 RenderThreadImpl::HistogramCustomizer::~HistogramCustomizer() {}
344 void RenderThreadImpl::HistogramCustomizer::RenderViewNavigatedToHost(
345 const std::string& host,
347 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
348 switches::kDisableHistogramCustomizer)) {
351 // Check if all RenderViews are displaying a page from the same host. If there
352 // is only one RenderView, the common host is this view's host. If there are
353 // many, check if this one shares the common host of the other
354 // RenderViews. It's ok to not detect some cases where the RenderViews share a
355 // common host. This information is only used for producing custom histograms.
358 else if (host != common_host_)
359 SetCommonHost(std::string());
362 std::string RenderThreadImpl::HistogramCustomizer::ConvertToCustomHistogramName(
363 const char* histogram_name) const {
364 std::string name(histogram_name);
365 if (!common_host_histogram_suffix_.empty() &&
366 base::Contains(custom_histograms_, name)) {
367 name += common_host_histogram_suffix_;
372 void RenderThreadImpl::HistogramCustomizer::SetCommonHost(
373 const std::string& host) {
374 if (host != common_host_) {
376 common_host_histogram_suffix_ = HostToCustomHistogramSuffix(host);
380 std::string RenderThreadImpl::HistogramCustomizer::HostToCustomHistogramSuffix(
381 const std::string& host) {
382 if (host == "mail.google.com")
384 if (host == "docs.google.com" || host == "drive.google.com")
386 if (host == "plus.google.com")
388 if (host == "inbox.google.com")
390 if (host == "calendar.google.com")
392 if (host == "www.youtube.com")
394 if (IsAlexaTop10NonGoogleSite(host))
397 return std::string();
400 bool RenderThreadImpl::HistogramCustomizer::IsAlexaTop10NonGoogleSite(
401 const std::string& host) {
402 // The Top10 sites have different TLD and/or subdomains depending on the
404 if (host == "sina.com.cn")
407 std::string sanitized_host =
408 net::registry_controlled_domains::GetDomainAndRegistry(
409 host, net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
411 if (sanitized_host == "facebook.com")
413 if (sanitized_host == "baidu.com")
415 if (sanitized_host == "qq.com")
417 if (sanitized_host == "twitter.com")
419 if (sanitized_host == "taobao.com")
421 if (sanitized_host == "live.com")
424 if (!sanitized_host.empty()) {
425 std::vector<base::StringPiece> host_tokens = base::SplitStringPiece(
426 sanitized_host, ".", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
428 if (host_tokens.size() >= 2) {
429 if ((host_tokens[0] == "yahoo") || (host_tokens[0] == "amazon") ||
430 (host_tokens[0] == "wikipedia")) {
439 RenderThreadImpl* RenderThreadImpl::current() {
440 return render_thread;
444 mojom::RenderMessageFilter* RenderThreadImpl::current_render_message_filter() {
445 if (g_render_message_filter_for_testing)
446 return g_render_message_filter_for_testing;
448 return current()->render_message_filter();
452 RendererBlinkPlatformImpl* RenderThreadImpl::current_blink_platform_impl() {
453 if (g_current_blink_platform_impl_for_testing)
454 return g_current_blink_platform_impl_for_testing;
456 return current()->blink_platform_impl();
460 void RenderThreadImpl::SetRenderMessageFilterForTesting(
461 mojom::RenderMessageFilter* render_message_filter) {
462 g_render_message_filter_for_testing = render_message_filter;
466 void RenderThreadImpl::SetRendererBlinkPlatformImplForTesting(
467 RendererBlinkPlatformImpl* blink_platform_impl) {
468 g_current_blink_platform_impl_for_testing = blink_platform_impl;
472 scoped_refptr<base::SingleThreadTaskRunner>
473 RenderThreadImpl::DeprecatedGetMainTaskRunner() {
474 return g_main_task_runner.Get();
477 // In single-process mode used for debugging, we don't pass a renderer client
478 // ID via command line because RenderThreadImpl lives in the same process as
480 RenderThreadImpl::RenderThreadImpl(
481 const InProcessChildThreadParams& params,
483 std::unique_ptr<blink::scheduler::WebThreadScheduler> scheduler)
487 .InBrowserProcess(params)
488 .ConnectToBrowser(true)
489 .IPCTaskRunner(scheduler->DeprecatedDefaultTaskRunner())
490 .ExposesInterfacesToBrowser()
492 main_thread_scheduler_(std::move(scheduler)),
493 client_id_(client_id) {
494 TRACE_EVENT0("startup", "RenderThreadImpl::Create");
499 int32_t GetClientIdFromCommandLine() {
500 DCHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
501 switches::kRendererClientId));
503 base::StringToInt(base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
504 switches::kRendererClientId),
508 } // anonymous namespace
510 // Multi-process mode.
511 RenderThreadImpl::RenderThreadImpl(
512 base::RepeatingClosure quit_closure,
513 std::unique_ptr<blink::scheduler::WebThreadScheduler> scheduler)
515 std::move(quit_closure),
517 .ConnectToBrowser(true)
518 .IPCTaskRunner(scheduler->DeprecatedDefaultTaskRunner())
519 .ExposesInterfacesToBrowser()
521 main_thread_scheduler_(std::move(scheduler)),
522 client_id_(GetClientIdFromCommandLine()) {
523 TRACE_EVENT0("startup", "RenderThreadImpl::Create");
527 void RenderThreadImpl::Init() {
528 TRACE_EVENT0("startup", "RenderThreadImpl::Init");
530 SCOPED_UMA_HISTOGRAM_TIMER("Renderer.RenderThreadImpl.Init");
532 GetContentClient()->renderer()->PostIOThreadCreated(GetIOTaskRunner().get());
534 base::trace_event::TraceLog::GetInstance()->SetThreadSortIndex(
535 base::PlatformThread::CurrentId(),
536 kTraceEventRendererMainThreadSortIndex);
538 #if BUILDFLAG(USE_EXTERNAL_POPUP_MENU)
539 // On Mac and Android Java UI, the select popups are rendered by the browser.
540 #if BUILDFLAG(IS_MAC)
541 // When UseCommonSelectPopup is enabled, the internal popup menu should be
543 if (!features::IsUseCommonSelectPopupEnabled())
545 blink::WebView::SetUseExternalPopupMenus(true);
548 render_thread = this;
549 g_main_task_runner.Get() = base::SingleThreadTaskRunner::GetCurrentDefault();
550 #if BUILDFLAG(IS_EFL)
551 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
552 blink::switches::kUseInternalPopupMenu)) {
553 blink::WebView::SetUseExternalPopupMenus(false);
558 // Register this object as the main thread.
559 ChildProcess::current()->set_main_thread(this);
561 metrics::InitializeSingleSampleMetricsFactory(base::BindRepeating(
562 &CreateSingleSampleMetricsProvider, child_process_host()));
564 mojo::PendingRemote<viz::mojom::Gpu> remote_gpu;
565 BindHostReceiver(remote_gpu.InitWithNewPipeAndPassReceiver());
566 gpu_ = viz::Gpu::Create(std::move(remote_gpu), GetIOTaskRunner());
568 // Establish the GPU channel now, so its ready when needed and we don't have
569 // to wait on a sync call.
570 if (base::FeatureList::IsEnabled(features::kEarlyEstablishGpuChannel)) {
571 gpu_->EstablishGpuChannel(
572 base::BindOnce([](scoped_refptr<gpu::GpuChannelHost> host) {
574 GetContentClient()->SetGpuInfo(host->gpu_info());
578 // NOTE: Do not add interfaces to |binders| within this method. Instead,
579 // modify the definition of |ExposeRendererInterfacesToBrowser()| to ensure
580 // security review coverage.
581 mojo::BinderMap binders;
582 InitializeWebKit(&binders);
584 vc_manager_ = std::make_unique<blink::WebVideoCaptureImplManager>();
586 GetContentClient()->renderer()->RenderThreadStarted();
587 ExposeRendererInterfacesToBrowser(weak_factory_.GetWeakPtr(), &binders);
588 ExposeInterfacesToBrowser(std::move(binders));
590 url_loader_throttle_provider_ =
591 GetContentClient()->renderer()->CreateURLLoaderThrottleProvider(
592 blink::URLLoaderThrottleProviderType::kFrame);
594 GetAssociatedInterfaceRegistry()->AddInterface<mojom::Renderer>(
595 base::BindRepeating(&RenderThreadImpl::OnRendererInterfaceReceiver,
596 base::Unretained(this)));
598 const base::CommandLine& command_line =
599 *base::CommandLine::ForCurrentProcess();
601 #if defined(ENABLE_IPC_FUZZER)
602 if (command_line.HasSwitch(switches::kIpcDumpDirectory)) {
603 base::FilePath dump_directory =
604 command_line.GetSwitchValuePath(switches::kIpcDumpDirectory);
605 IPC::ChannelProxy::OutgoingMessageFilter* filter =
606 LoadExternalIPCDumper(dump_directory);
607 GetChannel()->set_outgoing_message_filter(filter);
608 mojo::MessageDumper::SetMessageDumpDirectory(dump_directory);
612 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
613 SandboxedProcessThreadTypeHandler::NotifyMainChildThreadCreated();
616 cc::SetClientNameForMetrics("Renderer");
618 is_threaded_animation_enabled_ =
619 !command_line.HasSwitch(cc::switches::kDisableThreadedAnimation);
621 is_elastic_overscroll_enabled_ = switches::IsElasticOverscrollEnabled();
623 if (command_line.HasSwitch(switches::kDisableLCDText)) {
624 is_lcd_text_enabled_ = false;
625 } else if (command_line.HasSwitch(switches::kEnableLCDText)) {
626 is_lcd_text_enabled_ = true;
628 #if BUILDFLAG(IS_ANDROID)
629 is_lcd_text_enabled_ = false;
630 #elif BUILDFLAG(IS_MAC)
631 is_lcd_text_enabled_ = IsSubpixelAntialiasingAvailable();
633 is_lcd_text_enabled_ = true;
637 if (command_line.HasSwitch(switches::kDisableGpuCompositing))
638 is_gpu_compositing_disabled_ = true;
640 // Note that under Linux, the media library will normally already have
641 // been initialized by the Zygote before this instance became a Renderer.
642 media::InitializeMediaLibrary();
644 memory_pressure_listener_ = std::make_unique<base::MemoryPressureListener>(
646 base::BindRepeating(&RenderThreadImpl::OnMemoryPressure,
647 base::Unretained(this)),
648 base::BindRepeating(&RenderThreadImpl::OnSyncMemoryPressure,
649 base::Unretained(this)));
651 discardable_memory_allocator_ = CreateDiscardableMemoryAllocator();
653 // TODO(boliu): In single process, browser main loop should set up the
654 // discardable memory manager, and should skip this if kSingleProcess.
655 // See crbug.com/503724.
656 base::DiscardableMemoryAllocator::SetInstance(
657 discardable_memory_allocator_.get());
659 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
660 // The SandboxedProcessThreadTypeHandler isn't created in
661 // render_thread_impl_browsertest.cc, nor in --single-process mode.
662 if (SandboxedProcessThreadTypeHandler* sandboxed_process_thread_type_handler =
663 SandboxedProcessThreadTypeHandler::Get()) {
664 sandboxed_process_thread_type_handler->HandleThreadTypeChange(
665 ChildProcess::current()->io_thread_id(),
666 base::ThreadType::kCompositing);
670 process_foregrounded_count_ = 0;
672 if (!is_gpu_compositing_disabled_) {
673 BindHostReceiver(compositing_mode_reporter_.BindNewPipeAndPassReceiver());
675 compositing_mode_reporter_->AddCompositingModeWatcher(
676 compositing_mode_watcher_receiver_.BindNewPipeAndPassRemote(
677 main_thread_scheduler_->CompositorTaskRunner()));
680 variations_observer_ = std::make_unique<VariationsRenderThreadObserver>();
681 AddObserver(variations_observer_.get());
683 base::ThreadPool::PostTask(FROM_HERE,
684 base::BindOnce([] { SkFontMgr::RefDefault(); }));
686 bool should_actively_sample_fonts =
687 command_line.HasSwitch(kFirstRendererProcess) &&
688 blink::IdentifiabilityStudySettings::Get()->ShouldActivelySample() &&
689 !blink::IdentifiabilityStudySettings::Get()
690 ->FontFamiliesToActivelySample()
692 if (should_actively_sample_fonts) {
693 mojo::PendingRemote<ukm::mojom::UkmRecorderFactory> pending_factory;
694 RenderThread::Get()->BindHostReceiver(
695 pending_factory.InitWithNewPipeAndPassReceiver());
696 scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner =
697 base::ThreadPool::CreateSequencedTaskRunner(
698 {base::TaskPriority::BEST_EFFORT, base::MayBlock(),
699 base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN});
700 sequenced_task_runner->PostTask(
703 [](mojo::PendingRemote<ukm::mojom::UkmRecorderFactory>
705 mojo::Remote<ukm::mojom::UkmRecorderFactory> factory(
706 std::move(pending_factory));
707 auto ukm_recorder = ukm::MojoUkmRecorder::Create(*factory);
708 blink::IdentifiabilityActiveSampler::ActivelySampleAvailableFonts(
711 std::move(pending_factory)));
713 UpdateForegroundCrashKey(
714 /*foreground=*/!blink::kLaunchingProcessIsBackgrounded);
717 RenderThreadImpl::~RenderThreadImpl() {
718 g_main_task_runner.Get() = nullptr;
720 // Need to make sure this reference is removed on the correct task runner;
721 if (video_frame_compositor_thread_ &&
722 video_frame_compositor_context_provider_) {
723 video_frame_compositor_thread_->task_runner()->ReleaseSoon(
724 FROM_HERE, std::move(video_frame_compositor_context_provider_));
728 void RenderThreadImpl::Shutdown() {
729 ChildThreadImpl::Shutdown();
730 // In a multi-process mode, we immediately exit the renderer.
731 // Historically we had a graceful shutdown sequence here but it was
732 // 1) a waste of performance and 2) a source of lots of complicated
733 // crashes caused by shutdown ordering. Immediate exit eliminates
736 blink::LogStatsDuringShutdown();
738 // In a single-process mode, we cannot call _exit(0) in Shutdown() because
739 // it will exit the process before the browser side is ready to exit.
740 if (!IsSingleProcess())
741 base::Process::TerminateCurrentProcessImmediately(0);
744 bool RenderThreadImpl::ShouldBeDestroyed() {
745 DCHECK(IsSingleProcess());
746 // In a single-process mode, it is unsafe to destruct this renderer thread
747 // because we haven't run the shutdown sequence. Hence we leak the render
750 // In this case, we also need to disable at-exit callbacks because some of
751 // the at-exit callbacks are expected to run after the renderer thread
752 // has been destructed.
753 base::AtExitManager::DisableAllAtExitManagers();
757 IPC::SyncChannel* RenderThreadImpl::GetChannel() {
761 std::string RenderThreadImpl::GetLocale() {
762 // The browser process should have passed the locale to the renderer via the
763 // --lang command line flag.
764 const base::CommandLine& parsed_command_line =
765 *base::CommandLine::ForCurrentProcess();
766 const std::string& lang =
767 parsed_command_line.GetSwitchValueASCII(switches::kLang);
768 DCHECK(!lang.empty());
772 IPC::SyncMessageFilter* RenderThreadImpl::GetSyncMessageFilter() {
773 return sync_message_filter();
776 void RenderThreadImpl::AddRoute(int32_t routing_id, IPC::Listener* listener) {
777 ChildThreadImpl::GetRouter()->AddRoute(routing_id, listener);
780 void RenderThreadImpl::AttachTaskRunnerToRoute(
782 scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
783 GetChannel()->AddListenerTaskRunner(routing_id, std::move(task_runner));
786 void RenderThreadImpl::RemoveRoute(int32_t routing_id) {
787 ChildThreadImpl::GetRouter()->RemoveRoute(routing_id);
788 GetChannel()->RemoveListenerTaskRunner(routing_id);
789 pending_frames_.erase(routing_id);
792 mojom::RendererHost* RenderThreadImpl::GetRendererHost() {
793 if (!renderer_host_) {
794 DCHECK(GetChannel());
795 GetChannel()->GetRemoteAssociatedInterface(&renderer_host_);
797 return renderer_host_.get();
800 int RenderThreadImpl::GenerateRoutingID() {
801 int32_t routing_id = MSG_ROUTING_NONE;
802 render_message_filter()->GenerateRoutingID(&routing_id);
806 bool RenderThreadImpl::GenerateFrameRoutingID(
808 blink::LocalFrameToken& frame_token,
809 base::UnguessableToken& devtools_frame_token,
810 blink::DocumentToken& document_token) {
811 return render_message_filter()->GenerateFrameRoutingID(
812 &routing_id, &frame_token, &devtools_frame_token, &document_token);
815 void RenderThreadImpl::AddFilter(IPC::MessageFilter* filter) {
816 channel()->AddFilter(filter);
819 void RenderThreadImpl::RemoveFilter(IPC::MessageFilter* filter) {
820 channel()->RemoveFilter(filter);
823 void RenderThreadImpl::AddObserver(RenderThreadObserver* observer) {
824 observers_.AddObserver(observer);
825 observer->RegisterMojoInterfaces(&associated_interfaces_);
828 void RenderThreadImpl::RemoveObserver(RenderThreadObserver* observer) {
829 observer->UnregisterMojoInterfaces(&associated_interfaces_);
830 observers_.RemoveObserver(observer);
833 void RenderThreadImpl::InitializeCompositorThread() {
834 blink_platform_impl_->CreateAndSetCompositorThread();
835 compositor_task_runner_ = blink_platform_impl_->CompositorThreadTaskRunner();
837 compositor_task_runner_->PostTask(FROM_HERE,
838 base::BindOnce(&base::DisallowBlocking));
839 GetContentClient()->renderer()->PostCompositorThreadCreated(
840 compositor_task_runner_.get());
843 void RenderThreadImpl::InitializeWebKit(mojo::BinderMap* binders) {
844 DCHECK(!blink_platform_impl_);
846 const base::CommandLine& command_line =
847 *base::CommandLine::ForCurrentProcess();
849 #ifdef ENABLE_VTUNE_JIT_INTERFACE
850 if (command_line.HasSwitch(switches::kEnableVtune))
851 gin::Debug::SetJitCodeEventHandler(vTune::GetVtuneCodeEventHandler());
854 blink_platform_impl_ =
855 std::make_unique<RendererBlinkPlatformImpl>(main_thread_scheduler_.get());
856 // This, among other things, enables any feature marked "test" in
857 // runtime_enabled_features. It is run before
858 // SetRuntimeFeaturesDefaultsAndUpdateFromArgs() so that command line
859 // arguments take precedence over (and can disable) "test" features.
862 ->SetRuntimeFeaturesDefaultsBeforeBlinkInitialization();
863 SetRuntimeFeaturesDefaultsAndUpdateFromArgs(command_line);
865 blink::Initialize(blink_platform_impl_.get(), binders,
866 main_thread_scheduler_.get());
868 v8::Isolate* isolate = blink::MainThreadIsolate();
870 if (!command_line.HasSwitch(switches::kDisableThreadedCompositing))
871 InitializeCompositorThread();
873 RenderThreadImpl::RegisterSchemes();
875 RenderMediaClient::Initialize();
877 if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden()) {
878 // If we do not track widget visibility, then assume conservatively that
879 // the isolate is in background. This reduces memory usage.
880 isolate->IsolateInBackgroundNotification();
883 // Hook up blink's codecs so skia can call them. Since only the renderer
884 // processes should be doing image decoding, this is not done in the common
885 // skia initialization code for the GPU.
886 SkGraphics::SetImageGeneratorFromEncodedDataFactory(
887 blink::WebImageGenerator::CreateAsSkImageGenerator);
890 void RenderThreadImpl::InitializeRenderer(
891 const std::string& user_agent,
892 const blink::UserAgentMetadata& user_agent_metadata,
893 const std::vector<std::string>& cors_exempt_header_list,
894 blink::mojom::OriginTrialsSettingsPtr origin_trials_settings) {
895 DCHECK(user_agent_.IsNull());
897 user_agent_ = WebString::FromUTF8(user_agent);
898 GetContentClient()->renderer()->DidSetUserAgent(user_agent);
899 user_agent_metadata_ = user_agent_metadata;
900 cors_exempt_header_list_ = cors_exempt_header_list;
902 blink::WebVector<blink::WebString> web_cors_exempt_header_list(
903 cors_exempt_header_list.size());
904 base::ranges::transform(
905 cors_exempt_header_list, web_cors_exempt_header_list.begin(),
906 [](const auto& header) { return blink::WebString::FromLatin1(header); });
907 blink::SetCorsExemptHeaderList(web_cors_exempt_header_list);
909 // In single process mode, the settings have already been set by the browser.
910 if (!IsSingleProcess()) {
911 blink::OriginTrialsSettingsProvider::Get()->SetSettings(
912 std::move(origin_trials_settings));
916 void RenderThreadImpl::RegisterSchemes() {
918 WebString chrome_scheme(WebString::FromASCII(kChromeUIScheme));
919 WebSecurityPolicy::RegisterURLSchemeAsDisplayIsolated(chrome_scheme);
920 WebSecurityPolicy::RegisterURLSchemeAsNotAllowingJavascriptURLs(
922 WebSecurityPolicy::RegisterURLSchemeAsWebUI(chrome_scheme);
924 // Service workers for chrome://
925 if (base::FeatureList::IsEnabled(
926 features::kEnableServiceWorkersForChromeScheme)) {
927 WebSecurityPolicy::RegisterURLSchemeAsAllowingServiceWorkers(chrome_scheme);
930 WebString chrome_untrusted_scheme(
931 WebString::FromASCII(kChromeUIUntrustedScheme));
934 // Service workers for chrome-untrusted://
935 if (base::FeatureList::IsEnabled(
936 features::kEnableServiceWorkersForChromeUntrusted)) {
937 WebSecurityPolicy::RegisterURLSchemeAsAllowingServiceWorkers(
938 chrome_untrusted_scheme);
940 WebSecurityPolicy::RegisterURLSchemeAsNotAllowingJavascriptURLs(
941 chrome_untrusted_scheme);
942 WebSecurityPolicy::RegisterURLSchemeAsSupportingFetchAPI(
943 chrome_untrusted_scheme);
944 WebSecurityPolicy::RegisterURLSchemeAsAllowingWasmEvalCSP(
945 chrome_untrusted_scheme);
947 if (base::FeatureList::IsEnabled(features::kWebUICodeCache)) {
948 WebSecurityPolicy::RegisterURLSchemeAsCodeCacheWithHashing(chrome_scheme);
949 WebSecurityPolicy::RegisterURLSchemeAsCodeCacheWithHashing(
950 chrome_untrusted_scheme);
954 WebString devtools_scheme(WebString::FromASCII(kChromeDevToolsScheme));
955 WebSecurityPolicy::RegisterURLSchemeAsDisplayIsolated(devtools_scheme);
956 WebSecurityPolicy::RegisterURLSchemeAsSupportingFetchAPI(devtools_scheme);
957 WebSecurityPolicy::RegisterURLSchemeAsNotAllowingJavascriptURLs(
961 WebString view_source_scheme(WebString::FromASCII(kViewSourceScheme));
962 WebSecurityPolicy::RegisterURLSchemeAsDisplayIsolated(view_source_scheme);
965 WebString error_scheme(WebString::FromASCII(kChromeErrorScheme));
966 WebSecurityPolicy::RegisterURLSchemeAsDisplayIsolated(error_scheme);
967 WebSecurityPolicy::RegisterURLSchemeAsNotAllowingJavascriptURLs(error_scheme);
968 WebSecurityPolicy::RegisterURLSchemeAsError(error_scheme);
971 WebString google_chrome_scheme(WebString::FromASCII(kGoogleChromeScheme));
972 WebSecurityPolicy::RegisterURLSchemeAsDisplayIsolated(google_chrome_scheme);
975 void RenderThreadImpl::RecordAction(const base::UserMetricsAction& action) {
976 GetRendererHost()->RecordUserMetricsAction(action.str_);
979 void RenderThreadImpl::RecordComputedAction(const std::string& action) {
980 GetRendererHost()->RecordUserMetricsAction(action);
983 int RenderThreadImpl::PostTaskToAllWebWorkers(base::RepeatingClosure closure) {
984 return WorkerThreadRegistry::Instance()->PostTaskToAllThreads(
988 media::GpuVideoAcceleratorFactories* RenderThreadImpl::GetGpuFactories() {
989 DCHECK(IsMainThread());
991 if (!gpu_factories_.empty()) {
992 if (!gpu_factories_.back()->CheckContextProviderLostOnMainThread())
993 return gpu_factories_.back().get();
995 GetMediaSequencedTaskRunner()->PostTask(
997 base::BindOnce(&GpuVideoAcceleratorFactoriesImpl::DestroyContext,
998 base::Unretained(gpu_factories_.back().get())));
1001 const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
1003 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host =
1004 EstablishGpuChannelSync();
1005 if (!gpu_channel_host)
1007 // Currently, VideoResourceUpdater can't convert hardware resources to
1008 // software resources in software compositing mode. So, fall back to software
1009 // video decoding if gpu compositing is off.
1010 if (is_gpu_compositing_disabled_)
1012 // This context is only used to create textures and mailbox them, so
1013 // use lower limits than the default.
1014 gpu::SharedMemoryLimits limits = gpu::SharedMemoryLimits::ForMailboxContext();
1015 bool support_locking = false;
1016 bool support_gles2_interface = true;
1017 bool support_raster_interface = false;
1018 bool support_oop_rasterization = false;
1019 bool support_grcontext = false;
1020 bool automatic_flushes = false;
1021 scoped_refptr<viz::ContextProviderCommandBuffer> media_context_provider =
1022 CreateOffscreenContext(gpu_channel_host, limits, support_locking,
1023 support_gles2_interface, support_raster_interface,
1024 support_oop_rasterization, support_grcontext,
1026 viz::command_buffer_metrics::ContextType::MEDIA,
1027 kGpuStreamIdMedia, kGpuStreamPriorityMedia);
1029 const bool enable_video_decode_accelerator =
1030 #if BUILDFLAG(IS_LINUX)
1031 base::FeatureList::IsEnabled(media::kVaapiVideoDecodeLinux) &&
1032 #endif // BUILDFLAG(IS_LINUX)
1033 !cmd_line->HasSwitch(switches::kDisableAcceleratedVideoDecode) &&
1034 (gpu_channel_host->gpu_feature_info()
1035 .status_values[gpu::GPU_FEATURE_TYPE_ACCELERATED_VIDEO_DECODE] ==
1036 gpu::kGpuFeatureStatusEnabled);
1038 const bool enable_video_encode_accelerator =
1039 #if BUILDFLAG(IS_LINUX)
1040 base::FeatureList::IsEnabled(media::kVaapiVideoEncodeLinux) &&
1042 !cmd_line->HasSwitch(switches::kDisableAcceleratedVideoEncode) &&
1043 #endif // BUILDFLAG(IS_LINUX)
1044 (gpu_channel_host->gpu_feature_info()
1045 .status_values[gpu::GPU_FEATURE_TYPE_ACCELERATED_VIDEO_ENCODE] ==
1046 gpu::kGpuFeatureStatusEnabled);
1048 const bool enable_gpu_memory_buffers =
1049 !is_gpu_compositing_disabled_ &&
1050 #if !BUILDFLAG(IS_ANDROID)
1051 !cmd_line->HasSwitch(switches::kDisableGpuMemoryBufferVideoFrames);
1053 cmd_line->HasSwitch(switches::kEnableGpuMemoryBufferVideoFrames);
1055 const bool enable_media_stream_gpu_memory_buffers =
1056 enable_gpu_memory_buffers &&
1057 base::FeatureList::IsEnabled(
1058 features::kWebRtcUseGpuMemoryBufferVideoFrames);
1059 bool enable_video_gpu_memory_buffers = enable_gpu_memory_buffers;
1060 #if BUILDFLAG(IS_WIN)
1061 enable_video_gpu_memory_buffers =
1062 enable_video_gpu_memory_buffers &&
1063 (cmd_line->HasSwitch(switches::kEnableGpuMemoryBufferVideoFrames) ||
1064 gpu_channel_host->gpu_info().overlay_info.supports_overlays);
1065 #endif // BUILDFLAG(IS_WIN)
1067 auto codec_factory = CreateMediaCodecFactory(media_context_provider,
1068 enable_video_decode_accelerator,
1069 enable_video_encode_accelerator);
1070 gpu_factories_.push_back(GpuVideoAcceleratorFactoriesImpl::Create(
1071 std::move(gpu_channel_host),
1072 base::SingleThreadTaskRunner::GetCurrentDefault(),
1073 GetMediaSequencedTaskRunner(), std::move(media_context_provider),
1074 std::move(codec_factory), enable_video_gpu_memory_buffers,
1075 enable_media_stream_gpu_memory_buffers, enable_video_decode_accelerator,
1076 enable_video_encode_accelerator));
1078 gpu_factories_.back()->SetRenderingColorSpace(rendering_color_space_);
1079 return gpu_factories_.back().get();
1082 scoped_refptr<viz::RasterContextProvider>
1083 RenderThreadImpl::GetVideoFrameCompositorContextProvider(
1084 scoped_refptr<viz::RasterContextProvider> unwanted_context_provider) {
1085 auto video_frame_compositor_task_runner =
1086 blink_platform_impl_->VideoFrameCompositorTaskRunner();
1087 DCHECK(video_frame_compositor_task_runner);
1088 if (video_frame_compositor_context_provider_ &&
1089 video_frame_compositor_context_provider_ != unwanted_context_provider) {
1090 return video_frame_compositor_context_provider_;
1093 // Need to make sure these references are removed on the correct task runner;
1094 if (video_frame_compositor_context_provider_) {
1095 video_frame_compositor_task_runner->ReleaseSoon(
1096 FROM_HERE, std::move(video_frame_compositor_context_provider_));
1099 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host =
1100 EstablishGpuChannelSync();
1101 if (!gpu_channel_host)
1104 // This context is only used to create textures and mailbox them, so
1105 // use lower limits than the default.
1106 gpu::SharedMemoryLimits limits = gpu::SharedMemoryLimits::ForMailboxContext();
1108 bool support_locking = false;
1109 bool support_gles2_interface = true;
1110 // Use RasterInterface if kRasterInterfaceInVideoResourceUpdater is enabled.
1111 if (base::FeatureList::IsEnabled(
1112 media::kRasterInterfaceInVideoResourceUpdater)) {
1113 support_gles2_interface = false;
1115 bool support_raster_interface = true;
1116 bool support_oop_rasterization = false;
1117 bool support_grcontext = false;
1118 bool automatic_flushes = false;
1119 video_frame_compositor_context_provider_ = CreateOffscreenContext(
1120 gpu_channel_host, limits, support_locking, support_gles2_interface,
1121 support_raster_interface, support_oop_rasterization, support_grcontext,
1123 viz::command_buffer_metrics::ContextType::RENDER_COMPOSITOR,
1124 kGpuStreamIdMedia, kGpuStreamPriorityMedia);
1125 return video_frame_compositor_context_provider_;
1128 scoped_refptr<viz::ContextProviderCommandBuffer>
1129 RenderThreadImpl::SharedMainThreadContextProvider() {
1130 DCHECK(IsMainThread());
1131 if (shared_main_thread_contexts_ &&
1132 shared_main_thread_contexts_->RasterInterface()
1133 ->GetGraphicsResetStatusKHR() == GL_NO_ERROR)
1134 return shared_main_thread_contexts_;
1136 if (is_context_result_fatal_) {
1140 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host(
1141 EstablishGpuChannelSync());
1142 if (!gpu_channel_host) {
1143 shared_main_thread_contexts_ = nullptr;
1147 bool support_locking = false;
1148 bool support_raster_interface = true;
1149 bool support_oop_rasterization =
1150 gpu_channel_host->gpu_feature_info()
1151 .status_values[gpu::GPU_FEATURE_TYPE_CANVAS_OOP_RASTERIZATION] ==
1152 gpu::kGpuFeatureStatusEnabled;
1153 bool support_gles2_interface = false;
1154 #if defined(TIZEN_TBM_SUPPORT)
1155 support_gles2_interface = true;
1157 bool support_grcontext = !support_oop_rasterization;
1158 // Enable automatic flushes to improve canvas throughput.
1159 // See https://crbug.com/880901
1160 bool automatic_flushes = true;
1162 // We use kGpuStreamIdDefault here, the same as in
1163 // PepperVideoDecodeContextProvider, so we don't need to handle
1164 // synchronization between the pepper context and the shared main thread
1166 shared_main_thread_contexts_ = CreateOffscreenContext(
1167 std::move(gpu_channel_host), gpu::SharedMemoryLimits(), support_locking,
1168 support_gles2_interface, support_raster_interface,
1169 support_oop_rasterization, support_grcontext, automatic_flushes,
1170 viz::command_buffer_metrics::ContextType::RENDERER_MAIN_THREAD,
1171 kGpuStreamIdDefault, kGpuStreamPriorityDefault);
1172 auto result = shared_main_thread_contexts_->BindToCurrentSequence();
1173 if (result != gpu::ContextResult::kSuccess) {
1174 shared_main_thread_contexts_ = nullptr;
1175 is_context_result_fatal_ = result == gpu::ContextResult::kFatalFailure;
1178 return shared_main_thread_contexts_;
1181 scoped_refptr<viz::ContextProviderCommandBuffer>
1182 RenderThreadImpl::PepperVideoDecodeContextProvider() {
1183 DCHECK(IsMainThread());
1184 if (pepper_video_decode_contexts_ &&
1185 pepper_video_decode_contexts_->ContextGL()->GetGraphicsResetStatusKHR() ==
1187 return pepper_video_decode_contexts_;
1189 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host(
1190 EstablishGpuChannelSync());
1191 if (!gpu_channel_host) {
1192 pepper_video_decode_contexts_ = nullptr;
1196 bool support_locking = false;
1197 bool support_raster_interface = false;
1198 bool support_oop_rasterization = false;
1199 bool support_gles2_interface = true;
1200 bool support_grcontext = !support_oop_rasterization;
1201 bool automatic_flushes = false;
1202 // We use kGpuStreamIdDefault here, the same as in
1203 // SharedMainThreadContextProvider, so we don't need to handle
1204 // synchronization between the pepper context and the shared main thread
1206 pepper_video_decode_contexts_ = CreateOffscreenContext(
1207 std::move(gpu_channel_host), gpu::SharedMemoryLimits::ForMailboxContext(),
1208 support_locking, support_gles2_interface, support_raster_interface,
1209 support_oop_rasterization, support_grcontext, automatic_flushes,
1210 viz::command_buffer_metrics::ContextType::RENDERER_MAIN_THREAD,
1211 kGpuStreamIdDefault, kGpuStreamPriorityDefault);
1212 auto result = pepper_video_decode_contexts_->BindToCurrentSequence();
1213 if (result != gpu::ContextResult::kSuccess)
1214 pepper_video_decode_contexts_ = nullptr;
1215 return pepper_video_decode_contexts_;
1218 #if BUILDFLAG(IS_ANDROID)
1219 scoped_refptr<StreamTextureFactory> RenderThreadImpl::GetStreamTexureFactory() {
1220 DCHECK(IsMainThread());
1221 if (!stream_texture_factory_ || stream_texture_factory_->IsLost()) {
1222 scoped_refptr<gpu::GpuChannelHost> channel = EstablishGpuChannelSync();
1224 stream_texture_factory_ = nullptr;
1227 stream_texture_factory_ = StreamTextureFactory::Create(std::move(channel));
1229 return stream_texture_factory_;
1232 bool RenderThreadImpl::EnableStreamTextureCopy() {
1233 return GetContentClient()->UsingSynchronousCompositing();
1235 #endif // BUILDFLAG(IS_ANDROID)
1237 #if BUILDFLAG(IS_WIN)
1238 scoped_refptr<DCOMPTextureFactory> RenderThreadImpl::GetDCOMPTextureFactory() {
1239 DCHECK(IsMainThread());
1240 if (!dcomp_texture_factory_.get() || dcomp_texture_factory_->IsLost()) {
1241 scoped_refptr<gpu::GpuChannelHost> channel = EstablishGpuChannelSync();
1243 dcomp_texture_factory_ = nullptr;
1246 dcomp_texture_factory_ = DCOMPTextureFactory::Create(
1247 std::move(channel), GetMediaSequencedTaskRunner());
1249 return dcomp_texture_factory_;
1252 OverlayStateServiceProvider*
1253 RenderThreadImpl::GetOverlayStateServiceProvider() {
1254 DCHECK(IsMainThread());
1255 // Only set 'overlay_state_service_provider_' if Media Foundation for clear
1257 if (media::SupportMediaFoundationClearPlayback()) {
1258 if (!overlay_state_service_provider_ ||
1259 overlay_state_service_provider_->IsLost()) {
1260 scoped_refptr<gpu::GpuChannelHost> channel = EstablishGpuChannelSync();
1262 overlay_state_service_provider_ = nullptr;
1265 overlay_state_service_provider_ =
1266 std::make_unique<OverlayStateServiceProviderImpl>(std::move(channel));
1270 return overlay_state_service_provider_.get();
1272 #endif // BUILDFLAG(IS_WIN)
1274 base::WaitableEvent* RenderThreadImpl::GetShutdownEvent() {
1275 return ChildProcess::current()->GetShutDownEvent();
1278 int32_t RenderThreadImpl::GetClientId() {
1282 void RenderThreadImpl::SetRendererProcessType(
1283 blink::scheduler::WebRendererProcessType type) {
1284 main_thread_scheduler_->SetRendererProcessType(type);
1287 blink::WebString RenderThreadImpl::GetUserAgent() {
1288 DCHECK(!user_agent_.IsNull());
1293 const blink::UserAgentMetadata& RenderThreadImpl::GetUserAgentMetadata() {
1294 return user_agent_metadata_;
1297 void RenderThreadImpl::WriteIntoTrace(
1298 perfetto::TracedProto<perfetto::protos::pbzero::RenderProcessHost> proto) {
1299 int id = GetClientId();
1303 void RenderThreadImpl::OnAssociatedInterfaceRequest(
1304 const std::string& name,
1305 mojo::ScopedInterfaceEndpointHandle handle) {
1306 if (!associated_interfaces_.TryBindInterface(name, &handle))
1307 ChildThreadImpl::OnAssociatedInterfaceRequest(name, std::move(handle));
1310 bool RenderThreadImpl::IsLcdTextEnabled() {
1311 return is_lcd_text_enabled_;
1314 bool RenderThreadImpl::IsElasticOverscrollEnabled() {
1315 return is_elastic_overscroll_enabled_;
1318 gpu::GpuMemoryBufferManager* RenderThreadImpl::GetGpuMemoryBufferManager() {
1319 return gpu_->gpu_memory_buffer_manager();
1322 blink::scheduler::WebThreadScheduler*
1323 RenderThreadImpl::GetWebMainThreadScheduler() {
1324 return main_thread_scheduler_.get();
1327 bool RenderThreadImpl::IsThreadedAnimationEnabled() {
1328 return is_threaded_animation_enabled_;
1331 bool RenderThreadImpl::IsScrollAnimatorEnabled() {
1332 return is_scroll_animator_enabled_;
1335 void RenderThreadImpl::SetScrollAnimatorEnabled(
1336 bool enable_scroll_animator,
1337 base::PassKey<AgentSchedulingGroup>) {
1338 is_scroll_animator_enabled_ = enable_scroll_animator;
1341 bool RenderThreadImpl::IsMainThread() {
1345 void RenderThreadImpl::OnChannelError() {
1346 // In single-process mode, the renderer can't be restarted after shutdown.
1347 // So, if we get a channel error, crash the whole process right now to get a
1348 // more informative stack, since we will otherwise just crash later when we
1349 // try to restart it.
1350 CHECK(!IsSingleProcess());
1351 ChildThreadImpl::OnChannelError();
1354 void RenderThreadImpl::OnProcessFinalRelease() {
1355 // Do not shutdown the process. The browser process is the only one
1356 // responsible for renderer shutdown.
1358 // Renderer process used to request self shutdown. It has been removed. It
1359 // caused race conditions, where the browser process was reusing renderer
1360 // processes that were shutting down.
1361 // See https://crbug.com/535246 or https://crbug.com/873541/#c8.
1365 bool RenderThreadImpl::OnControlMessageReceived(const IPC::Message& msg) {
1366 for (auto& observer : observers_) {
1367 if (observer.OnControlMessageReceived(msg))
1374 void RenderThreadImpl::SetProcessState(
1375 mojom::RenderProcessBackgroundState background_state,
1376 mojom::RenderProcessVisibleState visible_state) {
1377 DCHECK(background_state_ != background_state ||
1378 visible_state_ != visible_state);
1380 if (background_state != background_state_) {
1381 if (background_state == mojom::RenderProcessBackgroundState::kForegrounded)
1382 OnRendererForegrounded();
1384 OnRendererBackgrounded();
1387 if (visible_state != visible_state_) {
1389 visible_state == mojom::RenderProcessVisibleState::kVisible;
1391 if (!IsInBrowserProcess()) {
1392 ProcessVisibilityTracker::GetInstance()->OnProcessVisibilityChanged(
1397 OnRendererVisible();
1402 background_state_ = background_state;
1403 visible_state_ = visible_state;
1406 void RenderThreadImpl::SetIsLockedToSite() {
1407 DCHECK(blink_platform_impl_);
1408 blink_platform_impl_->SetIsLockedToSite();
1411 #if BUILDFLAG(CLANG_PROFILING_INSIDE_SANDBOX)
1412 void RenderThreadImpl::WriteClangProfilingProfile(
1413 WriteClangProfilingProfileCallback callback) {
1414 // This will write the profiling profile to the file that has been opened and
1415 // passed to this renderer by the browser.
1416 base::WriteClangProfilingProfile();
1417 std::move(callback).Run();
1421 void RenderThreadImpl::SetIsCrossOriginIsolated(bool value) {
1422 blink::SetIsCrossOriginIsolated(value);
1425 void RenderThreadImpl::SetIsWebSecurityDisabled(bool value) {
1426 blink::SetIsWebSecurityDisabled(value);
1429 void RenderThreadImpl::SetIsIsolatedContext(bool value) {
1430 blink::SetIsIsolatedContext(value);
1433 void RenderThreadImpl::CompositingModeFallbackToSoftware() {
1434 gpu_->LoseChannel();
1435 is_gpu_compositing_disabled_ = true;
1438 scoped_refptr<gpu::GpuChannelHost> RenderThreadImpl::EstablishGpuChannelSync() {
1439 TRACE_EVENT0("gpu", "RenderThreadImpl::EstablishGpuChannelSync");
1441 scoped_refptr<gpu::GpuChannelHost> gpu_channel =
1442 gpu_->EstablishGpuChannelSync();
1444 GetContentClient()->SetGpuInfo(gpu_channel->gpu_info());
1448 void RenderThreadImpl::EstablishGpuChannel(
1449 EstablishGpuChannelCallback callback) {
1450 TRACE_EVENT_NESTABLE_ASYNC_BEGIN0(
1451 "gpu", "RenderThreadImpl::EstablishGpuChannel", this);
1452 gpu_->EstablishGpuChannel(base::BindOnce(
1453 [](EstablishGpuChannelCallback callback, RenderThreadImpl* thread,
1454 scoped_refptr<gpu::GpuChannelHost> host) {
1455 TRACE_EVENT_NESTABLE_ASYNC_END0(
1456 "gpu", "RenderThreadImpl::EstablishGpuChannel", thread);
1458 GetContentClient()->SetGpuInfo(host->gpu_info());
1459 std::move(callback).Run(std::move(host));
1461 // The GPU process can crash; in that case, run the callback with no host
1462 // to signal the compositor to wait and try again.
1463 mojo::WrapCallbackWithDefaultInvokeIfNotRun(std::move(callback), nullptr),
1467 blink::AssociatedInterfaceRegistry*
1468 RenderThreadImpl::GetAssociatedInterfaceRegistry() {
1469 return &associated_interfaces_;
1472 mojom::RenderMessageFilter* RenderThreadImpl::render_message_filter() {
1473 if (!render_message_filter_)
1474 GetChannel()->GetRemoteAssociatedInterface(&render_message_filter_);
1475 return render_message_filter_.get();
1478 gpu::GpuChannelHost* RenderThreadImpl::GetGpuChannel() {
1479 return gpu_->GetGpuChannel().get();
1482 void RenderThreadImpl::CreateAgentSchedulingGroup(
1483 mojo::PendingReceiver<IPC::mojom::ChannelBootstrap> bootstrap,
1484 mojo::PendingRemote<blink::mojom::BrowserInterfaceBroker> broker_remote) {
1485 agent_scheduling_groups_.emplace(std::make_unique<AgentSchedulingGroup>(
1486 *this, std::move(bootstrap), std::move(broker_remote)));
1489 void RenderThreadImpl::CreateAssociatedAgentSchedulingGroup(
1490 mojo::PendingAssociatedReceiver<mojom::AgentSchedulingGroup>
1491 agent_scheduling_group,
1492 mojo::PendingRemote<blink::mojom::BrowserInterfaceBroker> broker_remote) {
1493 agent_scheduling_groups_.emplace(std::make_unique<AgentSchedulingGroup>(
1494 *this, std::move(agent_scheduling_group), std::move(broker_remote)));
1497 void RenderThreadImpl::OnNetworkConnectionChanged(
1498 net::NetworkChangeNotifier::ConnectionType type,
1499 double max_bandwidth_mbps) {
1500 bool online_status = type != net::NetworkChangeNotifier::CONNECTION_NONE;
1501 WebNetworkStateNotifier::SetOnLine(online_status);
1502 WebNetworkStateNotifier::SetWebConnection(
1503 NetConnectionTypeToWebConnectionType(type), max_bandwidth_mbps);
1504 if (url_loader_throttle_provider_)
1505 url_loader_throttle_provider_->SetOnline(online_status);
1508 void RenderThreadImpl::OnNetworkQualityChanged(
1509 net::EffectiveConnectionType type,
1510 base::TimeDelta http_rtt,
1511 base::TimeDelta transport_rtt,
1512 double downlink_throughput_kbps) {
1513 LOCAL_HISTOGRAM_BOOLEAN("NQE.RenderThreadNotified", true);
1514 WebNetworkStateNotifier::SetNetworkQuality(
1515 EffectiveConnectionTypeToWebEffectiveConnectionType(type), http_rtt,
1516 transport_rtt, downlink_throughput_kbps);
1519 void RenderThreadImpl::SetWebKitSharedTimersSuspended(bool suspend) {
1520 #if BUILDFLAG(IS_ANDROID)
1522 main_thread_scheduler_->PauseTimersForAndroidWebView();
1524 main_thread_scheduler_->ResumeTimersForAndroidWebView();
1531 void RenderThreadImpl::UpdateScrollbarTheme(
1532 mojom::UpdateScrollbarThemeParamsPtr params) {
1533 #if BUILDFLAG(IS_MAC)
1534 blink::WebScrollbarTheme::UpdateScrollbarsWithNSDefaults(
1535 params->has_initial_button_delay
1536 ? absl::make_optional(params->initial_button_delay)
1538 params->has_autoscroll_button_delay
1539 ? absl::make_optional(params->autoscroll_button_delay)
1541 params->preferred_scroller_style, params->redraw,
1542 params->jump_on_track_click);
1543 #endif // BUILDFLAG(IS_MAC)
1544 #if BUILDFLAG(IS_APPLE)
1545 is_elastic_overscroll_enabled_ = params->scroll_view_rubber_banding;
1548 #endif // BUILDFLAG(IS_APPLE)
1551 void RenderThreadImpl::OnSystemColorsChanged(int32_t aqua_color_variant) {
1552 #if BUILDFLAG(IS_MAC)
1553 SystemColorsDidChange(aqua_color_variant);
1555 // Let blink know it should invalidate and recalculate styles for elements
1556 // that rely on system colors, such as the accent and highlight colors.
1557 blink::SystemColorsChanged();
1563 void RenderThreadImpl::UpdateSystemColorInfo(
1564 mojom::UpdateSystemColorInfoParamsPtr params) {
1565 bool color_providers_changed =
1566 blink_platform_impl_->ThemeEngine()->UpdateColorProviders(
1567 params->light_colors, params->dark_colors, params->forced_colors_map);
1568 if (color_providers_changed) {
1569 // Notify blink that the global ColorProvider instances for this renderer
1570 // have changed. These color providers are only used to paint native
1571 // controls and only require us to invalidate paint for local frames in this
1573 blink::ColorProvidersChanged();
1576 auto* native_theme = ui::NativeTheme::GetInstanceForWeb();
1578 bool did_system_color_info_change = native_theme->UpdateSystemColorInfo(
1579 params->is_dark_mode, params->forced_colors, params->colors);
1581 did_system_color_info_change |=
1582 native_theme->user_color() != params->accent_color;
1583 native_theme->set_user_color(params->accent_color);
1585 if (did_system_color_info_change) {
1586 // Notify blink of system color info changes. These give blink the
1587 // opportunity to update internal state to reflect the NativeTheme's color
1588 // scheme. These will also prompt blink to invalidate and recalculate styles
1589 // for elements that rely on system colors, such as those leveraging the
1590 // forced colors media feature. These can affect CSS styles and thus require
1591 // action beyond simply invalidating paint on local frames.
1592 blink::SystemColorsChanged();
1593 blink::ColorSchemeChanged();
1597 void RenderThreadImpl::PurgePluginListCache(bool reload_pages) {
1598 #if BUILDFLAG(ENABLE_PLUGINS)
1599 blink::ResetPluginCache(reload_pages);
1601 for (auto& observer : observers_)
1602 observer.PluginListChanged();
1608 void RenderThreadImpl::PurgeResourceCache(PurgeResourceCacheCallback callback) {
1609 blink::WebCache::Clear();
1610 std::move(callback).Run();
1613 void RenderThreadImpl::OnMemoryPressure(
1614 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
1616 "memory", "RenderThreadImpl::OnMemoryPressure",
1617 [&](perfetto::EventContext ctx) {
1618 auto* event = ctx.event<perfetto::protos::pbzero::ChromeTrackEvent>();
1619 auto* data = event->set_chrome_memory_pressure_notification();
1620 data->set_level(base::trace_event::MemoryPressureLevelToTraceEnum(
1621 memory_pressure_level));
1623 if (blink_platform_impl_)
1624 blink::WebMemoryPressureListener::OnMemoryPressure(memory_pressure_level);
1625 if (memory_pressure_level ==
1626 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL) {
1627 ReleaseFreeMemory();
1631 scoped_refptr<base::SequencedTaskRunner>
1632 RenderThreadImpl::GetMediaSequencedTaskRunner() {
1633 DCHECK(main_thread_runner()->BelongsToCurrentThread());
1634 if (base::FeatureList::IsEnabled(kUseThreadPoolForMediaTaskRunner)) {
1635 if (!media_task_runner_) {
1636 media_task_runner_ = base::ThreadPool::CreateSequencedTaskRunner(
1637 base::TaskTraits{base::TaskPriority::USER_VISIBLE,
1638 base::WithBaseSyncPrimitives(), base::MayBlock()});
1640 return media_task_runner_;
1642 if (!media_thread_) {
1643 media_thread_ = std::make_unique<base::Thread>("Media");
1644 #if BUILDFLAG(IS_FUCHSIA)
1645 // Start IO thread on Fuchsia to make that thread usable for FIDL.
1646 base::Thread::Options options(base::MessagePumpType::IO, 0);
1647 // TODO(crbug.com/1400772): Use kCompositing to address media latency on
1648 // Fuchsia until alignment on new media thread types is achieved.
1649 options.thread_type = base::ThreadType::kCompositing;
1651 base::Thread::Options options;
1653 media_thread_->StartWithOptions(std::move(options));
1655 return media_thread_->task_runner();
1658 scoped_refptr<cc::RasterContextProviderWrapper>
1659 RenderThreadImpl::SharedCompositorWorkerContextProvider(
1660 cc::RasterDarkModeFilter* dark_mode_filter) {
1661 DCHECK(IsMainThread());
1662 // Try to reuse existing shared worker context provider.
1663 if (shared_worker_context_provider_wrapper_) {
1664 // Note: If context is lost, delete reference after releasing the lock.
1665 viz::RasterContextProvider::ScopedRasterContextLock lock(
1666 shared_worker_context_provider_wrapper_->GetContext().get());
1667 if (lock.RasterInterface()->GetGraphicsResetStatusKHR() == GL_NO_ERROR)
1668 return shared_worker_context_provider_wrapper_;
1671 scoped_refptr<gpu::GpuChannelHost> gpu_channel_host(
1672 EstablishGpuChannelSync());
1673 if (!gpu_channel_host) {
1674 shared_worker_context_provider_wrapper_ = nullptr;
1675 return shared_worker_context_provider_wrapper_;
1678 bool support_locking = true;
1679 bool support_gpu_rasterization =
1680 gpu_channel_host->gpu_feature_info()
1681 .status_values[gpu::GPU_FEATURE_TYPE_GPU_RASTERIZATION] ==
1682 gpu::kGpuFeatureStatusEnabled;
1684 bool support_gles2_interface = false;
1685 bool support_raster_interface = true;
1686 bool support_grcontext = false;
1687 bool automatic_flushes = false;
1688 auto shared_memory_limits =
1689 support_gpu_rasterization ? gpu::SharedMemoryLimits::ForOOPRasterContext()
1690 : gpu::SharedMemoryLimits();
1691 scoped_refptr<viz::ContextProviderCommandBuffer>
1692 shared_worker_context_provider = CreateOffscreenContext(
1693 std::move(gpu_channel_host), shared_memory_limits, support_locking,
1694 support_gles2_interface, support_raster_interface,
1695 support_gpu_rasterization, support_grcontext, automatic_flushes,
1696 viz::command_buffer_metrics::ContextType::RENDER_WORKER,
1697 kGpuStreamIdWorker, kGpuStreamPriorityWorker);
1699 auto result = shared_worker_context_provider->BindToCurrentSequence();
1700 if (result != gpu::ContextResult::kSuccess)
1703 shared_worker_context_provider_wrapper_ =
1704 base::MakeRefCounted<cc::RasterContextProviderWrapper>(
1705 std::move(shared_worker_context_provider), dark_mode_filter,
1706 cc::ImageDecodeCacheUtils::GetWorkingSetBytesForImageDecode(
1707 /*for_renderer=*/true));
1709 return shared_worker_context_provider_wrapper_;
1712 bool RenderThreadImpl::RendererIsHidden() const {
1713 return visible_state_ == mojom::RenderProcessVisibleState::kHidden;
1716 void RenderThreadImpl::OnRendererHidden() {
1717 blink::IsolateInBackgroundNotification();
1719 // TODO(rmcilroy): Remove IdleHandler and replace it with an IdleTask
1720 // scheduled by the RendererScheduler - http://crbug.com/469210.
1721 if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
1723 main_thread_scheduler_->SetRendererHidden(true);
1726 void RenderThreadImpl::OnRendererVisible() {
1727 blink::IsolateInForegroundNotification();
1729 if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
1731 main_thread_scheduler_->SetRendererHidden(false);
1734 bool RenderThreadImpl::RendererIsBackgrounded() const {
1735 return background_state_ ==
1736 mojom::RenderProcessBackgroundState::kBackgrounded;
1739 void RenderThreadImpl::OnRendererBackgrounded() {
1740 UpdateForegroundCrashKey(/*foreground=*/false);
1741 main_thread_scheduler_->SetRendererBackgrounded(true);
1742 discardable_memory_allocator_->OnBackgrounded();
1743 base::allocator::PartitionAllocSupport::Get()->OnBackgrounded();
1746 void RenderThreadImpl::OnRendererForegrounded() {
1747 UpdateForegroundCrashKey(/*foreground=*/true);
1748 main_thread_scheduler_->SetRendererBackgrounded(false);
1749 discardable_memory_allocator_->OnForegrounded();
1750 base::allocator::PartitionAllocSupport::Get()->OnForegrounded(
1751 MainFrameCounter::has_main_frame());
1752 process_foregrounded_count_++;
1755 void RenderThreadImpl::ReleaseFreeMemory() {
1756 TRACE_EVENT0("blink", "RenderThreadImpl::ReleaseFreeMemory()");
1757 base::allocator::ReleaseFreeMemory();
1758 discardable_memory_allocator_->ReleaseFreeMemory();
1760 // Do not call into blink if it is not initialized.
1761 if (blink_platform_impl_) {
1762 // Purge Skia font cache, resource cache, and image filter.
1763 SkGraphics::PurgeAllCaches();
1764 blink::WebMemoryPressureListener::OnPurgeMemory();
1768 void RenderThreadImpl::OnSyncMemoryPressure(
1769 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
1770 if (!blink::MainThreadIsolate())
1773 v8::MemoryPressureLevel v8_memory_pressure_level =
1774 static_cast<v8::MemoryPressureLevel>(memory_pressure_level);
1776 #if !BUILDFLAG(ALLOW_CRITICAL_MEMORY_PRESSURE_HANDLING_IN_FOREGROUND)
1777 // In order to reduce performance impact, translate critical level to
1778 // moderate level for foreground renderer.
1779 if (!RendererIsHidden() &&
1780 v8_memory_pressure_level == v8::MemoryPressureLevel::kCritical)
1781 v8_memory_pressure_level = v8::MemoryPressureLevel::kModerate;
1782 #endif // !BUILDFLAG(ALLOW_CRITICAL_MEMORY_PRESSURE_HANDLING_IN_FOREGROUND)
1784 blink::MainThreadIsolate()->MemoryPressureNotification(
1785 v8_memory_pressure_level);
1786 blink::MemoryPressureNotificationToWorkerThreadIsolates(
1787 v8_memory_pressure_level);
1790 void RenderThreadImpl::OnRendererInterfaceReceiver(
1791 mojo::PendingAssociatedReceiver<mojom::Renderer> receiver) {
1792 DCHECK(!renderer_receiver_.is_bound());
1793 renderer_receiver_.Bind(
1794 std::move(receiver),
1795 GetWebMainThreadScheduler()->DeprecatedDefaultTaskRunner());
1798 void RenderThreadImpl::SetRenderingColorSpace(
1799 const gfx::ColorSpace& color_space) {
1800 DCHECK(IsMainThread());
1801 rendering_color_space_ = color_space;
1803 for (const auto& factories : gpu_factories_) {
1805 factories->SetRenderingColorSpace(color_space);
1809 gfx::ColorSpace RenderThreadImpl::GetRenderingColorSpace() {
1810 DCHECK(IsMainThread());
1811 return rendering_color_space_;
1814 std::unique_ptr<CodecFactory> RenderThreadImpl::CreateMediaCodecFactory(
1815 scoped_refptr<viz::ContextProviderCommandBuffer> context_provider,
1816 bool enable_video_decode_accelerator,
1817 bool enable_video_encode_accelerator) {
1818 mojo::PendingRemote<media::mojom::VideoEncodeAcceleratorProvider>
1820 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
1821 if (base::FeatureList::IsEnabled(media::kUseOutOfProcessVideoEncoding)) {
1822 BindHostReceiver(vea_provider.InitWithNewPipeAndPassReceiver());
1824 gpu_->CreateVideoEncodeAcceleratorProvider(
1825 vea_provider.InitWithNewPipeAndPassReceiver());
1828 gpu_->CreateVideoEncodeAcceleratorProvider(
1829 vea_provider.InitWithNewPipeAndPassReceiver());
1832 #if BUILDFLAG(ENABLE_MOJO_VIDEO_DECODER)
1833 mojo::PendingRemote<media::mojom::InterfaceFactory> interface_factory;
1834 BindHostReceiver(interface_factory.InitWithNewPipeAndPassReceiver());
1835 return std::make_unique<CodecFactoryMojo>(
1836 GetMediaSequencedTaskRunner(), context_provider,
1837 enable_video_decode_accelerator, enable_video_encode_accelerator,
1838 std::move(vea_provider), std::move(interface_factory));
1839 #elif BUILDFLAG(IS_FUCHSIA)
1840 mojo::PendingRemote<media::mojom::FuchsiaMediaCodecProvider>
1841 media_codec_provider;
1842 BindHostReceiver(media_codec_provider.InitWithNewPipeAndPassReceiver());
1843 return std::make_unique<CodecFactoryFuchsia>(
1844 GetMediaSequencedTaskRunner(), context_provider,
1845 enable_video_decode_accelerator, enable_video_encode_accelerator,
1846 std::move(vea_provider), std::move(media_codec_provider));
1848 return std::make_unique<CodecFactoryDefault>(
1849 GetMediaSequencedTaskRunner(), context_provider,
1850 enable_video_decode_accelerator, enable_video_encode_accelerator,
1851 std::move(vea_provider));
1855 #if BUILDFLAG(IS_ANDROID)
1856 void RenderThreadImpl::SetPrivateMemoryFootprint(
1857 uint64_t private_memory_footprint_bytes) {
1858 GetRendererHost()->SetPrivateMemoryFootprint(private_memory_footprint_bytes);
1861 void RenderThreadImpl::OnMemoryPressureFromBrowserReceived(
1862 base::MemoryPressureListener::MemoryPressureLevel level) {
1863 // To avoid that the browser process requests a signal while a renderer
1864 // is creating and blink has not been initialized yet, check
1865 // |blink_platform_impl_| here.
1866 if (!blink_platform_impl_) {
1869 blink::RequestUserLevelMemoryPressureSignal();
1874 } // namespace content