1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
6 #include "base/bind_helpers.h"
7 #include "base/command_line.h"
9 #include "base/json/json_writer.h"
10 #include "base/memory/shared_memory.h"
11 #include "base/time/time.h"
12 #include "base/trace_event/trace_event.h"
13 #include "build/build_config.h"
14 #include "content/common/gpu/devtools_gpu_instrumentation.h"
15 #include "content/common/gpu/gpu_channel.h"
16 #include "content/common/gpu/gpu_channel_manager.h"
17 #include "content/common/gpu/gpu_command_buffer_stub.h"
18 #include "content/common/gpu/gpu_memory_manager.h"
19 #include "content/common/gpu/gpu_memory_tracking.h"
20 #include "content/common/gpu/gpu_messages.h"
21 #include "content/common/gpu/gpu_watchdog.h"
22 #include "content/common/gpu/image_transport_surface.h"
23 #include "content/common/gpu/media/gpu_video_decode_accelerator.h"
24 #include "content/common/gpu/media/gpu_video_encode_accelerator.h"
25 #include "content/public/common/content_client.h"
26 #include "gpu/command_buffer/common/constants.h"
27 #include "gpu/command_buffer/common/gles2_cmd_utils.h"
28 #include "gpu/command_buffer/common/mailbox.h"
29 #include "gpu/command_buffer/service/gl_context_virtual.h"
30 #include "gpu/command_buffer/service/gl_state_restorer_impl.h"
31 #include "gpu/command_buffer/service/image_manager.h"
32 #include "gpu/command_buffer/service/logger.h"
33 #include "gpu/command_buffer/service/mailbox_manager.h"
34 #include "gpu/command_buffer/service/memory_tracking.h"
35 #include "gpu/command_buffer/service/query_manager.h"
36 #include "gpu/command_buffer/service/sync_point_manager.h"
37 #include "gpu/command_buffer/service/valuebuffer_manager.h"
38 #include "ui/gl/gl_bindings.h"
39 #include "ui/gl/gl_switches.h"
42 #include "content/public/common/sandbox_init.h"
45 #if defined(OS_ANDROID)
46 #include "content/common/gpu/stream_texture_android.h"
50 struct WaitForCommandState
{
51 WaitForCommandState(int32 start
, int32 end
, IPC::Message
* reply
)
52 : start(start
), end(end
), reply(reply
) {}
56 scoped_ptr
<IPC::Message
> reply
;
61 // The GpuCommandBufferMemoryTracker class provides a bridge between the
62 // ContextGroup's memory type managers and the GpuMemoryManager class.
63 class GpuCommandBufferMemoryTracker
: public gpu::gles2::MemoryTracker
{
65 explicit GpuCommandBufferMemoryTracker(GpuChannel
* channel
) :
66 tracking_group_(channel
->gpu_channel_manager()->gpu_memory_manager()->
67 CreateTrackingGroup(channel
->renderer_pid(), this)) {
70 void TrackMemoryAllocatedChange(
73 gpu::gles2::MemoryTracker::Pool pool
) override
{
74 tracking_group_
->TrackMemoryAllocatedChange(
75 old_size
, new_size
, pool
);
78 bool EnsureGPUMemoryAvailable(size_t size_needed
) override
{
79 return tracking_group_
->EnsureGPUMemoryAvailable(size_needed
);
83 ~GpuCommandBufferMemoryTracker() override
{}
84 scoped_ptr
<GpuMemoryTrackingGroup
> tracking_group_
;
86 DISALLOW_COPY_AND_ASSIGN(GpuCommandBufferMemoryTracker
);
89 // FastSetActiveURL will shortcut the expensive call to SetActiveURL when the
91 void FastSetActiveURL(const GURL
& url
, size_t url_hash
) {
92 // Leave the previously set URL in the empty case -- empty URLs are given by
93 // BlinkPlatformImpl::createOffscreenGraphicsContext3D. Hopefully the
94 // onscreen context URL was set previously and will show up even when a crash
95 // occurs during offscreen command processing.
98 static size_t g_last_url_hash
= 0;
99 if (url_hash
!= g_last_url_hash
) {
100 g_last_url_hash
= url_hash
;
101 GetContentClient()->SetActiveURL(url
);
105 // The first time polling a fence, delay some extra time to allow other
106 // stubs to process some work, or else the timing of the fences could
107 // allow a pattern of alternating fast and slow frames to occur.
108 const int64 kHandleMoreWorkPeriodMs
= 2;
109 const int64 kHandleMoreWorkPeriodBusyMs
= 1;
111 // Prevents idle work from being starved.
112 const int64 kMaxTimeSinceIdleMs
= 10;
114 class DevToolsChannelData
: public base::trace_event::ConvertableToTraceFormat
{
116 static scoped_refptr
<base::trace_event::ConvertableToTraceFormat
>
117 CreateForChannel(GpuChannel
* channel
);
119 void AppendAsTraceFormat(std::string
* out
) const override
{
121 base::JSONWriter::Write(value_
.get(), &tmp
);
126 explicit DevToolsChannelData(base::Value
* value
) : value_(value
) {}
127 ~DevToolsChannelData() override
{}
128 scoped_ptr
<base::Value
> value_
;
129 DISALLOW_COPY_AND_ASSIGN(DevToolsChannelData
);
132 scoped_refptr
<base::trace_event::ConvertableToTraceFormat
>
133 DevToolsChannelData::CreateForChannel(GpuChannel
* channel
) {
134 scoped_ptr
<base::DictionaryValue
> res(new base::DictionaryValue
);
135 res
->SetInteger("renderer_pid", channel
->renderer_pid());
136 res
->SetDouble("used_bytes", channel
->GetMemoryUsage());
137 res
->SetDouble("limit_bytes",
138 channel
->gpu_channel_manager()
139 ->gpu_memory_manager()
140 ->GetMaximumClientAllocation());
141 return new DevToolsChannelData(res
.release());
146 GpuCommandBufferStub::GpuCommandBufferStub(
148 GpuCommandBufferStub
* share_group
,
149 const gfx::GLSurfaceHandle
& handle
,
150 gpu::gles2::MailboxManager
* mailbox_manager
,
151 gpu::gles2::SubscriptionRefSet
* subscription_ref_set
,
152 gpu::ValueStateMap
* pending_valuebuffer_state
,
153 const gfx::Size
& size
,
154 const gpu::gles2::DisallowedFeatures
& disallowed_features
,
155 const std::vector
<int32
>& attribs
,
156 gfx::GpuPreference gpu_preference
,
157 bool use_virtualized_gl_context
,
160 GpuWatchdog
* watchdog
,
162 const GURL
& active_url
)
166 disallowed_features_(disallowed_features
),
167 requested_attribs_(attribs
),
168 gpu_preference_(gpu_preference
),
169 use_virtualized_gl_context_(use_virtualized_gl_context
),
171 surface_id_(surface_id
),
173 last_flush_count_(0),
174 last_memory_allocation_valid_(false),
176 sync_point_wait_count_(0),
177 delayed_work_scheduled_(false),
178 previous_messages_processed_(0),
179 active_url_(active_url
),
180 total_gpu_memory_(0) {
181 active_url_hash_
= base::Hash(active_url
.possibly_invalid_spec());
182 FastSetActiveURL(active_url_
, active_url_hash_
);
184 gpu::gles2::ContextCreationAttribHelper attrib_parser
;
185 attrib_parser
.Parse(requested_attribs_
);
188 context_group_
= share_group
->context_group_
;
189 DCHECK(context_group_
->bind_generates_resource() ==
190 attrib_parser
.bind_generates_resource
);
192 context_group_
= new gpu::gles2::ContextGroup(
194 new GpuCommandBufferMemoryTracker(channel
),
195 channel_
->gpu_channel_manager()->shader_translator_cache(),
197 subscription_ref_set
,
198 pending_valuebuffer_state
,
199 attrib_parser
.bind_generates_resource
);
202 use_virtualized_gl_context_
|=
203 context_group_
->feature_info()->workarounds().use_virtualized_gl_contexts
;
206 GpuCommandBufferStub::~GpuCommandBufferStub() {
209 GpuChannelManager
* gpu_channel_manager
= channel_
->gpu_channel_manager();
210 gpu_channel_manager
->Send(new GpuHostMsg_DestroyCommandBuffer(surface_id()));
213 GpuMemoryManager
* GpuCommandBufferStub::GetMemoryManager() const {
214 return channel()->gpu_channel_manager()->gpu_memory_manager();
217 bool GpuCommandBufferStub::OnMessageReceived(const IPC::Message
& message
) {
218 TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"),
221 DevToolsChannelData::CreateForChannel(channel()));
222 // TODO(yurys): remove devtools_gpu_instrumentation call once DevTools
223 // Timeline migrates to tracing crbug.com/361045.
224 devtools_gpu_instrumentation::ScopedGpuTask
task(channel());
225 FastSetActiveURL(active_url_
, active_url_hash_
);
227 bool have_context
= false;
228 // Ensure the appropriate GL context is current before handling any IPC
229 // messages directed at the command buffer. This ensures that the message
230 // handler can assume that the context is current (not necessary for
231 // RetireSyncPoint or WaitSyncPoint).
232 if (decoder_
.get() &&
233 message
.type() != GpuCommandBufferMsg_SetGetBuffer::ID
&&
234 message
.type() != GpuCommandBufferMsg_WaitForTokenInRange::ID
&&
235 message
.type() != GpuCommandBufferMsg_WaitForGetOffsetInRange::ID
&&
236 message
.type() != GpuCommandBufferMsg_RegisterTransferBuffer::ID
&&
237 message
.type() != GpuCommandBufferMsg_DestroyTransferBuffer::ID
&&
238 message
.type() != GpuCommandBufferMsg_RetireSyncPoint::ID
&&
239 message
.type() != GpuCommandBufferMsg_SignalSyncPoint::ID
&&
241 GpuCommandBufferMsg_SetClientHasMemoryAllocationChangedCallback::ID
) {
247 // Always use IPC_MESSAGE_HANDLER_DELAY_REPLY for synchronous message handlers
248 // here. This is so the reply can be delayed if the scheduler is unscheduled.
250 IPC_BEGIN_MESSAGE_MAP(GpuCommandBufferStub
, message
)
251 IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuCommandBufferMsg_Initialize
,
253 IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuCommandBufferMsg_SetGetBuffer
,
255 IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_ProduceFrontBuffer
,
256 OnProduceFrontBuffer
);
257 IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuCommandBufferMsg_WaitForTokenInRange
,
258 OnWaitForTokenInRange
);
259 IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuCommandBufferMsg_WaitForGetOffsetInRange
,
260 OnWaitForGetOffsetInRange
);
261 IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_AsyncFlush
, OnAsyncFlush
);
262 IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_Rescheduled
, OnRescheduled
);
263 IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_RegisterTransferBuffer
,
264 OnRegisterTransferBuffer
);
265 IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_DestroyTransferBuffer
,
266 OnDestroyTransferBuffer
);
267 IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuCommandBufferMsg_CreateVideoDecoder
,
268 OnCreateVideoDecoder
)
269 IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuCommandBufferMsg_CreateVideoEncoder
,
270 OnCreateVideoEncoder
)
271 IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_SetSurfaceVisible
,
273 IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_RetireSyncPoint
,
275 IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_SignalSyncPoint
,
277 IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_SignalQuery
,
280 GpuCommandBufferMsg_SetClientHasMemoryAllocationChangedCallback
,
281 OnSetClientHasMemoryAllocationChangedCallback
)
282 IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_CreateImage
, OnCreateImage
);
283 IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_DestroyImage
, OnDestroyImage
);
284 IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_CreateStreamTexture
,
285 OnCreateStreamTexture
)
286 IPC_MESSAGE_UNHANDLED(handled
= false)
287 IPC_END_MESSAGE_MAP()
289 CheckCompleteWaits();
292 // Ensure that any delayed work that was created will be handled.
293 ScheduleDelayedWork(kHandleMoreWorkPeriodMs
);
300 bool GpuCommandBufferStub::Send(IPC::Message
* message
) {
301 return channel_
->Send(message
);
304 bool GpuCommandBufferStub::IsScheduled() {
305 return (!scheduler_
.get() || scheduler_
->IsScheduled());
308 bool GpuCommandBufferStub::HasMoreWork() {
309 return scheduler_
.get() && scheduler_
->HasMoreWork();
312 void GpuCommandBufferStub::PollWork() {
313 TRACE_EVENT0("gpu", "GpuCommandBufferStub::PollWork");
314 delayed_work_scheduled_
= false;
315 FastSetActiveURL(active_url_
, active_url_hash_
);
316 if (decoder_
.get() && !MakeCurrent())
320 uint64 current_messages_processed
=
321 channel()->gpu_channel_manager()->MessagesProcessed();
322 // We're idle when no messages were processed or scheduled.
324 (previous_messages_processed_
== current_messages_processed
) &&
325 !channel()->gpu_channel_manager()->HandleMessagesScheduled();
326 if (!is_idle
&& !last_idle_time_
.is_null()) {
327 base::TimeDelta time_since_idle
=
328 base::TimeTicks::Now() - last_idle_time_
;
329 base::TimeDelta max_time_since_idle
=
330 base::TimeDelta::FromMilliseconds(kMaxTimeSinceIdleMs
);
332 // Force idle when it's been too long since last time we were idle.
333 if (time_since_idle
> max_time_since_idle
)
338 last_idle_time_
= base::TimeTicks::Now();
339 scheduler_
->PerformIdleWork();
342 ScheduleDelayedWork(kHandleMoreWorkPeriodBusyMs
);
345 bool GpuCommandBufferStub::HasUnprocessedCommands() {
346 if (command_buffer_
) {
347 gpu::CommandBuffer::State state
= command_buffer_
->GetLastState();
348 return command_buffer_
->GetPutOffset() != state
.get_offset
&&
349 !gpu::error::IsError(state
.error
);
354 void GpuCommandBufferStub::ScheduleDelayedWork(int64 delay
) {
355 if (!HasMoreWork()) {
356 last_idle_time_
= base::TimeTicks();
360 if (delayed_work_scheduled_
)
362 delayed_work_scheduled_
= true;
364 // Idle when no messages are processed between now and when
365 // PollWork is called.
366 previous_messages_processed_
=
367 channel()->gpu_channel_manager()->MessagesProcessed();
368 if (last_idle_time_
.is_null())
369 last_idle_time_
= base::TimeTicks::Now();
371 // IsScheduled() returns true after passing all unschedule fences
372 // and this is when we can start performing idle work. Idle work
373 // is done synchronously so we can set delay to 0 and instead poll
374 // for more work at the rate idle work is performed. This also ensures
375 // that idle work is done as efficiently as possible without any
376 // unnecessary delays.
377 if (scheduler_
.get() &&
378 scheduler_
->IsScheduled() &&
379 scheduler_
->HasMoreIdleWork()) {
383 base::MessageLoop::current()->PostDelayedTask(
385 base::Bind(&GpuCommandBufferStub::PollWork
, AsWeakPtr()),
386 base::TimeDelta::FromMilliseconds(delay
));
389 bool GpuCommandBufferStub::MakeCurrent() {
390 if (decoder_
->MakeCurrent())
392 DLOG(ERROR
) << "Context lost because MakeCurrent failed.";
393 command_buffer_
->SetContextLostReason(decoder_
->GetContextLostReason());
394 command_buffer_
->SetParseError(gpu::error::kLostContext
);
399 void GpuCommandBufferStub::Destroy() {
400 if (wait_for_token_
) {
401 Send(wait_for_token_
->reply
.release());
402 wait_for_token_
.reset();
404 if (wait_for_get_offset_
) {
405 Send(wait_for_get_offset_
->reply
.release());
406 wait_for_get_offset_
.reset();
408 if (handle_
.is_null() && !active_url_
.is_empty()) {
409 GpuChannelManager
* gpu_channel_manager
= channel_
->gpu_channel_manager();
410 gpu_channel_manager
->Send(new GpuHostMsg_DidDestroyOffscreenContext(
414 memory_manager_client_state_
.reset();
416 while (!sync_points_
.empty())
417 OnRetireSyncPoint(sync_points_
.front());
420 decoder_
->set_engine(NULL
);
422 // The scheduler has raw references to the decoder and the command buffer so
423 // destroy it before those.
426 bool have_context
= false;
427 if (decoder_
&& command_buffer_
&&
428 command_buffer_
->GetLastState().error
!= gpu::error::kLostContext
)
429 have_context
= decoder_
->MakeCurrent();
430 FOR_EACH_OBSERVER(DestructionObserver
,
431 destruction_observers_
,
432 OnWillDestroyStub());
435 decoder_
->Destroy(have_context
);
439 command_buffer_
.reset();
441 // Remove this after crbug.com/248395 is sorted out.
445 void GpuCommandBufferStub::OnInitializeFailed(IPC::Message
* reply_message
) {
447 GpuCommandBufferMsg_Initialize::WriteReplyParams(
448 reply_message
, false, gpu::Capabilities());
452 void GpuCommandBufferStub::OnInitialize(
453 base::SharedMemoryHandle shared_state_handle
,
454 IPC::Message
* reply_message
) {
455 TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnInitialize");
456 DCHECK(!command_buffer_
.get());
458 scoped_ptr
<base::SharedMemory
> shared_state_shm(
459 new base::SharedMemory(shared_state_handle
, false));
461 command_buffer_
.reset(new gpu::CommandBufferService(
462 context_group_
->transfer_buffer_manager()));
464 bool result
= command_buffer_
->Initialize();
467 decoder_
.reset(::gpu::gles2::GLES2Decoder::Create(context_group_
.get()));
469 scheduler_
.reset(new gpu::GpuScheduler(command_buffer_
.get(),
472 if (preemption_flag_
.get())
473 scheduler_
->SetPreemptByFlag(preemption_flag_
);
475 decoder_
->set_engine(scheduler_
.get());
477 if (!handle_
.is_null()) {
478 #if defined(OS_MACOSX) || defined(UI_COMPOSITOR_IMAGE_TRANSPORT)
480 LOG(ERROR
) << "No software support.";
481 OnInitializeFailed(reply_message
);
486 surface_
= ImageTransportSurface::CreateSurface(
487 channel_
->gpu_channel_manager(),
491 GpuChannelManager
* manager
= channel_
->gpu_channel_manager();
492 surface_
= manager
->GetDefaultOffscreenSurface();
495 if (!surface_
.get()) {
496 DLOG(ERROR
) << "Failed to create surface.";
497 OnInitializeFailed(reply_message
);
501 scoped_refptr
<gfx::GLContext
> context
;
502 if (use_virtualized_gl_context_
&& channel_
->share_group()) {
503 context
= channel_
->share_group()->GetSharedContext();
504 if (!context
.get()) {
505 context
= gfx::GLContext::CreateGLContext(
506 channel_
->share_group(),
507 channel_
->gpu_channel_manager()->GetDefaultOffscreenSurface(),
509 if (!context
.get()) {
510 DLOG(ERROR
) << "Failed to create shared context for virtualization.";
511 OnInitializeFailed(reply_message
);
514 channel_
->share_group()->SetSharedContext(context
.get());
516 // This should be a non-virtual GL context.
517 DCHECK(context
->GetHandle());
518 context
= new gpu::GLContextVirtual(
519 channel_
->share_group(), context
.get(), decoder_
->AsWeakPtr());
520 if (!context
->Initialize(surface_
.get(), gpu_preference_
)) {
521 // TODO(sievers): The real context created above for the default
522 // offscreen surface might not be compatible with this surface.
523 // Need to adjust at least GLX to be able to create the initial context
524 // with a config that is compatible with onscreen and offscreen surfaces.
527 DLOG(ERROR
) << "Failed to initialize virtual GL context.";
528 OnInitializeFailed(reply_message
);
532 if (!context
.get()) {
533 context
= gfx::GLContext::CreateGLContext(
534 channel_
->share_group(), surface_
.get(), gpu_preference_
);
536 if (!context
.get()) {
537 DLOG(ERROR
) << "Failed to create context.";
538 OnInitializeFailed(reply_message
);
542 if (!context
->MakeCurrent(surface_
.get())) {
543 LOG(ERROR
) << "Failed to make context current.";
544 OnInitializeFailed(reply_message
);
548 if (!context
->GetGLStateRestorer()) {
549 context
->SetGLStateRestorer(
550 new gpu::GLStateRestorerImpl(decoder_
->AsWeakPtr()));
553 if (!context
->GetTotalGpuMemory(&total_gpu_memory_
))
554 total_gpu_memory_
= 0;
556 if (!context_group_
->has_program_cache()) {
557 context_group_
->set_program_cache(
558 channel_
->gpu_channel_manager()->program_cache());
561 // Initialize the decoder with either the view or pbuffer GLContext.
562 if (!decoder_
->Initialize(surface_
,
566 disallowed_features_
,
567 requested_attribs_
)) {
568 DLOG(ERROR
) << "Failed to initialize decoder.";
569 OnInitializeFailed(reply_message
);
573 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
574 switches::kEnableGPUServiceLogging
)) {
575 decoder_
->set_log_commands(true);
578 decoder_
->GetLogger()->SetMsgCallback(
579 base::Bind(&GpuCommandBufferStub::SendConsoleMessage
,
580 base::Unretained(this)));
581 decoder_
->SetShaderCacheCallback(
582 base::Bind(&GpuCommandBufferStub::SendCachedShader
,
583 base::Unretained(this)));
584 decoder_
->SetWaitSyncPointCallback(
585 base::Bind(&GpuCommandBufferStub::OnWaitSyncPoint
,
586 base::Unretained(this)));
588 command_buffer_
->SetPutOffsetChangeCallback(
589 base::Bind(&GpuCommandBufferStub::PutChanged
, base::Unretained(this)));
590 command_buffer_
->SetGetBufferChangeCallback(
591 base::Bind(&gpu::GpuScheduler::SetGetBuffer
,
592 base::Unretained(scheduler_
.get())));
593 command_buffer_
->SetParseErrorCallback(
594 base::Bind(&GpuCommandBufferStub::OnParseError
, base::Unretained(this)));
595 scheduler_
->SetSchedulingChangedCallback(
596 base::Bind(&GpuChannel::StubSchedulingChanged
,
597 base::Unretained(channel_
)));
600 scheduler_
->SetCommandProcessedCallback(
601 base::Bind(&GpuCommandBufferStub::OnCommandProcessed
,
602 base::Unretained(this)));
605 const size_t kSharedStateSize
= sizeof(gpu::CommandBufferSharedState
);
606 if (!shared_state_shm
->Map(kSharedStateSize
)) {
607 DLOG(ERROR
) << "Failed to map shared state buffer.";
608 OnInitializeFailed(reply_message
);
611 command_buffer_
->SetSharedStateBuffer(gpu::MakeBackingFromSharedMemory(
612 shared_state_shm
.Pass(), kSharedStateSize
));
614 gpu::Capabilities capabilities
= decoder_
->GetCapabilities();
615 capabilities
.future_sync_points
= channel_
->allow_future_sync_points();
617 GpuCommandBufferMsg_Initialize::WriteReplyParams(
618 reply_message
, true, capabilities
);
621 if (handle_
.is_null() && !active_url_
.is_empty()) {
622 GpuChannelManager
* gpu_channel_manager
= channel_
->gpu_channel_manager();
623 gpu_channel_manager
->Send(new GpuHostMsg_DidCreateOffscreenContext(
628 void GpuCommandBufferStub::OnCreateStreamTexture(
629 uint32 texture_id
, int32 stream_id
, bool* succeeded
) {
630 #if defined(OS_ANDROID)
631 *succeeded
= StreamTexture::Create(this, texture_id
, stream_id
);
637 void GpuCommandBufferStub::SetLatencyInfoCallback(
638 const LatencyInfoCallback
& callback
) {
639 latency_info_callback_
= callback
;
642 int32
GpuCommandBufferStub::GetRequestedAttribute(int attr
) const {
643 // The command buffer is pairs of enum, value
644 // search for the requested attribute, return the value.
645 for (std::vector
<int32
>::const_iterator it
= requested_attribs_
.begin();
646 it
!= requested_attribs_
.end(); ++it
) {
654 void GpuCommandBufferStub::OnSetGetBuffer(int32 shm_id
,
655 IPC::Message
* reply_message
) {
656 TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnSetGetBuffer");
658 command_buffer_
->SetGetBuffer(shm_id
);
662 void GpuCommandBufferStub::OnProduceFrontBuffer(const gpu::Mailbox
& mailbox
) {
663 TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnProduceFrontBuffer");
665 LOG(ERROR
) << "Can't produce front buffer before initialization.";
669 decoder_
->ProduceFrontBuffer(mailbox
);
672 void GpuCommandBufferStub::OnParseError() {
673 TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnParseError");
674 DCHECK(command_buffer_
.get());
675 gpu::CommandBuffer::State state
= command_buffer_
->GetLastState();
676 IPC::Message
* msg
= new GpuCommandBufferMsg_Destroyed(
677 route_id_
, state
.context_lost_reason
);
678 msg
->set_unblock(true);
681 // Tell the browser about this context loss as well, so it can
682 // determine whether client APIs like WebGL need to be immediately
683 // blocked from automatically running.
684 GpuChannelManager
* gpu_channel_manager
= channel_
->gpu_channel_manager();
685 gpu_channel_manager
->Send(new GpuHostMsg_DidLoseContext(
686 handle_
.is_null(), state
.context_lost_reason
, active_url_
));
691 void GpuCommandBufferStub::OnWaitForTokenInRange(int32 start
,
693 IPC::Message
* reply_message
) {
694 TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnWaitForTokenInRange");
695 DCHECK(command_buffer_
.get());
698 LOG(ERROR
) << "Got WaitForToken command while currently waiting for token.";
700 make_scoped_ptr(new WaitForCommandState(start
, end
, reply_message
));
701 CheckCompleteWaits();
704 void GpuCommandBufferStub::OnWaitForGetOffsetInRange(
707 IPC::Message
* reply_message
) {
708 TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnWaitForGetOffsetInRange");
709 DCHECK(command_buffer_
.get());
711 if (wait_for_get_offset_
) {
713 << "Got WaitForGetOffset command while currently waiting for offset.";
715 wait_for_get_offset_
=
716 make_scoped_ptr(new WaitForCommandState(start
, end
, reply_message
));
717 CheckCompleteWaits();
720 void GpuCommandBufferStub::CheckCompleteWaits() {
721 if (wait_for_token_
|| wait_for_get_offset_
) {
722 gpu::CommandBuffer::State state
= command_buffer_
->GetLastState();
723 if (wait_for_token_
&&
724 (gpu::CommandBuffer::InRange(
725 wait_for_token_
->start
, wait_for_token_
->end
, state
.token
) ||
726 state
.error
!= gpu::error::kNoError
)) {
728 GpuCommandBufferMsg_WaitForTokenInRange::WriteReplyParams(
729 wait_for_token_
->reply
.get(), state
);
730 Send(wait_for_token_
->reply
.release());
731 wait_for_token_
.reset();
733 if (wait_for_get_offset_
&&
734 (gpu::CommandBuffer::InRange(wait_for_get_offset_
->start
,
735 wait_for_get_offset_
->end
,
737 state
.error
!= gpu::error::kNoError
)) {
739 GpuCommandBufferMsg_WaitForGetOffsetInRange::WriteReplyParams(
740 wait_for_get_offset_
->reply
.get(), state
);
741 Send(wait_for_get_offset_
->reply
.release());
742 wait_for_get_offset_
.reset();
747 void GpuCommandBufferStub::OnAsyncFlush(
750 const std::vector
<ui::LatencyInfo
>& latency_info
) {
752 "gpu", "GpuCommandBufferStub::OnAsyncFlush", "put_offset", put_offset
);
754 if (ui::LatencyInfo::Verify(latency_info
,
755 "GpuCommandBufferStub::OnAsyncFlush") &&
756 !latency_info_callback_
.is_null()) {
757 latency_info_callback_
.Run(latency_info
);
759 DCHECK(command_buffer_
.get());
760 if (flush_count
- last_flush_count_
< 0x8000000U
) {
761 last_flush_count_
= flush_count
;
762 command_buffer_
->Flush(put_offset
);
764 // We received this message out-of-order. This should not happen but is here
765 // to catch regressions. Ignore the message.
766 NOTREACHED() << "Received a Flush message out-of-order";
772 void GpuCommandBufferStub::OnRescheduled() {
773 gpu::CommandBuffer::State pre_state
= command_buffer_
->GetLastState();
774 command_buffer_
->Flush(command_buffer_
->GetPutOffset());
775 gpu::CommandBuffer::State post_state
= command_buffer_
->GetLastState();
777 if (pre_state
.get_offset
!= post_state
.get_offset
)
781 void GpuCommandBufferStub::OnRegisterTransferBuffer(
783 base::SharedMemoryHandle transfer_buffer
,
785 TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnRegisterTransferBuffer");
787 // Take ownership of the memory and map it into this process.
788 // This validates the size.
789 scoped_ptr
<base::SharedMemory
> shared_memory(
790 new base::SharedMemory(transfer_buffer
, false));
791 if (!shared_memory
->Map(size
)) {
792 DVLOG(0) << "Failed to map shared memory.";
796 if (command_buffer_
) {
797 command_buffer_
->RegisterTransferBuffer(
798 id
, gpu::MakeBackingFromSharedMemory(shared_memory
.Pass(), size
));
802 void GpuCommandBufferStub::OnDestroyTransferBuffer(int32 id
) {
803 TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnDestroyTransferBuffer");
806 command_buffer_
->DestroyTransferBuffer(id
);
809 void GpuCommandBufferStub::OnCommandProcessed() {
811 watchdog_
->CheckArmed();
814 void GpuCommandBufferStub::ReportState() { command_buffer_
->UpdateState(); }
816 void GpuCommandBufferStub::PutChanged() {
817 FastSetActiveURL(active_url_
, active_url_hash_
);
818 scheduler_
->PutChanged();
821 void GpuCommandBufferStub::OnCreateVideoDecoder(
822 media::VideoCodecProfile profile
,
823 int32 decoder_route_id
,
824 IPC::Message
* reply_message
) {
825 TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnCreateVideoDecoder");
826 GpuVideoDecodeAccelerator
* decoder
= new GpuVideoDecodeAccelerator(
827 decoder_route_id
, this, channel_
->io_message_loop());
828 decoder
->Initialize(profile
, reply_message
);
829 // decoder is registered as a DestructionObserver of this stub and will
830 // self-delete during destruction of this stub.
833 void GpuCommandBufferStub::OnCreateVideoEncoder(
834 media::VideoFrame::Format input_format
,
835 const gfx::Size
& input_visible_size
,
836 media::VideoCodecProfile output_profile
,
837 uint32 initial_bitrate
,
838 int32 encoder_route_id
,
839 IPC::Message
* reply_message
) {
840 TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnCreateVideoEncoder");
841 GpuVideoEncodeAccelerator
* encoder
=
842 new GpuVideoEncodeAccelerator(encoder_route_id
, this);
843 encoder
->Initialize(input_format
,
848 // encoder is registered as a DestructionObserver of this stub and will
849 // self-delete during destruction of this stub.
852 void GpuCommandBufferStub::OnSetSurfaceVisible(bool visible
) {
853 TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnSetSurfaceVisible");
854 if (memory_manager_client_state_
)
855 memory_manager_client_state_
->SetVisible(visible
);
858 void GpuCommandBufferStub::AddSyncPoint(uint32 sync_point
) {
859 sync_points_
.push_back(sync_point
);
862 void GpuCommandBufferStub::OnRetireSyncPoint(uint32 sync_point
) {
863 DCHECK(!sync_points_
.empty() && sync_points_
.front() == sync_point
);
864 sync_points_
.pop_front();
865 GpuChannelManager
* manager
= channel_
->gpu_channel_manager();
866 manager
->sync_point_manager()->RetireSyncPoint(sync_point
);
869 bool GpuCommandBufferStub::OnWaitSyncPoint(uint32 sync_point
) {
872 GpuChannelManager
* manager
= channel_
->gpu_channel_manager();
873 if (manager
->sync_point_manager()->IsSyncPointRetired(sync_point
))
876 if (sync_point_wait_count_
== 0) {
877 TRACE_EVENT_ASYNC_BEGIN1("gpu", "WaitSyncPoint", this,
878 "GpuCommandBufferStub", this);
880 scheduler_
->SetScheduled(false);
881 ++sync_point_wait_count_
;
882 manager
->sync_point_manager()->AddSyncPointCallback(
884 base::Bind(&GpuCommandBufferStub::OnSyncPointRetired
,
886 return scheduler_
->IsScheduled();
889 void GpuCommandBufferStub::OnSyncPointRetired() {
890 --sync_point_wait_count_
;
891 if (sync_point_wait_count_
== 0) {
892 TRACE_EVENT_ASYNC_END1("gpu", "WaitSyncPoint", this,
893 "GpuCommandBufferStub", this);
895 scheduler_
->SetScheduled(true);
898 void GpuCommandBufferStub::OnSignalSyncPoint(uint32 sync_point
, uint32 id
) {
899 GpuChannelManager
* manager
= channel_
->gpu_channel_manager();
900 manager
->sync_point_manager()->AddSyncPointCallback(
902 base::Bind(&GpuCommandBufferStub::OnSignalSyncPointAck
,
907 void GpuCommandBufferStub::OnSignalSyncPointAck(uint32 id
) {
908 Send(new GpuCommandBufferMsg_SignalSyncPointAck(route_id_
, id
));
911 void GpuCommandBufferStub::OnSignalQuery(uint32 query_id
, uint32 id
) {
913 gpu::gles2::QueryManager
* query_manager
= decoder_
->GetQueryManager();
915 gpu::gles2::QueryManager::Query
* query
=
916 query_manager
->GetQuery(query_id
);
919 base::Bind(&GpuCommandBufferStub::OnSignalSyncPointAck
,
926 // Something went wrong, run callback immediately.
927 OnSignalSyncPointAck(id
);
931 void GpuCommandBufferStub::OnSetClientHasMemoryAllocationChangedCallback(
935 "GpuCommandBufferStub::OnSetClientHasMemoryAllocationChangedCallback");
937 if (!memory_manager_client_state_
) {
938 memory_manager_client_state_
.reset(GetMemoryManager()->CreateClientState(
939 this, surface_id_
!= 0, true));
942 memory_manager_client_state_
.reset();
946 void GpuCommandBufferStub::OnCreateImage(int32 id
,
947 gfx::GpuMemoryBufferHandle handle
,
949 gfx::GpuMemoryBuffer::Format format
,
950 uint32 internalformat
) {
951 TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnCreateImage");
956 gpu::gles2::ImageManager
* image_manager
= decoder_
->GetImageManager();
957 DCHECK(image_manager
);
958 if (image_manager
->LookupImage(id
)) {
959 LOG(ERROR
) << "Image already exists with same ID.";
963 scoped_refptr
<gfx::GLImage
> image
= channel()->CreateImageForGpuMemoryBuffer(
964 handle
, size
, format
, internalformat
);
968 image_manager
->AddImage(image
.get(), id
);
971 void GpuCommandBufferStub::OnDestroyImage(int32 id
) {
972 TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnDestroyImage");
977 gpu::gles2::ImageManager
* image_manager
= decoder_
->GetImageManager();
978 DCHECK(image_manager
);
979 if (!image_manager
->LookupImage(id
)) {
980 LOG(ERROR
) << "Image with ID doesn't exist.";
984 image_manager
->RemoveImage(id
);
987 void GpuCommandBufferStub::SendConsoleMessage(
989 const std::string
& message
) {
990 GPUCommandBufferConsoleMessage console_message
;
991 console_message
.id
= id
;
992 console_message
.message
= message
;
993 IPC::Message
* msg
= new GpuCommandBufferMsg_ConsoleMsg(
994 route_id_
, console_message
);
995 msg
->set_unblock(true);
999 void GpuCommandBufferStub::SendCachedShader(
1000 const std::string
& key
, const std::string
& shader
) {
1001 channel_
->CacheShader(key
, shader
);
1004 void GpuCommandBufferStub::AddDestructionObserver(
1005 DestructionObserver
* observer
) {
1006 destruction_observers_
.AddObserver(observer
);
1009 void GpuCommandBufferStub::RemoveDestructionObserver(
1010 DestructionObserver
* observer
) {
1011 destruction_observers_
.RemoveObserver(observer
);
1014 void GpuCommandBufferStub::SetPreemptByFlag(
1015 scoped_refptr
<gpu::PreemptionFlag
> flag
) {
1016 preemption_flag_
= flag
;
1018 scheduler_
->SetPreemptByFlag(preemption_flag_
);
1021 bool GpuCommandBufferStub::GetTotalGpuMemory(uint64
* bytes
) {
1022 *bytes
= total_gpu_memory_
;
1023 return !!total_gpu_memory_
;
1026 gfx::Size
GpuCommandBufferStub::GetSurfaceSize() const {
1027 if (!surface_
.get())
1029 return surface_
->GetSize();
1032 gpu::gles2::MemoryTracker
* GpuCommandBufferStub::GetMemoryTracker() const {
1033 return context_group_
->memory_tracker();
1036 void GpuCommandBufferStub::SetMemoryAllocation(
1037 const gpu::MemoryAllocation
& allocation
) {
1038 if (!last_memory_allocation_valid_
||
1039 !allocation
.Equals(last_memory_allocation_
)) {
1040 Send(new GpuCommandBufferMsg_SetMemoryAllocation(
1041 route_id_
, allocation
));
1044 last_memory_allocation_valid_
= true;
1045 last_memory_allocation_
= allocation
;
1048 void GpuCommandBufferStub::SuggestHaveFrontBuffer(
1049 bool suggest_have_frontbuffer
) {
1050 // This can be called outside of OnMessageReceived, so the context needs
1051 // to be made current before calling methods on the surface.
1052 if (surface_
.get() && MakeCurrent())
1053 surface_
->SetFrontbufferAllocation(suggest_have_frontbuffer
);
1056 bool GpuCommandBufferStub::CheckContextLost() {
1057 DCHECK(command_buffer_
);
1058 gpu::CommandBuffer::State state
= command_buffer_
->GetLastState();
1059 bool was_lost
= state
.error
== gpu::error::kLostContext
;
1060 // Lose all other contexts if the reset was triggered by the robustness
1061 // extension instead of being synthetic.
1062 if (was_lost
&& decoder_
&& decoder_
->WasContextLostByRobustnessExtension() &&
1063 (gfx::GLContext::LosesAllContextsOnContextLost() ||
1064 use_virtualized_gl_context_
))
1065 channel_
->LoseAllContexts();
1066 CheckCompleteWaits();
1070 void GpuCommandBufferStub::MarkContextLost() {
1071 if (!command_buffer_
||
1072 command_buffer_
->GetLastState().error
== gpu::error::kLostContext
)
1075 command_buffer_
->SetContextLostReason(gpu::error::kUnknown
);
1077 decoder_
->LoseContext(GL_UNKNOWN_CONTEXT_RESET_ARB
);
1078 command_buffer_
->SetParseError(gpu::error::kLostContext
);
1081 uint64
GpuCommandBufferStub::GetMemoryUsage() const {
1082 return GetMemoryManager()->GetClientMemoryUsage(this);
1085 void GpuCommandBufferStub::SwapBuffersCompleted(
1086 const std::vector
<ui::LatencyInfo
>& latency_info
) {
1087 Send(new GpuCommandBufferMsg_SwapBuffersCompleted(route_id_
, latency_info
));
1090 } // namespace content