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