]> git.sesse.net Git - casparcg/blob - modules/screen/consumer/screen_consumer.cpp
* Added logging of severe diagnostics events to log at warning level. graph::set_tag...
[casparcg] / modules / screen / consumer / screen_consumer.cpp
1 /*
2 * Copyright (c) 2011 Sveriges Television AB <info@casparcg.com>
3 *
4 * This file is part of CasparCG (www.casparcg.com).
5 *
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.
10 *
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.
15 *
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/>.
18 *
19 * Author: Robert Nagy, ronag89@gmail.com
20 */
21
22 #include "screen_consumer.h"
23
24 #include <GL/glew.h>
25 #include <SFML/Window.hpp>
26
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
40 //#include <windows.h>
41
42 #include <ffmpeg/producer/filter/filter.h>
43
44 #include <core/video_format.h>
45 #include <core/frame/frame.h>
46 #include <core/consumer/frame_consumer.h>
47 #include <core/interaction/interaction_sink.h>
48 #include <core/help/help_sink.h>
49 #include <core/help/help_repository.h>
50
51 #include <boost/circular_buffer.hpp>
52 #include <boost/lexical_cast.hpp>
53 #include <boost/property_tree/ptree.hpp>
54 #include <boost/thread.hpp>
55 #include <boost/algorithm/string.hpp>
56
57 #include <tbb/atomic.h>
58 #include <tbb/concurrent_queue.h>
59 #include <tbb/parallel_for.h>
60
61 #include <asmlib.h>
62
63 #include <algorithm>
64 #include <vector>
65
66 #if defined(_MSC_VER)
67 #pragma warning (push)
68 #pragma warning (disable : 4244)
69 #endif
70 extern "C" 
71 {
72         #define __STDC_CONSTANT_MACROS
73         #define __STDC_LIMIT_MACROS
74         #include <libavcodec/avcodec.h>
75         #include <libavutil/imgutils.h>
76 }
77 #if defined(_MSC_VER)
78 #pragma warning (pop)
79 #endif
80
81 namespace caspar { namespace screen {
82                 
83 enum class stretch
84 {
85         none,
86         uniform,
87         fill,
88         uniform_to_fill
89 };
90
91 struct configuration
92 {
93         enum class aspect_ratio
94         {
95                 aspect_4_3 = 0,
96                 aspect_16_9,
97                 aspect_invalid,
98         };
99                 
100         std::wstring    name                            = L"ogl";
101         int                             screen_index            = 0;
102         screen::stretch stretch                         = screen::stretch::fill;
103         bool                    windowed                        = true;
104         bool                    auto_deinterlace        = true;
105         bool                    key_only                        = false;
106         aspect_ratio    aspect                          = aspect_ratio::aspect_invalid;
107         bool                    vsync                           = true;
108         bool                    interactive                     = true;
109         bool                    borderless                      = false;
110 };
111
112 struct screen_consumer : boost::noncopyable
113 {
114         const configuration                                                                     config_;
115         core::video_format_desc                                                         format_desc_;
116         int                                                                                                     channel_index_;
117
118         GLuint                                                                                          texture_                = 0;
119         std::vector<GLuint>                                                                     pbos_                   = std::vector<GLuint> { 0, 0 };
120                         
121         float                                                                                           width_;
122         float                                                                                           height_;
123         int                                                                                                     screen_x_;
124         int                                                                                                     screen_y_;
125         int                                                                                                     screen_width_   = format_desc_.width;
126         int                                                                                                     screen_height_  = format_desc_.height;
127         int                                                                                                     square_width_   = format_desc_.square_width;
128         int                                                                                                     square_height_  = format_desc_.square_height;
129
130         sf::Window                                                                                      window_;
131
132         spl::shared_ptr<diagnostics::graph>                                     graph_;
133         caspar::timer                                                                           perf_timer_;
134         caspar::timer                                                                           tick_timer_;
135
136         caspar::prec_timer                                                                      wait_timer_;
137
138         tbb::concurrent_bounded_queue<core::const_frame>        frame_buffer_;
139         core::interaction_sink*                                                         sink_;
140
141         boost::thread                                                                           thread_;
142         tbb::atomic<bool>                                                                       is_running_;
143         tbb::atomic<int64_t>                                                            current_presentation_age_;
144
145         ffmpeg::filter                                                                          filter_;
146 public:
147         screen_consumer(
148                         const configuration& config,
149                         const core::video_format_desc& format_desc,
150                         int channel_index,
151                         core::interaction_sink* sink) 
152                 : config_(config)
153                 , format_desc_(format_desc)
154                 , channel_index_(channel_index)
155                 , sink_(sink)
156                 , filter_([&]() -> ffmpeg::filter
157                 {                       
158                         const auto sample_aspect_ratio = 
159                                 boost::rational<int>(
160                                         format_desc.square_width, 
161                                         format_desc.square_height) /
162                                 boost::rational<int>(
163                                         format_desc.width, 
164                                         format_desc.height);
165
166                         return ffmpeg::filter(
167                                 format_desc.width,
168                                 format_desc.height,
169                                 boost::rational<int>(format_desc.duration, format_desc.time_scale),
170                                 boost::rational<int>(format_desc.time_scale, format_desc.duration),
171                                 sample_aspect_ratio,
172                                 AV_PIX_FMT_BGRA,
173                                 { AV_PIX_FMT_BGRA },
174                                 format_desc.field_mode == core::field_mode::progressive || !config.auto_deinterlace ? "" : "YADIF=1:-1");
175                 }())
176         {               
177                 if (format_desc_.format == core::video_format::ntsc && config_.aspect == configuration::aspect_ratio::aspect_4_3)
178                 {
179                         // Use default values which are 4:3.
180                 }
181                 else
182                 {
183                         if (config_.aspect == configuration::aspect_ratio::aspect_16_9)
184                                 square_width_ = (format_desc.height*16)/9;
185                         else if (config_.aspect == configuration::aspect_ratio::aspect_4_3)
186                                 square_width_ = (format_desc.height*4)/3;
187                 }
188
189                 frame_buffer_.set_capacity(1);
190                 
191                 graph_->set_color("tick-time", diagnostics::color(0.0f, 0.6f, 0.9f));   
192                 graph_->set_color("frame-time", diagnostics::color(0.1f, 1.0f, 0.1f));
193                 graph_->set_color("dropped-frame", diagnostics::color(0.3f, 0.6f, 0.3f));
194                 graph_->set_text(print());
195                 diagnostics::register_graph(graph_);
196                                                                         
197                 /*DISPLAY_DEVICE d_device = {sizeof(d_device), 0};
198                 std::vector<DISPLAY_DEVICE> displayDevices;
199                 for(int n = 0; EnumDisplayDevices(NULL, n, &d_device, NULL); ++n)
200                         displayDevices.push_back(d_device);
201
202                 if(config_.screen_index >= displayDevices.size())
203                         CASPAR_LOG(warning) << print() << L" Invalid screen-index: " << config_.screen_index;
204                 
205                 DEVMODE devmode = {};
206                 if(!EnumDisplaySettings(displayDevices[config_.screen_index].DeviceName, ENUM_CURRENT_SETTINGS, &devmode))
207                         CASPAR_LOG(warning) << print() << L" Could not find display settings for screen-index: " << config_.screen_index;
208                 
209                 screen_x_               = devmode.dmPosition.x;
210                 screen_y_               = devmode.dmPosition.y;
211                 screen_width_   = config_.windowed ? square_width_ : devmode.dmPelsWidth;
212                 screen_height_  = config_.windowed ? square_height_ : devmode.dmPelsHeight;*/
213                 screen_x_               = 0;
214                 screen_y_               = 0;
215                 screen_width_   = square_width_;
216                 screen_height_  = square_height_;
217                 
218                 is_running_ = true;
219                 current_presentation_age_ = 0;
220                 thread_ = boost::thread([this]{run();});
221         }
222         
223         ~screen_consumer()
224         {
225                 is_running_ = false;
226                 frame_buffer_.try_push(core::const_frame::empty());
227                 thread_.join();
228         }
229
230         void init()
231         {
232                 auto window_style = config_.borderless
233                         ? sf::Style::None
234                         : (config_.windowed
235                                 ? sf::Style::Resize | sf::Style::Close
236                                 : sf::Style::Fullscreen);
237                 window_.create(sf::VideoMode(screen_width_, screen_height_, 32), u8(L"Screen consumer " + channel_and_format()), window_style);
238                 window_.setMouseCursorVisible(config_.interactive);
239                 window_.setPosition(sf::Vector2i(screen_x_, screen_y_));
240                 window_.setSize(sf::Vector2u(screen_width_, screen_height_));
241                 window_.setActive();
242                 
243                 if(!GLEW_VERSION_2_1 && glewInit() != GLEW_OK)
244                         CASPAR_THROW_EXCEPTION(gl::ogl_exception() << msg_info("Failed to initialize GLEW."));
245
246                 if(!GLEW_VERSION_2_1)
247                         CASPAR_THROW_EXCEPTION(not_supported() << msg_info("Missing OpenGL 2.1 support."));
248
249                 GL(glEnable(GL_TEXTURE_2D));
250                 GL(glDisable(GL_DEPTH_TEST));           
251                 GL(glClearColor(0.0, 0.0, 0.0, 0.0));
252                 GL(glViewport(0, 0, format_desc_.width, format_desc_.height));
253                 GL(glLoadIdentity());
254                                 
255                 calculate_aspect();
256                         
257                 GL(glGenTextures(1, &texture_));
258                 GL(glBindTexture(GL_TEXTURE_2D, texture_));
259                 GL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
260                 GL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
261                 GL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP));
262                 GL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP));
263                 GL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, format_desc_.width, format_desc_.height, 0, GL_BGRA, GL_UNSIGNED_BYTE, 0));
264                 GL(glBindTexture(GL_TEXTURE_2D, 0));
265                                         
266                 GL(glGenBuffers(2, pbos_.data()));
267                         
268                 glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, pbos_[0]);
269                 glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, format_desc_.size, 0, GL_STREAM_DRAW_ARB);
270                 glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, pbos_[1]);
271                 glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, format_desc_.size, 0, GL_STREAM_DRAW_ARB);
272                 glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
273                 
274                 window_.setVerticalSyncEnabled(config_.vsync);
275
276                 if (config_.vsync)
277                 {
278                         CASPAR_LOG(info) << print() << " Enabled vsync.";
279                 }
280                 /*auto wglSwapIntervalEXT = reinterpret_cast<void(APIENTRY*)(int)>(wglGetProcAddress("wglSwapIntervalEXT"));
281                 if(wglSwapIntervalEXT)
282                 {
283                         if(config_.vsync)
284                         {
285                                 wglSwapIntervalEXT(1);
286                                 CASPAR_LOG(info) << print() << " Enabled vsync.";
287                         }
288                         else
289                                 wglSwapIntervalEXT(0);
290                 }*/
291         }
292
293         void uninit()
294         {               
295                 if(texture_)
296                         glDeleteTextures(1, &texture_);
297
298                 for (auto& pbo : pbos_)
299                 {
300                         if(pbo)
301                                 glDeleteBuffers(1, &pbo);
302                 }
303         }
304
305         void run()
306         {
307                 ensure_gpf_handler_installed_for_thread("screen-consumer-thread");
308
309                 try
310                 {
311                         init();
312
313                         while(is_running_)
314                         {                       
315                                 try
316                                 {
317                                         sf::Event e;            
318                                         while(window_.pollEvent(e))
319                                         {
320                                                 if (e.type == sf::Event::Resized)
321                                                         calculate_aspect();
322                                                 else if (e.type == sf::Event::Closed)
323                                                         is_running_ = false;
324                                                 else if (config_.interactive && sink_)
325                                                 {
326                                                         switch (e.type)
327                                                         {
328                                                         case sf::Event::MouseMoved:
329                                                                 {
330                                                                         auto& mouse_move = e.mouseMove;
331                                                                         sink_->on_interaction(spl::make_shared<core::mouse_move_event>(
332                                                                                         1,
333                                                                                         static_cast<double>(mouse_move.x) / screen_width_,
334                                                                                         static_cast<double>(mouse_move.y) / screen_height_));
335                                                                 }
336                                                                 break;
337                                                         case sf::Event::MouseButtonPressed:
338                                                         case sf::Event::MouseButtonReleased:
339                                                                 {
340                                                                         auto& mouse_button = e.mouseButton;
341                                                                         sink_->on_interaction(spl::make_shared<core::mouse_button_event>(
342                                                                                         1,
343                                                                                         static_cast<double>(mouse_button.x) / screen_width_,
344                                                                                         static_cast<double>(mouse_button.y) / screen_height_,
345                                                                                         static_cast<int>(mouse_button.button),
346                                                                                         e.type == sf::Event::MouseButtonPressed));
347                                                                 }
348                                                                 break;
349                                                         case sf::Event::MouseWheelMoved:
350                                                                 {
351                                                                         auto& wheel_moved = e.mouseWheel;
352                                                                         sink_->on_interaction(spl::make_shared<core::mouse_wheel_event>(
353                                                                                         1,
354                                                                                         static_cast<double>(wheel_moved.x) / screen_width_,
355                                                                                         static_cast<double>(wheel_moved.y) / screen_height_,
356                                                                                         wheel_moved.delta));
357                                                                 }
358                                                                 break;
359                                                         }
360                                                 }
361                                         }
362                         
363                                         core::const_frame frame;
364                                         frame_buffer_.pop(frame);
365
366                                         render_and_draw_frame(frame);
367                                         
368                                         /*perf_timer_.restart();
369                                         render(frame);
370                                         graph_->set_value("frame-time", perf_timer_.elapsed()*format_desc_.fps*0.5);    
371
372                                         window_.Display();*/
373
374                                         current_presentation_age_ = frame.get_age_millis();
375                                         graph_->set_value("tick-time", tick_timer_.elapsed()*format_desc_.fps*0.5);     
376                                         tick_timer_.restart();
377                                 }
378                                 catch(...)
379                                 {
380                                         CASPAR_LOG_CURRENT_EXCEPTION();
381                                         is_running_ = false;
382                                 }
383                         }
384
385                         uninit();
386                 }
387                 catch(...)
388                 {
389                         CASPAR_LOG_CURRENT_EXCEPTION();
390                 }
391         }
392
393         void try_sleep_almost_until_vblank()
394         {
395                 static const double THRESHOLD = 0.003;
396                 double threshold = config_.vsync ? THRESHOLD : 0.0;
397
398                 auto frame_time = 1.0 / (format_desc_.fps * format_desc_.field_count);
399
400                 wait_timer_.tick(frame_time - threshold);
401         }
402
403         void wait_for_vblank_and_display()
404         {
405                 try_sleep_almost_until_vblank();
406                 window_.display();
407                 // Make sure that the next tick measures the duration from this point in time.
408                 wait_timer_.tick(0.0);
409         }
410
411         spl::shared_ptr<AVFrame> get_av_frame()
412         {               
413                 spl::shared_ptr<AVFrame> av_frame(avcodec_alloc_frame(), av_free);      
414                 avcodec_get_frame_defaults(av_frame.get());
415                                                 
416                 av_frame->linesize[0]           = format_desc_.width*4;                 
417                 av_frame->format                        = PIX_FMT_BGRA;
418                 av_frame->width                         = format_desc_.width;
419                 av_frame->height                        = format_desc_.height;
420                 av_frame->interlaced_frame      = format_desc_.field_mode != core::field_mode::progressive;
421                 av_frame->top_field_first       = format_desc_.field_mode == core::field_mode::upper ? 1 : 0;
422
423                 return av_frame;
424         }
425
426         void render_and_draw_frame(core::const_frame input_frame)
427         {
428                 if(static_cast<size_t>(input_frame.image_data().size()) != format_desc_.size)
429                         return;
430
431                 if(screen_width_ == 0 && screen_height_ == 0)
432                         return;
433                                         
434                 perf_timer_.restart();
435                 auto av_frame = get_av_frame();
436                 av_frame->data[0] = const_cast<uint8_t*>(input_frame.image_data().begin());
437
438                 filter_.push(av_frame);
439                 auto frame = filter_.poll();
440
441                 if (!frame)
442                         return;
443
444                 if (!filter_.is_double_rate())
445                 {
446                         render(spl::make_shared_ptr(frame));
447                         graph_->set_value("frame-time", perf_timer_.elapsed() * format_desc_.fps * 0.5);
448
449                         wait_for_vblank_and_display(); // progressive frame
450                 }
451                 else
452                 {
453                         render(spl::make_shared_ptr(frame));
454                         double perf_elapsed = perf_timer_.elapsed();
455
456                         wait_for_vblank_and_display(); // field1
457
458                         perf_timer_.restart();
459                         frame = filter_.poll();
460                         render(spl::make_shared_ptr(frame));
461                         perf_elapsed += perf_timer_.elapsed();
462                         graph_->set_value("frame-time", perf_elapsed * format_desc_.fps * 0.5);
463
464                         wait_for_vblank_and_display(); // field2
465                 }
466         }
467
468         void render(spl::shared_ptr<AVFrame> av_frame)
469         {
470                 GL(glBindTexture(GL_TEXTURE_2D, texture_));
471
472                 GL(glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbos_[0]));
473                 GL(glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, format_desc_.width, format_desc_.height, GL_BGRA, GL_UNSIGNED_BYTE, 0));
474
475                 GL(glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbos_[1]));
476                 GL(glBufferData(GL_PIXEL_UNPACK_BUFFER, format_desc_.size, 0, GL_STREAM_DRAW));
477
478                 auto ptr = reinterpret_cast<char*>(GL2(glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_WRITE_ONLY)));
479                 if(ptr)
480                 {
481                         if(config_.key_only)
482                         {
483                                 tbb::parallel_for(tbb::blocked_range<int>(0, format_desc_.height), [&](const tbb::blocked_range<int>& r)
484                                 {
485                                         for(int n = r.begin(); n != r.end(); ++n)
486                                                 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);
487                                 });
488                         }
489                         else
490                         {       
491                                 tbb::parallel_for(tbb::blocked_range<int>(0, format_desc_.height), [&](const tbb::blocked_range<int>& r)
492                                 {
493                                         for(int n = r.begin(); n != r.end(); ++n)
494                                                 A_memcpy(ptr+n*format_desc_.width*4, av_frame->data[0]+n*av_frame->linesize[0], format_desc_.width*4);
495                                 });
496                         }
497                         
498                         GL(glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER)); // release the mapped buffer
499                 }
500
501                 GL(glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0));
502                                 
503                 GL(glClear(GL_COLOR_BUFFER_BIT));                       
504                 glBegin(GL_QUADS);
505                                 glTexCoord2f(0.0f,        1.0f);        glVertex2f(-width_, -height_);
506                                 glTexCoord2f(1.0f,        1.0f);        glVertex2f( width_, -height_);
507                                 glTexCoord2f(1.0f,        0.0f);        glVertex2f( width_,  height_);
508                                 glTexCoord2f(0.0f,        0.0f);        glVertex2f(-width_,  height_);
509                 glEnd();
510                 
511                 GL(glBindTexture(GL_TEXTURE_2D, 0));
512
513                 std::rotate(pbos_.begin(), pbos_.begin() + 1, pbos_.end());
514         }
515
516
517         std::future<bool> send(core::const_frame frame)
518         {
519                 if(!frame_buffer_.try_push(frame))
520                         graph_->set_tag(diagnostics::tag_severity::WARNING, "dropped-frame");
521
522                 return make_ready_future(is_running_.load());
523         }
524
525         std::wstring channel_and_format() const
526         {
527                 return L"[" + boost::lexical_cast<std::wstring>(channel_index_) + L"|" + format_desc_.name + L"]";
528         }
529
530         std::wstring print() const
531         {       
532                 return config_.name + channel_and_format();
533         }
534         
535         void calculate_aspect()
536         {
537                 if(config_.windowed)
538                 {
539                         screen_height_ = window_.getSize().y;
540                         screen_width_ = window_.getSize().x;
541                 }
542                 
543                 GL(glViewport(0, 0, screen_width_, screen_height_));
544
545                 std::pair<float, float> target_ratio = None();
546                 if (config_.stretch == screen::stretch::fill)
547                         target_ratio = Fill();
548                 else if (config_.stretch == screen::stretch::uniform)
549                         target_ratio = Uniform();
550                 else if (config_.stretch == screen::stretch::uniform_to_fill)
551                         target_ratio = UniformToFill();
552
553                 width_ = target_ratio.first;
554                 height_ = target_ratio.second;
555         }
556                 
557         std::pair<float, float> None()
558         {
559                 float width = static_cast<float>(square_width_)/static_cast<float>(screen_width_);
560                 float height = static_cast<float>(square_height_)/static_cast<float>(screen_height_);
561
562                 return std::make_pair(width, height);
563         }
564
565         std::pair<float, float> Uniform()
566         {
567                 float aspect = static_cast<float>(square_width_)/static_cast<float>(square_height_);
568                 float width = std::min(1.0f, static_cast<float>(screen_height_)*aspect/static_cast<float>(screen_width_));
569                 float height = static_cast<float>(screen_width_*width)/static_cast<float>(screen_height_*aspect);
570
571                 return std::make_pair(width, height);
572         }
573
574         std::pair<float, float> Fill()
575         {
576                 return std::make_pair(1.0f, 1.0f);
577         }
578
579         std::pair<float, float> UniformToFill()
580         {
581                 float wr = static_cast<float>(square_width_)/static_cast<float>(screen_width_);
582                 float hr = static_cast<float>(square_height_)/static_cast<float>(screen_height_);
583                 float r_inv = 1.0f/std::min(wr, hr);
584
585                 float width = wr*r_inv;
586                 float height = hr*r_inv;
587
588                 return std::make_pair(width, height);
589         }
590 };
591
592
593 struct screen_consumer_proxy : public core::frame_consumer
594 {
595         core::monitor::subject                          monitor_subject_;
596         const configuration                                     config_;
597         std::unique_ptr<screen_consumer>        consumer_;
598         core::interaction_sink*                         sink_;
599
600 public:
601
602         screen_consumer_proxy(const configuration& config, core::interaction_sink* sink)
603                 : config_(config)
604                 , sink_(sink)
605         {
606         }
607         
608         // frame_consumer
609
610         void initialize(const core::video_format_desc& format_desc, const core::audio_channel_layout&, int channel_index) override
611         {
612                 consumer_.reset();
613                 consumer_.reset(new screen_consumer(config_, format_desc, channel_index, sink_));
614         }
615
616         int64_t presentation_frame_age_millis() const override
617         {
618                 return consumer_ ? static_cast<int64_t>(consumer_->current_presentation_age_) : 0;
619         }
620
621         std::future<bool> send(core::const_frame frame) override
622         {
623                 return consumer_->send(frame);
624         }
625         
626         std::wstring print() const override
627         {
628                 return consumer_ ? consumer_->print() : L"[screen_consumer]";
629         }
630
631         std::wstring name() const override
632         {
633                 return L"screen";
634         }
635
636         boost::property_tree::wptree info() const override
637         {
638                 boost::property_tree::wptree info;
639                 info.add(L"type", L"screen");
640                 info.add(L"key-only", config_.key_only);
641                 info.add(L"windowed", config_.windowed);
642                 info.add(L"auto-deinterlace", config_.auto_deinterlace);
643                 info.add(L"vsync", config_.vsync);
644                 return info;
645         }
646
647         bool has_synchronization_clock() const override
648         {
649                 return false;
650         }
651         
652         int buffer_depth() const override
653         {
654                 return 1;
655         }
656
657         int index() const override
658         {
659                 return 600 + (config_.key_only ? 10 : 0) + config_.screen_index;
660         }
661
662         core::monitor::subject& monitor_output()
663         {
664                 return monitor_subject_;
665         }
666 };      
667
668 void describe_consumer(core::help_sink& sink, const core::help_repository& repo)
669 {
670         sink.short_description(L"Displays the contents of a channel on screen using OpenGL.");
671         sink.syntax(
672                         L"SCREEN "
673                         L"{[screen_index:int]|1} "
674                         L"{[fullscreen:FULLSCREEN]} "
675                         L"{[borderless:BORDERLESS]} "
676                         L"{[key_only:KEY_ONLY]} "
677                         L"{[non_interactive:NON_INTERACTIVE]} "
678                         L"{[no_auto_deinterlace:NO_AUTO_DEINTERLACE]} "
679                         L"{NAME [name:string]}");
680         sink.para()->text(L"Displays the contents of a channel on screen using OpenGL.");
681         sink.definitions()
682                 ->item(L"screen_index", L"Determines which screen the channel should be displayed on. Defaults to 1.")
683                 ->item(L"fullscreen", L"If specified opens the window in fullscreen.")
684                 ->item(L"borderless", L"Makes the window appear without any window decorations.")
685                 ->item(L"key_only", L"Only displays the alpha channel of the video channel if specified.")
686                 ->item(L"non_interactive", L"If specified does not send mouse input to producers on the video channel.")
687                 ->item(L"no_auto_deinterlace", L"If the video mode of the channel is an interlaced mode, specifying this will turn of deinterlacing.")
688                 ->item(L"name", L"Optionally specifies a name of the window to show.");
689         sink.para()->text(L"Examples:");
690         sink.example(L">> ADD 1 SCREEN", L"opens a screen consumer on the default screen.");
691         sink.example(L">> ADD 1 SCREEN 2", L"opens a screen consumer on the screen 2.");
692         sink.example(L">> ADD 1 SCREEN 1 FULLSCREEN", L"opens a screen consumer in fullscreen on screen 1.");
693         sink.example(L">> ADD 1 SCREEN 1 BORDERLESS", L"opens a screen consumer without borders/window decorations on screen 1.");
694 }
695
696 spl::shared_ptr<core::frame_consumer> create_consumer(const std::vector<std::wstring>& params, core::interaction_sink* sink)
697 {
698         if (params.size() < 1 || !boost::iequals(params.at(0), L"SCREEN"))
699                 return core::frame_consumer::empty();
700         
701         configuration config;
702                 
703         if (params.size() > 1)
704                 config.screen_index = boost::lexical_cast<int>(params.at(1));
705                 
706         config.windowed                 = !contains_param(L"FULLSCREEN", params);
707         config.key_only                 =  contains_param(L"KEY_ONLY", params);
708         config.interactive              = !contains_param(L"NON_INTERACTIVE", params);
709         config.auto_deinterlace = !contains_param(L"NO_AUTO_DEINTERLACE", params);
710         config.borderless               =  contains_param(L"BORDERLESS", params);
711
712         if (contains_param(L"NAME", params))
713                 config.name = get_param(L"NAME", params);
714
715         return spl::make_shared<screen_consumer_proxy>(config, sink);
716 }
717
718 spl::shared_ptr<core::frame_consumer> create_preconfigured_consumer(const boost::property_tree::wptree& ptree, core::interaction_sink* sink) 
719 {
720         configuration config;
721         config.name                             = ptree.get(L"name",                            config.name);
722         config.screen_index             = ptree.get(L"device",                          config.screen_index + 1) - 1;
723         config.windowed                 = ptree.get(L"windowed",                        config.windowed);
724         config.key_only                 = ptree.get(L"key-only",                        config.key_only);
725         config.auto_deinterlace = ptree.get(L"auto-deinterlace",        config.auto_deinterlace);
726         config.vsync                    = ptree.get(L"vsync",                           config.vsync);
727         config.interactive              = ptree.get(L"interactive",                     config.interactive);
728         config.borderless               = ptree.get(L"borderless",                      config.borderless);
729
730         auto stretch_str = ptree.get(L"stretch", L"default");
731         if(stretch_str == L"uniform")
732                 config.stretch = screen::stretch::uniform;
733         else if(stretch_str == L"uniform_to_fill")
734                 config.stretch = screen::stretch::uniform_to_fill;
735
736         auto aspect_str = ptree.get(L"aspect-ratio", L"default");
737         if(aspect_str == L"16:9")
738                 config.aspect = configuration::aspect_ratio::aspect_16_9;
739         else if(aspect_str == L"4:3")
740                 config.aspect = configuration::aspect_ratio::aspect_4_3;
741         
742         return spl::make_shared<screen_consumer_proxy>(config, sink);
743 }
744
745 }}