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>
36 #include <common/timer.h>
37 #include <common/param.h>
38 #include <common/os/general_protection_fault.h>
39 #include <common/scope_exit.h>
41 //#include <windows.h>
43 #include <ffmpeg/producer/filter/filter.h>
45 #include <core/video_format.h>
46 #include <core/frame/frame.h>
47 #include <core/consumer/frame_consumer.h>
48 #include <core/interaction/interaction_sink.h>
49 #include <core/help/help_sink.h>
50 #include <core/help/help_repository.h>
52 #include <boost/circular_buffer.hpp>
53 #include <boost/lexical_cast.hpp>
54 #include <boost/property_tree/ptree.hpp>
55 #include <boost/thread.hpp>
56 #include <boost/algorithm/string.hpp>
58 #include <tbb/atomic.h>
59 #include <tbb/concurrent_queue.h>
60 #include <tbb/parallel_for.h>
68 #pragma warning (push)
69 #pragma warning (disable : 4244)
73 #define __STDC_CONSTANT_MACROS
74 #define __STDC_LIMIT_MACROS
75 #include <libavcodec/avcodec.h>
76 #include <libavutil/imgutils.h>
82 namespace caspar { namespace screen {
94 enum class aspect_ratio
101 std::wstring name = L"ogl";
102 int screen_index = 0;
103 screen::stretch stretch = screen::stretch::fill;
104 bool windowed = true;
105 bool auto_deinterlace = true;
106 bool key_only = false;
107 aspect_ratio aspect = aspect_ratio::aspect_invalid;
109 bool interactive = true;
110 bool borderless = false;
113 struct screen_consumer : boost::noncopyable
115 const configuration config_;
116 core::video_format_desc format_desc_;
120 std::vector<GLuint> pbos_ = std::vector<GLuint> { 0, 0 };
126 int screen_width_ = format_desc_.width;
127 int screen_height_ = format_desc_.height;
128 int square_width_ = format_desc_.square_width;
129 int square_height_ = format_desc_.square_height;
132 tbb::atomic<bool> polling_event_;
134 spl::shared_ptr<diagnostics::graph> graph_;
135 caspar::timer perf_timer_;
136 caspar::timer tick_timer_;
138 caspar::prec_timer wait_timer_;
140 tbb::concurrent_bounded_queue<core::const_frame> frame_buffer_;
141 core::interaction_sink* sink_;
143 boost::thread thread_;
144 tbb::atomic<bool> is_running_;
145 tbb::atomic<int64_t> current_presentation_age_;
147 ffmpeg::filter filter_;
150 const configuration& config,
151 const core::video_format_desc& format_desc,
153 core::interaction_sink* sink)
155 , format_desc_(format_desc)
156 , channel_index_(channel_index)
158 , filter_([&]() -> ffmpeg::filter
160 const auto sample_aspect_ratio =
161 boost::rational<int>(
162 format_desc.square_width,
163 format_desc.square_height) /
164 boost::rational<int>(
168 return ffmpeg::filter(
171 boost::rational<int>(format_desc.duration, format_desc.time_scale),
172 boost::rational<int>(format_desc.time_scale, format_desc.duration),
176 format_desc.field_mode == core::field_mode::progressive || !config.auto_deinterlace ? "" : "YADIF=1:-1");
179 if (format_desc_.format == core::video_format::ntsc && config_.aspect == configuration::aspect_ratio::aspect_4_3)
181 // Use default values which are 4:3.
185 if (config_.aspect == configuration::aspect_ratio::aspect_16_9)
186 square_width_ = (format_desc.height*16)/9;
187 else if (config_.aspect == configuration::aspect_ratio::aspect_4_3)
188 square_width_ = (format_desc.height*4)/3;
191 frame_buffer_.set_capacity(1);
193 graph_->set_color("tick-time", diagnostics::color(0.0f, 0.6f, 0.9f));
194 graph_->set_color("frame-time", diagnostics::color(0.1f, 1.0f, 0.1f));
195 graph_->set_color("dropped-frame", diagnostics::color(0.3f, 0.6f, 0.3f));
196 graph_->set_text(print());
197 diagnostics::register_graph(graph_);
199 /*DISPLAY_DEVICE d_device = {sizeof(d_device), 0};
200 std::vector<DISPLAY_DEVICE> displayDevices;
201 for(int n = 0; EnumDisplayDevices(NULL, n, &d_device, NULL); ++n)
202 displayDevices.push_back(d_device);
204 if(config_.screen_index >= displayDevices.size())
205 CASPAR_LOG(warning) << print() << L" Invalid screen-index: " << config_.screen_index;
207 DEVMODE devmode = {};
208 if(!EnumDisplaySettings(displayDevices[config_.screen_index].DeviceName, ENUM_CURRENT_SETTINGS, &devmode))
209 CASPAR_LOG(warning) << print() << L" Could not find display settings for screen-index: " << config_.screen_index;
211 screen_x_ = devmode.dmPosition.x;
212 screen_y_ = devmode.dmPosition.y;
213 screen_width_ = config_.windowed ? square_width_ : devmode.dmPelsWidth;
214 screen_height_ = config_.windowed ? square_height_ : devmode.dmPelsHeight;*/
217 screen_width_ = square_width_;
218 screen_height_ = square_height_;
220 polling_event_ = false;
222 current_presentation_age_ = 0;
223 thread_ = boost::thread([this]{run();});
229 frame_buffer_.try_push(core::const_frame::empty());
235 auto window_style = config_.borderless
238 ? sf::Style::Resize | sf::Style::Close
239 : sf::Style::Fullscreen);
240 window_.create(sf::VideoMode(screen_width_, screen_height_, 32), u8(L"Screen consumer " + channel_and_format()), window_style);
241 window_.setMouseCursorVisible(config_.interactive);
242 window_.setPosition(sf::Vector2i(screen_x_, screen_y_));
243 window_.setSize(sf::Vector2u(screen_width_, screen_height_));
246 if(!GLEW_VERSION_2_1 && glewInit() != GLEW_OK)
247 CASPAR_THROW_EXCEPTION(gl::ogl_exception() << msg_info("Failed to initialize GLEW."));
249 if(!GLEW_VERSION_2_1)
250 CASPAR_THROW_EXCEPTION(not_supported() << msg_info("Missing OpenGL 2.1 support."));
252 GL(glEnable(GL_TEXTURE_2D));
253 GL(glDisable(GL_DEPTH_TEST));
254 GL(glClearColor(0.0, 0.0, 0.0, 0.0));
255 GL(glViewport(0, 0, format_desc_.width, format_desc_.height));
256 GL(glLoadIdentity());
260 GL(glGenTextures(1, &texture_));
261 GL(glBindTexture(GL_TEXTURE_2D, texture_));
262 GL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
263 GL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
264 GL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP));
265 GL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP));
266 GL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, format_desc_.width, format_desc_.height, 0, GL_BGRA, GL_UNSIGNED_BYTE, 0));
267 GL(glBindTexture(GL_TEXTURE_2D, 0));
269 GL(glGenBuffers(2, pbos_.data()));
271 glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, pbos_[0]);
272 glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, format_desc_.size, 0, GL_STREAM_DRAW_ARB);
273 glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, pbos_[1]);
274 glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, format_desc_.size, 0, GL_STREAM_DRAW_ARB);
275 glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
277 window_.setVerticalSyncEnabled(config_.vsync);
281 CASPAR_LOG(info) << print() << " Enabled vsync.";
283 /*auto wglSwapIntervalEXT = reinterpret_cast<void(APIENTRY*)(int)>(wglGetProcAddress("wglSwapIntervalEXT"));
284 if(wglSwapIntervalEXT)
288 wglSwapIntervalEXT(1);
289 CASPAR_LOG(info) << print() << " Enabled vsync.";
292 wglSwapIntervalEXT(0);
299 glDeleteTextures(1, &texture_);
301 for (auto& pbo : pbos_)
304 glDeleteBuffers(1, &pbo);
310 ensure_gpf_handler_installed_for_thread("screen-consumer-thread");
320 auto poll_event = [this](sf::Event& e)
322 polling_event_ = true;
325 polling_event_ = false;
327 return window_.pollEvent(e);
333 if (e.type == sf::Event::Resized)
335 else if (e.type == sf::Event::Closed)
337 else if (config_.interactive && sink_)
341 case sf::Event::MouseMoved:
343 auto& mouse_move = e.mouseMove;
344 sink_->on_interaction(spl::make_shared<core::mouse_move_event>(
346 static_cast<double>(mouse_move.x) / screen_width_,
347 static_cast<double>(mouse_move.y) / screen_height_));
350 case sf::Event::MouseButtonPressed:
351 case sf::Event::MouseButtonReleased:
353 auto& mouse_button = e.mouseButton;
354 sink_->on_interaction(spl::make_shared<core::mouse_button_event>(
356 static_cast<double>(mouse_button.x) / screen_width_,
357 static_cast<double>(mouse_button.y) / screen_height_,
358 static_cast<int>(mouse_button.button),
359 e.type == sf::Event::MouseButtonPressed));
362 case sf::Event::MouseWheelMoved:
364 auto& wheel_moved = e.mouseWheel;
365 sink_->on_interaction(spl::make_shared<core::mouse_wheel_event>(
367 static_cast<double>(wheel_moved.x) / screen_width_,
368 static_cast<double>(wheel_moved.y) / screen_height_,
376 core::const_frame frame;
377 frame_buffer_.pop(frame);
379 render_and_draw_frame(frame);
381 /*perf_timer_.restart();
383 graph_->set_value("frame-time", perf_timer_.elapsed()*format_desc_.fps*0.5);
387 current_presentation_age_ = frame.get_age_millis();
388 graph_->set_value("tick-time", tick_timer_.elapsed()*format_desc_.fps*0.5);
389 tick_timer_.restart();
393 CASPAR_LOG_CURRENT_EXCEPTION();
402 CASPAR_LOG_CURRENT_EXCEPTION();
406 void try_sleep_almost_until_vblank()
408 static const double THRESHOLD = 0.003;
409 double threshold = config_.vsync ? THRESHOLD : 0.0;
411 auto frame_time = 1.0 / (format_desc_.fps * format_desc_.field_count);
413 wait_timer_.tick(frame_time - threshold);
416 void wait_for_vblank_and_display()
418 try_sleep_almost_until_vblank();
420 // Make sure that the next tick measures the duration from this point in time.
421 wait_timer_.tick(0.0);
424 spl::shared_ptr<AVFrame> get_av_frame()
426 spl::shared_ptr<AVFrame> av_frame(avcodec_alloc_frame(), av_free);
427 avcodec_get_frame_defaults(av_frame.get());
429 av_frame->linesize[0] = format_desc_.width*4;
430 av_frame->format = PIX_FMT_BGRA;
431 av_frame->width = format_desc_.width;
432 av_frame->height = format_desc_.height;
433 av_frame->interlaced_frame = format_desc_.field_mode != core::field_mode::progressive;
434 av_frame->top_field_first = format_desc_.field_mode == core::field_mode::upper ? 1 : 0;
439 void render_and_draw_frame(core::const_frame input_frame)
441 if(static_cast<size_t>(input_frame.image_data().size()) != format_desc_.size)
444 if(screen_width_ == 0 && screen_height_ == 0)
447 perf_timer_.restart();
448 auto av_frame = get_av_frame();
449 av_frame->data[0] = const_cast<uint8_t*>(input_frame.image_data().begin());
451 filter_.push(av_frame);
452 auto frame = filter_.poll();
457 if (!filter_.is_double_rate())
459 render(spl::make_shared_ptr(frame));
460 graph_->set_value("frame-time", perf_timer_.elapsed() * format_desc_.fps * 0.5);
462 wait_for_vblank_and_display(); // progressive frame
466 render(spl::make_shared_ptr(frame));
467 double perf_elapsed = perf_timer_.elapsed();
469 wait_for_vblank_and_display(); // field1
471 perf_timer_.restart();
472 frame = filter_.poll();
473 render(spl::make_shared_ptr(frame));
474 perf_elapsed += perf_timer_.elapsed();
475 graph_->set_value("frame-time", perf_elapsed * format_desc_.fps * 0.5);
477 wait_for_vblank_and_display(); // field2
481 void render(spl::shared_ptr<AVFrame> av_frame)
483 GL(glBindTexture(GL_TEXTURE_2D, texture_));
485 GL(glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbos_[0]));
486 GL(glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, format_desc_.width, format_desc_.height, GL_BGRA, GL_UNSIGNED_BYTE, 0));
488 GL(glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbos_[1]));
489 GL(glBufferData(GL_PIXEL_UNPACK_BUFFER, format_desc_.size, 0, GL_STREAM_DRAW));
491 auto ptr = reinterpret_cast<char*>(GL2(glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_WRITE_ONLY)));
496 tbb::parallel_for(tbb::blocked_range<int>(0, format_desc_.height), [&](const tbb::blocked_range<int>& r)
498 for(int n = r.begin(); n != r.end(); ++n)
499 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);
504 tbb::parallel_for(tbb::blocked_range<int>(0, format_desc_.height), [&](const tbb::blocked_range<int>& r)
506 for(int n = r.begin(); n != r.end(); ++n)
507 A_memcpy(ptr+n*format_desc_.width*4, av_frame->data[0]+n*av_frame->linesize[0], format_desc_.width*4);
511 GL(glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER)); // release the mapped buffer
514 GL(glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0));
516 GL(glClear(GL_COLOR_BUFFER_BIT));
518 glTexCoord2f(0.0f, 1.0f); glVertex2f(-width_, -height_);
519 glTexCoord2f(1.0f, 1.0f); glVertex2f( width_, -height_);
520 glTexCoord2f(1.0f, 0.0f); glVertex2f( width_, height_);
521 glTexCoord2f(0.0f, 0.0f); glVertex2f(-width_, height_);
524 GL(glBindTexture(GL_TEXTURE_2D, 0));
526 std::rotate(pbos_.begin(), pbos_.begin() + 1, pbos_.end());
530 std::future<bool> send(core::const_frame frame)
532 if(!frame_buffer_.try_push(frame) && !polling_event_)
533 graph_->set_tag(diagnostics::tag_severity::WARNING, "dropped-frame");
535 return make_ready_future(is_running_.load());
538 std::wstring channel_and_format() const
540 return L"[" + boost::lexical_cast<std::wstring>(channel_index_) + L"|" + format_desc_.name + L"]";
543 std::wstring print() const
545 return config_.name + channel_and_format();
548 void calculate_aspect()
552 screen_height_ = window_.getSize().y;
553 screen_width_ = window_.getSize().x;
556 GL(glViewport(0, 0, screen_width_, screen_height_));
558 std::pair<float, float> target_ratio = None();
559 if (config_.stretch == screen::stretch::fill)
560 target_ratio = Fill();
561 else if (config_.stretch == screen::stretch::uniform)
562 target_ratio = Uniform();
563 else if (config_.stretch == screen::stretch::uniform_to_fill)
564 target_ratio = UniformToFill();
566 width_ = target_ratio.first;
567 height_ = target_ratio.second;
570 std::pair<float, float> None()
572 float width = static_cast<float>(square_width_)/static_cast<float>(screen_width_);
573 float height = static_cast<float>(square_height_)/static_cast<float>(screen_height_);
575 return std::make_pair(width, height);
578 std::pair<float, float> Uniform()
580 float aspect = static_cast<float>(square_width_)/static_cast<float>(square_height_);
581 float width = std::min(1.0f, static_cast<float>(screen_height_)*aspect/static_cast<float>(screen_width_));
582 float height = static_cast<float>(screen_width_*width)/static_cast<float>(screen_height_*aspect);
584 return std::make_pair(width, height);
587 std::pair<float, float> Fill()
589 return std::make_pair(1.0f, 1.0f);
592 std::pair<float, float> UniformToFill()
594 float wr = static_cast<float>(square_width_)/static_cast<float>(screen_width_);
595 float hr = static_cast<float>(square_height_)/static_cast<float>(screen_height_);
596 float r_inv = 1.0f/std::min(wr, hr);
598 float width = wr*r_inv;
599 float height = hr*r_inv;
601 return std::make_pair(width, height);
606 struct screen_consumer_proxy : public core::frame_consumer
608 core::monitor::subject monitor_subject_;
609 const configuration config_;
610 std::unique_ptr<screen_consumer> consumer_;
611 core::interaction_sink* sink_;
615 screen_consumer_proxy(const configuration& config, core::interaction_sink* sink)
623 void initialize(const core::video_format_desc& format_desc, const core::audio_channel_layout&, int channel_index) override
626 consumer_.reset(new screen_consumer(config_, format_desc, channel_index, sink_));
629 int64_t presentation_frame_age_millis() const override
631 return consumer_ ? static_cast<int64_t>(consumer_->current_presentation_age_) : 0;
634 std::future<bool> send(core::const_frame frame) override
636 return consumer_->send(frame);
639 std::wstring print() const override
641 return consumer_ ? consumer_->print() : L"[screen_consumer]";
644 std::wstring name() const override
649 boost::property_tree::wptree info() const override
651 boost::property_tree::wptree info;
652 info.add(L"type", L"screen");
653 info.add(L"key-only", config_.key_only);
654 info.add(L"windowed", config_.windowed);
655 info.add(L"auto-deinterlace", config_.auto_deinterlace);
656 info.add(L"vsync", config_.vsync);
660 bool has_synchronization_clock() const override
665 int buffer_depth() const override
670 int index() const override
672 return 600 + (config_.key_only ? 10 : 0) + config_.screen_index;
675 core::monitor::subject& monitor_output()
677 return monitor_subject_;
681 void describe_consumer(core::help_sink& sink, const core::help_repository& repo)
683 sink.short_description(L"Displays the contents of a channel on screen using OpenGL.");
686 L"{[screen_index:int]|1} "
687 L"{[fullscreen:FULLSCREEN]} "
688 L"{[borderless:BORDERLESS]} "
689 L"{[key_only:KEY_ONLY]} "
690 L"{[non_interactive:NON_INTERACTIVE]} "
691 L"{[no_auto_deinterlace:NO_AUTO_DEINTERLACE]} "
692 L"{NAME [name:string]}");
693 sink.para()->text(L"Displays the contents of a channel on screen using OpenGL.");
695 ->item(L"screen_index", L"Determines which screen the channel should be displayed on. Defaults to 1.")
696 ->item(L"fullscreen", L"If specified opens the window in fullscreen.")
697 ->item(L"borderless", L"Makes the window appear without any window decorations.")
698 ->item(L"key_only", L"Only displays the alpha channel of the video channel if specified.")
699 ->item(L"non_interactive", L"If specified does not send mouse input to producers on the video channel.")
700 ->item(L"no_auto_deinterlace", L"If the video mode of the channel is an interlaced mode, specifying this will turn of deinterlacing.")
701 ->item(L"name", L"Optionally specifies a name of the window to show.");
702 sink.para()->text(L"Examples:");
703 sink.example(L">> ADD 1 SCREEN", L"opens a screen consumer on the default screen.");
704 sink.example(L">> ADD 1 SCREEN 2", L"opens a screen consumer on the screen 2.");
705 sink.example(L">> ADD 1 SCREEN 1 FULLSCREEN", L"opens a screen consumer in fullscreen on screen 1.");
706 sink.example(L">> ADD 1 SCREEN 1 BORDERLESS", L"opens a screen consumer without borders/window decorations on screen 1.");
709 spl::shared_ptr<core::frame_consumer> create_consumer(const std::vector<std::wstring>& params, core::interaction_sink* sink)
711 if (params.size() < 1 || !boost::iequals(params.at(0), L"SCREEN"))
712 return core::frame_consumer::empty();
714 configuration config;
716 if (params.size() > 1)
717 config.screen_index = boost::lexical_cast<int>(params.at(1));
719 config.windowed = !contains_param(L"FULLSCREEN", params);
720 config.key_only = contains_param(L"KEY_ONLY", params);
721 config.interactive = !contains_param(L"NON_INTERACTIVE", params);
722 config.auto_deinterlace = !contains_param(L"NO_AUTO_DEINTERLACE", params);
723 config.borderless = contains_param(L"BORDERLESS", params);
725 if (contains_param(L"NAME", params))
726 config.name = get_param(L"NAME", params);
728 return spl::make_shared<screen_consumer_proxy>(config, sink);
731 spl::shared_ptr<core::frame_consumer> create_preconfigured_consumer(const boost::property_tree::wptree& ptree, core::interaction_sink* sink)
733 configuration config;
734 config.name = ptree.get(L"name", config.name);
735 config.screen_index = ptree.get(L"device", config.screen_index + 1) - 1;
736 config.windowed = ptree.get(L"windowed", config.windowed);
737 config.key_only = ptree.get(L"key-only", config.key_only);
738 config.auto_deinterlace = ptree.get(L"auto-deinterlace", config.auto_deinterlace);
739 config.vsync = ptree.get(L"vsync", config.vsync);
740 config.interactive = ptree.get(L"interactive", config.interactive);
741 config.borderless = ptree.get(L"borderless", config.borderless);
743 auto stretch_str = ptree.get(L"stretch", L"default");
744 if(stretch_str == L"uniform")
745 config.stretch = screen::stretch::uniform;
746 else if(stretch_str == L"uniform_to_fill")
747 config.stretch = screen::stretch::uniform_to_fill;
749 auto aspect_str = ptree.get(L"aspect-ratio", L"default");
750 if(aspect_str == L"16:9")
751 config.aspect = configuration::aspect_ratio::aspect_16_9;
752 else if(aspect_str == L"4:3")
753 config.aspect = configuration::aspect_ratio::aspect_4_3;
755 return spl::make_shared<screen_consumer_proxy>(config, sink);