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