]> git.sesse.net Git - casparcg/blob - shell/main.cpp
483c1230cc2aef7186e3c4082cff7e2d1e728de8
[casparcg] / shell / main.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 // tbbmalloc_proxy: 
23 // Replace the standard memory allocation routines in Microsoft* C/C++ RTL 
24 // (malloc/free, global new/delete, etc.) with the TBB memory allocator. 
25
26 #include "stdafx.h"
27
28 #include <tbb/task_scheduler_init.h>
29 #include <tbb/task_scheduler_observer.h>
30
31 #if defined _DEBUG && defined _MSC_VER
32         #define _CRTDBG_MAP_ALLOC
33         #include <stdlib.h>
34         #include <crtdbg.h>
35 #else
36         // Reenable when tbb gets official support for vc14
37         //#include <tbb/tbbmalloc_proxy.h>
38 #endif
39
40 #include "server.h"
41 #include "platform_specific.h"
42 #include "included_modules.h"
43
44 #include <protocol/util/strategy_adapters.h>
45 #include <protocol/amcp/AMCPProtocolStrategy.h>
46
47 #include <common/env.h>
48 #include <common/except.h>
49 #include <common/log.h>
50 #include <common/gl/gl_check.h>
51 #include <common/os/system_info.h>
52 #include <common/os/general_protection_fault.h>
53
54 #include <core/system_info_provider.h>
55
56 #include <boost/property_tree/detail/file_parser_error.hpp>
57 #include <boost/property_tree/xml_parser.hpp>
58 #include <boost/locale.hpp>
59 #include <boost/lexical_cast.hpp>
60 #include <boost/algorithm/string/predicate.hpp>
61 #include <boost/thread.hpp>
62 #include <boost/thread/future.hpp>
63 #include <boost/algorithm/string/case_conv.hpp>
64 #include <boost/algorithm/string/split.hpp>
65 #include <boost/algorithm/string/classification.hpp>
66
67 #include <tbb/atomic.h>
68
69 #include <future>
70 #include <set>
71
72 #include <csignal>
73
74 using namespace caspar;
75         
76 void setup_global_locale()
77 {
78         boost::locale::generator gen;
79         gen.categories(boost::locale::codepage_facet);
80
81         std::locale::global(gen(""));
82 }
83
84 void print_info()
85 {
86         CASPAR_LOG(info) << L"############################################################################";
87         CASPAR_LOG(info) << L"CasparCG Server is distributed by the Swedish Broadcasting Corporation (SVT)";
88         CASPAR_LOG(info) << L"under the GNU General Public License GPLv3 or higher.";
89         CASPAR_LOG(info) << L"Please see LICENSE.TXT for details.";
90         CASPAR_LOG(info) << L"http://www.casparcg.com/";
91         CASPAR_LOG(info) << L"############################################################################";
92         CASPAR_LOG(info) << L"Starting CasparCG Video and Graphics Playout Server " << env::version();
93         CASPAR_LOG(info) << L"on " << os_description();
94         CASPAR_LOG(info) << cpu_info();
95         CASPAR_LOG(info) << system_product_name();
96 }
97
98
99 void print_system_info(const spl::shared_ptr<core::system_info_provider_repository>& repo)
100 {
101         boost::property_tree::wptree info;
102         repo->fill_information(info);
103
104         for (auto& elem : info.get_child(L"system"))
105                 log::print_child(boost::log::trivial::info, L"", elem.first, elem.second);
106 }
107
108 void do_run(
109                 std::weak_ptr<caspar::IO::protocol_strategy<wchar_t>> amcp,
110                 std::promise<bool>& shutdown_server_now,
111                 tbb::atomic<bool>& should_wait_for_keypress)
112 {
113         std::wstring wcmd;
114         while(true)
115         {
116                 std::getline(std::wcin, wcmd); // TODO: It's blocking...
117                                 
118                 //boost::to_upper(wcmd);
119
120                 if(boost::iequals(wcmd, L"EXIT") || boost::iequals(wcmd, L"Q") || boost::iequals(wcmd, L"QUIT") || boost::iequals(wcmd, L"BYE"))
121                 {
122                         CASPAR_LOG(info) << L"Received message from Console: " << wcmd << L"\\r\\n";
123                         should_wait_for_keypress = true;
124                         shutdown_server_now.set_value(false);   //false to not restart
125                         break;
126                 }
127
128                 try
129                 {
130                         // This is just dummy code for testing.
131                         if(wcmd.substr(0, 1) == L"1")
132                                 wcmd = L"LOADBG 1-1 " + wcmd.substr(1, wcmd.length()-1) + L" SLIDE 100 LOOP \r\nPLAY 1-1";
133                         else if(wcmd.substr(0, 1) == L"2")
134                                 wcmd = L"MIXER 1-0 VIDEO IS_KEY 1";
135                         else if(wcmd.substr(0, 1) == L"3")
136                                 wcmd = L"CG 1-2 ADD 1 BBTELEFONARE 1";
137                         else if(wcmd.substr(0, 1) == L"4")
138                                 wcmd = L"PLAY 1-1 DV FILTER yadif=1:-1 LOOP";
139                         else if(wcmd.substr(0, 1) == L"5")
140                         {
141                                 auto file = wcmd.substr(2, wcmd.length()-1);
142                                 wcmd = L"PLAY 1-1 " + file + L" LOOP\r\n" 
143                                                 L"PLAY 1-2 " + file + L" LOOP\r\n" 
144                                                 L"PLAY 1-3 " + file + L" LOOP\r\n"
145                                                 L"PLAY 2-1 " + file + L" LOOP\r\n" 
146                                                 L"PLAY 2-2 " + file + L" LOOP\r\n" 
147                                                 L"PLAY 2-3 " + file + L" LOOP\r\n";
148                         }
149                         else if(wcmd.substr(0, 1) == L"7")
150                         {
151                                 wcmd = L"";
152                                 wcmd += L"CLEAR 1\r\n";
153                                 wcmd += L"MIXER 1 CLEAR\r\n";
154                                 wcmd += L"PLAY 1-0 GREEN\r\n";
155                                 wcmd += L"PLAY 1-1 BLUE\r\n";
156                                 wcmd += L"CG 1-2 ADD 1 ECS_TEST 1\r\n";
157                                 wcmd += L"MIXER 1-2 FILL 0 -1 1 2\r\n";
158                         }
159                         else if(wcmd.substr(0, 1) == L"8")
160                         {
161                                 wcmd = L"";
162                                 wcmd += L"MIXER 1-1 FILL 0.0 0.5 1.0 1.0 500 linear DEFER\r\n";
163                                 wcmd += L"MIXER 1-2 FILL 0.0 0.0 1.0 1.0 500 linear DEFER\r\n";
164                                 wcmd += L"MIXER 1 COMMIT\r\n";
165                         }
166                         else if(wcmd.substr(0, 1) == L"X")
167                         {
168                                 int num = 0;
169                                 std::wstring file;
170                                 try
171                                 {
172                                         num = boost::lexical_cast<int>(wcmd.substr(1, 2));
173                                         file = wcmd.substr(4, wcmd.length()-1);
174                                 }
175                                 catch(...)
176                                 {
177                                         num = boost::lexical_cast<int>(wcmd.substr(1, 1));
178                                         file = wcmd.substr(3, wcmd.length()-1);
179                                 }
180
181                                 int n = 0;
182                                 int num2 = num;
183                                 while(num2 > 0)
184                                 {
185                                         num2 >>= 1;
186                                         n++;
187                                 }
188
189                                 wcmd = L"MIXER 1 GRID " + boost::lexical_cast<std::wstring>(n);
190
191                                 for(int i = 1; i <= num; ++i)
192                                         wcmd += L"\r\nPLAY 1-" + boost::lexical_cast<std::wstring>(i) + L" " + file + L" LOOP";// + L" SLIDE 100 LOOP";
193                         }
194                 }
195                 catch (...)
196                 {
197                         CASPAR_LOG_CURRENT_EXCEPTION();
198                         continue;
199                 }
200
201                 wcmd += L"\r\n";
202                 auto strong = amcp.lock();
203                 if (strong)
204                         strong->parse(wcmd);
205                 else
206                         break;
207         }
208 };
209
210 bool run(const std::wstring& config_file_name, tbb::atomic<bool>& should_wait_for_keypress)
211 {
212         std::promise<bool> shutdown_server_now;
213         std::future<bool> shutdown_server = shutdown_server_now.get_future();
214
215         print_info();
216
217         // Create server object which initializes channels, protocols and controllers.
218         std::unique_ptr<server> caspar_server(new server(shutdown_server_now));
219
220         // Print environment information.
221         print_system_info(caspar_server->get_system_info_provider_repo());
222
223         std::wstringstream str;
224         boost::property_tree::xml_writer_settings<std::wstring> w(' ', 3);
225         boost::property_tree::write_xml(str, env::properties(), w);
226         CASPAR_LOG(info) << config_file_name << L":\n-----------------------------------------\n" << str.str() << L"-----------------------------------------";
227         
228         {
229                 CASPAR_SCOPED_CONTEXT_MSG(config_file_name + L": ")
230                 caspar_server->start();
231         }
232
233         // Create a dummy client which prints amcp responses to console.
234         auto console_client = spl::make_shared<IO::ConsoleClientInfo>();
235
236         // Create a amcp parser for console commands.
237         std::shared_ptr<IO::protocol_strategy<wchar_t>> amcp = spl::make_shared<caspar::IO::delimiter_based_chunking_strategy_factory<wchar_t>>(
238                         L"\r\n",
239                         spl::make_shared<caspar::IO::legacy_strategy_adapter_factory>(
240                                         spl::make_shared<protocol::amcp::AMCPProtocolStrategy>(
241                                                         L"Console",
242                                                         caspar_server->get_amcp_command_repository())))->create(console_client);
243         std::weak_ptr<IO::protocol_strategy<wchar_t>> weak_amcp = amcp;
244
245         // Use separate thread for the blocking console input, will be terminated 
246         // anyway when the main thread terminates.
247         boost::thread stdin_thread(std::bind(do_run, weak_amcp, std::ref(shutdown_server_now), std::ref(should_wait_for_keypress)));    //compiler didn't like lambda here...
248         stdin_thread.detach();
249         bool should_restart = shutdown_server.get();
250         amcp.reset();
251
252         while (weak_amcp.lock());
253
254         return should_restart;
255 }
256
257 void on_abort(int)
258 {
259         CASPAR_THROW_EXCEPTION(invalid_operation() << msg_info("abort called"));
260 }
261
262 int main(int argc, char** argv)
263 {
264         if (intercept_command_line_args(argc, argv))
265                 return 0;
266
267         int return_code = 0;
268         setup_prerequisites();
269         //std::signal(SIGABRT, on_abort);
270
271         setup_global_locale();
272
273         std::wcout << L"Type \"q\" to close application." << std::endl;
274         
275         // Set debug mode.
276         auto debugging_environment = setup_debugging_environment();
277
278         // Increase process priotity.
279         increase_process_priority();
280
281         // Install general protection fault handler.
282         ensure_gpf_handler_installed_for_thread("main thread");
283
284         // Install GPF handler into all tbb threads.
285         struct tbb_thread_installer : public tbb::task_scheduler_observer
286         {
287                 tbb_thread_installer(){observe(true);}
288                 void on_scheduler_entry(bool is_worker) override
289                 {
290                         ensure_gpf_handler_installed_for_thread("tbb-worker-thread");
291                 }
292         } tbb_thread_installer;
293
294         tbb::task_scheduler_init init;
295         std::wstring config_file_name(L"casparcg.config");
296         
297         try 
298         {
299                 // Configure environment properties from configuration.
300                 if (argc >= 2)
301                         config_file_name = caspar::u16(argv[1]);
302
303                 env::configure(config_file_name);
304
305                 log::set_log_level(env::properties().get(L"configuration.log-level", L"info"));
306                 auto log_categories_str = env::properties().get(L"configuration.log-categories", L"communication");
307                 std::set<std::wstring> log_categories;
308                 boost::split(log_categories, log_categories_str, boost::is_any_of(L", "));
309                 for (auto& log_category : { L"calltrace", L"communication" })
310                         log::set_log_category(log_category, log_categories.find(log_category) != log_categories.end());
311
312                 if (env::properties().get(L"configuration.debugging.remote", false))
313                         wait_for_remote_debugging();
314
315                 // Start logging to file.
316                 log::add_file_sink(env::log_folder() + L"caspar",               caspar::log::category != caspar::log::log_category::calltrace);
317                 log::add_file_sink(env::log_folder() + L"calltrace",    caspar::log::category == caspar::log::log_category::calltrace);
318                 std::wcout << L"Logging [info] or higher severity to " << env::log_folder() << std::endl << std::endl;
319                 
320                 // Setup console window.
321                 setup_console_window();
322
323                 tbb::atomic<bool> should_wait_for_keypress;
324                 should_wait_for_keypress = false;
325                 auto should_restart = run(config_file_name, should_wait_for_keypress);
326                 return_code = should_restart ? 5 : 0;
327
328                 for (auto& thread : get_thread_infos())
329                 {
330                         if (thread->name != "main thread" && thread->name != "tbb-worker-thread")
331                                 CASPAR_LOG(warning) << L"Thread left running: " << thread->name << L" (" << thread->native_id << L")";
332                 }
333                 
334                 CASPAR_LOG(info) << "Successfully shutdown CasparCG Server.";
335
336                 if (!should_wait_for_keypress)
337                         wait_for_keypress();
338         }
339         catch(const boost::property_tree::file_parser_error& e)
340         {
341                 CASPAR_LOG_CURRENT_EXCEPTION();
342                 CASPAR_LOG(fatal) << "At " << u8(config_file_name) << ":" << e.line() << ": " << e.message() << ". Please check the configuration file (" << u8(config_file_name) << ") for errors.";
343                 wait_for_keypress();
344         }
345         catch (const user_error& e)
346         {
347                 CASPAR_LOG_CURRENT_EXCEPTION_AT_LEVEL(debug);
348                 CASPAR_LOG(fatal) << get_message_and_context(e) << " Please check the configuration file (" << u8(config_file_name) << ") for errors. Turn on log level debug for stacktrace.";
349                 wait_for_keypress();
350         }
351         catch(...)
352         {
353                 CASPAR_LOG_CURRENT_EXCEPTION();
354                 CASPAR_LOG(fatal) << L"Unhandled exception in main thread. Please report this error on the CasparCG forums (www.casparcg.com/forum).";
355                 boost::this_thread::sleep_for(boost::chrono::milliseconds(1000));
356                 std::wcout << L"\n\nCasparCG will automatically shutdown. See the log file located at the configured log-file folder for more information.\n\n";
357                 boost::this_thread::sleep_for(boost::chrono::milliseconds(4000));
358         }
359
360         return return_code;
361 }