]> git.sesse.net Git - casparcg/blob - core/producer/text/text_producer.cpp
Throw user_error exception for errors that are caused by users of the system instead...
[casparcg] / core / producer / text / text_producer.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: Niklas P Andersson, niklas.p.andersson@svt.se
20 */
21
22 #include "../../StdAfx.h"
23
24 #include "text_producer.h"
25
26 #include <core/producer/frame_producer.h>
27 #include <core/producer/color/color_producer.h>
28 #include <core/producer/variable.h>
29 #include <core/frame/geometry.h>
30 #include <core/frame/frame.h>
31 #include <core/frame/draw_frame.h>
32 #include <core/frame/frame_factory.h>
33 #include <core/frame/pixel_format.h>
34 #include <core/frame/audio_channel_layout.h>
35 #include <core/monitor/monitor.h>
36 #include <core/consumer/frame_consumer.h>
37 #include <core/module_dependencies.h>
38 #include <core/help/help_repository.h>
39 #include <core/help/help_sink.h>
40
41 #include <modules/image/consumer/image_consumer.h>
42
43 #include <common/except.h>
44 #include <common/array.h>
45 #include <common/env.h>
46 #include <common/future.h>
47 #include <common/param.h>
48 #include <memory>
49
50 #include <boost/algorithm/string.hpp>
51 #include <boost/property_tree/ptree.hpp>
52 #include <boost/filesystem.hpp>
53
54 #include <ft2build.h>
55 #include FT_FREETYPE_H
56 #include FT_GLYPH_H
57
58 #include "utils/texture_atlas.h"
59 #include "utils/texture_font.h"
60 #include "utils/freetype_library.h"
61
62 class font_comparer {
63         const std::wstring& lhs;
64 public:
65         explicit font_comparer(const std::wstring& p) : lhs(p) {}
66         bool operator()(const std::pair<std::wstring, std::wstring>&rhs) { return boost::iequals(lhs, rhs.first); }
67 };
68
69
70 namespace caspar { namespace core { namespace text {
71
72 using namespace boost::filesystem;
73
74 std::map<std::wstring, std::wstring> enumerate_fonts()
75 {
76         std::map<std::wstring, std::wstring> result;
77
78         for(auto iter = directory_iterator(env::font_folder()), end = directory_iterator(); iter != end; ++iter)
79         {
80                 auto file = (*iter);
81                 if(is_regular_file(file.path()))
82                 {
83                         auto face = get_new_face(u8(file.path().native()));
84                         const char* fontname = FT_Get_Postscript_Name(face.get());      //this doesn't work for .fon fonts. Ignoring those for now
85                         if(fontname != nullptr)
86                         {
87                                 std::string fontname_str(fontname);
88                                 result.insert(std::make_pair(u16(fontname_str), u16(file.path().native())));
89                         }
90                 }
91         }
92
93         return result;
94 }
95
96 std::vector<std::pair<std::wstring, std::wstring>> list_fonts()
97 {
98         auto fonts = enumerate_fonts();
99         return std::vector<std::pair<std::wstring, std::wstring>>(fonts.begin(), fonts.end());
100 }
101
102 void describe_text_producer(help_sink&, const help_repository&);
103 spl::shared_ptr<frame_producer> create_text_producer(const frame_producer_dependencies&, const std::vector<std::wstring>&);
104
105 void init(module_dependencies dependencies)
106 {
107         dependencies.producer_registry->register_producer_factory(L"Text Producer", create_text_producer, describe_text_producer);
108 }
109
110 text_info& find_font_file(text_info& info)
111 {
112         auto& font_name = info.font;
113         auto fonts = enumerate_fonts();
114         auto it = std::find_if(fonts.begin(), fonts.end(), font_comparer(font_name));
115         info.font_file = (it != fonts.end()) ? (*it).second : L"";
116         return info;
117 }
118
119 } // namespace text
120         
121
122 struct text_producer::impl
123 {
124         monitor::subject                                                monitor_subject_;
125         spl::shared_ptr<core::frame_factory>    frame_factory_;
126         int                                                                             x_;
127         int                                                                             y_;
128         int                                                                             parent_width_;
129         int                                                                             parent_height_;
130         bool                                                                    standalone_;
131         constraints                                                             constraints_                            { parent_width_, parent_height_ };
132         variable_impl<std::wstring>                             text_;
133         std::shared_ptr<void>                                   text_subscription_;
134         variable_impl<double>                                   tracking_;
135         std::shared_ptr<void>                                   tracking_subscription_;
136         variable_impl<double>                                   current_bearing_y_;
137         variable_impl<double>                                   current_protrude_under_y_;
138         draw_frame                                                              frame_;
139         text::texture_atlas                                             atlas_                                          { 512, 512, 4 };
140         text::texture_font                                              font_;
141         bool                                                                    dirty_                                          = false;
142
143 public:
144         explicit impl(const spl::shared_ptr<frame_factory>& frame_factory, int x, int y, const std::wstring& str, text::text_info& text_info, long parent_width, long parent_height, bool standalone) 
145                 : frame_factory_(frame_factory)
146                 , x_(x), y_(y)
147                 , parent_width_(parent_width), parent_height_(parent_height)
148                 , standalone_(standalone)
149                 , font_(atlas_, text::find_font_file(text_info), !standalone)
150         {
151                 //TODO: examine str to determine which unicode_blocks to load
152                 font_.load_glyphs(text::unicode_block::Basic_Latin, text_info.color);
153                 font_.load_glyphs(text::unicode_block::Latin_1_Supplement, text_info.color);
154                 font_.load_glyphs(text::unicode_block::Latin_Extended_A, text_info.color);
155
156                 tracking_.value().set(text_info.tracking);
157                 text_subscription_ = text_.value().on_change([this]()
158                 {
159                         dirty_ = true;
160                 });
161                 tracking_subscription_ = tracking_.value().on_change([this]()
162                 {
163                         dirty_ = true;
164                 });
165
166                 constraints_.height.depend_on(text());
167                 constraints_.width.depend_on(text());
168                 current_bearing_y_.as<double>().depend_on(text());
169                 current_protrude_under_y_.as<double>().depend_on(text());
170
171                 //generate frame
172                 text_.value().set(str);
173
174                 CASPAR_LOG(info) << print() << L" Initialized";
175         }
176
177         void generate_frame()
178         {
179                 core::pixel_format_desc pfd(core::pixel_format::bgra);
180                 pfd.planes.push_back(core::pixel_format_desc::plane(static_cast<int>(atlas_.width()), static_cast<int>(atlas_.height()), static_cast<int>(atlas_.depth())));
181
182                 text::string_metrics metrics;
183                 font_.set_tracking(static_cast<int>(tracking_.value().get()));
184                 auto vertex_stream = font_.create_vertex_stream(text_.value().get(), x_, y_, parent_width_, parent_height_, &metrics);
185                 auto frame = frame_factory_->create_frame(vertex_stream.data(), pfd, core::audio_channel_layout::invalid());
186                 memcpy(frame.image_data().data(), atlas_.data(), frame.image_data().size());
187                 frame.set_geometry(frame_geometry(frame_geometry::geometry_type::quad_list, std::move(vertex_stream)));
188
189                 this->constraints_.width.set(metrics.width);
190                 this->constraints_.height.set(metrics.height);
191                 current_bearing_y_.value().set(metrics.bearingY);
192                 current_protrude_under_y_.value().set(metrics.protrudeUnderY);
193                 frame_ = core::draw_frame(std::move(frame));
194         }
195
196         text::string_metrics measure_string(const std::wstring& str)
197         {
198                 return font_.measure_string(str);
199         }
200
201         // frame_producer
202                         
203         draw_frame receive_impl()
204         {
205                 if (dirty_)
206                 {
207                         generate_frame();
208                         dirty_ = false;
209                 }
210
211                 return frame_;
212         }
213
214         std::future<std::wstring> call(const std::vector<std::wstring>& param)
215         {
216                 std::wstring result;
217                 text_.value().set(param.empty() ? L"" : param[0]);
218
219                 return make_ready_future(std::move(result));
220         }
221
222         variable& get_variable(const std::wstring& name)
223         {
224                 if (name == L"text")
225                         return text_;
226                 else if (name == L"current_bearing_y")
227                         return current_bearing_y_;
228                 else if (name == L"current_protrude_under_y")
229                         return current_protrude_under_y_;
230                 else if (name == L"tracking")
231                         return tracking_;
232
233                 CASPAR_THROW_EXCEPTION(user_error() << msg_info(L"text_producer does not have a variable called " + name));
234         }
235
236         const std::vector<std::wstring>& get_variables() const
237         {
238                 static const std::vector<std::wstring> vars = {
239                         L"text",
240                         L"tracking",
241                         L"current_bearing_y",
242                         L"current_protrude_under_y"
243                 };
244
245                 return vars;
246         }
247
248         constraints& pixel_constraints()
249         {
250                 return constraints_;
251         }
252
253         binding<std::wstring>& text()
254         {
255                 return text_.value();
256         }
257
258         binding<double>& tracking()
259         {
260                 return tracking_.value();
261         }
262
263         const binding<double>& current_bearing_y() const
264         {
265                 return current_bearing_y_.value();
266         }
267
268         const binding<double>& current_protrude_under_y() const
269         {
270                 return current_protrude_under_y_.value();
271         }
272         
273         std::wstring print() const
274         {
275                 return L"text[" + text_.value().get() + L"]";
276         }
277
278         std::wstring name() const
279         {
280                 return L"text";
281         }
282         
283         boost::property_tree::wptree info() const
284         {
285                 boost::property_tree::wptree info;
286                 info.add(L"type", L"text");
287                 info.add(L"text", text_.value().get());
288                 info.add(L"font", font_.get_name());
289                 info.add(L"size", font_.get_size());
290                 return info;
291         }
292 };
293
294 text_producer::text_producer(const spl::shared_ptr<frame_factory>& frame_factory, int x, int y, const std::wstring& str, text::text_info& text_info, long parent_width, long parent_height, bool standalone)
295         : impl_(new impl(frame_factory, x, y, str, text_info, parent_width, parent_height, standalone))
296 {}
297
298 draw_frame text_producer::receive_impl() { return impl_->receive_impl(); }
299 std::future<std::wstring> text_producer::call(const std::vector<std::wstring>& param) { return impl_->call(param); }
300 variable& text_producer::get_variable(const std::wstring& name) { return impl_->get_variable(name); }
301 const std::vector<std::wstring>& text_producer::get_variables() const { return impl_->get_variables(); }
302 text::string_metrics text_producer::measure_string(const std::wstring& str) { return impl_->measure_string(str); }
303
304 constraints& text_producer::pixel_constraints() { return impl_->pixel_constraints(); }
305 std::wstring text_producer::print() const { return impl_->print(); }
306 std::wstring text_producer::name() const { return impl_->name(); }
307 boost::property_tree::wptree text_producer::info() const { return impl_->info(); }
308 monitor::subject& text_producer::monitor_output() { return impl_->monitor_subject_; }
309 binding<std::wstring>& text_producer::text() { return impl_->text(); }
310 binding<double>& text_producer::tracking() { return impl_->tracking(); }
311 const binding<double>& text_producer::current_bearing_y() const { return impl_->current_bearing_y(); }
312 const binding<double>& text_producer::current_protrude_under_y() const { return impl_->current_protrude_under_y(); }
313
314 spl::shared_ptr<text_producer> text_producer::create(const spl::shared_ptr<frame_factory>& frame_factory, int x, int y, const std::wstring& str, text::text_info& text_info, long parent_width, long parent_height, bool standalone)
315 {
316         return spl::make_shared<text_producer>(frame_factory, x, y, str, text_info, parent_width, parent_height, standalone);
317 }
318 namespace text {
319
320 void describe_text_producer(help_sink& sink, const help_repository& repo)
321 {
322         sink.short_description(L"A producer for rendering dynamic text.");
323         sink.syntax(L"[TEXT] [text:string] {[x:int] [y:int]} {FONT [font:string]|verdana} {SIZE [size:float]|30.0} {COLOR [color:string]|#ffffffff} {STANDALONE [standalone:0,1]|0}");
324         sink.para()
325                 ->text(L"Renders dynamic text using fonts found under the ")->code(L"fonts")->text(L" folder. ")
326                 ->text(L"Parameters:");
327         sink.definitions()
328                 ->item(L"text", L"The text to display. Can be changed later via CALL as well.")
329                 ->item(L"x", L"The x position of the text.")
330                 ->item(L"y", L"The y position of the text.")
331                 ->item(L"font", L"The name of the font (not the actual filename, but the font name).")
332                 ->item(L"size", L"The point size.")
333                 ->item(L"color", L"The color as an ARGB hex value.")
334                 ->item(L"standalone", L"Whether to normalize coordinates or not.");
335         sink.para()->text(L"Examples:");
336         sink.example(L">> PLAY 1-10 [TEXT] \"John Doe\" 0 0 FONT ArialMT SIZE 30 COLOR #1b698d STANDALONE 1");
337         sink.example(L">> CALL 1-10 \"Jane Doe\"", L"for modifying the text while playing.");
338         sink.para()->text(L"See ")->see(L"FLS")->text(L" for listing the available fonts.");
339 }
340
341 spl::shared_ptr<frame_producer> create_text_producer(const frame_producer_dependencies& dependencies, const std::vector<std::wstring>& params)
342 {
343         if(params.size() < 2 || !boost::iequals(params.at(0), L"[text]"))
344                 return core::frame_producer::empty();
345
346         int x = 0, y = 0;
347         if(params.size() >= 4)
348         {
349                 x = boost::lexical_cast<int>(params.at(2));
350                 y = boost::lexical_cast<int>(params.at(3));
351         }
352
353         text::text_info text_info;
354         text_info.font = get_param(L"FONT", params, L"verdana");
355         text_info.size = get_param(L"SIZE", params, 30.0); // 30.0f does not seem to work to get as float directly
356         
357         std::wstring col_str = get_param(L"color", params, L"#ffffffff");
358         uint32_t col_val = 0xffffffff;
359         try_get_color(col_str, col_val);
360         text_info.color = core::text::color<double>(col_val);
361
362         bool standalone = get_param(L"STANDALONE", params, false);
363
364         return text_producer::create(
365                         dependencies.frame_factory,
366                         x, y,
367                         params.at(1),
368                         text_info,
369                         dependencies.format_desc.width, dependencies.format_desc.height,
370                         standalone);
371 }
372
373 }}}