2 * Copyright (c) 2011 Sveriges Television AB <info@casparcg.com>
4 * This file is part of CasparCG (www.casparcg.com).
6 * CasparCG is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * CasparCG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with CasparCG. If not, see <http://www.gnu.org/licenses/>.
19 * Author: Robert Nagy, ronag89@gmail.com
24 #include "../../StdAfx.h"
32 #include <common/assert.h>
33 #include <common/except.h>
34 #include <common/future.h>
35 #include <common/array.h>
36 #include <common/memory.h>
37 #include <common/gl/gl_check.h>
38 #include <common/timer.h>
42 #include <SFML/Window/Context.hpp>
44 #include <tbb/concurrent_unordered_map.h>
45 #include <tbb/concurrent_hash_map.h>
46 #include <tbb/concurrent_queue.h>
48 #include <boost/utility/declval.hpp>
49 #include <boost/property_tree/ptree.hpp>
52 #include <unordered_map>
55 #include <tbb/parallel_for.h>
57 namespace caspar { namespace accelerator { namespace ogl {
59 struct device::impl : public std::enable_shared_from_this<impl>
61 static_assert(std::is_same<decltype(boost::declval<device>().impl_), spl::shared_ptr<impl>>::value, "impl_ must be shared_ptr");
63 tbb::concurrent_hash_map<buffer*, std::shared_ptr<texture>> texture_cache_;
65 std::unique_ptr<sf::Context> device_;
67 std::array<tbb::concurrent_unordered_map<std::size_t, tbb::concurrent_bounded_queue<std::shared_ptr<texture>>>, 8> device_pools_;
68 std::array<tbb::concurrent_unordered_map<std::size_t, tbb::concurrent_bounded_queue<std::shared_ptr<buffer>>>, 2> host_pools_;
74 impl(executor& executor)
77 executor_.set_capacity(256);
79 CASPAR_LOG(info) << L"Initializing OpenGL Device.";
83 device_.reset(new sf::Context());
84 device_->setActive(true);
86 if (glewInit() != GLEW_OK)
87 CASPAR_THROW_EXCEPTION(gl::ogl_exception() << msg_info("Failed to initialize GLEW."));
90 CASPAR_THROW_EXCEPTION(not_supported() << msg_info("Your graphics card does not meet the minimum hardware requirements since it does not support OpenGL 3.0 or higher."));
92 glGenFramebuffers(1, &fbo_);
93 glBindFramebuffer(GL_FRAMEBUFFER, fbo_);
96 CASPAR_LOG(info) << L"Successfully initialized OpenGL " << version();
103 texture_cache_.clear();
105 for (auto& pool : host_pools_)
108 for (auto& pool : device_pools_)
111 glDeleteFramebuffers(1, &fbo_);
117 boost::property_tree::wptree info() const
119 boost::property_tree::wptree info;
121 boost::property_tree::wptree pooled_device_buffers;
122 size_t total_pooled_device_buffer_size = 0;
123 size_t total_pooled_device_buffer_count = 0;
125 for (size_t i = 0; i < device_pools_.size(); ++i)
127 auto& pools = device_pools_.at(i);
128 bool mipmapping = i > 3;
129 auto stride = mipmapping ? i - 3 : i + 1;
131 for (auto& pool : pools)
133 auto width = pool.first >> 16;
134 auto height = pool.first & 0x0000FFFF;
135 auto size = width * height * stride;
136 auto count = pool.second.size();
141 boost::property_tree::wptree pool_info;
143 pool_info.add(L"stride", stride);
144 pool_info.add(L"mipmapping", mipmapping);
145 pool_info.add(L"width", width);
146 pool_info.add(L"height", height);
147 pool_info.add(L"size", size);
148 pool_info.add(L"count", count);
150 total_pooled_device_buffer_size += size * count;
151 total_pooled_device_buffer_count += count;
153 pooled_device_buffers.add_child(L"device_buffer_pool", pool_info);
157 info.add_child(L"gl.details.pooled_device_buffers", pooled_device_buffers);
159 boost::property_tree::wptree pooled_host_buffers;
160 size_t total_read_size = 0;
161 size_t total_write_size = 0;
162 size_t total_read_count = 0;
163 size_t total_write_count = 0;
165 for (size_t i = 0; i < host_pools_.size(); ++i)
167 auto& pools = host_pools_.at(i);
168 auto usage = static_cast<buffer::usage>(i);
170 for (auto& pool : pools)
172 auto size = pool.first;
173 auto count = pool.second.size();
178 boost::property_tree::wptree pool_info;
180 pool_info.add(L"usage", usage == buffer::usage::read_only ? L"read_only" : L"write_only");
181 pool_info.add(L"size", size);
182 pool_info.add(L"count", count);
184 pooled_host_buffers.add_child(L"host_buffer_pool", pool_info);
186 (usage == buffer::usage::read_only ? total_read_count : total_write_count) += count;
187 (usage == buffer::usage::read_only ? total_read_size : total_write_size) += size * count;
191 info.add_child(L"gl.details.pooled_host_buffers", pooled_host_buffers);
192 info.add(L"gl.summary.pooled_device_buffers.total_count", total_pooled_device_buffer_count);
193 info.add(L"gl.summary.pooled_device_buffers.total_size", total_pooled_device_buffer_size);
194 info.add_child(L"gl.summary.all_device_buffers", texture::info());
195 info.add(L"gl.summary.pooled_host_buffers.total_read_count", total_read_count);
196 info.add(L"gl.summary.pooled_host_buffers.total_write_count", total_write_count);
197 info.add(L"gl.summary.pooled_host_buffers.total_read_size", total_read_size);
198 info.add(L"gl.summary.pooled_host_buffers.total_write_size", total_write_size);
199 info.add_child(L"gl.summary.all_host_buffers", buffer::info());
204 std::wstring version()
208 return executor_.invoke([]
210 return u16(reinterpret_cast<const char*>(GL2(glGetString(GL_VERSION)))) + L" " + u16(reinterpret_cast<const char*>(GL2(glGetString(GL_VENDOR))));
215 return L"Not found";;
219 spl::shared_ptr<texture> create_texture(int width, int height, int stride, bool mipmapped, bool clear)
221 CASPAR_VERIFY(stride > 0 && stride < 5);
222 CASPAR_VERIFY(width > 0 && height > 0);
224 if(!executor_.is_current())
225 CASPAR_THROW_EXCEPTION(invalid_operation() << msg_info("Operation only valid in an OpenGL Context."));
227 auto pool = &device_pools_[stride - 1 + (mipmapped ? 4 : 0)][((width << 16) & 0xFFFF0000) | (height & 0x0000FFFF)];
229 std::shared_ptr<texture> tex;
230 if(!pool->try_pop(tex))
231 tex = spl::make_shared<texture>(width, height, stride, mipmapped);
236 return spl::shared_ptr<texture>(tex.get(), [tex, pool](texture*) mutable
242 spl::shared_ptr<buffer> create_buffer(std::size_t size, buffer::usage usage)
244 CASPAR_VERIFY(size > 0);
246 auto pool = &host_pools_[static_cast<int>(usage)][size];
248 std::shared_ptr<buffer> buf;
249 if(!pool->try_pop(buf))
253 buf = executor_.invoke([&]
255 return std::make_shared<buffer>(size, usage);
256 }, task_priority::high_priority);
258 if(timer.elapsed() > 0.02)
259 CASPAR_LOG(warning) << L"[ogl-device] Performance warning. Buffer allocation blocked: " << timer.elapsed();
262 std::weak_ptr<impl> self = shared_from_this(); // buffers can leave the device context, take a hold on life-time.
263 return spl::shared_ptr<buffer>(buf.get(), [=](buffer*) mutable
265 auto strong = self.lock();
269 strong->texture_cache_.erase(buf.get());
274 CASPAR_LOG(info) << L"Buffer outlived ogl device";
279 array<std::uint8_t> create_array(std::size_t size)
281 auto buf = create_buffer(size, buffer::usage::write_only);
282 return array<std::uint8_t>(buf->data(), buf->size(), false, buf);
286 std::shared_ptr<buffer> copy_to_buf(const T& source)
288 std::shared_ptr<buffer> buf;
290 auto tmp = source.template storage<spl::shared_ptr<buffer>>();
295 buf = create_buffer(source.size(), buffer::usage::write_only);
296 tbb::parallel_for(tbb::blocked_range<std::size_t>(0, source.size()), [&](const tbb::blocked_range<std::size_t>& r)
298 A_memcpy(buf->data() + r.begin(), source.data() + r.begin(), r.size());
305 // TODO: Since the returned texture is cached it SHOULD NOT be modified.
306 std::future<std::shared_ptr<texture>> copy_async(const array<const std::uint8_t>& source, int width, int height, int stride, bool mipmapped)
308 std::shared_ptr<buffer> buf = copy_to_buf(source);
310 return executor_.begin_invoke([=]() -> std::shared_ptr<texture>
312 tbb::concurrent_hash_map<buffer*, std::shared_ptr<texture>>::const_accessor a;
313 if(texture_cache_.find(a, buf.get()))
314 return spl::make_shared_ptr(a->second);
316 auto texture = create_texture(width, height, stride, mipmapped, false);
317 texture->copy_from(*buf);
319 texture_cache_.insert(std::make_pair(buf.get(), texture));
322 }, task_priority::high_priority);
325 std::future<std::shared_ptr<texture>> copy_async(const array<std::uint8_t>& source, int width, int height, int stride, bool mipmapped)
327 std::shared_ptr<buffer> buf = copy_to_buf(source);
329 return executor_.begin_invoke([=]() -> std::shared_ptr<texture>
331 auto texture = create_texture(width, height, stride, mipmapped, false);
332 texture->copy_from(*buf);
335 }, task_priority::high_priority);
338 std::future<array<const std::uint8_t>> copy_async(const spl::shared_ptr<texture>& source)
340 if(!executor_.is_current())
341 CASPAR_THROW_EXCEPTION(invalid_operation() << msg_info("Operation only valid in an OpenGL Context."));
343 auto buffer = create_buffer(source->size(), buffer::usage::read_only);
344 source->copy_to(*buffer);
346 auto self = shared_from_this();
347 auto cmd = [self, buffer]() mutable -> array<const std::uint8_t>
349 self->executor_.invoke(std::bind(&buffer::map, std::ref(buffer))); // Defer blocking "map" call until data is needed.
350 return array<const std::uint8_t>(buffer->data(), buffer->size(), true, buffer);
352 return std::async(std::launch::deferred, std::move(cmd));
355 std::future<void> gc()
357 return executor_.begin_invoke([=]
359 CASPAR_LOG(info) << " ogl: Running GC.";
363 for (auto& pools : device_pools_)
365 for (auto& pool : pools)
368 for (auto& pools : host_pools_)
370 for (auto& pool : pools)
376 CASPAR_LOG_CURRENT_EXCEPTION();
378 }, task_priority::high_priority);
383 : executor_(L"OpenGL Rendering Context")
384 , impl_(new impl(executor_)){}
386 spl::shared_ptr<texture> device::create_texture(int width, int height, int stride, bool mipmapped){ return impl_->create_texture(width, height, stride, mipmapped, true); }
387 array<std::uint8_t> device::create_array(int size){return impl_->create_array(size);}
388 std::future<std::shared_ptr<texture>> device::copy_async(const array<const std::uint8_t>& source, int width, int height, int stride, bool mipmapped){return impl_->copy_async(source, width, height, stride, mipmapped);}
389 std::future<std::shared_ptr<texture>> device::copy_async(const array<std::uint8_t>& source, int width, int height, int stride, bool mipmapped){ return impl_->copy_async(source, width, height, stride, mipmapped); }
390 std::future<array<const std::uint8_t>> device::copy_async(const spl::shared_ptr<texture>& source){return impl_->copy_async(source);}
391 std::future<void> device::gc() { return impl_->gc(); }
392 boost::property_tree::wptree device::info() const { return impl_->info(); }
393 std::wstring device::version() const{return impl_->version();}