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