]> git.sesse.net Git - casparcg/blob - core/diagnostics/osd_graph.cpp
- Fixed diag to work with new SFML version.
[casparcg] / core / diagnostics / osd_graph.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 "../stdafx.h"
23
24 #include "osd_graph.h"
25
26 #pragma warning (disable : 4244)
27
28 #include "call_context.h"
29
30 #include <common/executor.h>
31 #include <common/lock.h>
32 #include <common/env.h>
33 #include <common/prec_timer.h>
34
35 #include <SFML/Graphics.hpp>
36
37 #include <boost/optional.hpp>
38 #include <boost/circular_buffer.hpp>
39 #include <boost/lexical_cast.hpp>
40
41 #include <tbb/concurrent_unordered_map.h>
42 #include <tbb/atomic.h>
43 #include <tbb/spin_mutex.h>
44
45 #include <GL/glew.h>
46
47 #include <numeric>
48 #include <tuple>
49 #include <memory>
50
51 #include <Windows.h>
52
53 namespace caspar { namespace core { namespace diagnostics { namespace osd {
54
55 static const int PREFERRED_VERTICAL_GRAPHS = 8;
56 static const int RENDERING_WIDTH = 750;
57 static const int RENDERING_HEIGHT = RENDERING_WIDTH / PREFERRED_VERTICAL_GRAPHS;
58
59 sf::Color get_sfml_color(int color)
60 {
61         auto c = caspar::diagnostics::color(color);
62
63         return {
64                 (color >> 24) & 255,
65                 (color >> 16) & 255,
66                 (color >> 8) & 255,
67                 (color >> 0) & 255
68         };
69 }
70
71 sf::Font& get_default_font()
72 {
73         static sf::Font DEFAULT_FONT = []()
74         {
75                 sf::Font font;
76                 if (!font.loadFromFile("LiberationSans-Regular.ttf"))
77                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("LiberationSans-Regular.ttf not found"));
78                 return font;
79         }();
80
81         return DEFAULT_FONT;
82 }
83
84 struct drawable : public sf::Drawable, public sf::Transformable
85 {
86         virtual ~drawable(){}
87         virtual void render(sf::RenderTarget& target, sf::RenderStates states) = 0;
88         virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const override
89         {
90                 states.transform *= getTransform();
91                 const_cast<drawable*>(this)->render(target, states);
92         }
93 };
94
95 class context : public drawable
96 {       
97         std::unique_ptr<sf::RenderWindow>       window_;
98         sf::View                                                        view_;
99         
100         std::list<std::weak_ptr<drawable>>      drawables_;
101         int64_t                                                         refresh_rate_millis_            = 16;
102         boost::timer                                            display_time_;
103         bool                                                            calculate_view_;
104         int                                                                     scroll_position_                        = 0;
105         bool                                                            dragging_                                       = false;
106         int                                                                     last_mouse_y_;
107
108         executor                                                        executor_                                       = L"diagnostics";
109 public:                                 
110
111         static void register_drawable(const std::shared_ptr<drawable>& drawable)
112         {
113                 if(!drawable)
114                         return;
115
116                 get_instance()->executor_.begin_invoke([=]
117                 {
118                         get_instance()->do_register_drawable(drawable);
119                 }, task_priority::high_priority);
120         }
121
122         static void show(bool value)
123         {
124                 get_instance()->executor_.begin_invoke([=]
125                 {       
126                         get_instance()->do_show(value);
127                 }, task_priority::high_priority);
128         }
129         
130         static void shutdown()
131         {
132                 get_instance().reset();
133         }
134 private:
135         context()
136         {
137                 executor_.begin_invoke([=]
138                 {                       
139                         SetThreadPriority(GetCurrentThread(), BELOW_NORMAL_PRIORITY_CLASS);
140                 });
141         }
142
143         void do_show(bool value)
144         {
145                 if(value)
146                 {
147                         if(!window_)
148                         {
149                                 window_.reset(new sf::RenderWindow(sf::VideoMode(RENDERING_WIDTH, RENDERING_WIDTH), "CasparCG Diagnostics"));
150                                 window_->setPosition(sf::Vector2i(0, 0));
151                                 window_->setActive();
152                                 window_->setVerticalSyncEnabled(true);
153                                 calculate_view_ = true;
154                                 glEnable(GL_BLEND);
155                                 glEnable(GL_LINE_SMOOTH);
156                                 glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
157                                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
158
159                                 tick();
160                         }
161                 }
162                 else
163                         window_.reset();
164         }
165
166         void tick()
167         {
168                 if(!window_)
169                         return;
170
171                 sf::Event e;
172                 while (window_->pollEvent(e))
173                 {
174                         switch (e.type)
175                         {
176                         case sf::Event::Closed:
177                                 window_.reset();
178                                 return;
179                         case sf::Event::Resized:
180                                 calculate_view_ = true;
181                                 break;
182                         case sf::Event::MouseButtonPressed:
183                                 dragging_ = true;
184                                 last_mouse_y_ = e.mouseButton.y;
185                                 break;
186                         case sf::Event::MouseButtonReleased:
187                                 dragging_ = false;
188                                 break;
189                         case sf::Event::MouseMoved:
190                                 if (dragging_)
191                                 {
192                                         auto delta_y = e.mouseMove.y - last_mouse_y_;
193                                         scroll_position_ += delta_y;
194                                         last_mouse_y_ = e.mouseMove.y;
195                                         calculate_view_ = true;
196                                 }
197
198                                 break;
199                         case sf::Event::MouseWheelMoved:
200                                 scroll_position_ += e.mouseWheel.delta * 15;
201                                 calculate_view_ = true;
202                                 break;
203                         }
204                 }
205
206                 window_->clear();
207
208                 if (calculate_view_)
209                 {
210                         view_.setViewport(sf::FloatRect(0, 0, 1.0, 1.0));
211                         view_.setSize(RENDERING_WIDTH, window_->getSize().y);
212                         view_.setCenter(RENDERING_WIDTH / 2, window_->getSize().y / 2 - scroll_position_);
213                         window_->setView(view_);
214                         calculate_view_ = false;
215                 }
216
217                 window_->draw(*this);
218
219                 static const auto THRESHOLD = 1;
220                 int64_t since_last_refresh = display_time_.elapsed() * 1000;
221                 int64_t until_next_refresh = refresh_rate_millis_ - since_last_refresh;
222                 int64_t sleep_for = until_next_refresh - THRESHOLD;
223
224                 if (sleep_for > 0)
225                 {
226                         prec_timer timer;
227                         timer.tick_millis(0);
228                         timer.tick_millis(sleep_for);
229                 }
230
231                 window_->display();
232                 display_time_.restart();
233                 executor_.begin_invoke([this]{tick();});
234         }
235
236         void render(sf::RenderTarget& target, sf::RenderStates states)
237         {
238                 int n = 0;
239
240                 for (auto it = drawables_.begin(); it != drawables_.end(); ++n)
241                 {
242                         auto drawable = it->lock();
243                         if (drawable)
244                         {
245                                 float target_y = n * RENDERING_HEIGHT;
246                                 drawable->setPosition(0.0f, target_y);                  
247                                 target.draw(*drawable, states);
248                                 ++it;           
249                         }
250                         else    
251                                 it = drawables_.erase(it);
252                 }
253         }       
254         
255         void do_register_drawable(const std::shared_ptr<drawable>& drawable)
256         {
257                 drawables_.push_back(drawable);
258                 auto it = drawables_.begin();
259                 while(it != drawables_.end())
260                 {
261                         if(it->lock())
262                                 ++it;
263                         else    
264                                 it = drawables_.erase(it);                      
265                 }
266         }
267         
268         static std::unique_ptr<context>& get_instance()
269         {
270                 static auto impl = std::unique_ptr<context>(new context);
271                 return impl;
272         }
273 };
274
275 class line : public drawable
276 {
277         size_t                                                                                                          res_;
278         boost::circular_buffer<sf::Vertex>                                                      line_data_      { res_ };
279         boost::circular_buffer<boost::optional<sf::VertexArray>>        line_tags_      { res_ };
280
281         tbb::atomic<float>                                                                                      tick_data_;
282         tbb::atomic<bool>                                                                                       tick_tag_;
283         tbb::atomic<int>                                                                                        color_;
284
285         double                                                                                                          x_delta_        = 1.0 / (res_ - 1);
286         //double                                                                                                                x_pos_          = 1.0;
287 public:
288         line(size_t res = 750)
289                 : res_(res)
290         {
291                 tick_data_      = -1.0f;
292                 color_          = 0xFFFFFFFF;
293                 tick_tag_       = false;
294         }
295         
296         void set_value(float value)
297         {
298                 tick_data_ = value;
299         }
300         
301         void set_tag()
302         {
303                 tick_tag_ = true;
304         }
305                 
306         void set_color(int color)
307         {
308                 color_ = color;
309         }
310
311         int get_color()
312         {
313                 return color_;
314         }
315                 
316         void render(sf::RenderTarget& target, sf::RenderStates states)
317         {
318                 /*states.transform.translate(x_pos_, 0.f);
319
320                 if (line_data_.size() == res_)
321                         x_pos_ = -get_insertion_xcoord() + 1.0 - x_delta_; // Otherwise the graph will drift because of floating point precision
322                 else
323                         x_pos_ -= x_delta_;*/
324
325                 for (auto& vertex : line_data_)
326                         vertex.position.x -= x_delta_;
327
328                 auto color = get_sfml_color(color_);
329                 color.a = 255 * 0.8;
330                 line_data_.push_back(sf::Vertex(sf::Vector2f(get_insertion_xcoord(), std::max(0.05, std::min(0.95, (1.0f - tick_data_) * 0.8 + 0.1f))), color));
331
332                 if (tick_tag_)
333                 {
334                         sf::VertexArray vertical_dash(sf::LinesStrip);
335                         vertical_dash.append(sf::Vertex(sf::Vector2f(get_insertion_xcoord() - x_delta_, 0.f), color));
336                         vertical_dash.append(sf::Vertex(sf::Vector2f(get_insertion_xcoord() - x_delta_, 1.f), color));
337                         line_tags_.push_back(vertical_dash);
338                 }
339                 else
340                         line_tags_.push_back(boost::none);
341
342                 tick_tag_ = false;
343
344                 if (tick_data_ > -0.5)
345                 {
346                         auto array_one = line_data_.array_one();
347                         auto array_two = line_data_.array_two();
348                         // since boost::circular_buffer guarantees two contigous views of the buffer we can provide raw access to SFML, which can use glDrawArrays.
349                         target.draw(array_one.first, static_cast<unsigned int>(array_one.second), sf::LinesStrip, states);
350                         target.draw(array_two.first, static_cast<unsigned int>(array_two.second), sf::LinesStrip, states);
351
352                         if (array_one.second > 0 && array_two.second > 0)
353                         {
354                                 // Connect the gap between the arrays
355                                 sf::VertexArray connecting_line(sf::LinesStrip);
356                                 connecting_line.append(*(array_one.first + array_one.second - 1));
357                                 connecting_line.append(*(array_two.first));
358                                 target.draw(connecting_line, states);
359                         }
360                 }
361                 else
362                 {
363                         glEnable(GL_LINE_STIPPLE);
364                         glLineStipple(3, 0xAAAA);
365
366                         for (size_t n = 0; n < line_tags_.size(); ++n)
367                         {
368                                 if (line_tags_[n])
369                                 {
370                                         target.draw(*line_tags_[n], states);
371                                 }
372                         }
373
374                         glDisable(GL_LINE_STIPPLE);
375                 }
376         }
377 private:
378         double get_insertion_xcoord() const
379         {
380                 return line_data_.empty() ? 1.0 : line_data_.back().position.x + x_delta_;
381         }
382 };
383
384 struct graph : public drawable, public caspar::diagnostics::spi::graph_sink, public std::enable_shared_from_this<graph>
385 {
386         call_context                                                                            context_        = call_context::for_thread();
387         tbb::concurrent_unordered_map<std::string, line>        lines_;
388
389         tbb::spin_mutex                                                                         mutex_;
390         std::wstring                                                                            text_;
391         bool                                                                                            auto_reset_     = false;
392
393         graph()
394         {
395         }
396
397         void activate() override
398         {
399                 context::register_drawable(shared_from_this());
400         }
401                 
402         void set_text(const std::wstring& value) override
403         {
404                 auto temp = value;
405                 lock(mutex_, [&]
406                 {
407                         text_ = std::move(temp);
408                 });
409         }
410
411         void set_value(const std::string& name, double value) override
412         {
413                 lines_[name].set_value(value);
414         }
415
416         void set_tag(const std::string& name) override
417         {
418                 lines_[name].set_tag();
419         }
420
421         void set_color(const std::string& name, int color) override
422         {
423                 lines_[name].set_color(color);
424         }
425
426         void auto_reset() override
427         {
428                 lock(mutex_, [this]
429                 {
430                         auto_reset_ = true;
431                 });
432         }
433                 
434 private:
435         void render(sf::RenderTarget& target, sf::RenderStates states) override
436         {
437                 const size_t text_size = 15;
438                 const size_t text_margin = 2;
439                 const size_t text_offset = (text_size+text_margin*2)*2;
440
441                 std::wstring text_str;
442                 bool auto_reset;
443
444                 {
445                         tbb::spin_mutex::scoped_lock lock(mutex_);
446                         text_str = text_;
447                         auto_reset = auto_reset_;
448                 }
449
450                 sf::Text text(text_str.c_str(), get_default_font(), text_size);
451                 text.setStyle(sf::Text::Italic);
452                 text.move(text_margin, text_margin);
453                 
454                 target.draw(text, states);
455
456                 if (context_.video_channel != -1)
457                 {
458                         auto ctx_str = boost::lexical_cast<std::string>(context_.video_channel);
459
460                         if (context_.layer != -1)
461                                 ctx_str += "-" + boost::lexical_cast<std::string>(context_.layer);
462
463                         sf::Text context_text(ctx_str, get_default_font(), text_size);
464                         context_text.setStyle(sf::Text::Italic);
465                         context_text.move(RENDERING_WIDTH - text_margin - 5 - context_text.getLocalBounds().width, text_margin);
466
467                         target.draw(context_text, states);
468                 }
469
470                 float x_offset = text_margin;
471
472                 for(auto it = lines_.begin(); it != lines_.end(); ++it)
473                 {
474                         sf::Text line_text(it->first, get_default_font(), text_size);
475                         line_text.setPosition(x_offset, text_margin+text_offset/2);
476                         line_text.setColor(get_sfml_color(it->second.get_color()));
477                         target.draw(line_text, states);
478                         x_offset += line_text.getLocalBounds().width + text_margin * 2;
479                 }
480
481                 static const auto rect = []()
482                 {
483                         sf::RectangleShape r(sf::Vector2f(RENDERING_WIDTH, RENDERING_HEIGHT - 2));
484                         r.setFillColor(sf::Color(255, 255, 255, 51));
485                         r.setOutlineThickness(0.00f);
486                         r.move(0, 1);
487                         return r;
488                 }();
489                 target.draw(rect, states);
490
491                 states.transform
492                         .translate(0, text_offset)
493                         .scale(RENDERING_WIDTH, RENDERING_HEIGHT * (static_cast<float>(RENDERING_HEIGHT - text_offset) / static_cast<float>(RENDERING_HEIGHT)));
494                 
495                 static const sf::Color guide_color(255, 255, 255, 127);
496                 static const sf::VertexArray middle_guide = []()
497                 {
498                         sf::VertexArray result(sf::LinesStrip);
499                         result.append(sf::Vertex(sf::Vector2f(0.0f, 0.5f), guide_color));
500                         result.append(sf::Vertex(sf::Vector2f(1.0f, 0.5f), guide_color));
501                         return result;
502                 }();
503                 static const sf::VertexArray bottom_guide = []()
504                 {
505                         sf::VertexArray result(sf::LinesStrip);
506                         result.append(sf::Vertex(sf::Vector2f(0.0f, 0.9f), guide_color));
507                         result.append(sf::Vertex(sf::Vector2f(1.0f, 0.9f), guide_color));
508                         return result;
509                 }();
510                 static const sf::VertexArray top_guide = []()
511                 {
512                         sf::VertexArray result(sf::LinesStrip);
513                         result.append(sf::Vertex(sf::Vector2f(0.0f, 0.1f), guide_color));
514                         result.append(sf::Vertex(sf::Vector2f(1.0f, 0.1f), guide_color));
515                         return result;
516                 }();
517
518                 glEnable(GL_LINE_STIPPLE);
519                 glLineStipple(3, 0xAAAA);
520                 
521                 target.draw(middle_guide, states);
522                 target.draw(bottom_guide, states);
523                 target.draw(top_guide, states);
524                 
525                 glDisable(GL_LINE_STIPPLE);
526
527                 for (auto it = lines_.begin(); it != lines_.end(); ++it)                
528                 {
529                         target.draw(it->second, states);
530                         if(auto_reset)
531                                 it->second.set_value(0.0f);
532                 }
533         }
534 };
535
536 void register_sink()
537 {
538         caspar::diagnostics::spi::register_sink_factory([]
539         {
540                 return spl::make_shared<graph>();
541         });
542 }
543
544 void show_graphs(bool value)
545 {
546         context::show(value);
547 }
548
549 void shutdown()
550 {
551         context::shutdown();
552 }
553
554 }}}}