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
22 #include "screen_consumer.h"
25 #include <SFML/Window.hpp>
27 #include <common/diagnostics/graph.h>
28 #include <common/gl/gl_check.h>
29 #include <common/log.h>
30 #include <common/memory.h>
31 #include <common/array.h>
32 #include <common/memshfl.h>
33 #include <common/utf.h>
34 #include <common/prec_timer.h>
35 #include <common/future.h>
39 #include <ffmpeg/producer/filter/filter.h>
41 #include <core/video_format.h>
42 #include <core/frame/frame.h>
43 #include <core/consumer/frame_consumer.h>
45 #include <boost/timer.hpp>
46 #include <boost/circular_buffer.hpp>
47 #include <boost/lexical_cast.hpp>
48 #include <boost/property_tree/ptree.hpp>
49 #include <boost/thread.hpp>
51 #include <tbb/atomic.h>
52 #include <tbb/concurrent_queue.h>
53 #include <tbb/parallel_for.h>
61 #pragma warning (push)
62 #pragma warning (disable : 4244)
66 #define __STDC_CONSTANT_MACROS
67 #define __STDC_LIMIT_MACROS
68 #include <libavcodec/avcodec.h>
69 #include <libavutil/imgutils.h>
75 namespace caspar { namespace screen {
87 enum class aspect_ratio
94 std::wstring name = L"ogl";
96 stretch stretch = stretch::fill;
98 bool auto_deinterlace = true;
99 bool key_only = false;
100 aspect_ratio aspect = aspect_ratio::aspect_invalid;
102 bool interactive = true;
105 struct screen_consumer : boost::noncopyable
107 const configuration config_;
108 core::video_format_desc format_desc_;
112 std::vector<GLuint> pbos_ = std::vector<GLuint> { 0, 0 };
118 int screen_width_ = format_desc_.width;
119 int screen_height_ = format_desc_.height;
120 int square_width_ = format_desc_.square_width;
121 int square_height_ = format_desc_.square_height;
125 spl::shared_ptr<diagnostics::graph> graph_;
126 boost::timer perf_timer_;
127 boost::timer tick_timer_;
129 caspar::prec_timer wait_timer_;
131 tbb::concurrent_bounded_queue<core::const_frame> frame_buffer_;
132 core::interaction_sink* sink_;
134 boost::thread thread_;
135 tbb::atomic<bool> is_running_;
137 ffmpeg::filter filter_;
140 const configuration& config,
141 const core::video_format_desc& format_desc,
143 core::interaction_sink* sink)
145 , format_desc_(format_desc)
146 , channel_index_(channel_index)
148 , filter_([&]() -> ffmpeg::filter
150 const auto sample_aspect_ratio =
151 boost::rational<int>(
152 format_desc.square_width,
153 format_desc.square_height) /
154 boost::rational<int>(
158 return ffmpeg::filter(
161 boost::rational<int>(format_desc.duration, format_desc.time_scale),
162 boost::rational<int>(format_desc.time_scale, format_desc.duration),
166 format_desc.field_mode == core::field_mode::progressive || !config.auto_deinterlace ? "" : "YADIF=1:-1");
169 if (format_desc_.format == core::video_format::ntsc && config_.aspect == configuration::aspect_ratio::aspect_4_3)
171 // Use default values which are 4:3.
175 if (config_.aspect == configuration::aspect_ratio::aspect_16_9)
176 square_width_ = (format_desc.height*16)/9;
177 else if (config_.aspect == configuration::aspect_ratio::aspect_4_3)
178 square_width_ = (format_desc.height*4)/3;
181 frame_buffer_.set_capacity(1);
183 graph_->set_color("tick-time", diagnostics::color(0.0f, 0.6f, 0.9f));
184 graph_->set_color("frame-time", diagnostics::color(0.1f, 1.0f, 0.1f));
185 graph_->set_color("dropped-frame", diagnostics::color(0.3f, 0.6f, 0.3f));
186 graph_->set_text(print());
187 diagnostics::register_graph(graph_);
189 DISPLAY_DEVICE d_device = {sizeof(d_device), 0};
190 std::vector<DISPLAY_DEVICE> displayDevices;
191 for(int n = 0; EnumDisplayDevices(NULL, n, &d_device, NULL); ++n)
192 displayDevices.push_back(d_device);
194 if(config_.screen_index >= displayDevices.size())
195 CASPAR_LOG(warning) << print() << L" Invalid screen-index: " << config_.screen_index;
197 DEVMODE devmode = {};
198 if(!EnumDisplaySettings(displayDevices[config_.screen_index].DeviceName, ENUM_CURRENT_SETTINGS, &devmode))
199 CASPAR_LOG(warning) << print() << L" Could not find display settings for screen-index: " << config_.screen_index;
201 screen_x_ = devmode.dmPosition.x;
202 screen_y_ = devmode.dmPosition.y;
203 screen_width_ = config_.windowed ? square_width_ : devmode.dmPelsWidth;
204 screen_height_ = config_.windowed ? square_height_ : devmode.dmPelsHeight;
207 thread_ = boost::thread([this]{run();});
213 frame_buffer_.try_push(core::const_frame::empty());
219 window_.create(sf::VideoMode(screen_width_, screen_height_, 32), u8(L"Screen consumer " + channel_and_format()), config_.windowed ? sf::Style::Resize | sf::Style::Close : sf::Style::Fullscreen);
220 window_.setMouseCursorVisible(config_.interactive);
221 window_.setPosition(sf::Vector2i(screen_x_, screen_y_));
222 window_.setSize(sf::Vector2u(screen_width_, screen_height_));
225 if(!GLEW_VERSION_2_1 && glewInit() != GLEW_OK)
226 CASPAR_THROW_EXCEPTION(gl::ogl_exception() << msg_info("Failed to initialize GLEW."));
228 if(!GLEW_VERSION_2_1)
229 CASPAR_THROW_EXCEPTION(not_supported() << msg_info("Missing OpenGL 2.1 support."));
231 GL(glEnable(GL_TEXTURE_2D));
232 GL(glDisable(GL_DEPTH_TEST));
233 GL(glClearColor(0.0, 0.0, 0.0, 0.0));
234 GL(glViewport(0, 0, format_desc_.width, format_desc_.height));
235 GL(glLoadIdentity());
239 GL(glGenTextures(1, &texture_));
240 GL(glBindTexture(GL_TEXTURE_2D, texture_));
241 GL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
242 GL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
243 GL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP));
244 GL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP));
245 GL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, format_desc_.width, format_desc_.height, 0, GL_BGRA, GL_UNSIGNED_BYTE, 0));
246 GL(glBindTexture(GL_TEXTURE_2D, 0));
248 GL(glGenBuffers(2, pbos_.data()));
250 glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, pbos_[0]);
251 glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, format_desc_.size, 0, GL_STREAM_DRAW_ARB);
252 glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, pbos_[1]);
253 glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, format_desc_.size, 0, GL_STREAM_DRAW_ARB);
254 glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
256 auto wglSwapIntervalEXT = reinterpret_cast<void(APIENTRY*)(int)>(wglGetProcAddress("wglSwapIntervalEXT"));
257 if(wglSwapIntervalEXT)
261 wglSwapIntervalEXT(1);
262 CASPAR_LOG(info) << print() << " Enabled vsync.";
265 wglSwapIntervalEXT(0);
268 CASPAR_LOG(info) << print() << " Successfully Initialized.";
274 glDeleteTextures(1, &texture_);
276 for (auto& pbo : pbos_)
279 glDeleteBuffers(1, &pbo);
294 while(window_.pollEvent(e))
296 if (e.type == sf::Event::Resized)
298 else if (e.type == sf::Event::Closed)
300 else if (config_.interactive && sink_)
304 case sf::Event::MouseMoved:
306 auto& mouse_move = e.mouseMove;
307 sink_->on_interaction(spl::make_shared<core::mouse_move_event>(
309 static_cast<double>(mouse_move.x) / screen_width_,
310 static_cast<double>(mouse_move.y) / screen_height_));
313 case sf::Event::MouseButtonPressed:
314 case sf::Event::MouseButtonReleased:
316 auto& mouse_button = e.mouseButton;
317 sink_->on_interaction(spl::make_shared<core::mouse_button_event>(
319 static_cast<double>(mouse_button.x) / screen_width_,
320 static_cast<double>(mouse_button.y) / screen_height_,
321 static_cast<int>(mouse_button.button),
322 e.type == sf::Event::MouseButtonPressed));
329 auto frame = core::const_frame::empty();
330 frame_buffer_.pop(frame);
332 render_and_draw_frame(frame);
334 /*perf_timer_.restart();
336 graph_->set_value("frame-time", perf_timer_.elapsed()*format_desc_.fps*0.5);
340 graph_->set_value("tick-time", tick_timer_.elapsed()*format_desc_.fps*0.5);
341 tick_timer_.restart();
345 CASPAR_LOG_CURRENT_EXCEPTION();
354 CASPAR_LOG_CURRENT_EXCEPTION();
358 void try_sleep_almost_until_vblank()
360 static const double THRESHOLD = 0.003;
361 double threshold = config_.vsync ? THRESHOLD : 0.0;
363 auto frame_time = 1.0 / (format_desc_.fps * format_desc_.field_count);
365 wait_timer_.tick(frame_time - threshold);
368 void wait_for_vblank_and_display()
370 try_sleep_almost_until_vblank();
372 // Make sure that the next tick measures the duration from this point in time.
373 wait_timer_.tick(0.0);
376 spl::shared_ptr<AVFrame> get_av_frame()
378 spl::shared_ptr<AVFrame> av_frame(avcodec_alloc_frame(), av_free);
379 avcodec_get_frame_defaults(av_frame.get());
381 av_frame->linesize[0] = format_desc_.width*4;
382 av_frame->format = PIX_FMT_BGRA;
383 av_frame->width = format_desc_.width;
384 av_frame->height = format_desc_.height;
385 av_frame->interlaced_frame = format_desc_.field_mode != core::field_mode::progressive;
386 av_frame->top_field_first = format_desc_.field_mode == core::field_mode::upper ? 1 : 0;
391 void render_and_draw_frame(core::const_frame frame)
393 if(static_cast<size_t>(frame.image_data().size()) != format_desc_.size)
396 if(screen_width_ == 0 && screen_height_ == 0)
399 perf_timer_.restart();
400 auto av_frame = get_av_frame();
401 av_frame->data[0] = const_cast<uint8_t*>(frame.image_data().begin());
403 filter_.push(av_frame);
404 auto frames = filter_.poll_all();
409 if (frames.size() == 1)
412 graph_->set_value("frame-time", perf_timer_.elapsed() * format_desc_.fps * 0.5);
414 wait_for_vblank_and_display(); // progressive frame
416 else if (frames.size() == 2)
419 double perf_elapsed = perf_timer_.elapsed();
421 wait_for_vblank_and_display(); // field1
423 perf_timer_.restart();
425 perf_elapsed += perf_timer_.elapsed();
426 graph_->set_value("frame-time", perf_elapsed * format_desc_.fps * 0.5);
428 wait_for_vblank_and_display(); // field2
432 void render(spl::shared_ptr<AVFrame> av_frame)
434 GL(glBindTexture(GL_TEXTURE_2D, texture_));
436 GL(glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbos_[0]));
437 GL(glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, format_desc_.width, format_desc_.height, GL_BGRA, GL_UNSIGNED_BYTE, 0));
439 GL(glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbos_[1]));
440 GL(glBufferData(GL_PIXEL_UNPACK_BUFFER, format_desc_.size, 0, GL_STREAM_DRAW));
442 auto ptr = reinterpret_cast<char*>(GL2(glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_WRITE_ONLY)));
447 tbb::parallel_for(tbb::blocked_range<int>(0, format_desc_.height), [&](const tbb::blocked_range<int>& r)
449 for(int n = r.begin(); n != r.end(); ++n)
450 aligned_memshfl(ptr+n*format_desc_.width*4, av_frame->data[0]+n*av_frame->linesize[0], format_desc_.width*4, 0x0F0F0F0F, 0x0B0B0B0B, 0x07070707, 0x03030303);
455 tbb::parallel_for(tbb::blocked_range<int>(0, format_desc_.height), [&](const tbb::blocked_range<int>& r)
457 for(int n = r.begin(); n != r.end(); ++n)
458 A_memcpy(ptr+n*format_desc_.width*4, av_frame->data[0]+n*av_frame->linesize[0], format_desc_.width*4);
462 GL(glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER)); // release the mapped buffer
465 GL(glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0));
467 GL(glClear(GL_COLOR_BUFFER_BIT));
469 glTexCoord2f(0.0f, 1.0f); glVertex2f(-width_, -height_);
470 glTexCoord2f(1.0f, 1.0f); glVertex2f( width_, -height_);
471 glTexCoord2f(1.0f, 0.0f); glVertex2f( width_, height_);
472 glTexCoord2f(0.0f, 0.0f); glVertex2f(-width_, height_);
475 GL(glBindTexture(GL_TEXTURE_2D, 0));
477 std::rotate(pbos_.begin(), pbos_.begin() + 1, pbos_.end());
481 std::future<bool> send(core::const_frame frame)
483 if(!frame_buffer_.try_push(frame))
484 graph_->set_tag("dropped-frame");
486 return make_ready_future(is_running_.load());
489 std::wstring channel_and_format() const
491 return L"[" + boost::lexical_cast<std::wstring>(channel_index_) + L"|" + format_desc_.name + L"]";
494 std::wstring print() const
496 return config_.name + channel_and_format();
499 void calculate_aspect()
503 screen_height_ = window_.getSize().y;
504 screen_width_ = window_.getSize().x;
507 GL(glViewport(0, 0, screen_width_, screen_height_));
509 std::pair<float, float> target_ratio = None();
510 if (config_.stretch == stretch::fill)
511 target_ratio = Fill();
512 else if (config_.stretch == stretch::uniform)
513 target_ratio = Uniform();
514 else if (config_.stretch == stretch::uniform_to_fill)
515 target_ratio = UniformToFill();
517 width_ = target_ratio.first;
518 height_ = target_ratio.second;
521 std::pair<float, float> None()
523 float width = static_cast<float>(square_width_)/static_cast<float>(screen_width_);
524 float height = static_cast<float>(square_height_)/static_cast<float>(screen_height_);
526 return std::make_pair(width, height);
529 std::pair<float, float> Uniform()
531 float aspect = static_cast<float>(square_width_)/static_cast<float>(square_height_);
532 float width = std::min(1.0f, static_cast<float>(screen_height_)*aspect/static_cast<float>(screen_width_));
533 float height = static_cast<float>(screen_width_*width)/static_cast<float>(screen_height_*aspect);
535 return std::make_pair(width, height);
538 std::pair<float, float> Fill()
540 return std::make_pair(1.0f, 1.0f);
543 std::pair<float, float> UniformToFill()
545 float wr = static_cast<float>(square_width_)/static_cast<float>(screen_width_);
546 float hr = static_cast<float>(square_height_)/static_cast<float>(screen_height_);
547 float r_inv = 1.0f/std::min(wr, hr);
549 float width = wr*r_inv;
550 float height = hr*r_inv;
552 return std::make_pair(width, height);
557 struct screen_consumer_proxy : public core::frame_consumer
559 core::monitor::subject monitor_subject_;
560 const configuration config_;
561 std::unique_ptr<screen_consumer> consumer_;
562 core::interaction_sink* sink_;
566 screen_consumer_proxy(const configuration& config, core::interaction_sink* sink)
574 void initialize(const core::video_format_desc& format_desc, int channel_index) override
577 consumer_.reset(new screen_consumer(config_, format_desc, channel_index, sink_));
580 std::future<bool> send(core::const_frame frame) override
582 return consumer_->send(frame);
585 std::wstring print() const override
587 return consumer_ ? consumer_->print() : L"[screen_consumer]";
590 std::wstring name() const override
595 boost::property_tree::wptree info() const override
597 boost::property_tree::wptree info;
598 info.add(L"type", L"screen");
599 info.add(L"key-only", config_.key_only);
600 info.add(L"windowed", config_.windowed);
601 info.add(L"auto-deinterlace", config_.auto_deinterlace);
605 bool has_synchronization_clock() const override
610 int buffer_depth() const override
615 int index() const override
617 return 600 + (config_.key_only ? 10 : 0) + config_.screen_index;
620 core::monitor::subject& monitor_output()
622 return monitor_subject_;
626 spl::shared_ptr<core::frame_consumer> create_consumer(const std::vector<std::wstring>& params)
628 if(params.size() < 1 || params[0] != L"SCREEN")
629 return core::frame_consumer::empty();
631 configuration config;
633 if(params.size() > 1)
634 config.screen_index = boost::lexical_cast<int>(params[1]);
636 config.key_only = std::find(params.begin(), params.end(), L"WINDOWED") != params.end();
637 config.key_only = std::find(params.begin(), params.end(), L"KEY_ONLY") != params.end();
639 auto name_it = std::find(params.begin(), params.end(), L"NAME");
640 if(name_it != params.end() && ++name_it != params.end())
641 config.name = *name_it;
643 return spl::make_shared<screen_consumer_proxy>(config, nullptr);
646 spl::shared_ptr<core::frame_consumer> create_consumer(const boost::property_tree::wptree& ptree, core::interaction_sink* sink)
648 configuration config;
649 config.name = ptree.get(L"name", config.name);
650 config.screen_index = ptree.get(L"device", config.screen_index+1)-1;
651 config.windowed = ptree.get(L"windowed", config.windowed);
652 config.key_only = ptree.get(L"key-only", config.key_only);
653 config.auto_deinterlace = ptree.get(L"auto-deinterlace", config.auto_deinterlace);
654 config.vsync = ptree.get(L"vsync", config.vsync);
656 auto stretch_str = ptree.get(L"stretch", L"default");
657 if(stretch_str == L"uniform")
658 config.stretch = stretch::uniform;
659 else if(stretch_str == L"uniform_to_fill")
660 config.stretch = stretch::uniform_to_fill;
662 auto aspect_str = ptree.get(L"aspect-ratio", L"default");
663 if(aspect_str == L"16:9")
664 config.aspect = configuration::aspect_ratio::aspect_16_9;
665 else if(aspect_str == L"4:3")
666 config.aspect = configuration::aspect_ratio::aspect_4_3;
668 return spl::make_shared<screen_consumer_proxy>(config, sink);