]> git.sesse.net Git - casparcg/blob - shell/main.cpp
Implemented INFO QUEUES command for debugging AMCP command queues. Useful for debuggi...
[casparcg] / shell / main.cpp
1 /*\r
2 * Copyright 2013 Sveriges Television AB http://casparcg.com/\r
3 *\r
4 * This file is part of CasparCG (www.casparcg.com).\r
5 *\r
6 * CasparCG is free software: you can redistribute it and/or modify\r
7 * it under the terms of the GNU General Public License as published by\r
8 * the Free Software Foundation, either version 3 of the License, or\r
9 * (at your option) any later version.\r
10 *\r
11 * CasparCG is distributed in the hope that it will be useful,\r
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
14 * GNU General Public License for more details.\r
15 *\r
16 * You should have received a copy of the GNU General Public License\r
17 * along with CasparCG. If not, see <http://www.gnu.org/licenses/>.\r
18 *\r
19 * Author: Robert Nagy, ronag89@gmail.com\r
20 */\r
21 \r
22 // tbbmalloc_proxy: \r
23 // Replace the standard memory allocation routines in Microsoft* C/C++ RTL \r
24 // (malloc/free, global new/delete, etc.) with the TBB memory allocator. \r
25 \r
26 #ifdef _DEBUG\r
27         #define _CRTDBG_MAP_ALLOC\r
28         #include <stdlib.h>\r
29         #include <crtdbg.h>\r
30 #else\r
31         #include <tbb/tbbmalloc_proxy.h>\r
32 #endif\r
33 \r
34 #include "resource.h"\r
35 \r
36 #include "server.h"\r
37 \r
38 #define NOMINMAX\r
39 #define WIN32_LEAN_AND_MEAN\r
40 \r
41 #include <locale>\r
42 \r
43 #include <windows.h>\r
44 #include <winnt.h>\r
45 #include <mmsystem.h>\r
46 #include <atlbase.h>\r
47 \r
48 #include <protocol/amcp/AMCPProtocolStrategy.h>\r
49 \r
50 #include <modules/bluefish/bluefish.h>\r
51 #include <modules/decklink/decklink.h>\r
52 #include <modules/flash/flash.h>\r
53 #include <modules/ffmpeg/ffmpeg.h>\r
54 #include <modules/image/image.h>\r
55 #include <modules/newtek/util/air_send.h>\r
56 #include <modules/html/html.h>\r
57 \r
58 #include <common/env.h>\r
59 #include <common/exception/win32_exception.h>\r
60 #include <common/exception/exceptions.h>\r
61 #include <common/log/log.h>\r
62 #include <common/gl/gl_check.h>\r
63 #include <common/os/windows/current_version.h>\r
64 #include <common/os/windows/system_info.h>\r
65 \r
66 #include <tbb/task_scheduler_init.h>\r
67 #include <tbb/task_scheduler_observer.h>\r
68 \r
69 #include <boost/property_tree/detail/file_parser_error.hpp>\r
70 #include <boost/property_tree/xml_parser.hpp>\r
71 #include <boost/foreach.hpp>\r
72 #include <boost/thread.hpp>\r
73 #include <boost/thread/future.hpp>\r
74 #include <boost/locale.hpp>\r
75 #include <boost/algorithm/string/case_conv.hpp>\r
76 \r
77 #include <functional>\r
78 \r
79 // NOTE: This is needed in order to make CComObject work since this is not a real ATL project.\r
80 CComModule _AtlModule;\r
81 extern __declspec(selectany) CAtlModule* _pAtlModule = &_AtlModule;\r
82 \r
83 void change_icon( const HICON hNewIcon )\r
84 {\r
85    auto hMod = ::LoadLibrary(L"Kernel32.dll"); \r
86    typedef DWORD(__stdcall *SCI)(HICON);\r
87    auto pfnSetConsoleIcon = reinterpret_cast<SCI>(::GetProcAddress(hMod, "SetConsoleIcon")); \r
88    pfnSetConsoleIcon(hNewIcon); \r
89    ::FreeLibrary(hMod);\r
90 }\r
91 \r
92 void setup_global_locale()\r
93 {\r
94         boost::locale::generator gen;\r
95         gen.categories(boost::locale::codepage_facet);\r
96 \r
97         std::locale::global(gen(""));\r
98 }\r
99 \r
100 void setup_console_window()\r
101 {        \r
102         auto hOut = GetStdHandle(STD_OUTPUT_HANDLE);\r
103 \r
104         // Disable close button in console to avoid shutdown without cleanup.\r
105         EnableMenuItem(GetSystemMenu(GetConsoleWindow(), FALSE), SC_CLOSE , MF_GRAYED);\r
106         DrawMenuBar(GetConsoleWindow());\r
107         //SetConsoleCtrlHandler(HandlerRoutine, true);\r
108 \r
109         // Configure console size and position.\r
110         auto coord = GetLargestConsoleWindowSize(hOut);\r
111         coord.X /= 2;\r
112 \r
113         SetConsoleScreenBufferSize(hOut, coord);\r
114 \r
115         SMALL_RECT DisplayArea = {0, 0, 0, 0};\r
116         DisplayArea.Right = coord.X-1;\r
117         DisplayArea.Bottom = (coord.Y-1)/2;\r
118         SetConsoleWindowInfo(hOut, TRUE, &DisplayArea);\r
119                  \r
120         change_icon(::LoadIcon(GetModuleHandle(0), MAKEINTRESOURCE(101)));\r
121 \r
122         // Set console title.\r
123         std::wstringstream str;\r
124         str << "CasparCG Server " << caspar::env::version();\r
125 #ifdef COMPILE_RELEASE\r
126         str << " Release";\r
127 #elif  COMPILE_PROFILE\r
128         str << " Profile";\r
129 #elif  COMPILE_DEVELOP\r
130         str << " Develop";\r
131 #elif  COMPILE_DEBUG\r
132         str << " Debug";\r
133 #endif\r
134         SetConsoleTitle(str.str().c_str());\r
135 }\r
136 \r
137 void print_info()\r
138 {\r
139         CASPAR_LOG(info) << L"############################################################################";\r
140         CASPAR_LOG(info) << L"CasparCG Server is distributed by the Swedish Broadcasting Corporation (SVT)";\r
141         CASPAR_LOG(info) << L"under the GNU General Public License GPLv3 or higher.";\r
142         CASPAR_LOG(info) << L"Please see LICENSE.TXT for details.";\r
143         CASPAR_LOG(info) << L"http://www.casparcg.com/";\r
144         CASPAR_LOG(info) << L"############################################################################";\r
145         CASPAR_LOG(info) << L"Starting CasparCG Video and Graphics Playout Server " << caspar::env::version();\r
146         CASPAR_LOG(info) << L"on " << caspar::get_win_product_name() << L" " << caspar::get_win_sp_version();\r
147         CASPAR_LOG(info) << caspar::get_cpu_info();\r
148         CASPAR_LOG(info) << caspar::get_system_product_name();\r
149         \r
150         CASPAR_LOG(info) << L"Decklink " << caspar::decklink::get_version();\r
151         BOOST_FOREACH(auto device, caspar::decklink::get_device_list())\r
152                 CASPAR_LOG(info) << L" - " << device;   \r
153                 \r
154         CASPAR_LOG(info) << L"Bluefish " << caspar::bluefish::get_version();\r
155         BOOST_FOREACH(auto device, caspar::bluefish::get_device_list())\r
156                 CASPAR_LOG(info) << L" - " << device;   \r
157         \r
158         CASPAR_LOG(info) << L"FreeImage "               << caspar::image::get_version();\r
159         CASPAR_LOG(info) << L"FFMPEG-avcodec "  << caspar::ffmpeg::get_avcodec_version();\r
160         CASPAR_LOG(info) << L"FFMPEG-avformat " << caspar::ffmpeg::get_avformat_version();\r
161         CASPAR_LOG(info) << L"FFMPEG-avfilter " << caspar::ffmpeg::get_avfilter_version();\r
162         CASPAR_LOG(info) << L"FFMPEG-avutil "   << caspar::ffmpeg::get_avutil_version();\r
163         CASPAR_LOG(info) << L"FFMPEG-swscale "  << caspar::ffmpeg::get_swscale_version();\r
164         CASPAR_LOG(info) << L"Flash "                   << caspar::flash::get_version();\r
165         CASPAR_LOG(info) << L"Template-Host "   << caspar::flash::get_cg_version();\r
166         CASPAR_LOG(info) << L"NewTek iVGA "             << (caspar::newtek::airsend::is_available() ? L"available" : L"unavailable (" + caspar::newtek::airsend::dll_name() + L")");\r
167 }\r
168 \r
169 LONG WINAPI UserUnhandledExceptionFilter(EXCEPTION_POINTERS* info)\r
170 {\r
171         try\r
172         {\r
173                 CASPAR_LOG(fatal) << L"#######################\n UNHANDLED EXCEPTION: \n" \r
174                         << L"Adress:" << info->ExceptionRecord->ExceptionAddress << L"\n"\r
175                         << L"Code:" << info->ExceptionRecord->ExceptionCode << L"\n"\r
176                         << L"Flag:" << info->ExceptionRecord->ExceptionFlags << L"\n"\r
177                         << L"Info:" << info->ExceptionRecord->ExceptionInformation << L"\n"\r
178                         << L"Continuing execution. \n#######################";\r
179         }\r
180         catch(...){}\r
181 \r
182     return EXCEPTION_EXECUTE_HANDLER;\r
183 }\r
184 \r
185 std::wstring make_upper_case(const std::wstring& str)\r
186 {\r
187         return boost::to_upper_copy(str);\r
188 }\r
189 \r
190 struct init_t\r
191 {\r
192         std::wstring name;\r
193         std::function<void()> uninit;\r
194 \r
195         init_t(std::wstring name, std::function<void()> init, std::function<void()> uninit)\r
196                 : name(name)\r
197                 , uninit(uninit)\r
198         {\r
199                 if (init)\r
200                         init();\r
201                 CASPAR_LOG(info) << L"Initialized " << name << L" module.";\r
202         }\r
203 \r
204         ~init_t()\r
205         {\r
206                 if (uninit)\r
207                         uninit();\r
208                 CASPAR_LOG(info) << L"Uninitialized " << name << L" module.";\r
209         }\r
210 };\r
211 \r
212 int main(int argc, char* argv[])\r
213 {\r
214         if (!caspar::html::init())\r
215                 return 0;\r
216 \r
217         static_assert(sizeof(void*) == 4, "64-bit code generation is not supported.");\r
218         \r
219         SetUnhandledExceptionFilter(UserUnhandledExceptionFilter);\r
220 \r
221         setup_global_locale();\r
222 \r
223         std::wcout << L"Type \"q\" to close application." << std::endl;\r
224         \r
225         // Set debug mode.\r
226         #ifdef _DEBUG\r
227                 HANDLE hLogFile;\r
228                 hLogFile = CreateFile(L"crt_log.txt", GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);\r
229                 std::shared_ptr<void> crt_log(nullptr, [](HANDLE h){::CloseHandle(h);});\r
230 \r
231                 _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);\r
232                 _CrtSetReportMode(_CRT_WARN,    _CRTDBG_MODE_FILE);\r
233                 _CrtSetReportFile(_CRT_WARN,    hLogFile);\r
234                 _CrtSetReportMode(_CRT_ERROR,   _CRTDBG_MODE_FILE);\r
235                 _CrtSetReportFile(_CRT_ERROR,   hLogFile);\r
236                 _CrtSetReportMode(_CRT_ASSERT,  _CRTDBG_MODE_FILE);\r
237                 _CrtSetReportFile(_CRT_ASSERT,  hLogFile);\r
238         #endif\r
239 \r
240         // Increase process priotity.\r
241         SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS);\r
242 \r
243         // Install structured exception handler.\r
244         caspar::win32_exception::ensure_handler_installed_for_thread("main-thread");\r
245                                 \r
246         // Increase time precision. This will increase accuracy of function like Sleep(1) from 10 ms to 1 ms.\r
247         struct inc_prec\r
248         {\r
249                 inc_prec(){timeBeginPeriod(1);}\r
250                 ~inc_prec(){timeEndPeriod(1);}\r
251         } inc_prec;     \r
252 \r
253         // Install unstructured exception handlers into all tbb threads.\r
254         struct tbb_thread_installer : public tbb::task_scheduler_observer\r
255         {\r
256                 tbb_thread_installer(){observe(true);}\r
257                 void on_scheduler_entry(bool is_worker)\r
258                 {\r
259                         caspar::win32_exception::ensure_handler_installed_for_thread("tbb-worker-thread");\r
260                 }\r
261         } tbb_thread_installer;\r
262 \r
263         bool restart = false;\r
264         tbb::task_scheduler_init init;\r
265         std::wstring config_file_name(L"casparcg.config");\r
266         \r
267         try \r
268         {\r
269                 // Configure environment properties from configuration.\r
270                 if (argc >= 2)\r
271                 {\r
272                         config_file_name = caspar::widen(argv[1]);\r
273                 }\r
274 \r
275                 caspar::env::configure(config_file_name);\r
276                                 \r
277                 caspar::log::set_log_level(caspar::env::properties().get(L"configuration.log-level", L"debug"));\r
278 \r
279         #ifdef _DEBUG\r
280                 if(caspar::env::properties().get(L"configuration.debugging.remote", false))\r
281                         MessageBox(nullptr, TEXT("Now is the time to connect for remote debugging..."), TEXT("Debug"), MB_OK | MB_TOPMOST);\r
282         #endif   \r
283 \r
284                 // Start logging to file.\r
285                 caspar::log::add_file_sink(caspar::env::log_folder());                  \r
286                 std::wcout << L"Logging [info] or higher severity to " << caspar::env::log_folder() << std::endl << std::endl;\r
287                 \r
288                 // Setup console window.\r
289                 setup_console_window();\r
290 \r
291                 // Print environment information.\r
292                 print_info();\r
293                         \r
294                 std::wstringstream str;\r
295                 boost::property_tree::xml_writer_settings<wchar_t> w(' ', 3);\r
296                 boost::property_tree::write_xml(str, caspar::env::properties(), w);\r
297                 CASPAR_LOG(info) << config_file_name << L":\n-----------------------------------------\n" << str.str().c_str() << L"-----------------------------------------";\r
298                 tbb::atomic<bool> wait_for_keypress;\r
299                 wait_for_keypress = false;\r
300 \r
301                 {\r
302                         init_t html_init(L"html", nullptr, caspar::html::uninit);\r
303 \r
304                         boost::promise<bool> shutdown_server_now;\r
305                         boost::unique_future<bool> shutdown_server = shutdown_server_now.get_future();\r
306 \r
307                         // Create server object which initializes channels, protocols and controllers.\r
308                         caspar::server caspar_server(shutdown_server_now);\r
309 \r
310                         // Use separate thread for the blocking console input, will be terminated \r
311                         // anyway when the main thread terminates.\r
312                         boost::thread stdin_thread([&caspar_server, &shutdown_server_now, &wait_for_keypress]\r
313                         {\r
314                                 caspar::win32_exception::ensure_handler_installed_for_thread("stdin-thread");\r
315 \r
316                                 // Create a amcp parser for console commands.\r
317                                 caspar::protocol::amcp::AMCPProtocolStrategy amcp(\r
318                                                 L"Console",\r
319                                                 caspar_server.get_channels(),\r
320                                                 caspar_server.get_thumbnail_generator(),\r
321                                                 caspar_server.get_media_info_repo(),\r
322                                                 caspar_server.get_ogl_device(),\r
323                                                 shutdown_server_now);\r
324 \r
325                                 // Create a dummy client which prints amcp responses to console.\r
326                                 auto console_client = std::make_shared<caspar::IO::ConsoleClientInfo>();\r
327                                 std::wstring wcmd;\r
328         \r
329                                 while(true)\r
330                                 {\r
331                                         std::getline(std::wcin, wcmd); // TODO: It's blocking...\r
332                                 \r
333                                         //boost::to_upper(wcmd);  // TODO COMPILER crashes on this line, Strange!\r
334                                         auto upper_cmd = make_upper_case(wcmd);\r
335 \r
336                                         if(upper_cmd == L"EXIT" || upper_cmd == L"Q" || upper_cmd == L"QUIT" || upper_cmd == L"BYE")\r
337                                         {\r
338                                                 wait_for_keypress = true;\r
339                                                 shutdown_server_now.set_value(false); // False to not restart server\r
340                                                 break;\r
341                                         }\r
342                                 \r
343                                         try\r
344                                         {\r
345                                                 // This is just dummy code for testing.\r
346                                                 if(wcmd.substr(0, 1) == L"1")\r
347                                                         wcmd = L"LOADBG 1-1 " + wcmd.substr(1, wcmd.length()-1) + L" SLIDE 100 LOOP \r\nPLAY 1-1";\r
348                                                 else if(wcmd.substr(0, 1) == L"2")\r
349                                                         wcmd = L"MIXER 1-0 VIDEO IS_KEY 1";\r
350                                                 else if(wcmd.substr(0, 1) == L"3")\r
351                                                         wcmd = L"CG 1-2 ADD 1 BBTELEFONARE 1";\r
352                                                 else if(wcmd.substr(0, 1) == L"4")\r
353                                                         wcmd = L"PLAY 1-1 DV FILTER yadif=1:-1 LOOP";\r
354                                                 else if(wcmd.substr(0, 1) == L"5")\r
355                                                 {\r
356                                                         auto file = wcmd.substr(2, wcmd.length()-1);\r
357                                                         wcmd = L"PLAY 1-1 " + file + L" LOOP\r\n" \r
358                                                                         L"PLAY 1-2 " + file + L" LOOP\r\n" \r
359                                                                         L"PLAY 1-3 " + file + L" LOOP\r\n"\r
360                                                                         L"PLAY 2-1 " + file + L" LOOP\r\n" \r
361                                                                         L"PLAY 2-2 " + file + L" LOOP\r\n" \r
362                                                                         L"PLAY 2-3 " + file + L" LOOP\r\n";\r
363                                                 }\r
364                                                 else if(upper_cmd.substr(0, 1) == L"X")\r
365                                                 {\r
366                                                         int num = 0;\r
367                                                         std::wstring file;\r
368                                                         try\r
369                                                         {\r
370                                                                 num = boost::lexical_cast<int>(wcmd.substr(1, 2));\r
371                                                                 file = wcmd.substr(4, wcmd.length()-1);\r
372                                                         }\r
373                                                         catch(...)\r
374                                                         {\r
375                                                                 num = boost::lexical_cast<int>(wcmd.substr(1, 1));\r
376                                                                 file = wcmd.substr(3, wcmd.length()-1);\r
377                                                         }\r
378 \r
379                                                         int n = 0;\r
380                                                         int num2 = num;\r
381                                                         while(num2 > 0)\r
382                                                         {\r
383                                                                 num2 >>= 1;\r
384                                                                 n++;\r
385                                                         }\r
386 \r
387                                                         wcmd = L"MIXER 1 GRID " + boost::lexical_cast<std::wstring>(n);\r
388 \r
389                                                         for(int i = 1; i <= num; ++i)\r
390                                                                 wcmd += L"\r\nPLAY 1-" + boost::lexical_cast<std::wstring>(i) + L" " + file + L" LOOP";// + L" SLIDE 100 LOOP";\r
391                                                 }\r
392                                         }\r
393                                         catch (...)\r
394                                         {\r
395                                                 CASPAR_LOG_CURRENT_EXCEPTION();\r
396                                                 continue;\r
397                                         }\r
398 \r
399                                         wcmd += L"\r\n";\r
400                                         amcp.Parse(wcmd.c_str(), wcmd.length(), console_client);\r
401                                 }       \r
402                         });\r
403                         stdin_thread.detach();\r
404                         restart = shutdown_server.get();\r
405                 }\r
406                 Sleep(500);\r
407                 CASPAR_LOG(info) << "Successfully shutdown CasparCG Server.";\r
408 \r
409                 if (wait_for_keypress)\r
410                         system("pause");        \r
411         }\r
412         catch(boost::property_tree::file_parser_error&)\r
413         {\r
414                 CASPAR_LOG_CURRENT_EXCEPTION();\r
415                 CASPAR_LOG(fatal) << L"Unhandled configuration error in main thread. Please check the configuration file (" << config_file_name << L") for errors.";\r
416                 system("pause");        \r
417         }\r
418         catch(...)\r
419         {\r
420                 CASPAR_LOG_CURRENT_EXCEPTION();\r
421                 CASPAR_LOG(fatal) << L"Unhandled exception in main thread. Please report this error on the CasparCG forums (www.casparcg.com/forum).";\r
422                 Sleep(1000);\r
423                 std::wcout << L"\n\nCasparCG will automatically shutdown. See the log file located at the configured log-file folder for more information.\n\n";\r
424                 Sleep(4000);\r
425         }       \r
426         \r
427         return restart ? 5 : 0;\r
428 }