[Android WebView] Upstream WebViewShell to chromium.
[chromium-blink-merge.git] / cc / resources / resource_provider.h
blob70b7fc7bb75ac0475ba5a073594b2a3f93744857
1 // Copyright 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 #ifndef CC_RESOURCES_RESOURCE_PROVIDER_H_
6 #define CC_RESOURCES_RESOURCE_PROVIDER_H_
8 #include <deque>
9 #include <set>
10 #include <string>
11 #include <utility>
12 #include <vector>
14 #include "base/basictypes.h"
15 #include "base/callback.h"
16 #include "base/containers/hash_tables.h"
17 #include "base/memory/linked_ptr.h"
18 #include "base/memory/scoped_ptr.h"
19 #include "base/threading/thread_checker.h"
20 #include "cc/base/cc_export.h"
21 #include "cc/output/context_provider.h"
22 #include "cc/output/output_surface.h"
23 #include "cc/resources/release_callback_impl.h"
24 #include "cc/resources/resource_format.h"
25 #include "cc/resources/return_callback.h"
26 #include "cc/resources/shared_bitmap.h"
27 #include "cc/resources/single_release_callback_impl.h"
28 #include "cc/resources/texture_mailbox.h"
29 #include "cc/resources/transferable_resource.h"
30 #include "third_party/khronos/GLES2/gl2.h"
31 #include "third_party/khronos/GLES2/gl2ext.h"
32 #include "third_party/skia/include/core/SkBitmap.h"
33 #include "third_party/skia/include/core/SkCanvas.h"
34 #include "ui/gfx/geometry/size.h"
36 class GrContext;
38 namespace gpu {
39 class GpuMemoryBufferManager;
40 namespace gles {
41 class GLES2Interface;
45 namespace gfx {
46 class GpuMemoryBuffer;
47 class Rect;
48 class Vector2d;
51 namespace cc {
52 class BlockingTaskRunner;
53 class IdAllocator;
54 class SharedBitmap;
55 class SharedBitmapManager;
56 class TextureUploader;
58 // This class is not thread-safe and can only be called from the thread it was
59 // created on (in practice, the impl thread).
60 class CC_EXPORT ResourceProvider {
61 private:
62 struct Resource;
64 public:
65 typedef unsigned ResourceId;
66 typedef std::vector<ResourceId> ResourceIdArray;
67 typedef base::hash_set<ResourceId> ResourceIdSet;
68 typedef base::hash_map<ResourceId, ResourceId> ResourceIdMap;
69 enum TextureHint {
70 TEXTURE_HINT_DEFAULT = 0x0,
71 TEXTURE_HINT_IMMUTABLE = 0x1,
72 TEXTURE_HINT_FRAMEBUFFER = 0x2,
73 TEXTURE_HINT_IMMUTABLE_FRAMEBUFFER =
74 TEXTURE_HINT_IMMUTABLE | TEXTURE_HINT_FRAMEBUFFER
76 enum ResourceType {
77 RESOURCE_TYPE_GL_TEXTURE,
78 RESOURCE_TYPE_BITMAP,
81 static scoped_ptr<ResourceProvider> Create(
82 OutputSurface* output_surface,
83 SharedBitmapManager* shared_bitmap_manager,
84 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
85 BlockingTaskRunner* blocking_main_thread_task_runner,
86 int highp_threshold_min,
87 bool use_rgba_4444_texture_format,
88 size_t id_allocation_chunk_size);
89 virtual ~ResourceProvider();
91 void DidLoseOutputSurface() { lost_output_surface_ = true; }
93 int max_texture_size() const { return max_texture_size_; }
94 ResourceFormat memory_efficient_texture_format() const {
95 return use_rgba_4444_texture_format_ ? RGBA_4444 : best_texture_format_;
97 ResourceFormat best_texture_format() const { return best_texture_format_; }
98 ResourceFormat yuv_resource_format() const { return yuv_resource_format_; }
99 bool use_sync_query() const { return use_sync_query_; }
100 size_t num_resources() const { return resources_.size(); }
102 // Checks whether a resource is in use by a consumer.
103 bool InUseByConsumer(ResourceId id);
105 bool IsLost(ResourceId id);
106 bool AllowOverlay(ResourceId id);
108 // Producer interface.
110 ResourceType default_resource_type() const { return default_resource_type_; }
111 ResourceType GetResourceType(ResourceId id);
113 // Creates a resource of the default resource type.
114 ResourceId CreateResource(const gfx::Size& size,
115 GLint wrap_mode,
116 TextureHint hint,
117 ResourceFormat format);
119 // Creates a resource which is tagged as being managed for GPU memory
120 // accounting purposes.
121 ResourceId CreateManagedResource(const gfx::Size& size,
122 GLenum target,
123 GLint wrap_mode,
124 TextureHint hint,
125 ResourceFormat format);
127 // You can also explicitly create a specific resource type.
128 ResourceId CreateGLTexture(const gfx::Size& size,
129 GLenum target,
130 GLenum texture_pool,
131 GLint wrap_mode,
132 TextureHint hint,
133 ResourceFormat format);
135 ResourceId CreateBitmap(const gfx::Size& size, GLint wrap_mode);
136 // Wraps an IOSurface into a GL resource.
137 ResourceId CreateResourceFromIOSurface(const gfx::Size& size,
138 unsigned io_surface_id);
140 // Wraps an external texture mailbox into a GL resource.
141 ResourceId CreateResourceFromTextureMailbox(
142 const TextureMailbox& mailbox,
143 scoped_ptr<SingleReleaseCallbackImpl> release_callback_impl);
145 void DeleteResource(ResourceId id);
147 // Update pixels from image, copying source_rect (in image) to dest_offset (in
148 // the resource).
149 // NOTE: DEPRECATED. Use CopyToResource() instead.
150 void SetPixels(ResourceId id,
151 const uint8_t* image,
152 const gfx::Rect& image_rect,
153 const gfx::Rect& source_rect,
154 const gfx::Vector2d& dest_offset);
155 void CopyToResource(ResourceId id,
156 const uint8_t* image,
157 const gfx::Size& image_size);
159 // Check upload status.
160 size_t NumBlockingUploads();
161 void MarkPendingUploadsAsNonBlocking();
162 size_t EstimatedUploadsPerTick();
163 void FlushUploads();
164 void ReleaseCachedData();
165 base::TimeTicks EstimatedUploadCompletionTime(size_t uploads_per_tick);
167 // Only flush the command buffer if supported.
168 // Returns true if the shallow flush occurred, false otherwise.
169 bool ShallowFlushIfSupported();
171 // Creates accounting for a child. Returns a child ID.
172 int CreateChild(const ReturnCallback& return_callback);
174 // Destroys accounting for the child, deleting all accounted resources.
175 void DestroyChild(int child);
177 // Sets whether resources need sync points set on them when returned to this
178 // child. Defaults to true.
179 void SetChildNeedsSyncPoints(int child, bool needs_sync_points);
181 // Gets the child->parent resource ID map.
182 const ResourceIdMap& GetChildToParentMap(int child) const;
184 // Prepares resources to be transfered to the parent, moving them to
185 // mailboxes and serializing meta-data into TransferableResources.
186 // Resources are not removed from the ResourceProvider, but are marked as
187 // "in use".
188 void PrepareSendToParent(const ResourceIdArray& resources,
189 TransferableResourceArray* transferable_resources);
191 // Receives resources from a child, moving them from mailboxes. Resource IDs
192 // passed are in the child namespace, and will be translated to the parent
193 // namespace, added to the child->parent map.
194 // This adds the resources to the working set in the ResourceProvider without
195 // declaring which resources are in use. Use DeclareUsedResourcesFromChild
196 // after calling this method to do that. All calls to ReceiveFromChild should
197 // be followed by a DeclareUsedResourcesFromChild.
198 // NOTE: if the sync_point is set on any TransferableResource, this will
199 // wait on it.
200 void ReceiveFromChild(
201 int child, const TransferableResourceArray& transferable_resources);
203 // Once a set of resources have been received, they may or may not be used.
204 // This declares what set of resources are currently in use from the child,
205 // releasing any other resources back to the child.
206 void DeclareUsedResourcesFromChild(int child,
207 const ResourceIdSet& resources_from_child);
209 // Receives resources from the parent, moving them from mailboxes. Resource
210 // IDs passed are in the child namespace.
211 // NOTE: if the sync_point is set on any TransferableResource, this will
212 // wait on it.
213 void ReceiveReturnsFromParent(
214 const ReturnedResourceArray& transferable_resources);
216 // The following lock classes are part of the ResourceProvider API and are
217 // needed to read and write the resource contents. The user must ensure
218 // that they only use GL locks on GL resources, etc, and this is enforced
219 // by assertions.
220 class CC_EXPORT ScopedReadLockGL {
221 public:
222 ScopedReadLockGL(ResourceProvider* resource_provider,
223 ResourceProvider::ResourceId resource_id);
224 virtual ~ScopedReadLockGL();
226 unsigned texture_id() const { return texture_id_; }
228 protected:
229 ResourceProvider* resource_provider_;
230 ResourceProvider::ResourceId resource_id_;
232 private:
233 unsigned texture_id_;
235 DISALLOW_COPY_AND_ASSIGN(ScopedReadLockGL);
238 class CC_EXPORT ScopedSamplerGL : public ScopedReadLockGL {
239 public:
240 ScopedSamplerGL(ResourceProvider* resource_provider,
241 ResourceProvider::ResourceId resource_id,
242 GLenum filter);
243 ScopedSamplerGL(ResourceProvider* resource_provider,
244 ResourceProvider::ResourceId resource_id,
245 GLenum unit,
246 GLenum filter);
247 ~ScopedSamplerGL() override;
249 GLenum target() const { return target_; }
251 private:
252 GLenum unit_;
253 GLenum target_;
255 DISALLOW_COPY_AND_ASSIGN(ScopedSamplerGL);
258 class CC_EXPORT ScopedWriteLockGL {
259 public:
260 ScopedWriteLockGL(ResourceProvider* resource_provider,
261 ResourceProvider::ResourceId resource_id);
262 ~ScopedWriteLockGL();
264 unsigned texture_id() const { return texture_id_; }
266 private:
267 ResourceProvider* resource_provider_;
268 ResourceProvider::Resource* resource_;
269 unsigned texture_id_;
271 DISALLOW_COPY_AND_ASSIGN(ScopedWriteLockGL);
274 class CC_EXPORT ScopedReadLockSoftware {
275 public:
276 ScopedReadLockSoftware(ResourceProvider* resource_provider,
277 ResourceProvider::ResourceId resource_id);
278 ~ScopedReadLockSoftware();
280 const SkBitmap* sk_bitmap() const {
281 DCHECK(valid());
282 return &sk_bitmap_;
284 GLint wrap_mode() const { return wrap_mode_; }
286 bool valid() const { return !!sk_bitmap_.getPixels(); }
288 private:
289 ResourceProvider* resource_provider_;
290 ResourceProvider::ResourceId resource_id_;
291 SkBitmap sk_bitmap_;
292 GLint wrap_mode_;
294 DISALLOW_COPY_AND_ASSIGN(ScopedReadLockSoftware);
297 class CC_EXPORT ScopedWriteLockSoftware {
298 public:
299 ScopedWriteLockSoftware(ResourceProvider* resource_provider,
300 ResourceProvider::ResourceId resource_id);
301 ~ScopedWriteLockSoftware();
303 SkBitmap& sk_bitmap() { return sk_bitmap_; }
304 bool valid() const { return !!sk_bitmap_.getPixels(); }
306 private:
307 ResourceProvider* resource_provider_;
308 ResourceProvider::Resource* resource_;
309 SkBitmap sk_bitmap_;
310 base::ThreadChecker thread_checker_;
312 DISALLOW_COPY_AND_ASSIGN(ScopedWriteLockSoftware);
315 class CC_EXPORT ScopedWriteLockGpuMemoryBuffer {
316 public:
317 ScopedWriteLockGpuMemoryBuffer(ResourceProvider* resource_provider,
318 ResourceProvider::ResourceId resource_id);
319 ~ScopedWriteLockGpuMemoryBuffer();
321 gfx::GpuMemoryBuffer* GetGpuMemoryBuffer();
323 private:
324 ResourceProvider* resource_provider_;
325 ResourceProvider::Resource* resource_;
326 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager_;
327 gfx::GpuMemoryBuffer* gpu_memory_buffer_;
328 gfx::Size size_;
329 ResourceFormat format_;
330 base::ThreadChecker thread_checker_;
332 DISALLOW_COPY_AND_ASSIGN(ScopedWriteLockGpuMemoryBuffer);
335 class CC_EXPORT ScopedWriteLockGr {
336 public:
337 ScopedWriteLockGr(ResourceProvider* resource_provider,
338 ResourceProvider::ResourceId resource_id);
339 ~ScopedWriteLockGr();
341 void InitSkSurface(bool use_distance_field_text,
342 bool can_use_lcd_text,
343 int msaa_sample_count);
344 void ReleaseSkSurface();
346 SkSurface* sk_surface() { return sk_surface_.get(); }
347 ResourceProvider::Resource* resource() { return resource_; }
349 private:
350 ResourceProvider* resource_provider_;
351 ResourceProvider::Resource* resource_;
352 base::ThreadChecker thread_checker_;
353 skia::RefPtr<SkSurface> sk_surface_;
355 DISALLOW_COPY_AND_ASSIGN(ScopedWriteLockGr);
358 class Fence : public base::RefCounted<Fence> {
359 public:
360 Fence() {}
362 virtual void Set() = 0;
363 virtual bool HasPassed() = 0;
364 virtual void Wait() = 0;
366 protected:
367 friend class base::RefCounted<Fence>;
368 virtual ~Fence() {}
370 private:
371 DISALLOW_COPY_AND_ASSIGN(Fence);
374 class SynchronousFence : public ResourceProvider::Fence {
375 public:
376 explicit SynchronousFence(gpu::gles2::GLES2Interface* gl);
378 // Overridden from Fence:
379 void Set() override;
380 bool HasPassed() override;
381 void Wait() override;
383 // Returns true if fence has been set but not yet synchornized.
384 bool has_synchronized() const { return has_synchronized_; }
386 private:
387 ~SynchronousFence() override;
389 void Synchronize();
391 gpu::gles2::GLES2Interface* gl_;
392 bool has_synchronized_;
394 DISALLOW_COPY_AND_ASSIGN(SynchronousFence);
397 // Acquire pixel buffer for resource. The pixel buffer can be used to
398 // set resource pixels without performing unnecessary copying.
399 void AcquirePixelBuffer(ResourceId resource);
400 void ReleasePixelBuffer(ResourceId resource);
401 // Map/unmap the acquired pixel buffer.
402 uint8_t* MapPixelBuffer(ResourceId id, int* stride);
403 void UnmapPixelBuffer(ResourceId id);
404 // Asynchronously update pixels from acquired pixel buffer.
405 void BeginSetPixels(ResourceId id);
406 void ForceSetPixelsToComplete(ResourceId id);
407 bool DidSetPixelsComplete(ResourceId id);
409 // For tests only! This prevents detecting uninitialized reads.
410 // Use SetPixels or LockForWrite to allocate implicitly.
411 void AllocateForTesting(ResourceId id);
413 // For tests only!
414 void CreateForTesting(ResourceId id);
416 GLenum TargetForTesting(ResourceId id);
418 // Sets the current read fence. If a resource is locked for read
419 // and has read fences enabled, the resource will not allow writes
420 // until this fence has passed.
421 void SetReadLockFence(Fence* fence) { current_read_lock_fence_ = fence; }
423 // Indicates if we can currently lock this resource for write.
424 bool CanLockForWrite(ResourceId id);
426 // Copy pixels from source to destination.
427 void CopyResource(ResourceId source_id, ResourceId dest_id);
429 void WaitSyncPointIfNeeded(ResourceId id);
431 void WaitReadLockIfNeeded(ResourceId id);
433 static GLint GetActiveTextureUnit(gpu::gles2::GLES2Interface* gl);
435 OutputSurface* output_surface() { return output_surface_; }
437 void ValidateResource(ResourceId id);
439 private:
440 struct Resource {
441 enum Origin { INTERNAL, EXTERNAL, DELEGATED };
443 ~Resource();
444 Resource(unsigned texture_id,
445 const gfx::Size& size,
446 Origin origin,
447 GLenum target,
448 GLenum filter,
449 GLenum texture_pool,
450 GLint wrap_mode,
451 TextureHint hint,
452 ResourceFormat format);
453 Resource(uint8_t* pixels,
454 SharedBitmap* bitmap,
455 const gfx::Size& size,
456 Origin origin,
457 GLenum filter,
458 GLint wrap_mode);
459 Resource(const SharedBitmapId& bitmap_id,
460 const gfx::Size& size,
461 Origin origin,
462 GLenum filter,
463 GLint wrap_mode);
465 int child_id;
466 unsigned gl_id;
467 // Pixel buffer used for set pixels without unnecessary copying.
468 unsigned gl_pixel_buffer_id;
469 // Query used to determine when asynchronous set pixels complete.
470 unsigned gl_upload_query_id;
471 // Query used to determine when read lock fence has passed.
472 unsigned gl_read_lock_query_id;
473 TextureMailbox mailbox;
474 ReleaseCallbackImpl release_callback_impl;
475 uint8_t* pixels;
476 int lock_for_read_count;
477 int imported_count;
478 int exported_count;
479 bool dirty_image : 1;
480 bool locked_for_write : 1;
481 bool lost : 1;
482 bool marked_for_deletion : 1;
483 bool pending_set_pixels : 1;
484 bool set_pixels_completion_forced : 1;
485 bool allocated : 1;
486 bool read_lock_fences_enabled : 1;
487 bool has_shared_bitmap_id : 1;
488 bool allow_overlay : 1;
489 scoped_refptr<Fence> read_lock_fence;
490 gfx::Size size;
491 Origin origin;
492 GLenum target;
493 // TODO(skyostil): Use a separate sampler object for filter state.
494 GLenum original_filter;
495 GLenum filter;
496 unsigned image_id;
497 unsigned bound_image_id;
498 GLenum texture_pool;
499 GLint wrap_mode;
500 TextureHint hint;
501 ResourceType type;
502 ResourceFormat format;
503 SharedBitmapId shared_bitmap_id;
504 SharedBitmap* shared_bitmap;
505 gfx::GpuMemoryBuffer* gpu_memory_buffer;
507 typedef base::hash_map<ResourceId, Resource> ResourceMap;
509 struct Child {
510 Child();
511 ~Child();
513 ResourceIdMap child_to_parent_map;
514 ResourceIdMap parent_to_child_map;
515 ReturnCallback return_callback;
516 bool marked_for_deletion;
517 bool needs_sync_points;
519 typedef base::hash_map<int, Child> ChildMap;
521 bool ReadLockFenceHasPassed(const Resource* resource) {
522 return !resource->read_lock_fence.get() ||
523 resource->read_lock_fence->HasPassed();
526 ResourceProvider(OutputSurface* output_surface,
527 SharedBitmapManager* shared_bitmap_manager,
528 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
529 BlockingTaskRunner* blocking_main_thread_task_runner,
530 int highp_threshold_min,
531 ResourceType default_resource_type,
532 bool use_rgba_4444_texture_format,
533 size_t id_allocation_chunk_size);
535 void InitializeSoftware();
536 void InitializeGL();
538 Resource* InsertResource(ResourceId id, const Resource& resource);
539 Resource* GetResource(ResourceId id);
540 const Resource* LockForRead(ResourceId id);
541 void UnlockForRead(ResourceId id);
542 Resource* LockForWrite(ResourceId id);
543 void UnlockForWrite(Resource* resource);
545 static void PopulateSkBitmapWithResource(SkBitmap* sk_bitmap,
546 const Resource* resource);
548 void TransferResource(gpu::gles2::GLES2Interface* gl,
549 ResourceId id,
550 TransferableResource* resource);
551 enum DeleteStyle {
552 NORMAL,
553 FOR_SHUTDOWN,
555 void DeleteResourceInternal(ResourceMap::iterator it, DeleteStyle style);
556 void DeleteAndReturnUnusedResourcesToChild(ChildMap::iterator child_it,
557 DeleteStyle style,
558 const ResourceIdArray& unused);
559 void DestroyChildInternal(ChildMap::iterator it, DeleteStyle style);
560 void LazyCreate(Resource* resource);
561 void LazyAllocate(Resource* resource);
563 void BindImageForSampling(Resource* resource);
564 // Binds the given GL resource to a texture target for sampling using the
565 // specified filter for both minification and magnification. Returns the
566 // texture target used. The resource must be locked for reading.
567 GLenum BindForSampling(ResourceId resource_id, GLenum unit, GLenum filter);
569 // Returns NULL if the output_surface_ does not have a ContextProvider.
570 gpu::gles2::GLES2Interface* ContextGL() const;
571 class GrContext* GrContext(bool worker_context) const;
573 OutputSurface* output_surface_;
574 SharedBitmapManager* shared_bitmap_manager_;
575 gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager_;
576 BlockingTaskRunner* blocking_main_thread_task_runner_;
577 bool lost_output_surface_;
578 int highp_threshold_min_;
579 ResourceId next_id_;
580 ResourceMap resources_;
581 int next_child_;
582 ChildMap children_;
584 const ResourceType default_resource_type_;
585 bool use_texture_storage_ext_;
586 bool use_texture_format_bgra_;
587 bool use_texture_usage_hint_;
588 bool use_compressed_texture_etc1_;
589 ResourceFormat yuv_resource_format_;
590 scoped_ptr<TextureUploader> texture_uploader_;
591 int max_texture_size_;
592 ResourceFormat best_texture_format_;
594 base::ThreadChecker thread_checker_;
596 scoped_refptr<Fence> current_read_lock_fence_;
597 bool use_rgba_4444_texture_format_;
599 const size_t id_allocation_chunk_size_;
600 scoped_ptr<IdAllocator> texture_id_allocator_;
601 scoped_ptr<IdAllocator> buffer_id_allocator_;
603 bool use_sync_query_;
604 // Fence used for CopyResource if CHROMIUM_sync_query is not supported.
605 scoped_refptr<SynchronousFence> synchronous_fence_;
607 DISALLOW_COPY_AND_ASSIGN(ResourceProvider);
610 // TODO(epenner): Move these format conversions to resource_format.h
611 // once that builds on mac (npapi.h currently #includes OpenGL.h).
612 inline unsigned BitsPerPixel(ResourceFormat format) {
613 switch (format) {
614 case BGRA_8888:
615 case RGBA_8888:
616 return 32;
617 case RGBA_4444:
618 case RGB_565:
619 return 16;
620 case ALPHA_8:
621 case LUMINANCE_8:
622 case RED_8:
623 return 8;
624 case ETC1:
625 return 4;
627 NOTREACHED();
628 return 0;
631 inline GLenum GLDataType(ResourceFormat format) {
632 DCHECK_LE(format, RESOURCE_FORMAT_MAX);
633 static const unsigned format_gl_data_type[RESOURCE_FORMAT_MAX + 1] = {
634 GL_UNSIGNED_BYTE, // RGBA_8888
635 GL_UNSIGNED_SHORT_4_4_4_4, // RGBA_4444
636 GL_UNSIGNED_BYTE, // BGRA_8888
637 GL_UNSIGNED_BYTE, // ALPHA_8
638 GL_UNSIGNED_BYTE, // LUMINANCE_8
639 GL_UNSIGNED_SHORT_5_6_5, // RGB_565,
640 GL_UNSIGNED_BYTE, // ETC1
641 GL_UNSIGNED_BYTE // RED_8
643 return format_gl_data_type[format];
646 inline GLenum GLDataFormat(ResourceFormat format) {
647 DCHECK_LE(format, RESOURCE_FORMAT_MAX);
648 static const unsigned format_gl_data_format[RESOURCE_FORMAT_MAX + 1] = {
649 GL_RGBA, // RGBA_8888
650 GL_RGBA, // RGBA_4444
651 GL_BGRA_EXT, // BGRA_8888
652 GL_ALPHA, // ALPHA_8
653 GL_LUMINANCE, // LUMINANCE_8
654 GL_RGB, // RGB_565
655 GL_ETC1_RGB8_OES, // ETC1
656 GL_RED_EXT // RED_8
658 return format_gl_data_format[format];
661 inline GLenum GLInternalFormat(ResourceFormat format) {
662 return GLDataFormat(format);
665 } // namespace cc
667 #endif // CC_RESOURCES_RESOURCE_PROVIDER_H_