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