]> git.sesse.net Git - casparcg/blob - shell/main.cpp
Reduced the coupling between specific modules and InfoCommand, VersionCommand and...
[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 #ifdef _DEBUG
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 "resource.h"
40
41 #include "server.h"
42
43 #include <common/os/windows/windows.h>
44 #include <winnt.h>
45 #include <mmsystem.h>
46 #include <atlbase.h>
47
48 #include <protocol/util/strategy_adapters.h>
49 #include <protocol/amcp/AMCPProtocolStrategy.h>
50
51 #include <common/env.h>
52 #include <common/except.h>
53 #include <common/log.h>
54 #include <common/gl/gl_check.h>
55 #include <common/os/system_info.h>
56 #include <common/os/general_protection_fault.h>
57
58 #include <core/system_info_provider.h>
59
60 #include <boost/property_tree/detail/file_parser_error.hpp>
61 #include <boost/property_tree/xml_parser.hpp>
62 #include <boost/locale.hpp>
63 #include <boost/lexical_cast.hpp>
64 #include <boost/algorithm/string/predicate.hpp>
65 #include <boost/thread.hpp>
66 #include <boost/thread/future.hpp>
67 #include <boost/algorithm/string/case_conv.hpp>
68
69 #include <future>
70
71 #include <signal.h>
72
73 using namespace caspar;
74         
75 // NOTE: This is needed in order to make CComObject work since this is not a real ATL project.
76 CComModule _AtlModule;
77 extern __declspec(selectany) CAtlModule* _pAtlModule = &_AtlModule;
78
79 void change_icon( const HICON hNewIcon )
80 {
81    auto hMod = ::LoadLibrary(L"Kernel32.dll"); 
82    typedef DWORD(__stdcall *SCI)(HICON);
83    auto pfnSetConsoleIcon = reinterpret_cast<SCI>(::GetProcAddress(hMod, "SetConsoleIcon")); 
84    pfnSetConsoleIcon(hNewIcon); 
85    ::FreeLibrary(hMod);
86 }
87
88 void setup_global_locale()
89 {
90         boost::locale::generator gen;
91         gen.categories(boost::locale::codepage_facet);
92
93         std::locale::global(gen(""));
94 }
95
96 void setup_console_window()
97 {        
98         auto hOut = GetStdHandle(STD_OUTPUT_HANDLE);
99
100         // Disable close button in console to avoid shutdown without cleanup.
101         EnableMenuItem(GetSystemMenu(GetConsoleWindow(), FALSE), SC_CLOSE , MF_GRAYED);
102         DrawMenuBar(GetConsoleWindow());
103         //SetConsoleCtrlHandler(HandlerRoutine, true);
104
105         // Configure console size and position.
106         auto coord = GetLargestConsoleWindowSize(hOut);
107         coord.X /= 2;
108
109         SetConsoleScreenBufferSize(hOut, coord);
110
111         SMALL_RECT DisplayArea = {0, 0, 0, 0};
112         DisplayArea.Right = coord.X-1;
113         DisplayArea.Bottom = (coord.Y-1)/2;
114         SetConsoleWindowInfo(hOut, TRUE, &DisplayArea);
115                  
116         change_icon(::LoadIcon(GetModuleHandle(0), MAKEINTRESOURCE(101)));
117
118         // Set console title.
119         std::wstringstream str;
120         str << "CasparCG Server " << env::version() << L" x64 ";
121 #ifdef COMPILE_RELEASE
122         str << " Release";
123 #elif  COMPILE_PROFILE
124         str << " Profile";
125 #elif  COMPILE_DEVELOP
126         str << " Develop";
127 #elif  COMPILE_DEBUG
128         str << " Debug";
129 #endif
130         SetConsoleTitle(str.str().c_str());
131 }
132
133 void print_info()
134 {
135         CASPAR_LOG(info) << L"############################################################################";
136         CASPAR_LOG(info) << L"CasparCG Server is distributed by the Swedish Broadcasting Corporation (SVT)";
137         CASPAR_LOG(info) << L"under the GNU General Public License GPLv3 or higher.";
138         CASPAR_LOG(info) << L"Please see LICENSE.TXT for details.";
139         CASPAR_LOG(info) << L"http://www.casparcg.com/";
140         CASPAR_LOG(info) << L"############################################################################";
141         CASPAR_LOG(info) << L"Starting CasparCG Video and Graphics Playout Server " << env::version();
142         CASPAR_LOG(info) << L"on " << os_description();
143         CASPAR_LOG(info) << cpu_info();
144         CASPAR_LOG(info) << system_product_name();
145 }
146
147 void print_child(const std::wstring& indent, const std::wstring& elem, const boost::property_tree::wptree& tree)
148 {
149         auto data = tree.data();
150
151         if (data.empty())
152                 CASPAR_LOG(info) << indent << elem;
153         else
154                 CASPAR_LOG(info) << indent << elem << L" " << tree.data();
155
156         for (auto& child : tree)
157                 print_child(indent + L"    ", child.first, child.second);
158 }
159
160 void print_system_info(const spl::shared_ptr<core::system_info_provider_repository>& repo)
161 {
162         boost::property_tree::wptree info;
163         repo->fill_information(info);
164         
165         /*CASPAR_LOG(info) << L"Decklink " << decklink::version();
166         for (auto device : decklink::device_list())
167                 CASPAR_LOG(info) << L" - " << device;
168                 
169         CASPAR_LOG(info) << L"Bluefish " << bluefish::version();
170         for (auto device : bluefish::device_list())
171                 CASPAR_LOG(info) << L" - " << device;*/
172
173         for (auto& elem : info.get_child(L"system"))
174                 print_child(L"", elem.first, elem.second);
175
176         //CASPAR_LOG(info) << L"Flash "                 << flash::version();
177         //CASPAR_LOG(info) << L"FreeImage "             << image::version();
178         /*CASPAR_LOG(info) << L"FFMPEG-avcodec "  << ffmpeg::avcodec_version();
179         CASPAR_LOG(info) << L"FFMPEG-avformat " << ffmpeg::avformat_version();
180         CASPAR_LOG(info) << L"FFMPEG-avfilter " << ffmpeg::avfilter_version();
181         CASPAR_LOG(info) << L"FFMPEG-avutil "   << ffmpeg::avutil_version();
182         CASPAR_LOG(info) << L"FFMPEG-swscale "  << ffmpeg::swscale_version();*/
183 }
184
185 LONG WINAPI UserUnhandledExceptionFilter(EXCEPTION_POINTERS* info)
186 {
187         try
188         {
189                 CASPAR_LOG(fatal) << L"#######################\n UNHANDLED EXCEPTION: \n" 
190                         << L"Adress:" << info->ExceptionRecord->ExceptionAddress << L"\n"
191                         << L"Code:" << info->ExceptionRecord->ExceptionCode << L"\n"
192                         << L"Flag:" << info->ExceptionRecord->ExceptionFlags << L"\n"
193                         << L"Info:" << info->ExceptionRecord->ExceptionInformation << L"\n"
194                         << L"Continuing execution. \n#######################";
195
196                 CASPAR_LOG_CALL_STACK();
197         }
198         catch(...){}
199
200         return EXCEPTION_CONTINUE_EXECUTION;
201 }
202
203 void do_run(server& caspar_server, std::promise<bool>& shutdown_server_now)
204 {
205         // Create a dummy client which prints amcp responses to console.
206         auto console_client = spl::make_shared<IO::ConsoleClientInfo>();
207         
208         // Create a amcp parser for console commands.
209         //protocol::amcp::AMCPProtocolStrategy amcp(caspar_server.channels());
210         auto amcp = spl::make_shared<caspar::IO::delimiter_based_chunking_strategy_factory<wchar_t>>(
211                         L"\r\n",
212                         spl::make_shared<caspar::IO::legacy_strategy_adapter_factory>(
213                                         spl::make_shared<protocol::amcp::AMCPProtocolStrategy>(
214                                                         caspar_server.channels(),
215                                                         caspar_server.get_thumbnail_generator(),
216                                                         caspar_server.get_media_info_repo(),
217                                                         caspar_server.get_system_info_provider_repo(),
218                                                         shutdown_server_now)))->create(console_client);
219
220         std::wstring wcmd;
221         while(true)
222         {
223                 std::getline(std::wcin, wcmd); // TODO: It's blocking...
224                                 
225                 //boost::to_upper(wcmd);
226
227                 if(boost::iequals(wcmd, L"EXIT") || boost::iequals(wcmd, L"Q") || boost::iequals(wcmd, L"QUIT") || boost::iequals(wcmd, L"BYE"))
228                 {
229                         shutdown_server_now.set_value(true);    //true to wait for keypress
230                         break;
231                 }
232
233                 try
234                 {
235                         // This is just dummy code for testing.
236                         if(wcmd.substr(0, 1) == L"1")
237                                 wcmd = L"LOADBG 1-1 " + wcmd.substr(1, wcmd.length()-1) + L" SLIDE 100 LOOP \r\nPLAY 1-1";
238                         else if(wcmd.substr(0, 1) == L"2")
239                                 wcmd = L"MIXER 1-0 VIDEO IS_KEY 1";
240                         else if(wcmd.substr(0, 1) == L"3")
241                                 wcmd = L"CG 1-2 ADD 1 BBTELEFONARE 1";
242                         else if(wcmd.substr(0, 1) == L"4")
243                                 wcmd = L"PLAY 1-1 DV FILTER yadif=1:-1 LOOP";
244                         else if(wcmd.substr(0, 1) == L"5")
245                         {
246                                 auto file = wcmd.substr(2, wcmd.length()-1);
247                                 wcmd = L"PLAY 1-1 " + file + L" LOOP\r\n" 
248                                                 L"PLAY 1-2 " + file + L" LOOP\r\n" 
249                                                 L"PLAY 1-3 " + file + L" LOOP\r\n"
250                                                 L"PLAY 2-1 " + file + L" LOOP\r\n" 
251                                                 L"PLAY 2-2 " + file + L" LOOP\r\n" 
252                                                 L"PLAY 2-3 " + file + L" LOOP\r\n";
253                         }
254                         else if(wcmd.substr(0, 1) == L"7")
255                         {
256                                 wcmd = L"";
257                                 wcmd += L"CLEAR 1\r\n";
258                                 wcmd += L"MIXER 1 CLEAR\r\n";
259                                 wcmd += L"PLAY 1-0 GREEN\r\n";
260                                 wcmd += L"PLAY 1-1 BLUE\r\n";
261                                 wcmd += L"CG 1-2 ADD 1 ECS_TEST 1\r\n";
262                                 wcmd += L"MIXER 1-2 FILL 0 -1 1 2\r\n";
263                         }
264                         else if(wcmd.substr(0, 1) == L"8")
265                         {
266                                 wcmd = L"";
267                                 wcmd += L"MIXER 1-1 FILL 0.0 0.5 1.0 1.0 500 linear DEFER\r\n";
268                                 wcmd += L"MIXER 1-2 FILL 0.0 0.0 1.0 1.0 500 linear DEFER\r\n";
269                                 wcmd += L"MIXER 1 COMMIT\r\n";
270                         }
271                         else if(wcmd.substr(0, 1) == L"X")
272                         {
273                                 int num = 0;
274                                 std::wstring file;
275                                 try
276                                 {
277                                         num = boost::lexical_cast<int>(wcmd.substr(1, 2));
278                                         file = wcmd.substr(4, wcmd.length()-1);
279                                 }
280                                 catch(...)
281                                 {
282                                         num = boost::lexical_cast<int>(wcmd.substr(1, 1));
283                                         file = wcmd.substr(3, wcmd.length()-1);
284                                 }
285
286                                 int n = 0;
287                                 int num2 = num;
288                                 while(num2 > 0)
289                                 {
290                                         num2 >>= 1;
291                                         n++;
292                                 }
293
294                                 wcmd = L"MIXER 1 GRID " + boost::lexical_cast<std::wstring>(n);
295
296                                 for(int i = 1; i <= num; ++i)
297                                         wcmd += L"\r\nPLAY 1-" + boost::lexical_cast<std::wstring>(i) + L" " + file + L" LOOP";// + L" SLIDE 100 LOOP";
298                         }
299                 }
300                 catch (...)
301                 {
302                         CASPAR_LOG_CURRENT_EXCEPTION();
303                         continue;
304                 }
305
306                 wcmd += L"\r\n";
307                 amcp->parse(wcmd);
308         }
309 };
310
311 bool run()
312 {
313         std::promise<bool> shutdown_server_now;
314         std::future<bool> shutdown_server = shutdown_server_now.get_future();
315
316         print_info();
317
318         // Create server object which initializes channels, protocols and controllers.
319         server caspar_server(shutdown_server_now);
320         
321         // Print environment information.
322         print_system_info(caspar_server.get_system_info_provider_repo());
323
324         std::wstringstream str;
325         boost::property_tree::xml_writer_settings<std::wstring> w(' ', 3);
326         boost::property_tree::write_xml(str, env::properties(), w);
327         CASPAR_LOG(info) << L"casparcg.config:\n-----------------------------------------\n" << str.str().c_str() << L"-----------------------------------------";
328         
329         caspar_server.start();
330
331         //auto console_obs = reactive::make_observer([](const monitor::event& e)
332         //{
333         //      std::stringstream str;
334         //      str << e;
335         //      CASPAR_LOG(trace) << str.str().c_str();
336         //});
337
338         //caspar_server.subscribe(console_obs);
339
340
341         // Use separate thread for the blocking console input, will be terminated 
342         // anyway when the main thread terminates.
343         boost::thread stdin_thread(std::bind(do_run, std::ref(caspar_server), std::ref(shutdown_server_now)));  //compiler didn't like lambda here...
344         stdin_thread.detach();
345         return shutdown_server.get();
346 }
347
348 void on_abort(int)
349 {
350         CASPAR_THROW_EXCEPTION(invalid_operation() << msg_info("abort called"));
351 }
352
353 int main(int argc, wchar_t* argv[])
354 {       
355         int return_code = 0;
356         SetUnhandledExceptionFilter(UserUnhandledExceptionFilter);
357         signal(SIGABRT, on_abort);
358
359         setup_global_locale();
360
361         std::wcout << L"Type \"q\" to close application." << std::endl;
362         
363         // Set debug mode.
364         #ifdef _DEBUG
365                 HANDLE hLogFile;
366                 hLogFile = CreateFile(L"crt_log.txt", GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
367                 std::shared_ptr<void> crt_log(nullptr, [](HANDLE h){::CloseHandle(h);});
368
369                 _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
370                 _CrtSetReportMode(_CRT_WARN,    _CRTDBG_MODE_FILE);
371                 _CrtSetReportFile(_CRT_WARN,    hLogFile);
372                 _CrtSetReportMode(_CRT_ERROR,   _CRTDBG_MODE_FILE);
373                 _CrtSetReportFile(_CRT_ERROR,   hLogFile);
374                 _CrtSetReportMode(_CRT_ASSERT,  _CRTDBG_MODE_FILE);
375                 _CrtSetReportFile(_CRT_ASSERT,  hLogFile);
376         #endif
377
378         // Increase process priotity.
379         SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS);
380
381         // Install structured exception handler.
382         ensure_gpf_handler_installed_for_thread("main thread");
383                                 
384         // Increase time precision. This will increase accuracy of function like Sleep(1) from 10 ms to 1 ms.
385         struct inc_prec
386         {
387                 inc_prec(){timeBeginPeriod(1);}
388                 ~inc_prec(){timeEndPeriod(1);}
389         } inc_prec;     
390
391         // Install SEH into all tbb threads.
392         struct tbb_thread_installer : public tbb::task_scheduler_observer
393         {
394                 tbb_thread_installer(){observe(true);}
395                 void on_scheduler_entry(bool is_worker)
396                 {
397                         ensure_gpf_handler_installed_for_thread("tbb-worker-thread");
398                 }
399         } tbb_thread_installer;
400
401         tbb::task_scheduler_init init;
402         
403         try 
404         {
405                 // Configure environment properties from configuration.
406                 env::configure(L"casparcg.config");
407                                 
408                 log::set_log_level(env::properties().get(L"configuration.log-level", L"debug"));
409
410         #ifdef _DEBUG
411                 if(env::properties().get(L"configuration.debugging.remote", false))
412                         MessageBox(nullptr, L"Now is the time to connect for remote debugging...", L"Debug", MB_OK | MB_TOPMOST);
413         #endif   
414
415                 // Start logging to file.
416                 log::add_file_sink(env::log_folder());                  
417                 std::wcout << L"Logging [info] or higher severity to " << env::log_folder() << std::endl << std::endl;
418                 
419                 // Setup console window.
420                 setup_console_window();
421
422                 return_code = run() ? 5 : 0;
423                 
424                 Sleep(500);
425                 CASPAR_LOG(info) << "Successfully shutdown CasparCG Server.";
426         }
427         catch(boost::property_tree::file_parser_error&)
428         {
429                 CASPAR_LOG_CURRENT_EXCEPTION();
430                 CASPAR_LOG(fatal) << L"Unhandled configuration error in main thread. Please check the configuration file (casparcg.config) for errors.";
431                 system("pause");        
432         }
433         catch(...)
434         {
435                 CASPAR_LOG_CURRENT_EXCEPTION();
436                 CASPAR_LOG(fatal) << L"Unhandled exception in main thread. Please report this error on the CasparCG forums (www.casparcg.com/forum).";
437                 Sleep(1000);
438                 std::wcout << L"\n\nCasparCG will automatically shutdown. See the log file located at the configured log-file folder for more information.\n\n";
439                 Sleep(4000);
440         }               
441         
442         return return_code;
443 }