[memory-inspector] UI fixes + bump version number for release.
[chromium-blink-merge.git] / content / common / gpu / gpu_command_buffer_stub.cc
blob4c0d12bb4e62eb0e053fb5b2b820b4d7b3c6a104
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.
5 #include "base/bind.h"
6 #include "base/bind_helpers.h"
7 #include "base/command_line.h"
8 #include "base/debug/trace_event.h"
9 #include "base/hash.h"
10 #include "base/json/json_writer.h"
11 #include "base/memory/shared_memory.h"
12 #include "base/time/time.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"
41 #if defined(OS_WIN)
42 #include "content/public/common/sandbox_init.h"
43 #endif
45 #if defined(OS_ANDROID)
46 #include "content/common/gpu/stream_texture_android.h"
47 #endif
49 namespace content {
50 struct WaitForCommandState {
51 WaitForCommandState(int32 start, int32 end, IPC::Message* reply)
52 : start(start), end(end), reply(reply) {}
54 int32 start;
55 int32 end;
56 scoped_ptr<IPC::Message> reply;
59 namespace {
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 {
64 public:
65 explicit GpuCommandBufferMemoryTracker(GpuChannel* channel) :
66 tracking_group_(channel->gpu_channel_manager()->gpu_memory_manager()->
67 CreateTrackingGroup(channel->renderer_pid(), this)) {
70 void TrackMemoryAllocatedChange(
71 size_t old_size,
72 size_t new_size,
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);
82 private:
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
90 // url_hash matches.
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.
96 if (url.is_empty())
97 return;
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::debug::ConvertableToTraceFormat {
115 public:
116 static scoped_refptr<base::debug::ConvertableToTraceFormat> CreateForChannel(
117 GpuChannel* channel);
119 void AppendAsTraceFormat(std::string* out) const override {
120 std::string tmp;
121 base::JSONWriter::Write(value_.get(), &tmp);
122 *out += tmp;
125 private:
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::debug::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());
144 } // namespace
146 GpuCommandBufferStub::GpuCommandBufferStub(
147 GpuChannel* channel,
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,
158 int32 route_id,
159 int32 surface_id,
160 GpuWatchdog* watchdog,
161 bool software,
162 const GURL& active_url)
163 : channel_(channel),
164 handle_(handle),
165 initial_size_(size),
166 disallowed_features_(disallowed_features),
167 requested_attribs_(attribs),
168 gpu_preference_(gpu_preference),
169 use_virtualized_gl_context_(use_virtualized_gl_context),
170 route_id_(route_id),
171 surface_id_(surface_id),
172 software_(software),
173 last_flush_count_(0),
174 last_memory_allocation_valid_(false),
175 watchdog_(watchdog),
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_);
187 if (share_group) {
188 context_group_ = share_group->context_group_;
189 DCHECK(context_group_->bind_generates_resource() ==
190 attrib_parser.bind_generates_resource);
191 } else {
192 context_group_ = new gpu::gles2::ContextGroup(
193 mailbox_manager,
194 new GpuCommandBufferMemoryTracker(channel),
195 channel_->gpu_channel_manager()->shader_translator_cache(),
196 NULL,
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() {
207 Destroy();
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"),
219 "GPUTask",
220 "data",
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 &&
240 message.type() !=
241 GpuCommandBufferMsg_SetClientHasMemoryAllocationChangedCallback::ID) {
242 if (!MakeCurrent())
243 return false;
244 have_context = true;
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.
249 bool handled = true;
250 IPC_BEGIN_MESSAGE_MAP(GpuCommandBufferStub, message)
251 IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuCommandBufferMsg_Initialize,
252 OnInitialize);
253 IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuCommandBufferMsg_SetGetBuffer,
254 OnSetGetBuffer);
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,
272 OnSetSurfaceVisible)
273 IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_RetireSyncPoint,
274 OnRetireSyncPoint)
275 IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_SignalSyncPoint,
276 OnSignalSyncPoint)
277 IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_SignalQuery,
278 OnSignalQuery)
279 IPC_MESSAGE_HANDLER(
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();
291 if (have_context) {
292 // Ensure that any delayed work that was created will be handled.
293 ScheduleDelayedWork(kHandleMoreWorkPeriodMs);
296 DCHECK(handled);
297 return handled;
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())
317 return;
319 if (scheduler_) {
320 uint64 current_messages_processed =
321 channel()->gpu_channel_manager()->MessagesProcessed();
322 // We're idle when no messages were processed or scheduled.
323 bool is_idle =
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)
334 is_idle = true;
337 if (is_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);
351 return false;
354 void GpuCommandBufferStub::ScheduleDelayedWork(int64 delay) {
355 if (!HasMoreWork()) {
356 last_idle_time_ = base::TimeTicks();
357 return;
360 if (delayed_work_scheduled_)
361 return;
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()) {
380 delay = 0;
383 base::MessageLoop::current()->PostDelayedTask(
384 FROM_HERE,
385 base::Bind(&GpuCommandBufferStub::PollWork, AsWeakPtr()),
386 base::TimeDelta::FromMilliseconds(delay));
389 bool GpuCommandBufferStub::MakeCurrent() {
390 if (decoder_->MakeCurrent())
391 return true;
392 DLOG(ERROR) << "Context lost because MakeCurrent failed.";
393 command_buffer_->SetContextLostReason(decoder_->GetContextLostReason());
394 command_buffer_->SetParseError(gpu::error::kLostContext);
395 CheckContextLost();
396 return false;
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(
411 active_url_));
414 memory_manager_client_state_.reset();
416 while (!sync_points_.empty())
417 OnRetireSyncPoint(sync_points_.front());
419 if (decoder_)
420 decoder_->set_engine(NULL);
422 // The scheduler has raw references to the decoder and the command buffer so
423 // destroy it before those.
424 scheduler_.reset();
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());
434 if (decoder_) {
435 decoder_->Destroy(have_context);
436 decoder_.reset();
439 command_buffer_.reset();
441 // Remove this after crbug.com/248395 is sorted out.
442 surface_ = NULL;
445 void GpuCommandBufferStub::OnInitializeFailed(IPC::Message* reply_message) {
446 Destroy();
447 GpuCommandBufferMsg_Initialize::WriteReplyParams(
448 reply_message, false, gpu::Capabilities());
449 Send(reply_message);
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();
465 DCHECK(result);
467 decoder_.reset(::gpu::gles2::GLES2Decoder::Create(context_group_.get()));
469 scheduler_.reset(new gpu::GpuScheduler(command_buffer_.get(),
470 decoder_.get(),
471 decoder_.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)
479 if (software_) {
480 LOG(ERROR) << "No software support.";
481 OnInitializeFailed(reply_message);
482 return;
484 #endif
486 surface_ = ImageTransportSurface::CreateSurface(
487 channel_->gpu_channel_manager(),
488 this,
489 handle_);
490 } else {
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);
498 return;
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(),
508 gpu_preference_);
509 if (!context.get()) {
510 DLOG(ERROR) << "Failed to create shared context for virtualization.";
511 OnInitializeFailed(reply_message);
512 return;
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.
525 context = NULL;
527 DLOG(ERROR) << "Failed to initialize virtual GL context.";
528 OnInitializeFailed(reply_message);
529 return;
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);
539 return;
542 if (!context->MakeCurrent(surface_.get())) {
543 LOG(ERROR) << "Failed to make context current.";
544 OnInitializeFailed(reply_message);
545 return;
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_,
563 context,
564 !surface_id(),
565 initial_size_,
566 disallowed_features_,
567 requested_attribs_)) {
568 DLOG(ERROR) << "Failed to initialize decoder.";
569 OnInitializeFailed(reply_message);
570 return;
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_)));
599 if (watchdog_) {
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);
609 return;
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);
619 Send(reply_message);
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(
624 active_url_));
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);
632 #else
633 *succeeded = false;
634 #endif
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) {
647 if (*it++ == attr) {
648 return *it;
651 return -1;
654 void GpuCommandBufferStub::OnSetGetBuffer(int32 shm_id,
655 IPC::Message* reply_message) {
656 TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnSetGetBuffer");
657 if (command_buffer_)
658 command_buffer_->SetGetBuffer(shm_id);
659 Send(reply_message);
662 void GpuCommandBufferStub::OnProduceFrontBuffer(const gpu::Mailbox& mailbox) {
663 TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnProduceFrontBuffer");
664 if (!decoder_) {
665 LOG(ERROR) << "Can't produce front buffer before initialization.";
666 return;
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);
679 Send(msg);
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_));
688 CheckContextLost();
691 void GpuCommandBufferStub::OnWaitForTokenInRange(int32 start,
692 int32 end,
693 IPC::Message* reply_message) {
694 TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnWaitForTokenInRange");
695 DCHECK(command_buffer_.get());
696 CheckContextLost();
697 if (wait_for_token_)
698 LOG(ERROR) << "Got WaitForToken command while currently waiting for token.";
699 wait_for_token_ =
700 make_scoped_ptr(new WaitForCommandState(start, end, reply_message));
701 CheckCompleteWaits();
704 void GpuCommandBufferStub::OnWaitForGetOffsetInRange(
705 int32 start,
706 int32 end,
707 IPC::Message* reply_message) {
708 TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnWaitForGetOffsetInRange");
709 DCHECK(command_buffer_.get());
710 CheckContextLost();
711 if (wait_for_get_offset_) {
712 LOG(ERROR)
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)) {
727 ReportState();
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,
736 state.get_offset) ||
737 state.error != gpu::error::kNoError)) {
738 ReportState();
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(
748 int32 put_offset,
749 uint32 flush_count,
750 const std::vector<ui::LatencyInfo>& latency_info) {
751 TRACE_EVENT1(
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);
763 } else {
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";
769 ReportState();
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)
778 ReportState();
781 void GpuCommandBufferStub::OnRegisterTransferBuffer(
782 int32 id,
783 base::SharedMemoryHandle transfer_buffer,
784 uint32 size) {
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.";
793 return;
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");
805 if (command_buffer_)
806 command_buffer_->DestroyTransferBuffer(id);
809 void GpuCommandBufferStub::OnCommandProcessed() {
810 if (watchdog_)
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,
844 input_visible_size,
845 output_profile,
846 initial_bitrate,
847 reply_message);
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) {
870 if (!sync_point)
871 return true;
872 GpuChannelManager* manager = channel_->gpu_channel_manager();
873 if (manager->sync_point_manager()->IsSyncPointRetired(sync_point))
874 return true;
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(
883 sync_point,
884 base::Bind(&GpuCommandBufferStub::OnSyncPointRetired,
885 this->AsWeakPtr()));
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(
901 sync_point,
902 base::Bind(&GpuCommandBufferStub::OnSignalSyncPointAck,
903 this->AsWeakPtr(),
904 id));
907 void GpuCommandBufferStub::OnSignalSyncPointAck(uint32 id) {
908 Send(new GpuCommandBufferMsg_SignalSyncPointAck(route_id_, id));
911 void GpuCommandBufferStub::OnSignalQuery(uint32 query_id, uint32 id) {
912 if (decoder_) {
913 gpu::gles2::QueryManager* query_manager = decoder_->GetQueryManager();
914 if (query_manager) {
915 gpu::gles2::QueryManager::Query* query =
916 query_manager->GetQuery(query_id);
917 if (query) {
918 query->AddCallback(
919 base::Bind(&GpuCommandBufferStub::OnSignalSyncPointAck,
920 this->AsWeakPtr(),
921 id));
922 return;
926 // Something went wrong, run callback immediately.
927 OnSignalSyncPointAck(id);
931 void GpuCommandBufferStub::OnSetClientHasMemoryAllocationChangedCallback(
932 bool has_callback) {
933 TRACE_EVENT0(
934 "gpu",
935 "GpuCommandBufferStub::OnSetClientHasMemoryAllocationChangedCallback");
936 if (has_callback) {
937 if (!memory_manager_client_state_) {
938 memory_manager_client_state_.reset(GetMemoryManager()->CreateClientState(
939 this, surface_id_ != 0, true));
941 } else {
942 memory_manager_client_state_.reset();
946 void GpuCommandBufferStub::OnCreateImage(int32 id,
947 gfx::GpuMemoryBufferHandle handle,
948 gfx::Size size,
949 gfx::GpuMemoryBuffer::Format format,
950 uint32 internalformat) {
951 TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnCreateImage");
953 if (!decoder_)
954 return;
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.";
960 return;
963 scoped_refptr<gfx::GLImage> image = channel()->CreateImageForGpuMemoryBuffer(
964 handle, size, format, internalformat);
965 if (!image.get())
966 return;
968 image_manager->AddImage(image.get(), id);
971 void GpuCommandBufferStub::OnDestroyImage(int32 id) {
972 TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnDestroyImage");
974 if (!decoder_)
975 return;
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.";
981 return;
984 image_manager->RemoveImage(id);
987 void GpuCommandBufferStub::SendConsoleMessage(
988 int32 id,
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);
996 Send(msg);
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;
1017 if (scheduler_)
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())
1028 return gfx::Size();
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();
1067 return was_lost;
1070 void GpuCommandBufferStub::MarkContextLost() {
1071 if (!command_buffer_ ||
1072 command_buffer_->GetLastState().error == gpu::error::kLostContext)
1073 return;
1075 command_buffer_->SetContextLostReason(gpu::error::kUnknown);
1076 if (decoder_)
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