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