]> git.sesse.net Git - casparcg/blob - accelerator/ogl/util/device.cpp
6d10667743b5c79c47bd0f38562e719420d94843
[casparcg] / accelerator / ogl / util / device.cpp
1 /*\r
2 * Copyright (c) 2011 Sveriges Television AB <info@casparcg.com>\r
3 *\r
4 * This file is part of CasparCG (www.casparcg.com).\r
5 *\r
6 * CasparCG is free software: you can redistribute it and/or modify\r
7 * it under the terms of the GNU General Public License as published by\r
8 * the Free Software Foundation, either version 3 of the License, or\r
9 * (at your option) any later version.\r
10 *\r
11 * CasparCG is distributed in the hope that it will be useful,\r
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
14 * GNU General Public License for more details.\r
15 *\r
16 * You should have received a copy of the GNU General Public License\r
17 * along with CasparCG. If not, see <http://www.gnu.org/licenses/>.\r
18 *\r
19 * Author: Robert Nagy, ronag89@gmail.com\r
20 */\r
21 \r
22 // TODO: Smart GC\r
23 \r
24 #include "../../stdafx.h"\r
25 \r
26 #include "device.h"\r
27 \r
28 #include "buffer.h"\r
29 #include "texture.h"\r
30 #include "shader.h"\r
31 \r
32 #include <common/assert.h>\r
33 #include <common/except.h>\r
34 #include <common/concurrency/async.h>\r
35 #include <common/memory/array.h>\r
36 #include <common/gl/gl_check.h>\r
37 #include <common/os/windows/windows.h>\r
38 \r
39 #include <boost/foreach.hpp>\r
40 \r
41 #include <gl/glew.h>\r
42 \r
43 #include <SFML/Window/Context.hpp>\r
44 \r
45 #include <tbb/concurrent_unordered_map.h>\r
46 #include <tbb/concurrent_hash_map.h>\r
47 #include <tbb/concurrent_queue.h>\r
48 \r
49 #include <boost/utility/declval.hpp>\r
50 \r
51 #include <array>\r
52 #include <unordered_map>\r
53 \r
54 tbb::atomic<int> g_count = tbb::atomic<int>();\r
55 \r
56 namespace caspar { namespace accelerator { namespace ogl {\r
57                 \r
58 struct device::impl : public std::enable_shared_from_this<impl>\r
59 {       \r
60         static_assert(std::is_same<decltype(boost::declval<device>().impl_), spl::shared_ptr<impl>>::value, "impl_ must be shared_ptr");\r
61 \r
62         tbb::concurrent_hash_map<buffer*, std::shared_ptr<texture>> texture_cache_;\r
63 \r
64         std::unique_ptr<sf::Context> device_;\r
65         std::unique_ptr<sf::Context> host_alloc_device_;\r
66         \r
67         std::array<tbb::concurrent_unordered_map<std::size_t, tbb::concurrent_bounded_queue<std::shared_ptr<texture>>>, 4>      device_pools_;\r
68         std::array<tbb::concurrent_unordered_map<std::size_t, tbb::concurrent_bounded_queue<std::shared_ptr<buffer>>>, 2>       host_pools_;\r
69         \r
70         GLuint fbo_;\r
71 \r
72         executor& render_executor_;\r
73         executor  alloc_executor_;\r
74                                 \r
75         impl(executor& executor) \r
76                 : render_executor_(executor)\r
77                 , alloc_executor_(L"OpenGL allocation context.")\r
78         {\r
79                 if(g_count++ > 1)\r
80                         CASPAR_LOG(warning) << L"Multiple OGL devices.";\r
81 \r
82                 CASPAR_LOG(info) << L"Initializing OpenGL Device.";\r
83                 \r
84                 auto ctx1 = render_executor_.invoke([=]() -> HGLRC \r
85                 {\r
86                         device_.reset(new sf::Context());\r
87                         device_->SetActive(true);               \r
88                                                 \r
89                         if (glewInit() != GLEW_OK)\r
90                                 BOOST_THROW_EXCEPTION(gl::ogl_exception() << msg_info("Failed to initialize GLEW."));\r
91                 \r
92                         if(!GLEW_VERSION_3_0)\r
93                                 BOOST_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."));\r
94         \r
95                         glGenFramebuffers(1, &fbo_);                            \r
96                         glBindFramebuffer(GL_FRAMEBUFFER, fbo_);\r
97                         \r
98                         auto ctx1 = wglGetCurrentContext();\r
99                         \r
100                         device_->SetActive(false);\r
101 \r
102                         return ctx1;\r
103                 });\r
104 \r
105                 alloc_executor_.invoke([=]\r
106                 {\r
107                         host_alloc_device_.reset(new sf::Context());\r
108                         host_alloc_device_->SetActive(true);    \r
109                         auto ctx2 = wglGetCurrentContext();\r
110 \r
111                         if(!wglShareLists(ctx1, ctx2))\r
112                                 BOOST_THROW_EXCEPTION(gl::ogl_exception() << msg_info("Failed to share OpenGL devices."));\r
113                 });\r
114 \r
115                 render_executor_.invoke([=]\r
116                 {               \r
117                         device_->SetActive(true);\r
118                 });\r
119                 \r
120                 CASPAR_LOG(info) << L"Successfully initialized OpenGL " << version();\r
121         }\r
122 \r
123         ~impl()\r
124         {\r
125                 alloc_executor_.invoke([=]\r
126                 {\r
127                         host_alloc_device_.reset();\r
128                         BOOST_FOREACH(auto& pool, host_pools_)\r
129                                 pool.clear();\r
130                 });\r
131 \r
132                 render_executor_.invoke([=]\r
133                 {\r
134                         BOOST_FOREACH(auto& pool, device_pools_)\r
135                                 pool.clear();\r
136                         glDeleteFramebuffers(1, &fbo_);\r
137 \r
138                         device_.reset();\r
139                 });\r
140         }\r
141                 \r
142         std::wstring version()\r
143         {       \r
144                 try\r
145                 {\r
146                         return alloc_executor_.invoke([]\r
147                         {\r
148                                 return u16(reinterpret_cast<const char*>(GL2(glGetString(GL_VERSION)))) + L" " + u16(reinterpret_cast<const char*>(GL2(glGetString(GL_VENDOR))));\r
149                         });     \r
150                 }\r
151                 catch(...)\r
152                 {\r
153                         return L"Not found";;\r
154                 }\r
155         }\r
156                                                         \r
157         spl::shared_ptr<texture> create_texture(int width, int height, int stride)\r
158         {\r
159                 CASPAR_VERIFY(stride > 0 && stride < 5);\r
160                 CASPAR_VERIFY(width > 0 && height > 0);\r
161                 \r
162                 auto pool = &device_pools_[stride-1][((width << 16) & 0xFFFF0000) | (height & 0x0000FFFF)];\r
163                 \r
164                 std::shared_ptr<texture> buffer;\r
165                 if(!pool->try_pop(buffer))              \r
166                         buffer = spl::make_shared<texture>(width, height, stride);\r
167         \r
168                 return spl::shared_ptr<texture>(buffer.get(), [buffer, pool](texture*) mutable\r
169                 {               \r
170                         pool->push(buffer);     \r
171                 });\r
172         }\r
173                 \r
174         spl::shared_ptr<buffer> create_buffer(std::size_t size, buffer::usage usage)\r
175         {\r
176                 CASPAR_VERIFY(size > 0);\r
177                 \r
178                 auto pool = &host_pools_[usage.value()][size];\r
179                 \r
180                 std::shared_ptr<buffer> buf;\r
181                 if(!pool->try_pop(buf)) \r
182                 {\r
183                         buf = alloc_executor_.invoke([&]\r
184                         {\r
185                                 return spl::make_shared<buffer>(size, usage);\r
186                         });\r
187                 }\r
188                                 \r
189                 auto ptr = buf->data();\r
190                 auto self = shared_from_this(); // buffers can leave the device context, take a hold on life-time.\r
191 \r
192                 auto on_release = [self, buf, ptr, usage, pool]() mutable\r
193                 {               \r
194                         if(usage == buffer::usage::write_only)                                  \r
195                                 buf->map();                                     \r
196                         else\r
197                                 buf->unmap();\r
198 \r
199                         self->texture_cache_.erase(buf.get());\r
200 \r
201                         pool->push(buf);\r
202                 };\r
203                 \r
204                 return spl::shared_ptr<buffer>(buf.get(), [=](buffer*) mutable\r
205                 {\r
206                         self->alloc_executor_.begin_invoke(on_release); \r
207                 });\r
208         }\r
209 \r
210         array<std::uint8_t> create_array(std::size_t size)\r
211         {               \r
212                 auto buf = create_buffer(size, buffer::usage::write_only);\r
213                 return array<std::uint8_t>(buf->data(), buf->size(), false, buf);\r
214         }\r
215 \r
216         boost::unique_future<spl::shared_ptr<texture>> copy_async(const array<const std::uint8_t>& source, int width, int height, int stride)\r
217         {\r
218                 auto buf = source.storage<spl::shared_ptr<buffer>>();\r
219                                 \r
220                 return render_executor_.begin_invoke([=]() -> spl::shared_ptr<texture>\r
221                 {\r
222                         tbb::concurrent_hash_map<buffer*, std::shared_ptr<texture>>::const_accessor a;\r
223                         if(texture_cache_.find(a, buf.get()))\r
224                                 return spl::make_shared_ptr(a->second);\r
225 \r
226                         auto texture = create_texture(width, height, stride);\r
227                         texture->copy_from(*buf);       \r
228 \r
229                         texture_cache_.insert(std::make_pair(buf.get(), texture));\r
230 \r
231                         return texture;\r
232 \r
233                 }, task_priority::high_priority);\r
234         }\r
235         \r
236         boost::unique_future<spl::shared_ptr<texture>> copy_async(const array<std::uint8_t>& source, int width, int height, int stride)\r
237         {\r
238                 auto buf = source.storage<spl::shared_ptr<buffer>>();\r
239                                 \r
240                 return render_executor_.begin_invoke([=]() -> spl::shared_ptr<texture>\r
241                 {\r
242                         auto texture = create_texture(width, height, stride);\r
243                         texture->copy_from(*buf);                               \r
244                         return texture;\r
245                 }, task_priority::high_priority);\r
246         }\r
247 \r
248         boost::unique_future<array<const std::uint8_t>> copy_async(const spl::shared_ptr<texture>& source)\r
249         {\r
250                 return flatten(render_executor_.begin_invoke([=]() -> boost::shared_future<array<const std::uint8_t>>\r
251                 {\r
252                         auto buffer = create_buffer(source->size(), buffer::usage::read_only); \r
253                         source->copy_to(*buffer);       \r
254 \r
255                         auto self = shared_from_this();\r
256                         return make_shared(async(launch::deferred, [self, buffer]() mutable -> array<const std::uint8_t>\r
257                         {\r
258                                 const auto& buf = buffer.get();\r
259                                 if(!buf->data())\r
260                                         self->alloc_executor_.invoke(std::bind(&buffer::map, std::ref(buf))); // Defer blocking "map" call until data is needed.\r
261 \r
262                                 return array<const std::uint8_t>(buf->data(), buf->size(), true, buffer);\r
263                         }));\r
264                 }, task_priority::high_priority));\r
265         }\r
266 };\r
267 \r
268 device::device() \r
269         : executor_(L"OpenGL Rendering Context.")\r
270         , impl_(new impl(executor_)){}\r
271 device::~device(){}\r
272 spl::shared_ptr<texture>                                                        device::create_texture(int width, int height, int stride){return impl_->create_texture(width, height, stride);}\r
273 array<std::uint8_t>                                                                     device::create_array(int size){return impl_->create_array(size);}\r
274 boost::unique_future<spl::shared_ptr<texture>>          device::copy_async(const array<const std::uint8_t>& source, int width, int height, int stride){return impl_->copy_async(source, width, height, stride);}\r
275 boost::unique_future<spl::shared_ptr<texture>>          device::copy_async(const array<std::uint8_t>& source, int width, int height, int stride){return impl_->copy_async(source, width, height, stride);}\r
276 boost::unique_future<array<const std::uint8_t>>         device::copy_async(const spl::shared_ptr<texture>& source){return impl_->copy_async(source);}\r
277 std::wstring                                                                            device::version() const{return impl_->version();}\r
278 \r
279 \r
280 }}}\r
281 \r
282 \r