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