]> git.sesse.net Git - casparcg/blob - modules/ogl/consumer/ogl_consumer.cpp
2.0.2: ogl_consumer: Window is closable.
[casparcg] / modules / ogl / consumer / ogl_consumer.cpp
1 /*\r
2 * copyright (c) 2010 Sveriges Television AB <info@casparcg.com>\r
3 *\r
4 *  This file is part of CasparCG.\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 */\r
20 \r
21 #include "ogl_consumer.h"\r
22 \r
23 #include <GL/glew.h>\r
24 #include <SFML/Window.hpp>\r
25 \r
26 #include <common/diagnostics/graph.h>\r
27 #include <common/gl/gl_check.h>\r
28 #include <common/log/log.h>\r
29 #include <common/memory/safe_ptr.h>\r
30 #include <common/memory/memcpy.h>\r
31 #include <common/memory/memshfl.h>\r
32 #include <common/utility/timer.h>\r
33 #include <common/utility/string.h>\r
34 \r
35 #include <ffmpeg/producer/filter/filter.h>\r
36 \r
37 #include <core/video_format.h>\r
38 #include <core/mixer/read_frame.h>\r
39 #include <core/consumer/frame_consumer.h>\r
40 \r
41 #include <boost/timer.hpp>\r
42 #include <boost/circular_buffer.hpp>\r
43 #include <boost/foreach.hpp>\r
44 #include <boost/thread.hpp>\r
45 \r
46 #include <tbb/atomic.h>\r
47 #include <tbb/concurrent_queue.h>\r
48 \r
49 #include <boost/assign.hpp>\r
50 \r
51 #include <algorithm>\r
52 #include <vector>\r
53 \r
54 #if defined(_MSC_VER)\r
55 #pragma warning (push)\r
56 #pragma warning (disable : 4244)\r
57 #endif\r
58 extern "C" \r
59 {\r
60         #define __STDC_CONSTANT_MACROS\r
61         #define __STDC_LIMIT_MACROS\r
62         #include <libavcodec/avcodec.h>\r
63         #include <libavutil/imgutils.h>\r
64 }\r
65 #if defined(_MSC_VER)\r
66 #pragma warning (pop)\r
67 #endif\r
68 \r
69 namespace caspar { namespace ogl {\r
70                 \r
71 enum stretch\r
72 {\r
73         none,\r
74         uniform,\r
75         fill,\r
76         uniform_to_fill\r
77 };\r
78 \r
79 struct configuration\r
80 {\r
81         std::wstring    name;\r
82         size_t                  screen_index;\r
83         stretch                 stretch;\r
84         bool                    windowed;\r
85         bool                    auto_deinterlace;\r
86         bool                    key_only;\r
87 \r
88         configuration()\r
89                 : name(L"ogl")\r
90                 , screen_index(0)\r
91                 , stretch(fill)\r
92                 , windowed(true)\r
93                 , auto_deinterlace(true)\r
94                 , key_only(false)\r
95         {\r
96         }\r
97 };\r
98 \r
99 struct ogl_consumer : boost::noncopyable\r
100 {               \r
101         const configuration             config_;\r
102         core::video_format_desc format_desc_;\r
103         int                                             channel_index_;\r
104         int                                             sub_index_;\r
105 \r
106         GLuint                                  texture_;\r
107         std::vector<GLuint>             pbos_;\r
108         \r
109         float                                   width_;\r
110         float                                   height_;        \r
111         unsigned int                    screen_x_;\r
112         unsigned int                    screen_y_;\r
113         unsigned int                    screen_width_;\r
114         unsigned int                    screen_height_;\r
115         size_t                                  square_width_;\r
116         size_t                                  square_height_;                         \r
117         \r
118         sf::Window                              window_;\r
119         \r
120         safe_ptr<diagnostics::graph>    graph_;\r
121         boost::timer                                    perf_timer_;\r
122         boost::timer                                    tick_timer_;\r
123 \r
124         tbb::concurrent_bounded_queue<safe_ptr<core::read_frame>>       frame_buffer_;\r
125 \r
126         boost::thread                   thread_;\r
127         tbb::atomic<bool>               is_running_;\r
128 \r
129         \r
130         ffmpeg::filter                  filter_;\r
131 public:\r
132         ogl_consumer(const configuration& config, const core::video_format_desc& format_desc, int channel_index, int sub_index) \r
133                 : config_(config)\r
134                 , format_desc_(format_desc)\r
135                 , channel_index_(channel_index)\r
136                 , sub_index_(sub_index)\r
137                 , texture_(0)\r
138                 , pbos_(2, 0)   \r
139                 , screen_width_(format_desc.width)\r
140                 , screen_height_(format_desc.height)\r
141                 , square_width_(format_desc.square_width)\r
142                 , square_height_(format_desc.square_height)\r
143                 , filter_(format_desc.field_mode == core::field_mode::progressive || !config.auto_deinterlace ? L"" : L"YADIF=0:-1", boost::assign::list_of(PIX_FMT_BGRA))\r
144         {               \r
145                 frame_buffer_.set_capacity(2);\r
146                 \r
147                 graph_->add_guide("tick-time", 0.5);\r
148                 graph_->set_color("tick-time", diagnostics::color(0.0f, 0.6f, 0.9f));   \r
149                 graph_->set_color("frame-time", diagnostics::color(0.1f, 1.0f, 0.1f));\r
150                 graph_->set_color("dropped-frame", diagnostics::color(0.3f, 0.6f, 0.3f));\r
151                 graph_->set_text(print());\r
152                 diagnostics::register_graph(graph_);\r
153                                                                         \r
154                 DISPLAY_DEVICE d_device = {sizeof(d_device), 0};                        \r
155                 std::vector<DISPLAY_DEVICE> displayDevices;\r
156                 for(int n = 0; EnumDisplayDevices(NULL, n, &d_device, NULL); ++n)\r
157                         displayDevices.push_back(d_device);\r
158 \r
159                 if(config_.screen_index >= displayDevices.size())\r
160                         BOOST_THROW_EXCEPTION(out_of_range() << arg_name_info("screen_index_") << msg_info(narrow(print())));\r
161                 \r
162                 DEVMODE devmode = {};\r
163                 if(!EnumDisplaySettings(displayDevices[config_.screen_index].DeviceName, ENUM_CURRENT_SETTINGS, &devmode))\r
164                         BOOST_THROW_EXCEPTION(invalid_operation() << arg_name_info("screen_index") << msg_info(narrow(print()) + " EnumDisplaySettings"));\r
165                 \r
166                 screen_x_               = devmode.dmPosition.x;\r
167                 screen_y_               = devmode.dmPosition.y;\r
168                 screen_width_   = config_.windowed ? square_width_ : devmode.dmPelsWidth;\r
169                 screen_height_  = config_.windowed ? square_height_ : devmode.dmPelsHeight;\r
170                 \r
171                 is_running_ = true;\r
172                 thread_ = boost::thread([this]{run();});\r
173         }\r
174         \r
175         ~ogl_consumer()\r
176         {\r
177                 is_running_ = false;\r
178                 frame_buffer_.try_push(make_safe<core::read_frame>());\r
179                 thread_.join();\r
180         }\r
181 \r
182         void init()\r
183         {\r
184                 if(!GLEW_VERSION_2_1)\r
185                         BOOST_THROW_EXCEPTION(not_supported() << msg_info("Missing OpenGL 2.1 support."));\r
186 \r
187                 window_.Create(sf::VideoMode(screen_width_, screen_height_, 32), narrow(print()), config_.windowed ? sf::Style::Resize | sf::Style::Close : sf::Style::Fullscreen);\r
188                 window_.ShowMouseCursor(false);\r
189                 window_.SetPosition(screen_x_, screen_y_);\r
190                 window_.SetSize(screen_width_, screen_height_);\r
191                 window_.SetActive();\r
192                 GL(glEnable(GL_TEXTURE_2D));\r
193                 GL(glDisable(GL_DEPTH_TEST));           \r
194                 GL(glClearColor(0.0, 0.0, 0.0, 0.0));\r
195                 GL(glViewport(0, 0, format_desc_.width, format_desc_.height));\r
196                 GL(glLoadIdentity());\r
197                                 \r
198                 calculate_aspect();\r
199                         \r
200                 GL(glGenTextures(1, &texture_));\r
201                 GL(glBindTexture(GL_TEXTURE_2D, texture_));\r
202                 GL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));\r
203                 GL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));\r
204                 GL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP));\r
205                 GL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP));\r
206                 GL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, format_desc_.width, format_desc_.height, 0, GL_BGRA, GL_UNSIGNED_BYTE, 0));\r
207                 GL(glBindTexture(GL_TEXTURE_2D, 0));\r
208                                         \r
209                 GL(glGenBuffers(2, pbos_.data()));\r
210                         \r
211                 glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, pbos_[0]);\r
212                 glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, format_desc_.size, 0, GL_STREAM_DRAW_ARB);\r
213                 glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, pbos_[1]);\r
214                 glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, format_desc_.size, 0, GL_STREAM_DRAW_ARB);\r
215                 glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0);\r
216 \r
217                 CASPAR_LOG(info) << print() << " Sucessfully Initialized.";\r
218         }\r
219 \r
220         void uninit()\r
221         {               \r
222                 if(texture_)\r
223                         glDeleteTextures(1, &texture_);\r
224 \r
225                 BOOST_FOREACH(auto& pbo, pbos_)\r
226                 {\r
227                         if(pbo)\r
228                                 glDeleteBuffers(1, &pbo);\r
229                 }\r
230 \r
231                 CASPAR_LOG(info) << print() << " Sucessfully Uninitialized.";\r
232         }\r
233 \r
234         void run()\r
235         {\r
236                 try\r
237                 {\r
238                         init();\r
239 \r
240                         while(is_running_)\r
241                         {                       \r
242                                 try\r
243                                 {\r
244 \r
245                                         sf::Event e;            \r
246                                         while(window_.GetEvent(e))\r
247                                         {\r
248                                                 if(e.Type == sf::Event::Resized)\r
249                                                         calculate_aspect();\r
250                                                 else if(e.Type == sf::Event::Closed)\r
251                                                         is_running_ = false;\r
252                                         }\r
253                         \r
254                                         safe_ptr<core::read_frame> frame;\r
255                                         frame_buffer_.pop(frame);\r
256                                         \r
257                                         perf_timer_.restart();\r
258                                         render(frame);\r
259                                         graph_->update_value("frame-time", perf_timer_.elapsed()*format_desc_.fps*0.5); \r
260 \r
261                                         window_.Display();\r
262                                         \r
263                                         graph_->update_value("tick-time", tick_timer_.elapsed()*format_desc_.fps*0.5);  \r
264                                         tick_timer_.restart();\r
265                                 }\r
266                                 catch(...)\r
267                                 {\r
268                                         CASPAR_LOG_CURRENT_EXCEPTION();\r
269                                         is_running_ = false;\r
270                                 }\r
271                         }\r
272 \r
273                         uninit();\r
274                 }\r
275                 catch(...)\r
276                 {\r
277                         CASPAR_LOG_CURRENT_EXCEPTION();\r
278                 }\r
279         }\r
280         \r
281         safe_ptr<AVFrame> get_av_frame()\r
282         {               \r
283                 safe_ptr<AVFrame> av_frame(avcodec_alloc_frame(), av_free);     \r
284                 avcodec_get_frame_defaults(av_frame.get());\r
285                                                 \r
286                 av_frame->linesize[0]           = format_desc_.width*4;                 \r
287                 av_frame->format                        = PIX_FMT_BGRA;\r
288                 av_frame->width                         = format_desc_.width;\r
289                 av_frame->height                        = format_desc_.height;\r
290                 av_frame->interlaced_frame      = format_desc_.field_mode != core::field_mode::progressive;\r
291                 av_frame->top_field_first       = format_desc_.field_mode == core::field_mode::upper ? 1 : 0;\r
292 \r
293                 return av_frame;\r
294         }\r
295 \r
296         void render(const safe_ptr<core::read_frame>& frame)\r
297         {                       \r
298                 if(static_cast<size_t>(frame->image_data().size()) != format_desc_.size)\r
299                         return;\r
300                                         \r
301                 auto av_frame = get_av_frame();\r
302                 av_frame->data[0] = const_cast<uint8_t*>(frame->image_data().begin());\r
303 \r
304                 filter_.push(av_frame);\r
305                 auto frames = filter_.poll_all();\r
306 \r
307                 if(frames.empty())\r
308                         return;\r
309 \r
310                 av_frame = frames[0];\r
311 \r
312                 if(av_frame->linesize[0] != static_cast<int>(format_desc_.width*4))\r
313                 {\r
314                         const uint8_t *src_data[4] = {0};\r
315                         memcpy(const_cast<uint8_t**>(&src_data[0]), av_frame->data, 4);\r
316                         const int src_linesizes[4] = {0};\r
317                         memcpy(const_cast<int*>(&src_linesizes[0]), av_frame->linesize, 4);\r
318 \r
319                         auto av_frame2 = get_av_frame();\r
320                         av_image_alloc(av_frame2->data, av_frame2->linesize, av_frame2->width, av_frame2->height, PIX_FMT_BGRA, 16);\r
321                         av_frame = safe_ptr<AVFrame>(av_frame2.get(), [=](AVFrame*)\r
322                         {\r
323                                 av_freep(&av_frame2->data[0]);\r
324                         });\r
325 \r
326                         av_image_copy(av_frame2->data, av_frame2->linesize, src_data, src_linesizes, PIX_FMT_BGRA, av_frame2->width, av_frame2->height);\r
327                 }\r
328 \r
329                 glBindTexture(GL_TEXTURE_2D, texture_);\r
330 \r
331                 glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbos_[0]);\r
332                 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, format_desc_.width, format_desc_.height, GL_BGRA, GL_UNSIGNED_BYTE, 0);\r
333 \r
334                 glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbos_[1]);\r
335                 glBufferData(GL_PIXEL_UNPACK_BUFFER, format_desc_.size, 0, GL_STREAM_DRAW);\r
336 \r
337                 auto ptr = glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_WRITE_ONLY);\r
338                 if(ptr)\r
339                 {\r
340                         if(config_.key_only)\r
341                                 fast_memshfl(reinterpret_cast<char*>(ptr), av_frame->data[0], frame->image_data().size(), 0x0F0F0F0F, 0x0B0B0B0B, 0x07070707, 0x03030303);\r
342                         else\r
343                                 fast_memcpy(reinterpret_cast<char*>(ptr), av_frame->data[0], frame->image_data().size());\r
344 \r
345                         glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER); // release the mapped buffer\r
346                 }\r
347 \r
348                 glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);\r
349                                 \r
350                 GL(glClear(GL_COLOR_BUFFER_BIT));                       \r
351                 glBegin(GL_QUADS);\r
352                                 glTexCoord2f(0.0f,        1.0f);        glVertex2f(-width_, -height_);\r
353                                 glTexCoord2f(1.0f,        1.0f);        glVertex2f( width_, -height_);\r
354                                 glTexCoord2f(1.0f,        0.0f);        glVertex2f( width_,  height_);\r
355                                 glTexCoord2f(0.0f,        0.0f);        glVertex2f(-width_,  height_);\r
356                 glEnd();\r
357                 \r
358                 glBindTexture(GL_TEXTURE_2D, 0);\r
359 \r
360                 std::rotate(pbos_.begin(), pbos_.begin() + 1, pbos_.end());\r
361         }\r
362 \r
363         bool send(const safe_ptr<core::read_frame>& frame)\r
364         {\r
365                 if(!frame_buffer_.try_push(frame))\r
366                         graph_->add_tag("dropped-frame");\r
367                 return is_running_;\r
368         }\r
369                 \r
370         std::wstring print() const\r
371         {       \r
372                 return config_.name + L"[" + boost::lexical_cast<std::wstring>(channel_index_) + L"-" + boost::lexical_cast<std::wstring>(sub_index_) + L"|" + format_desc_.name + L"]";\r
373         }\r
374         \r
375         void calculate_aspect()\r
376         {\r
377                 if(config_.windowed)\r
378                 {\r
379                         screen_height_ = window_.GetHeight();\r
380                         screen_width_ = window_.GetWidth();\r
381                 }\r
382                 \r
383                 GL(glViewport(0, 0, screen_width_, screen_height_));\r
384 \r
385                 std::pair<float, float> target_ratio = None();\r
386                 if(config_.stretch == fill)\r
387                         target_ratio = Fill();\r
388                 else if(config_.stretch == uniform)\r
389                         target_ratio = Uniform();\r
390                 else if(config_.stretch == uniform_to_fill)\r
391                         target_ratio = UniformToFill();\r
392 \r
393                 width_ = target_ratio.first;\r
394                 height_ = target_ratio.second;\r
395         }\r
396                 \r
397         std::pair<float, float> None()\r
398         {\r
399                 float width = static_cast<float>(square_width_)/static_cast<float>(screen_width_);\r
400                 float height = static_cast<float>(square_height_)/static_cast<float>(screen_height_);\r
401 \r
402                 return std::make_pair(width, height);\r
403         }\r
404 \r
405         std::pair<float, float> Uniform()\r
406         {\r
407                 float aspect = static_cast<float>(square_width_)/static_cast<float>(square_height_);\r
408                 float width = std::min(1.0f, static_cast<float>(screen_height_)*aspect/static_cast<float>(screen_width_));\r
409                 float height = static_cast<float>(screen_width_*width)/static_cast<float>(screen_height_*aspect);\r
410 \r
411                 return std::make_pair(width, height);\r
412         }\r
413 \r
414         std::pair<float, float> Fill()\r
415         {\r
416                 return std::make_pair(1.0f, 1.0f);\r
417         }\r
418 \r
419         std::pair<float, float> UniformToFill()\r
420         {\r
421                 float wr = static_cast<float>(square_width_)/static_cast<float>(screen_width_);\r
422                 float hr = static_cast<float>(square_height_)/static_cast<float>(screen_height_);\r
423                 float r_inv = 1.0f/std::min(wr, hr);\r
424 \r
425                 float width = wr*r_inv;\r
426                 float height = hr*r_inv;\r
427 \r
428                 return std::make_pair(width, height);\r
429         }\r
430 };\r
431 \r
432 \r
433 struct ogl_consumer_proxy : public core::frame_consumer\r
434 {\r
435         const configuration config_;\r
436         std::unique_ptr<ogl_consumer> consumer_;\r
437 \r
438 public:\r
439 \r
440         ogl_consumer_proxy(const configuration& config)\r
441                 : config_(config){}\r
442         \r
443         // frame_consumer\r
444 \r
445         virtual void initialize(const core::video_format_desc& format_desc, int channel_index, int sub_index) override\r
446         {\r
447                 consumer_.reset();\r
448                 consumer_.reset(new ogl_consumer(config_, format_desc, channel_index, sub_index));\r
449         }\r
450         \r
451         virtual bool send(const safe_ptr<core::read_frame>& frame) override\r
452         {\r
453                 return consumer_->send(frame);\r
454         }\r
455         \r
456         virtual std::wstring print() const override\r
457         {\r
458                 return consumer_->print();\r
459         }\r
460 \r
461         virtual bool has_synchronization_clock() const override\r
462         {\r
463                 return false;\r
464         }\r
465         \r
466         virtual size_t buffer_depth() const override\r
467         {\r
468                 return 1;\r
469         }\r
470 };      \r
471 \r
472 safe_ptr<core::frame_consumer> create_consumer(const std::vector<std::wstring>& params)\r
473 {\r
474         if(params.size() < 1 || params[0] != L"SCREEN")\r
475                 return core::frame_consumer::empty();\r
476         \r
477         configuration config;\r
478                 \r
479         if(params.size() > 1) \r
480                 config.screen_index = lexical_cast_or_default<int>(params[2], config.screen_index);\r
481 \r
482         if(params.size() > 2) \r
483                 config.windowed = lexical_cast_or_default<bool>(params[3], config.windowed);\r
484 \r
485         config.key_only = std::find(params.begin(), params.end(), L"KEY_ONLY") != params.end();\r
486 \r
487         return make_safe<ogl_consumer_proxy>(config);\r
488 }\r
489 \r
490 safe_ptr<core::frame_consumer> create_consumer(const boost::property_tree::ptree& ptree) \r
491 {\r
492         configuration config;\r
493         config.name                             = widen(ptree.get("name",               narrow(config.name)));\r
494         config.screen_index             = ptree.get("device",   config.screen_index+1)-1;\r
495         config.windowed                 = ptree.get("windowed", config.windowed);\r
496         config.key_only                 = ptree.get("key-only", config.key_only);\r
497         config.auto_deinterlace = ptree.get("auto-deinterlace", config.auto_deinterlace);\r
498         \r
499         auto stretch_str = ptree.get("stretch", "default");\r
500         if(stretch_str == "uniform")\r
501                 config.stretch = stretch::uniform;\r
502         else if(stretch_str == "uniform_to_fill")\r
503                 config.stretch = stretch::uniform_to_fill;\r
504         \r
505         return make_safe<ogl_consumer_proxy>(config);\r
506 }\r
507 \r
508 }}