[M120 Migration] Enable input picker for chrome
[platform/framework/web/chromium-efl.git] / content / renderer / render_thread_impl.cc
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.
4
5 #include "content/renderer/render_thread_impl.h"
6
7 #include <limits>
8 #include <map>
9 #include <memory>
10 #include <string>
11 #include <utility>
12 #include <vector>
13
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"
173
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"
178 #endif
179
180 #if BUILDFLAG(IS_MAC)
181 #include "base/mac/mac_util.h"
182 #include "content/renderer/theme_helper_mac.h"
183 #endif
184
185 #if BUILDFLAG(IS_WIN)
186 #include <objbase.h>
187 #include <windows.h>
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"
191 #endif
192
193 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
194 #include "content/child/sandboxed_process_thread_type_handler.h"
195 #endif
196
197 #ifdef ENABLE_VTUNE_JIT_INTERFACE
198 #include "v8/src/third_party/vtune/v8-vtune.h"
199 #endif
200
201 #if defined(ENABLE_IPC_FUZZER)
202 #include "content/common/external_ipc_dumper.h"
203 #include "mojo/public/cpp/bindings/message_dumper.h"
204 #endif
205
206 #if BUILDFLAG(IS_APPLE)
207 #include <malloc/malloc.h>
208 #else
209 #include <malloc.h>
210 #endif
211
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"
215 #endif
216
217 #if BUILDFLAG(IS_FUCHSIA)
218 #include "content/renderer/media/codec_factory_fuchsia.h"
219 #include "media/mojo/mojom/fuchsia_media.mojom.h"
220 #endif
221
222 #if BUILDFLAG(CLANG_PROFILING_INSIDE_SANDBOX)
223 #include "base/test/clang_profiling.h"
224 #endif
225
226 namespace content {
227
228 namespace {
229
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;
238
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;
242
243 // An implementation of RendererBlinkPlatformImpl which can be mocked out
244 // for tests.
245 RendererBlinkPlatformImpl* g_current_blink_platform_impl_for_testing;
246
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;
250
251 base::LazyInstance<scoped_refptr<base::SingleThreadTaskRunner>>::
252     DestructorAtExit g_main_task_runner = LAZY_INSTANCE_INITIALIZER;
253
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");
259 static_assert(
260     static_cast<v8::MemoryPressureLevel>(
261         base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE) ==
262         v8::MemoryPressureLevel::kModerate,
263     "moderate level not align");
264 static_assert(
265     static_cast<v8::MemoryPressureLevel>(
266         base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL) ==
267         v8::MemoryPressureLevel::kCritical,
268     "critical level not align");
269
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};
275
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");
281 }
282
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,
293     int32_t stream_id,
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,
319       type);
320 }
321
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>
327         receiver) {
328   process_host->BindHostReceiver(std::move(receiver));
329 }
330
331 static bool IsSingleProcess() {
332   return base::CommandLine::ForCurrentProcess()->HasSwitch(
333       switches::kSingleProcess);
334 }
335
336 }  // namespace
337
338 RenderThreadImpl::HistogramCustomizer::HistogramCustomizer() {
339   custom_histograms_.insert("V8.MemoryHeapSampleTotalCommitted");
340 }
341
342 RenderThreadImpl::HistogramCustomizer::~HistogramCustomizer() {}
343
344 void RenderThreadImpl::HistogramCustomizer::RenderViewNavigatedToHost(
345     const std::string& host,
346     size_t view_count) {
347   if (base::CommandLine::ForCurrentProcess()->HasSwitch(
348           switches::kDisableHistogramCustomizer)) {
349     return;
350   }
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.
356   if (view_count == 1)
357     SetCommonHost(host);
358   else if (host != common_host_)
359     SetCommonHost(std::string());
360 }
361
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_;
368   }
369   return name;
370 }
371
372 void RenderThreadImpl::HistogramCustomizer::SetCommonHost(
373     const std::string& host) {
374   if (host != common_host_) {
375     common_host_ = host;
376     common_host_histogram_suffix_ = HostToCustomHistogramSuffix(host);
377   }
378 }
379
380 std::string RenderThreadImpl::HistogramCustomizer::HostToCustomHistogramSuffix(
381     const std::string& host) {
382   if (host == "mail.google.com")
383     return ".gmail";
384   if (host == "docs.google.com" || host == "drive.google.com")
385     return ".docs";
386   if (host == "plus.google.com")
387     return ".plus";
388   if (host == "inbox.google.com")
389     return ".inbox";
390   if (host == "calendar.google.com")
391     return ".calendar";
392   if (host == "www.youtube.com")
393     return ".youtube";
394   if (IsAlexaTop10NonGoogleSite(host))
395     return ".top10";
396
397   return std::string();
398 }
399
400 bool RenderThreadImpl::HistogramCustomizer::IsAlexaTop10NonGoogleSite(
401     const std::string& host) {
402   // The Top10 sites have different TLD and/or subdomains depending on the
403   // localization.
404   if (host == "sina.com.cn")
405     return true;
406
407   std::string sanitized_host =
408       net::registry_controlled_domains::GetDomainAndRegistry(
409           host, net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
410
411   if (sanitized_host == "facebook.com")
412     return true;
413   if (sanitized_host == "baidu.com")
414     return true;
415   if (sanitized_host == "qq.com")
416     return true;
417   if (sanitized_host == "twitter.com")
418     return true;
419   if (sanitized_host == "taobao.com")
420     return true;
421   if (sanitized_host == "live.com")
422     return true;
423
424   if (!sanitized_host.empty()) {
425     std::vector<base::StringPiece> host_tokens = base::SplitStringPiece(
426         sanitized_host, ".", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
427
428     if (host_tokens.size() >= 2) {
429       if ((host_tokens[0] == "yahoo") || (host_tokens[0] == "amazon") ||
430           (host_tokens[0] == "wikipedia")) {
431         return true;
432       }
433     }
434   }
435   return false;
436 }
437
438 // static
439 RenderThreadImpl* RenderThreadImpl::current() {
440   return render_thread;
441 }
442
443 // static
444 mojom::RenderMessageFilter* RenderThreadImpl::current_render_message_filter() {
445   if (g_render_message_filter_for_testing)
446     return g_render_message_filter_for_testing;
447   DCHECK(current());
448   return current()->render_message_filter();
449 }
450
451 // static
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;
455   DCHECK(current());
456   return current()->blink_platform_impl();
457 }
458
459 // static
460 void RenderThreadImpl::SetRenderMessageFilterForTesting(
461     mojom::RenderMessageFilter* render_message_filter) {
462   g_render_message_filter_for_testing = render_message_filter;
463 }
464
465 // static
466 void RenderThreadImpl::SetRendererBlinkPlatformImplForTesting(
467     RendererBlinkPlatformImpl* blink_platform_impl) {
468   g_current_blink_platform_impl_for_testing = blink_platform_impl;
469 }
470
471 // static
472 scoped_refptr<base::SingleThreadTaskRunner>
473 RenderThreadImpl::DeprecatedGetMainTaskRunner() {
474   return g_main_task_runner.Get();
475 }
476
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
479 // the browser
480 RenderThreadImpl::RenderThreadImpl(
481     const InProcessChildThreadParams& params,
482     int32_t client_id,
483     std::unique_ptr<blink::scheduler::WebThreadScheduler> scheduler)
484     : ChildThreadImpl(
485           base::DoNothing(),
486           Options::Builder()
487               .InBrowserProcess(params)
488               .ConnectToBrowser(true)
489               .IPCTaskRunner(scheduler->DeprecatedDefaultTaskRunner())
490               .ExposesInterfacesToBrowser()
491               .Build()),
492       main_thread_scheduler_(std::move(scheduler)),
493       client_id_(client_id) {
494   TRACE_EVENT0("startup", "RenderThreadImpl::Create");
495   Init();
496 }
497
498 namespace {
499 int32_t GetClientIdFromCommandLine() {
500   DCHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
501       switches::kRendererClientId));
502   int32_t client_id;
503   base::StringToInt(base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
504                         switches::kRendererClientId),
505                     &client_id);
506   return client_id;
507 }
508 }  // anonymous namespace
509
510 // Multi-process mode.
511 RenderThreadImpl::RenderThreadImpl(
512     base::RepeatingClosure quit_closure,
513     std::unique_ptr<blink::scheduler::WebThreadScheduler> scheduler)
514     : ChildThreadImpl(
515           std::move(quit_closure),
516           Options::Builder()
517               .ConnectToBrowser(true)
518               .IPCTaskRunner(scheduler->DeprecatedDefaultTaskRunner())
519               .ExposesInterfacesToBrowser()
520               .Build()),
521       main_thread_scheduler_(std::move(scheduler)),
522       client_id_(GetClientIdFromCommandLine()) {
523   TRACE_EVENT0("startup", "RenderThreadImpl::Create");
524   Init();
525 }
526
527 void RenderThreadImpl::Init() {
528   TRACE_EVENT0("startup", "RenderThreadImpl::Init");
529
530   SCOPED_UMA_HISTOGRAM_TIMER("Renderer.RenderThreadImpl.Init");
531
532   GetContentClient()->renderer()->PostIOThreadCreated(GetIOTaskRunner().get());
533
534   base::trace_event::TraceLog::GetInstance()->SetThreadSortIndex(
535       base::PlatformThread::CurrentId(),
536       kTraceEventRendererMainThreadSortIndex);
537
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
542   // used.
543   if (!features::IsUseCommonSelectPopupEnabled())
544 #endif
545     blink::WebView::SetUseExternalPopupMenus(true);
546 #endif
547
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);
554   }
555 #endif
556
557
558   // Register this object as the main thread.
559   ChildProcess::current()->set_main_thread(this);
560
561   metrics::InitializeSingleSampleMetricsFactory(base::BindRepeating(
562       &CreateSingleSampleMetricsProvider, child_process_host()));
563
564   mojo::PendingRemote<viz::mojom::Gpu> remote_gpu;
565   BindHostReceiver(remote_gpu.InitWithNewPipeAndPassReceiver());
566   gpu_ = viz::Gpu::Create(std::move(remote_gpu), GetIOTaskRunner());
567
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) {
573           if (host)
574             GetContentClient()->SetGpuInfo(host->gpu_info());
575         }));
576   }
577
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);
583
584   vc_manager_ = std::make_unique<blink::WebVideoCaptureImplManager>();
585
586   GetContentClient()->renderer()->RenderThreadStarted();
587   ExposeRendererInterfacesToBrowser(weak_factory_.GetWeakPtr(), &binders);
588   ExposeInterfacesToBrowser(std::move(binders));
589
590   url_loader_throttle_provider_ =
591       GetContentClient()->renderer()->CreateURLLoaderThrottleProvider(
592           blink::URLLoaderThrottleProviderType::kFrame);
593
594   GetAssociatedInterfaceRegistry()->AddInterface<mojom::Renderer>(
595       base::BindRepeating(&RenderThreadImpl::OnRendererInterfaceReceiver,
596                           base::Unretained(this)));
597
598   const base::CommandLine& command_line =
599       *base::CommandLine::ForCurrentProcess();
600
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);
609   }
610 #endif
611
612 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
613   SandboxedProcessThreadTypeHandler::NotifyMainChildThreadCreated();
614 #endif
615
616   cc::SetClientNameForMetrics("Renderer");
617
618   is_threaded_animation_enabled_ =
619       !command_line.HasSwitch(cc::switches::kDisableThreadedAnimation);
620
621   is_elastic_overscroll_enabled_ = switches::IsElasticOverscrollEnabled();
622
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;
627   } else {
628 #if BUILDFLAG(IS_ANDROID)
629     is_lcd_text_enabled_ = false;
630 #elif BUILDFLAG(IS_MAC)
631     is_lcd_text_enabled_ = IsSubpixelAntialiasingAvailable();
632 #else
633     is_lcd_text_enabled_ = true;
634 #endif
635   }
636
637   if (command_line.HasSwitch(switches::kDisableGpuCompositing))
638     is_gpu_compositing_disabled_ = true;
639
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();
643
644   memory_pressure_listener_ = std::make_unique<base::MemoryPressureListener>(
645       FROM_HERE,
646       base::BindRepeating(&RenderThreadImpl::OnMemoryPressure,
647                           base::Unretained(this)),
648       base::BindRepeating(&RenderThreadImpl::OnSyncMemoryPressure,
649                           base::Unretained(this)));
650
651   discardable_memory_allocator_ = CreateDiscardableMemoryAllocator();
652
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());
658
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);
667   }
668 #endif
669
670   process_foregrounded_count_ = 0;
671
672   if (!is_gpu_compositing_disabled_) {
673     BindHostReceiver(compositing_mode_reporter_.BindNewPipeAndPassReceiver());
674
675     compositing_mode_reporter_->AddCompositingModeWatcher(
676         compositing_mode_watcher_receiver_.BindNewPipeAndPassRemote(
677             main_thread_scheduler_->CompositorTaskRunner()));
678   }
679
680   variations_observer_ = std::make_unique<VariationsRenderThreadObserver>();
681   AddObserver(variations_observer_.get());
682
683   base::ThreadPool::PostTask(FROM_HERE,
684                              base::BindOnce([] { SkFontMgr::RefDefault(); }));
685
686   bool should_actively_sample_fonts =
687       command_line.HasSwitch(kFirstRendererProcess) &&
688       blink::IdentifiabilityStudySettings::Get()->ShouldActivelySample() &&
689       !blink::IdentifiabilityStudySettings::Get()
690            ->FontFamiliesToActivelySample()
691            .empty();
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(
701         FROM_HERE,
702         base::BindOnce(
703             [](mojo::PendingRemote<ukm::mojom::UkmRecorderFactory>
704                    pending_factory) {
705               mojo::Remote<ukm::mojom::UkmRecorderFactory> factory(
706                   std::move(pending_factory));
707               auto ukm_recorder = ukm::MojoUkmRecorder::Create(*factory);
708               blink::IdentifiabilityActiveSampler::ActivelySampleAvailableFonts(
709                   ukm_recorder.get());
710             },
711             std::move(pending_factory)));
712   }
713   UpdateForegroundCrashKey(
714       /*foreground=*/!blink::kLaunchingProcessIsBackgrounded);
715 }
716
717 RenderThreadImpl::~RenderThreadImpl() {
718   g_main_task_runner.Get() = nullptr;
719
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_));
725   }
726 }
727
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
734   // those problems.
735
736   blink::LogStatsDuringShutdown();
737
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);
742 }
743
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
748   // thread.
749   //
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();
754   return false;
755 }
756
757 IPC::SyncChannel* RenderThreadImpl::GetChannel() {
758   return channel();
759 }
760
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());
769   return lang;
770 }
771
772 IPC::SyncMessageFilter* RenderThreadImpl::GetSyncMessageFilter() {
773   return sync_message_filter();
774 }
775
776 void RenderThreadImpl::AddRoute(int32_t routing_id, IPC::Listener* listener) {
777   ChildThreadImpl::GetRouter()->AddRoute(routing_id, listener);
778 }
779
780 void RenderThreadImpl::AttachTaskRunnerToRoute(
781     int32_t routing_id,
782     scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
783   GetChannel()->AddListenerTaskRunner(routing_id, std::move(task_runner));
784 }
785
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);
790 }
791
792 mojom::RendererHost* RenderThreadImpl::GetRendererHost() {
793   if (!renderer_host_) {
794     DCHECK(GetChannel());
795     GetChannel()->GetRemoteAssociatedInterface(&renderer_host_);
796   }
797   return renderer_host_.get();
798 }
799
800 int RenderThreadImpl::GenerateRoutingID() {
801   int32_t routing_id = MSG_ROUTING_NONE;
802   render_message_filter()->GenerateRoutingID(&routing_id);
803   return routing_id;
804 }
805
806 bool RenderThreadImpl::GenerateFrameRoutingID(
807     int32_t& routing_id,
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);
813 }
814
815 void RenderThreadImpl::AddFilter(IPC::MessageFilter* filter) {
816   channel()->AddFilter(filter);
817 }
818
819 void RenderThreadImpl::RemoveFilter(IPC::MessageFilter* filter) {
820   channel()->RemoveFilter(filter);
821 }
822
823 void RenderThreadImpl::AddObserver(RenderThreadObserver* observer) {
824   observers_.AddObserver(observer);
825   observer->RegisterMojoInterfaces(&associated_interfaces_);
826 }
827
828 void RenderThreadImpl::RemoveObserver(RenderThreadObserver* observer) {
829   observer->UnregisterMojoInterfaces(&associated_interfaces_);
830   observers_.RemoveObserver(observer);
831 }
832
833 void RenderThreadImpl::InitializeCompositorThread() {
834   blink_platform_impl_->CreateAndSetCompositorThread();
835   compositor_task_runner_ = blink_platform_impl_->CompositorThreadTaskRunner();
836
837   compositor_task_runner_->PostTask(FROM_HERE,
838                                     base::BindOnce(&base::DisallowBlocking));
839   GetContentClient()->renderer()->PostCompositorThreadCreated(
840       compositor_task_runner_.get());
841 }
842
843 void RenderThreadImpl::InitializeWebKit(mojo::BinderMap* binders) {
844   DCHECK(!blink_platform_impl_);
845
846   const base::CommandLine& command_line =
847       *base::CommandLine::ForCurrentProcess();
848
849 #ifdef ENABLE_VTUNE_JIT_INTERFACE
850   if (command_line.HasSwitch(switches::kEnableVtune))
851     gin::Debug::SetJitCodeEventHandler(vTune::GetVtuneCodeEventHandler());
852 #endif
853
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.
860   GetContentClient()
861       ->renderer()
862       ->SetRuntimeFeaturesDefaultsBeforeBlinkInitialization();
863   SetRuntimeFeaturesDefaultsAndUpdateFromArgs(command_line);
864
865   blink::Initialize(blink_platform_impl_.get(), binders,
866                     main_thread_scheduler_.get());
867
868   v8::Isolate* isolate = blink::MainThreadIsolate();
869
870   if (!command_line.HasSwitch(switches::kDisableThreadedCompositing))
871     InitializeCompositorThread();
872
873   RenderThreadImpl::RegisterSchemes();
874
875   RenderMediaClient::Initialize();
876
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();
881   }
882
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);
888 }
889
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());
896
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;
901
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);
908
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));
913   }
914 }
915
916 void RenderThreadImpl::RegisterSchemes() {
917   // chrome:
918   WebString chrome_scheme(WebString::FromASCII(kChromeUIScheme));
919   WebSecurityPolicy::RegisterURLSchemeAsDisplayIsolated(chrome_scheme);
920   WebSecurityPolicy::RegisterURLSchemeAsNotAllowingJavascriptURLs(
921       chrome_scheme);
922   WebSecurityPolicy::RegisterURLSchemeAsWebUI(chrome_scheme);
923
924   // Service workers for chrome://
925   if (base::FeatureList::IsEnabled(
926           features::kEnableServiceWorkersForChromeScheme)) {
927     WebSecurityPolicy::RegisterURLSchemeAsAllowingServiceWorkers(chrome_scheme);
928   }
929
930   WebString chrome_untrusted_scheme(
931       WebString::FromASCII(kChromeUIUntrustedScheme));
932
933   // chrome-untrusted:
934   // Service workers for chrome-untrusted://
935   if (base::FeatureList::IsEnabled(
936           features::kEnableServiceWorkersForChromeUntrusted)) {
937     WebSecurityPolicy::RegisterURLSchemeAsAllowingServiceWorkers(
938         chrome_untrusted_scheme);
939   }
940   WebSecurityPolicy::RegisterURLSchemeAsNotAllowingJavascriptURLs(
941       chrome_untrusted_scheme);
942   WebSecurityPolicy::RegisterURLSchemeAsSupportingFetchAPI(
943       chrome_untrusted_scheme);
944   WebSecurityPolicy::RegisterURLSchemeAsAllowingWasmEvalCSP(
945       chrome_untrusted_scheme);
946
947   if (base::FeatureList::IsEnabled(features::kWebUICodeCache)) {
948     WebSecurityPolicy::RegisterURLSchemeAsCodeCacheWithHashing(chrome_scheme);
949     WebSecurityPolicy::RegisterURLSchemeAsCodeCacheWithHashing(
950         chrome_untrusted_scheme);
951   }
952
953   // devtools:
954   WebString devtools_scheme(WebString::FromASCII(kChromeDevToolsScheme));
955   WebSecurityPolicy::RegisterURLSchemeAsDisplayIsolated(devtools_scheme);
956   WebSecurityPolicy::RegisterURLSchemeAsSupportingFetchAPI(devtools_scheme);
957   WebSecurityPolicy::RegisterURLSchemeAsNotAllowingJavascriptURLs(
958       devtools_scheme);
959
960   // view-source:
961   WebString view_source_scheme(WebString::FromASCII(kViewSourceScheme));
962   WebSecurityPolicy::RegisterURLSchemeAsDisplayIsolated(view_source_scheme);
963
964   // chrome-error:
965   WebString error_scheme(WebString::FromASCII(kChromeErrorScheme));
966   WebSecurityPolicy::RegisterURLSchemeAsDisplayIsolated(error_scheme);
967   WebSecurityPolicy::RegisterURLSchemeAsNotAllowingJavascriptURLs(error_scheme);
968   WebSecurityPolicy::RegisterURLSchemeAsError(error_scheme);
969
970   // googlechrome:
971   WebString google_chrome_scheme(WebString::FromASCII(kGoogleChromeScheme));
972   WebSecurityPolicy::RegisterURLSchemeAsDisplayIsolated(google_chrome_scheme);
973 }
974
975 void RenderThreadImpl::RecordAction(const base::UserMetricsAction& action) {
976   GetRendererHost()->RecordUserMetricsAction(action.str_);
977 }
978
979 void RenderThreadImpl::RecordComputedAction(const std::string& action) {
980   GetRendererHost()->RecordUserMetricsAction(action);
981 }
982
983 int RenderThreadImpl::PostTaskToAllWebWorkers(base::RepeatingClosure closure) {
984   return WorkerThreadRegistry::Instance()->PostTaskToAllThreads(
985       std::move(closure));
986 }
987
988 media::GpuVideoAcceleratorFactories* RenderThreadImpl::GetGpuFactories() {
989   DCHECK(IsMainThread());
990
991   if (!gpu_factories_.empty()) {
992     if (!gpu_factories_.back()->CheckContextProviderLostOnMainThread())
993       return gpu_factories_.back().get();
994
995     GetMediaSequencedTaskRunner()->PostTask(
996         FROM_HERE,
997         base::BindOnce(&GpuVideoAcceleratorFactoriesImpl::DestroyContext,
998                        base::Unretained(gpu_factories_.back().get())));
999   }
1000
1001   const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
1002
1003   scoped_refptr<gpu::GpuChannelHost> gpu_channel_host =
1004       EstablishGpuChannelSync();
1005   if (!gpu_channel_host)
1006     return nullptr;
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_)
1011     return nullptr;
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,
1025                              automatic_flushes,
1026                              viz::command_buffer_metrics::ContextType::MEDIA,
1027                              kGpuStreamIdMedia, kGpuStreamPriorityMedia);
1028
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);
1037
1038   const bool enable_video_encode_accelerator =
1039 #if BUILDFLAG(IS_LINUX)
1040       base::FeatureList::IsEnabled(media::kVaapiVideoEncodeLinux) &&
1041 #else
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);
1047
1048   const bool enable_gpu_memory_buffers =
1049       !is_gpu_compositing_disabled_ &&
1050 #if !BUILDFLAG(IS_ANDROID)
1051       !cmd_line->HasSwitch(switches::kDisableGpuMemoryBufferVideoFrames);
1052 #else
1053       cmd_line->HasSwitch(switches::kEnableGpuMemoryBufferVideoFrames);
1054 #endif
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)
1066
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));
1077
1078   gpu_factories_.back()->SetRenderingColorSpace(rendering_color_space_);
1079   return gpu_factories_.back().get();
1080 }
1081
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_;
1091   }
1092
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_));
1097   }
1098
1099   scoped_refptr<gpu::GpuChannelHost> gpu_channel_host =
1100       EstablishGpuChannelSync();
1101   if (!gpu_channel_host)
1102     return nullptr;
1103
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();
1107
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;
1114   }
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,
1122       automatic_flushes,
1123       viz::command_buffer_metrics::ContextType::RENDER_COMPOSITOR,
1124       kGpuStreamIdMedia, kGpuStreamPriorityMedia);
1125   return video_frame_compositor_context_provider_;
1126 }
1127
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_;
1135
1136   if (is_context_result_fatal_) {
1137     return nullptr;
1138   }
1139
1140   scoped_refptr<gpu::GpuChannelHost> gpu_channel_host(
1141       EstablishGpuChannelSync());
1142   if (!gpu_channel_host) {
1143     shared_main_thread_contexts_ = nullptr;
1144     return nullptr;
1145   }
1146
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;
1156 #endif
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;
1161
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
1165   // context.
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;
1176   }
1177
1178   return shared_main_thread_contexts_;
1179 }
1180
1181 scoped_refptr<viz::ContextProviderCommandBuffer>
1182 RenderThreadImpl::PepperVideoDecodeContextProvider() {
1183   DCHECK(IsMainThread());
1184   if (pepper_video_decode_contexts_ &&
1185       pepper_video_decode_contexts_->ContextGL()->GetGraphicsResetStatusKHR() ==
1186           GL_NO_ERROR)
1187     return pepper_video_decode_contexts_;
1188
1189   scoped_refptr<gpu::GpuChannelHost> gpu_channel_host(
1190       EstablishGpuChannelSync());
1191   if (!gpu_channel_host) {
1192     pepper_video_decode_contexts_ = nullptr;
1193     return nullptr;
1194   }
1195
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
1205   // context.
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_;
1216 }
1217
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();
1223     if (!channel) {
1224       stream_texture_factory_ = nullptr;
1225       return nullptr;
1226     }
1227     stream_texture_factory_ = StreamTextureFactory::Create(std::move(channel));
1228   }
1229   return stream_texture_factory_;
1230 }
1231
1232 bool RenderThreadImpl::EnableStreamTextureCopy() {
1233   return GetContentClient()->UsingSynchronousCompositing();
1234 }
1235 #endif  // BUILDFLAG(IS_ANDROID)
1236
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();
1242     if (!channel) {
1243       dcomp_texture_factory_ = nullptr;
1244       return nullptr;
1245     }
1246     dcomp_texture_factory_ = DCOMPTextureFactory::Create(
1247         std::move(channel), GetMediaSequencedTaskRunner());
1248   }
1249   return dcomp_texture_factory_;
1250 }
1251
1252 OverlayStateServiceProvider*
1253 RenderThreadImpl::GetOverlayStateServiceProvider() {
1254   DCHECK(IsMainThread());
1255   // Only set 'overlay_state_service_provider_' if Media Foundation for clear
1256   // is enabled.
1257   if (media::SupportMediaFoundationClearPlayback()) {
1258     if (!overlay_state_service_provider_ ||
1259         overlay_state_service_provider_->IsLost()) {
1260       scoped_refptr<gpu::GpuChannelHost> channel = EstablishGpuChannelSync();
1261       if (!channel) {
1262         overlay_state_service_provider_ = nullptr;
1263         return nullptr;
1264       }
1265       overlay_state_service_provider_ =
1266           std::make_unique<OverlayStateServiceProviderImpl>(std::move(channel));
1267     }
1268   }
1269
1270   return overlay_state_service_provider_.get();
1271 }
1272 #endif  // BUILDFLAG(IS_WIN)
1273
1274 base::WaitableEvent* RenderThreadImpl::GetShutdownEvent() {
1275   return ChildProcess::current()->GetShutDownEvent();
1276 }
1277
1278 int32_t RenderThreadImpl::GetClientId() {
1279   return client_id_;
1280 }
1281
1282 void RenderThreadImpl::SetRendererProcessType(
1283     blink::scheduler::WebRendererProcessType type) {
1284   main_thread_scheduler_->SetRendererProcessType(type);
1285 }
1286
1287 blink::WebString RenderThreadImpl::GetUserAgent() {
1288   DCHECK(!user_agent_.IsNull());
1289
1290   return user_agent_;
1291 }
1292
1293 const blink::UserAgentMetadata& RenderThreadImpl::GetUserAgentMetadata() {
1294   return user_agent_metadata_;
1295 }
1296
1297 void RenderThreadImpl::WriteIntoTrace(
1298     perfetto::TracedProto<perfetto::protos::pbzero::RenderProcessHost> proto) {
1299   int id = GetClientId();
1300   proto->set_id(id);
1301 }
1302
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));
1308 }
1309
1310 bool RenderThreadImpl::IsLcdTextEnabled() {
1311   return is_lcd_text_enabled_;
1312 }
1313
1314 bool RenderThreadImpl::IsElasticOverscrollEnabled() {
1315   return is_elastic_overscroll_enabled_;
1316 }
1317
1318 gpu::GpuMemoryBufferManager* RenderThreadImpl::GetGpuMemoryBufferManager() {
1319   return gpu_->gpu_memory_buffer_manager();
1320 }
1321
1322 blink::scheduler::WebThreadScheduler*
1323 RenderThreadImpl::GetWebMainThreadScheduler() {
1324   return main_thread_scheduler_.get();
1325 }
1326
1327 bool RenderThreadImpl::IsThreadedAnimationEnabled() {
1328   return is_threaded_animation_enabled_;
1329 }
1330
1331 bool RenderThreadImpl::IsScrollAnimatorEnabled() {
1332   return is_scroll_animator_enabled_;
1333 }
1334
1335 void RenderThreadImpl::SetScrollAnimatorEnabled(
1336     bool enable_scroll_animator,
1337     base::PassKey<AgentSchedulingGroup>) {
1338   is_scroll_animator_enabled_ = enable_scroll_animator;
1339 }
1340
1341 bool RenderThreadImpl::IsMainThread() {
1342   return !!current();
1343 }
1344
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();
1352 }
1353
1354 void RenderThreadImpl::OnProcessFinalRelease() {
1355   // Do not shutdown the process. The browser process is the only one
1356   // responsible for renderer shutdown.
1357   //
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.
1362   NOTREACHED();
1363 }
1364
1365 bool RenderThreadImpl::OnControlMessageReceived(const IPC::Message& msg) {
1366   for (auto& observer : observers_) {
1367     if (observer.OnControlMessageReceived(msg))
1368       return true;
1369   }
1370
1371   return false;
1372 }
1373
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);
1379
1380   if (background_state != background_state_) {
1381     if (background_state == mojom::RenderProcessBackgroundState::kForegrounded)
1382       OnRendererForegrounded();
1383     else
1384       OnRendererBackgrounded();
1385   }
1386
1387   if (visible_state != visible_state_) {
1388     bool is_visible =
1389         visible_state == mojom::RenderProcessVisibleState::kVisible;
1390
1391     if (!IsInBrowserProcess()) {
1392       ProcessVisibilityTracker::GetInstance()->OnProcessVisibilityChanged(
1393           is_visible);
1394     }
1395
1396     if (is_visible)
1397       OnRendererVisible();
1398     else
1399       OnRendererHidden();
1400   }
1401
1402   background_state_ = background_state;
1403   visible_state_ = visible_state;
1404 }
1405
1406 void RenderThreadImpl::SetIsLockedToSite() {
1407   DCHECK(blink_platform_impl_);
1408   blink_platform_impl_->SetIsLockedToSite();
1409 }
1410
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();
1418 }
1419 #endif
1420
1421 void RenderThreadImpl::SetIsCrossOriginIsolated(bool value) {
1422   blink::SetIsCrossOriginIsolated(value);
1423 }
1424
1425 void RenderThreadImpl::SetIsWebSecurityDisabled(bool value) {
1426   blink::SetIsWebSecurityDisabled(value);
1427 }
1428
1429 void RenderThreadImpl::SetIsIsolatedContext(bool value) {
1430   blink::SetIsIsolatedContext(value);
1431 }
1432
1433 void RenderThreadImpl::CompositingModeFallbackToSoftware() {
1434   gpu_->LoseChannel();
1435   is_gpu_compositing_disabled_ = true;
1436 }
1437
1438 scoped_refptr<gpu::GpuChannelHost> RenderThreadImpl::EstablishGpuChannelSync() {
1439   TRACE_EVENT0("gpu", "RenderThreadImpl::EstablishGpuChannelSync");
1440
1441   scoped_refptr<gpu::GpuChannelHost> gpu_channel =
1442       gpu_->EstablishGpuChannelSync();
1443   if (gpu_channel)
1444     GetContentClient()->SetGpuInfo(gpu_channel->gpu_info());
1445   return gpu_channel;
1446 }
1447
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);
1457         if (host)
1458           GetContentClient()->SetGpuInfo(host->gpu_info());
1459         std::move(callback).Run(std::move(host));
1460       },
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),
1464       this));
1465 }
1466
1467 blink::AssociatedInterfaceRegistry*
1468 RenderThreadImpl::GetAssociatedInterfaceRegistry() {
1469   return &associated_interfaces_;
1470 }
1471
1472 mojom::RenderMessageFilter* RenderThreadImpl::render_message_filter() {
1473   if (!render_message_filter_)
1474     GetChannel()->GetRemoteAssociatedInterface(&render_message_filter_);
1475   return render_message_filter_.get();
1476 }
1477
1478 gpu::GpuChannelHost* RenderThreadImpl::GetGpuChannel() {
1479   return gpu_->GetGpuChannel().get();
1480 }
1481
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)));
1487 }
1488
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)));
1495 }
1496
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);
1506 }
1507
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);
1517 }
1518
1519 void RenderThreadImpl::SetWebKitSharedTimersSuspended(bool suspend) {
1520 #if BUILDFLAG(IS_ANDROID)
1521   if (suspend) {
1522     main_thread_scheduler_->PauseTimersForAndroidWebView();
1523   } else {
1524     main_thread_scheduler_->ResumeTimersForAndroidWebView();
1525   }
1526 #else
1527   NOTREACHED();
1528 #endif
1529 }
1530
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)
1537           : absl::nullopt,
1538       params->has_autoscroll_button_delay
1539           ? absl::make_optional(params->autoscroll_button_delay)
1540           : absl::nullopt,
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;
1546 #else
1547   NOTREACHED();
1548 #endif  // BUILDFLAG(IS_APPLE)
1549 }
1550
1551 void RenderThreadImpl::OnSystemColorsChanged(int32_t aqua_color_variant) {
1552 #if BUILDFLAG(IS_MAC)
1553   SystemColorsDidChange(aqua_color_variant);
1554
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();
1558 #else
1559   NOTREACHED();
1560 #endif
1561 }
1562
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
1572     // renderer.
1573     blink::ColorProvidersChanged();
1574   }
1575
1576   auto* native_theme = ui::NativeTheme::GetInstanceForWeb();
1577
1578   bool did_system_color_info_change = native_theme->UpdateSystemColorInfo(
1579       params->is_dark_mode, params->forced_colors, params->colors);
1580
1581   did_system_color_info_change |=
1582       native_theme->user_color() != params->accent_color;
1583   native_theme->set_user_color(params->accent_color);
1584
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();
1594   }
1595 }
1596
1597 void RenderThreadImpl::PurgePluginListCache(bool reload_pages) {
1598 #if BUILDFLAG(ENABLE_PLUGINS)
1599   blink::ResetPluginCache(reload_pages);
1600
1601   for (auto& observer : observers_)
1602     observer.PluginListChanged();
1603 #else
1604   NOTREACHED();
1605 #endif
1606 }
1607
1608 void RenderThreadImpl::PurgeResourceCache(PurgeResourceCacheCallback callback) {
1609   blink::WebCache::Clear();
1610   std::move(callback).Run();
1611 }
1612
1613 void RenderThreadImpl::OnMemoryPressure(
1614     base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
1615   TRACE_EVENT(
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));
1622       });
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();
1628   }
1629 }
1630
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()});
1639     }
1640     return media_task_runner_;
1641   }
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;
1650 #else
1651     base::Thread::Options options;
1652 #endif
1653     media_thread_->StartWithOptions(std::move(options));
1654   }
1655   return media_thread_->task_runner();
1656 }
1657
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_;
1669   }
1670
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_;
1676   }
1677
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;
1683
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);
1698
1699   auto result = shared_worker_context_provider->BindToCurrentSequence();
1700   if (result != gpu::ContextResult::kSuccess)
1701     return nullptr;
1702
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));
1708
1709   return shared_worker_context_provider_wrapper_;
1710 }
1711
1712 bool RenderThreadImpl::RendererIsHidden() const {
1713   return visible_state_ == mojom::RenderProcessVisibleState::kHidden;
1714 }
1715
1716 void RenderThreadImpl::OnRendererHidden() {
1717   blink::IsolateInBackgroundNotification();
1718
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())
1722     return;
1723   main_thread_scheduler_->SetRendererHidden(true);
1724 }
1725
1726 void RenderThreadImpl::OnRendererVisible() {
1727   blink::IsolateInForegroundNotification();
1728
1729   if (!GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden())
1730     return;
1731   main_thread_scheduler_->SetRendererHidden(false);
1732 }
1733
1734 bool RenderThreadImpl::RendererIsBackgrounded() const {
1735   return background_state_ ==
1736          mojom::RenderProcessBackgroundState::kBackgrounded;
1737 }
1738
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();
1744 }
1745
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_++;
1753 }
1754
1755 void RenderThreadImpl::ReleaseFreeMemory() {
1756   TRACE_EVENT0("blink", "RenderThreadImpl::ReleaseFreeMemory()");
1757   base::allocator::ReleaseFreeMemory();
1758   discardable_memory_allocator_->ReleaseFreeMemory();
1759
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();
1765   }
1766 }
1767
1768 void RenderThreadImpl::OnSyncMemoryPressure(
1769     base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
1770   if (!blink::MainThreadIsolate())
1771     return;
1772
1773   v8::MemoryPressureLevel v8_memory_pressure_level =
1774       static_cast<v8::MemoryPressureLevel>(memory_pressure_level);
1775
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)
1783
1784   blink::MainThreadIsolate()->MemoryPressureNotification(
1785       v8_memory_pressure_level);
1786   blink::MemoryPressureNotificationToWorkerThreadIsolates(
1787       v8_memory_pressure_level);
1788 }
1789
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());
1796 }
1797
1798 void RenderThreadImpl::SetRenderingColorSpace(
1799     const gfx::ColorSpace& color_space) {
1800   DCHECK(IsMainThread());
1801   rendering_color_space_ = color_space;
1802
1803   for (const auto& factories : gpu_factories_) {
1804     if (factories)
1805       factories->SetRenderingColorSpace(color_space);
1806   }
1807 }
1808
1809 gfx::ColorSpace RenderThreadImpl::GetRenderingColorSpace() {
1810   DCHECK(IsMainThread());
1811   return rendering_color_space_;
1812 }
1813
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>
1819       vea_provider;
1820 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
1821   if (base::FeatureList::IsEnabled(media::kUseOutOfProcessVideoEncoding)) {
1822     BindHostReceiver(vea_provider.InitWithNewPipeAndPassReceiver());
1823   } else {
1824     gpu_->CreateVideoEncodeAcceleratorProvider(
1825         vea_provider.InitWithNewPipeAndPassReceiver());
1826   }
1827 #else
1828   gpu_->CreateVideoEncodeAcceleratorProvider(
1829       vea_provider.InitWithNewPipeAndPassReceiver());
1830 #endif
1831
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));
1847 #else
1848   return std::make_unique<CodecFactoryDefault>(
1849       GetMediaSequencedTaskRunner(), context_provider,
1850       enable_video_decode_accelerator, enable_video_encode_accelerator,
1851       std::move(vea_provider));
1852 #endif
1853 }
1854
1855 #if BUILDFLAG(IS_ANDROID)
1856 void RenderThreadImpl::SetPrivateMemoryFootprint(
1857     uint64_t private_memory_footprint_bytes) {
1858   GetRendererHost()->SetPrivateMemoryFootprint(private_memory_footprint_bytes);
1859 }
1860
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_) {
1867     return;
1868   }
1869   blink::RequestUserLevelMemoryPressureSignal();
1870 }
1871
1872 #endif
1873
1874 }  // namespace content