]> git.sesse.net Git - casparcg/blob - protocol/amcp/AMCPCommandsImpl.cpp
Made the server more portable
[casparcg] / protocol / amcp / AMCPCommandsImpl.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: Nicklas P Andersson
20 */
21
22 #include "../StdAfx.h"
23
24 #if defined(_MSC_VER)
25 #pragma warning (push, 1) // TODO: Legacy code, just disable warnings
26 #endif
27
28 #include "AMCPCommandsImpl.h"
29 #include "AMCPProtocolStrategy.h"
30
31 #include <common/env.h>
32
33 #include <common/log.h>
34 #include <common/param.h>
35 #include <common/os/system_info.h>
36 #include <common/base64.h>
37
38 #include <core/producer/frame_producer.h>
39 #include <core/video_format.h>
40 #include <core/producer/transition/transition_producer.h>
41 #include <core/frame/frame_transform.h>
42 #include <core/producer/stage.h>
43 #include <core/producer/layer.h>
44 #include <core/mixer/mixer.h>
45 #include <core/consumer/output.h>
46 #include <core/thumbnail_generator.h>
47 #include <core/diagnostics/call_context.h>
48 #include <core/diagnostics/osd_graph.h>
49
50 #include <modules/reroute/producer/reroute_producer.h>
51 #include <modules/bluefish/bluefish.h>
52 #include <modules/decklink/decklink.h>
53 #include <modules/ffmpeg/ffmpeg.h>
54 #include <modules/flash/flash.h>
55 #include <modules/flash/util/swf.h>
56 #include <modules/flash/producer/flash_producer.h>
57 #include <modules/flash/producer/cg_proxy.h>
58 #include <modules/ffmpeg/producer/util/util.h>
59 #include <modules/screen/screen.h>
60 #include <modules/reroute/producer/reroute_producer.h>
61
62 #include <algorithm>
63 #include <locale>
64 #include <fstream>
65 #include <memory>
66 #include <cctype>
67 //#include <io.h>
68 #include <future>
69
70 #include <boost/date_time/posix_time/posix_time.hpp>
71 #include <boost/lexical_cast.hpp>
72 #include <boost/algorithm/string.hpp>
73 #include <boost/filesystem.hpp>
74 #include <boost/filesystem/fstream.hpp>
75 #include <boost/regex.hpp>
76 #include <boost/property_tree/xml_parser.hpp>
77 #include <boost/locale.hpp>
78 #include <boost/range/adaptor/transformed.hpp>
79 #include <boost/range/algorithm/copy.hpp>
80 #include <boost/archive/iterators/base64_from_binary.hpp>
81 #include <boost/archive/iterators/insert_linebreaks.hpp>
82 #include <boost/archive/iterators/transform_width.hpp>
83
84 #include <tbb/concurrent_unordered_map.h>
85
86 /* Return codes
87
88 102 [action]                    Information that [action] has happened
89 101 [action]                    Information that [action] has happened plus one row of data  
90
91 202 [command] OK                [command] has been executed
92 201 [command] OK                [command] has been executed, plus one row of data  
93 200 [command] OK                [command] has been executed, plus multiple lines of data. ends with an empty line
94
95 400 ERROR                               the command could not be understood
96 401 [command] ERROR             invalid/missing channel
97 402 [command] ERROR             parameter missing
98 403 [command] ERROR             invalid parameter  
99 404 [command] ERROR             file not found
100
101 500 FAILED                              internal error
102 501 [command] FAILED    internal error
103 502 [command] FAILED    could not read file
104 503 [command] FAILED    access denied
105
106 600 [command] FAILED    [command] not implemented
107 */
108
109 namespace caspar { namespace protocol {
110
111 using namespace core;
112
113 std::wstring read_file_base64(const boost::filesystem::wpath& file)
114 {
115         using namespace boost::archive::iterators;
116
117         boost::filesystem::ifstream filestream(file, std::ios::binary);
118
119         if (!filestream)
120                 return L"";
121
122         auto length = boost::filesystem::file_size(file);
123         std::vector<char> bytes;
124         bytes.resize(length);
125         filestream.read(bytes.data(), length);
126
127         std::string result(to_base64(bytes.data(), length));
128         return std::wstring(result.begin(), result.end());
129 }
130
131 std::wstring read_utf8_file(const boost::filesystem::wpath& file)
132 {
133         std::wstringstream result;
134         boost::filesystem::wifstream filestream(file);
135
136         if (filestream) 
137         {
138                 // Consume BOM first
139                 filestream.get();
140                 // read all data
141                 result << filestream.rdbuf();
142         }
143
144         return result.str();
145 }
146
147 std::wstring read_latin1_file(const boost::filesystem::wpath& file)
148 {
149         boost::locale::generator gen;
150         gen.locale_cache_enabled(true);
151         gen.categories(boost::locale::codepage_facet);
152
153         std::stringstream result_stream;
154         boost::filesystem::ifstream filestream(file);
155         filestream.imbue(gen("en_US.ISO8859-1"));
156
157         if (filestream)
158         {
159                 // read all data
160                 result_stream << filestream.rdbuf();
161         }
162
163         std::string result = result_stream.str();
164         std::wstring widened_result;
165
166         // The first 255 codepoints in unicode is the same as in latin1
167         boost::copy(
168                 result | boost::adaptors::transformed(
169                                 [](char c) { return static_cast<unsigned char>(c); }),
170                 std::back_inserter(widened_result));
171
172         return widened_result;
173 }
174
175 std::wstring read_file(const boost::filesystem::wpath& file)
176 {
177         static const uint8_t BOM[] = {0xef, 0xbb, 0xbf};
178
179         if (!boost::filesystem::exists(file))
180         {
181                 return L"";
182         }
183
184         if (boost::filesystem::file_size(file) >= 3)
185         {
186                 boost::filesystem::ifstream bom_stream(file);
187
188                 char header[3];
189                 bom_stream.read(header, 3);
190                 bom_stream.close();
191
192                 if (std::memcmp(BOM, header, 3) == 0)
193                         return read_utf8_file(file);
194         }
195
196         return read_latin1_file(file);
197 }
198
199 std::wstring MediaInfo(const boost::filesystem::path& path)
200 {
201         if(boost::filesystem::is_regular_file(path))
202         {
203                 std::wstring clipttype = L"N/A";
204                 std::wstring extension = boost::to_upper_copy(path.extension().wstring());
205                 if(extension == L".TGA" || extension == L".COL" || extension == L".PNG" || extension == L".JPEG" || extension == L".JPG" ||
206                         extension == L"GIF" || extension == L"BMP")
207                         clipttype = L"STILL";
208                 else if(extension == L".WAV" || extension == L".MP3")
209                         clipttype = L"AUDIO";
210                 else if(extension == L"SWF" || extension == L"CT" || extension == L"DV" || extension == L"MOV" || extension == L"MPG" || extension == L"AVI" || caspar::ffmpeg::is_valid_file(path.wstring()))
211                         clipttype = L"MOVIE";
212
213                 if(clipttype != L"N/A")
214                 {               
215                         auto is_not_digit = [](char c){ return std::isdigit(c) == 0; };
216
217                         auto relativePath = boost::filesystem::path(path.wstring().substr(env::media_folder().size()-1, path.wstring().size()));
218
219                         auto writeTimeStr = boost::posix_time::to_iso_string(boost::posix_time::from_time_t(boost::filesystem::last_write_time(path)));
220                         writeTimeStr.erase(std::remove_if(writeTimeStr.begin(), writeTimeStr.end(), is_not_digit), writeTimeStr.end());
221                         auto writeTimeWStr = std::wstring(writeTimeStr.begin(), writeTimeStr.end());
222
223                         auto sizeStr = boost::lexical_cast<std::wstring>(boost::filesystem::file_size(path));
224                         sizeStr.erase(std::remove_if(sizeStr.begin(), sizeStr.end(), is_not_digit), sizeStr.end());
225                         auto sizeWStr = std::wstring(sizeStr.begin(), sizeStr.end());
226                                 
227                         auto str = relativePath.replace_extension(L"").generic_wstring();
228                         while(str.size() > 0 && (str[0] == L'\\' || str[0] == L'/'))
229                                 str = std::wstring(str.begin() + 1, str.end());
230
231                         return std::wstring() + L"\"" + str +
232                                         + L"\" " + clipttype +
233                                         + L" " + sizeStr +
234                                         + L" " + writeTimeWStr +
235                                         + L"\r\n";
236                 }       
237         }
238         return L"";
239 }
240
241 std::wstring ListMedia()
242 {       
243         std::wstringstream replyString;
244         for (boost::filesystem::recursive_directory_iterator itr(env::media_folder()), end; itr != end; ++itr)  
245                 replyString << MediaInfo(itr->path());
246         
247         return boost::to_upper_copy(replyString.str());
248 }
249
250 std::wstring ListTemplates() 
251 {
252         std::wstringstream replyString;
253
254         for (boost::filesystem::recursive_directory_iterator itr(env::template_folder()), end; itr != end; ++itr)
255         {               
256                 if(boost::filesystem::is_regular_file(itr->path()) && (itr->path().extension() == L".ft" || itr->path().extension() == L".ct"))
257                 {
258                         auto relativePath = boost::filesystem::wpath(itr->path().wstring().substr(env::template_folder().size()-1, itr->path().wstring().size()));
259
260                         auto writeTimeStr = boost::posix_time::to_iso_string(boost::posix_time::from_time_t(boost::filesystem::last_write_time(itr->path())));
261                         writeTimeStr.erase(std::remove_if(writeTimeStr.begin(), writeTimeStr.end(), [](char c){ return std::isdigit(c) == 0;}), writeTimeStr.end());
262                         auto writeTimeWStr = std::wstring(writeTimeStr.begin(), writeTimeStr.end());
263
264                         auto sizeStr = boost::lexical_cast<std::string>(boost::filesystem::file_size(itr->path()));
265                         sizeStr.erase(std::remove_if(sizeStr.begin(), sizeStr.end(), [](char c){ return std::isdigit(c) == 0;}), sizeStr.end());
266
267                         auto sizeWStr = std::wstring(sizeStr.begin(), sizeStr.end());
268
269                         std::wstring dir = relativePath.parent_path().generic_wstring();
270                         std::wstring file = boost::to_upper_copy(relativePath.filename().wstring());
271                         relativePath = boost::filesystem::wpath(dir + L"/" + file);
272                                                 
273                         auto str = relativePath.replace_extension(L"").generic_wstring();
274                         boost::trim_if(str, boost::is_any_of("\\/"));
275
276                         replyString << L"\"" << str
277                                                 << L"\" " << sizeWStr
278                                                 << L" " << writeTimeWStr
279                                                 << L"\r\n";
280                 }
281         }
282         return replyString.str();
283 }
284
285 namespace amcp {
286         
287 void AMCPCommand::SendReply()
288 {
289         if(replyString_.empty())
290                 return;
291
292         client_->send(std::move(replyString_));
293 }
294
295 bool DiagnosticsCommand::DoExecute()
296 {       
297         try
298         {
299                 core::diagnostics::osd::show_graphs(true);
300
301                 SetReplyString(L"202 DIAG OK\r\n");
302
303                 return true;
304         }
305         catch(...)
306         {
307                 CASPAR_LOG_CURRENT_EXCEPTION();
308                 SetReplyString(L"502 DIAG FAILED\r\n");
309                 return false;
310         }
311 }
312
313 bool ChannelGridCommand::DoExecute()
314 {
315         int index = 1;
316         auto self = channels().back().channel;
317         
318         core::diagnostics::scoped_call_context save;
319         core::diagnostics::call_context::for_thread().video_channel = channels().size();
320
321         std::vector<std::wstring> params;
322         params.push_back(L"SCREEN");
323         params.push_back(L"0");
324         params.push_back(L"NAME");
325         params.push_back(L"Channel Grid Window");
326         auto screen = create_consumer(params);
327
328         self->output().add(screen);
329
330         for (auto& channel : channels())
331         {
332                 if(channel.channel != self)
333                 {
334                         core::diagnostics::call_context::for_thread().layer = index;
335                         auto producer = reroute::create_producer(*channel.channel);
336                         self->stage().load(index, producer, false);
337                         self->stage().play(index);
338                         index++;
339                 }
340         }
341
342         int n = channels().size()-1;
343         double delta = 1.0/static_cast<double>(n);
344         for(int x = 0; x < n; ++x)
345         {
346                 for(int y = 0; y < n; ++y)
347                 {
348                         int index = x+y*n+1;
349                         auto transform = [=](frame_transform transform) -> frame_transform
350                         {               
351                                 transform.image_transform.fill_translation[0]   = x*delta;
352                                 transform.image_transform.fill_translation[1]   = y*delta;
353                                 transform.image_transform.fill_scale[0]                 = delta;
354                                 transform.image_transform.fill_scale[1]                 = delta;
355                                 transform.image_transform.clip_translation[0]   = x*delta;
356                                 transform.image_transform.clip_translation[1]   = y*delta;
357                                 transform.image_transform.clip_scale[0]                 = delta;
358                                 transform.image_transform.clip_scale[1]                 = delta;                        
359                                 return transform;
360                         };
361                         self->stage().apply_transform(index, transform);
362                 }
363         }
364
365         return true;
366 }
367
368 bool CallCommand::DoExecute()
369 {       
370         //Perform loading of the clip
371         try
372         {
373                 auto result = channel()->stage().call(layer_index(), parameters());
374                 
375                 // TODO: because of std::async deferred timed waiting does not work
376
377                 /*auto wait_res = result.wait_for(std::chrono::seconds(2));
378                 if (wait_res == std::future_status::timeout)
379                         CASPAR_THROW_EXCEPTION(timed_out());*/
380                                 
381                 std::wstringstream replyString;
382                 if(result.get().empty())
383                         replyString << L"202 CALL OK\r\n";
384                 else
385                         replyString << L"201 CALL OK\r\n" << result.get() << L"\r\n";
386                 
387                 SetReplyString(replyString.str());
388
389                 return true;
390         }
391         catch(...)
392         {
393                 CASPAR_LOG_CURRENT_EXCEPTION();
394                 SetReplyString(L"502 CALL FAILED\r\n");
395                 return false;
396         }
397 }
398
399 tbb::concurrent_unordered_map<int, std::vector<stage::transform_tuple_t>> deferred_transforms;
400
401 bool MixerCommand::DoExecute()
402 {       
403         //Perform loading of the clip
404         try
405         {       
406                 bool defer = boost::iequals(parameters().back(), L"DEFER");
407                 if(defer)
408                         parameters().pop_back();
409
410                 std::vector<stage::transform_tuple_t> transforms;
411
412                 if(boost::iequals(parameters()[0], L"KEYER") || boost::iequals(parameters()[0], L"IS_KEY"))
413                 {
414                         bool value = boost::lexical_cast<int>(parameters().at(1));
415                         transforms.push_back(stage::transform_tuple_t(layer_index(), [=](frame_transform transform) -> frame_transform
416                         {
417                                 transform.image_transform.is_key = value;
418                                 return transform;                                       
419                         }, 0, L"linear"));
420                 }
421                 else if(boost::iequals(parameters()[0], L"OPACITY"))
422                 {
423                         int duration = parameters().size() > 2 ? boost::lexical_cast<int>(parameters()[2]) : 0;
424                         std::wstring tween = parameters().size() > 3 ? parameters()[3] : L"linear";
425
426                         double value = boost::lexical_cast<double>(parameters().at(1));
427                         
428                         transforms.push_back(stage::transform_tuple_t(layer_index(), [=](frame_transform transform) -> frame_transform
429                         {
430                                 transform.image_transform.opacity = value;
431                                 return transform;                                       
432                         }, duration, tween));
433                 }
434                 else if(boost::iequals(parameters()[0], L"FILL") || boost::iequals(parameters()[0], L"FILL_RECT"))
435                 {
436                         int duration = parameters().size() > 5 ? boost::lexical_cast<int>(parameters()[5]) : 0;
437                         std::wstring tween = parameters().size() > 6 ? parameters()[6] : L"linear";
438                         double x        = boost::lexical_cast<double>(parameters().at(1));
439                         double y        = boost::lexical_cast<double>(parameters().at(2));
440                         double x_s      = boost::lexical_cast<double>(parameters().at(3));
441                         double y_s      = boost::lexical_cast<double>(parameters().at(4));
442
443                         transforms.push_back(stage::transform_tuple_t(layer_index(), [=](frame_transform transform) mutable -> frame_transform
444                         {
445                                 transform.image_transform.fill_translation[0]   = x;
446                                 transform.image_transform.fill_translation[1]   = y;
447                                 transform.image_transform.fill_scale[0]                 = x_s;
448                                 transform.image_transform.fill_scale[1]                 = y_s;
449                                 return transform;
450                         }, duration, tween));
451                 }
452                 else if(boost::iequals(parameters()[0], L"CLIP") || boost::iequals(parameters()[0], L"CLIP_RECT"))
453                 {
454                         int duration = parameters().size() > 5 ? boost::lexical_cast<int>(parameters()[5]) : 0;
455                         std::wstring tween = parameters().size() > 6 ? parameters()[6] : L"linear";
456                         double x        = boost::lexical_cast<double>(parameters().at(1));
457                         double y        = boost::lexical_cast<double>(parameters().at(2));
458                         double x_s      = boost::lexical_cast<double>(parameters().at(3));
459                         double y_s      = boost::lexical_cast<double>(parameters().at(4));
460
461                         transforms.push_back(stage::transform_tuple_t(layer_index(), [=](frame_transform transform) -> frame_transform
462                         {
463                                 transform.image_transform.clip_translation[0]   = x;
464                                 transform.image_transform.clip_translation[1]   = y;
465                                 transform.image_transform.clip_scale[0]                 = x_s;
466                                 transform.image_transform.clip_scale[1]                 = y_s;
467                                 return transform;
468                         }, duration, tween));
469                 }
470                 else if(boost::iequals(parameters()[0], L"GRID"))
471                 {
472                         int duration = parameters().size() > 2 ? boost::lexical_cast<int>(parameters()[2]) : 0;
473                         std::wstring tween = parameters().size() > 3 ? parameters()[3] : L"linear";
474                         int n = boost::lexical_cast<int>(parameters().at(1));
475                         double delta = 1.0/static_cast<double>(n);
476                         for(int x = 0; x < n; ++x)
477                         {
478                                 for(int y = 0; y < n; ++y)
479                                 {
480                                         int index = x+y*n+1;
481                                         transforms.push_back(stage::transform_tuple_t(index, [=](frame_transform transform) -> frame_transform
482                                         {               
483                                                 transform.image_transform.fill_translation[0]   = x*delta;
484                                                 transform.image_transform.fill_translation[1]   = y*delta;
485                                                 transform.image_transform.fill_scale[0]                 = delta;
486                                                 transform.image_transform.fill_scale[1]                 = delta;
487                                                 transform.image_transform.clip_translation[0]   = x*delta;
488                                                 transform.image_transform.clip_translation[1]   = y*delta;
489                                                 transform.image_transform.clip_scale[0]                 = delta;
490                                                 transform.image_transform.clip_scale[1]                 = delta;                        
491                                                 return transform;
492                                         }, duration, tween));
493                                 }
494                         }
495                 }
496                 else if(boost::iequals(parameters()[0], L"BLEND"))
497                 {
498                         auto blend_str = parameters().at(1);                                                            
499                         int layer = layer_index();
500                         channel()->mixer().set_blend_mode(layer, get_blend_mode(blend_str));    
501                 }
502                 else if(boost::iequals(parameters()[0], L"MASTERVOLUME"))
503                 {
504                         float master_volume = boost::lexical_cast<float>(parameters().at(1));
505                         channel()->mixer().set_master_volume(master_volume);
506                 }
507                 else if(boost::iequals(parameters()[0], L"BRIGHTNESS"))
508                 {
509                         auto value = boost::lexical_cast<double>(parameters().at(1));
510                         int duration = parameters().size() > 2 ? boost::lexical_cast<int>(parameters()[2]) : 0;
511                         std::wstring tween = parameters().size() > 3 ? parameters()[3] : L"linear";
512                         transforms.push_back(stage::transform_tuple_t(layer_index(), [=](frame_transform transform) -> frame_transform
513                         {
514                                 transform.image_transform.brightness = value;
515                                 return transform;
516                         }, duration, tween));
517                 }
518                 else if(boost::iequals(parameters()[0], L"SATURATION"))
519                 {
520                         auto value = boost::lexical_cast<double>(parameters().at(1));
521                         int duration = parameters().size() > 2 ? boost::lexical_cast<int>(parameters()[2]) : 0;
522                         std::wstring tween = parameters().size() > 3 ? parameters()[3] : L"linear";
523                         transforms.push_back(stage::transform_tuple_t(layer_index(), [=](frame_transform transform) -> frame_transform
524                         {
525                                 transform.image_transform.saturation = value;
526                                 return transform;
527                         }, duration, tween));   
528                 }
529                 else if(parameters()[0] == L"CONTRAST")
530                 {
531                         auto value = boost::lexical_cast<double>(parameters().at(1));
532                         int duration = parameters().size() > 2 ? boost::lexical_cast<int>(parameters()[2]) : 0;
533                         std::wstring tween = parameters().size() > 3 ? parameters()[3] : L"linear";
534                         transforms.push_back(stage::transform_tuple_t(layer_index(), [=](frame_transform transform) -> frame_transform
535                         {
536                                 transform.image_transform.contrast = value;
537                                 return transform;
538                         }, duration, tween));   
539                 }
540                 else if(boost::iequals(parameters()[0], L"LEVELS"))
541                 {
542                         levels value;
543                         value.min_input  = boost::lexical_cast<double>(parameters().at(1));
544                         value.max_input  = boost::lexical_cast<double>(parameters().at(2));
545                         value.gamma              = boost::lexical_cast<double>(parameters().at(3));
546                         value.min_output = boost::lexical_cast<double>(parameters().at(4));
547                         value.max_output = boost::lexical_cast<double>(parameters().at(5));
548                         int duration = parameters().size() > 6 ? boost::lexical_cast<int>(parameters()[6]) : 0;
549                         std::wstring tween = parameters().size() > 7 ? parameters()[7] : L"linear";
550
551                         transforms.push_back(stage::transform_tuple_t(layer_index(), [=](frame_transform transform) -> frame_transform
552                         {
553                                 transform.image_transform.levels = value;
554                                 return transform;
555                         }, duration, tween));
556                 }
557                 else if(boost::iequals(parameters()[0], L"VOLUME"))
558                 {
559                         int duration = parameters().size() > 2 ? boost::lexical_cast<int>(parameters()[2]) : 0;
560                         std::wstring tween = parameters().size() > 3 ? parameters()[3] : L"linear";
561                         double value = boost::lexical_cast<double>(parameters()[1]);
562
563                         transforms.push_back(stage::transform_tuple_t(layer_index(), [=](frame_transform transform) -> frame_transform
564                         {
565                                 transform.audio_transform.volume = value;
566                                 return transform;
567                         }, duration, tween));
568                 }
569                 else if(boost::iequals(parameters()[0], L"CLEAR"))
570                 {
571                         int layer = layer_index(std::numeric_limits<int>::max());
572
573                         if (layer == std::numeric_limits<int>::max())
574                         {
575                                 channel()->stage().clear_transforms();
576                                 channel()->mixer().clear_blend_modes();
577                         }
578                         else
579                         {
580                                 channel()->stage().clear_transforms(layer);
581                                 channel()->mixer().clear_blend_mode(layer);
582                         }
583                 }
584                 else if(boost::iequals(parameters()[0], L"COMMIT"))
585                 {
586                         transforms = std::move(deferred_transforms[channel_index()]);
587                 }
588                 else
589                 {
590                         SetReplyString(L"404 MIXER ERROR\r\n");
591                         return false;
592                 }
593
594                 if(defer)
595                 {
596                         auto& defer_tranforms = deferred_transforms[channel_index()];
597                         defer_tranforms.insert(defer_tranforms.end(), transforms.begin(), transforms.end());
598                 }
599                 else
600                         channel()->stage().apply_transforms(transforms);
601         
602                 SetReplyString(L"202 MIXER OK\r\n");
603
604                 return true;
605         }
606         catch(file_not_found&)
607         {
608                 CASPAR_LOG_CURRENT_EXCEPTION();
609                 SetReplyString(L"404 MIXER ERROR\r\n");
610                 return false;
611         }
612         catch(...)
613         {
614                 CASPAR_LOG_CURRENT_EXCEPTION();
615                 SetReplyString(L"502 MIXER FAILED\r\n");
616                 return false;
617         }
618 }
619
620 bool SwapCommand::DoExecute()
621 {       
622         //Perform loading of the clip
623         try
624         {
625                 if(layer_index(-1) != -1)
626                 {
627                         std::vector<std::string> strs;
628                         boost::split(strs, parameters()[0], boost::is_any_of("-"));
629                         
630                         auto ch1 = channel();
631                         auto ch2 = channels().at(boost::lexical_cast<int>(strs.at(0))-1);
632
633                         int l1 = layer_index();
634                         int l2 = boost::lexical_cast<int>(strs.at(1));
635
636                         ch1->stage().swap_layer(l1, l2, ch2.channel->stage());
637                 }
638                 else
639                 {
640                         auto ch1 = channel();
641                         auto ch2 = channels().at(boost::lexical_cast<int>(parameters()[0])-1);
642                         ch1->stage().swap_layers(ch2.channel->stage());
643                 }
644                 
645                 SetReplyString(L"202 SWAP OK\r\n");
646
647                 return true;
648         }
649         catch(file_not_found&)
650         {
651                 CASPAR_LOG_CURRENT_EXCEPTION();
652                 SetReplyString(L"404 SWAP ERROR\r\n");
653                 return false;
654         }
655         catch(...)
656         {
657                 CASPAR_LOG_CURRENT_EXCEPTION();
658                 SetReplyString(L"502 SWAP FAILED\r\n");
659                 return false;
660         }
661 }
662
663 bool AddCommand::DoExecute()
664 {       
665         //Perform loading of the clip
666         try
667         {
668                 //create_consumer still expects all parameters to be uppercase
669                 for (auto& str : parameters())
670                 {
671                         boost::to_upper(str);
672                 }
673
674                 core::diagnostics::scoped_call_context save;
675                 core::diagnostics::call_context::for_thread().video_channel = channel_index() + 1;
676
677                 auto consumer = create_consumer(parameters());
678                 channel()->output().add(layer_index(consumer->index()), consumer);
679         
680                 SetReplyString(L"202 ADD OK\r\n");
681
682                 return true;
683         }
684         catch(file_not_found&)
685         {
686                 CASPAR_LOG_CURRENT_EXCEPTION();
687                 SetReplyString(L"404 ADD ERROR\r\n");
688                 return false;
689         }
690         catch(...)
691         {
692                 CASPAR_LOG_CURRENT_EXCEPTION();
693                 SetReplyString(L"502 ADD FAILED\r\n");
694                 return false;
695         }
696 }
697
698 bool RemoveCommand::DoExecute()
699 {       
700         //Perform loading of the clip
701         try
702         {
703                 auto index = layer_index(std::numeric_limits<int>::min());
704                 if(index == std::numeric_limits<int>::min())
705                 {
706                         //create_consumer still expects all parameters to be uppercase
707                         for (auto& str : parameters())
708                         {
709                                 boost::to_upper(str);
710                         }
711
712                         index = create_consumer(parameters())->index();
713                 }
714
715                 channel()->output().remove(index);
716
717                 SetReplyString(L"202 REMOVE OK\r\n");
718
719                 return true;
720         }
721         catch(file_not_found&)
722         {
723                 CASPAR_LOG_CURRENT_EXCEPTION();
724                 SetReplyString(L"404 REMOVE ERROR\r\n");
725                 return false;
726         }
727         catch(...)
728         {
729                 CASPAR_LOG_CURRENT_EXCEPTION();
730                 SetReplyString(L"502 REMOVE FAILED\r\n");
731                 return false;
732         }
733 }
734
735 bool LoadCommand::DoExecute()
736 {       
737         //Perform loading of the clip
738         try
739         {
740                 core::diagnostics::scoped_call_context save;
741                 core::diagnostics::call_context::for_thread().video_channel = channel_index() + 1;
742                 core::diagnostics::call_context::for_thread().layer = layer_index();
743                 auto pFP = create_producer(channel()->frame_factory(), channel()->video_format_desc(), parameters());
744                 channel()->stage().load(layer_index(), pFP, true);
745         
746                 SetReplyString(L"202 LOAD OK\r\n");
747
748                 return true;
749         }
750         catch(file_not_found&)
751         {
752                 CASPAR_LOG_CURRENT_EXCEPTION();
753                 SetReplyString(L"404 LOAD ERROR\r\n");
754                 return false;
755         }
756         catch(...)
757         {
758                 CASPAR_LOG_CURRENT_EXCEPTION();
759                 SetReplyString(L"502 LOAD FAILED\r\n");
760                 return false;
761         }
762 }
763
764
765
766 //std::function<std::wstring()> channel_cg_add_command::parse(const std::wstring& message, const std::vector<renderer::render_device_ptr>& channels)
767 //{
768 //      static boost::wregex expr(L"^CG\\s(?<video_channel>\\d+)-?(?<LAYER>\\d+)?\\sADD\\s(?<FLASH_LAYER>\\d+)\\s(?<TEMPLATE>\\S+)\\s?(?<START_LABEL>\\S\\S+)?\\s?(?<PLAY_ON_LOAD>\\d)?\\s?(?<DATA>.*)?");
769 //
770 //      boost::wsmatch what;
771 //      if(!boost::regex_match(message, what, expr))
772 //              return nullptr;
773 //
774 //      auto info = channel_info::parse(what, channels);
775 //
776 //      int flash_layer_index = boost::lexical_cast<int>(what["FLASH_LAYER"].str());
777 //
778 //      std::wstring templatename = what["TEMPLATE"].str();
779 //      bool play_on_load = what["PLAY_ON_LOAD"].matched ? what["PLAY_ON_LOAD"].str() != L"0" : 0;
780 //      std::wstring start_label = what["START_LABEL"].str();   
781 //      std::wstring data = get_data(what["DATA"].str());
782 //      
783 //      boost::replace_all(templatename, "\"", "");
784 //
785 //      return [=]() -> std::wstring
786 //      {       
787 //              std::wstring fullFilename = flash::flash_producer::find_template(server::template_folder() + templatename);
788 //              if(fullFilename.empty())
789 //                      CASPAR_THROW_EXCEPTION(file_not_found());
790 //      
791 //              std::wstring extension = boost::filesystem::wpath(fullFilename).extension();
792 //              std::wstring filename = templatename;
793 //              filename.append(extension);
794 //
795 //              flash::flash::create_cg_proxy(info.video_channel, std::max<int>(DEFAULT_CHANNEL_LAYER+1, info.layer_index))
796 //                      ->add(flash_layer_index, filename, play_on_load, start_label, data);
797 //
798 //              CASPAR_LOG(info) << L"Executed [amcp_channel_cg_add]";
799 //              return L"";
800 //      };
801
802 bool LoadbgCommand::DoExecute()
803 {
804         transition_info transitionInfo;
805         
806         // TRANSITION
807
808         std::wstring message;
809         for(size_t n = 0; n < parameters().size(); ++n)
810                 message += boost::to_upper_copy(parameters()[n]) + L" ";
811                 
812         static const boost::wregex expr(LR"(.*(?<TRANSITION>CUT|PUSH|SLIDE|WIPE|MIX)\s*(?<DURATION>\d+)\s*(?<TWEEN>(LINEAR)|(EASE[^\s]*))?\s*(?<DIRECTION>FROMLEFT|FROMRIGHT|LEFT|RIGHT)?.*)");
813         boost::wsmatch what;
814         if(boost::regex_match(message, what, expr))
815         {
816                 auto transition = what["TRANSITION"].str();
817                 transitionInfo.duration = boost::lexical_cast<size_t>(what["DURATION"].str());
818                 auto direction = what["DIRECTION"].matched ? what["DIRECTION"].str() : L"";
819                 auto tween = what["TWEEN"].matched ? what["TWEEN"].str() : L"";
820                 transitionInfo.tweener = tween;         
821
822                 if(transition == L"CUT")
823                         transitionInfo.type = transition_type::cut;
824                 else if(transition == L"MIX")
825                         transitionInfo.type = transition_type::mix;
826                 else if(transition == L"PUSH")
827                         transitionInfo.type = transition_type::push;
828                 else if(transition == L"SLIDE")
829                         transitionInfo.type = transition_type::slide;
830                 else if(transition == L"WIPE")
831                         transitionInfo.type = transition_type::wipe;
832                 
833                 if(direction == L"FROMLEFT")
834                         transitionInfo.direction = transition_direction::from_left;
835                 else if(direction == L"FROMRIGHT")
836                         transitionInfo.direction = transition_direction::from_right;
837                 else if(direction == L"LEFT")
838                         transitionInfo.direction = transition_direction::from_right;
839                 else if(direction == L"RIGHT")
840                         transitionInfo.direction = transition_direction::from_left;
841         }
842         
843         //Perform loading of the clip
844         try
845         {
846                 std::shared_ptr<core::frame_producer> pFP;
847                 
848                 static boost::wregex expr(LR"(\[(?<CHANNEL>\d+)\])", boost::regex::icase);
849                         
850                 core::diagnostics::scoped_call_context save;
851                 core::diagnostics::call_context::for_thread().video_channel = channel_index() + 1;
852                 core::diagnostics::call_context::for_thread().layer = layer_index();
853
854                 boost::wsmatch what;
855                 if(boost::regex_match(parameters().at(0), what, expr))
856                 {
857                         auto channel_index = boost::lexical_cast<int>(what["CHANNEL"].str());
858                         pFP = reroute::create_producer(*channels().at(channel_index-1).channel); 
859                 }
860                 else
861                 {
862                         pFP = create_producer(channel()->frame_factory(), channel()->video_format_desc(), parameters());
863                 }
864                 
865                 if(pFP == frame_producer::empty())
866                         CASPAR_THROW_EXCEPTION(file_not_found() << msg_info(parameters().size() > 0 ? parameters()[0] : L""));
867
868                 bool auto_play = contains_param(L"AUTO", parameters());
869
870                 auto pFP2 = create_transition_producer(channel()->video_format_desc().field_mode, spl::make_shared_ptr(pFP), transitionInfo);
871                 if(auto_play)
872                         channel()->stage().load(layer_index(), pFP2, false, transitionInfo.duration); // TODO: LOOP
873                 else
874                         channel()->stage().load(layer_index(), pFP2, false); // TODO: LOOP
875         
876                 
877                 SetReplyString(L"202 LOADBG OK\r\n");
878
879                 return true;
880         }
881         catch(file_not_found&)
882         {               
883                 CASPAR_LOG(error) << L"File not found. No match found for parameters. Check syntax.";
884                 SetReplyString(L"404 LOADBG ERROR\r\n");
885                 return false;
886         }
887         catch(...)
888         {
889                 CASPAR_LOG_CURRENT_EXCEPTION();
890                 SetReplyString(L"502 LOADBG FAILED\r\n");
891                 return false;
892         }
893 }
894
895 bool PauseCommand::DoExecute()
896 {
897         try
898         {
899                 channel()->stage().pause(layer_index());
900                 SetReplyString(L"202 PAUSE OK\r\n");
901                 return true;
902         }
903         catch(...)
904         {
905                 SetReplyString(L"501 PAUSE FAILED\r\n");
906         }
907
908         return false;
909 }
910
911 bool PlayCommand::DoExecute()
912 {
913         try
914         {
915                 if(!parameters().empty())
916                 {
917                         LoadbgCommand lbg(*this);
918
919                         if(!lbg.Execute())
920                                 throw std::exception();
921                 }
922
923                 channel()->stage().play(layer_index());
924                 
925                 SetReplyString(L"202 PLAY OK\r\n");
926                 return true;
927         }
928         catch(...)
929         {
930                 SetReplyString(L"501 PLAY FAILED\r\n");
931         }
932
933         return false;
934 }
935
936 bool StopCommand::DoExecute()
937 {
938         try
939         {
940                 channel()->stage().stop(layer_index());
941                 SetReplyString(L"202 STOP OK\r\n");
942                 return true;
943         }
944         catch(...)
945         {
946                 SetReplyString(L"501 STOP FAILED\r\n");
947         }
948
949         return false;
950 }
951
952 bool ClearCommand::DoExecute()
953 {
954         int index = layer_index(std::numeric_limits<int>::min());
955         if(index != std::numeric_limits<int>::min())
956                 channel()->stage().clear(index);
957         else
958                 channel()->stage().clear();
959                 
960         SetReplyString(L"202 CLEAR OK\r\n");
961
962         return true;
963 }
964
965 bool PrintCommand::DoExecute()
966 {
967         channel()->output().add(create_consumer({ L"IMAGE" }));
968                 
969         SetReplyString(L"202 PRINT OK\r\n");
970
971         return true;
972 }
973
974 bool LogCommand::DoExecute()
975 {
976         if(boost::iequals(parameters().at(0), L"LEVEL"))
977                 log::set_log_level(parameters().at(1));
978
979         SetReplyString(L"202 LOG OK\r\n");
980
981         return true;
982 }
983
984 bool CGCommand::DoExecute()
985 {
986         try
987         {
988                 std::wstring command = boost::to_upper_copy(parameters()[0]);
989                 if(command == L"ADD")
990                         return DoExecuteAdd();
991                 else if(command == L"PLAY")
992                         return DoExecutePlay();
993                 else if(command == L"STOP")
994                         return DoExecuteStop();
995                 else if(command == L"NEXT")
996                         return DoExecuteNext();
997                 else if(command == L"REMOVE")
998                         return DoExecuteRemove();
999                 else if(command == L"CLEAR")
1000                         return DoExecuteClear();
1001                 else if(command == L"UPDATE")
1002                         return DoExecuteUpdate();
1003                 else if(command == L"INVOKE")
1004                         return DoExecuteInvoke();
1005                 else if(command == L"INFO")
1006                         return DoExecuteInfo();
1007         }
1008         catch(...)
1009         {
1010                 CASPAR_LOG_CURRENT_EXCEPTION();
1011         }
1012
1013         SetReplyString(L"403 CG ERROR\r\n");
1014         return false;
1015 }
1016
1017 bool CGCommand::ValidateLayer(const std::wstring& layerstring) {
1018         int length = layerstring.length();
1019         for(int i = 0; i < length; ++i) {
1020                 if(!std::isdigit(layerstring[i])) {
1021                         return false;
1022                 }
1023         }
1024
1025         return true;
1026 }
1027
1028 bool CGCommand::DoExecuteAdd() {
1029         //CG 1 ADD 0 "template_folder/templatename" [STARTLABEL] 0/1 [DATA]
1030
1031         int layer = 0;                          //_parameters[1]
1032 //      std::wstring templateName;      //_parameters[2]
1033         std::wstring label;             //_parameters[3]
1034         bool bDoStart = false;          //_parameters[3] alt. _parameters[4]
1035 //      std::wstring data;                      //_parameters[4] alt. _parameters[5]
1036
1037         if(parameters().size() < 4) 
1038         {
1039                 SetReplyString(L"402 CG ERROR\r\n");
1040                 return false;
1041         }
1042         unsigned int dataIndex = 4;
1043
1044         if(!ValidateLayer(parameters()[1])) 
1045         {
1046                 SetReplyString(L"403 CG ERROR\r\n");
1047                 return false;
1048         }
1049
1050         layer = boost::lexical_cast<int>(parameters()[1]);
1051
1052         if(parameters()[3].length() > 1) 
1053         {       //read label
1054                 label = parameters()[3];
1055                 ++dataIndex;
1056
1057                 if(parameters().size() > 4 && parameters()[4].length() > 0)     //read play-on-load-flag
1058                         bDoStart = (parameters()[4][0]==L'1') ? true : false;
1059                 else 
1060                 {
1061                         SetReplyString(L"402 CG ERROR\r\n");
1062                         return false;
1063                 }
1064         }
1065         else if(parameters()[3].length() > 0) { //read play-on-load-flag
1066                 bDoStart = (parameters()[3][0]==L'1') ? true : false;
1067         }
1068         else 
1069         {
1070                 SetReplyString(L"403 CG ERROR\r\n");
1071                 return false;
1072         }
1073
1074         const wchar_t* pDataString = 0;
1075         std::wstring dataFromFile;
1076         if(parameters().size() > dataIndex) 
1077         {       //read data
1078                 const std::wstring& dataString = parameters()[dataIndex];
1079
1080                 if(dataString[0] == L'<') //the data is an XML-string
1081                         pDataString = dataString.c_str();
1082                 else 
1083                 {
1084                         //The data is not an XML-string, it must be a filename
1085                         std::wstring filename = env::data_folder();
1086                         filename.append(dataString);
1087                         filename.append(L".ftd");
1088
1089                         dataFromFile = read_file(boost::filesystem::wpath(filename));
1090                         pDataString = dataFromFile.c_str();
1091                 }
1092         }
1093
1094         std::wstring fullFilename = flash::find_template(env::template_folder() + parameters()[2]);
1095         if(!fullFilename.empty())
1096         {
1097                 std::wstring extension = boost::filesystem::path(fullFilename).extension().wstring();
1098                 std::wstring filename = parameters()[2];
1099                 filename.append(extension);
1100
1101                 flash::create_cg_proxy(spl::shared_ptr<core::video_channel>(channel()), layer_index(flash::cg_proxy::DEFAULT_LAYER)).add(layer, filename, bDoStart, label, (pDataString!=0) ? pDataString : L"");
1102                 SetReplyString(L"202 CG OK\r\n");
1103         }
1104         else
1105         {
1106                 CASPAR_LOG(warning) << "Could not find template " << parameters()[2];
1107                 SetReplyString(L"404 CG ERROR\r\n");
1108         }
1109         return true;
1110 }
1111
1112 bool CGCommand::DoExecutePlay()
1113 {
1114         if(parameters().size() > 1)
1115         {
1116                 if(!ValidateLayer(parameters()[1])) 
1117                 {
1118                         SetReplyString(L"403 CG ERROR\r\n");
1119                         return false;
1120                 }
1121                 int layer = boost::lexical_cast<int>(parameters()[1]);
1122                 flash::create_cg_proxy(spl::shared_ptr<core::video_channel>(channel()), layer_index(flash::cg_proxy::DEFAULT_LAYER)).play(layer);
1123         }
1124         else
1125         {
1126                 SetReplyString(L"402 CG ERROR\r\n");
1127                 return true;
1128         }
1129
1130         SetReplyString(L"202 CG OK\r\n");
1131         return true;
1132 }
1133
1134 bool CGCommand::DoExecuteStop() 
1135 {
1136         if(parameters().size() > 1)
1137         {
1138                 if(!ValidateLayer(parameters()[1])) 
1139                 {
1140                         SetReplyString(L"403 CG ERROR\r\n");
1141                         return false;
1142                 }
1143                 int layer = boost::lexical_cast<int>(parameters()[1]);
1144                 flash::create_cg_proxy(spl::shared_ptr<core::video_channel>(channel()), layer_index(flash::cg_proxy::DEFAULT_LAYER)).stop(layer, 0);
1145         }
1146         else 
1147         {
1148                 SetReplyString(L"402 CG ERROR\r\n");
1149                 return true;
1150         }
1151
1152         SetReplyString(L"202 CG OK\r\n");
1153         return true;
1154 }
1155
1156 bool CGCommand::DoExecuteNext()
1157 {
1158         if(parameters().size() > 1) 
1159         {
1160                 if(!ValidateLayer(parameters()[1])) 
1161                 {
1162                         SetReplyString(L"403 CG ERROR\r\n");
1163                         return false;
1164                 }
1165
1166                 int layer = boost::lexical_cast<int>(parameters()[1]);
1167                 flash::create_cg_proxy(spl::shared_ptr<core::video_channel>(channel()), layer_index(flash::cg_proxy::DEFAULT_LAYER)).next(layer);
1168         }
1169         else 
1170         {
1171                 SetReplyString(L"402 CG ERROR\r\n");
1172                 return true;
1173         }
1174
1175         SetReplyString(L"202 CG OK\r\n");
1176         return true;
1177 }
1178
1179 bool CGCommand::DoExecuteRemove() 
1180 {
1181         if(parameters().size() > 1) 
1182         {
1183                 if(!ValidateLayer(parameters()[1])) 
1184                 {
1185                         SetReplyString(L"403 CG ERROR\r\n");
1186                         return false;
1187                 }
1188
1189                 int layer = boost::lexical_cast<int>(parameters()[1]);
1190                 flash::create_cg_proxy(spl::shared_ptr<core::video_channel>(channel()), layer_index(flash::cg_proxy::DEFAULT_LAYER)).remove(layer);
1191         }
1192         else 
1193         {
1194                 SetReplyString(L"402 CG ERROR\r\n");
1195                 return true;
1196         }
1197
1198         SetReplyString(L"202 CG OK\r\n");
1199         return true;
1200 }
1201
1202 bool CGCommand::DoExecuteClear() 
1203 {
1204         channel()->stage().clear(layer_index(flash::cg_proxy::DEFAULT_LAYER));
1205         SetReplyString(L"202 CG OK\r\n");
1206         return true;
1207 }
1208
1209 bool CGCommand::DoExecuteUpdate() 
1210 {
1211         try
1212         {
1213                 if(!ValidateLayer(parameters().at(1)))
1214                 {
1215                         SetReplyString(L"403 CG ERROR\r\n");
1216                         return false;
1217                 }
1218                                                 
1219                 std::wstring dataString = parameters().at(2);                           
1220                 if(dataString.at(0) != L'<')
1221                 {
1222                         //The data is not an XML-string, it must be a filename
1223                         std::wstring filename = env::data_folder();
1224                         filename.append(dataString);
1225                         filename.append(L".ftd");
1226
1227                         dataString = read_file(boost::filesystem::wpath(filename));
1228                 }               
1229
1230                 int layer = boost::lexical_cast<int>(parameters()[1]);
1231                 flash::create_cg_proxy(spl::shared_ptr<core::video_channel>(channel()), layer_index(flash::cg_proxy::DEFAULT_LAYER)).update(layer, dataString);
1232         }
1233         catch(...)
1234         {
1235                 SetReplyString(L"402 CG ERROR\r\n");
1236                 return true;
1237         }
1238
1239         SetReplyString(L"202 CG OK\r\n");
1240         return true;
1241 }
1242
1243 bool CGCommand::DoExecuteInvoke() 
1244 {
1245         std::wstringstream replyString;
1246         replyString << L"201 CG OK\r\n";
1247
1248         if(parameters().size() > 2)
1249         {
1250                 if(!ValidateLayer(parameters()[1]))
1251                 {
1252                         SetReplyString(L"403 CG ERROR\r\n");
1253                         return false;
1254                 }
1255                 int layer = boost::lexical_cast<int>(parameters()[1]);
1256                 auto result = flash::create_cg_proxy(spl::shared_ptr<core::video_channel>(channel()), layer_index(flash::cg_proxy::DEFAULT_LAYER)).invoke(layer, parameters()[2]);
1257                 replyString << result << L"\r\n";
1258         }
1259         else 
1260         {
1261                 SetReplyString(L"402 CG ERROR\r\n");
1262                 return true;
1263         }
1264         
1265         SetReplyString(replyString.str());
1266         return true;
1267 }
1268
1269 bool CGCommand::DoExecuteInfo() 
1270 {
1271         std::wstringstream replyString;
1272         replyString << L"201 CG OK\r\n";
1273
1274         if(parameters().size() > 1)
1275         {
1276                 if(!ValidateLayer(parameters()[1]))
1277                 {
1278                         SetReplyString(L"403 CG ERROR\r\n");
1279                         return false;
1280                 }
1281
1282                 int layer = boost::lexical_cast<int>(parameters()[1]);
1283                 auto desc = flash::create_cg_proxy(spl::shared_ptr<core::video_channel>(channel()), layer_index(flash::cg_proxy::DEFAULT_LAYER)).description(layer);
1284                 
1285                 replyString << desc << L"\r\n";
1286         }
1287         else 
1288         {
1289                 auto info = flash::create_cg_proxy(spl::shared_ptr<core::video_channel>(channel()), layer_index(flash::cg_proxy::DEFAULT_LAYER)).template_host_info();
1290                 replyString << info << L"\r\n";
1291         }       
1292
1293         SetReplyString(replyString.str());
1294         return true;
1295 }
1296
1297 bool DataCommand::DoExecute()
1298 {
1299         std::wstring command = boost::to_upper_copy(parameters()[0]);
1300         if(command == L"STORE")
1301                 return DoExecuteStore();
1302         else if(command == L"RETRIEVE")
1303                 return DoExecuteRetrieve();
1304         else if(command == L"REMOVE")
1305                 return DoExecuteRemove();
1306         else if(command == L"LIST")
1307                 return DoExecuteList();
1308
1309         SetReplyString(L"403 DATA ERROR\r\n");
1310         return false;
1311 }
1312
1313 bool DataCommand::DoExecuteStore() 
1314 {
1315         if(parameters().size() < 3) 
1316         {
1317                 SetReplyString(L"402 DATA STORE ERROR\r\n");
1318                 return false;
1319         }
1320
1321         std::wstring filename = env::data_folder();
1322         filename.append(parameters()[1]);
1323         filename.append(L".ftd");
1324
1325         auto data_path = boost::filesystem::wpath(
1326                 boost::filesystem::wpath(filename).parent_path());
1327
1328         if(!boost::filesystem::exists(data_path))
1329                 boost::filesystem::create_directories(data_path);
1330
1331         boost::filesystem::wofstream datafile(filename);
1332         if(!datafile) 
1333         {
1334                 SetReplyString(L"501 DATA STORE FAILED\r\n");
1335                 return false;
1336         }
1337
1338         datafile << static_cast<wchar_t>(65279); // UTF-8 BOM character
1339         datafile << parameters()[2] << std::flush;
1340         datafile.close();
1341
1342         std::wstring replyString = L"202 DATA STORE OK\r\n";
1343         SetReplyString(replyString);
1344         return true;
1345 }
1346
1347 bool DataCommand::DoExecuteRetrieve() 
1348 {
1349         if(parameters().size() < 2) 
1350         {
1351                 SetReplyString(L"402 DATA RETRIEVE ERROR\r\n");
1352                 return false;
1353         }
1354
1355         std::wstring filename = env::data_folder();
1356         filename.append(parameters()[1]);
1357         filename.append(L".ftd");
1358
1359         std::wstring file_contents = read_file(boost::filesystem::wpath(filename));
1360
1361         if (file_contents.empty()) 
1362         {
1363                 SetReplyString(L"404 DATA RETRIEVE ERROR\r\n");
1364                 return false;
1365         }
1366
1367         std::wstringstream reply(L"201 DATA RETRIEVE OK\r\n");
1368
1369         std::wstringstream file_contents_stream(file_contents);
1370         std::wstring line;
1371         
1372         bool firstLine = true;
1373         while(std::getline(file_contents_stream, line))
1374         {
1375                 if(firstLine)
1376                         firstLine = false;
1377                 else
1378                         reply << "\n";
1379
1380                 reply << line;
1381         }
1382
1383         reply << "\r\n";
1384         SetReplyString(reply.str());
1385         return true;
1386 }
1387
1388 bool DataCommand::DoExecuteRemove()
1389
1390         if (parameters().size() < 2)
1391         {
1392                 SetReplyString(L"402 DATA REMOVE ERROR\r\n");
1393                 return false;
1394         }
1395
1396         std::wstring filename = env::data_folder();
1397         filename.append(parameters()[1]);
1398         filename.append(L".ftd");
1399
1400         if (!boost::filesystem::exists(filename))
1401         {
1402                 SetReplyString(L"404 DATA REMOVE ERROR\r\n");
1403                 return false;
1404         }
1405
1406         if (!boost::filesystem::remove(filename))
1407         {
1408                 SetReplyString(L"403 DATA REMOVE ERROR\r\n");
1409                 return false;
1410         }
1411
1412         SetReplyString(L"201 DATA REMOVE OK\r\n");
1413
1414         return true;
1415 }
1416
1417 bool DataCommand::DoExecuteList() 
1418 {
1419         std::wstringstream replyString;
1420         replyString << L"200 DATA LIST OK\r\n";
1421
1422         for (boost::filesystem::recursive_directory_iterator itr(env::data_folder()), end; itr != end; ++itr)
1423         {                       
1424                 if(boost::filesystem::is_regular_file(itr->path()))
1425                 {
1426                         if(!boost::iequals(itr->path().extension().wstring(), L".ftd"))
1427                                 continue;
1428                         
1429                         auto relativePath = boost::filesystem::wpath(itr->path().wstring().substr(env::data_folder().size()-1, itr->path().wstring().size()));
1430                         
1431                         auto str = relativePath.replace_extension(L"").generic_wstring();
1432                         if(str[0] == L'\\' || str[0] == L'/')
1433                                 str = std::wstring(str.begin() + 1, str.end());
1434
1435                         replyString << str << L"\r\n";
1436                 }
1437         }
1438         
1439         replyString << L"\r\n";
1440
1441         SetReplyString(boost::to_upper_copy(replyString.str()));
1442         return true;
1443 }
1444
1445 bool CinfCommand::DoExecute()
1446 {
1447         std::wstringstream replyString;
1448         
1449         try
1450         {
1451                 std::wstring info;
1452                 for (boost::filesystem::recursive_directory_iterator itr(env::media_folder()), end; itr != end && info.empty(); ++itr)
1453                 {
1454                         auto path = itr->path();
1455                         auto file = path.replace_extension(L"").filename();
1456                         if(boost::iequals(file.wstring(), parameters().at(0)))
1457                                 info += MediaInfo(itr->path()) + L"\r\n";
1458                 }
1459
1460                 if(info.empty())
1461                 {
1462                         SetReplyString(L"404 CINF ERROR\r\n");
1463                         return false;
1464                 }
1465                 replyString << L"200 CINF OK\r\n";
1466                 replyString << info << "\r\n";
1467         }
1468         catch(...)
1469         {
1470                 CASPAR_LOG_CURRENT_EXCEPTION();
1471                 SetReplyString(L"404 CINF ERROR\r\n");
1472                 return false;
1473         }
1474         
1475         SetReplyString(replyString.str());
1476         return true;
1477 }
1478
1479 void GenerateChannelInfo(int index, const spl::shared_ptr<core::video_channel>& pChannel, std::wstringstream& replyString)
1480 {
1481         replyString << index+1 << L" " << pChannel->video_format_desc().name << L" PLAYING\r\n";
1482 }
1483
1484 bool InfoCommand::DoExecute()
1485 {
1486         std::wstringstream replyString;
1487         
1488         boost::property_tree::xml_writer_settings<std::wstring> w(' ', 3);
1489
1490         try
1491         {
1492                 if(parameters().size() >= 1 && boost::iequals(parameters()[0], L"TEMPLATE"))
1493                 {               
1494                         replyString << L"201 INFO TEMPLATE OK\r\n";
1495
1496                         // Needs to be extended for any file, not just flash.
1497
1498                         auto filename = flash::find_template(env::template_folder() + parameters().at(1));
1499                                                 
1500                         std::wstringstream str;
1501                         str << u16(flash::read_template_meta_info(filename));
1502                         boost::property_tree::wptree info;
1503                         boost::property_tree::xml_parser::read_xml(str, info, boost::property_tree::xml_parser::trim_whitespace | boost::property_tree::xml_parser::no_comments);
1504
1505                         boost::property_tree::xml_parser::write_xml(replyString, info, w);
1506                 }
1507                 else if(parameters().size() >= 1 && boost::iequals(parameters()[0], L"CONFIG"))
1508                 {               
1509                         replyString << L"201 INFO CONFIG OK\r\n";
1510
1511                         boost::property_tree::write_xml(replyString, caspar::env::properties(), w);
1512                 }
1513                 else if(parameters().size() >= 1 && boost::iequals(parameters()[0], L"PATHS"))
1514                 {
1515                         replyString << L"201 INFO PATHS OK\r\n";
1516
1517                         boost::property_tree::wptree info;
1518                         info.add_child(L"paths", caspar::env::properties().get_child(L"configuration.paths"));
1519                         info.add(L"paths.initial-path", boost::filesystem::initial_path().wstring() + L"\\");
1520
1521                         boost::property_tree::write_xml(replyString, info, w);
1522                 }
1523                 else if(parameters().size() >= 1 && boost::iequals(parameters()[0], L"SYSTEM"))
1524                 {
1525                         replyString << L"201 INFO SYSTEM OK\r\n";
1526                         
1527                         boost::property_tree::wptree info;
1528                         
1529                         info.add(L"system.name",                                        caspar::system_product_name());
1530                         info.add(L"system.os.description",                      caspar::os_description());
1531                         info.add(L"system.cpu",                                         caspar::cpu_info());
1532         
1533                         for (auto& device : caspar::decklink::device_list())
1534                                 info.add(L"system.decklink.device", device);
1535
1536                         for (auto& device : caspar::bluefish::device_list())
1537                                 info.add(L"system.bluefish.device", device);
1538                                 
1539                         info.add(L"system.flash",                                       caspar::flash::version());
1540                         info.add(L"system.ffmpeg.avcodec",                      caspar::ffmpeg::avcodec_version());
1541                         info.add(L"system.ffmpeg.avformat",                     caspar::ffmpeg::avformat_version());
1542                         info.add(L"system.ffmpeg.avfilter",                     caspar::ffmpeg::avfilter_version());
1543                         info.add(L"system.ffmpeg.avutil",                       caspar::ffmpeg::avutil_version());
1544                         info.add(L"system.ffmpeg.swscale",                      caspar::ffmpeg::swscale_version());
1545                                                 
1546                         boost::property_tree::write_xml(replyString, info, w);
1547                 }
1548                 else if(parameters().size() >= 1 && boost::iequals(parameters()[0], L"SERVER"))
1549                 {
1550                         replyString << L"201 INFO SERVER OK\r\n";
1551                         
1552                         boost::property_tree::wptree info;
1553
1554                         int index = 0;
1555                         for (auto& channel : channels())
1556                                 info.add_child(L"channels.channel", channel.channel->info())
1557                                         .add(L"index", ++index);
1558                         
1559                         boost::property_tree::write_xml(replyString, info, w);
1560                 }
1561                 else // channel
1562                 {                       
1563                         if(parameters().size() >= 1)
1564                         {
1565                                 replyString << L"201 INFO OK\r\n";
1566                                 boost::property_tree::wptree info;
1567
1568                                 std::vector<std::wstring> split;
1569                                 boost::split(split, parameters()[0], boost::is_any_of("-"));
1570                                         
1571                                 int layer = std::numeric_limits<int>::min();
1572                                 int channel = boost::lexical_cast<int>(split[0]) - 1;
1573
1574                                 if(split.size() > 1)
1575                                         layer = boost::lexical_cast<int>(split[1]);
1576                                 
1577                                 if(layer == std::numeric_limits<int>::min())
1578                                 {       
1579                                         info.add_child(L"channel", channels().at(channel).channel->info())
1580                                                         .add(L"index", channel);
1581                                 }
1582                                 else
1583                                 {
1584                                         if(parameters().size() >= 2)
1585                                         {
1586                                                 if(boost::iequals(parameters()[1], L"B"))
1587                                                         info.add_child(L"producer", channels().at(channel).channel->stage().background(layer).get()->info());
1588                                                 else
1589                                                         info.add_child(L"producer", channels().at(channel).channel->stage().foreground(layer).get()->info());
1590                                         }
1591                                         else
1592                                         {
1593                                                 info.add_child(L"layer", channels().at(channel).channel->stage().info(layer).get())
1594                                                         .add(L"index", layer);
1595                                         }
1596                                 }
1597                                 boost::property_tree::xml_parser::write_xml(replyString, info, w);
1598                         }
1599                         else
1600                         {
1601                                 // This is needed for backwards compatibility with old clients
1602                                 replyString << L"200 INFO OK\r\n";
1603                                 for(size_t n = 0; n < channels().size(); ++n)
1604                                         GenerateChannelInfo(n, channels()[n].channel, replyString);
1605                         }
1606
1607                 }
1608         }
1609         catch(...)
1610         {
1611                 CASPAR_LOG_CURRENT_EXCEPTION();
1612                 SetReplyString(L"403 INFO ERROR\r\n");
1613                 return false;
1614         }
1615
1616         replyString << L"\r\n";
1617         SetReplyString(replyString.str());
1618         return true;
1619 }
1620
1621 bool ClsCommand::DoExecute()
1622 {
1623 /*
1624                 wav = audio
1625                 mp3 = audio
1626                 swf     = movie
1627                 dv  = movie
1628                 tga = still
1629                 col = still
1630         */
1631         try
1632         {
1633                 std::wstringstream replyString;
1634                 replyString << L"200 CLS OK\r\n";
1635                 replyString << ListMedia();
1636                 replyString << L"\r\n";
1637                 SetReplyString(boost::to_upper_copy(replyString.str()));
1638         }
1639         catch(...)
1640         {
1641                 CASPAR_LOG_CURRENT_EXCEPTION();
1642                 SetReplyString(L"501 CLS FAILED\r\n");
1643                 return false;
1644         }
1645
1646         return true;
1647 }
1648
1649 bool TlsCommand::DoExecute()
1650 {
1651         try
1652         {
1653                 std::wstringstream replyString;
1654                 replyString << L"200 TLS OK\r\n";
1655
1656                 replyString << ListTemplates();
1657                 replyString << L"\r\n";
1658
1659                 SetReplyString(replyString.str());
1660         }
1661         catch(...)
1662         {
1663                 CASPAR_LOG_CURRENT_EXCEPTION();
1664                 SetReplyString(L"501 TLS FAILED\r\n");
1665                 return false;
1666         }
1667         return true;
1668 }
1669
1670 bool VersionCommand::DoExecute()
1671 {
1672         std::wstring replyString = L"201 VERSION OK\r\n" + env::version() + L"\r\n";
1673
1674         if(parameters().size() > 0)
1675         {
1676                 if(boost::iequals(parameters()[0], L"FLASH"))
1677                         replyString = L"201 VERSION OK\r\n" + flash::version() + L"\r\n";
1678                 else if(boost::iequals(parameters()[0], L"TEMPLATEHOST"))
1679                         replyString = L"201 VERSION OK\r\n" + flash::cg_version() + L"\r\n";
1680                 else if(!boost::iequals(parameters()[0], L"SERVER"))
1681                         replyString = L"403 VERSION ERROR\r\n";
1682         }
1683
1684         SetReplyString(replyString);
1685         return true;
1686 }
1687
1688 bool ByeCommand::DoExecute()
1689 {
1690         client()->disconnect();
1691         return true;
1692 }
1693
1694 bool SetCommand::DoExecute()
1695 {
1696         try
1697         {
1698                 std::wstring name = boost::to_upper_copy(parameters()[0]);
1699                 std::wstring value = boost::to_upper_copy(parameters()[1]);
1700
1701                 if(name == L"MODE")
1702                 {
1703                         auto format_desc = core::video_format_desc(value);
1704                         if(format_desc.format != core::video_format::invalid)
1705                         {
1706                                 channel()->video_format_desc(format_desc);
1707                                 SetReplyString(L"202 SET MODE OK\r\n");
1708                         }
1709                         else
1710                                 SetReplyString(L"501 SET MODE FAILED\r\n");
1711                 }
1712                 else
1713                 {
1714                         this->SetReplyString(L"403 SET ERROR\r\n");
1715                 }
1716         }
1717         catch(...)
1718         {
1719                 CASPAR_LOG_CURRENT_EXCEPTION();
1720                 SetReplyString(L"501 SET FAILED\r\n");
1721                 return false;
1722         }
1723
1724         return true;
1725 }
1726
1727 bool LockCommand::DoExecute()
1728 {
1729         try
1730         {
1731                 auto it = parameters().begin();
1732
1733                 std::shared_ptr<caspar::IO::lock_container> lock;
1734                 try
1735                 {
1736                         int channel_index = boost::lexical_cast<int>(*it) - 1;
1737                         lock = channels().at(channel_index).lock;
1738                 }
1739                 catch(const boost::bad_lexical_cast&) {}
1740                 catch(...)
1741                 {
1742                         SetReplyString(L"401 LOCK ERROR\r\n");
1743                         return false;
1744                 }
1745
1746                 if(lock)
1747                         ++it;
1748
1749                 if(it == parameters().end())    //too few parameters
1750                 {
1751                         SetReplyString(L"402 LOCK ERROR\r\n");
1752                         return false;
1753                 }
1754
1755                 std::wstring command = boost::to_upper_copy(*it);
1756                 if(command == L"ACQUIRE")
1757                 {
1758                         ++it;
1759                         if(it == parameters().end())    //too few parameters
1760                         {
1761                                 SetReplyString(L"402 LOCK ACQUIRE ERROR\r\n");
1762                                 return false;
1763                         }
1764                         std::wstring lock_phrase = (*it);
1765
1766                         //TODO: read options
1767
1768                         if(lock)
1769                         {
1770                                 //just lock one channel
1771                                 if(!lock->try_lock(lock_phrase, client()))
1772                                 {
1773                                         SetReplyString(L"503 LOCK ACQUIRE FAILED\r\n");
1774                                         return false;
1775                                 }
1776                         }
1777                         else
1778                         {
1779                                 //TODO: lock all channels
1780                                 CASPAR_THROW_EXCEPTION(not_implemented());
1781                         }
1782                         SetReplyString(L"202 LOCK ACQUIRE OK\r\n");
1783
1784                 }
1785                 else if(command == L"RELEASE")
1786                 {
1787                         if(lock)
1788                         {
1789                                 lock->release_lock(client());
1790                         }
1791                         else
1792                         {
1793                                 //TODO: release all channels
1794                                 CASPAR_THROW_EXCEPTION(not_implemented());
1795                         }
1796                         SetReplyString(L"202 LOCK RELEASE OK\r\n");
1797                 }
1798                 else if(command == L"CLEAR")
1799                 {
1800                         std::wstring override_phrase = env::properties().get(L"configuration.lock-clear-phrase", L"");
1801                         std::wstring client_override_phrase;
1802                         if(!override_phrase.empty())
1803                         {
1804                                 ++it;
1805                                 if(it == parameters().end())
1806                                 {
1807                                         SetReplyString(L"402 LOCK CLEAR ERROR\r\n");
1808                                         return false;
1809                                 }
1810                                 client_override_phrase = (*it);
1811                         }
1812
1813                         if(lock)
1814                         {
1815                                 //just clear one channel
1816                                 if(client_override_phrase != override_phrase)
1817                                 {
1818                                         SetReplyString(L"503 LOCK CLEAR FAILED\r\n");
1819                                         return false;
1820                                 }
1821                                 
1822                                 lock->clear_locks();
1823                         }
1824                         else
1825                         {
1826                                 //TODO: clear all channels
1827                                 CASPAR_THROW_EXCEPTION(not_implemented());
1828                         }
1829
1830                         SetReplyString(L"202 LOCK CLEAR OK\r\n");
1831                 }
1832                 else
1833                 {
1834                         SetReplyString(L"403 LOCK ERROR\r\n");
1835                         return false;
1836                 }
1837         }
1838         catch(not_implemented&)
1839         {
1840                 SetReplyString(L"600 LOCK FAILED\r\n");
1841                 return false;
1842         }
1843         catch(...)
1844         {
1845                 CASPAR_LOG_CURRENT_EXCEPTION();
1846                 SetReplyString(L"501 LOCK FAILED\r\n");
1847                 return false;
1848         }
1849
1850         return true;
1851 }
1852
1853 bool ThumbnailCommand::DoExecute()
1854 {
1855         std::wstring command = boost::to_upper_copy(parameters()[0]);
1856
1857         if (command == L"RETRIEVE")
1858                 return DoExecuteRetrieve();
1859         else if (command == L"LIST")
1860                 return DoExecuteList();
1861         else if (command == L"GENERATE")
1862                 return DoExecuteGenerate();
1863         else if (command == L"GENERATE_ALL")
1864                 return DoExecuteGenerateAll();
1865
1866         SetReplyString(L"403 THUMBNAIL ERROR\r\n");
1867         return false;
1868 }
1869
1870 bool ThumbnailCommand::DoExecuteRetrieve() 
1871 {
1872         if(parameters().size() < 2) 
1873         {
1874                 SetReplyString(L"402 THUMBNAIL RETRIEVE ERROR\r\n");
1875                 return false;
1876         }
1877
1878         std::wstring filename = env::thumbnails_folder();
1879         filename.append(parameters()[1]);
1880         filename.append(L".png");
1881
1882         std::wstring file_contents = read_file_base64(boost::filesystem::wpath(filename));
1883
1884         if (file_contents.empty())
1885         {
1886                 SetReplyString(L"404 THUMBNAIL RETRIEVE ERROR\r\n");
1887                 return false;
1888         }
1889
1890         std::wstringstream reply;
1891
1892         reply << L"201 THUMBNAIL RETRIEVE OK\r\n";
1893         reply << file_contents;
1894         reply << L"\r\n";
1895         SetReplyString(reply.str());
1896         return true;
1897 }
1898
1899 bool ThumbnailCommand::DoExecuteList()
1900 {
1901         std::wstringstream replyString;
1902         replyString << L"200 THUMBNAIL LIST OK\r\n";
1903
1904         for (boost::filesystem::recursive_directory_iterator itr(env::thumbnails_folder()), end; itr != end; ++itr)
1905         {      
1906                 if(boost::filesystem::is_regular_file(itr->path()))
1907                 {
1908                         if(!boost::iequals(itr->path().extension().wstring(), L".png"))
1909                                 continue;
1910
1911                         auto relativePath = boost::filesystem::wpath(itr->path().wstring().substr(env::thumbnails_folder().size()-1, itr->path().wstring().size()));
1912
1913                         auto str = relativePath.replace_extension(L"").generic_wstring();
1914                         if(str[0] == '\\' || str[0] == '/')
1915                                 str = std::wstring(str.begin() + 1, str.end());
1916
1917                         auto mtime = boost::filesystem::last_write_time(itr->path());
1918                         auto mtime_readable = boost::posix_time::to_iso_wstring(boost::posix_time::from_time_t(mtime));
1919                         auto file_size = boost::filesystem::file_size(itr->path());
1920
1921                         replyString << L"\"" << str << L"\" " << mtime_readable << L" " << file_size << L"\r\n";
1922                 }
1923         }
1924
1925         replyString << L"\r\n";
1926
1927         SetReplyString(boost::to_upper_copy(replyString.str()));
1928         return true;
1929 }
1930
1931 bool ThumbnailCommand::DoExecuteGenerate()
1932 {
1933         if (parameters().size() < 2) 
1934         {
1935                 SetReplyString(L"402 THUMBNAIL GENERATE ERROR\r\n");
1936                 return false;
1937         }
1938
1939         if (thumb_gen_)
1940         {
1941                 thumb_gen_->generate(parameters()[1]);
1942                 SetReplyString(L"202 THUMBNAIL GENERATE OK\r\n");
1943                 return true;
1944         }
1945         else
1946         {
1947                 SetReplyString(L"500 THUMBNAIL GENERATE ERROR\r\n");
1948                 return false;
1949         }
1950 }
1951
1952 bool ThumbnailCommand::DoExecuteGenerateAll()
1953 {
1954         if (thumb_gen_)
1955         {
1956                 thumb_gen_->generate_all();
1957                 SetReplyString(L"202 THUMBNAIL GENERATE_ALL OK\r\n");
1958                 return true;
1959         }
1960         else
1961         {
1962                 SetReplyString(L"500 THUMBNAIL GENERATE_ALL ERROR\r\n");
1963                 return false;
1964         }
1965 }
1966
1967 bool KillCommand::DoExecute()
1968 {
1969         shutdown_server_now_->set_value(false); //false for not attempting to restart
1970         SetReplyString(L"202 KILL OK\r\n");
1971         return true;
1972 }
1973
1974 bool RestartCommand::DoExecute()
1975 {
1976         shutdown_server_now_->set_value(true);  //true for attempting to restart
1977         SetReplyString(L"202 RESTART OK\r\n");
1978         return true;
1979 }
1980
1981 }       //namespace amcp
1982 }}      //namespace caspar