2 * Copyright 2013 Sveriges Television AB http://casparcg.com/
\r
4 * This file is part of CasparCG (www.casparcg.com).
\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
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
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
19 * Author: Robert Nagy, ronag89@gmail.com
\r
22 #include "ogl_consumer.h"
\r
24 #include <GL/glew.h>
\r
25 #include <SFML/Window.hpp>
\r
27 #include <common/diagnostics/graph.h>
\r
28 #include <common/gl/gl_check.h>
\r
29 #include <common/log/log.h>
\r
30 #include <common/memory/safe_ptr.h>
\r
31 #include <common/memory/memcpy.h>
\r
32 #include <common/memory/memshfl.h>
\r
33 #include <common/utility/timer.h>
\r
34 #include <common/utility/string.h>
\r
35 #include <common/concurrency/future_util.h>
\r
37 #include <ffmpeg/producer/filter/filter.h>
\r
39 #include <core/parameters/parameters.h>
\r
40 #include <core/video_format.h>
\r
41 #include <core/mixer/read_frame.h>
\r
42 #include <core/consumer/frame_consumer.h>
\r
44 #include <boost/timer.hpp>
\r
45 #include <boost/circular_buffer.hpp>
\r
46 #include <boost/foreach.hpp>
\r
47 #include <boost/thread.hpp>
\r
48 #include <boost/property_tree/ptree.hpp>
\r
50 #include <tbb/atomic.h>
\r
51 #include <tbb/concurrent_queue.h>
\r
53 #include <boost/assign.hpp>
\r
55 #include <algorithm>
\r
58 #if defined(_MSC_VER)
\r
59 #pragma warning (push)
\r
60 #pragma warning (disable : 4244)
\r
64 #define __STDC_CONSTANT_MACROS
\r
65 #define __STDC_LIMIT_MACROS
\r
66 #include <libavcodec/avcodec.h>
\r
67 #include <libavutil/imgutils.h>
\r
69 #if defined(_MSC_VER)
\r
70 #pragma warning (pop)
\r
73 typedef int (*PFNWGLEXTGETSWAPINTERVALPROC) (void);
\r
75 namespace caspar { namespace ogl {
\r
85 struct configuration
\r
95 size_t screen_index;
\r
98 bool auto_deinterlace;
\r
100 aspect_ratio aspect;
\r
108 , auto_deinterlace(true)
\r
110 , aspect(aspect_invalid)
\r
116 struct ogl_consumer : boost::noncopyable
\r
118 const configuration config_;
\r
119 core::video_format_desc format_desc_;
\r
120 int channel_index_;
\r
123 std::vector<GLuint> pbos_;
\r
127 unsigned int screen_x_;
\r
128 unsigned int screen_y_;
\r
129 unsigned int screen_width_;
\r
130 unsigned int screen_height_;
\r
131 size_t square_width_;
\r
132 size_t square_height_;
\r
134 sf::Window window_;
\r
136 safe_ptr<diagnostics::graph> graph_;
\r
137 boost::timer perf_timer_;
\r
138 boost::timer tick_timer_;
\r
140 caspar::high_prec_timer wait_timer_;
\r
142 tbb::concurrent_bounded_queue<safe_ptr<core::read_frame>> frame_buffer_;
\r
144 boost::thread thread_;
\r
145 tbb::atomic<bool> is_running_;
\r
147 ffmpeg::filter filter_;
\r
149 ogl_consumer(const configuration& config, const core::video_format_desc& format_desc, int channel_index)
\r
151 , format_desc_(format_desc)
\r
152 , channel_index_(channel_index)
\r
155 , screen_width_(format_desc.width)
\r
156 , screen_height_(format_desc.height)
\r
157 , square_width_(format_desc.square_width)
\r
158 , square_height_(format_desc.square_height)
\r
159 , filter_(format_desc.field_mode == core::field_mode::progressive || !config.auto_deinterlace ? L"" : L"YADIF=1:-1", boost::assign::list_of(PIX_FMT_BGRA))
\r
161 if(format_desc_.format == core::video_format::ntsc && config_.aspect == configuration::aspect_4_3)
\r
163 // Use default values which are 4:3.
\r
167 if(config_.aspect == configuration::aspect_16_9)
\r
168 square_width_ = (format_desc.height*16)/9;
\r
169 else if(config_.aspect == configuration::aspect_4_3)
\r
170 square_width_ = (format_desc.height*4)/3;
\r
173 frame_buffer_.set_capacity(2);
\r
175 graph_->set_color("tick-time", diagnostics::color(0.0f, 0.6f, 0.9f));
\r
176 graph_->set_color("frame-time", diagnostics::color(0.1f, 1.0f, 0.1f));
\r
177 graph_->set_color("dropped-frame", diagnostics::color(0.3f, 0.6f, 0.3f));
\r
179 graph_->set_text(print());
\r
180 diagnostics::register_graph(graph_);
\r
182 DISPLAY_DEVICE d_device = {sizeof(d_device), 0};
\r
183 std::vector<DISPLAY_DEVICE> displayDevices;
\r
184 for(int n = 0; EnumDisplayDevices(NULL, n, &d_device, NULL); ++n)
\r
185 displayDevices.push_back(d_device);
\r
187 if(config_.screen_index >= displayDevices.size())
\r
188 CASPAR_LOG(warning) << print() << L" Invalid screen-index: " << config_.screen_index;
\r
190 DEVMODE devmode = {};
\r
191 if(!EnumDisplaySettings(displayDevices[config_.screen_index].DeviceName, ENUM_CURRENT_SETTINGS, &devmode))
\r
192 CASPAR_LOG(warning) << print() << L" Could not find display settings for screen-index: " << config_.screen_index;
\r
194 screen_x_ = devmode.dmPosition.x;
\r
195 screen_y_ = devmode.dmPosition.y;
\r
196 screen_width_ = config_.windowed ? square_width_ : devmode.dmPelsWidth;
\r
197 screen_height_ = config_.windowed ? square_height_ : devmode.dmPelsHeight;
\r
199 is_running_ = true;
\r
200 thread_ = boost::thread([this]{run();});
\r
205 is_running_ = false;
\r
206 frame_buffer_.try_push(make_safe<core::read_frame>());
\r
212 if(!GLEW_VERSION_2_1)
\r
213 BOOST_THROW_EXCEPTION(not_supported() << msg_info("Missing OpenGL 2.1 support."));
\r
215 window_.Create(sf::VideoMode(screen_width_, screen_height_, 32), narrow(L"Screen consumer " + channel_and_format()), config_.windowed ? sf::Style::Resize | sf::Style::Close : sf::Style::Fullscreen);
\r
216 window_.ShowMouseCursor(false);
\r
217 window_.SetPosition(screen_x_, screen_y_);
\r
218 window_.SetSize(screen_width_, screen_height_);
\r
219 window_.SetActive();
\r
220 GL(glEnable(GL_TEXTURE_2D));
\r
221 GL(glDisable(GL_DEPTH_TEST));
\r
222 GL(glClearColor(0.0, 0.0, 0.0, 0.0));
\r
223 GL(glViewport(0, 0, format_desc_.width, format_desc_.height));
\r
224 GL(glLoadIdentity());
\r
226 calculate_aspect();
\r
228 GL(glGenTextures(1, &texture_));
\r
229 GL(glBindTexture(GL_TEXTURE_2D, texture_));
\r
230 GL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
\r
231 GL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
\r
232 GL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP));
\r
233 GL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP));
\r
234 GL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, format_desc_.width, format_desc_.height, 0, GL_BGRA, GL_UNSIGNED_BYTE, 0));
\r
235 GL(glBindTexture(GL_TEXTURE_2D, 0));
\r
237 GL(glGenBuffers(2, pbos_.data()));
\r
239 glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, pbos_[0]);
\r
240 glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, format_desc_.size, 0, GL_STREAM_DRAW_ARB);
\r
241 glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, pbos_[1]);
\r
242 glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, format_desc_.size, 0, GL_STREAM_DRAW_ARB);
\r
243 glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
\r
247 auto wglSwapIntervalEXT = reinterpret_cast<void(APIENTRY*)(int)>(wglGetProcAddress("wglSwapIntervalEXT"));
\r
248 if(wglSwapIntervalEXT)
\r
250 wglSwapIntervalEXT(1);
\r
251 CASPAR_LOG(info) << print() << " Successfully enabled vsync.";
\r
254 CASPAR_LOG(info) << print() << " Failed to enable vsync.";
\r
257 CASPAR_LOG(info) << print() << " Successfully Initialized.";
\r
263 glDeleteTextures(1, &texture_);
\r
265 BOOST_FOREACH(auto& pbo, pbos_)
\r
268 glDeleteBuffers(1, &pbo);
\r
284 while(window_.GetEvent(e))
\r
286 if(e.Type == sf::Event::Resized)
\r
287 calculate_aspect();
\r
288 else if(e.Type == sf::Event::Closed)
\r
289 is_running_ = false;
\r
292 safe_ptr<core::read_frame> frame;
\r
294 frame_buffer_.pop(frame);
\r
296 render_and_draw_frame(frame);
\r
298 graph_->set_value("tick-time", tick_timer_.elapsed()*format_desc_.fps*0.5);
\r
299 tick_timer_.restart();
\r
303 CASPAR_LOG_CURRENT_EXCEPTION();
\r
304 is_running_ = false;
\r
312 CASPAR_LOG_CURRENT_EXCEPTION();
\r
316 void try_sleep_almost_until_vblank()
\r
318 static const double THRESHOLD = 0.003;
\r
319 double threshold = config_.vsync ? THRESHOLD : 0.0;
\r
321 auto frame_time = 1.0 / (format_desc_.fps * format_desc_.field_count);
\r
323 wait_timer_.tick(frame_time - threshold);
\r
326 void wait_for_vblank_and_display()
\r
328 try_sleep_almost_until_vblank();
\r
330 // Make sure that the next tick measures the duration from this point in time.
\r
331 wait_timer_.tick(0.0);
\r
334 safe_ptr<AVFrame> get_av_frame()
\r
336 safe_ptr<AVFrame> av_frame(avcodec_alloc_frame(), av_free);
\r
337 avcodec_get_frame_defaults(av_frame.get());
\r
339 av_frame->linesize[0] = format_desc_.width*4;
\r
340 av_frame->format = PIX_FMT_BGRA;
\r
341 av_frame->width = format_desc_.width;
\r
342 av_frame->height = format_desc_.height;
\r
343 av_frame->interlaced_frame = format_desc_.field_mode != core::field_mode::progressive;
\r
344 av_frame->top_field_first = format_desc_.field_mode == core::field_mode::upper ? 1 : 0;
\r
349 void render_and_draw_frame(const safe_ptr<core::read_frame>& frame)
\r
351 if(static_cast<size_t>(frame->image_data().size()) != format_desc_.size)
\r
354 perf_timer_.restart();
\r
355 auto av_frame = get_av_frame();
\r
356 av_frame->data[0] = const_cast<uint8_t*>(frame->image_data().begin());
\r
358 filter_.push(av_frame);
\r
359 auto frames = filter_.poll_all();
\r
361 if (frames.empty())
\r
364 if (frames.size() == 1)
\r
366 render(frames[0], frame->image_data().size());
\r
367 graph_->set_value("frame-time", perf_timer_.elapsed() * format_desc_.fps * 0.5);
\r
369 wait_for_vblank_and_display(); // progressive frame
\r
371 else if (frames.size() == 2)
\r
373 render(frames[0], frame->image_data().size());
\r
374 double perf_elapsed = perf_timer_.elapsed();
\r
376 wait_for_vblank_and_display(); // field1
\r
378 perf_timer_.restart();
\r
379 render(frames[1], frame->image_data().size());
\r
380 perf_elapsed += perf_timer_.elapsed();
\r
381 graph_->set_value("frame-time", perf_elapsed * format_desc_.fps * 0.5);
\r
383 wait_for_vblank_and_display(); // field2
\r
387 void render(safe_ptr<AVFrame> av_frame, int image_data_size)
\r
389 if(av_frame->linesize[0] != static_cast<int>(format_desc_.width*4))
\r
391 const uint8_t *src_data[4] = {0};
\r
392 memcpy(const_cast<uint8_t**>(&src_data[0]), av_frame->data, 4);
\r
393 const int src_linesizes[4] = {0};
\r
394 memcpy(const_cast<int*>(&src_linesizes[0]), av_frame->linesize, 4);
\r
396 auto av_frame2 = get_av_frame();
\r
397 av_image_alloc(av_frame2->data, av_frame2->linesize, av_frame2->width, av_frame2->height, PIX_FMT_BGRA, 16);
\r
398 av_frame = safe_ptr<AVFrame>(av_frame2.get(), [=](AVFrame*)
\r
400 av_freep(&av_frame2->data[0]);
\r
403 av_image_copy(av_frame2->data, av_frame2->linesize, src_data, src_linesizes, PIX_FMT_BGRA, av_frame2->width, av_frame2->height);
\r
406 glBindTexture(GL_TEXTURE_2D, texture_);
\r
408 glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbos_[0]);
\r
409 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, format_desc_.width, format_desc_.height, GL_BGRA, GL_UNSIGNED_BYTE, 0);
\r
411 glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbos_[1]);
\r
412 glBufferData(GL_PIXEL_UNPACK_BUFFER, format_desc_.size, 0, GL_STREAM_DRAW);
\r
414 auto ptr = glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_WRITE_ONLY);
\r
417 if(config_.key_only)
\r
418 fast_memshfl(reinterpret_cast<char*>(ptr), av_frame->data[0], image_data_size, 0x0F0F0F0F, 0x0B0B0B0B, 0x07070707, 0x03030303);
\r
420 fast_memcpy(reinterpret_cast<char*>(ptr), av_frame->data[0], image_data_size);
\r
422 glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER); // release the mapped buffer
\r
425 glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
\r
427 GL(glClear(GL_COLOR_BUFFER_BIT));
\r
429 glTexCoord2f(0.0f, 1.0f); glVertex2f(-width_, -height_);
\r
430 glTexCoord2f(1.0f, 1.0f); glVertex2f( width_, -height_);
\r
431 glTexCoord2f(1.0f, 0.0f); glVertex2f( width_, height_);
\r
432 glTexCoord2f(0.0f, 0.0f); glVertex2f(-width_, height_);
\r
435 glBindTexture(GL_TEXTURE_2D, 0);
\r
437 std::rotate(pbos_.begin(), pbos_.begin() + 1, pbos_.end());
\r
440 boost::unique_future<bool> send(const safe_ptr<core::read_frame>& frame)
\r
442 if (!frame_buffer_.try_push(frame))
\r
443 graph_->set_tag("dropped-frame");
\r
445 return wrap_as_future(is_running_.load());
\r
448 std::wstring channel_and_format() const
\r
450 return L"[" + boost::lexical_cast<std::wstring>(channel_index_) + L"|" + format_desc_.name + L"]";
\r
453 std::wstring print() const
\r
455 return config_.name + channel_and_format();
\r
458 void calculate_aspect()
\r
460 if(config_.windowed)
\r
462 screen_height_ = window_.GetHeight();
\r
463 screen_width_ = window_.GetWidth();
\r
466 GL(glViewport(0, 0, screen_width_, screen_height_));
\r
468 std::pair<float, float> target_ratio = None();
\r
469 if(config_.stretch == fill)
\r
470 target_ratio = Fill();
\r
471 else if(config_.stretch == uniform)
\r
472 target_ratio = Uniform();
\r
473 else if(config_.stretch == uniform_to_fill)
\r
474 target_ratio = UniformToFill();
\r
476 width_ = target_ratio.first;
\r
477 height_ = target_ratio.second;
\r
480 std::pair<float, float> None()
\r
482 float width = static_cast<float>(square_width_)/static_cast<float>(screen_width_);
\r
483 float height = static_cast<float>(square_height_)/static_cast<float>(screen_height_);
\r
485 return std::make_pair(width, height);
\r
488 std::pair<float, float> Uniform()
\r
490 float aspect = static_cast<float>(square_width_)/static_cast<float>(square_height_);
\r
491 float width = std::min(1.0f, static_cast<float>(screen_height_)*aspect/static_cast<float>(screen_width_));
\r
492 float height = static_cast<float>(screen_width_*width)/static_cast<float>(screen_height_*aspect);
\r
494 return std::make_pair(width, height);
\r
497 std::pair<float, float> Fill()
\r
499 return std::make_pair(1.0f, 1.0f);
\r
502 std::pair<float, float> UniformToFill()
\r
504 float wr = static_cast<float>(square_width_)/static_cast<float>(screen_width_);
\r
505 float hr = static_cast<float>(square_height_)/static_cast<float>(screen_height_);
\r
506 float r_inv = 1.0f/std::min(wr, hr);
\r
508 float width = wr*r_inv;
\r
509 float height = hr*r_inv;
\r
511 return std::make_pair(width, height);
\r
516 struct ogl_consumer_proxy : public core::frame_consumer
\r
518 const configuration config_;
\r
519 std::unique_ptr<ogl_consumer> consumer_;
\r
523 ogl_consumer_proxy(const configuration& config)
\r
524 : config_(config){}
\r
526 ~ogl_consumer_proxy()
\r
530 auto str = print();
\r
532 CASPAR_LOG(info) << str << L" Successfully Uninitialized.";
\r
538 virtual void initialize(const core::video_format_desc& format_desc, int channel_index) override
\r
541 consumer_.reset(new ogl_consumer(config_, format_desc, channel_index));
\r
542 CASPAR_LOG(info) << print() << L" Successfully Initialized.";
\r
545 virtual boost::unique_future<bool> send(const safe_ptr<core::read_frame>& frame) override
\r
547 return consumer_->send(frame);
\r
550 virtual std::wstring print() const override
\r
552 return consumer_ ? consumer_->print() : L"[ogl_consumer]";
\r
555 virtual boost::property_tree::wptree info() const override
\r
557 boost::property_tree::wptree info;
\r
558 info.add(L"type", L"ogl-consumer");
\r
559 info.add(L"key-only", config_.key_only);
\r
560 info.add(L"windowed", config_.windowed);
\r
561 info.add(L"auto-deinterlace", config_.auto_deinterlace);
\r
565 virtual bool has_synchronization_clock() const override
\r
570 virtual size_t buffer_depth() const override
\r
575 virtual int index() const override
\r
577 return 600 + config_.screen_index;
\r
581 safe_ptr<core::frame_consumer> create_consumer(const core::parameters& params)
\r
583 if(params.size() < 1 || params[0] != L"SCREEN")
\r
584 return core::frame_consumer::empty();
\r
586 configuration config;
\r
588 if(params.size() > 1)
\r
589 config.screen_index = lexical_cast_or_default<int>(params[1], config.screen_index);
\r
591 auto device_it = std::find(params.begin(), params.end(), L"DEVICE");
\r
592 if(device_it != params.end() && ++device_it != params.end())
\r
593 config.screen_index = boost::lexical_cast<int>(*device_it);
\r
595 config.windowed = std::find(params.begin(), params.end(), L"FULLSCREEN") == params.end();
\r
596 config.key_only = std::find(params.begin(), params.end(), L"KEY_ONLY") != params.end();
\r
598 auto name_it = std::find(params.begin(), params.end(), L"NAME");
\r
599 if(name_it != params.end() && ++name_it != params.end())
\r
600 config.name = *name_it;
\r
602 return make_safe<ogl_consumer_proxy>(config);
\r
605 safe_ptr<core::frame_consumer> create_consumer(const boost::property_tree::wptree& ptree)
\r
607 configuration config;
\r
608 config.name = ptree.get(L"name", config.name);
\r
609 config.screen_index = ptree.get(L"device", config.screen_index+1)-1;
\r
610 config.windowed = ptree.get(L"windowed", config.windowed);
\r
611 config.key_only = ptree.get(L"key-only", config.key_only);
\r
612 config.auto_deinterlace = ptree.get(L"auto-deinterlace", config.auto_deinterlace);
\r
613 config.vsync = ptree.get(L"vsync", config.vsync);
\r
615 auto stretch_str = ptree.get(L"stretch", L"default");
\r
616 if(stretch_str == L"uniform")
\r
617 config.stretch = stretch::uniform;
\r
618 else if(stretch_str == L"uniform_to_fill")
\r
619 config.stretch = stretch::uniform_to_fill;
\r
621 auto aspect_str = ptree.get(L"aspect-ratio", L"default");
\r
622 if(aspect_str == L"16:9")
\r
623 config.aspect = configuration::aspect_16_9;
\r
624 else if(aspect_str == L"4:3")
\r
625 config.aspect = configuration::aspect_4_3;
\r
627 return make_safe<ogl_consumer_proxy>(config);
\r