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>
44 #include <core/interaction/interaction_sink.h>
46 #include <boost/timer.hpp>
47 #include <boost/circular_buffer.hpp>
48 #include <boost/lexical_cast.hpp>
49 #include <boost/property_tree/ptree.hpp>
50 #include <boost/thread.hpp>
52 #include <tbb/atomic.h>
53 #include <tbb/concurrent_queue.h>
54 #include <tbb/parallel_for.h>
62 #pragma warning (push)
63 #pragma warning (disable : 4244)
67 #define __STDC_CONSTANT_MACROS
68 #define __STDC_LIMIT_MACROS
69 #include <libavcodec/avcodec.h>
70 #include <libavutil/imgutils.h>
76 namespace caspar { namespace screen {
88 enum class aspect_ratio
95 std::wstring name = L"ogl";
97 stretch stretch = stretch::fill;
99 bool auto_deinterlace = true;
100 bool key_only = false;
101 aspect_ratio aspect = aspect_ratio::aspect_invalid;
103 bool interactive = true;
106 struct screen_consumer : boost::noncopyable
108 const configuration config_;
109 core::video_format_desc format_desc_;
113 std::vector<GLuint> pbos_ = std::vector<GLuint> { 0, 0 };
119 int screen_width_ = format_desc_.width;
120 int screen_height_ = format_desc_.height;
121 int square_width_ = format_desc_.square_width;
122 int square_height_ = format_desc_.square_height;
126 spl::shared_ptr<diagnostics::graph> graph_;
127 boost::timer perf_timer_;
128 boost::timer tick_timer_;
130 caspar::prec_timer wait_timer_;
132 tbb::concurrent_bounded_queue<core::const_frame> frame_buffer_;
133 core::interaction_sink* sink_;
135 boost::thread thread_;
136 tbb::atomic<bool> is_running_;
138 ffmpeg::filter filter_;
141 const configuration& config,
142 const core::video_format_desc& format_desc,
144 core::interaction_sink* sink)
146 , format_desc_(format_desc)
147 , channel_index_(channel_index)
149 , filter_([&]() -> ffmpeg::filter
151 const auto sample_aspect_ratio =
152 boost::rational<int>(
153 format_desc.square_width,
154 format_desc.square_height) /
155 boost::rational<int>(
159 return ffmpeg::filter(
162 boost::rational<int>(format_desc.duration, format_desc.time_scale),
163 boost::rational<int>(format_desc.time_scale, format_desc.duration),
167 format_desc.field_mode == core::field_mode::progressive || !config.auto_deinterlace ? "" : "YADIF=1:-1");
170 if (format_desc_.format == core::video_format::ntsc && config_.aspect == configuration::aspect_ratio::aspect_4_3)
172 // Use default values which are 4:3.
176 if (config_.aspect == configuration::aspect_ratio::aspect_16_9)
177 square_width_ = (format_desc.height*16)/9;
178 else if (config_.aspect == configuration::aspect_ratio::aspect_4_3)
179 square_width_ = (format_desc.height*4)/3;
182 frame_buffer_.set_capacity(1);
184 graph_->set_color("tick-time", diagnostics::color(0.0f, 0.6f, 0.9f));
185 graph_->set_color("frame-time", diagnostics::color(0.1f, 1.0f, 0.1f));
186 graph_->set_color("dropped-frame", diagnostics::color(0.3f, 0.6f, 0.3f));
187 graph_->set_text(print());
188 diagnostics::register_graph(graph_);
190 DISPLAY_DEVICE d_device = {sizeof(d_device), 0};
191 std::vector<DISPLAY_DEVICE> displayDevices;
192 for(int n = 0; EnumDisplayDevices(NULL, n, &d_device, NULL); ++n)
193 displayDevices.push_back(d_device);
195 if(config_.screen_index >= displayDevices.size())
196 CASPAR_LOG(warning) << print() << L" Invalid screen-index: " << config_.screen_index;
198 DEVMODE devmode = {};
199 if(!EnumDisplaySettings(displayDevices[config_.screen_index].DeviceName, ENUM_CURRENT_SETTINGS, &devmode))
200 CASPAR_LOG(warning) << print() << L" Could not find display settings for screen-index: " << config_.screen_index;
202 screen_x_ = devmode.dmPosition.x;
203 screen_y_ = devmode.dmPosition.y;
204 screen_width_ = config_.windowed ? square_width_ : devmode.dmPelsWidth;
205 screen_height_ = config_.windowed ? square_height_ : devmode.dmPelsHeight;
208 thread_ = boost::thread([this]{run();});
214 frame_buffer_.try_push(core::const_frame::empty());
220 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);
221 window_.setMouseCursorVisible(config_.interactive);
222 window_.setPosition(sf::Vector2i(screen_x_, screen_y_));
223 window_.setSize(sf::Vector2u(screen_width_, screen_height_));
226 if(!GLEW_VERSION_2_1 && glewInit() != GLEW_OK)
227 CASPAR_THROW_EXCEPTION(gl::ogl_exception() << msg_info("Failed to initialize GLEW."));
229 if(!GLEW_VERSION_2_1)
230 CASPAR_THROW_EXCEPTION(not_supported() << msg_info("Missing OpenGL 2.1 support."));
232 GL(glEnable(GL_TEXTURE_2D));
233 GL(glDisable(GL_DEPTH_TEST));
234 GL(glClearColor(0.0, 0.0, 0.0, 0.0));
235 GL(glViewport(0, 0, format_desc_.width, format_desc_.height));
236 GL(glLoadIdentity());
240 GL(glGenTextures(1, &texture_));
241 GL(glBindTexture(GL_TEXTURE_2D, texture_));
242 GL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
243 GL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
244 GL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP));
245 GL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP));
246 GL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, format_desc_.width, format_desc_.height, 0, GL_BGRA, GL_UNSIGNED_BYTE, 0));
247 GL(glBindTexture(GL_TEXTURE_2D, 0));
249 GL(glGenBuffers(2, pbos_.data()));
251 glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, pbos_[0]);
252 glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, format_desc_.size, 0, GL_STREAM_DRAW_ARB);
253 glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, pbos_[1]);
254 glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, format_desc_.size, 0, GL_STREAM_DRAW_ARB);
255 glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
257 auto wglSwapIntervalEXT = reinterpret_cast<void(APIENTRY*)(int)>(wglGetProcAddress("wglSwapIntervalEXT"));
258 if(wglSwapIntervalEXT)
262 wglSwapIntervalEXT(1);
263 CASPAR_LOG(info) << print() << " Enabled vsync.";
266 wglSwapIntervalEXT(0);
269 CASPAR_LOG(info) << print() << " Successfully Initialized.";
275 glDeleteTextures(1, &texture_);
277 for (auto& pbo : pbos_)
280 glDeleteBuffers(1, &pbo);
295 while(window_.pollEvent(e))
297 if (e.type == sf::Event::Resized)
299 else if (e.type == sf::Event::Closed)
301 else if (config_.interactive && sink_)
305 case sf::Event::MouseMoved:
307 auto& mouse_move = e.mouseMove;
308 sink_->on_interaction(spl::make_shared<core::mouse_move_event>(
310 static_cast<double>(mouse_move.x) / screen_width_,
311 static_cast<double>(mouse_move.y) / screen_height_));
314 case sf::Event::MouseButtonPressed:
315 case sf::Event::MouseButtonReleased:
317 auto& mouse_button = e.mouseButton;
318 sink_->on_interaction(spl::make_shared<core::mouse_button_event>(
320 static_cast<double>(mouse_button.x) / screen_width_,
321 static_cast<double>(mouse_button.y) / screen_height_,
322 static_cast<int>(mouse_button.button),
323 e.type == sf::Event::MouseButtonPressed));
330 auto frame = core::const_frame::empty();
331 frame_buffer_.pop(frame);
333 render_and_draw_frame(frame);
335 /*perf_timer_.restart();
337 graph_->set_value("frame-time", perf_timer_.elapsed()*format_desc_.fps*0.5);
341 graph_->set_value("tick-time", tick_timer_.elapsed()*format_desc_.fps*0.5);
342 tick_timer_.restart();
346 CASPAR_LOG_CURRENT_EXCEPTION();
355 CASPAR_LOG_CURRENT_EXCEPTION();
359 void try_sleep_almost_until_vblank()
361 static const double THRESHOLD = 0.003;
362 double threshold = config_.vsync ? THRESHOLD : 0.0;
364 auto frame_time = 1.0 / (format_desc_.fps * format_desc_.field_count);
366 wait_timer_.tick(frame_time - threshold);
369 void wait_for_vblank_and_display()
371 try_sleep_almost_until_vblank();
373 // Make sure that the next tick measures the duration from this point in time.
374 wait_timer_.tick(0.0);
377 spl::shared_ptr<AVFrame> get_av_frame()
379 spl::shared_ptr<AVFrame> av_frame(avcodec_alloc_frame(), av_free);
380 avcodec_get_frame_defaults(av_frame.get());
382 av_frame->linesize[0] = format_desc_.width*4;
383 av_frame->format = PIX_FMT_BGRA;
384 av_frame->width = format_desc_.width;
385 av_frame->height = format_desc_.height;
386 av_frame->interlaced_frame = format_desc_.field_mode != core::field_mode::progressive;
387 av_frame->top_field_first = format_desc_.field_mode == core::field_mode::upper ? 1 : 0;
392 void render_and_draw_frame(core::const_frame frame)
394 if(static_cast<size_t>(frame.image_data().size()) != format_desc_.size)
397 if(screen_width_ == 0 && screen_height_ == 0)
400 perf_timer_.restart();
401 auto av_frame = get_av_frame();
402 av_frame->data[0] = const_cast<uint8_t*>(frame.image_data().begin());
404 filter_.push(av_frame);
405 auto frames = filter_.poll_all();
410 if (frames.size() == 1)
413 graph_->set_value("frame-time", perf_timer_.elapsed() * format_desc_.fps * 0.5);
415 wait_for_vblank_and_display(); // progressive frame
417 else if (frames.size() == 2)
420 double perf_elapsed = perf_timer_.elapsed();
422 wait_for_vblank_and_display(); // field1
424 perf_timer_.restart();
426 perf_elapsed += perf_timer_.elapsed();
427 graph_->set_value("frame-time", perf_elapsed * format_desc_.fps * 0.5);
429 wait_for_vblank_and_display(); // field2
433 void render(spl::shared_ptr<AVFrame> av_frame)
435 GL(glBindTexture(GL_TEXTURE_2D, texture_));
437 GL(glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbos_[0]));
438 GL(glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, format_desc_.width, format_desc_.height, GL_BGRA, GL_UNSIGNED_BYTE, 0));
440 GL(glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbos_[1]));
441 GL(glBufferData(GL_PIXEL_UNPACK_BUFFER, format_desc_.size, 0, GL_STREAM_DRAW));
443 auto ptr = reinterpret_cast<char*>(GL2(glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_WRITE_ONLY)));
448 tbb::parallel_for(tbb::blocked_range<int>(0, format_desc_.height), [&](const tbb::blocked_range<int>& r)
450 for(int n = r.begin(); n != r.end(); ++n)
451 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);
456 tbb::parallel_for(tbb::blocked_range<int>(0, format_desc_.height), [&](const tbb::blocked_range<int>& r)
458 for(int n = r.begin(); n != r.end(); ++n)
459 A_memcpy(ptr+n*format_desc_.width*4, av_frame->data[0]+n*av_frame->linesize[0], format_desc_.width*4);
463 GL(glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER)); // release the mapped buffer
466 GL(glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0));
468 GL(glClear(GL_COLOR_BUFFER_BIT));
470 glTexCoord2f(0.0f, 1.0f); glVertex2f(-width_, -height_);
471 glTexCoord2f(1.0f, 1.0f); glVertex2f( width_, -height_);
472 glTexCoord2f(1.0f, 0.0f); glVertex2f( width_, height_);
473 glTexCoord2f(0.0f, 0.0f); glVertex2f(-width_, height_);
476 GL(glBindTexture(GL_TEXTURE_2D, 0));
478 std::rotate(pbos_.begin(), pbos_.begin() + 1, pbos_.end());
482 std::future<bool> send(core::const_frame frame)
484 if(!frame_buffer_.try_push(frame))
485 graph_->set_tag("dropped-frame");
487 return make_ready_future(is_running_.load());
490 std::wstring channel_and_format() const
492 return L"[" + boost::lexical_cast<std::wstring>(channel_index_) + L"|" + format_desc_.name + L"]";
495 std::wstring print() const
497 return config_.name + channel_and_format();
500 void calculate_aspect()
504 screen_height_ = window_.getSize().y;
505 screen_width_ = window_.getSize().x;
508 GL(glViewport(0, 0, screen_width_, screen_height_));
510 std::pair<float, float> target_ratio = None();
511 if (config_.stretch == stretch::fill)
512 target_ratio = Fill();
513 else if (config_.stretch == stretch::uniform)
514 target_ratio = Uniform();
515 else if (config_.stretch == stretch::uniform_to_fill)
516 target_ratio = UniformToFill();
518 width_ = target_ratio.first;
519 height_ = target_ratio.second;
522 std::pair<float, float> None()
524 float width = static_cast<float>(square_width_)/static_cast<float>(screen_width_);
525 float height = static_cast<float>(square_height_)/static_cast<float>(screen_height_);
527 return std::make_pair(width, height);
530 std::pair<float, float> Uniform()
532 float aspect = static_cast<float>(square_width_)/static_cast<float>(square_height_);
533 float width = std::min(1.0f, static_cast<float>(screen_height_)*aspect/static_cast<float>(screen_width_));
534 float height = static_cast<float>(screen_width_*width)/static_cast<float>(screen_height_*aspect);
536 return std::make_pair(width, height);
539 std::pair<float, float> Fill()
541 return std::make_pair(1.0f, 1.0f);
544 std::pair<float, float> UniformToFill()
546 float wr = static_cast<float>(square_width_)/static_cast<float>(screen_width_);
547 float hr = static_cast<float>(square_height_)/static_cast<float>(screen_height_);
548 float r_inv = 1.0f/std::min(wr, hr);
550 float width = wr*r_inv;
551 float height = hr*r_inv;
553 return std::make_pair(width, height);
558 struct screen_consumer_proxy : public core::frame_consumer
560 core::monitor::subject monitor_subject_;
561 const configuration config_;
562 std::unique_ptr<screen_consumer> consumer_;
563 core::interaction_sink* sink_;
567 screen_consumer_proxy(const configuration& config, core::interaction_sink* sink)
575 void initialize(const core::video_format_desc& format_desc, int channel_index) override
578 consumer_.reset(new screen_consumer(config_, format_desc, channel_index, sink_));
581 std::future<bool> send(core::const_frame frame) override
583 return consumer_->send(frame);
586 std::wstring print() const override
588 return consumer_ ? consumer_->print() : L"[screen_consumer]";
591 std::wstring name() const override
596 boost::property_tree::wptree info() const override
598 boost::property_tree::wptree info;
599 info.add(L"type", L"screen");
600 info.add(L"key-only", config_.key_only);
601 info.add(L"windowed", config_.windowed);
602 info.add(L"auto-deinterlace", config_.auto_deinterlace);
606 bool has_synchronization_clock() const override
611 int buffer_depth() const override
616 int index() const override
618 return 600 + (config_.key_only ? 10 : 0) + config_.screen_index;
621 core::monitor::subject& monitor_output()
623 return monitor_subject_;
627 spl::shared_ptr<core::frame_consumer> create_consumer(const std::vector<std::wstring>& params, core::interaction_sink* sink)
629 if(params.size() < 1 || params[0] != L"SCREEN")
630 return core::frame_consumer::empty();
632 configuration config;
634 if(params.size() > 1)
635 config.screen_index = boost::lexical_cast<int>(params[1]);
637 config.windowed = std::find(params.begin(), params.end(), L"WINDOWED") != params.end();
638 config.key_only = std::find(params.begin(), params.end(), L"KEY_ONLY") != params.end();
639 config.interactive = std::find(params.begin(), params.end(), L"INTERACTIVE") != params.end();
641 auto name_it = std::find(params.begin(), params.end(), L"NAME");
642 if(name_it != params.end() && ++name_it != params.end())
643 config.name = *name_it;
645 return spl::make_shared<screen_consumer_proxy>(config, sink);
648 spl::shared_ptr<core::frame_consumer> create_preconfigured_consumer(const boost::property_tree::wptree& ptree, core::interaction_sink* sink)
650 configuration config;
651 config.name = ptree.get(L"name", config.name);
652 config.screen_index = ptree.get(L"device", config.screen_index+1)-1;
653 config.windowed = ptree.get(L"windowed", config.windowed);
654 config.key_only = ptree.get(L"key-only", config.key_only);
655 config.auto_deinterlace = ptree.get(L"auto-deinterlace", config.auto_deinterlace);
656 config.vsync = ptree.get(L"vsync", config.vsync);
658 auto stretch_str = ptree.get(L"stretch", L"default");
659 if(stretch_str == L"uniform")
660 config.stretch = stretch::uniform;
661 else if(stretch_str == L"uniform_to_fill")
662 config.stretch = stretch::uniform_to_fill;
664 auto aspect_str = ptree.get(L"aspect-ratio", L"default");
665 if(aspect_str == L"16:9")
666 config.aspect = configuration::aspect_ratio::aspect_16_9;
667 else if(aspect_str == L"4:3")
668 config.aspect = configuration::aspect_ratio::aspect_4_3;
670 return spl::make_shared<screen_consumer_proxy>(config, sink);