]> git.sesse.net Git - casparcg/blob - shell/server.cpp
Merge pull request #404 from krzyc/patch-1
[casparcg] / shell / server.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 "server.h"
25 #include "included_modules.h"
26 #include "default_audio_config.h"
27
28 #include <accelerator/accelerator.h>
29
30 #include <common/env.h>
31 #include <common/except.h>
32 #include <common/utf.h>
33 #include <common/memory.h>
34 #include <common/polling_filesystem_monitor.h>
35 #include <common/ptree.h>
36
37 #include <core/video_channel.h>
38 #include <core/video_format.h>
39 #include <core/frame/audio_channel_layout.h>
40 #include <core/producer/stage.h>
41 #include <core/producer/frame_producer.h>
42 #include <core/producer/scene/scene_producer.h>
43 #include <core/producer/scene/xml_scene_producer.h>
44 #include <core/producer/text/text_producer.h>
45 #include <core/consumer/output.h>
46 #include <core/mixer/mixer.h>
47 #include <core/mixer/image/image_mixer.h>
48 #include <core/thumbnail_generator.h>
49 #include <core/producer/media_info/media_info.h>
50 #include <core/producer/media_info/media_info_repository.h>
51 #include <core/producer/media_info/in_memory_media_info_repository.h>
52 #include <core/producer/cg_proxy.h>
53 #include <core/diagnostics/subject_diagnostics.h>
54 #include <core/diagnostics/call_context.h>
55 #include <core/diagnostics/osd_graph.h>
56 #include <core/diagnostics/graph_to_log_sink.h>
57 #include <core/system_info_provider.h>
58 #include <core/help/help_repository.h>
59
60 #include <modules/image/consumer/image_consumer.h>
61
62 #include <protocol/amcp/AMCPProtocolStrategy.h>
63 #include <protocol/amcp/amcp_command_repository.h>
64 #include <protocol/amcp/AMCPCommandsImpl.h>
65 #include <protocol/cii/CIIProtocolStrategy.h>
66 #include <protocol/clk/CLKProtocolStrategy.h>
67 #include <protocol/util/AsyncEventServer.h>
68 #include <protocol/util/strategy_adapters.h>
69 #include <protocol/osc/client.h>
70 #include <protocol/log/tcp_logger_protocol_strategy.h>
71
72 #include <boost/algorithm/string.hpp>
73 #include <boost/thread.hpp>
74 #include <boost/lexical_cast.hpp>
75 #include <boost/property_tree/ptree.hpp>
76 #include <boost/property_tree/xml_parser.hpp>
77 #include <boost/asio.hpp>
78
79 #include <tbb/atomic.h>
80
81 #include <future>
82
83 namespace caspar {
84
85 using namespace core;
86 using namespace protocol;
87
88 std::shared_ptr<boost::asio::io_service> create_running_io_service()
89 {
90         auto service = std::make_shared<boost::asio::io_service>();
91         // To keep the io_service::run() running although no pending async
92         // operations are posted.
93         auto work = std::make_shared<boost::asio::io_service::work>(*service);
94         auto weak_work = std::weak_ptr<boost::asio::io_service::work>(work);
95         auto thread = std::make_shared<boost::thread>([service, weak_work]
96         {
97                 ensure_gpf_handler_installed_for_thread("asio-thread");
98
99                 while (auto strong = weak_work.lock())
100                 {
101                         try
102                         {
103                                 service->run();
104                         }
105                         catch (...)
106                         {
107                                 CASPAR_LOG_CURRENT_EXCEPTION();
108                         }
109                 }
110         });
111
112         return std::shared_ptr<boost::asio::io_service>(
113                         service.get(),
114                         [service, work, thread](void*) mutable
115                         {
116                                 work.reset();
117                                 service->stop();
118                                 if (thread->get_id() != boost::this_thread::get_id())
119                                         thread->join();
120                                 else
121                                         thread->detach();
122                         });
123 }
124
125 struct server::impl : boost::noncopyable
126 {
127         std::shared_ptr<boost::asio::io_service>                        io_service_                                             = create_running_io_service();
128         spl::shared_ptr<monitor::subject>                                       monitor_subject_;
129         spl::shared_ptr<monitor::subject>                                       diag_subject_                                   = core::diagnostics::get_or_create_subject();
130         accelerator::accelerator                                                        accelerator_;
131         spl::shared_ptr<help_repository>                                        help_repo_;
132         std::shared_ptr<amcp::amcp_command_repository>          amcp_command_repo_;
133         std::vector<spl::shared_ptr<IO::AsyncEventServer>>      async_servers_;
134         std::shared_ptr<IO::AsyncEventServer>                           primary_amcp_server_;
135         std::shared_ptr<osc::client>                                            osc_client_                                             = std::make_shared<osc::client>(io_service_);
136         std::vector<std::shared_ptr<void>>                                      predefined_osc_subscriptions_;
137         std::vector<spl::shared_ptr<video_channel>>                     channels_;
138         spl::shared_ptr<media_info_repository>                          media_info_repo_;
139         boost::thread                                                                           initial_media_info_thread_;
140         spl::shared_ptr<system_info_provider_repository>        system_info_provider_repo_;
141         spl::shared_ptr<core::cg_producer_registry>                     cg_registry_;
142         spl::shared_ptr<core::frame_producer_registry>          producer_registry_;
143         spl::shared_ptr<core::frame_consumer_registry>          consumer_registry_;
144         tbb::atomic<bool>                                                                       running_;
145         std::shared_ptr<thumbnail_generator>                            thumbnail_generator_;
146         std::promise<bool>&                                                                     shutdown_server_now_;
147
148         explicit impl(std::promise<bool>& shutdown_server_now)          
149                 : accelerator_(env::properties().get(L"configuration.accelerator", L"auto"))
150                 , media_info_repo_(create_in_memory_media_info_repository())
151                 , producer_registry_(spl::make_shared<core::frame_producer_registry>(help_repo_))
152                 , consumer_registry_(spl::make_shared<core::frame_consumer_registry>(help_repo_))
153                 , shutdown_server_now_(shutdown_server_now)
154         {
155                 running_ = false;
156                 core::diagnostics::register_graph_to_log_sink();
157                 caspar::core::diagnostics::osd::register_sink();
158                 diag_subject_->attach_parent(monitor_subject_);
159
160                 module_dependencies dependencies(
161                                 system_info_provider_repo_,
162                                 cg_registry_,
163                                 media_info_repo_,
164                                 producer_registry_,
165                                 consumer_registry_);
166
167                 initialize_modules(dependencies);
168                 core::text::init(dependencies);
169                 core::scene::init(dependencies);
170         }
171
172         void start()
173         {
174                 running_ = true;
175
176                 setup_audio_config(env::properties());
177                 CASPAR_LOG(info) << L"Initialized audio config.";
178
179                 setup_channels(env::properties());
180                 CASPAR_LOG(info) << L"Initialized channels.";
181
182                 setup_thumbnail_generation(env::properties());
183                 CASPAR_LOG(info) << L"Initialized thumbnail generator.";
184
185                 setup_controllers(env::properties());
186                 CASPAR_LOG(info) << L"Initialized controllers.";
187
188                 setup_osc(env::properties());
189                 CASPAR_LOG(info) << L"Initialized osc.";
190
191                 start_initial_media_info_scan();
192                 CASPAR_LOG(info) << L"Started initial media information retrieval.";
193         }
194
195         ~impl()
196         {
197                 if (running_)
198                 {
199                         running_ = false;
200                         initial_media_info_thread_.join();
201                 }
202
203                 std::weak_ptr<boost::asio::io_service> weak_io_service = io_service_;
204                 io_service_.reset();
205                 osc_client_.reset();
206                 thumbnail_generator_.reset();
207                 amcp_command_repo_.reset();
208                 primary_amcp_server_.reset();
209                 async_servers_.clear();
210                 destroy_producers_synchronously();
211                 destroy_consumers_synchronously();
212                 channels_.clear();
213                 
214                 while (weak_io_service.lock())
215                         boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
216
217                 uninitialize_modules();
218                 core::diagnostics::osd::shutdown();
219         }
220
221         void setup_audio_config(const boost::property_tree::wptree& pt)
222         {
223                 using boost::property_tree::wptree;
224
225                 auto default_config = get_default_audio_config();
226
227                 // Start with the defaults
228                 audio_channel_layout_repository::get_default()->register_all_layouts(default_config.get_child(L"audio.channel-layouts"));
229                 audio_mix_config_repository::get_default()->register_all_configs(default_config.get_child(L"audio.mix-configs"));
230
231                 // Merge with user configuration (adds to or overwrites the defaults)
232                 auto custom_channel_layouts     = pt.get_child_optional(L"configuration.audio.channel-layouts");
233                 auto custom_mix_configs         = pt.get_child_optional(L"configuration.audio.mix-configs");
234
235                 if (custom_channel_layouts)
236                 {
237                         CASPAR_SCOPED_CONTEXT_MSG("/configuration/audio/channel-layouts");
238                         audio_channel_layout_repository::get_default()->register_all_layouts(*custom_channel_layouts);
239                 }
240
241                 if (custom_mix_configs)
242                 {
243                         CASPAR_SCOPED_CONTEXT_MSG("/configuration/audio/mix-configs");
244                         audio_mix_config_repository::get_default()->register_all_configs(*custom_mix_configs);
245                 }
246         }
247
248         void setup_channels(const boost::property_tree::wptree& pt)
249         {   
250                 using boost::property_tree::wptree;
251                 for (auto& xml_channel : pt | witerate_children(L"configuration.channels") | welement_context_iteration)
252                 {
253                         ptree_verify_element_name(xml_channel, L"channel");
254
255                         auto format_desc_str = xml_channel.second.get(L"video-mode", L"PAL");
256                         auto format_desc = video_format_desc(format_desc_str);
257                         if(format_desc.format == video_format::invalid)
258                                 CASPAR_THROW_EXCEPTION(user_error() << msg_info(L"Invalid video-mode: " + format_desc_str));
259
260                         auto channel_layout_str = xml_channel.second.get(L"channel-layout", L"stereo");
261                         auto channel_layout = core::audio_channel_layout_repository::get_default()->get_layout(channel_layout_str);
262                         if (!channel_layout)
263                                 CASPAR_THROW_EXCEPTION(user_error() << msg_info(L"Unknown channel-layout: " + channel_layout_str));
264
265                         auto channel_id = static_cast<int>(channels_.size() + 1);
266                         auto channel = spl::make_shared<video_channel>(channel_id, format_desc, *channel_layout, accelerator_.create_image_mixer(channel_id));
267
268                         core::diagnostics::scoped_call_context save;
269                         core::diagnostics::call_context::for_thread().video_channel = channel->index();
270
271                         for (auto& xml_consumer : xml_channel.second | witerate_children(L"consumers") | welement_context_iteration)
272                         {
273                                 auto name = xml_consumer.first;
274
275                                 try
276                                 {
277                                         if (name != L"<xmlcomment>")
278                                                 channel->output().add(consumer_registry_->create_consumer(name, xml_consumer.second, &channel->stage()));
279                                 }
280                                 catch (const user_error& e)
281                                 {
282                                         CASPAR_LOG_CURRENT_EXCEPTION_AT_LEVEL(debug);
283                                         CASPAR_LOG(error) << get_message_and_context(e) << " Turn on log level debug for stacktrace.";
284                                 }
285                                 catch (...)
286                                 {
287                                         CASPAR_LOG_CURRENT_EXCEPTION();
288                                 }
289                         }               
290
291                     channel->monitor_output().attach_parent(monitor_subject_);
292                         channel->mixer().set_straight_alpha_output(xml_channel.second.get(L"straight-alpha-output", false));
293                         channels_.push_back(channel);
294                 }
295
296                 // Dummy diagnostics channel
297                 if (env::properties().get(L"configuration.channel-grid", false))
298                 {
299                         auto channel_id = static_cast<int>(channels_.size() + 1);
300                         channels_.push_back(spl::make_shared<video_channel>(
301                                         channel_id,
302                                         core::video_format_desc(core::video_format::x576p2500),
303                                         *core::audio_channel_layout_repository::get_default()->get_layout(L"stereo"),
304                                         accelerator_.create_image_mixer(channel_id)));
305                         channels_.back()->monitor_output().attach_parent(monitor_subject_);
306                 }
307         }
308
309         void setup_osc(const boost::property_tree::wptree& pt)
310         {               
311                 using boost::property_tree::wptree;
312                 using namespace boost::asio::ip;
313
314                 monitor_subject_->attach_parent(osc_client_->sink());
315                 
316                 auto default_port =
317                                 pt.get<unsigned short>(L"configuration.osc.default-port", 6250);
318                 auto predefined_clients =
319                                 pt.get_child_optional(L"configuration.osc.predefined-clients");
320
321                 if (predefined_clients)
322                 {
323                         for (auto& predefined_client : pt | witerate_children(L"configuration.osc.predefined-clients") | welement_context_iteration)
324                         {
325                                 ptree_verify_element_name(predefined_client, L"predefined-client");
326
327                                 const auto address =
328                                                 ptree_get<std::wstring>(predefined_client.second, L"address");
329                                 const auto port =
330                                                 ptree_get<unsigned short>(predefined_client.second, L"port");
331                                 predefined_osc_subscriptions_.push_back(
332                                                 osc_client_->get_subscription_token(udp::endpoint(
333                                                                 address_v4::from_string(u8(address)),
334                                                                 port)));
335                         }
336                 }
337
338                 if (primary_amcp_server_)
339                         primary_amcp_server_->add_client_lifecycle_object_factory(
340                                         [=] (const std::string& ipv4_address)
341                                                         -> std::pair<std::wstring, std::shared_ptr<void>>
342                                         {
343                                                 using namespace boost::asio::ip;
344
345                                                 return std::make_pair(
346                                                                 std::wstring(L"osc_subscribe"),
347                                                                 osc_client_->get_subscription_token(
348                                                                                 udp::endpoint(
349                                                                                                 address_v4::from_string(
350                                                                                                                 ipv4_address),
351                                                                                                 default_port)));
352                                         });
353         }
354
355         void setup_thumbnail_generation(const boost::property_tree::wptree& pt)
356         {
357                 if (!pt.get(L"configuration.thumbnails.generate-thumbnails", true))
358                         return;
359
360                 auto scan_interval_millis = pt.get(L"configuration.thumbnails.scan-interval-millis", 5000);
361
362                 polling_filesystem_monitor_factory monitor_factory(io_service_, scan_interval_millis);
363                 thumbnail_generator_.reset(new thumbnail_generator(
364                         monitor_factory, 
365                         env::media_folder(),
366                         env::thumbnails_folder(),
367                         pt.get(L"configuration.thumbnails.width", 256),
368                         pt.get(L"configuration.thumbnails.height", 144),
369                         core::video_format_desc(pt.get(L"configuration.thumbnails.video-mode", L"720p2500")),
370                         accelerator_.create_image_mixer(0),
371                         pt.get(L"configuration.thumbnails.generate-delay-millis", 2000),
372                         &image::write_cropped_png,
373                         media_info_repo_,
374                         producer_registry_,
375                         pt.get(L"configuration.thumbnails.mipmap", true)));
376         }
377                 
378         void setup_controllers(const boost::property_tree::wptree& pt)
379         {
380                 amcp_command_repo_ = spl::make_shared<amcp::amcp_command_repository>(
381                                 channels_,
382                                 thumbnail_generator_,
383                                 media_info_repo_,
384                                 system_info_provider_repo_,
385                                 cg_registry_,
386                                 help_repo_,
387                                 producer_registry_,
388                                 consumer_registry_,
389                                 accelerator_.get_ogl_device(),
390                                 shutdown_server_now_);
391                 amcp::register_commands(*amcp_command_repo_);
392
393                 using boost::property_tree::wptree;
394                 for (auto& xml_controller : pt | witerate_children(L"configuration.controllers") | welement_context_iteration)
395                 {
396                         auto name = xml_controller.first;
397                         auto protocol = ptree_get<std::wstring>(xml_controller.second, L"protocol");
398
399                         if(name == L"tcp")
400                         {                                       
401                                 auto port = ptree_get<unsigned int>(xml_controller.second, L"port");
402                                 auto asyncbootstrapper = spl::make_shared<IO::AsyncEventServer>(
403                                                 io_service_,
404                                                 create_protocol(protocol, L"TCP Port " + boost::lexical_cast<std::wstring>(port)),
405                                                 port);
406                                 async_servers_.push_back(asyncbootstrapper);
407
408                                 if (!primary_amcp_server_ && boost::iequals(protocol, L"AMCP"))
409                                         primary_amcp_server_ = asyncbootstrapper;
410                         }
411                         else
412                                 CASPAR_LOG(warning) << "Invalid controller: " << name;  
413                 }
414         }
415
416         IO::protocol_strategy_factory<char>::ptr create_protocol(const std::wstring& name, const std::wstring& port_description) const
417         {
418                 using namespace IO;
419
420                 if(boost::iequals(name, L"AMCP"))
421                         return wrap_legacy_protocol("\r\n", spl::make_shared<amcp::AMCPProtocolStrategy>(port_description, spl::make_shared_ptr(amcp_command_repo_)));
422                 else if(boost::iequals(name, L"CII"))
423                         return wrap_legacy_protocol("\r\n", spl::make_shared<cii::CIIProtocolStrategy>(channels_, cg_registry_, producer_registry_));
424                 else if(boost::iequals(name, L"CLOCK"))
425                         return spl::make_shared<to_unicode_adapter_factory>(
426                                         "ISO-8859-1",
427                                         spl::make_shared<CLK::clk_protocol_strategy_factory>(channels_, cg_registry_, producer_registry_));
428                 else if (boost::iequals(name, L"LOG"))
429                         return spl::make_shared<protocol::log::tcp_logger_protocol_strategy_factory>();
430
431                 CASPAR_THROW_EXCEPTION(user_error() << msg_info(L"Invalid protocol: " + name));
432         }
433
434         void start_initial_media_info_scan()
435         {
436                 initial_media_info_thread_ = boost::thread([this]
437                 {
438                         try
439                         {
440                                 ensure_gpf_handler_installed_for_thread("initial media scan");
441
442                                 for (boost::filesystem::wrecursive_directory_iterator iter(env::media_folder()), end; iter != end; ++iter)
443                                 {
444                                         if (running_)
445                                         {
446                                                 if (boost::filesystem::is_regular_file(iter->path()))
447                                                         media_info_repo_->get(iter->path().wstring());
448                                         }
449                                         else
450                                         {
451                                                 CASPAR_LOG(info) << L"Initial media information retrieval aborted.";
452                                                 return;
453                                         }
454                                 }
455
456                                 CASPAR_LOG(info) << L"Initial media information retrieval finished.";
457                         }
458                         catch (...)
459                         {
460                                 CASPAR_LOG_CURRENT_EXCEPTION();
461                         }
462                 });
463         }
464 };
465
466 server::server(std::promise<bool>& shutdown_server_now) : impl_(new impl(shutdown_server_now)){}
467 void server::start() { impl_->start(); }
468 spl::shared_ptr<core::system_info_provider_repository> server::get_system_info_provider_repo() const { return impl_->system_info_provider_repo_; }
469 spl::shared_ptr<protocol::amcp::amcp_command_repository> server::get_amcp_command_repository() const { return spl::make_shared_ptr(impl_->amcp_command_repo_); }
470 core::monitor::subject& server::monitor_output() { return *impl_->monitor_subject_; }
471
472 }