]> git.sesse.net Git - casparcg/blob - shell/main.cpp
Manually merged 44adc50 from master
[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/util/strategy_adapters.h>
46 #include <protocol/amcp/AMCPProtocolStrategy.h>
47 #include <protocol/osc/server.h>
48
49 #include <modules/bluefish/bluefish.h>
50 #include <modules/decklink/decklink.h>
51 #include <modules/flash/flash.h>
52 #include <modules/ffmpeg/ffmpeg.h>
53 #include <modules/image/image.h>
54
55 #include <common/env.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 #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 <signal.h>
75
76 using namespace caspar;
77         
78 // NOTE: This is needed in order to make CComObject work since this is not a real ATL project.
79 CComModule _AtlModule;
80 extern __declspec(selectany) CAtlModule* _pAtlModule = &_AtlModule;
81
82 void change_icon( const HICON hNewIcon )
83 {
84    auto hMod = ::LoadLibrary(L"Kernel32.dll"); 
85    typedef DWORD(__stdcall *SCI)(HICON);
86    auto pfnSetConsoleIcon = reinterpret_cast<SCI>(::GetProcAddress(hMod, "SetConsoleIcon")); 
87    pfnSetConsoleIcon(hNewIcon); 
88    ::FreeLibrary(hMod);
89 }
90
91 void setup_global_locale()
92 {
93         boost::locale::generator gen;
94         gen.categories(boost::locale::codepage_facet);
95
96         std::locale::global(gen(""));
97 }
98
99 void setup_console_window()
100 {        
101         auto hOut = GetStdHandle(STD_OUTPUT_HANDLE);
102
103         // Disable close button in console to avoid shutdown without cleanup.
104         EnableMenuItem(GetSystemMenu(GetConsoleWindow(), FALSE), SC_CLOSE , MF_GRAYED);
105         DrawMenuBar(GetConsoleWindow());
106         //SetConsoleCtrlHandler(HandlerRoutine, true);
107
108         // Configure console size and position.
109         auto coord = GetLargestConsoleWindowSize(hOut);
110         coord.X /= 2;
111
112         SetConsoleScreenBufferSize(hOut, coord);
113
114         SMALL_RECT DisplayArea = {0, 0, 0, 0};
115         DisplayArea.Right = coord.X-1;
116         DisplayArea.Bottom = (coord.Y-1)/2;
117         SetConsoleWindowInfo(hOut, TRUE, &DisplayArea);
118                  
119         change_icon(::LoadIcon(GetModuleHandle(0), MAKEINTRESOURCE(101)));
120
121         // Set console title.
122         std::wstringstream str;
123         str << "CasparCG Server " << env::version() << L" x64 ";
124 #ifdef COMPILE_RELEASE
125         str << " Release";
126 #elif  COMPILE_PROFILE
127         str << " Profile";
128 #elif  COMPILE_DEVELOP
129         str << " Develop";
130 #elif  COMPILE_DEBUG
131         str << " Debug";
132 #endif
133         SetConsoleTitle(str.str().c_str());
134 }
135
136 void print_info()
137 {
138         CASPAR_LOG(info) << L"############################################################################";
139         CASPAR_LOG(info) << L"CasparCG Server is distributed by the Swedish Broadcasting Corporation (SVT)";
140         CASPAR_LOG(info) << L"under the GNU General Public License GPLv3 or higher.";
141         CASPAR_LOG(info) << L"Please see LICENSE.TXT for details.";
142         CASPAR_LOG(info) << L"http://www.casparcg.com/";
143         CASPAR_LOG(info) << L"############################################################################";
144         CASPAR_LOG(info) << L"Starting CasparCG Video and Graphics Playout Server " << env::version();
145         CASPAR_LOG(info) << L"on " << win_product_name() << L" " << win_sp_version();
146         CASPAR_LOG(info) << cpu_info();
147         CASPAR_LOG(info) << system_product_name();
148         
149         CASPAR_LOG(info) << L"Decklink " << decklink::version();
150         BOOST_FOREACH(auto device, decklink::device_list())
151                 CASPAR_LOG(info) << L" - " << device;   
152                 
153         CASPAR_LOG(info) << L"Bluefish " << bluefish::version();
154         BOOST_FOREACH(auto device, bluefish::device_list())
155                 CASPAR_LOG(info) << L" - " << device;   
156         
157         CASPAR_LOG(info) << L"Flash "                   << flash::version();
158         CASPAR_LOG(info) << L"FreeImage "               << image::version();
159         CASPAR_LOG(info) << L"FFMPEG-avcodec "  << ffmpeg::avcodec_version();
160         CASPAR_LOG(info) << L"FFMPEG-avformat " << ffmpeg::avformat_version();
161         CASPAR_LOG(info) << L"FFMPEG-avfilter " << ffmpeg::avfilter_version();
162         CASPAR_LOG(info) << L"FFMPEG-avutil "   << ffmpeg::avutil_version();
163         CASPAR_LOG(info) << L"FFMPEG-swscale "  << ffmpeg::swscale_version();
164 }
165
166 LONG WINAPI UserUnhandledExceptionFilter(EXCEPTION_POINTERS* info)
167 {
168         try
169         {
170                 CASPAR_LOG(fatal) << L"#######################\n UNHANDLED EXCEPTION: \n" 
171                         << L"Adress:" << info->ExceptionRecord->ExceptionAddress << L"\n"
172                         << L"Code:" << info->ExceptionRecord->ExceptionCode << L"\n"
173                         << L"Flag:" << info->ExceptionRecord->ExceptionFlags << L"\n"
174                         << L"Info:" << info->ExceptionRecord->ExceptionInformation << L"\n"
175                         << L"Continuing execution. \n#######################";
176
177                 CASPAR_LOG_CALL_STACK();
178         }
179         catch(...){}
180
181         return EXCEPTION_CONTINUE_EXECUTION;
182 }
183
184 void do_run(server& caspar_server, boost::promise<bool>& shutdown_server_now)
185 {
186         // Create a dummy client which prints amcp responses to console.
187         auto console_client = spl::make_shared<IO::ConsoleClientInfo>();
188         
189         // Create a amcp parser for console commands.
190         //protocol::amcp::AMCPProtocolStrategy amcp(caspar_server.channels());
191         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);
192
193         std::wstring wcmd;
194         while(true)
195         {
196                 std::getline(std::wcin, wcmd); // TODO: It's blocking...
197                                 
198                 //boost::to_upper(wcmd);
199
200                 if(boost::iequals(wcmd, L"EXIT") || boost::iequals(wcmd, L"Q") || boost::iequals(wcmd, L"QUIT") || boost::iequals(wcmd, L"BYE"))
201                 {
202                         shutdown_server_now.set_value(true);    //true to wait for keypress
203                         break;
204                 }
205
206                 try
207                 {
208                         // This is just dummy code for testing.
209                         if(wcmd.substr(0, 1) == L"1")
210                                 wcmd = L"LOADBG 1-1 " + wcmd.substr(1, wcmd.length()-1) + L" SLIDE 100 LOOP \r\nPLAY 1-1";
211                         else if(wcmd.substr(0, 1) == L"2")
212                                 wcmd = L"MIXER 1-0 VIDEO IS_KEY 1";
213                         else if(wcmd.substr(0, 1) == L"3")
214                                 wcmd = L"CG 1-2 ADD 1 BBTELEFONARE 1";
215                         else if(wcmd.substr(0, 1) == L"4")
216                                 wcmd = L"PLAY 1-1 DV FILTER yadif=1:-1 LOOP";
217                         else if(wcmd.substr(0, 1) == L"5")
218                         {
219                                 auto file = wcmd.substr(2, wcmd.length()-1);
220                                 wcmd = L"PLAY 1-1 " + file + L" LOOP\r\n" 
221                                                 L"PLAY 1-2 " + file + L" LOOP\r\n" 
222                                                 L"PLAY 1-3 " + file + L" LOOP\r\n"
223                                                 L"PLAY 2-1 " + file + L" LOOP\r\n" 
224                                                 L"PLAY 2-2 " + file + L" LOOP\r\n" 
225                                                 L"PLAY 2-3 " + file + L" LOOP\r\n";
226                         }
227                         else if(wcmd.substr(0, 1) == L"7")
228                         {
229                                 wcmd = L"";
230                                 wcmd += L"CLEAR 1\r\n";
231                                 wcmd += L"MIXER 1 CLEAR\r\n";
232                                 wcmd += L"PLAY 1-0 GREEN\r\n";
233                                 wcmd += L"PLAY 1-1 BLUE\r\n";
234                                 wcmd += L"CG 1-2 ADD 1 ECS_TEST 1\r\n";
235                                 wcmd += L"MIXER 1-2 FILL 0 -1 1 2\r\n";
236                         }
237                         else if(wcmd.substr(0, 1) == L"8")
238                         {
239                                 wcmd = L"";
240                                 wcmd += L"MIXER 1-1 FILL 0.0 0.5 1.0 1.0 500 linear DEFER\r\n";
241                                 wcmd += L"MIXER 1-2 FILL 0.0 0.0 1.0 1.0 500 linear DEFER\r\n";
242                                 wcmd += L"MIXER 1 COMMIT\r\n";
243                         }
244                         else if(wcmd.substr(0, 1) == L"X")
245                         {
246                                 int num = 0;
247                                 std::wstring file;
248                                 try
249                                 {
250                                         num = boost::lexical_cast<int>(wcmd.substr(1, 2));
251                                         file = wcmd.substr(4, wcmd.length()-1);
252                                 }
253                                 catch(...)
254                                 {
255                                         num = boost::lexical_cast<int>(wcmd.substr(1, 1));
256                                         file = wcmd.substr(3, wcmd.length()-1);
257                                 }
258
259                                 int n = 0;
260                                 int num2 = num;
261                                 while(num2 > 0)
262                                 {
263                                         num2 >>= 1;
264                                         n++;
265                                 }
266
267                                 wcmd = L"MIXER 1 GRID " + boost::lexical_cast<std::wstring>(n);
268
269                                 for(int i = 1; i <= num; ++i)
270                                         wcmd += L"\r\nPLAY 1-" + boost::lexical_cast<std::wstring>(i) + L" " + file + L" LOOP";// + L" SLIDE 100 LOOP";
271                         }
272                 }
273                 catch (...)
274                 {
275                         CASPAR_LOG_CURRENT_EXCEPTION();
276                         continue;
277                 }
278
279                 wcmd += L"\r\n";
280                 amcp->parse(wcmd);
281         }
282 };
283
284 bool run()
285 {
286         boost::promise<bool> shutdown_server_now;
287         boost::unique_future<bool> shutdown_server = shutdown_server_now.get_future();
288
289         // Create server object which initializes channels, protocols and controllers.
290         server caspar_server(shutdown_server_now);
291                                 
292         auto server = spl::make_shared<protocol::osc::server>(5253);
293         caspar_server.subscribe(server);
294                                                 
295         //auto console_obs = reactive::make_observer([](const monitor::event& e)
296         //{
297         //      std::stringstream str;
298         //      str << e;
299         //      CASPAR_LOG(trace) << str.str().c_str();
300         //});
301
302         //caspar_server.subscribe(console_obs);
303
304
305         // Use separate thread for the blocking console input, will be terminated 
306         // anyway when the main thread terminates.
307         boost::thread stdin_thread(std::bind(do_run, std::ref(caspar_server), std::ref(shutdown_server_now)));  //compiler didn't like lambda here...
308         stdin_thread.detach();
309         return shutdown_server.get();
310 }
311
312 void on_abort(int)
313 {
314         CASPAR_THROW_EXCEPTION(invalid_operation() << msg_info("abort called"));
315 }
316
317 int main(int argc, wchar_t* argv[])
318 {       
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<wchar_t> 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                 auto wait = run();
395                 
396                 Sleep(500);
397                 CASPAR_LOG(info) << "Successfully shutdown CasparCG Server.";
398
399                 if(wait) system("pause");       
400         }
401         catch(boost::property_tree::file_parser_error&)
402         {
403                 CASPAR_LOG_CURRENT_EXCEPTION();
404                 CASPAR_LOG(fatal) << L"Unhandled configuration error in main thread. Please check the configuration file (casparcg.config) for errors.";
405                 system("pause");        
406         }
407         catch(...)
408         {
409                 CASPAR_LOG_CURRENT_EXCEPTION();
410                 CASPAR_LOG(fatal) << L"Unhandled exception in main thread. Please report this error on the CasparCG forums (www.casparcg.com/forum).";
411                 Sleep(1000);
412                 std::wcout << L"\n\nCasparCG will automatically shutdown. See the log file located at the configured log-file folder for more information.\n\n";
413                 Sleep(4000);
414         }               
415         
416         return 0;
417 }