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