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>
37 #include <ffmpeg/producer/filter/filter.h>
39 #include <core/video_format.h>
40 #include <core/frame/frame.h>
41 #include <core/consumer/frame_consumer.h>
43 #include <boost/timer.hpp>
44 #include <boost/circular_buffer.hpp>
45 #include <boost/lexical_cast.hpp>
46 #include <boost/foreach.hpp>
47 #include <boost/property_tree/ptree.hpp>
48 #include <boost/thread.hpp>
50 #include <tbb/atomic.h>
51 #include <tbb/concurrent_queue.h>
52 #include <tbb/parallel_for.h>
54 #include <boost/assign.hpp>
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 {
99 bool auto_deinterlace;
109 , auto_deinterlace(true)
111 , aspect(aspect_invalid)
117 struct screen_consumer : boost::noncopyable
119 const configuration config_;
120 core::video_format_desc format_desc_;
124 std::vector<GLuint> pbos_;
137 spl::shared_ptr<diagnostics::graph> graph_;
138 boost::timer perf_timer_;
139 boost::timer tick_timer_;
141 caspar::prec_timer wait_timer_;
143 tbb::concurrent_bounded_queue<core::const_frame> frame_buffer_;
145 boost::thread thread_;
146 tbb::atomic<bool> is_running_;
148 ffmpeg::filter filter_;
150 screen_consumer(const configuration& config, const core::video_format_desc& format_desc, int channel_index)
152 , format_desc_(format_desc)
153 , channel_index_(channel_index)
156 , screen_width_(format_desc.width)
157 , screen_height_(format_desc.height)
158 , square_width_(format_desc.square_width)
159 , square_height_(format_desc.square_height)
160 , filter_(format_desc.field_mode == core::field_mode::progressive || !config.auto_deinterlace ? L"" : L"YADIF=1:-1", boost::assign::list_of(PIX_FMT_BGRA))
162 if(format_desc_.format == core::video_format::ntsc && config_.aspect == configuration::aspect_4_3)
164 // Use default values which are 4:3.
168 if(config_.aspect == configuration::aspect_16_9)
169 square_width_ = (format_desc.height*16)/9;
170 else if(config_.aspect == configuration::aspect_4_3)
171 square_width_ = (format_desc.height*4)/3;
174 frame_buffer_.set_capacity(2);
176 graph_->set_color("tick-time", diagnostics::color(0.0f, 0.6f, 0.9f));
177 graph_->set_color("frame-time", diagnostics::color(0.1f, 1.0f, 0.1f));
178 graph_->set_color("dropped-frame", diagnostics::color(0.3f, 0.6f, 0.3f));
179 graph_->set_text(print());
180 diagnostics::register_graph(graph_);
182 DISPLAY_DEVICE d_device = {sizeof(d_device), 0};
183 std::vector<DISPLAY_DEVICE> displayDevices;
184 for(int n = 0; EnumDisplayDevices(NULL, n, &d_device, NULL); ++n)
185 displayDevices.push_back(d_device);
187 if(config_.screen_index >= displayDevices.size())
188 CASPAR_LOG(warning) << print() << L" Invalid screen-index: " << config_.screen_index;
190 DEVMODE devmode = {};
191 if(!EnumDisplaySettings(displayDevices[config_.screen_index].DeviceName, ENUM_CURRENT_SETTINGS, &devmode))
192 CASPAR_LOG(warning) << print() << L" Could not find display settings for screen-index: " << config_.screen_index;
194 screen_x_ = devmode.dmPosition.x;
195 screen_y_ = devmode.dmPosition.y;
196 screen_width_ = config_.windowed ? square_width_ : devmode.dmPelsWidth;
197 screen_height_ = config_.windowed ? square_height_ : devmode.dmPelsHeight;
200 thread_ = boost::thread([this]{run();});
206 frame_buffer_.try_push(core::const_frame::empty());
212 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);
213 window_.ShowMouseCursor(false);
214 window_.SetPosition(screen_x_, screen_y_);
215 window_.SetSize(screen_width_, screen_height_);
218 if(!GLEW_VERSION_2_1 && glewInit() != GLEW_OK)
219 CASPAR_THROW_EXCEPTION(gl::ogl_exception() << msg_info("Failed to initialize GLEW."));
221 if(!GLEW_VERSION_2_1)
222 CASPAR_THROW_EXCEPTION(not_supported() << msg_info("Missing OpenGL 2.1 support."));
224 GL(glEnable(GL_TEXTURE_2D));
225 GL(glDisable(GL_DEPTH_TEST));
226 GL(glClearColor(0.0, 0.0, 0.0, 0.0));
227 GL(glViewport(0, 0, format_desc_.width, format_desc_.height));
228 GL(glLoadIdentity());
232 GL(glGenTextures(1, &texture_));
233 GL(glBindTexture(GL_TEXTURE_2D, texture_));
234 GL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
235 GL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
236 GL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP));
237 GL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP));
238 GL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, format_desc_.width, format_desc_.height, 0, GL_BGRA, GL_UNSIGNED_BYTE, 0));
239 GL(glBindTexture(GL_TEXTURE_2D, 0));
241 GL(glGenBuffers(2, pbos_.data()));
243 glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, pbos_[0]);
244 glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, format_desc_.size, 0, GL_STREAM_DRAW_ARB);
245 glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, pbos_[1]);
246 glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, format_desc_.size, 0, GL_STREAM_DRAW_ARB);
247 glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
249 auto wglSwapIntervalEXT = reinterpret_cast<void(APIENTRY*)(int)>(wglGetProcAddress("wglSwapIntervalEXT"));
250 if(wglSwapIntervalEXT)
254 wglSwapIntervalEXT(1);
255 CASPAR_LOG(info) << print() << " Enabled vsync.";
258 wglSwapIntervalEXT(0);
261 CASPAR_LOG(info) << print() << " Successfully Initialized.";
267 glDeleteTextures(1, &texture_);
269 BOOST_FOREACH(auto& pbo, pbos_)
272 glDeleteBuffers(1, &pbo);
287 while(window_.GetEvent(e))
289 if(e.Type == sf::Event::Resized)
291 else if(e.Type == sf::Event::Closed)
295 auto frame = core::const_frame::empty();
296 frame_buffer_.pop(frame);
298 render_and_draw_frame(frame);
300 /*perf_timer_.restart();
302 graph_->set_value("frame-time", perf_timer_.elapsed()*format_desc_.fps*0.5);
306 graph_->set_value("tick-time", tick_timer_.elapsed()*format_desc_.fps*0.5);
307 tick_timer_.restart();
311 CASPAR_LOG_CURRENT_EXCEPTION();
320 CASPAR_LOG_CURRENT_EXCEPTION();
324 void try_sleep_almost_until_vblank()
326 static const double THRESHOLD = 0.003;
327 double threshold = config_.vsync ? THRESHOLD : 0.0;
329 auto frame_time = 1.0 / (format_desc_.fps * format_desc_.field_count);
331 wait_timer_.tick(frame_time - threshold);
334 void wait_for_vblank_and_display()
336 try_sleep_almost_until_vblank();
338 // Make sure that the next tick measures the duration from this point in time.
339 wait_timer_.tick(0.0);
342 spl::shared_ptr<AVFrame> get_av_frame()
344 spl::shared_ptr<AVFrame> av_frame(avcodec_alloc_frame(), av_free);
345 avcodec_get_frame_defaults(av_frame.get());
347 av_frame->linesize[0] = format_desc_.width*4;
348 av_frame->format = PIX_FMT_BGRA;
349 av_frame->width = format_desc_.width;
350 av_frame->height = format_desc_.height;
351 av_frame->interlaced_frame = format_desc_.field_mode != core::field_mode::progressive;
352 av_frame->top_field_first = format_desc_.field_mode == core::field_mode::upper ? 1 : 0;
357 void render_and_draw_frame(core::const_frame frame)
359 if(static_cast<size_t>(frame.image_data().size()) != format_desc_.size)
362 if(screen_width_ == 0 && screen_height_ == 0)
365 perf_timer_.restart();
366 auto av_frame = get_av_frame();
367 av_frame->data[0] = const_cast<uint8_t*>(frame.image_data().begin());
369 filter_.push(av_frame);
370 auto frames = filter_.poll_all();
375 if (frames.size() == 1)
378 graph_->set_value("frame-time", perf_timer_.elapsed() * format_desc_.fps * 0.5);
380 wait_for_vblank_and_display(); // progressive frame
382 else if (frames.size() == 2)
385 double perf_elapsed = perf_timer_.elapsed();
387 wait_for_vblank_and_display(); // field1
389 perf_timer_.restart();
391 perf_elapsed += perf_timer_.elapsed();
392 graph_->set_value("frame-time", perf_elapsed * format_desc_.fps * 0.5);
394 wait_for_vblank_and_display(); // field2
398 void render(spl::shared_ptr<AVFrame> av_frame)
400 GL(glBindTexture(GL_TEXTURE_2D, texture_));
402 GL(glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbos_[0]));
403 GL(glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, format_desc_.width, format_desc_.height, GL_BGRA, GL_UNSIGNED_BYTE, 0));
405 GL(glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbos_[1]));
406 GL(glBufferData(GL_PIXEL_UNPACK_BUFFER, format_desc_.size, 0, GL_STREAM_DRAW));
408 auto ptr = reinterpret_cast<char*>(GL2(glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_WRITE_ONLY)));
413 tbb::parallel_for(tbb::blocked_range<int>(0, format_desc_.height), [&](const tbb::blocked_range<int>& r)
415 for(int n = r.begin(); n != r.end(); ++n)
416 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);
421 tbb::parallel_for(tbb::blocked_range<int>(0, format_desc_.height), [&](const tbb::blocked_range<int>& r)
423 for(int n = r.begin(); n != r.end(); ++n)
424 A_memcpy(ptr+n*format_desc_.width*4, av_frame->data[0]+n*av_frame->linesize[0], format_desc_.width*4);
428 GL(glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER)); // release the mapped buffer
431 GL(glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0));
433 GL(glClear(GL_COLOR_BUFFER_BIT));
435 glTexCoord2f(0.0f, 1.0f); glVertex2f(-width_, -height_);
436 glTexCoord2f(1.0f, 1.0f); glVertex2f( width_, -height_);
437 glTexCoord2f(1.0f, 0.0f); glVertex2f( width_, height_);
438 glTexCoord2f(0.0f, 0.0f); glVertex2f(-width_, height_);
441 GL(glBindTexture(GL_TEXTURE_2D, 0));
443 std::rotate(pbos_.begin(), pbos_.begin() + 1, pbos_.end());
447 boost::unique_future<bool> send(core::const_frame frame)
449 if(!frame_buffer_.try_push(frame))
450 graph_->set_tag("dropped-frame");
452 return wrap_as_future(is_running_.load());
455 std::wstring channel_and_format() const
457 return L"[" + boost::lexical_cast<std::wstring>(channel_index_) + L"|" + format_desc_.name + L"]";
460 std::wstring print() const
462 return config_.name + channel_and_format();
465 void calculate_aspect()
469 screen_height_ = window_.GetHeight();
470 screen_width_ = window_.GetWidth();
473 GL(glViewport(0, 0, screen_width_, screen_height_));
475 std::pair<float, float> target_ratio = None();
476 if(config_.stretch == fill)
477 target_ratio = Fill();
478 else if(config_.stretch == uniform)
479 target_ratio = Uniform();
480 else if(config_.stretch == uniform_to_fill)
481 target_ratio = UniformToFill();
483 width_ = target_ratio.first;
484 height_ = target_ratio.second;
487 std::pair<float, float> None()
489 float width = static_cast<float>(square_width_)/static_cast<float>(screen_width_);
490 float height = static_cast<float>(square_height_)/static_cast<float>(screen_height_);
492 return std::make_pair(width, height);
495 std::pair<float, float> Uniform()
497 float aspect = static_cast<float>(square_width_)/static_cast<float>(square_height_);
498 float width = std::min(1.0f, static_cast<float>(screen_height_)*aspect/static_cast<float>(screen_width_));
499 float height = static_cast<float>(screen_width_*width)/static_cast<float>(screen_height_*aspect);
501 return std::make_pair(width, height);
504 std::pair<float, float> Fill()
506 return std::make_pair(1.0f, 1.0f);
509 std::pair<float, float> UniformToFill()
511 float wr = static_cast<float>(square_width_)/static_cast<float>(screen_width_);
512 float hr = static_cast<float>(square_height_)/static_cast<float>(screen_height_);
513 float r_inv = 1.0f/std::min(wr, hr);
515 float width = wr*r_inv;
516 float height = hr*r_inv;
518 return std::make_pair(width, height);
523 struct screen_consumer_proxy : public core::frame_consumer
525 const configuration config_;
526 std::unique_ptr<screen_consumer> consumer_;
530 screen_consumer_proxy(const configuration& config)
535 void initialize(const core::video_format_desc& format_desc, int channel_index) override
538 consumer_.reset(new screen_consumer(config_, format_desc, channel_index));
541 boost::unique_future<bool> send(core::const_frame frame) override
543 return consumer_->send(frame);
546 std::wstring print() const override
548 return consumer_ ? consumer_->print() : L"[screen_consumer]";
551 std::wstring name() const override
556 boost::property_tree::wptree info() const override
558 boost::property_tree::wptree info;
559 info.add(L"type", L"screen");
560 info.add(L"key-only", config_.key_only);
561 info.add(L"windowed", config_.windowed);
562 info.add(L"auto-deinterlace", config_.auto_deinterlace);
566 bool has_synchronization_clock() const override
571 int buffer_depth() const override
576 int index() const override
578 return 600 + (config_.key_only ? 10 : 0) + config_.screen_index;
581 void subscribe(const monitor::observable::observer_ptr& o) override
585 void unsubscribe(const monitor::observable::observer_ptr& o) override
590 spl::shared_ptr<core::frame_consumer> create_consumer(const std::vector<std::wstring>& params)
592 if(params.size() < 1 || params[0] != L"SCREEN")
593 return core::frame_consumer::empty();
595 configuration config;
597 if(params.size() > 1)
598 config.screen_index = boost::lexical_cast<int>(params[1]);
600 config.key_only = std::find(params.begin(), params.end(), L"WINDOWED") != params.end();
601 config.key_only = std::find(params.begin(), params.end(), L"KEY_ONLY") != params.end();
603 auto name_it = std::find(params.begin(), params.end(), L"NAME");
604 if(name_it != params.end() && ++name_it != params.end())
605 config.name = *name_it;
607 return spl::make_shared<screen_consumer_proxy>(config);
610 spl::shared_ptr<core::frame_consumer> create_consumer(const boost::property_tree::wptree& ptree)
612 configuration config;
613 config.name = ptree.get(L"name", config.name);
614 config.screen_index = ptree.get(L"device", config.screen_index+1)-1;
615 config.windowed = ptree.get(L"windowed", config.windowed);
616 config.key_only = ptree.get(L"key-only", config.key_only);
617 config.auto_deinterlace = ptree.get(L"auto-deinterlace", config.auto_deinterlace);
618 config.vsync = ptree.get(L"vsync", config.vsync);
620 auto stretch_str = ptree.get(L"stretch", L"default");
621 if(stretch_str == L"uniform")
622 config.stretch = stretch::uniform;
623 else if(stretch_str == L"uniform_to_fill")
624 config.stretch = stretch::uniform_to_fill;
626 auto aspect_str = ptree.get(L"aspect-ratio", L"default");
627 if(aspect_str == L"16:9")
628 config.aspect = configuration::aspect_16_9;
629 else if(aspect_str == L"4:3")
630 config.aspect = configuration::aspect_4_3;
632 return spl::make_shared<screen_consumer_proxy>(config);